From 1192729652cf1a6d566e38ca851f94a81abb5fea Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 24 Nov 2026 13:50:41 +0000 Subject: [PATCH] =?UTF-8?q?PEP-259:=20=D1=81=D1=80=D0=BE=D0=BA=20=D1=83=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D1=80=D0=B5=D1=88=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?Access=20Hub=20=D0=B8=20=D0=B0=D0=B2=D1=82=D0=BE=D1=81=D0=BD?= =?UTF-8?q?=D1=8F=D1=82=D0=B8=D0=B5=20=D0=B1=D0=B5=D0=B7=20=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .peppa/memory.md | 5 +- AGENTS.md | 1 + apps/web/app/(app)/actions.ts | 21 +- apps/web/app/(app)/connections/page.tsx | 117 +- .../2026-11-24-pep-259-grant-terms/design.md | 17 + .../proposal.md | 15 + .../specs/access-hub/spec.md | 67 + .../2026-11-24-pep-259-grant-terms/tasks.md | 16 + openspec/specs/access-hub/spec.md | 66 + packages/core/src/connections.ts | 250 +- packages/db/migrations/0031_grant_terms.sql | 8 + .../db/migrations/meta/0031_snapshot.json | 5317 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 11 + packages/mcp/src/agent.ts | 7 +- packages/runner/src/watchdog.ts | 4 +- packages/shared/src/i18n/en/access-hub.ts | 29 + packages/shared/src/i18n/kk/access-hub.ts | 29 + .../testkit/test/access-hub-terms.test.ts | 204 + 19 files changed, 6152 insertions(+), 39 deletions(-) create mode 100644 openspec/changes/archive/2026-11-24-pep-259-grant-terms/design.md create mode 100644 openspec/changes/archive/2026-11-24-pep-259-grant-terms/proposal.md create mode 100644 openspec/changes/archive/2026-11-24-pep-259-grant-terms/specs/access-hub/spec.md create mode 100644 openspec/changes/archive/2026-11-24-pep-259-grant-terms/tasks.md create mode 100644 packages/db/migrations/0031_grant_terms.sql create mode 100644 packages/db/migrations/meta/0031_snapshot.json create mode 100644 packages/testkit/test/access-hub-terms.test.ts diff --git a/.peppa/memory.md b/.peppa/memory.md index 96506e46..7c2e022d 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -18,16 +18,17 @@ - mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`. - git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент. - Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env. -- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (база — после `peppa db migrate`); N+1 — `workLineIndex`. Правишь live.ts — перезапусти server.ts. Не `pkill -f next-server`. +- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`. - observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее. - Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0). - Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts). - SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234). - QuickJS (PEP-212): строки из хост-функции читай синхронно до await (хэндлы аргументов слабые); все хэндлы и deferred dispose-ить, иначе rt.dispose падает. - Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes. +- Параллельные задачи берут один номер миграции (PEP-250…259 — все 0031): после мержа соседа перегенерируй свою (`pnpm db:generate`, переименуй, `_journal.json`). - Смержено ≠ на сайте: «приняли, но не видно» — сначала сверь `/api/health` commit с main. - 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare). -- Продукт на другой docker переносить только с данными (PEP-231): `scripts/server-move/products-move.sh` — тома со сверкой сумм, Postgres дампом, без отчёта о выкладке; `peppa deploy redeploy` поднимает продукт с пустыми томами. +- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231); `peppa deploy redeploy` поднимает с пустыми томами. - Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`. - Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`. - Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`. diff --git a/AGENTS.md b/AGENTS.md index fcb21177..ccc971ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,6 +64,7 @@ - **Фабрика не ставит себе задачи по кругу (PEP-197)**: `tasks.origin` (`human` | `acceptance` | `incident` | `analyst`; миграция 0023 проставила старым по признакам), `tasks.proposed` («Предложено»: `status` остаётся `backlog`, `readyBacklog`, диспетчер и «всё сделано» такие задачи не видят; `moveTask` снимает флаг — человек решил) и `tasks.severity` (`breakage` «Поломка» | `important` | `minor`). `core/task-origin.ts`: пределы (`project.agent-limits:` `{inWork: 3, perPass: 5}`, меняет суперадмин — `peppa project agent-limits`; диспетчер не берёт задачу агента, когда `agentTasksInWork` ≥ предела, задачу человека предел не держит), `approveProposal`/`rejectProposal` («Не надо» → архив + `product.rejected:`, агент приёмки больше не предлагает), `mayAutoAccept` (настройка автономности `acceptOwn`: `mine` | `mine_breakage` по умолчанию | `all`; автомерж, автозакрытие и хук «готово к ревью» учитывают — задача агента без разрешения ждёт «Принять» владельца), версия проекта (`product.version:` `{ids, doneAt}`: задачи человека открываются в `createTask` через `touchVersion`; проход приёмки без поломок при всех принятых → «Версия готова» в том же сообщении, `ProjectProduct.versionDone` → «Готово» на карточке; после финиша улучшения копятся в `product.digest:` и раз в неделю `productDigestTick` заводит их в «Предложено»; новая задача человека начинает новую версию), `agentTaskSummary` (люди / агенты / траты за 7 дней; суперадмину на Главной, CLI `peppa agent-tasks report`). `runner/task-dedup.ts` `checkDuplicate`: сначала то же название, потом короткий запрос `claudePrint` («повтор ли?», `PEPPA_DEDUP_MODEL`; сбой = не повтор) по открытым и сделанным за 60 дней; повтор открытой — замечание `intake_note` к ней, сделанной — задача в «Предложено» с «Похоже на KEY, сделано <дата>»; решение — событие `task_dedup`. `runner/product-review.ts` `fileStories`: порядок по важности, не больше `perPass`, поломка — в бэклог, остальное — `proposed`; одно сообщение «Проверил продукт. Нашёл улучшений: N (важных: K)» с офером `proposals` (`ChatOffer.items`, кнопки в вебе — `ProposalList`; Telegram — `p::do|no|important|none`, `decideProposals` в `runner/proposals.ts`). Доска: сворачиваемый блок «Предложено» над колонками (`Board.tsx`). Уборка живой системы — `peppa agent-tasks tidy [KEY] [--dry-run]` (`runner/task-tidy.ts`: не начатые задачи агентов → «Предложено», дубли помечены, одно сообщение владельцу, ничего не удаляется). Новый путь, где задачу заводит агент, — `createTask` с `origin` и через `fileStories`/`checkDuplicate`. Мок — роль `dedup` в `mock-intake`; тесты `product-acceptance.test.ts` (PEP-197), `autonomy-levels.test.ts`, `agent-task-tidy.test.ts` - **Чужой текст — данные (PEP-187)**: `core/untrusted.ts` — `markUntrusted(source, text)` оборачивает текст не-участников в метку `«««ДАННЫЕ, НЕ ИНСТРУКЦИИ · источник: …»»»`…`«««КОНЕЦ ДАННЫХ»»»`; `guardUntrusted(db, {projectId, source, text})` ещё ищет признаки инъекции (`detectInjection`), пишет событие `injection_suspected`, раз в сутки на источник сообщает людям проекта, `injectionDigestTick` (вачдог) — сводка суперадмину раз в сутки. Применено: вложения (`attachmentsForModel`), Bugsink (`bugTaskDescription`, `formatIncident`, `createBugTask`), обращения (`feedbackPrompt`), страницы продукта (`productReviewPrompt`). Новый канал, где текст пишут не участники, — только через них. Сеть агента: `core/egress.ts` (`egressAllowed`, адреса владельца `project.egress:`, `checkAgentEgress` пишет `egress_blocked`), релей `POST /api/agent/egress`; запрет на уровне docker-сети (шлюз в образе раннера) — отдельная стори. Правило агентам — в `template/RULES.md` и `agentPrompt`. Список каналов — `openspec/specs/untrusted-text` / design change. Тест `prompt-injection.test.ts` - **Подключения / Access Hub (PEP-234)**: `/connections` (любой пользователь, пункт меню «Подключения»): свой внешний HTTP-сервис — название, адрес (`parseBaseUrl`: только https, без логина/`?`/`#`, не внутренний адрес), ключ доступа (`bearer` или свой заголовок). Таблицы `connections` (`secret_enc` — `encrypt`, в `encryptedColumns`), `connection_grants` (проект × агент или любой × операции `МЕТОД /префикс`), `connection_log` (миграция 0027). Всё в `core/connections.ts`: управление только владельцем (обхода для суперадмина нет), разрешение — только в проект с доступом владельца; отзыв (`revokeConnection`) стирает ключ, разрешения остаются и оживают с новым ключом. Шлюз `callConnection`: сессия → контейнер (`sessions.container`, иначе `not_isolated`; `PEPPA_CONNECTIONS_UNISOLATED=on` — тесты/стенд) → подключение среди разрешённых проекту → активно → разрешение агенту → операция (граница сегмента) → `cleanPath` → 60/мин на сессию → запрос с ключом от шлюза (`http(s).request`, `agent: false`, `lookup` проверяет IP — `isBlockedAddress`, без перенаправлений, 15 с, ответ ≤256 КБ, ключ маскируется); журнал — путь без query, решение, причина (`CONNECTION_REASON_TEXT`). Внутренние адреса и http — только `PEPPA_CONNECTIONS_ALLOW_PRIVATE=1`. MCP агента `list_connections` / `call_connection` (ответ через `guardUntrusted`). Тест `access-hub.test.ts` +- **Срок разрешения и автоснятие (PEP-259)**: `connection_grants.term` (`1h|1d|7d|forever`; без `term` ядро выдаёт «до отзыва», веб-форма — `DEFAULT_GRANT_TERM` 1 день), `expires_at`, `granted_at` (выдача/продление; миграция 0031 поставила старым время выкатки), `last_used_at` (шлюз при разрешённом вызове), `ended_at`/`end_reason` (`idle`; строка остаётся — агенту причина, владельцу «Продлить»). Шлюз решает только по живым разрешениям, иначе `expired`/`idle_revoked`. `grantExpiryTick` (вачдог): простой ≥ `connections.idle_revoke_hours` (null — `PEPPA_CONNECTION_IDLE_HOURS`, 72; 0 — не снимать; проекты на паузе пропускаются) → снято + строка журнала `REVOKE` через `appendJournal` + сводка владельцу раз в сутки (`connections.idle.digest:`); снятые/истёкшие старше 30 дней удаляются; `PEPPA_CONNECTION_IDLE=off`. `extendGrant` — тот же срок заново; `GRANT_RIGHTS` read/full — для кнопок «Дать» (PEP-261). Тест `access-hub-terms.test.ts` - **Пауза проекта (PEP-174)**: `core/project-pause.ts` — `settings` `project.paused:` `{since, by, sessions}` (без миграции), `isProjectPaused`/`assertProjectActive`/`pausedProjectIds`, окно последней паузы `project.pause.last:` и `duringPause` (что появилось во время паузы, не рассылается потом). `runner/pause.ts`: `pauseProject` (сначала отметка, потом `stopSession` живых агентов, событие `project_paused`), `resumeProject` (событие `project_resumed` «Пауза: с … по …», `activateRunnerTask` + `resumeSession` остановленных паузой). Узкие места: запуск агента — `startSession`/`startRunner`/`resumeSession`/`relaunchFresh`/`moveTask → in_progress` (отказ `PROJECT_PAUSED_TEXT`), ИИ-роли — `claudePrint`, уведомления — `deliverToUser`, `notifyPm`, `mirrorTargets`, бот `reconcile`; тики пропускают проект без потери состояния (автономность, перезапуски, напоминания, intake, уточнение, чат с аналитиком, приёмка продукта, ссылка на продукт, перезапуск из-за секретов, ревьюер, «готово к ревью», отложенное «Принять», ошибки из прода — `open` без сообщения), вебхуки (красные проверки, комментарии Gitea) записываются без запуска агента; живой агент проекта на паузе вачдог останавливает сам и дописывает в `sessions`. Веб: `components/ProjectPause.tsx` (кнопка с подтверждением, плашка, метка «На паузе»), «⋯ Настройки проекта → Пауза», «Ждут вашего ответа»/счётчики/дайджест без проектов на паузе. CLI `peppa project pause|resume `. Новое место, которое запускает агента, зовёт модель или пишет человеку по проекту, — через эти узкие места или с `isProjectPaused`. Тест `project-pause.test.ts` - **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx` - **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts` diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 7d83c314..18d337c2 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -64,7 +64,7 @@ import { checkGiteaBotToken, setUiMode, } from "@peppa/core"; -import { checkConnection, createConnection, deleteConnection, grantConnection, replaceConnectionSecret, revokeConnection, revokeGrant, type CatalogAuth, type ConnectionCheckResult, type GrantMode } from "@peppa/core"; +import { checkConnection, createConnection, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGrantTerm, replaceConnectionSecret, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core"; import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core"; import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner"; import { bugsinkFromEnv } from "@peppa/bugsink"; @@ -1034,7 +1034,24 @@ export async function grantConnectionAction(f: FormData) { await attempt(f, async () => { const agent = str(f, "agentId"); const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off"); - await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? "") }); + await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? ""), term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM }); + }); +} + +/** PEP-259 «Продлить»: the same term again from now. */ +export async function extendGrantAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + await extendGrant(db, user.id, Number(str(f, "grantId"))); + }); +} + +/** PEP-259: «Снимать разрешение без дела через …» of one connection ("" — platform default). */ +export async function setConnectionIdleAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const v = str(f, "idleHours"); + await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v)); }); } diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx index d2cb7ad1..4aaf6d1c 100644 --- a/apps/web/app/(app)/connections/page.tsx +++ b/apps/web/app/(app)/connections/page.tsx @@ -7,6 +7,12 @@ import { CONNECTION_CHECK_TEXT, CONNECTION_REASON_TEXT, connectionJournal, + DEFAULT_GRANT_TERM, + defaultIdleRevokeHours, + GRANT_TERM_TEXT, + GRANT_TERMS, + IDLE_HOURS_CHOICES, + serverTimezone, JOURNAL_VERIFY_SCRIPT, grantableAgents, listConnections, @@ -21,6 +27,7 @@ import { type GrantMode, } from "@peppa/core"; import { Hidden } from "@/components/cards"; +import { intlLocale } from "@peppa/shared/i18n"; import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; @@ -31,7 +38,7 @@ import { requireUser, uiMode } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; import type { Translator } from "@peppa/shared/i18n"; -import { checkConnectionAction, createConnectionAction, deleteConnectionAction, grantConnectionAction, replaceConnectionSecretAction, revokeConnectionAction, revokeGrantAction } from "../actions"; +import { checkConnectionAction, createConnectionAction, deleteConnectionAction, extendGrantAction, grantConnectionAction, replaceConnectionSecretAction, revokeConnectionAction, revokeGrantAction, setConnectionIdleAction } from "../actions"; export async function generateMetadata() { const t = await getT(); @@ -67,23 +74,97 @@ function modeText(m: GrantMode, t: Translator): string { return m === "auto" ? t("сразу") : m === "ask" ? t("спрашивать меня") : t("нет"); } +/** «14:05 25.11» in the platform's time zone. */ +function when(d: Date, t: Translator): string { + const loc = intlLocale(t.locale); + const tz = serverTimezone(); + return `${d.toLocaleTimeString(loc, { hour: "2-digit", minute: "2-digit", timeZone: tz })} ${d.toLocaleDateString(loc, { day: "2-digit", month: "2-digit", timeZone: tz })}`; +} + +/** «через 5 ч» / «через 2 дн» — how soon a grant is revoked without calls. */ +function hoursLeft(d: Date, t: Translator): string { + const h = Math.max(0, Math.ceil((d.getTime() - Date.now()) / 3600_000)); + return h < 48 ? t("{n} ч", { n: h }) : t("{n} дн", { n: Math.round(h / 24) }); +} + function GrantLine({ g, engineer, t }: { g: ConnectionGrantView; engineer: boolean; t: Translator }) { + const ended = g.state !== "active"; return ( -
  • - {g.projectKey} - · {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")} - - · {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })} - - {engineer && g.operations.length > 0 && {g.operations.join(", ")}} -
    - - - +
  • +
    + {g.projectKey} + · {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")} + + · {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })} + + {g.state === "expired" && {t("срок истёк")}} + {g.state === "idle" && {t("снято: {n} ч без дела", { n: g.idleHours })}} + {engineer && g.operations.length > 0 && {g.operations.join(", ")}} +
    + {(ended || g.term !== "forever") && ( +
    + + + + )} +
    + + + +
    +
    +
    + {!ended && {g.expiresAt ? t("до {when}", { when: when(g.expiresAt, t) }) : t("до отзыва")}} + {g.state === "expired" && g.expiresAt && {t("действовало до {when}", { when: when(g.expiresAt, t) })}} + {g.state === "idle" && g.endedAt && {t("снято {ago}", { ago: ago(g.endedAt, t) })}} + {g.lastUsedAt ? t("последний вызов {ago}", { ago: ago(g.lastUsedAt, t) }) : t("вызовов ещё не было")} + {g.idleRevokeAt && {t("снимется через {left} без дела", { left: hoursLeft(g.idleRevokeAt, t) })}} +
  • ); } +function TermSelect({ t }: { t: Translator }) { + return ( + + ); +} + +function idleText(h: number, t: Translator): string { + return h === 0 ? t("не снимать") : h % 24 === 0 && h >= 48 ? t("{n} дн без дела", { n: h / 24 }) : t("{n} ч без дела", { n: h }); +} + +/** PEP-259: «Снимать разрешение без дела через …» of one connection. */ +function IdleForm({ c, t }: { c: ConnectionView; t: Translator }) { + const def = defaultIdleRevokeHours(); + return ( +
    + + {t("Снимать разрешение, которым не пользуются:")} + + + + ); +} + function ModeSelect({ name, label, def, t }: { name: string; label: string; def: GrantMode; t: Translator }) { return ( +

    {t("Чтение — смотреть данные, ничего не меняя. Запись — создавать, менять, удалять и отправлять. «Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.")} @@ -182,6 +264,7 @@ function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionVie ))} )} + {c.grants.length > 0 && } {active && projects.length > 0 && } @@ -407,9 +490,13 @@ export default async function ConnectionsPage({ searchParams }: { searchParams: {r.projectKey ?? "—"} {r.agentName ? ` · ${r.agentName}` : ""} - - {r.method} {r.path} - + {r.method === "REVOKE" ? ( + {t("разрешение снято")} + ) : ( + + {r.method} {r.path} + + )} diff --git a/openspec/changes/archive/2026-11-24-pep-259-grant-terms/design.md b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/design.md new file mode 100644 index 00000000..cdf0d9ef --- /dev/null +++ b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/design.md @@ -0,0 +1,17 @@ +## Context +Access Hub (PEP-234/249/254): подключения владельца, разрешения проекту/агенту (`connection_grants`), шлюз `callConnection`, журнал с цепочкой хэшей (`appendJournal`). Запросы доступа агента (PEP-250) — в ревью, не в main. + +## Decisions +- **Срок хранится двумя полями**: `term` (`1h|1d|7d|forever`) — чтобы «Продлить» выдавало тот же срок, и `expires_at` (null — до отзыва). Ядро без `term` выдаёт «до отзыва» (обратная совместимость: прежние вызовы и тесты); веб-форма по умолчанию — 1 день (минимум привилегий). +- **Простой**: `granted_at` (выдача/продление) и `last_used_at` (шлюз, при разрешённом вызове). Якорь = `max(last_used_at, granted_at)`. Миграция ставит `granted_at` = время миграции всем старым строкам — отсчёт с выкатки, ничего не снимется сразу. +- **Снятие не удаляет строку**: `ended_at` + `end_reason` (`idle`). Так шлюз отличает «нет разрешения» от «снято/истекло» и говорит агенту правильную причину, а владелец видит строку «снято: 72 ч без дела» и может продлить. Истечение — вычисляемое (`expires_at <= now`), тик его не пишет. Снятые и истёкшие строки старше 30 дней тик удаляет. +- **Порог** — `connections.idle_revoke_hours` (null — умолчание платформы `PEPPA_CONNECTION_IDLE_HOURS`, 72; 0 — не снимать). +- **Причины шлюза**: `expired`, `idle_revoked`. Если у агента есть живое разрешение — решает оно; иначе, если подходящее разрешение было, но истекло/снято — эта причина, иначе `no_grant`. +- **Журнал**: снятие — строка `connection_log` через `appendJournal` (метод `REVOKE`, путь `/`, `denied`, причина `idle_revoked`, проект и агент разрешения) — попадает в цепочку хэшей и в журнал на экране. +- **Сводка владельцу**: снятые за прошедшие сутки копятся в `settings` `connections.idle.digest:`; тик раз в сутки шлёт одно сообщение (мастер-чат + `deliverToUser` событием `failures`, ночная тишина — у очередей сама). Живому агенту ничего не шлётся. +- **Пауза проекта**: разрешения проектов на паузе (`pausedProjectIds`) по простою не снимаются. +- **Права для будущих кнопок «Дать»**: `GRANT_RIGHTS` — `read` (чтение сразу, запись нет) и `full` (чтение сразу, запись — `auto`). Когда появится режим подключения PEP-235, `full` возьмёт его. +- Вынесено в отдельную задачу PEP-261 (ждёт PEP-250): кнопки под запросом доступа. Telegram-кнопок без запроса нет — нечему их показывать. + +## Risks +- Миграция 0031 может столкнуться с параллельными задачами Access Hub (PEP-250…253) — при rebase перенумеровать. diff --git a/openspec/changes/archive/2026-11-24-pep-259-grant-terms/proposal.md b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/proposal.md new file mode 100644 index 00000000..baa6ec2c --- /dev/null +++ b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/proposal.md @@ -0,0 +1,15 @@ +## Why +Разрешение агенту в Access Hub (`connection_grants`) сейчас вечное: выдали — живёт, пока владелец не вспомнит и не отзовёт. По образцу брокеров доступа (Sallyport) у разрешения должен быть срок, а разрешение, которым долго никто не пользуется, должно сниматься само. + +## What Changes +- У разрешения появляется срок: 1 час · 1 день · 7 дней · до отзыва (`connection_grants.term`, `expires_at`). Истёкшее разрешение шлюз не принимает: агенту — «доступ истёк», в журнал — `denied` с причиной `expired`. +- Шлюз отмечает `last_used_at` разрешения при разрешённом вызове. +- Автоснятие без дела: разрешение, которым не пользовались `idleRevokeHours` (у подключения; по умолчанию платформы 72 ч, `PEPPA_CONNECTION_IDLE_HOURS`; 0 — выкл), снимается в тике вачдога (`grantExpiryTick`). Отсчёт — от последнего вызова, иначе от выдачи. Запись в журнал подключений («снято: 72 ч без дела»), владельцу — одна сводка в сутки, если что-то снято. Проекты на паузе не считаются. +- «Продлить» — тот же срок заново одной кнопкой; снятое и истёкшее разрешение можно продлить. +- Веб «Подключения»: срок в форме выдачи (по умолчанию 1 день), у разрешения — «до ЧЧ:ММ ДД.ММ» / «до отзыва», последний вызов, «снимется через N ч без дела», «истекло» / «снято», кнопка «Продлить»; у подключения — «Снимать разрешение без дела через …». +- MCP агента `list_connections` (и `peppa.connections.list()`) показывает срок и когда разрешение снимется; отказ шлюза по сроку объясняет, что делать. +- Миграция: новые колонки, старые разрешения — «до отзыва», отсчёт простоя с момента выкатки (`granted_at` = время миграции). +- **Не входит** (отдельная задача после PEP-250): кнопки «Дать: чтение / полные права / Отказать» и выбор срока под запросом доступа агента в вебе и Telegram — запросов доступа (PEP-250) ещё нет в основной ветке. Для них готова функция выдачи с правами и сроком (`grantConnection` с `term`, `GRANT_RIGHTS`). + +## Impact +- `packages/db` (схема, миграция 0031), `packages/core/src/connections.ts`, `packages/runner/src/watchdog.ts`, `packages/mcp/src/agent.ts`, веб `/connections` и действия, переводы en/kk, тесты `access-hub-terms.test.ts`. diff --git a/openspec/changes/archive/2026-11-24-pep-259-grant-terms/specs/access-hub/spec.md b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/specs/access-hub/spec.md new file mode 100644 index 00000000..0fdbcd7a --- /dev/null +++ b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/specs/access-hub/spec.md @@ -0,0 +1,67 @@ +## ADDED Requirements + +### Requirement: Срок разрешения +Владелец SHALL выдавать разрешение агенту на срок: 1 час, 1 день, 7 дней или до отзыва. Шлюз SHALL отклонять вызов по истёкшему разрешению с причиной `expired` и записью `denied` в журнале. Владелец SHALL продлевать разрешение на тот же срок одной кнопкой, в том числе истёкшее или снятое. + +#### Scenario: Вызов по живому разрешению на 1 день +- **GIVEN** владелец «anna» выдала агенту проекта «чтение» подключения «CRM» на 1 день +- **WHEN** агент через 2 часа читает `GET /items` +- **THEN** сервис отвечает агенту +- **AND** у разрешения виден последний вызов + +#### Scenario: Вызов после истечения срока +- **GIVEN** разрешение на 1 день выдано 25 часов назад +- **WHEN** агент читает `GET /items` +- **THEN** вызов отклонён с причиной «доступ истёк» +- **AND** в журнале владельца строка `denied` с причиной `expired` + +#### Scenario: Продление истёкшего разрешения +- **GIVEN** разрешение на 1 день истекло +- **WHEN** владелец нажимает «Продлить» +- **THEN** разрешение действует ещё сутки от нажатия +- **AND** агент снова читает `GET /items` + +#### Scenario: Чужой пользователь не продлевает +- **GIVEN** разрешение подключения «anna» +- **WHEN** пользователь «boris» пытается его продлить +- **THEN** отказ «Подключение не найдено» + +### Requirement: Автоснятие разрешения без дела +Разрешение, которым не пользовались дольше порога подключения (по умолчанию 72 ч; 0 — не снимать), SHALL сниматься само в тике вачдога. Отсчёт SHALL идти от последнего вызова, а без вызовов — от выдачи или продления. Снятие SHALL записываться в журнал подключений; владелец SHALL получать не больше одной сводки в сутки. Разрешения проектов на паузе SHALL не сниматься по простою. + +#### Scenario: Разрешение без вызовов 72 часа +- **GIVEN** разрешение выдано 73 часа назад, вызовов не было +- **WHEN** проходит тик вачдога +- **THEN** разрешение снято с отметкой «72 ч без дела» +- **AND** в журнале подключений строка «снято» +- **AND** вызов агента отклонён с причиной `idle_revoked` + +#### Scenario: Недавний вызов продлевает жизнь +- **GIVEN** разрешение выдано 100 часов назад, последний вызов был 10 часов назад +- **WHEN** проходит тик вачдога +- **THEN** разрешение остаётся + +#### Scenario: Порог 0 — не снимать +- **GIVEN** у подключения «Снимать без дела» = никогда +- **AND** разрешением не пользовались 500 часов +- **WHEN** проходит тик вачдога +- **THEN** разрешение остаётся + +#### Scenario: Проект на паузе +- **GIVEN** проект на паузе, разрешение без вызовов 100 часов +- **WHEN** проходит тик вачдога +- **THEN** разрешение остаётся + +#### Scenario: Старые разрешения после выкатки +- **GIVEN** разрешение выдано до выкатки +- **WHEN** выкатка применила миграцию +- **THEN** разрешение действует до отзыва +- **AND** простой считается с момента выкатки + +### Requirement: Агент видит срок разрешения +`list_connections` SHALL показывать агенту, до какого времени действует доступ и когда он снимется без дела. + +#### Scenario: Список подключений агента +- **GIVEN** агенту выдано «чтение» CRM на 7 дней +- **WHEN** агент вызывает `list_connections` +- **THEN** в ответе есть время окончания доступа и время снятия без дела diff --git a/openspec/changes/archive/2026-11-24-pep-259-grant-terms/tasks.md b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/tasks.md new file mode 100644 index 00000000..f4bba6d9 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-pep-259-grant-terms/tasks.md @@ -0,0 +1,16 @@ +## 1. Данные +- [x] 1.1 Схема: `connection_grants.term|expires_at|granted_at|last_used_at|ended_at|end_reason`, `connections.idle_revoke_hours`; миграция 0031 (старым — `granted_at` = время миграции) + +## 2. Ядро +- [x] 2.1 `grantConnection` с `term`, `GRANT_TERMS`, `GRANT_RIGHTS`; `extendGrant`; `setConnectionIdleHours`; вид разрешения (срок, последний вызов, когда снимется, состояние) +- [x] 2.2 Шлюз: только живые разрешения, причины `expired` / `idle_revoked`, `last_used_at` разрешения +- [x] 2.3 `grantExpiryTick`: снятие без дела (пауза проекта, журнал, событие), уборка старых, суточная сводка владельцу; вачдог +- [x] 2.4 `agentConnections`: срок и когда снимется + +## 3. Поверхности +- [x] 3.1 MCP `list_connections` и подсказка в отказе `call_connection` +- [x] 3.2 Веб `/connections`: срок в форме, строка разрешения, «Продлить», порог у подключения; переводы en/kk; словарь + +## 4. Проверка +- [x] 4.1 Тесты `access-hub-terms.test.ts` (истечение, автоснятие с `now`, продление, чужой пользователь, пауза) + регрессия access-hub* +- [x] 4.2 Проверки (lint, typecheck, test), память, задача на кнопки «Дать» после PEP-250 diff --git a/openspec/specs/access-hub/spec.md b/openspec/specs/access-hub/spec.md index 7fd6e07b..1af32605 100644 --- a/openspec/specs/access-hub/spec.md +++ b/openspec/specs/access-hub/spec.md @@ -229,3 +229,69 @@ SHALL отправить владельцу одно сообщение. - **WHEN** выполняется перевод ключей - **THEN** у «CRM» появляется свой ключ данных - **AND** вызов через «CRM» работает с прежним ключом доступа + +### Requirement: Срок разрешения +Владелец SHALL выдавать разрешение агенту на срок: 1 час, 1 день, 7 дней или до отзыва. Шлюз SHALL отклонять вызов по истёкшему разрешению с причиной `expired` и записью `denied` в журнале. Владелец SHALL продлевать разрешение на тот же срок одной кнопкой, в том числе истёкшее или снятое. + +#### Scenario: Вызов по живому разрешению на 1 день +- **GIVEN** владелец «anna» выдала агенту проекта «чтение» подключения «CRM» на 1 день +- **WHEN** агент через 2 часа читает `GET /items` +- **THEN** сервис отвечает агенту +- **AND** у разрешения виден последний вызов + +#### Scenario: Вызов после истечения срока +- **GIVEN** разрешение на 1 день выдано 25 часов назад +- **WHEN** агент читает `GET /items` +- **THEN** вызов отклонён с причиной «доступ истёк» +- **AND** в журнале владельца строка `denied` с причиной `expired` + +#### Scenario: Продление истёкшего разрешения +- **GIVEN** разрешение на 1 день истекло +- **WHEN** владелец нажимает «Продлить» +- **THEN** разрешение действует ещё сутки от нажатия +- **AND** агент снова читает `GET /items` + +#### Scenario: Чужой пользователь не продлевает +- **GIVEN** разрешение подключения «anna» +- **WHEN** пользователь «boris» пытается его продлить +- **THEN** отказ «Подключение не найдено» + +### Requirement: Автоснятие разрешения без дела +Разрешение, которым не пользовались дольше порога подключения (по умолчанию 72 ч; 0 — не снимать), SHALL сниматься само в тике вачдога. Отсчёт SHALL идти от последнего вызова, а без вызовов — от выдачи или продления. Снятие SHALL записываться в журнал подключений; владелец SHALL получать не больше одной сводки в сутки. Разрешения проектов на паузе SHALL не сниматься по простою. + +#### Scenario: Разрешение без вызовов 72 часа +- **GIVEN** разрешение выдано 73 часа назад, вызовов не было +- **WHEN** проходит тик вачдога +- **THEN** разрешение снято с отметкой «72 ч без дела» +- **AND** в журнале подключений строка «снято» +- **AND** вызов агента отклонён с причиной `idle_revoked` + +#### Scenario: Недавний вызов продлевает жизнь +- **GIVEN** разрешение выдано 100 часов назад, последний вызов был 10 часов назад +- **WHEN** проходит тик вачдога +- **THEN** разрешение остаётся + +#### Scenario: Порог 0 — не снимать +- **GIVEN** у подключения «Снимать без дела» = никогда +- **AND** разрешением не пользовались 500 часов +- **WHEN** проходит тик вачдога +- **THEN** разрешение остаётся + +#### Scenario: Проект на паузе +- **GIVEN** проект на паузе, разрешение без вызовов 100 часов +- **WHEN** проходит тик вачдога +- **THEN** разрешение остаётся + +#### Scenario: Старые разрешения после выкатки +- **GIVEN** разрешение выдано до выкатки +- **WHEN** выкатка применила миграцию +- **THEN** разрешение действует до отзыва +- **AND** простой считается с момента выкатки + +### Requirement: Агент видит срок разрешения +`list_connections` SHALL показывать агенту, до какого времени действует доступ и когда он снимется без дела. + +#### Scenario: Список подключений агента +- **GIVEN** агенту выдано «чтение» CRM на 7 дней +- **WHEN** агент вызывает `list_connections` +- **THEN** в ответе есть время окончания доступа и время снятия без дела diff --git a/packages/core/src/connections.ts b/packages/core/src/connections.ts index d44566ad..a2425f80 100644 --- a/packages/core/src/connections.ts +++ b/packages/core/src/connections.ts @@ -6,7 +6,7 @@ // the agent's project (and the agent, or any agent of the project). See the change // pep-234-access-hub (design.md — threat model). import { asIs, m as tr } from "@peppa/shared/i18n"; -import { agents, connectionGrants, connectionLog, connections, projects, sessions, users, type Db } from "@peppa/db"; +import { agents, connectionGrants, connectionLog, connections, keyPrefix, projects, sessions, settings, users, type Db } from "@peppa/db"; import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm"; import { lookup as dnsLookup, type LookupAddress } from "node:dns"; import { request as httpRequest, type IncomingMessage } from "node:http"; @@ -21,6 +21,8 @@ import { deliverToUser } from "./notifications.ts"; import { PeppaError } from "./errors.ts"; import { maskSecrets } from "./secrets.ts"; import { projectForUser } from "./users.ts"; +import { pausedProjectIds } from "./project-pause.ts"; +import { getSetting, setSetting } from "./settings.ts"; export const CONNECTION_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const; export type ConnectionMethod = (typeof CONNECTION_METHODS)[number]; @@ -41,6 +43,8 @@ export type ConnectionReason = | "ambiguous_connection" | "revoked" | "no_grant" + | "expired" + | "idle_revoked" | "operation_denied" | "read_denied" | "write_denied" @@ -62,6 +66,8 @@ export const CONNECTION_REASON_TEXT: Record = { ambiguous_connection: tr("несколько подключений с таким названием"), revoked: tr("подключение отозвано"), no_grant: tr("нет разрешения для проекта или агента"), + expired: tr("срок доступа истёк"), + idle_revoked: tr("доступ снят: им долго не пользовались"), operation_denied: tr("операция не разрешена"), read_denied: tr("чтение не разрешено"), write_denied: tr("запись не разрешена"), @@ -93,6 +99,8 @@ export interface ConnectionView { hasKey: boolean; revokedAt: Date | null; lastUsedAt: Date | null; + /** PEP-259: own threshold of «revoke after N hours without calls»; null — platform default. */ + idleRevokeHours: number | null; createdAt: Date; grants: ConnectionGrantView[]; } @@ -108,6 +116,51 @@ export interface ConnectionGrantView { readMode: GrantMode; writeMode: GrantMode; createdAt: Date; + /** PEP-259: the term chosen; «Продлить» gives the same again. */ + term: GrantTerm; + /** null — until revoked. */ + expiresAt: Date | null; + lastUsedAt: Date | null; + /** When it is revoked if nobody uses it (null — never: the connection's threshold is 0). */ + idleRevokeAt: Date | null; + /** active; expired — the term is over; idle — revoked by the watchdog for no use. */ + state: GrantState; + endedAt: Date | null; + /** Hours of the threshold that revoked it (for «снято: 72 ч без дела»). */ + idleHours: number; +} + +/** PEP-259: how long a grant lives. */ +export type GrantTerm = "1h" | "1d" | "7d" | "forever"; +export const GRANT_TERMS: GrantTerm[] = ["1h", "1d", "7d", "forever"]; +export const GRANT_TERM_MS: Record = { "1h": 3600_000, "1d": 24 * 3600_000, "7d": 7 * 24 * 3600_000, forever: null }; +export const GRANT_TERM_TEXT: Record = { "1h": tr("1 час"), "1d": tr("1 день"), "7d": tr("7 дней"), forever: tr("до отзыва") }; +/** Default term of a grant given by a button (web form, an agent's request). */ +export const DEFAULT_GRANT_TERM: GrantTerm = "1d"; +export type GrantState = "active" | "expired" | "idle"; +/** PEP-259: «Дать: чтение» / «Дать: полные права» (full = reading and writing at once; PEP-235 mode later). */ +export type GrantRights = "read" | "full"; +export const GRANT_RIGHTS: Record = { read: { readMode: "auto", writeMode: "off" }, full: { readMode: "auto", writeMode: "auto" } }; +export const isGrantTerm = (v: unknown): v is GrantTerm => GRANT_TERMS.includes(v as GrantTerm); + +/** PEP-259: platform default of «revoke a grant after N hours without calls» (0 — never). */ +export function defaultIdleRevokeHours(env: NodeJS.ProcessEnv = process.env): number { + const n = Number(env.PEPPA_CONNECTION_IDLE_HOURS); + return env.PEPPA_CONNECTION_IDLE_HOURS != null && env.PEPPA_CONNECTION_IDLE_HOURS !== "" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 72; +} +export const IDLE_HOURS_CHOICES = [24, 72, 168, 0] as const; +const idleHoursOf = (c: { idleRevokeHours: number | null }) => c.idleRevokeHours ?? defaultIdleRevokeHours(); + +type GrantRow = typeof connectionGrants.$inferSelect; +/** The countdown of «no use» starts at the last call, otherwise at the grant (or the deploy that added the column). */ +const idleAnchor = (g: Pick) => Math.max(g.lastUsedAt?.getTime() ?? 0, (g.grantedAt ?? g.createdAt).getTime()); +export function grantState(g: Pick, now: Date): GrantState { + if (g.endedAt) return "idle"; + if (g.expiresAt && g.expiresAt.getTime() <= now.getTime()) return "expired"; + return "active"; +} +function idleRevokeAt(g: Pick, hours: number): Date | null { + return hours > 0 ? new Date(idleAnchor(g) + hours * 3600_000) : null; } export type GrantMode = "off" | "auto" | "ask"; @@ -390,6 +443,11 @@ export interface GrantInput { /** PEP-249: reading / writing by the catalog's read rule. */ readMode?: GrantMode; writeMode?: GrantMode; + /** PEP-259: how long; default — until revoked (the web form and buttons default to 1 day). */ + term?: GrantTerm; + /** «Дать: чтение / полные права» — sets both modes. */ + rights?: GrantRights; + now?: Date; } const mode = (m: unknown): GrantMode => (GRANT_MODES.includes(m as GrantMode) ? (m as GrantMode) : "off"); @@ -403,22 +461,45 @@ export async function grantConnection(db: Db, userId: number, connectionId: numb const [a] = await db.select({ id: agents.id }).from(agents).where(eq(agents.id, agentId)); if (!a) throw new PeppaError(tr("Агент не найден")); } - const readMode = mode(g.readMode); - const writeMode = mode(g.writeMode); + const readMode = g.rights ? GRANT_RIGHTS[g.rights].readMode : mode(g.readMode); + const writeMode = g.rights ? GRANT_RIGHTS[g.rights].writeMode : mode(g.writeMode); + const term: GrantTerm = isGrantTerm(g.term) ? g.term : "forever"; + const now = g.now ?? new Date(); + const life = { term, expiresAt: GRANT_TERM_MS[term] == null ? null : new Date(now.getTime() + GRANT_TERM_MS[term]!), grantedAt: now, endedAt: null, endReason: null }; const anyMode = readMode !== "off" || writeMode !== "off"; const operations = normalizeOperations(g.operations ?? [], { allowEmpty: true }); if (!anyMode && !operations.length) throw new PeppaError(tr("Разрешите чтение, запись или хотя бы одну операцию")); const existing = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, c.id), eq(connectionGrants.projectId, g.projectId)))).find((x) => x.agentId === agentId); let id: number; if (existing) { - await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId }).where(eq(connectionGrants.id, existing.id)); + await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId, ...life }).where(eq(connectionGrants.id, existing.id)); id = existing.id; } else { - const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId }).returning({ id: connectionGrants.id }); + const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId, ...life }).returning({ id: connectionGrants.id }); id = row!.id; } - await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode } }); - return (await grantViews(db, [c.id])).find((x) => x.id === id)!; + await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode, term } }); + return (await grantViews(db, [c.id], now)).find((x) => x.id === id)!; +} + +/** PEP-259 «Продлить»: the same term again from now; brings back an expired or revoked-for-idle grant. */ +export async function extendGrant(db: Db, userId: number, grantId: number, o: { now?: Date } = {}): Promise { + const [g] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId)); + if (!g) throw new PeppaError(tr("Разрешение не найдено")); + const c = await ownConnection(db, userId, g.connectionId); + if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа")); + const now = o.now ?? new Date(); + const ms = GRANT_TERM_MS[g.term]; + await db.update(connectionGrants).set({ expiresAt: ms == null ? null : new Date(now.getTime() + ms), grantedAt: now, endedAt: null, endReason: null }).where(eq(connectionGrants.id, g.id)); + await logEvent(db, { projectId: g.projectId, type: "connection_grant_extended", payload: { connectionId: g.connectionId, agentId: g.agentId, term: g.term } }); + return (await grantViews(db, [c.id], now)).find((x) => x.id === g.id)!; +} + +/** PEP-259: the connection's «revoke a grant after N hours without calls»; null — platform default, 0 — never. */ +export async function setConnectionIdleHours(db: Db, userId: number, connectionId: number, hours: number | null): Promise { + const c = await ownConnection(db, userId, connectionId); + if (hours != null && (!Number.isInteger(hours) || hours < 0 || hours > 24 * 365)) throw new PeppaError(tr("Недопустимый срок")); + await db.update(connections).set({ idleRevokeHours: hours }).where(eq(connections.id, c.id)); } export async function revokeGrant(db: Db, userId: number, grantId: number): Promise { @@ -429,9 +510,9 @@ export async function revokeGrant(db: Db, userId: number, grantId: number): Prom await logEvent(db, { projectId: g.projectId, type: "connection_grant_revoked", payload: { connectionId: g.connectionId, agentId: g.agentId } }); } -async function grantViews(db: Db, connectionIds: number[]): Promise> { +async function grantViews(db: Db, connectionIds: number[], now: Date = new Date()): Promise> { if (!connectionIds.length) return []; - return db + const rows = await db .select({ id: connectionGrants.id, connectionId: connectionGrants.connectionId, @@ -444,21 +525,33 @@ async function grantViews(db: Db, connectionIds: number[]): Promise { + const idleHours = idleHoursOf({ idleRevokeHours }); + const state = grantState(r, now); + return { ...r, state, idleHours, idleRevokeAt: state === "active" ? idleRevokeAt({ ...r, grantedAt }, idleHours) : null }; + }); } /** Short name for agents; connections made before PEP-249 get one from their name. */ export const connectionSlug = (r: { id: number; name: string; slug: string | null }) => r.slug || slugify(r.name) || `c${r.id}`; /** The user's own connections with grants; never the key. */ -export async function listConnections(db: Db, userId: number): Promise { +export async function listConnections(db: Db, userId: number, o: { now?: Date } = {}): Promise { const rows = await db.select().from(connections).where(eq(connections.ownerId, userId)).orderBy(asc(connections.name)); - const grants = await grantViews(db, rows.map((r) => r.id)); + const grants = await grantViews(db, rows.map((r) => r.id), o.now); return rows.map((r) => ({ id: r.id, name: r.name, @@ -473,6 +566,7 @@ export async function listConnections(db: Db, userId: number): Promise g.connectionId === r.id).map(({ connectionId: _, ...g }) => g), })); @@ -561,6 +655,10 @@ export interface AgentConnection { writeMode: GrantMode; operations: string[]; checkStatus: ConnectionCheckStatus | null; + /** PEP-259: the latest end among the agent's live grants; null — at least one is until revoked. */ + expiresAt: Date | null; + /** When the last live grant is revoked without calls; null — never. */ + idleRevokeAt: Date | null; } const RANK: Record = { off: 0, ask: 1, auto: 2 }; @@ -568,12 +666,13 @@ const RANK: Record = { off: 0, ask: 1, auto: 2 }; const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a); /** What this session's agent may use: active connections granted to its project and agent. */ -export async function agentConnections(db: Db, sessionId: number): Promise { +export async function agentConnections(db: Db, sessionId: number, o: { now?: Date } = {}): Promise { + const now = o.now ?? new Date(); const s = await sessionCtx(db, sessionId); // Like the gateway: an unisolated agent is refused, so it is shown nothing. if (!s || !agentIsolated(s)) return []; const rows = await db - .select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode }) + .select({ c: connections, g: connectionGrants, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode }) .from(connectionGrants) .innerJoin(connections, eq(connections.id, connectionGrants.connectionId)) .where(and(eq(connectionGrants.projectId, s.projectId), eq(connections.status, "active"))) @@ -581,8 +680,13 @@ export async function agentConnections(db: Db, sessionId: number): Promise(); for (const r of rows) { if (r.agentId != null && r.agentId !== s.agentId) continue; + if (grantState(r.g, now) !== "active") continue; const card = catalogService(r.c.catalogId); - const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus }; + const first = !by.has(r.c.id); + const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus, expiresAt: null, idleRevokeAt: null }; + const idle = idleRevokeAt(r.g, idleHoursOf(r.c)); + c.expiresAt = first ? r.g.expiresAt : c.expiresAt && r.g.expiresAt ? (r.g.expiresAt > c.expiresAt ? r.g.expiresAt : c.expiresAt) : null; + c.idleRevokeAt = first ? idle : c.idleRevokeAt && idle ? (idle > c.idleRevokeAt ? idle : c.idleRevokeAt) : null; c.operations = [...new Set([...c.operations, ...r.operations])]; c.readMode = widest(c.readMode, r.readMode); c.writeMode = widest(c.writeMode, r.writeMode); @@ -746,7 +850,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: // Find the connection among those granted to this project (never by a bare id of someone else). const granted = await db - .select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode }) + .select({ c: connections, g: connectionGrants, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode }) .from(connectionGrants) .innerJoin(connections, eq(connections.id, connectionGrants.connectionId)) .where(eq(connectionGrants.projectId, s.projectId)); @@ -761,8 +865,11 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: if (!agentIsolated(s, o.env)) return deny("not_isolated"); if (conn.status !== "active" || !conn.secretEnc) return deny("revoked"); - const mine = matches.filter((g) => g.agentId == null || g.agentId === s.agentId); - if (!mine.length) return deny("no_grant"); + const ours = matches.filter((g) => g.agentId == null || g.agentId === s.agentId); + if (!ours.length) return deny("no_grant"); + // PEP-259: only live grants decide; with none left, say why — the term is over or it was revoked for no use. + const mine = ours.filter((g) => grantState(g.g, now) === "active"); + if (!mine.length) return deny(ours.some((g) => grantState(g.g, now) === "expired") ? "expired" : "idle_revoked"); if (!CONNECTION_METHODS.includes(method as ConnectionMethod)) return deny("bad_request"); const clean = cleanPath(rawPath); if (!clean) return deny("bad_path"); @@ -789,6 +896,8 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: // Written before the service is called: a crash in the middle leaves «started, no result». const callId = (await record("allowed", null, null))!; + // PEP-259: the grant is in use — the idle countdown starts again (even if the service then fails). + await db.update(connectionGrants).set({ lastUsedAt: now }).where(inArray(connectionGrants.id, mine.map((g) => g.g.id))); const started = Date.now(); const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) => record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started }); @@ -912,3 +1021,110 @@ export async function tellKeyStopped(db: Db, c: { id: number; ownerId: number; n push: { title: tr("FORGE"), body: text, url: "/connections", tag: key }, }).catch(() => null); } + +// ---------- PEP-259: terms and revoking idle grants ---------- + +/** Revoked-for-idle and expired grants stay visible (extend in one click) this long, then go. */ +export const GRANT_KEEP_ENDED_MS = 30 * 24 * 3600_000; +const IDLE_DIGEST = "connections.idle.digest:"; +const IDLE_DIGEST_SENT = "connections.idle.sent:"; +const DIGEST_EVERY_MS = 24 * 3600_000; + +interface IdleDigestItem { + connection: string; + project: string; + agent: string | null; + hours: number; +} + +/** + * Watchdog tick: a live grant nobody called for the connection's threshold (default 72 h) is + * revoked — journal row, event, a line for the owner's daily summary; the live agent is told + * nothing (it learns on its next call). Paused projects are skipped (their agents can't call). + * Ended grants older than 30 days are deleted. Returns how many were revoked. + */ +export async function grantExpiryTick(db: Db, o: { now?: Date; notify?: (db: Db, ownerId: number, items: IdleDigestItem[]) => Promise } = {}): Promise { + if (process.env.PEPPA_CONNECTION_IDLE === "off") return 0; + const now = o.now ?? new Date(); + const paused = await pausedProjectIds(db); + const rows = await db + .select({ g: connectionGrants, c: connections, projectKey: projects.key, agentName: agents.name }) + .from(connectionGrants) + .innerJoin(connections, eq(connections.id, connectionGrants.connectionId)) + .innerJoin(projects, eq(projects.id, connectionGrants.projectId)) + .leftJoin(agents, eq(agents.id, connectionGrants.agentId)) + .where(and(isNull(connectionGrants.endedAt), eq(connections.status, "active"))); + let revoked = 0; + for (const r of rows) { + if (paused.has(r.g.projectId) || grantState(r.g, now) !== "active") continue; + const hours = idleHoursOf(r.c); + const at = idleRevokeAt(r.g, hours); + if (!at || at.getTime() > now.getTime()) continue; + // Claim: a concurrent call that just used it, or another tick, wins. + const done = await db + .update(connectionGrants) + .set({ endedAt: now, endReason: "idle" }) + .where(and(eq(connectionGrants.id, r.g.id), isNull(connectionGrants.endedAt), r.g.lastUsedAt ? eq(connectionGrants.lastUsedAt, r.g.lastUsedAt) : isNull(connectionGrants.lastUsedAt))) + .returning({ id: connectionGrants.id }); + if (!done.length) continue; + revoked++; + await appendJournal(db, { + ownerId: r.c.ownerId, + kind: "call", + connectionId: r.c.id, + connectionName: r.c.name, + projectId: r.g.projectId, + projectKey: r.projectKey, + agentId: r.g.agentId, + agentName: r.agentName, + method: "REVOKE", + path: "/", + decision: "denied", + reason: "idle_revoked", + statusCode: null, + createdAt: now, + }); + await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_revoked", payload: { connectionId: r.c.id, agentId: r.g.agentId, reason: "idle", hours } }); + const key = `${IDLE_DIGEST}${r.c.ownerId}`; + const list = (await getSetting(db, key)) ?? []; + list.push({ connection: r.c.name, project: r.projectKey, agent: r.agentName, hours }); + await setSetting(db, key, list.slice(-50)); + } + // Ended long ago — gone (the journal keeps the history). + const old = new Date(now.getTime() - GRANT_KEEP_ENDED_MS); + await db.delete(connectionGrants).where(sql`(${connectionGrants.endedAt} is not null and ${connectionGrants.endedAt} < ${old.getTime()}) or (${connectionGrants.endedAt} is null and ${connectionGrants.expiresAt} is not null and ${connectionGrants.expiresAt} < ${old.getTime()})`); + // One summary a day per owner, only when something was revoked. + for (const d of await db.select().from(settings).where(keyPrefix(settings.key, IDLE_DIGEST))) { + const ownerId = Number(d.key.slice(IDLE_DIGEST.length)); + const items = (d.value as IdleDigestItem[] | null) ?? []; + if (!Number.isFinite(ownerId) || !items.length) continue; + const sent = await getSetting(db, `${IDLE_DIGEST_SENT}${ownerId}`); + if (sent != null && now.getTime() - sent < DIGEST_EVERY_MS) continue; + await setSetting(db, `${IDLE_DIGEST_SENT}${ownerId}`, now.getTime()); + await setSetting(db, d.key, []); + await (o.notify ?? tellIdleRevoked)(db, ownerId, items); + } + return revoked; +} + +/** The owner's daily summary of grants revoked for no use: master chat + Telegram/push (night quiet is the outbox's). */ +export async function tellIdleRevoked(db: Db, ownerId: number, items: IdleDigestItem[]): Promise { + const lines = items.slice(0, 10).map((i) => + i.agent + ? tr("— «{name}» в {project}, агент {agent}: {hours} ч без дела", { name: asIs(i.connection), project: asIs(i.project), agent: asIs(i.agent), hours: i.hours }) + : tr("— «{name}» в {project}: {hours} ч без дела", { name: asIs(i.connection), project: asIs(i.project), hours: i.hours }), + ); + const more = items.length > 10 ? [tr("и ещё {n}", { n: items.length - 10 })] : []; + const text = [tr("Сняты разрешения, которыми агенты долго не пользовались: {n}. Если доступ снова нужен — нажмите «Продлить» в разделе «Подключения».", { n: items.length }), ...lines, ...more].join("\n"); + const key = `connection-idle:${ownerId}:${Date.now()}`; + await addMasterMessage(db, ownerId, { kind: "event", text, dedupeKey: `master:${key}`, url: "/connections" }).catch(() => null); + const [u] = await db.select().from(users).where(eq(users.id, ownerId)); + if (!u) return; + await deliverToUser(db, u, { + event: "failures", + dedupeKey: `${key}:${u.telegramChatId}`, + pushKey: `${key}:u${u.id}`, + telegram: { params: { text } }, + push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-idle" }, + }).catch(() => null); +} diff --git a/packages/db/migrations/0031_grant_terms.sql b/packages/db/migrations/0031_grant_terms.sql new file mode 100644 index 00000000..1ddebe95 --- /dev/null +++ b/packages/db/migrations/0031_grant_terms.sql @@ -0,0 +1,8 @@ +ALTER TABLE `connection_grants` ADD `term` text DEFAULT 'forever' NOT NULL;--> statement-breakpoint +ALTER TABLE `connection_grants` ADD `expires_at` integer;--> statement-breakpoint +ALTER TABLE `connection_grants` ADD `granted_at` integer;--> statement-breakpoint +ALTER TABLE `connection_grants` ADD `last_used_at` integer;--> statement-breakpoint +ALTER TABLE `connection_grants` ADD `ended_at` integer;--> statement-breakpoint +ALTER TABLE `connection_grants` ADD `end_reason` text;--> statement-breakpoint +ALTER TABLE `connections` ADD `idle_revoke_hours` integer;--> statement-breakpoint +UPDATE `connection_grants` SET `granted_at` = CAST(unixepoch('subsec') * 1000 AS INTEGER); \ No newline at end of file diff --git a/packages/db/migrations/meta/0031_snapshot.json b/packages/db/migrations/meta/0031_snapshot.json new file mode 100644 index 00000000..376e9019 --- /dev/null +++ b/packages/db/migrations/meta/0031_snapshot.json @@ -0,0 +1,5317 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "2fc490d2-f70d-4f4b-a5a7-677006b3cb22", + "prevId": "1ad8db33-759f-4508-9ebd-50d0f75742c5", + "tables": { + "agents": { + "name": "agents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "character": { + "name": "character", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "agents_name_unique": { + "name": "agents_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "attachments": { + "name": "attachments", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "attachments_task": { + "name": "attachments_task", + "columns": [ + "task_id" + ], + "isUnique": false + }, + "attachments_message": { + "name": "attachments_message", + "columns": [ + "chat_message_id" + ], + "isUnique": false + }, + "attachments_event": { + "name": "attachments_event", + "columns": [ + "event_id" + ], + "isUnique": false + }, + "attachments_project": { + "name": "attachments_project", + "columns": [ + "project_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "attachments_project_id_projects_id_fk": { + "name": "attachments_project_id_projects_id_fk", + "tableFrom": "attachments", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_user_id_users_id_fk": { + "name": "attachments_user_id_users_id_fk", + "tableFrom": "attachments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_task_id_tasks_id_fk": { + "name": "attachments_task_id_tasks_id_fk", + "tableFrom": "attachments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_chat_message_id_chat_messages_id_fk": { + "name": "attachments_chat_message_id_chat_messages_id_fk", + "tableFrom": "attachments", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_event_id_events_id_fk": { + "name": "attachments_event_id_events_id_fk", + "tableFrom": "attachments", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_messages": { + "name": "chat_messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "chat_id": { + "name": "chat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "thread_key": { + "name": "thread_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thread_title": { + "name": "thread_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "important": { + "name": "important", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "author_kind": { + "name": "author_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'system'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_message_id": { + "name": "tg_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chat_messages_dedupe_key_unique": { + "name": "chat_messages_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "chat_messages_chat": { + "name": "chat_messages_chat", + "columns": [ + "chat_id", + "id" + ], + "isUnique": false + }, + "chat_messages_thread": { + "name": "chat_messages_thread", + "columns": [ + "chat_id", + "thread_key", + "id" + ], + "isUnique": false + }, + "chat_messages_created_at": { + "name": "chat_messages_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "chat_messages_tg": { + "name": "chat_messages_tg", + "columns": [ + "tg_chat_id", + "tg_message_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "chat_messages_chat_id_chats_id_fk": { + "name": "chat_messages_chat_id_chats_id_fk", + "tableFrom": "chat_messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_messages_author_user_id_users_id_fk": { + "name": "chat_messages_author_user_id_users_id_fk", + "tableFrom": "chat_messages", + "tableTo": "users", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_question_id_questions_id_fk": { + "name": "chat_messages_question_id_questions_id_fk", + "tableFrom": "chat_messages", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_task_id_tasks_id_fk": { + "name": "chat_messages_task_id_tasks_id_fk", + "tableFrom": "chat_messages", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_title": { + "name": "tg_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_at": { + "name": "tg_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_by": { + "name": "tg_linked_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_bot_user_id": { + "name": "tg_bot_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chats_user_id_unique": { + "name": "chats_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + }, + "chats_project_id_unique": { + "name": "chats_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + }, + "chats_tg_chat_id_unique": { + "name": "chats_tg_chat_id_unique", + "columns": [ + "tg_chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chats_user_id_users_id_fk": { + "name": "chats_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_project_id_projects_id_fk": { + "name": "chats_project_id_projects_id_fk", + "tableFrom": "chats", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_tg_linked_by_users_id_fk": { + "name": "chats_tg_linked_by_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_linked_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chats_tg_bot_user_id_users_id_fk": { + "name": "chats_tg_bot_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_bot_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + }, + "check_runs_task_sha": { + "name": "check_runs_task_sha", + "columns": [ + "task_id", + "sha" + ], + "isUnique": false + }, + "check_runs_updated": { + "name": "check_runs_updated", + "columns": [ + "updated_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "connection_grants": { + "name": "connection_grants", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "connection_id": { + "name": "connection_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "operations": { + "name": "operations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "read_mode": { + "name": "read_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'off'" + }, + "write_mode": { + "name": "write_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'off'" + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "term": { + "name": "term", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'forever'" + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "granted_at": { + "name": "granted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "connection_grants_project": { + "name": "connection_grants_project", + "columns": [ + "project_id" + ], + "isUnique": false + }, + "connection_grants_connection": { + "name": "connection_grants_connection", + "columns": [ + "connection_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "connection_grants_connection_id_connections_id_fk": { + "name": "connection_grants_connection_id_connections_id_fk", + "tableFrom": "connection_grants", + "tableTo": "connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_grants_project_id_projects_id_fk": { + "name": "connection_grants_project_id_projects_id_fk", + "tableFrom": "connection_grants", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_grants_agent_id_agents_id_fk": { + "name": "connection_grants_agent_id_agents_id_fk", + "tableFrom": "connection_grants", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_grants_created_by_users_id_fk": { + "name": "connection_grants_created_by_users_id_fk", + "tableFrom": "connection_grants", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "connection_log": { + "name": "connection_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_id": { + "name": "connection_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_name": { + "name": "connection_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_name": { + "name": "agent_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status_code": { + "name": "status_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'call'" + }, + "parent_id": { + "name": "parent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_key": { + "name": "project_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prev_hash": { + "name": "prev_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "connection_log_owner": { + "name": "connection_log_owner", + "columns": [ + "owner_id", + "id" + ], + "isUnique": false + }, + "connection_log_session_created": { + "name": "connection_log_session_created", + "columns": [ + "session_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "connection_log_owner_id_users_id_fk": { + "name": "connection_log_owner_id_users_id_fk", + "tableFrom": "connection_log", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_log_connection_id_connections_id_fk": { + "name": "connection_log_connection_id_connections_id_fk", + "tableFrom": "connection_log", + "tableTo": "connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "connection_log_project_id_projects_id_fk": { + "name": "connection_log_project_id_projects_id_fk", + "tableFrom": "connection_log", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "connection_log_session_id_sessions_id_fk": { + "name": "connection_log_session_id_sessions_id_fk", + "tableFrom": "connection_log", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "connection_log_agent_id_agents_id_fk": { + "name": "connection_log_agent_id_agents_id_fk", + "tableFrom": "connection_log", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "connections": { + "name": "connections", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'bearer'" + }, + "auth_header": { + "name": "auth_header", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "catalog_id": { + "name": "catalog_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_status": { + "name": "check_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_alerted_at": { + "name": "check_alerted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dek_enc": { + "name": "dek_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "idle_revoke_hours": { + "name": "idle_revoke_hours", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "connections_owner_name": { + "name": "connections_owner_name", + "columns": [ + "owner_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "connections_owner_id_users_id_fk": { + "name": "connections_owner_id_users_id_fk", + "tableFrom": "connections", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "events_session_type": { + "name": "events_session_type", + "columns": [ + "session_id", + "type" + ], + "isUnique": false + }, + "events_type_created": { + "name": "events_type_created", + "columns": [ + "type", + "created_at" + ], + "isUnique": false + }, + "events_project_created": { + "name": "events_project_created", + "columns": [ + "project_id", + "created_at" + ], + "isUnique": false + }, + "events_task_type": { + "name": "events_task_type", + "columns": [ + "task_id", + "type" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "feedback": { + "name": "feedback", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'received'" + }, + "analysis": { + "name": "analysis", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_error": { + "name": "analysis_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_started_at": { + "name": "analysis_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "option_index": { + "name": "option_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reject_reason": { + "name": "reject_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "feedback_user": { + "name": "feedback_user", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + }, + "feedback_status": { + "name": "feedback_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "feedback_user_id_users_id_fk": { + "name": "feedback_user_id_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "feedback_task_id_tasks_id_fk": { + "name": "feedback_task_id_tasks_id_fk", + "tableFrom": "feedback", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "feedback_decided_by_users_id_fk": { + "name": "feedback_decided_by_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "decided_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_deleted_by_users_id_fk": { + "name": "projects_deleted_by_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "deleted_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "push_outbox_status_created": { + "name": "push_outbox_status_created", + "columns": [ + "status", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "msg_type": { + "name": "msg_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_option": { + "name": "default_option", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "questions_project_answered": { + "name": "questions_project_answered", + "columns": [ + "project_id", + "answered_at" + ], + "isUnique": false + }, + "questions_task": { + "name": "questions_task", + "columns": [ + "task_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + }, + "sessions_task_status": { + "name": "sessions_task_status", + "columns": [ + "task_id", + "status" + ], + "isUnique": false + }, + "sessions_status": { + "name": "sessions_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_agent_id_agents_id_fk": { + "name": "sessions_agent_id_agents_id_fk", + "tableFrom": "sessions", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'human'" + }, + "proposed": { + "name": "proposed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + }, + "tasks_project_status_pos": { + "name": "tasks_project_status_pos", + "columns": [ + "project_id", + "status", + "position" + ], + "isUnique": false + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "telegram_outbox_status_created": { + "name": "telegram_outbox_status_created", + "columns": [ + "status", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "telegram_outbox_chat_message_id_chat_messages_id_fk": { + "name": "telegram_outbox_chat_message_id_chat_messages_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "telegram_updates_created": { + "name": "telegram_updates_created", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_token_enc": { + "name": "telegram_bot_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_username": { + "name": "telegram_bot_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_sub": { + "name": "google_sub", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_email": { + "name": "google_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_linked_at": { + "name": "google_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + }, + "users_google_sub_unique": { + "name": "users_google_sub_unique", + "columns": [ + "google_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index b7d35a85..07102705 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -218,6 +218,13 @@ "when": 1795512094088, "tag": "0030_access_hub_journal", "breakpoints": true + }, + { + "idx": 31, + "version": "6", + "when": 1795527756427, + "tag": "0031_grant_terms", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 3483bc51..593bc9f5 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -692,6 +692,8 @@ export const connections = sqliteTable( status: text("status").$type<"active" | "revoked">().notNull().default("active"), revokedAt: integer("revoked_at", { mode: "timestamp_ms" }), lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), + // PEP-259: hours without calls after which a grant is revoked; null = platform default (72), 0 = never. + idleRevokeHours: integer("idle_revoke_hours"), createdAt: createdAt(), updatedAt: updatedAt(), }, @@ -712,6 +714,15 @@ export const connectionGrants = sqliteTable( readMode: text("read_mode").$type<"off" | "auto" | "ask">().notNull().default("off"), writeMode: text("write_mode").$type<"off" | "auto" | "ask">().notNull().default("off"), createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), + // PEP-259: the term chosen (extend gives the same again) and when it ends (null = until revoked). + term: text("term").$type<"1h" | "1d" | "7d" | "forever">().notNull().default("forever"), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }), + // Idle countdown anchor: given / extended (migration: the deploy time); last allowed call. + grantedAt: integer("granted_at", { mode: "timestamp_ms" }), + lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), + // Revoked by the watchdog (the row stays to tell the agent why and let the owner extend). + endedAt: integer("ended_at", { mode: "timestamp_ms" }), + endReason: text("end_reason").$type<"idle">(), createdAt: createdAt(), }, (t) => [index("connection_grants_project").on(t.projectId), index("connection_grants_connection").on(t.connectionId)], diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index 1df600b7..f98d97b4 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -406,7 +406,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer // PEP-234 Access Hub: the owner's external services, reached only through Peppa's gateway. tool( "list_connections", - "List the external services (Access Hub connections) you may use in this session: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? Tell the owner through ask_pm which service and what for — they grant it in «Подключения».", + "List the external services (Access Hub connections) you may use in this session: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works, until when the access lasts and when it is revoked if unused. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? Tell the owner through ask_pm which service and what for — they grant it in «Подключения».", {}, async () => { if (!sessionId) return "Connections work only in sessions started by FORGE."; @@ -422,6 +422,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer `- ${c.slug} (#${c.id} «${c.name}»${c.service ? `, ${c.service}` : ", own service"}) — ${c.baseUrl}`, ` read: ${modeText(c.readMode)}; write: ${modeText(c.writeMode)}${c.operations.length ? `; also allowed: ${c.operations.join(", ")}` : ""}`, ` key: ${keyText(c.checkStatus)}${c.docsUrl ? `; API docs: ${c.docsUrl}` : ""}`, + ` access: ${c.expiresAt ? `until ${c.expiresAt.toISOString()}` : "until the owner revokes it"}${c.idleRevokeAt ? `; revoked automatically if unused until ${c.idleRevokeAt.toISOString()} (each allowed call restarts this countdown)` : ""}`, ].join("\n"), ), ].join("\n"); @@ -440,7 +441,9 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer }, async ({ connection, method, path, body, content_type }) => { const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type }); - if (!r.ok) throw new PeppaError(`Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}`); + // PEP-259: a term that ran out / a grant revoked for no use — the owner extends it with one click. + const again = r.ok ? "" : r.reason === "expired" || r.reason === "idle_revoked" ? `. Access to «${String(connection)}» ended — ask the owner to extend it (one click in «Подключения»; tell them through ask_pm which service and what for), or continue without it.` : ""; + if (!r.ok) throw new PeppaError(`Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}${again}`); const s = await getSession(db, sessionId!); const data = await guardUntrusted(db, { projectId: s.projectId, taskId: s.taskId, sessionId, source: `подключение ${String(connection)}`, text: r.body }); return [`HTTP ${r.status}${r.contentType ? ` · ${r.contentType}` : ""}${r.truncated ? " · truncated at 256 KB" : ""}`, data].join("\n"); diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 0aaddba0..cf0313ca 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -39,7 +39,7 @@ import { limitDelay, limitOver } from "./limit-delay.ts"; import { checksQueueTick, platformDelayTick } from "./platform-delays.ts"; import { readyDigestTick } from "./ready-digest.ts"; import { stuckTaskTick } from "./stuck-tasks.ts"; -import { connectionCheckTick, connectionJournalTick } from "@peppa/core"; +import { connectionCheckTick, connectionJournalTick, grantExpiryTick } from "@peppa/core"; import { domainGuardTick } from "./domain-guard.ts"; import { orphanContainersTick } from "./orphan-containers.ts"; import { removeContainer } from "./sandbox.ts"; @@ -428,6 +428,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS await connectionCheckTick(db).catch(failed(db, log, "connection check failed")); // PEP-254: hourly — the connections journal chain is checked, a daily checkpoint goes outside the table. await connectionJournalTick(db, { log }).catch(failed(db, log, "connection journal failed")); + // PEP-259: grants nobody used for the connection's threshold (72 h) are revoked; one summary a day. + await grantExpiryTick(db).catch(failed(db, log, "connection grants expiry failed")); // PEP-209: one «Готово к приёмке» summary instead of many «готово» messages in Telegram. await acceptDigestTick(db, { log }).catch(failed(db, log, "accept digest failed")); await pruneAcceptFailures(db).catch(() => {}); diff --git a/packages/shared/src/i18n/en/access-hub.ts b/packages/shared/src/i18n/en/access-hub.ts index ed68b521..682f7095 100644 --- a/packages/shared/src/i18n/en/access-hub.ts +++ b/packages/shared/src/i18n/en/access-hub.ts @@ -163,4 +163,33 @@ export const accessHub: Record = { "Журнал подключений: контрольные точки": "Connections journal: checkpoints", "Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "The connections journal of user {login} was changed bypassing FORGE (entry {id}). Check access to the database.", "Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "The journal of your connections was changed bypassing FORGE. The administrator already knows and is looking into it; better replace the access keys in «Connections».", + // PEP-259: grant terms and revoking unused grants. + "срок истёк": "term is over", + "снято: {n} ч без дела": "revoked: {n} h unused", + "Продлить на {term}": "Extend for {term}", + "до {when}": "until {when}", + "до отзыва": "until revoked", + "действовало до {when}": "was valid until {when}", + "снято {ago}": "revoked {ago}", + "последний вызов {ago}": "last call {ago}", + "вызовов ещё не было": "no calls yet", + "снимется через {left} без дела": "revoked in {left} if unused", + "Срок": "Term", + "не снимать": "never revoke", + "{n} дн без дела": "{n} days unused", + "{n} ч без дела": "{n} h unused", + "Снимать разрешение, которым не пользуются:": "Revoke a permission nobody uses after:", + "Снимать разрешение без дела": "Revoke an unused permission", + "как обычно — {text}": "default — {text}", + "разрешение снято": "permission revoked", + "срок доступа истёк": "the access term is over", + "доступ снят: им долго не пользовались": "access revoked: unused for too long", + "1 час": "1 hour", + "1 день": "1 day", + "7 дней": "7 days", + "Недопустимый срок": "Invalid term", + "— «{name}» в {project}, агент {agent}: {hours} ч без дела": "— «{name}» in {project}, agent {agent}: {hours} h unused", + "— «{name}» в {project}: {hours} ч без дела": "— «{name}» in {project}: {hours} h unused", + "Сняты разрешения, которыми агенты долго не пользовались: {n}. Если доступ снова нужен — нажмите «Продлить» в разделе «Подключения».": "Permissions agents haven't used for a long time were revoked: {n}. If the access is needed again, press «Extend» in «Connections».", + "Вернуть": "Restore", }; diff --git a/packages/shared/src/i18n/kk/access-hub.ts b/packages/shared/src/i18n/kk/access-hub.ts index 147b3c06..67f5a281 100644 --- a/packages/shared/src/i18n/kk/access-hub.ts +++ b/packages/shared/src/i18n/kk/access-hub.ts @@ -163,4 +163,33 @@ export const accessHub: Record = { "Журнал подключений: контрольные точки": "Қосылымдар журналы: бақылау нүктелері", "Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "{login} пайдаланушысының қосылымдар журналы FORGE-ды айналып өтіп өзгертілді (жазба {id}). Дерекқорға қолжетімділікті тексеріңіз.", "Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "Қосылымдарыңыздың журналы FORGE-ды айналып өтіп өзгертілді. Әкімші біледі және анықтап жатыр; қолжетімділік кілттерін «Қосылымдар» бөлімінде ауыстырған жөн.", + // PEP-259: grant terms and revoking unused grants. + "срок истёк": "мерзімі өтті", + "снято: {n} ч без дела": "алынды: {n} сағ қолданылмады", + "Продлить на {term}": "{term} ұзарту", + "до {when}": "{when} дейін", + "до отзыва": "кері қайтарылғанға дейін", + "действовало до {when}": "{when} дейін жарамды болды", + "снято {ago}": "алынды {ago}", + "последний вызов {ago}": "соңғы шақыру {ago}", + "вызовов ещё не было": "шақырулар әлі болған жоқ", + "снимется через {left} без дела": "қолданылмаса, {left} кейін алынады", + "Срок": "Мерзімі", + "не снимать": "алмау", + "{n} дн без дела": "{n} күн қолданылмаса", + "{n} ч без дела": "{n} сағ қолданылмаса", + "Снимать разрешение, которым не пользуются:": "Қолданылмайтын рұқсатты алу:", + "Снимать разрешение без дела": "Қолданылмайтын рұқсатты алу", + "как обычно — {text}": "әдеттегідей — {text}", + "разрешение снято": "рұқсат алынды", + "срок доступа истёк": "қолжетімділік мерзімі өтті", + "доступ снят: им долго не пользовались": "қолжетімділік алынды: ұзақ уақыт қолданылмады", + "1 час": "1 сағат", + "1 день": "1 күн", + "7 дней": "7 күн", + "Недопустимый срок": "Жарамсыз мерзім", + "— «{name}» в {project}, агент {agent}: {hours} ч без дела": "— «{name}», {project}, агент {agent}: {hours} сағ қолданылмады", + "— «{name}» в {project}: {hours} ч без дела": "— «{name}», {project}: {hours} сағ қолданылмады", + "Сняты разрешения, которыми агенты долго не пользовались: {n}. Если доступ снова нужен — нажмите «Продлить» в разделе «Подключения».": "Агенттер ұзақ қолданбаған рұқсаттар алынды: {n}. Қолжетімділік қайта керек болса, «Қосылымдар» бөлімінде «Ұзарту» түймесін басыңыз.", + "Вернуть": "Қайтару", }; diff --git a/packages/testkit/test/access-hub-terms.test.ts b/packages/testkit/test/access-hub-terms.test.ts new file mode 100644 index 00000000..099d92ba --- /dev/null +++ b/packages/testkit/test/access-hub-terms.test.ts @@ -0,0 +1,204 @@ +// PEP-259 Access Hub: a grant lives for a term (1 h · 1 day · 7 days · until revoked) and is +// revoked by the watchdog after the connection's threshold (72 h) without calls. Scenario names +// follow openspec/changes/archive/2026-11-24-pep-259-grant-terms/specs/access-hub/spec.md. +import assert from "node:assert/strict"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { after, before, describe, test } from "node:test"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { and, eq } from "drizzle-orm"; +import { core, db, project, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET ??= "mock-access-hub-secret"; +process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1 +const { createAgentServer } = await import("@peppa/mcp/agent"); +const { connectionGrants, connectionLog, agents, sessions, events } = await import("@peppa/db"); + +const H = 3600_000; +let mock: Server; +let base: string; +let anna: Awaited>; +let boris: Awaited>; + +before(async () => { + mock = createServer((req, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, path: req.url })); + }); + await new Promise((r) => mock.listen(0, "127.0.0.1", r)); + base = `http://127.0.0.1:${(mock.address() as AddressInfo).port}/api`; + anna = await core.upsertUserFromGitea(db, { id: 2591, login: "mock-anna-259" }, { access_token: "a" }); + boris = await core.upsertUserFromGitea(db, { id: 2592, login: "mock-boris-259" }, { access_token: "b" }); +}); +after(async () => { + await new Promise((r) => mock.close(() => r())); + await teardown(); +}); + +let seq = 0; +/** Anna's project, an isolated agent session in it and a fresh connection «CRM» granted read on `term`. */ +async function setup(o: { term?: "1h" | "1d" | "7d" | "forever"; at: Date; idleHours?: number | null }) { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, anna.id); + const task = (await core.listTasks(db, { projectId: proj.id }))[0]!; + const s = await core.createSession(db, { projectId: proj.id, taskId: task.id }); + const [a] = await db.insert(agents).values({ name: `Мок-агент 259-${++seq}-${Date.now()}` }).returning(); + await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id)); + const c = await core.createConnection(db, anna.id, { name: `CRM ${seq}`, baseUrl: base, secret: `sk_mock_259_${seq}_abcdef` }); + if (o.idleHours !== undefined) await core.setConnectionIdleHours(db, anna.id, c.id, o.idleHours); + const g = await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "read", term: o.term, now: o.at }); + return { proj, sessionId: s.id, c, g }; +} +const call = (sessionId: number, c: { id: number }, now: Date) => core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { now }); +const grantRow = async (id: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.id, id)))[0]; +const silent = async () => {}; + +describe("Срок разрешения", () => { + test("Вызов по живому разрешению на 1 день", async () => { + const t0 = new Date(Date.now() - 2 * H); + const { sessionId, c, g } = await setup({ term: "1d", at: t0 }); + assert.equal(g.term, "1d"); + assert.equal(g.expiresAt!.getTime(), t0.getTime() + 24 * H); + const r = await call(sessionId, c, new Date()); + assert.ok(r.ok, JSON.stringify(r)); + const [view] = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.grants; + assert.ok(view!.lastUsedAt, "the grant shows its last call"); + assert.equal(view!.state, "active"); + assert.ok(view!.idleRevokeAt && view!.idleRevokeAt.getTime() > Date.now() + 70 * H, "72 h from the last call"); + }); + + test("Вызов после истечения срока", async () => { + const t0 = new Date(Date.now() - 25 * H); + const { sessionId, c } = await setup({ term: "1d", at: t0 }); + const r = await call(sessionId, c, new Date()); + assert.deepEqual(r, { ok: false, reason: "expired" }); + const [row] = await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "call"))); + assert.equal(row!.decision, "denied"); + assert.equal(row!.reason, "expired"); + const view = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.grants[0]!; + assert.equal(view.state, "expired"); + assert.equal(view.idleRevokeAt, null); + }); + + test("Агенту — понятная причина через MCP", async () => { + const { proj, sessionId, c } = await setup({ term: "1h", at: new Date(Date.now() - 2 * H) }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await createAgentServer(db, { defaultKey: proj.key, sessionId, lockProject: true }).connect(a); + const client = new Client({ name: "mock-agent", version: "0" }); + await client.connect(b); + const r = await client.callTool({ name: "call_connection", arguments: { connection: c.id, method: "GET", path: "/items" } }); + const text = (r.content as Array<{ text: string }>)[0]!.text; + assert.ok(r.isError); + assert.match(text, /\(expired\)/); + assert.match(text, /extend/); + const list = await client.callTool({ name: "list_connections", arguments: {} }); + assert.match((list.content as Array<{ text: string }>)[0]!.text, /No connections/, "an expired grant is not offered"); + }); + + test("Продление истёкшего разрешения", async () => { + const { sessionId, c, g } = await setup({ term: "1d", at: new Date(Date.now() - 30 * H) }); + assert.equal((await call(sessionId, c, new Date())).ok, false); + const now = new Date(); + const ext = await core.extendGrant(db, anna.id, g.id, { now }); + assert.equal(ext.state, "active"); + assert.equal(ext.expiresAt!.getTime(), now.getTime() + 24 * H); + assert.ok((await call(sessionId, c, new Date())).ok); + const ev = await db.select().from(events).where(eq(events.type, "connection_grant_extended")); + assert.ok(ev.length >= 1); + }); + + test("Чужой пользователь не продлевает", async () => { + const { g } = await setup({ term: "1h", at: new Date(Date.now() - 2 * H) }); + await assert.rejects(core.extendGrant(db, boris.id, g.id), /Подключение не найдено/); + await assert.rejects(core.setConnectionIdleHours(db, boris.id, (await grantRow(g.id))!.connectionId, 0), core.PeppaError); + assert.equal((await grantRow(g.id))!.expiresAt!.getTime() < Date.now(), true, "unchanged"); + }); + + test("Без срока — до отзыва (как раньше)", async () => { + const { g } = await setup({ at: new Date() }); + assert.equal(g.term, "forever"); + assert.equal(g.expiresAt, null); + }); +}); + +describe("Автоснятие разрешения без дела", () => { + test("Разрешение без вызовов 72 часа", async () => { + const now = new Date(); + const { sessionId, c, g, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) }); + const sent: Array<{ ownerId: number; n: number }> = []; + const n = await core.grantExpiryTick(db, { now, notify: async (_db, ownerId, items) => void sent.push({ ownerId, n: items.length }) }); + assert.ok(n >= 1); + const row = await grantRow(g.id); + assert.equal(row!.endReason, "idle"); + const view = (await core.listConnections(db, anna.id, { now })).find((x) => x.id === c.id)!.grants[0]!; + assert.equal(view.state, "idle"); + assert.equal(view.idleHours, 72); + const journal = await core.connectionJournal(db, anna.id, { connectionId: c.id }); + assert.ok(journal.some((j) => j.method === "REVOKE" && j.reason === "idle_revoked" && j.projectKey === proj.key)); + assert.equal((await core.verifyConnectionJournal(db, anna.id)).ok, true, "the revoke row is in the hash chain"); + assert.deepEqual(await call(sessionId, c, new Date()), { ok: false, reason: "idle_revoked" }); + assert.ok(sent.some((x) => x.ownerId === anna.id)); + // Within a day — no second summary even if more are revoked. + await setup({ term: "forever", at: new Date(now.getTime() - 80 * H) }); + const again: number[] = []; + await core.grantExpiryTick(db, { now: new Date(now.getTime() + H), notify: async () => void again.push(1) }); + assert.equal(again.length, 0); + await core.grantExpiryTick(db, { now: new Date(now.getTime() + 25 * H), notify: async () => void again.push(1) }); + assert.equal(again.length, 1, "the next day — one summary"); + // Extending brings it back. + await core.extendGrant(db, anna.id, g.id); + assert.ok((await call(sessionId, c, new Date())).ok); + }); + + test("Недавний вызов продлевает жизнь", async () => { + const now = new Date(); + const { sessionId, c, g } = await setup({ term: "forever", at: new Date(now.getTime() - 100 * H) }); + assert.ok((await call(sessionId, c, new Date(now.getTime() - 10 * H))).ok); + await core.grantExpiryTick(db, { now, notify: silent }); + assert.equal((await grantRow(g.id))!.endedAt, null); + }); + + test("Порог 0 — не снимать", async () => { + const now = new Date(); + const { g } = await setup({ term: "forever", at: new Date(now.getTime() - 500 * H), idleHours: 0 }); + await core.grantExpiryTick(db, { now, notify: silent }); + assert.equal((await grantRow(g.id))!.endedAt, null); + const view = (await core.listConnections(db, anna.id, { now })).flatMap((x) => x.grants).find((x) => x.id === g.id)!; + assert.equal(view.idleRevokeAt, null); + }); + + test("Проект на паузе", async () => { + const now = new Date(); + const { g, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 100 * H) }); + await core.setSetting(db, `project.paused:${proj.id}`, { since: now.toISOString(), by: anna.id, sessions: [] }); + await core.grantExpiryTick(db, { now, notify: silent }); + assert.equal((await grantRow(g.id))!.endedAt, null); + }); + + test("Снятые давно разрешения убираются", async () => { + const now = new Date(); + const { g } = await setup({ term: "1h", at: new Date(now.getTime() - 40 * 24 * H) }); + await core.grantExpiryTick(db, { now, notify: silent }); + assert.equal(await grantRow(g.id), undefined); + }); +}); + +describe("Агент видит срок разрешения", () => { + test("Список подключений агента", async () => { + const { proj, sessionId } = await setup({ term: "7d", at: new Date() }); + const list = await core.agentConnections(db, sessionId); + assert.equal(list.length, 1); + assert.ok(list[0]!.expiresAt && list[0]!.expiresAt.getTime() > Date.now() + 6 * 24 * H); + assert.ok(list[0]!.idleRevokeAt); + const [a, b] = InMemoryTransport.createLinkedPair(); + await createAgentServer(db, { defaultKey: proj.key, sessionId, lockProject: true }).connect(a); + const client = new Client({ name: "mock-agent", version: "0" }); + await client.connect(b); + const r = await client.callTool({ name: "list_connections", arguments: {} }); + const text = (r.content as Array<{ text: string }>)[0]!.text; + assert.match(text, /access: until \d{4}-/); + assert.match(text, /revoked automatically if unused until/); + }); +});