From cae49d5b54edfa22105c5e91e1181f1657f95ea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Fri, 13 Nov 2026 14:30:49 +0500 Subject: [PATCH 001/536] =?UTF-8?q?PEP-57:=20CI=20feedback=20=E2=80=94=20c?= =?UTF-8?q?heck=20runs,=20red=20checks=20back=20to=20the=20agent,=20review?= =?UTF-8?q?/merge=20gates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 + apps/web/app/(app)/t/[key]/page.tsx | 19 + apps/web/app/api/hooks/gitea/route.ts | 18 + openspec/changes/pep-57-ci-cd/design.md | 8 + openspec/changes/pep-57-ci-cd/tasks.md | 10 +- packages/core/src/ci.ts | 190 ++ packages/core/src/index.ts | 1 + packages/core/src/tasks.ts | 5 +- .../0012_faithful_matthew_murdock.sql | 22 + .../db/migrations/meta/0012_snapshot.json | 2061 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 26 + packages/mcp/src/format.ts | 2 + packages/mcp/src/index.ts | 8 + packages/mcp/src/manager.ts | 2 +- packages/runner/src/ci-feedback.ts | 214 ++ packages/runner/src/ci.ts | 10 +- packages/runner/src/flow.ts | 25 +- packages/runner/src/index.ts | 1 + packages/runner/src/watchdog.ts | 8 + packages/testkit/test/ci-feedback.test.ts | 251 ++ packages/testkit/test/ci.test.ts | 2 + 22 files changed, 2880 insertions(+), 12 deletions(-) create mode 100644 apps/web/app/api/hooks/gitea/route.ts create mode 100644 packages/core/src/ci.ts create mode 100644 packages/db/migrations/0012_faithful_matthew_murdock.sql create mode 100644 packages/db/migrations/meta/0012_snapshot.json create mode 100644 packages/runner/src/ci-feedback.ts create mode 100644 packages/testkit/test/ci-feedback.test.ts diff --git a/AGENTS.md b/AGENTS.md index b8cbc6b6..b0a35ab1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,8 @@ - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) + - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) + - Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены») - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index ef33e308..c46919d0 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -6,6 +6,7 @@ import { requireUser } from "@/lib/auth"; import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries"; import { db } from "@/lib/db"; import { goals } from "@peppa/db"; +import { taskCiSummary } from "@peppa/core"; import { eq } from "drizzle-orm"; import { startTaskSession } from "../../actions"; @@ -19,6 +20,7 @@ export default async function TaskPage({ params, searchParams }: { params: Promi const [goal] = task.goalId ? await db.select().from(goals).where(eq(goals.id, task.goalId)) : []; const { questions, sessions, events } = await taskActivity(task.id); const artifacts = openspecArtifacts(project, task.openspecChange); + const ci = await taskCiSummary(db, ref); const back = `/t/${ref.key}`; return ( <> @@ -32,6 +34,23 @@ export default async function TaskPage({ params, searchParams }: { params: Promi {ref.key} {task.title} {task.prUrl &&

PR

} +
+

Проверки

+

+ {ci.state === "success" ? "✅ " : ci.state === "failure" ? "❌ " : ci.state === "pending" ? "⏳ " : ""} + {ci.runUrl ? {ci.label} : ci.label} + {ci.sha && · {ci.sha.slice(0, 7)}} + {task.ciAttempts > 0 && · красных подряд: {task.ciAttempts}} +

+ {ci.failed.map((f) => ( +
+ + ❌ {f.check} {f.runUrl && лог} + + {f.logTail &&
{f.logTail.split("\n").slice(-60).join("\n")}
} +
+ ))} +

{task.description || Без описания}

diff --git a/apps/web/app/api/hooks/gitea/route.ts b/apps/web/app/api/hooks/gitea/route.ts new file mode 100644 index 00000000..ffb6c599 --- /dev/null +++ b/apps/web/app/api/hooks/gitea/route.ts @@ -0,0 +1,18 @@ +import { handleGiteaHook } from "@peppa/runner"; +import { db } from "@/lib/db"; + +export const dynamic = "force-dynamic"; + +/** + * Gitea webhooks and CI step reports of project repos (PEP-57). No login: each request is + * signed (X-Gitea-Signature, HMAC-SHA256 of the body) with the project's secret. + */ +export async function POST(req: Request) { + const body = await req.text(); + const r = await handleGiteaHook(db, { + event: req.headers.get("x-peppa-event") ?? req.headers.get("x-gitea-event") ?? "", + signature: req.headers.get("x-gitea-signature"), + body, + }); + return Response.json(r.body, { status: r.status }); +} diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md index e7334f63..49185f5f 100644 --- a/openspec/changes/pep-57-ci-cd/design.md +++ b/openspec/changes/pep-57-ci-cd/design.md @@ -66,3 +66,11 @@ Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не н хранится). Тот же секрет — у вебхука Gitea проекта. - **Статусы**: `install` сообщает только о провале; «N из N» считается по статусам `peppa/*` головного SHA. +- **Вебхуки Gitea**: `pull_request` и `push` (события `status` в 1.22 нет); статусы проверок + приходят отчётом шага CI, запасной путь — опрос статусов вачдогом раз в минуту. +- **Попытка** = красный прогон нового головного SHA; несколько красных проверок одного коммита — + одна попытка. Зелёный прогон обнуляет счётчик. +- **Гейт ревью открыт при недоступной Gitea** (иначе агент застрянет); мерж по «Принять» в этом + случае всё равно не пройдёт. Задача без PR и проект без `checks` гейт не проходят — он выключен. +- **Автомерж** (`autoMergeTask`) готов, но не подключён к триггеру — режим авто-мержа проекта + появится в PEP-23/25. diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md index 768d3037..5cc94c2f 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -10,14 +10,14 @@ - [x] 1.1 `infra/`: act_runner в docker (метка `peppa-trusted`), включить Actions в Gitea; проверка: тестовый workflow в `peppa-bot/sandbox` зелёный - [x] 1.2 Шаблон: `.gitea/workflows/ci.yml` (читает `checks` из `.peppa/project.json`), поля `checks`/`deploy` в project.json, раздел в RULES.md «перед PR запусти checks локально»; залить шаблон -- [ ] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX +- [x] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX ## 2. Обратная связь и гейты -- [ ] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки -- [ ] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью» -- [ ] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок -- [ ] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт» +- [x] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки +- [x] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью» +- [x] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок +- [x] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт» ## 3. CD diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts new file mode 100644 index 00000000..32a123c9 --- /dev/null +++ b/packages/core/src/ci.ts @@ -0,0 +1,190 @@ +// CI results of factory projects (PEP-57): check runs per commit, the summary shown on the +// task card and the gate for review and merge (green checks of the PR head, no conflicts). +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { checkRuns, tasks, type Db } from "@peppa/db"; +import { CHECK_NAMES, formatTaskKey, loadEnv, type CheckName, type PeppaProjectFile } from "@peppa/shared"; +import { and, desc, eq } from "drizzle-orm"; +import type { GiteaClient, GiteaPull } from "./gitea.ts"; +import { giteaForBot } from "./users.ts"; +import type { Project } from "./projects.ts"; +import type { TaskRef } from "./tasks.ts"; + +export type CheckRun = typeof checkRuns.$inferSelect; +export type CheckState = CheckRun["state"]; + +export interface CheckReport { + sha: string; + branch?: string | null; + prNumber?: number | null; + check: string; + state: CheckState; + runUrl?: string | null; + logTail?: string | null; + durationSec?: number | null; + source?: CheckRun["source"]; +} + +/** Commands configured in a project file (JSON text); missing/empty ones are skipped by CI. */ +export function configuredChecks(projectJson: string | null | undefined): CheckName[] { + if (!projectJson) return []; + try { + const checks = (JSON.parse(projectJson) as PeppaProjectFile).checks ?? {}; + return CHECK_NAMES.filter((c) => typeof checks[c] === "string" && checks[c]!.trim() !== ""); + } catch { + return []; + } +} + +/** Full link to a run: CI reports relative `/owner/repo/actions/runs/N`. */ +export function runLink(url: string | null | undefined): string | null { + if (!url) return null; + return url.startsWith("/") ? `${loadEnv().GITEA_URL}${url}` : url; +} + +export interface CiSummary { + state: "not_configured" | "none" | "pending" | "success" | "failure"; + passed: number; + total: number; + sha: string | null; + runUrl: string | null; + failed: Array<{ check: string; runUrl: string | null; logTail?: string | null }>; + /** One line for the task card, e.g. "Проверки: 4 из 4 пройдены". */ + label: string; +} + +type RunLike = { check: string; state: CheckState; runUrl?: string | null; logTail?: string | null }; + +export function summarizeChecks(configured: string[], runs: RunLike[], sha: string | null): CiSummary { + const total = configured.length; + const base = { sha, total, runUrl: runLink(runs.find((r) => r.runUrl)?.runUrl) }; + if (!total) return { ...base, state: "not_configured", passed: 0, failed: [], label: "проверки не настроены" }; + // `install` is not a check of its own, but when it fails nothing else ran. + const failed = runs.filter((r) => r.state === "failure" || r.state === "error").map((r) => ({ check: r.check, runUrl: runLink(r.runUrl), logTail: r.logTail })); + const passed = configured.filter((c) => runs.some((r) => r.check === c && r.state === "success")).length; + if (failed.length) return { ...base, state: "failure", passed, failed, label: `Проверки: ${passed} из ${total} пройдены, упало: ${failed.map((f) => f.check).join(", ")}` }; + if (passed === total) return { ...base, state: "success", passed, failed, label: `Проверки: ${passed} из ${total} пройдены` }; + if (!runs.length) return { ...base, state: "none", passed, failed, label: "Проверки ещё не запускались" }; + return { ...base, state: "pending", passed, failed, label: `Проверки идут: ${passed} из ${total}` }; +} + +/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */ +export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> { + const [prev] = await db + .select() + .from(checkRuns) + .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), eq(checkRuns.check, r.check))); + const values = { + taskId: taskId ?? prev?.taskId ?? null, + branch: r.branch ?? prev?.branch ?? null, + prNumber: r.prNumber ?? prev?.prNumber ?? null, + state: r.state, + runUrl: r.runUrl ?? prev?.runUrl ?? null, + // A poll carries no log: keep the one the CI step sent. + logTail: r.logTail ?? prev?.logTail ?? null, + durationSec: r.durationSec ?? prev?.durationSec ?? null, + source: r.source ?? "report", + }; + const [run] = prev + ? await db.update(checkRuns).set(values).where(eq(checkRuns.id, prev.id)).returning() + : await db.insert(checkRuns).values({ projectId: project.id, sha: r.sha, check: r.check, ...values }).returning(); + return { run: run!, changed: prev?.state !== r.state }; +} + +/** PR number of a task's pr_url when it points at the project's repo. */ +export function taskPrNumber(project: Project, prUrl: string | null | undefined): number | null { + const m = prUrl?.match(/\/([^/]+)\/([^/]+)\/pulls\/(\d+)/); + if (!m || m[1]!.toLowerCase() !== project.giteaOwner.toLowerCase() || m[2]!.toLowerCase() !== project.giteaRepo.toLowerCase()) return null; + return Number(m[3]); +} + +/** Task of a CI result: its branch `task/-…`, or the task whose PR it is. */ +export async function taskForCheck(db: Db, project: Project, branch: string | null | undefined, prNumber: number | null | undefined): Promise { + const m = branch?.match(new RegExp(`^task/${project.key}-(\\d+)`, "i")); + if (m) { + const [task] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.number, Number(m[1])))); + if (task) return { project, task, key: formatTaskKey(project.key, task.number) }; + } + if (prNumber) { + for (const task of await db.select().from(tasks).where(eq(tasks.projectId, project.id))) { + if (taskPrNumber(project, task.prUrl) === prNumber) return { project, task, key: formatTaskKey(project.key, task.number) }; + } + } + return null; +} + +function workspaceProjectJson(project: Project): string | null { + const f = join(project.workspacePath, ".peppa/project.json"); + return existsSync(f) ? readFileSync(f, "utf8") : null; +} + +/** For the task card and MCP (no Gitea calls): checks of the task's latest commit. */ +export async function taskCiSummary(db: Db, ref: TaskRef): Promise { + const runs = await db.select().from(checkRuns).where(eq(checkRuns.taskId, ref.task.id)).orderBy(desc(checkRuns.updatedAt)); + const sha = runs[0]?.sha ?? null; + return summarizeChecks(configuredChecks(workspaceProjectJson(ref.project)), runs.filter((r) => r.sha === sha), sha); +} + +export interface GateResult { + ok: boolean; + /** Why not, for the PM: "проверки не пройдены", conflicts… */ + reason?: string; + summary: CiSummary | null; + pull: GiteaPull | null; +} + +/** + * Gate for review and merge: the task's PR head has green checks and no conflicts. A task + * without a PR or a project without checks passes (the card says "проверки не настроены"). + */ +export async function prGate(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise { + const n = taskPrNumber(ref.project, ref.task.prUrl); + if (!n) return { ok: true, summary: null, pull: null }; + const { giteaOwner: o, giteaRepo: r } = ref.project; + const pull = await gitea.getPullRequest(o, r, n); + if (pull.merged) return { ok: true, summary: null, pull }; + const [projectJson, status] = await Promise.all([gitea.fileText(o, r, ".peppa/project.json", pull.head.sha), gitea.combinedStatus(o, r, pull.head.sha)]); + const runs = (status.statuses ?? []) + .filter((s) => s.context.startsWith("peppa/")) + .map((s) => ({ check: s.context.slice(6), state: (s.status === "error" || s.status === "failure" ? "failure" : s.status === "success" ? "success" : "pending") as CheckState, runUrl: s.target_url })); + const summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha); + if (summary.state === "failure") return { ok: false, reason: `проверки не пройдены (${summary.failed.map((f) => f.check).join(", ")})`, summary, pull }; + if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: `проверки ещё идут (${summary.passed} из ${summary.total})`, summary, pull }; + if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: "есть конфликты с основной веткой", summary, pull }; + return { ok: true, summary, pull }; +} + +/** Files that define the pipeline: changing them needs the PM's review even in auto mode. */ +export function isPipelineFile(path: string): boolean { + return path.startsWith(".gitea/") || path === ".peppa/project.json"; +} + +/** + * Pipeline changes in a PR: workflow files, or `checks`/`deploy` in .peppa/project.json + * (other fields of the project file are not the pipeline). Empty = none. + */ +export async function pipelineChanges(ref: TaskRef, pull: GiteaPull, gitea: GiteaClient = giteaForBot()): Promise { + const { giteaOwner: o, giteaRepo: r } = ref.project; + const out: string[] = []; + for (const f of (await gitea.pullFiles(o, r, pull.number)).filter(isPipelineFile)) { + if (f !== ".peppa/project.json") { + out.push(f); + continue; + } + const [before, after] = await Promise.all([gitea.fileText(o, r, f, pull.base.ref), gitea.fileText(o, r, f, pull.head.sha)]); + const pick = (t: string | null) => { + try { + const j = JSON.parse(t ?? "{}") as PeppaProjectFile; + return { checks: j.checks ?? {}, deploy: j.deploy ?? {} }; + } catch { + return null; + } + }; + const a = pick(before); + const b = pick(after); + for (const k of ["checks", "deploy"] as const) { + if (JSON.stringify(a?.[k]) !== JSON.stringify(b?.[k])) out.push(`${f} → ${k}: ${JSON.stringify(a?.[k] ?? null)} → ${JSON.stringify(b?.[k] ?? null)}`); + } + } + return out; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d01c9289..c224e041 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,3 +15,4 @@ export * from "./access.ts"; export * from "./monitor.ts"; export * from "./repo-info.ts"; export * from "./incidents.ts"; +export * from "./ci.ts"; diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 10610281..15d397f5 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -5,6 +5,7 @@ import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { getGoal, getProject, type Goal, type Project } from "./projects.ts"; import { incidentForTask, type Incident } from "./incidents.ts"; +import { taskCiSummary, type CiSummary } from "./ci.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -119,6 +120,8 @@ export interface TaskDetails { recentEvents: Array; /** The production error this task fixes (PEP-58), if any. */ incident: Incident | null; + /** CI checks of the task's latest commit (PEP-57). */ + ci: CiSummary; } export async function getTaskDetails(db: Db, ref: TaskRef): Promise { @@ -131,7 +134,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise .orderBy(desc(events.id)) .limit(20); const incident = await incidentForTask(db, ref.task.id); - return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident }; + return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref) }; } export interface NewQuestion { diff --git a/packages/db/migrations/0012_faithful_matthew_murdock.sql b/packages/db/migrations/0012_faithful_matthew_murdock.sql new file mode 100644 index 00000000..8e8e5e30 --- /dev/null +++ b/packages/db/migrations/0012_faithful_matthew_murdock.sql @@ -0,0 +1,22 @@ +CREATE TABLE "check_runs" ( + "id" serial PRIMARY KEY NOT NULL, + "project_id" integer NOT NULL, + "task_id" integer, + "sha" text NOT NULL, + "branch" text, + "pr_number" integer, + "check" text NOT NULL, + "state" text NOT NULL, + "run_url" text, + "log_tail" text, + "duration_sec" integer, + "source" text DEFAULT 'report' NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "tasks" ADD COLUMN "ci_attempts" integer DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE "tasks" ADD COLUMN "ci_failed_sha" text;--> statement-breakpoint +ALTER TABLE "check_runs" ADD CONSTRAINT "check_runs_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "check_runs" ADD CONSTRAINT "check_runs_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "check_runs_project_sha_check" ON "check_runs" USING btree ("project_id","sha","check"); \ No newline at end of file diff --git a/packages/db/migrations/meta/0012_snapshot.json b/packages/db/migrations/meta/0012_snapshot.json new file mode 100644 index 00000000..c30f3501 --- /dev/null +++ b/packages/db/migrations/meta/0012_snapshot.json @@ -0,0 +1,2061 @@ +{ + "id": "ca89d235-ea51-4284-95fe-50b24621c88a", + "prevId": "47a9fc06-6fdb-42ad-8a5f-d80e76193258", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.check_runs": { + "name": "check_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "check", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.error_sources": { + "name": "error_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "nullsNotDistinct": false, + "columns": [ + "bugsink_project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.incident_settings": { + "name": "incident_settings", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environments": { + "name": "environments", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[\"prod\",\"production\"]'::jsonb" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "nullsNotDistinct": false, + "columns": [ + "hook_secret" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.incidents": { + "name": "incidents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_seen": { + "name": "last_seen", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "nullsNotDistinct": false, + "columns": [ + "bugsink_issue_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_invites": { + "name": "project_invites", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": { + "name": "project_invites_project_id_login_pk", + "columns": [ + "project_id", + "login" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_members": { + "name": "project_members", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": { + "name": "project_members_project_id_user_id_pk", + "columns": [ + "project_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "nullsNotDistinct": false, + "columns": [ + "telegram_chat_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 309369cd..7c258cac 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -85,6 +85,13 @@ "when": 1794561166402, "tag": "0011_pep58_incidents", "breakpoints": true + }, + { + "idx": 12, + "version": "7", + "when": 1794562626634, + "tag": "0012_faithful_matthew_murdock", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index d05ef5cb..a055a2bd 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -109,12 +109,38 @@ export const tasks = pgTable( // OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth" openspecChange: text("openspec_change"), prUrl: text("pr_url"), + // PEP-57: red CI runs in a row (distinct head SHAs) since the last green one. + ciAttempts: integer("ci_attempts").notNull().default(0), + ciFailedSha: text("ci_failed_sha"), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], ); +/** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */ +export const checkRuns = pgTable( + "check_runs", + { + id: serial("id").primaryKey(), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), + sha: text("sha").notNull(), + branch: text("branch"), + prNumber: integer("pr_number"), + check: text("check").notNull(), + state: text("state", { enum: ["pending", "success", "failure", "error"] }).notNull(), + runUrl: text("run_url"), + logTail: text("log_tail"), + durationSec: integer("duration_sec"), + // "report" — the CI step itself (with the log), "poll" — commit status read by the watchdog. + source: text("source", { enum: ["report", "poll"] }).notNull().default("report"), + createdAt: createdAt(), + updatedAt: updatedAt(), + }, + (t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)], +); + export const sessionStatus = pgEnum("session_status", [ "starting", "running", diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts index fcb28d51..a076ca01 100644 --- a/packages/mcp/src/format.ts +++ b/packages/mcp/src/format.ts @@ -21,6 +21,8 @@ export function formatTask(d: TaskDetails): string { `- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`, ]; if (task.prUrl) lines.push(`- PR: ${task.prUrl}`); + lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`); + for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`); lines.push("", "## Описание", "", task.description?.trim() || "_нет описания_"); if (goal?.description) lines.push("", `## Цель #${goal.id}: ${goal.title}`, "", goal.description.trim()); if (d.incident) lines.push("", "## Инцидент", "", formatIncident(d.incident)); diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index fa0c9088..e44a540d 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -21,6 +21,7 @@ import { updateTask, } from "@peppa/core"; import { createDb } from "@peppa/db"; +import { reviewGate } from "@peppa/runner"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; @@ -128,6 +129,13 @@ tool( if (status === "in_progress" && ref.task.status === "awaiting_approval") { throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress."); } + if (status === "review" && ref.task.status !== "review") { + // PEP-57: review only with green checks of the PR head (the PR given now counts). + const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } }); + if (reason) { + throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`); + } + } const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId); return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`; }, diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 5f05522b..0f9d0fb3 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -272,7 +272,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool( "answer_question", - "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' closes the task, any other text goes back to the agent.", + "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the task's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the task, any other text goes back to the agent.", { question_id: z.number().int(), answer: z.string().min(1) }, false, async ({ question_id, answer }) => { diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts new file mode 100644 index 00000000..57311b9c --- /dev/null +++ b/packages/runner/src/ci-feedback.ts @@ -0,0 +1,214 @@ +// CI feedback (PEP-57): results come from the CI step itself (signed report with the log), +// from Gitea webhooks, and from the watchdog polling commit statuses as a fallback. A red +// check goes back to the agent with the step and the log tail; 3 red runs in a row → the PM. +import { + askPm, + giteaForBot, + listSessions, + listTasks, + PeppaError, + prGate, + pipelineChanges, + runLink, + taskForCheck, + taskPrNumber, + upsertCheckRun, + verifyHookSignature, + type CheckReport, + type GiteaClient, + type Project, + type TaskRef, +} from "@peppa/core"; +import { checkRuns, projects, tasks, type Db } from "@peppa/db"; +import { and, eq, sql } from "drizzle-orm"; +import { sendToSession } from "./sessions.ts"; +import { moveTask } from "./flow.ts"; + +/** Red runs in a row after which the PM is asked instead of the agent. */ +export const MAX_CI_ATTEMPTS = 3; +const LOG_LINES = 100; + +const tail = (log: string | null | undefined, n = LOG_LINES) => (log ?? "").trimEnd().split("\n").slice(-n).join("\n"); + +async function activeSessionId(db: Db, taskId: number): Promise { + return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null; +} + +export interface CheckOutcome { + task: string | null; + /** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */ + action: "none" | "agent" | "restarted" | "pm" | "green"; +} + +/** Records one CI result and reacts to it for the task of that branch/PR. */ +export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise { + const ref = await taskForCheck(db, project, r.branch, r.prNumber); + const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r); + if (!ref || !changed) return { task: ref?.key ?? null, action: "none" }; + if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" }; + + if (r.state === "success") { + const [red] = await db + .select({ id: checkRuns.id }) + .from(checkRuns) + .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), sql`${checkRuns.state} in ('failure','error')`)); + if (red || ref.task.ciAttempts === 0) return { task: ref.key, action: "none" }; + await db.update(tasks).set({ ciAttempts: 0, ciFailedSha: null }).where(eq(tasks.id, ref.task.id)); + return { task: ref.key, action: "green" }; + } + if (r.state !== "failure" && r.state !== "error") return { task: ref.key, action: "none" }; + + // Several red checks of one commit are one attempt. + const newRun = ref.task.ciFailedSha !== r.sha; + const attempts = newRun ? ref.task.ciAttempts + 1 : ref.task.ciAttempts; + if (newRun) await db.update(tasks).set({ ciAttempts: attempts, ciFailedSha: r.sha }).where(eq(tasks.id, ref.task.id)); + const link = runLink(r.runUrl); + const sessionId = await activeSessionId(db, ref.task.id); + + if (attempts >= MAX_CI_ATTEMPTS) { + if (!newRun) return { task: ref.key, action: "none" }; // the PM already has this commit + await askPm(db, ref, { + kind: "question", + sessionId: sessionId ?? undefined, + text: `❌ ${ref.key}: проверки PR красные ${attempts} раза подряд — агент не справился сам. Упала «${r.check}» (коммит ${r.sha.slice(0, 7)}).${link ? `\nЛог: ${link}` : ""}\n\nЧто делать? Ответ уйдёт агенту.`, + }); + if (sessionId) { + await sendToSession(db, sessionId, `Проверки PR ${ref.key} красные ${attempts} раза подряд — я спросил PM. Не пушь новых попыток, закончи ход и жди ответа PM.`).catch(() => {}); + } + return { task: ref.key, action: "pm" }; + } + + const text = [ + `❌ CI по ${ref.key}: упала проверка «${r.check}» (коммит ${r.sha.slice(0, 7)}, попытка ${attempts} из ${MAX_CI_ATTEMPTS}).${link ? ` Лог: ${link}` : ""}`, + r.logTail ? `Последние строки лога:\n${tail(r.logTail)}` : "Лога в отчёте нет — открой ссылку.", + `Почини (локально: bash .gitea/peppa-check.sh ${r.check}) и запушь в ту же ветку; не ослабляй проверки.`, + ].join("\n\n"); + if (sessionId) { + await sendToSession(db, sessionId, text); + // The work is not done: a task that already went to review goes back. + if (ref.task.status === "review") await moveTask(db, ref, "in_progress"); + return { task: ref.key, action: "agent" }; + } + await moveTask(db, ref, "in_progress", { prompt: text }); + return { task: ref.key, action: "restarted" }; +} + +/** Project of a repository "owner/name" (case-insensitive). */ +export async function projectByRepo(db: Db, fullName: string): Promise { + const [owner, name] = fullName.split("/"); + if (!owner || !name) return null; + const [p] = await db + .select() + .from(projects) + .where(and(sql`lower(${projects.giteaOwner}) = ${owner.toLowerCase()}`, sql`lower(${projects.giteaRepo}) = ${name.toLowerCase()}`)); + return p ?? null; +} + +export interface HookRequest { + /** X-Gitea-Event (Gitea webhooks) or X-Peppa-Event (the CI step). */ + event: string; + signature: string | null; + body: string; +} + +/** Handlers for Gitea events other than CI checks (deploys hook in here). */ +export type GiteaEventHandler = (db: Db, project: Project, event: string, payload: Record) => Promise; +const eventHandlers: GiteaEventHandler[] = []; +export function onGiteaEvent(h: GiteaEventHandler) { + eventHandlers.push(h); +} + +/** POST /api/hooks/gitea: verifies the project's signature, then records/dispatches. */ +export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ status: number; body: Record }> { + let payload: Record; + try { + payload = JSON.parse(req.body) as Record; + } catch { + return { status: 400, body: { error: "invalid json" } }; + } + const repo = typeof payload.repository === "string" ? payload.repository : ((payload.repository as { full_name?: string } | undefined)?.full_name ?? ""); + const project = await projectByRepo(db, repo); + if (!project) return { status: 404, body: { error: "unknown repository" } }; + if (!verifyHookSignature(project.id, req.body, req.signature)) return { status: 401, body: { error: "bad signature" } }; + + if (req.event === "check") { + const state = String(payload.state); + if (!["success", "failure", "error", "pending"].includes(state) || typeof payload.sha !== "string" || typeof payload.check !== "string") { + return { status: 400, body: { error: "bad check report" } }; + } + const out = await recordCheck(db, project, { + sha: payload.sha, + branch: (payload.branch as string) || null, + prNumber: typeof payload.pr === "number" ? payload.pr : null, + check: payload.check, + state: state as CheckReport["state"], + runUrl: (payload.run_url as string) ?? null, + logTail: (payload.log_tail as string) ?? null, + durationSec: typeof payload.duration_sec === "number" ? payload.duration_sec : null, + source: "report", + }); + return { status: 200, body: { ok: true, ...out } }; + } + for (const h of eventHandlers) await h(db, project, req.event, payload); + return { status: 200, body: { ok: true } }; +} + +/** + * Fallback when reports/webhooks are lost: commit statuses `peppa/*` of the PR heads of + * tasks in work or review (the watchdog calls this about once a minute). + */ +export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Promise { + let seen = 0; + for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) { + if (!t.prUrl) continue; + const [p] = await db.select().from(projects).where(eq(projects.id, t.projectId)); + const n = p && taskPrNumber(p, t.prUrl); + if (!p || !n) continue; + try { + const pull = await gitea.getPullRequest(p.giteaOwner, p.giteaRepo, n); + if (pull.state !== "open") continue; + const st = await gitea.combinedStatus(p.giteaOwner, p.giteaRepo, pull.head.sha); + for (const s of st.statuses ?? []) { + if (!s.context.startsWith("peppa/")) continue; + const state = s.status === "warning" ? "pending" : s.status; + await recordCheck(db, p, { sha: pull.head.sha, branch: pull.head.ref, prNumber: n, check: s.context.slice(6), state, runUrl: s.target_url ?? null, source: "poll" }); + seen++; + } + } catch {} + } + return seen; +} + +/** + * Merge on "Accept" (PEP-57): only with green checks of the PR head and no conflicts. + * Throws with the reason for the PM; a task without a PR has nothing to merge. + */ +export async function mergeTaskPr(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<"merged" | "already" | "no_pr"> { + const gate = await prGate(ref, gitea); + if (!gate.pull) return "no_pr"; + if (gate.pull.merged) return "already"; + if (!gate.ok) throw new PeppaError(`Мерж не выполнен: ${gate.reason}`); + await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); + return "merged"; +} + +/** + * Automatic merge (auto mode of a project, PEP-23/25): the same gate, and a PR that changes + * the pipeline is never merged automatically — the PM gets a question describing the change. + */ +export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<{ merged: boolean; reason?: string }> { + const gate = await prGate(ref, gitea); + if (!gate.pull) return { merged: false, reason: "нет PR" }; + if (gate.pull.merged) return { merged: true }; + if (!gate.ok) return { merged: false, reason: gate.reason }; + const changes = await pipelineChanges(ref, gate.pull, gitea); + if (changes.length) { + await askPm(db, ref, { + kind: "question", + text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}`, + }); + return { merged: false, reason: "изменение конвейера требует ревью PM" }; + } + await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); + return { merged: true }; +} diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts index c1bfc310..652132ed 100644 --- a/packages/runner/src/ci.ts +++ b/packages/runner/src/ci.ts @@ -16,6 +16,9 @@ export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh"]; export const CI_BRANCH = "peppa/ci"; export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; +/** Where Gitea webhooks and CI reports reach Peppa. */ +export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`; + const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot"; /** @@ -48,7 +51,7 @@ export interface CiSetup { runner: "bot" | "repo"; } -/** Runner coverage and the Actions secret for CI reports. Idempotent. */ +/** Runner coverage, the Actions secret for CI reports and the webhook. Idempotent. */ export async function setupCi(db: Db, project: Project): Promise { const clients = await repoAdmins(db, project); if (!clients.length) throw new PeppaError("Нет доступа к Gitea"); @@ -58,7 +61,10 @@ export async function setupCi(db: Db, project: Project): Promise { await registerCiRunner(`repo-${project.giteaOwner}--${project.giteaRepo}`, token); runner = "repo"; } - await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, projectHookSecret(project.id))); + const secret = projectHookSecret(project.id); + await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret)); + // PR and push events (preview stands, merges) — signed with the same secret. + await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, ["pull_request", "push"])); return { runner }; } diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 1e74e265..5858cf4d 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -1,9 +1,10 @@ // PM-side moves on the task board and review acceptance (web and Telegram use these). -import { answerQuestion, getQuestion, listSessions, PeppaError, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core"; +import { answerQuestion, getQuestion, listSessions, PeppaError, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core"; import { tasks, projects, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { eq } from "drizzle-orm"; import { startSession, stopSession, type StartOptions } from "./sessions.ts"; +import { mergeTaskPr } from "./ci-feedback.ts"; export type BoardColumn = "backlog" | "in_progress" | "review" | "done"; @@ -19,9 +20,19 @@ async function activeSessions(db: Db, taskId: number) { return (await listSessions(db, { active: true, taskId })); } +/** + * Review gate (PEP-57): the task's PR head must have green checks and no conflicts. Fails + * open when Gitea can't be reached — merging is gated again on "Accept". + */ +export async function reviewGate(ref: TaskRef): Promise { + const gate = await prGate(ref).catch(() => null); + return gate && !gate.ok ? gate.reason ?? "проверки не пройдены" : null; +} + /** * Moves a task card. Into "in progress": status in_progress and an agent session is - * started unless one is running. Into "backlog"/"done": active sessions are stopped. + * started unless one is running. Into "review": only past the CI gate. Into + * "backlog"/"done": active sessions are stopped. */ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}): Promise<{ started?: number; stopped: number }> { const from = columnOf(ref.task.status); @@ -34,6 +45,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta } return { stopped }; } + if (to === "review" && from !== "review") { + const reason = await reviewGate(ref); + if (reason) throw new PeppaError(`${ref.key} нельзя в ревью: ${reason}`); + } if (to === "backlog" || to === "done") { for (const s of await activeSessions(db, ref.task.id)) { await stopSession(db, s.id); @@ -44,7 +59,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta return { stopped }; } -/** "Accept" on a ready-for-review message: task done, session stopped, question closed. */ +/** + * "Accept" on a ready-for-review message: the task's PR is merged (green checks, no + * conflicts — otherwise nothing changes and the PM sees why), task done, session stopped. + */ export async function acceptTask(db: Db, questionId: number, via: NonNullable): Promise { const q = await getQuestion(db, questionId); if (!q.taskId) throw new PeppaError("Вопрос не привязан к задаче"); @@ -56,6 +74,7 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable { const log = opts.log ?? (() => {}); log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`); @@ -128,6 +131,11 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); // Heartbeat and the check on the bot and the web (PEP-20). await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`)); + // CI results lost on the way (PEP-57): poll commit statuses about once a minute. + if (Date.now() - lastCiPoll >= 60_000) { + lastCiPoll = Date.now(); + await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`)); + } await new Promise((r) => setTimeout(r, opts.intervalMs)); } } diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts new file mode 100644 index 00000000..bdea79c1 --- /dev/null +++ b/packages/testkit/test/ci-feedback.test.ts @@ -0,0 +1,251 @@ +// PEP-57, spec delivery-pipeline: «Проверки на каждый PR», «Красные проверки возвращаются +// агенту», «Гейт ревью и мержа», «Изменение конвейера требует ревью» — one test per scenario, +// against mock Gitea (commit statuses, PRs, webhooks) and mock-claude runners. +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { createHmac } from "node:crypto"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-cifb-")), "gitea")); +const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; +const CHECKS = { lint: "pnpm lint", typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" }; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +interface CiTask { + p: TestProject; + proj: Awaited>; + ref: () => ReturnType; + branch: string; + /** Pushes a commit to the task branch, returns its SHA. */ + push(files?: Record): string; + /** CI result of one check, as the CI step reports it (signed webhook). */ + report(sha: string, check: string, state: string, log?: string): ReturnType; + statuses(sha: string, state: string, checks?: string[]): void; +} + +/** Project with a repo in mock Gitea and a task with an open PR from task/-1. */ +async function ciTask(opts: { checks?: Record; turns?: Parameters[0]["turns"] } = {}): Promise { + const p = await project({ turns: opts.turns ?? [] }); + const proj = await core.getProject(db, p.key); + const pj = JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: "http://test", ...(opts.checks ? { checks: opts.checks } : {}) }); + writeFileSync(join(p.dir, ".peppa/project.json"), pj); + gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); + gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; + const branch = `task/${p.taskKey}`; + let n = 0; + const push = (files: Record = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${n++}.txt`]: String(n), ...files }); + push(); + const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch); + const ref = () => core.resolveTask(db, p.taskKey); + await core.updateTask(db, await ref(), { status: "in_progress", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); + const repo = `${proj.giteaOwner}/${proj.giteaRepo}`; + return { + p, + proj, + ref, + branch, + push, + report(sha, check, state, log = "") { + const body = JSON.stringify({ repository: repo, sha, branch, pr: pr.number, check, state, run_url: `/${repo}/actions/runs/${sha.slice(0, 4)}`, duration_sec: 3, log_tail: log }); + const signature = createHmac("sha256", core.projectHookSecret(proj.id)).update(body).digest("hex"); + return runner.handleGiteaHook(db, { event: "check", signature, body }); + }, + statuses(sha, state, checks = Object.keys(CHECKS)) { + for (const c of checks) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, state, { target_url: `/${repo}/actions/runs/1` }); + }, + }; +} + +async function toReview(t: CiTask) { + await core.updateTask(db, await t.ref(), { status: "review" }); + return core.askPm(db, await t.ref(), { kind: "attention", text: "готова к ревью" }); +} + +describe("Проверки на каждый PR", () => { + test("Scenario: Зелёные проверки — в карточке «Проверки: 4 из 4 пройдены» со ссылкой на прогон", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + for (const c of Object.keys(CHECKS)) assert.equal((await t.report(sha, c, "success")).status, 200); + const d = await core.getTaskDetails(db, await t.ref()); + assert.equal(d.ci.label, "Проверки: 4 из 4 пройдены"); + assert.equal(d.ci.runUrl, `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/actions/runs/${sha.slice(0, 4)}`); + const { formatTask } = await import("../../mcp/src/format.ts"); + assert.match(formatTask(d), /Проверки: 4 из 4 пройдены \(коммит [0-9a-f]{7}\)/, "MCP get_task shows the checks"); + }); + + test("Scenario: Проверки не настроены — видно «проверки не настроены», переход в «Ревью» не блокируется", async () => { + const t = await ciTask(); + t.push(); + assert.equal((await core.getTaskDetails(db, await t.ref())).ci.label, "проверки не настроены"); + await runner.moveTask(db, await t.ref(), "review"); + assert.equal((await t.ref()).task.status, "review"); + }); +}); + +describe("Красные проверки возвращаются агенту", () => { + test("Scenario: Агент чинит сам — раннер получает шаг «test» и хвост лога, задача в работе, PM ничего не получает", async () => { + const t = await ciTask({ checks: CHECKS, turns: [[{ say: "PR открыт" }], [{ say: "чиню" }], [{ say: "ещё" }], [{ say: "и ещё" }]] }); + const id = await t.p.start(); + await t.p.waitLog("agent started", (e) => e.ev === "prompt"); + const sha = t.push(); + const r = await t.report(sha, "test", "failure", "ok 1 - adds\nnot ok 2 - divides by zero\n# fail 1"); + assert.equal((r.body as { action: string }).action, "agent"); + await t.p.waitLog("failure delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("«test»") && String(e.prompt).includes("not ok 2 - divides by zero")); + assert.equal((await t.ref()).task.status, "in_progress"); + assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind !== "attention").length, 0); + const task = (await t.ref()).task; + assert.equal(task.ciAttempts, 1); + // A second red check of the same commit is the same attempt. + await t.report(sha, "lint", "failure", "lint error"); + assert.equal((await t.ref()).task.ciAttempts, 1); + await runner.stopSession(db, id); + }); + + test("Scenario: Три неудачи подряд — PM получает вопрос со ссылкой на лог", async () => { + const t = await ciTask({ checks: CHECKS, turns: [[{ say: "1" }], [{ say: "2" }], [{ say: "3" }], [{ say: "4" }], [{ say: "5" }]] }); + const id = await t.p.start(); + await t.p.waitLog("agent started", (e) => e.ev === "prompt"); + const actions: string[] = []; + for (let i = 0; i < 3; i++) actions.push(((await t.report(t.push(), "test", "failure", `fail #${i}`)).body as { action: string }).action); + assert.deepEqual(actions, ["agent", "agent", "pm"]); + const q = (await core.pendingQuestions(db, t.proj.id)).find((x) => x.kind === "question"); + assert.ok(q, "PM got a question"); + assert.equal(q.taskId, (await t.ref()).task.id); + assert.match(q.text, new RegExp(`красные 3 раза подряд[\\s\\S]*Лог: ${gitea.url}/`)); + await t.p.waitLog("runner told to wait", (e) => e.ev === "prompt" && String(e.prompt).includes("жди ответа PM")); + // Green again → the counter starts over. + const sha = t.push(); + for (const c of Object.keys(CHECKS)) await t.report(sha, c, "success"); + assert.equal((await t.ref()).task.ciAttempts, 0); + await runner.stopSession(db, id); + }); + + test("no runner: a red check sends a task in review back to work and starts the agent with the log", async () => { + const t = await ciTask({ checks: CHECKS, turns: [[{ say: "чиню" }]] }); + const sha = t.push(); + await core.updateTask(db, await t.ref(), { status: "review" }); + const r = await t.report(sha, "build", "failure", "error TS2304: Cannot find name 'x'"); + assert.equal((r.body as { action: string }).action, "restarted"); + assert.equal((await t.ref()).task.status, "in_progress"); + await t.p.waitLog("agent started with the failure", (e) => e.ev === "prompt" && String(e.prompt).includes("Cannot find name 'x'")); + for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id); + }); + + test("the template's CI step reports to Peppa: signature accepted, log tail stored", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + // Peppa's POST /api/hooks/gitea, as the web route does it. + const server = createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", async () => { + const r = await runner.handleGiteaHook(db, { event: String(req.headers["x-peppa-event"]), signature: String(req.headers["x-gitea-signature"]), body }); + res.writeHead(r.status).end(JSON.stringify(r.body)); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const job = mkdtempSync(join(tmpdir(), "peppa-job-")); + mkdirSync(join(job, ".peppa")); + writeFileSync(join(job, ".peppa/project.json"), JSON.stringify({ peppaUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, checks: { test: "echo 'not ok 1 - кириллица и \"кавычки\"'; exit 1" } })); + const script = resolve(fileURLToPath(import.meta.url), "../../../../template/.gitea/peppa-check.sh"); + const env = { ...process.env, GITHUB_ACTIONS: "true", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${t.proj.giteaOwner}/${t.proj.giteaRepo}`, GITHUB_RUN_NUMBER: "9", PEPPA_SHA: sha, PEPPA_BRANCH: t.branch, PEPPA_PR: "1", GITEA_TOKEN: BOT.token, PEPPA_CI_SECRET: core.projectHookSecret(t.proj.id) }; + const out = await new Promise((done) => execFile("bash", [script, "test"], { cwd: job, env, encoding: "utf8" }, (_e, stdout) => done(stdout))); + server.close(); + assert.doesNotMatch(out, /недоступна/); + const d = await core.getTaskDetails(db, await t.ref()); + assert.equal(d.ci.failed[0]?.check, "test"); + assert.match(d.ci.failed[0]?.logTail ?? "", /not ok 1 - кириллица и "кавычки"/); + assert.equal(d.ci.failed[0]?.runUrl, `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/actions/runs/9`); + assert.equal((await t.ref()).task.ciAttempts, 1); + }); + + test("webhook: wrong signature and unknown repo are rejected; polling picks up lost results", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + const body = JSON.stringify({ repository: `${t.proj.giteaOwner}/${t.proj.giteaRepo}`, sha, check: "test", state: "success" }); + assert.equal((await runner.handleGiteaHook(db, { event: "check", signature: "00", body })).status, 401); + assert.equal((await runner.handleGiteaHook(db, { event: "check", signature: "00", body: JSON.stringify({ repository: "nobody/nothing" }) })).status, 404); + t.statuses(sha, "success"); + assert.ok((await runner.pollChecks(db)) >= 4); + assert.equal((await core.getTaskDetails(db, await t.ref())).ci.label, "Проверки: 4 из 4 пройдены"); + }); +}); + +describe("Гейт ревью и мержа", () => { + test("Scenario: Мерж при красных проверках — мерж не выполняется, PM видит «проверки не пройдены»", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success", ["lint", "typecheck", "build"]); + t.statuses(sha, "failure", ["test"]); + const q = await toReview(t); + await assert.rejects(runner.acceptTask(db, q.id, "web"), /Мерж не выполнен: проверки не пройдены \(test\)/); + assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, false); + assert.equal((await t.ref()).task.status, "review"); + assert.equal((await core.getQuestion(db, q.id)).answeredAt, null, "the review question stays open"); + }); + + test("Scenario: Приёмка — PR смержен в основную ветку, задача в «Готово»", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success"); + const q = await toReview(t); + await runner.acceptTask(db, q.id, "web"); + const pr = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!; + assert.equal(pr.merged, true); + assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha); + assert.equal((await t.ref()).task.status, "done"); + }); + + test("review gate: the agent can't move a task to review with red or running checks", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success", ["lint"]); + assert.match((await runner.reviewGate(await t.ref())) ?? "", /проверки ещё идут \(1 из 4\)/); + await assert.rejects(runner.moveTask(db, await t.ref(), "review"), /нельзя в ревью: проверки ещё идут/); + t.statuses(sha, "success"); + gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.mergeable = false; + assert.equal(await runner.reviewGate(await t.ref()), "есть конфликты с основной веткой"); + gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.mergeable = true; + assert.equal(await runner.reviewGate(await t.ref()), null); + }); +}); + +describe("Изменение конвейера требует ревью", () => { + test("Scenario: Агент отключил тесты — PR не мержится автоматически, PM получает вопрос с описанием изменения", async () => { + const t = await ciTask({ checks: CHECKS }); + const pj = JSON.stringify({ slug: t.proj.slug, key: t.p.key, name: t.p.key, peppaUrl: "http://test", checks: { ...CHECKS, test: "true" } }); + const sha = t.push({ ".peppa/project.json": pj }); + t.statuses(sha, "success"); + const r = await runner.autoMergeTask(db, await t.ref()); + assert.deepEqual(r, { merged: false, reason: "изменение конвейера требует ревью PM" }); + assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, false); + const q = await waitFor("pipeline question", async () => (await core.pendingQuestions(db, t.proj.id)).find((x) => x.text.includes("меняет конвейер"))); + assert.match(q.text, /checks: .*"test":"pnpm test".* → .*"test":"true"/); + }); + + test("auto-merge without pipeline changes merges a green PR", async () => { + const t = await ciTask({ checks: CHECKS }); + t.statuses(t.push(), "success"); + assert.deepEqual(await runner.autoMergeTask(db, await t.ref()), { merged: true }); + }); +}); diff --git a/packages/testkit/test/ci.test.ts b/packages/testkit/test/ci.test.ts index 9143d755..0e7db66c 100644 --- a/packages/testkit/test/ci.test.ts +++ b/packages/testkit/test/ci.test.ts @@ -65,6 +65,8 @@ describe("CI: connect a project", () => { assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos"); const repo = gitea.repo(BOT.login, p.giteaRepo); assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id)); + assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), ["pull_request", "push"]]]); + assert.match(runner.giteaHookUrl(), /\/api\/hooks\/gitea$/); assert.ok(r.prUrl?.endsWith("/pulls/1")); const pr = repo.pulls[0]!; assert.equal(pr.head, runner.CI_BRANCH); -- 2.45.2 From daa612b0d884091efd351296014caddd158b0c1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Fri, 13 Nov 2026 14:36:47 +0500 Subject: [PATCH 002/536] =?UTF-8?q?PEP-57:=20gate=20=E2=80=94=20Gitea=20cl?= =?UTF-8?q?ient=20only=20for=20tasks=20with=20a=20PR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- packages/core/src/ci.ts | 3 ++- packages/runner/src/ci-feedback.ts | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts index 32a123c9..06a5a5cb 100644 --- a/packages/core/src/ci.ts +++ b/packages/core/src/ci.ts @@ -137,9 +137,10 @@ export interface GateResult { * Gate for review and merge: the task's PR head has green checks and no conflicts. A task * without a PR or a project without checks passes (the card says "проверки не настроены"). */ -export async function prGate(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise { +export async function prGate(ref: TaskRef, client?: GiteaClient): Promise { const n = taskPrNumber(ref.project, ref.task.prUrl); if (!n) return { ok: true, summary: null, pull: null }; + const gitea = client ?? giteaForBot(); const { giteaOwner: o, giteaRepo: r } = ref.project; const pull = await gitea.getPullRequest(o, r, n); if (pull.merged) return { ok: true, summary: null, pull }; diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 57311b9c..0c76c0ec 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -183,7 +183,9 @@ export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Pr * Merge on "Accept" (PEP-57): only with green checks of the PR head and no conflicts. * Throws with the reason for the PM; a task without a PR has nothing to merge. */ -export async function mergeTaskPr(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<"merged" | "already" | "no_pr"> { +export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<"merged" | "already" | "no_pr"> { + if (!taskPrNumber(ref.project, ref.task.prUrl)) return "no_pr"; + const gitea = client ?? giteaForBot(); const gate = await prGate(ref, gitea); if (!gate.pull) return "no_pr"; if (gate.pull.merged) return "already"; -- 2.45.2 From 59c3b583deb944f738f0a4d5ada686b5a29c12f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Fri, 13 Nov 2026 14:49:24 +0500 Subject: [PATCH 003/536] =?UTF-8?q?PEP-57:=20CD=20=E2=80=94=20deploy=20wor?= =?UTF-8?q?kflow,=20preview/staging/prod,=20health=20check=20and=20rollbac?= =?UTF-8?q?k,=20releases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/bot/src/render.ts | 2 +- apps/web/app/(app)/actions.ts | 11 +- apps/web/app/(app)/help/page.tsx | 24 +- apps/web/app/(app)/p/[key]/page.tsx | 48 +- openspec/changes/pep-57-ci-cd/design.md | 16 + openspec/changes/pep-57-ci-cd/tasks.md | 8 +- packages/cli/src/index.ts | 17 +- packages/core/src/tasks.ts | 7 + .../db/migrations/0013_pep57_releases.sql | 20 + .../db/migrations/meta/0013_snapshot.json | 2189 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 22 + packages/mcp/src/manager.ts | 23 +- packages/runner/src/ci-feedback.ts | 22 + packages/runner/src/ci.ts | 7 +- packages/runner/src/deploy.ts | 167 ++ packages/runner/src/index.ts | 1 + packages/runner/src/sessions.ts | 3 + packages/testkit/bin/mock-docker | 35 + packages/testkit/src/mock-gitea.ts | 7 +- packages/testkit/test/deploy.test.ts | 241 ++ template/.gitea/peppa-deploy.sh | 116 + template/.gitea/workflows/deploy.yml | 35 + template/RULES.md | 18 + template/deploy/Dockerfile.node | 16 + template/deploy/Dockerfile.python | 10 + template/deploy/compose.yml | 21 + 28 files changed, 3079 insertions(+), 15 deletions(-) create mode 100644 packages/db/migrations/0013_pep57_releases.sql create mode 100644 packages/db/migrations/meta/0013_snapshot.json create mode 100644 packages/runner/src/deploy.ts create mode 100755 packages/testkit/bin/mock-docker create mode 100644 packages/testkit/test/deploy.test.ts create mode 100644 template/.gitea/peppa-deploy.sh create mode 100644 template/.gitea/workflows/deploy.yml create mode 100644 template/deploy/Dockerfile.node create mode 100644 template/deploy/Dockerfile.python create mode 100644 template/deploy/compose.yml diff --git a/AGENTS.md b/AGENTS.md index b0a35ab1..a23dcfda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,7 @@ - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) - Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены») +- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index d1a7fc8c..890c9fdd 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -22,7 +22,7 @@ export function renderQuestion( q: Question, ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, ): Rendered { - const head = [`${esc(ctx.taskKey ?? `Сессия ${q.sessionId ?? "?"}`)}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] + const head = [`${esc(ctx.taskKey ?? (q.sessionId ? `Сессия ${q.sessionId}` : "Релизы проекта"))}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); const body = esc(clip(q.text, 3300)); diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 66a05cca..2aca86d1 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -15,12 +15,13 @@ import { getSetting, unpairTelegram, getIncident, + getProject as getProjectByKey, updateIncidentSettings, type IncidentPolicy, } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; -import { bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -140,6 +141,14 @@ export async function createProjectAction(f: FormData) { }); } +export async function deployProdAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, (await getProjectByKey(db, str(f, "projectKey"))).id); + await deployProd(db, p, user.login); + }); +} + export async function moveTaskCard(f: FormData) { const user = await requireUser(); await attempt(f, async () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 431fdee9..21c302e8 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -10,7 +10,8 @@ const TOOLS: Array<[string, string]> = [ ["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"], ["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"], ["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"], - ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"], + ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"], + ["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"], ["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"], ["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"], ["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"], @@ -29,6 +30,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [ { title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" }, { title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «Подключить отслеживание ошибок»" }, { title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" }, + { title: "Выкатить в прод", say: "Что сейчас на staging в PAY? · Выкати PAY в прод", how: "list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет" }, { title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" }, ]; @@ -82,6 +84,26 @@ export default async function Help() { +

CI/CD

+

+ Каждый PR агента проверяет Gitea Actions: install, lint,{" "} + typecheck, test, build. Команды — + в .peppa/project.json → checks (заполняет агент на первой задаче), workflow приходит из + шаблона; в старый проект — командой peppa ci connect KEY (PR от Пеппы). Результат виден в + карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных + прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без + конфликтов. PR, меняющий конвейер (.gitea/, checks,{" "} + deploy), сам не мержится никогда. +

+

+ Деплой — deploy в project.json и Dockerfile (заготовки в{" "} + deploy/): PR получает preview slug-prN.telecom.quest (удаляется при + закрытии), мерж выкатывает staging slug-staging.telecom.quest, прод{" "} + slug-prod.telecom.quest — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "} + deploy). После каждого деплоя — проверка /healthz до 2 минут; не + прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта. +

+

Telegram

Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index c05afd36..154de0aa 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -2,14 +2,22 @@ import { notFound } from "next/navigation"; import { AutoRefresh } from "@/components/AutoRefresh"; import { Flash, Notice, SessionCard } from "@/components/ui"; import { Board, type Card } from "@/components/Board"; -import { columnOf, describeRepo } from "@peppa/runner"; +import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner"; import { requireUser } from "@/lib/auth"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { bugsinkWebhookBase } from "@peppa/runner"; import { IncidentsSection } from "@/components/Incidents"; import { db } from "@/lib/db"; -import { addGoal, addProjectMember, addTask, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; +import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; + +const RELEASE_STATUS: Record = { + deploying: "⏳ выкатывается", + healthy: "✅ работает", + rolled_back: "↩️ откат", + failed: "❌ не поднялся", + removed: "🗑 удалён", +}; export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) { const user = await requireUser(); @@ -17,7 +25,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const { error, created } = await searchParams; const p = await projectForUserByKey(user.id, key).catch(() => null); if (!p) notFound(); - const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents] = await Promise.all([ + const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([ board(p.id), projectSessions(p.id), listMembers(db, p), @@ -25,6 +33,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr getIncidentSettings(db, p.id), listErrorSources(db, p.id), listIncidents(db, p.id), + listReleases(db, p.id, 15), + currentReleases(db, p.id), ]); const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase())); // Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway). @@ -88,6 +98,38 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr

+
+

Релизы

+

+ Staging: {current.staging ? <>{current.staging.sha.slice(0, 7)}{current.staging.host && <> · {current.staging.host}} : нет} + {" · "}Прод: {current.prod ? <>{current.prod.sha.slice(0, 7)}{current.prod.host && <> · {current.prod.host}} : нет} +

+ {current.staging && current.staging.sha !== current.prod?.sha && ( +
+ + + +
+ )} + {releases.length === 0 ? ( +

Деплоев ещё не было. Настройка — deploy в .peppa/project.json (см. «Помощь → CI/CD»).

+ ) : ( + + + {releases.map((r) => ( + + + + + + + + ))} + +
{r.env}{r.prNumber ? ` #${r.prNumber}` : ""}{r.sha.slice(0, 7)}{RELEASE_STATUS[r.status]}{r.reason ? — {r.reason} : null}{r.tasks.join(", ")}{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
+ )} +
+ -pr.telecom.quest`, + `-staging.telecom.quest`, `-prod.telecom.quest` (можно переопределить в + `deploy.hosts`). Многоуровневые `pr-N.slug.preview.telecom.quest` из proposal не проходят TLS: + универсальный сертификат Cloudflare покрывает только `*.telecom.quest`. Прод не на + `.telecom.quest`, чтобы проект не перехватил существующий хост (проект Пеппы — `peppa`). + Маршруты — docker-метками (провайдер docker Traefik), файлы в `dynamic/` не нужны. +- **Прод — тег `deploy-prod-<время>`** на коммит здорового staging-релиза, его ставит Пеппа от + имени peppa-bot: в Gitea 1.22 нет API `workflow_dispatch`. Тот же образ (`peppa/:` + уже собран staging'ом), сборки нет. +- **Health** — изнутри сети `traefik_default` по имени контейнера `<проект>-<сервис>-1`, до + `PEPPA_HEALTH_TIMEOUT` (120 с). Откат — `compose up` с образом, который работал в окружении до + деплоя (из `docker inspect`), не из таблицы `releases`: так откат работает и без Пеппы. +- **Задачи релиза** — ключи `-N` из сообщений коммитов между предыдущим и новым SHA (шаг + присылает их); для прода по кнопке — задачи staging-релизов с прошлого прода. +- **Сообщения PM** — вопросы без задачи (`askPmProject`): «staging обновлён» с кнопкой + «🚀 Выкатить в прод» (прежние такие предложения закрываются), откат/провал, прод выкачен. diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md index 5cc94c2f..3638fdc1 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -21,10 +21,10 @@ ## 3. CD -- [ ] 3.1 Шаблон: `Dockerfile`-заготовки (node, python), `deploy/compose.yml` с метками Traefik, `deploy.yml` (build → staging → smoke); `releases` в БД -- [ ] 3.2 Preview на PR и удаление при закрытии; staging на мерж; прод по кнопке (веб, Telegram, MCP `deploy`) через `workflow_dispatch` -- [ ] 3.3 Проверка здоровья и авто-откат; блок «Релизы» на странице проекта; сообщения PM -- [ ] 3.4 Тесты сценариев «Деплой» и «Откат» (деплой — на моке: compose-команда подменяется mock-скриптом) +- [x] 3.1 Шаблон: `Dockerfile`-заготовки (node, python), `deploy/compose.yml` с метками Traefik, `deploy.yml` (build → staging → smoke); `releases` в БД +- [x] 3.2 Preview на PR и удаление при закрытии; staging на мерж; прод по кнопке (веб, Telegram, MCP `deploy`) через `workflow_dispatch` +- [x] 3.3 Проверка здоровья и авто-откат; блок «Релизы» на странице проекта; сообщения PM +- [x] 3.4 Тесты сценариев «Деплой» и «Откат» (деплой — на моке: compose-команда подменяется mock-скриптом) ## 4. Пеппа на собственном конвейере diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 0714401e..4635b0ef 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -39,7 +39,7 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb } from "@peppa/db"; -import { answerAndDeliver, connectCi, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, deployProd, listReleases, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { loadEnv } from "@peppa/shared"; @@ -49,6 +49,8 @@ const USAGE = `peppa — Peppa software factory CLI peppa project add [--owner peppa] [--repo ] [--path ] (register only) peppa project owner peppa project list + peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) + peppa release list [KEY] peppa ci connect [KEY] (runner + secret + PR with the CI workflow from the template) peppa goal add [KEY] [-d <description>] peppa goal list [KEY] @@ -176,6 +178,19 @@ async function main(): Promise<void> { console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`); break; } + case "deploy prod": { + const [key] = withKey(args, 0); + const p = await getProject(db, key); + const r = await deployProd(db, p, process.env.USER ?? "cli"); + console.log(`${p.key}: ${r.sha.slice(0, 7)} → prod (release #${r.id}, tasks: ${r.tasks.join(", ") || "—"})`); + break; + } + case "release list": { + const [key] = withKey(args, 0); + const p = await getProject(db, key); + for (const r of await listReleases(db, p.id)) console.log(`#${r.id} ${r.env.padEnd(8)} ${r.sha.slice(0, 7)} ${r.status.padEnd(11)} ${r.tasks.join(",")} ${r.deployedBy} ${r.reason ?? ""}`); + break; + } case "goal add": { const [key, [title]] = withKey(args, 1); if (!title) throw new PeppaError("usage: peppa goal add [KEY] <title>"); diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 15d397f5..f392e3e1 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -155,6 +155,13 @@ export async function askPm(db: Db, ref: TaskRef, q: NewQuestion): Promise<Quest return row!; } +/** A message for the PM about the project as a whole (releases), not about a task. */ +export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise<Question> { + const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); + await notify(db, { type: "question", questionId: row!.id }); + return row!; +} + export async function pendingQuestions(db: Db, projectId?: number): Promise<Question[]> { return db .select() diff --git a/packages/db/migrations/0013_pep57_releases.sql b/packages/db/migrations/0013_pep57_releases.sql new file mode 100644 index 00000000..9f82d934 --- /dev/null +++ b/packages/db/migrations/0013_pep57_releases.sql @@ -0,0 +1,20 @@ +CREATE TABLE "releases" ( + "id" serial PRIMARY KEY NOT NULL, + "project_id" integer NOT NULL, + "env" text NOT NULL, + "sha" text NOT NULL, + "previous_sha" text, + "image" text, + "host" text, + "pr_number" integer, + "tasks" jsonb DEFAULT '[]'::jsonb NOT NULL, + "status" text DEFAULT 'deploying' NOT NULL, + "deployed_by" text DEFAULT 'ci' NOT NULL, + "reason" text, + "run_url" text, + "log_tail" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "releases" ADD CONSTRAINT "releases_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file diff --git a/packages/db/migrations/meta/0013_snapshot.json b/packages/db/migrations/meta/0013_snapshot.json new file mode 100644 index 00000000..56cb70cd --- /dev/null +++ b/packages/db/migrations/meta/0013_snapshot.json @@ -0,0 +1,2189 @@ +{ + "id": "82ed94db-27de-4e8f-81c1-5440cb5f4011", + "prevId": "ca89d235-ea51-4284-95fe-50b24621c88a", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.check_runs": { + "name": "check_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "check", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.error_sources": { + "name": "error_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "nullsNotDistinct": false, + "columns": [ + "bugsink_project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.incident_settings": { + "name": "incident_settings", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environments": { + "name": "environments", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[\"prod\",\"production\"]'::jsonb" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "nullsNotDistinct": false, + "columns": [ + "hook_secret" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.incidents": { + "name": "incidents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_seen": { + "name": "last_seen", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "nullsNotDistinct": false, + "columns": [ + "bugsink_issue_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_invites": { + "name": "project_invites", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": { + "name": "project_invites_project_id_login_pk", + "columns": [ + "project_id", + "login" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_members": { + "name": "project_members", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": { + "name": "project_members_project_id_user_id_pk", + "columns": [ + "project_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.releases": { + "name": "releases", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tasks": { + "name": "tasks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "nullsNotDistinct": false, + "columns": [ + "telegram_chat_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 7c258cac..108d9a85 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -92,6 +92,13 @@ "when": 1794562626634, "tag": "0012_faithful_matthew_murdock", "breakpoints": true + }, + { + "idx": 13, + "version": "7", + "when": 1794562970727, + "tag": "0013_pep57_releases", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index a055a2bd..3e6194fc 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -118,6 +118,28 @@ export const tasks = pgTable( (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], ); +/** PEP-57: one deployment of a project to an environment (and its outcome). */ +export const releases = pgTable("releases", { + id: serial("id").primaryKey(), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + env: text("env", { enum: ["preview", "staging", "prod"] }).notNull(), + sha: text("sha").notNull(), + previousSha: text("previous_sha"), + image: text("image"), + host: text("host"), + prNumber: integer("pr_number"), + // Task keys in the release ("PAY-7"), from the merged commits. + tasks: jsonb("tasks").$type<string[]>().notNull().default([]), + status: text("status", { enum: ["deploying", "healthy", "rolled_back", "failed", "removed"] }).notNull().default("deploying"), + // "ci" for automatic deploys, the PM's login for prod by the button. + deployedBy: text("deployed_by").notNull().default("ci"), + reason: text("reason"), + runUrl: text("run_url"), + logTail: text("log_tail"), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + /** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */ export const checkRuns = pgTable( "check_runs", diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 0f9d0fb3..c5f59784 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -32,7 +32,7 @@ import { } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, loadEnv } from "@peppa/shared"; -import { decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; +import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; import { and, asc, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; @@ -54,6 +54,7 @@ Good habits: - Only move a task to in_progress when the user asks to start the work. - Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user. - Projects can be shared: add_member / remove_member (owner only); members can do everything else. +- CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks. - Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`; export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { @@ -251,6 +252,26 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ }, ); + tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, tasks, who deployed).", { project: projectArg }, true, async ({ project }) => { + const p = await ownedProject(project); + const [cur, rows] = await Promise.all([currentReleases(db, p.id), listReleases(db, p.id, 15)]); + const head = (["staging", "prod"] as const).map((e) => `${e}: ${cur[e] ? `${cur[e]!.sha.slice(0, 7)}${cur[e]!.host ? ` https://${cur[e]!.host}` : ""}` : "—"}`).join(" · "); + if (!rows.length) return `${head}\nNo deployments yet (deploy is configured in .peppa/project.json → "deploy").`; + return [head, ...rows.map((r) => `- ${r.env}${r.prNumber ? ` #${r.prNumber}` : ""} ${r.sha.slice(0, 7)} ${r.status}${r.reason ? ` (${r.reason})` : ""}${r.tasks.length ? ` · ${r.tasks.join(", ")}` : ""} · ${r.deployedBy} · ${r.createdAt.toISOString().slice(0, 16)}`)].join("\n"); + }); + + tool( + "deploy", + "Deploy the project's healthy staging release to prod (the same image). Only when the user asks; the result arrives as a release (list_releases) and a message.", + { project: projectArg, env: z.enum(["prod"]).default("prod") }, + false, + async ({ project }) => { + const p = await ownedProject(project); + const r = await deployProd(db, p, user.login); + return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (tasks ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`; + }, + ); + tool("list_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => { const ids = await userProjectIds(db, user.id); if (!ids.length) return "Inbox is empty — agents need nothing from you."; diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 0c76c0ec..030cc42f 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -23,6 +23,7 @@ import { checkRuns, projects, tasks, type Db } from "@peppa/db"; import { and, eq, sql } from "drizzle-orm"; import { sendToSession } from "./sessions.ts"; import { moveTask } from "./flow.ts"; +import { recordRelease } from "./deploy.ts"; /** Red runs in a row after which the PM is asked instead of the agent. */ export const MAX_CI_ATTEMPTS = 3; @@ -149,6 +150,27 @@ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ statu }); return { status: 200, body: { ok: true, ...out } }; } + if (req.event === "deploy") { + const env = String(payload.env); + const status = String(payload.status); + if (!["preview", "staging", "prod"].includes(env) || !["deploying", "healthy", "rolled_back", "failed", "removed"].includes(status) || typeof payload.sha !== "string") { + return { status: 400, body: { error: "bad deploy report" } }; + } + const rel = await recordRelease(db, project, { + env: env as "preview", + sha: payload.sha, + previousSha: (payload.previous_sha as string) || null, + image: (payload.image as string) ?? null, + host: (payload.host as string) ?? null, + prNumber: typeof payload.pr === "number" ? payload.pr : null, + status: status as "healthy", + reason: (payload.reason as string) ?? null, + runUrl: (payload.run_url as string) ?? null, + commits: Array.isArray(payload.commits) ? payload.commits.map(String) : [], + logTail: (payload.log_tail as string) ?? null, + }); + return { status: 200, body: { ok: true, release: rel.id, status: rel.status } }; + } for (const h of eventHandlers) await h(db, project, req.event, payload); return { status: 200, body: { ok: true } }; } diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts index 652132ed..976dc050 100644 --- a/packages/runner/src/ci.ts +++ b/packages/runner/src/ci.ts @@ -12,7 +12,9 @@ import { repoAdmins } from "./share.ts"; import { git, run, templateRepoUrl } from "./git.ts"; /** Files of the CI contract, copied from the template into project repos. */ -export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh"]; +export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh", ".gitea/workflows/deploy.yml", ".gitea/peppa-deploy.sh"]; +/** Starting points copied only when the project has none yet (the project owns them after). */ +export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "deploy/Dockerfile.python"]; export const CI_BRANCH = "peppa/ci"; export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; @@ -93,7 +95,7 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str await git(work, "clone", "-q", repo.clone_url, dest); await git(work, "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl); await git(dest, "checkout", "-q", "-B", CI_BRANCH, `origin/${base}`); - for (const f of CI_FILES) { + for (const f of [...CI_FILES, ...CD_SCAFFOLD.filter((f) => !existsSync(join(dest, f)))]) { mkdirSync(dirname(join(dest, f)), { recursive: true }); cpSync(join(tpl, f), join(dest, f)); } @@ -122,6 +124,7 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str "", `- ${CI_FILES.map((f) => `\`${f}\``).join(", ")} — из шаблона, под стек не меняются;`, "- команды проверок — в `.peppa/project.json` → `checks` (`install`, `lint`, `typecheck`, `test`, `build`); пустая команда = шаг пропущен.", + "- деплой (preview на PR, staging на мерж, прод по кнопке PM) — `.peppa/project.json` → `deploy` + `Dockerfile` (заготовки в `deploy/`); без `deploy` шаг пропускается.", "", "Заполнить `checks` — первая задача агента в проекте. Изменение конвейера требует ревью PM.", ].join("\n"), diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts new file mode 100644 index 00000000..0ed7364f --- /dev/null +++ b/packages/runner/src/deploy.ts @@ -0,0 +1,167 @@ +// Deployments of factory projects (PEP-57). The project's deploy workflow does the work on +// the host (docker compose behind Traefik, health check, rollback) and reports each step +// here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a +// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). +import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { projects, questions, releases, type Db } from "@peppa/db"; +import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; + +export type Release = typeof releases.$inferSelect; +export type ReleaseEnv = Release["env"]; +export type ReleaseStatus = Release["status"]; + +/** The option of the "staging updated" message that sends the release to prod. */ +export const PROD_OPTION = "🚀 Выкатить в прод"; + +export interface DeployReport { + env: ReleaseEnv; + sha: string; + previousSha?: string | null; + image?: string | null; + host?: string | null; + prNumber?: number | null; + status: ReleaseStatus; + reason?: string | null; + runUrl?: string | null; + commits?: string[]; + logTail?: string | null; +} + +/** Task keys of the project mentioned in commit subjects ("…from task/PAY-7 into main"). */ +export function tasksInCommits(project: Project, commits: string[]): string[] { + const re = new RegExp(`\\b${project.key}-(\\d+)\\b`, "gi"); + const out = new Set<string>(); + for (const c of commits) for (const m of c.matchAll(re)) out.add(`${project.key}-${Number(m[1])}`); + return [...out].sort((a, b) => Number(a.split("-")[1]) - Number(b.split("-")[1])); +} + +export async function listReleases(db: Db, projectId: number, limit = 20): Promise<Release[]> { + return db.select().from(releases).where(eq(releases.projectId, projectId)).orderBy(desc(releases.id)).limit(limit); +} + +/** What runs in each environment now: the latest healthy (or rolled back to) release. */ +export async function currentReleases(db: Db, projectId: number): Promise<Partial<Record<ReleaseEnv, Release>>> { + const out: Partial<Record<ReleaseEnv, Release>> = {}; + for (const env of ["staging", "prod"] as const) { + const [r] = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy"))) + .orderBy(desc(releases.id)) + .limit(1); + if (r) out[env] = r; + } + return out; +} + +const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—"); + +/** Closes earlier unanswered "deploy to prod?" offers of the project: a newer staging is up. */ +async function expireProdOffers(db: Db, projectId: number) { + const open = await db + .select() + .from(questions) + .where(and(eq(questions.projectId, projectId), isNull(questions.taskId), isNull(questions.answeredAt), sql`${questions.options} @> ${JSON.stringify([PROD_OPTION])}::jsonb`)); + for (const q of open) await answerQuestion(db, q.id, "(неактуально: на staging новый релиз)", "system").catch(() => {}); +} + +/** Records one step of a deploy and tells the PM what they need to know. */ +export async function recordRelease(db: Db, project: Project, r: DeployReport): Promise<Release> { + const sameRun = and( + eq(releases.projectId, project.id), + eq(releases.env, r.env), + eq(releases.sha, r.sha), + eq(releases.status, "deploying"), + r.env === "preview" && r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined, + ); + const [open] = await db.select().from(releases).where(sameRun).orderBy(desc(releases.id)).limit(1); + const fromCommits = tasksInCommits(project, r.commits ?? []); + const values = { + previousSha: r.previousSha ?? open?.previousSha ?? null, + image: r.image ?? open?.image ?? null, + host: r.host ?? open?.host ?? null, + prNumber: r.prNumber ?? open?.prNumber ?? null, + tasks: open?.tasks.length ? open.tasks : fromCommits, + status: r.status, + reason: r.reason ?? null, + runUrl: r.runUrl ?? open?.runUrl ?? null, + logTail: r.logTail ?? open?.logTail ?? null, + }; + let rel: Release; + if (r.status === "removed") { + // Preview torn down: every release of that PR's stand is gone. + await db + .update(releases) + .set({ status: "removed" }) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, r.prNumber ?? -1), inArray(releases.status, ["deploying", "healthy"]))); + [rel] = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, r.prNumber ?? -1))).orderBy(desc(releases.id)).limit(1); + if (rel!) return rel; + } + [rel] = open + ? await db.update(releases).set(values).where(eq(releases.id, open.id)).returning() + : await db.insert(releases).values({ projectId: project.id, env: r.env, sha: r.sha, ...values }).returning(); + await notifyRelease(db, project, rel!); + return rel!; +} + +async function notifyRelease(db: Db, project: Project, rel: Release) { + const tasks = rel.tasks.length ? ` · задачи: ${rel.tasks.join(", ")}` : ""; + const log = runLink(rel.runUrl); + if (rel.status === "rolled_back" || rel.status === "failed") { + const back = rel.status === "rolled_back" ? ` — возвращён ${short(rel.previousSha)}` : ""; + await askPmProject(db, project, { + kind: "attention", + text: `❌ ${project.name}: релиз ${short(rel.sha)} в ${rel.env} не прошёл${back}.\nПричина: ${rel.reason ?? "неизвестна"}${log ? `\nЛог: ${log}` : ""}`, + }); + } else if (rel.status === "healthy" && rel.env === "staging") { + await expireProdOffers(db, project.id); + await askPmProject(db, project, { + kind: "question", + options: [PROD_OPTION], + text: `✅ ${project.name}: staging обновлён — ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}\nВыкатить этот релиз в прод?`, + }); + } else if (rel.status === "healthy" && rel.env === "prod") { + await askPmProject(db, project, { kind: "attention", text: `🚀 ${project.name} в проде: ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}` }); + } +} + +/** + * "Deploy to prod" (web, Telegram, MCP): the image of the latest healthy staging release + * goes to prod — Peppa tags that commit `deploy-prod-<time>` and the workflow deploys it. + */ +export async function deployProd(db: Db, project: Project, by: string, gitea: GiteaClient = giteaForBot()): Promise<Release> { + const { staging, prod } = await currentReleases(db, project.id); + if (!staging) throw new PeppaError(`${project.key}: на staging нет здорового релиза — выкатывать нечего`); + const [running] = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))) + .limit(1); + if (running) throw new PeppaError(`${project.key}: прод уже выкатывается (${short(running.sha)})`); + // Tasks since the last prod release: every healthy staging release after it. + const since = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"), eq(releases.status, "healthy"), prod ? sql`${releases.id} > ${prod.id}` : undefined)); + const taskKeys = [...new Set([...since.flatMap((r) => r.tasks), ...staging.tasks])].sort(); + const tag = `deploy-prod-${new Date().toISOString().replace(/\D/g, "").slice(0, 17)}`; + await gitea.createTag(project.giteaOwner, project.giteaRepo, tag, staging.sha, `Прод по кнопке: ${by}`); + const [rel] = await db + .insert(releases) + .values({ projectId: project.id, env: "prod", sha: staging.sha, previousSha: prod?.sha ?? null, image: staging.image, tasks: taskKeys, status: "deploying", deployedBy: by }) + .returning(); + return rel!; +} + +/** The PM pressed "deploy to prod" on a "staging updated" message (any channel). */ +export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: string): Promise<boolean> { + if (q.taskId || q.sessionId || !(q.options ?? []).includes(PROD_OPTION) || answer.trim() !== PROD_OPTION) return false; + const [project] = await db.select().from(projects).where(eq(projects.id, q.projectId)); + if (!project) return false; + try { + await deployProd(db, project, by); + } catch (e) { + await askPmProject(db, project, { kind: "attention", text: `Прод не запущен: ${(e as Error).message}` }); + } + return true; +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 7f457f98..71e8ed88 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -14,3 +14,4 @@ export * from "./ci.ts"; export * from "./incidents.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; +export * from "./deploy.ts"; diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 8fa5bdcd..86601e24 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -22,6 +22,7 @@ import { trustWorkspace } from "./claude-config.ts"; import { buildCommand, type Provider } from "./providers.ts"; import { runDir } from "./run-settings.ts"; import * as tmux from "./tmux.ts"; +import { onReleaseAnswer } from "./deploy.ts"; export interface StartOptions { /** Extra instructions appended to the default "work on <task>" prompt. */ @@ -179,6 +180,8 @@ export async function answerAndDeliver( message = `Ответ PM на вопрос #${q.id}: ${answer}`; } + // "Deploy to prod" on a "staging updated" message (PEP-57). + if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q }; if (!q.sessionId) return { delivered: false, question: q }; const s = await getSession(db, q.sessionId); if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q }; diff --git a/packages/testkit/bin/mock-docker b/packages/testkit/bin/mock-docker new file mode 100755 index 00000000..0a37532d --- /dev/null +++ b/packages/testkit/bin/mock-docker @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# mock-docker — stands in for the docker CLI in .gitea/peppa-deploy.sh tests (first on PATH). +# Same calls and exit codes as the script uses from real docker; state lives in +# $MOCK_DOCKER_STATE: images (one tag per line), containers/<name> (its image), calls.log. +# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail. +set -uo pipefail +st="${MOCK_DOCKER_STATE:?MOCK_DOCKER_STATE is required}" +mkdir -p "$st/containers" +touch "$st/images" +echo "docker $*" >> "$st/calls.log" +case "$1" in + inspect) # docker inspect -f '{{.Config.Image}}' <container> + c="${@: -1}" + [[ -f "$st/containers/$c" ]] || { echo "Error: No such object: $c" >&2; exit 1; } + cat "$st/containers/$c" ;; + image) + case "$2" in + inspect) grep -qxF "$3" "$st/images" || { echo "Error: No such image: $3" >&2; exit 1; }; echo "[{}]" ;; + prune) exit 0 ;; + esac ;; + build) # docker build -t <image> ... + [[ -n "${MOCK_DOCKER_BUILD_FAIL:-}" ]] && { echo "mock build failed" >&2; exit 1; } + shift; while [[ $# -gt 0 ]]; do [[ $1 == -t ]] && { echo "$2" >> "$st/images"; break; }; shift; done + echo "Successfully built" ;; + compose) # docker compose -p <project> -f <file> <up|down|run> ... + shift; project=""; while [[ $# -gt 0 ]]; do case "$1" in -p) project="$2"; shift 2 ;; -f) shift 2 ;; *) break ;; esac; done + svc="${MOCK_DOCKER_SERVICE:-web}" + case "$1" in + up) grep -qxF "$IMAGE" "$st/images" || { echo "pull access denied for $IMAGE" >&2; exit 1; } + echo "$IMAGE" > "$st/containers/$project-$svc-1"; echo "Container $project-$svc-1 Started" ;; + down) rm -f "$st/containers/$project-"*; echo "Removed $project" ;; + run) echo "ran in $IMAGE: ${*: -1}" ;; + esac ;; + *) echo "mock-docker: unsupported: $*" >&2; exit 1 ;; +esac diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index e587790d..1fa3591f 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -60,7 +60,12 @@ export class MockGitea { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { - const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {}); + let r: { status: number; body?: unknown }; + try { + r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {}); + } catch (e) { + r = { status: 422, body: { message: `mock-gitea: ${(e as Error).message.split("\n")[0]}` } }; + } res.writeHead(r.status, { "Content-Type": "application/json" }); res.end(r.body === undefined ? "" : JSON.stringify(r.body)); }); diff --git a/packages/testkit/test/deploy.test.ts b/packages/testkit/test/deploy.test.ts new file mode 100644 index 00000000..4b4edc3f --- /dev/null +++ b/packages/testkit/test/deploy.test.ts @@ -0,0 +1,241 @@ +// PEP-57, spec delivery-pipeline: «Деплой по окружениям» и «Проверка здоровья и откат». +// The template's .gitea/peppa-deploy.sh runs for real against mock-docker (docker CLI on +// PATH) and a mock health endpoint; it reports to Peppa through handleGiteaHook. +import assert from "node:assert/strict"; +import { execFile, execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-deploy-")); +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const gitea = new MockGitea(join(TMP, "gitea")); +const BOT = { id: 81, login: "peppa-bot", token: "mock-token-bot" }; +const SCRIPT = join(ROOT, "template/.gitea/peppa-deploy.sh"); + +// docker → mock-docker, first on PATH for the script. +const BIN = join(TMP, "bin"); +mkdirSync(BIN); +symlinkSync(join(ROOT, "packages/testkit/bin/mock-docker"), join(BIN, "docker")); + +let server: Server; +let base = ""; +/** Images whose app fails its health check. */ +const badImages = new Set<string>(); + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); + // One server: Peppa's /api/hooks/gitea and the deployed apps' /<project>/healthz. + server = createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", async () => { + if (req.url === "/api/hooks/gitea") { + const r = await runner.handleGiteaHook(db, { event: String(req.headers["x-peppa-event"]), signature: String(req.headers["x-gitea-signature"]), body }); + res.writeHead(r.status).end(JSON.stringify(r.body)); + return; + } + const [, stateDir, proj] = decodeURIComponent(req.url ?? "").match(/^\/state:([^:]+):([^/]+)\/healthz$/) ?? []; + const f = stateDir && join(stateDir, "containers", `${proj}-web-1`); + const image = f && existsSync(f) ? readFileSync(f, "utf8").trim() : null; + res.writeHead(image && !badImages.has(image) ? 200 : 503).end(); + }); + }); + await new Promise<void>((r) => server.listen(0, "127.0.0.1", r)); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); +after(async () => { + server.close(); + await gitea.stop(); + await teardown(); +}); + +/** A project with deploy settings, its repo checked out as the CI job sees it. */ +async function deployable(deploy: object | null = { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" }) { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + const work = join(TMP, `work-${p.key}`); + const state = join(TMP, `docker-${p.key}`); + mkdirSync(join(work, ".peppa"), { recursive: true }); + mkdirSync(join(work, "deploy")); + writeFileSync(join(work, "deploy/compose.yml"), readFileSync(join(ROOT, "template/deploy/compose.yml"))); + writeFileSync(join(work, "Dockerfile"), "FROM scratch\n"); + writeFileSync(join(work, ".peppa/project.json"), JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: base, ...(deploy ? { deploy } : {}) })); + const git = (...a: string[]) => execFileSync("git", ["-C", work, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim(); + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-qm", "init"); + const repo = gitea.addRepo(proj.giteaOwner, proj.giteaRepo); + repo.collaborators[BOT.login] = "write"; + /** A merge of a task branch into main, pushed to Gitea; returns its SHA. */ + const merge = (task: string) => { + writeFileSync(join(work, `${task}.txt`), task); + git("add", "-A"); + git("commit", "-qm", `Merge pull request '${task}' (#1) from task/${task} into main`); + git("push", "-q", repo.path, "main"); + return git("rev-parse", "HEAD"); + }; + const run = (mode: string, sha: string, extra: Record<string, string> = {}) => + new Promise<{ code: number; out: string }>((done) => { + git("checkout", "-q", sha); + const env = { + ...process.env, + PATH: `${BIN}:${process.env.PATH}`, + MOCK_DOCKER_STATE: state, + PEPPA_SHA: sha, + PEPPA_CI_SECRET: core.projectHookSecret(proj.id), + PEPPA_HEALTH_BASE: `${base}/state:${state}:{project}`, + PEPPA_HEALTH_TIMEOUT: "2", + PEPPA_HEALTH_INTERVAL: "0.3", + GITHUB_REPOSITORY: `${proj.giteaOwner}/${proj.giteaRepo}`, + GITHUB_RUN_NUMBER: "5", + ...extra, + }; + execFile("bash", [SCRIPT, mode], { cwd: work, env, encoding: "utf8" }, (err, stdout, stderr) => { + git("checkout", "-q", "main"); + done({ code: err ? Number((err as { code?: number }).code ?? 1) : 0, out: stdout + stderr }); + }); + }); + const container = (env: string) => { + const f = join(state, "containers", `${proj.slug}-${env}-web-1`); + return existsSync(f) ? readFileSync(f, "utf8").trim() : null; + }; + const calls = () => (existsSync(join(state, "calls.log")) ? readFileSync(join(state, "calls.log"), "utf8") : ""); + return { p, proj, merge, run, container, calls }; +} + +async function releases(projectId: number) { + return (await runner.listReleases(db, projectId, 50)).reverse(); +} + +describe("Деплой по окружениям", () => { + test("Scenario: Staging после мержа — образ с тегом коммита на staging, релиз со списком задач", async () => { + const d = await deployable(); + const sha = d.merge(`${d.p.key}-7`); + const r = await d.run("staging", sha); + assert.equal(r.code, 0, r.out); + assert.equal(d.container("staging"), `peppa/${d.proj.slug}:${sha}`); + const [rel] = await releases(d.proj.id); + assert.equal(rel!.env, "staging"); + assert.equal(rel!.status, "healthy"); + assert.equal(rel!.sha, sha); + assert.equal(rel!.host, `${d.proj.slug}-staging.telecom.quest`); + assert.deepEqual(rel!.tasks, [`${d.p.key}-7`]); + const offer = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION)); + assert.ok(offer, "the PM is offered to deploy to prod"); + assert.equal(offer.taskId, null); + }); + + test("Scenario: Прод по кнопке — тот же образ в проде, релиз прода с автором PM", async () => { + const d = await deployable(); + const sha = d.merge(`${d.p.key}-7`); + assert.equal((await d.run("staging", sha)).code, 0); + const rel = await runner.deployProd(db, d.proj, "mock-pm"); + assert.equal(rel.status, "deploying"); + const tag = gitea.repo(d.proj.giteaOwner, d.proj.giteaRepo).tags.at(-1)!; + assert.match(tag.name, /^deploy-prod-\d{17}$/); + assert.equal(tag.target, sha, "Peppa tags the healthy staging commit"); + // The tag starts the deploy workflow in prod mode. + const r = await d.run("prod", sha, { GITHUB_REF: `refs/tags/${tag.name}` }); + assert.equal(r.code, 0, r.out); + assert.equal(d.container("prod"), `peppa/${d.proj.slug}:${sha}`); + assert.equal(d.calls().match(/docker build/g)?.length, 1, "prod reuses the staging image"); + const prod = (await releases(d.proj.id)).filter((x) => x.env === "prod"); + assert.equal(prod.length, 1); + assert.equal(prod[0]!.status, "healthy"); + assert.equal(prod[0]!.deployedBy, "mock-pm"); + assert.deepEqual(prod[0]!.tasks, [`${d.p.key}-7`]); + await assert.rejects(runner.deployProd(db, d.proj, "mock-pm").then(() => runner.deployProd(db, d.proj, "mock-pm")), /уже выкатывается/); + }); + + test("Telegram button: answering the staging message with «Выкатить в прод» starts prod", async () => { + const d = await deployable(); + assert.equal((await d.run("staging", d.merge(`${d.p.key}-2`))).code, 0); + const offer = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION))!; + await runner.answerAndDeliver(db, offer.id, runner.PROD_OPTION, "telegram"); + const [prod] = (await releases(d.proj.id)).filter((x) => x.env === "prod"); + assert.equal(prod?.status, "deploying"); + assert.equal(prod?.deployedBy, "PM (telegram)"); + }); + + test("no healthy staging: nothing to deploy to prod", async () => { + const d = await deployable(); + await assert.rejects(runner.deployProd(db, d.proj, "mock-pm"), /на staging нет здорового релиза/); + }); + + test("preview on a PR, removed when the PR is closed", async () => { + const d = await deployable(); + const sha = d.merge(`${d.p.key}-3`); + assert.equal((await d.run("preview", sha, { PEPPA_PR: "3" })).code, 0); + assert.equal(d.container("pr3"), `peppa/${d.proj.slug}:${sha}`); + let [rel] = await releases(d.proj.id); + assert.equal(rel!.host, `${d.proj.slug}-pr3.telecom.quest`); + assert.equal(rel!.status, "healthy"); + assert.equal((await d.run("preview-down", sha, { PEPPA_PR: "3" })).code, 0); + assert.equal(d.container("pr3"), null); + [rel] = await releases(d.proj.id); + assert.equal(rel!.status, "removed"); + }); + + test("project without deploy settings: the step is skipped", async () => { + const d = await deployable(null); + const r = await d.run("staging", d.merge("x")); + assert.equal(r.code, 0); + assert.match(r.out, /деплой не настроен/); + assert.equal((await releases(d.proj.id)).length, 0); + }); +}); + +describe("Проверка здоровья и откат", () => { + test("Scenario: Неудачный релиз — прод возвращён на предыдущий, релиз помечен «откат», PM получает причину и лог", async () => { + const d = await deployable(); + const good = d.merge(`${d.p.key}-1`); + assert.equal((await d.run("prod", good)).code, 0); + const bad = d.merge(`${d.p.key}-2`); + badImages.add(`peppa/${d.proj.slug}:${bad}`); + const r = await d.run("prod", bad); + assert.equal(r.code, 1); + assert.equal(d.container("prod"), `peppa/${d.proj.slug}:${good}`, "prod is back on the previous release"); + const rel = (await releases(d.proj.id)).find((x) => x.sha === bad)!; + assert.equal(rel.status, "rolled_back"); + assert.equal(rel.previousSha, good); + assert.match(rel.reason ?? "", /проверка \/healthz не прошла за 2 с/); + assert.deepEqual(rel.tasks, [`${d.p.key}-2`], "only what was merged since the previous release"); + const msg = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.text.includes(bad.slice(0, 7)) && q.text.includes("не прошёл"))!; + assert.ok(msg, "the PM got a message"); + assert.match(msg.text, new RegExp(`возвращён ${good.slice(0, 7)}`)); + assert.match(msg.text, /Причина: проверка \/healthz/); + assert.match(msg.text, new RegExp(`Лог: ${gitea.url}/test/${d.proj.giteaRepo}/actions/runs/5`)); + assert.equal((await runner.currentReleases(db, d.proj.id)).prod?.sha, good); + }); + + test("first release fails its health check: nothing to roll back to, release failed", async () => { + const d = await deployable(); + const sha = d.merge("first"); + badImages.add(`peppa/${d.proj.slug}:${sha}`); + assert.equal((await d.run("staging", sha)).code, 1); + const [rel] = await releases(d.proj.id); + assert.equal(rel!.status, "failed"); + assert.match(rel!.reason ?? "", /откатывать не на что/); + }); + + test("image build fails: release failed, the running stand is untouched", async () => { + const d = await deployable(); + const good = d.merge("a"); + assert.equal((await d.run("staging", good)).code, 0); + const r = await d.run("staging", d.merge("b"), { MOCK_DOCKER_BUILD_FAIL: "1" }); + assert.equal(r.code, 1); + assert.equal(d.container("staging"), `peppa/${d.proj.slug}:${good}`); + assert.equal((await releases(d.proj.id)).at(-1)!.reason, "сборка образа не удалась"); + }); +}); diff --git a/template/.gitea/peppa-deploy.sh b/template/.gitea/peppa-deploy.sh new file mode 100644 index 00000000..98eabe51 --- /dev/null +++ b/template/.gitea/peppa-deploy.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +# Деплой проекта Пеппы: bash .gitea/peppa-deploy.sh <preview|staging|prod|preview-down> +# Образ peppa/<slug>:<sha> собирается из Dockerfile (deploy.dockerfile) на docker хоста, +# поднимается `docker compose -p <slug>-<окружение>` за Traefik, затем проверка здоровья +# (deploy.health, по умолчанию /healthz, PEPPA_HEALTH_TIMEOUT секунд, по умолчанию 120). +# Не прошла — откат на образ, который работал до этого. Итог уходит в Пеппу (подпись +# PEPPA_CI_SECRET): окружение, SHA, предыдущий SHA, коммиты (для списка задач), хвост лога. +set -uo pipefail +mode="$1" +cfg=.peppa/project.json +compose=$(jq -r '.deploy.compose // empty' "$cfg" 2>/dev/null) +if [[ -z "$compose" || ! -f "$compose" ]]; then + echo "peppa: деплой не настроен (.peppa/project.json → deploy.compose) — пропуск" + exit 0 +fi +slug=$(jq -r '.slug' "$cfg") +service=$(jq -r '.deploy.service // "web"' "$cfg") +port=$(jq -r '.deploy.port // 3000' "$cfg") +health=$(jq -r '.deploy.health // "/healthz"' "$cfg") +migrate=$(jq -r '.deploy.migrate // empty' "$cfg") +dockerfile=$(jq -r '.deploy.dockerfile // "Dockerfile"' "$cfg") +domain="${PEPPA_DEPLOY_DOMAIN:-telecom.quest}" +timeout="${PEPPA_HEALTH_TIMEOUT:-120}" +sha="${PEPPA_SHA:-${GITHUB_SHA:-$(git rev-parse HEAD)}}" +pr="${PEPPA_PR:-}" + +env_name="$mode" +[[ $mode == preview-down ]] && env_name=preview +# Один уровень поддомена: сертификат Cloudflare покрывает только *.telecom.quest. +case "$env_name" in + preview) project="$slug-pr$pr"; host="$slug-pr$pr.$domain" ;; + staging) project="$slug-staging"; host="$slug-staging.$domain" ;; + prod) project="$slug-prod"; host="$slug-prod.$domain" ;; + *) echo "usage: peppa-deploy.sh <preview|staging|prod|preview-down>" >&2; exit 2 ;; +esac +custom=$(jq -r --arg e "$env_name" '.deploy.hosts[$e] // empty' "$cfg") +[[ -n "$custom" ]] && host="${custom//\{pr\}/$pr}" +image="peppa/$slug:$sha" +router=$(tr -c 'a-zA-Z0-9\n' - <<<"$project") +container="$project-$service-1" +log=$(mktemp) +exec > >(tee -a "$log") 2>&1 + +prev_image=$(docker inspect -f '{{.Config.Image}}' "$container" 2>/dev/null || true) +prev_sha="" +[[ $prev_image == peppa/$slug:* ]] && prev_sha="${prev_image##*:}" + +report() { # report <status> [reason] + local status="$1" reason="${2:-}" peppa_url commits body sig + echo "peppa: $env_name $status${reason:+ — $reason}" + peppa_url=$(jq -r '.peppaUrl // empty' "$cfg") + [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]] || return 0 + if [[ -n "$prev_sha" ]] && git cat-file -e "$prev_sha^{commit}" 2>/dev/null; then + commits=$(git log --format=%s "$prev_sha..$sha" 2>/dev/null | head -n 200 | jq -Rsc 'split("\n") | map(select(. != ""))') + else + commits=$(git log --format=%s -n 20 "$sha" 2>/dev/null | jq -Rsc 'split("\n") | map(select(. != ""))') + fi + body=$(tail -n 200 "$log" | jq -Rs --arg repo "${GITHUB_REPOSITORY:-}" --arg env "$env_name" --arg sha "$sha" \ + --arg prev "$prev_sha" --arg image "$image" --arg host "$host" --arg pr "$pr" --arg status "$status" \ + --arg reason "$reason" --arg url "/${GITHUB_REPOSITORY:-}/actions/runs/${GITHUB_RUN_NUMBER:-0}" --arg ref "${GITHUB_REF:-}" \ + --argjson commits "${commits:-[]}" \ + '{repository:$repo, env:$env, sha:$sha, previous_sha:(if $prev == "" then null else $prev end), image:$image, host:$host, + pr:($pr|tonumber? // null), status:$status, reason:(if $reason == "" then null else $reason end), run_url:$url, ref:$ref, + commits:$commits, log_tail:.}') + sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}') + curl -fsS -o /dev/null -m 20 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \ + -H "X-Peppa-Event: deploy" -H "X-Gitea-Signature: $sig" --data-binary "$body" || + echo "peppa: Пеппа недоступна — релиз не записан" +} + +dc() { # dc <image> <compose args…> + local img="$1"; shift + IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@" +} + +healthy() { + local url="${PEPPA_HEALTH_BASE:-http://$container:$port}" deadline=$((SECONDS + timeout)) + url="${url//\{project\}/$project}$health" + while ((SECONDS < deadline)); do + curl -fsS -o /dev/null -m 5 "$url" && return 0 + sleep "${PEPPA_HEALTH_INTERVAL:-3}" + done + return 1 +} + +if [[ $mode == preview-down ]]; then + dc "$image" down --remove-orphans || true + report removed + exit 0 +fi + +report deploying +if ! docker image inspect "$image" >/dev/null 2>&1; then + docker build -t "$image" --label "peppa.project=$slug" -f "$dockerfile" . || { report failed "сборка образа не удалась"; exit 1; } +fi +if [[ -n "$migrate" ]]; then + dc "$image" run --rm "$service" sh -c "$migrate" || { report failed "миграция не удалась"; exit 1; } +fi +dc "$image" up -d --remove-orphans || { report failed "docker compose up не удался"; exit 1; } +if healthy; then + report healthy + docker image prune -af --filter "label=peppa.project=$slug" --filter "until=336h" >/dev/null 2>&1 || true + exit 0 +fi +why="проверка $health не прошла за ${timeout} с" +if [[ -n "$prev_image" && "$prev_image" != "$image" ]]; then + echo "peppa: $why — откат на $prev_image" + if dc "$prev_image" up -d --remove-orphans && healthy; then + report rolled_back "$why" + else + report failed "$why; откат на $prev_image тоже не поднялся" + fi +else + report failed "$why; откатывать не на что" +fi +exit 1 diff --git a/template/.gitea/workflows/deploy.yml b/template/.gitea/workflows/deploy.yml new file mode 100644 index 00000000..7400926c --- /dev/null +++ b/template/.gitea/workflows/deploy.yml @@ -0,0 +1,35 @@ +# CD проекта Пеппы (PEP-57): preview на PR (удаляется при закрытии), staging на мерж в main, +# прод — тег deploy-prod-* (его ставит Пеппа по кнопке PM). Настройки — .peppa/project.json → +# "deploy"; без них шаг пропускается. Изменение файла PM видит отдельно. +name: deploy +on: + push: + branches: [main] + tags: ["deploy-prod-*"] + pull_request: + types: [opened, synchronize, reopened, closed] +env: + PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }} + PEPPA_PR: ${{ github.event.pull_request.number }} + PEPPA_PR_ACTION: ${{ github.event.action }} + PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }} + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} +jobs: + deploy: + # Раннер с docker.sock хоста: только ветки этого репозитория, PR из форков не запускаются. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: peppa-trusted + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.PEPPA_SHA }} + fetch-depth: 0 + - name: deploy + run: | + if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then + [[ "$PEPPA_PR_ACTION" == closed ]] && exec bash .gitea/peppa-deploy.sh preview-down + exec bash .gitea/peppa-deploy.sh preview + fi + [[ "$GITHUB_REF" == refs/tags/deploy-prod-* ]] && exec bash .gitea/peppa-deploy.sh prod + exec bash .gitea/peppa-deploy.sh staging diff --git a/template/RULES.md b/template/RULES.md index 84829fae..dd7c0e47 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -86,6 +86,24 @@ PM отвечает только на **архитектурные стоппе отдельно, такой PR не мержится автоматически — опиши в PR, зачем это нужно. - Задача попадает в ревью и мержится только с зелёными проверками последнего коммита. +## CD: деплой + +Деплой описывает `.peppa/project.json` → `deploy` и `Dockerfile` в корне (заготовки — +`deploy/Dockerfile.node`, `deploy/Dockerfile.python`; стенд — `deploy/compose.yml`): + +```json +{ "deploy": { "compose": "deploy/compose.yml", "service": "web", "port": 3000, + "health": "/healthz", "migrate": "pnpm db:migrate" } } +``` + +- Приложение слушает `$PORT` и отвечает 200 на `GET /healthz` (`deploy.health`) — без этого + деплой считается неудачным и откатывается. +- PR получает preview `<slug>-pr<N>.telecom.quest`, мерж в main — staging + `<slug>-staging.telecom.quest`, прод `<slug>-prod.telecom.quest` выкатывает только PM. +- Проверить локально: `docker build .` и запуск образа с `PORT=3000`, затем `curl /healthz`. +- Секреты приложения — не в репозиторий: попроси PM через `ask_pm` завести их в secrets + Actions репозитория и передай в `deploy/compose.yml` через `environment`. + ## Спецификации — сценарии в формате Gherkin Требования в `specs/**/spec.md` пиши как раньше (`### Requirement:` + текст с SHALL), а diff --git a/template/deploy/Dockerfile.node b/template/deploy/Dockerfile.node new file mode 100644 index 00000000..5854142d --- /dev/null +++ b/template/deploy/Dockerfile.node @@ -0,0 +1,16 @@ +# Заготовка для Node.js (pnpm). Скопируй в ./Dockerfile и поправь под проект. +# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health). +FROM node:22-bookworm-slim AS build +WORKDIR /app +RUN corepack enable +COPY package.json pnpm-lock.yaml* ./ +RUN pnpm install --frozen-lockfile +COPY . . +RUN pnpm build + +FROM node:22-bookworm-slim +WORKDIR /app +ENV NODE_ENV=production PORT=3000 +COPY --from=build /app ./ +EXPOSE 3000 +CMD ["node", "dist/index.js"] diff --git a/template/deploy/Dockerfile.python b/template/deploy/Dockerfile.python new file mode 100644 index 00000000..b2dbc0ec --- /dev/null +++ b/template/deploy/Dockerfile.python @@ -0,0 +1,10 @@ +# Заготовка для Python. Скопируй в ./Dockerfile и поправь под проект. +# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health). +FROM python:3.12-slim +WORKDIR /app +ENV PYTHONUNBUFFERED=1 PORT=3000 +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY . . +EXPOSE 3000 +CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT}"] diff --git a/template/deploy/compose.yml b/template/deploy/compose.yml new file mode 100644 index 00000000..01936ba5 --- /dev/null +++ b/template/deploy/compose.yml @@ -0,0 +1,21 @@ +# Стенд проекта Пеппы (PEP-57). Деплой: docker compose -p <slug>-<env> -f deploy/compose.yml up -d +# с переменными IMAGE (образ peppa/<slug>:<sha>), HOST, ROUTER, APP_PORT — их задаёт +# .gitea/peppa-deploy.sh. Сервис и порт — .peppa/project.json → deploy.service / deploy.port. +# Секреты приложения — в secrets Actions репозитория, сюда только через environment. +services: + web: + image: ${IMAGE} + restart: unless-stopped + environment: + PORT: "${APP_PORT:-3000}" + networks: + - traefik_default + labels: + - traefik.enable=true + - traefik.docker.network=traefik_default + - traefik.http.routers.${ROUTER}.rule=Host(`${HOST}`) + - traefik.http.routers.${ROUTER}.entrypoints=web + - traefik.http.services.${ROUTER}.loadbalancer.server.port=${APP_PORT:-3000} +networks: + traefik_default: + external: true -- 2.45.2 From c964a00c21da8dcf95d5c81b8fe6dc96d8ac7e4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:53:34 +0500 Subject: [PATCH 004/536] PEP-57: MCP tool list in the OAuth test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/testkit/test/incidents.test.ts | 3 ++- packages/testkit/test/oauth.test.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/testkit/test/incidents.test.ts b/packages/testkit/test/incidents.test.ts index fd07e926..b82bb807 100644 --- a/packages/testkit/test/incidents.test.ts +++ b/packages/testkit/test/incidents.test.ts @@ -503,7 +503,8 @@ describe("MCP для PM", () => { await bugsink.capture(c.api, { ...AMOUNT, value: "via mcp" }); const i = await waitIncident(c, "TypeError: via mcp", (x) => x.status === "pending"); assert.match(await call("list_incidents", { project: c.key, status: "pending" }), new RegExp(`#${i.id} \\[pending\\] TypeError: via mcp`)); - assert.match(await call("decide_incident", { id: i.id, action: "backlog" }), /created in the backlog/); + assert.match(await call("decide_incident", + "deploy", { id: i.id, action: "backlog" }), /created in the backlog/); assert.match(await call("resolve_incident", { id: i.id }), /Incident #\d+ resolved/); await waitFor("ask message closed", async () => pmMessages("via mcp").some((m) => m.text.includes("Решено (mock-pm): в бэклог"))); }); diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 53794896..3da211ab 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -99,7 +99,7 @@ describe("PM tools over MCP", () => { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_goal", "create_project", "create_task", "decide_incident", "get_incident", "get_incident_policy", "get_task", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "update_goal", "update_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "update_goal", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); -- 2.45.2 From 56a7756e712d8c37d49c971385f9a91d41bf56cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:01:45 +0500 Subject: [PATCH 005/536] PEP-22: scripts/ci.sh, PR status peppa/ci, mock-act-runner Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 3 +- infra/ci/peppa-ci.yml | 16 ++++ openspec/changes/pep-22-peppa-ci/proposal.md | 52 +++++++++++++ .../pep-22-peppa-ci/specs/peppa-ci/spec.md | 77 +++++++++++++++++++ openspec/changes/pep-22-peppa-ci/tasks.md | 10 +++ package.json | 3 +- scripts/ci.sh | 76 ++++++++++++++++++ scripts/lib/ci-env.sh | 6 ++ scripts/mock-act-runner.sh | 43 +++++++++++ 9 files changed, 284 insertions(+), 2 deletions(-) create mode 100644 infra/ci/peppa-ci.yml create mode 100644 openspec/changes/pep-22-peppa-ci/proposal.md create mode 100644 openspec/changes/pep-22-peppa-ci/specs/peppa-ci/spec.md create mode 100644 openspec/changes/pep-22-peppa-ci/tasks.md create mode 100755 scripts/ci.sh create mode 100644 scripts/lib/ci-env.sh create mode 100755 scripts/mock-act-runner.sh diff --git a/AGENTS.md b/AGENTS.md index a23dcfda..fe144519 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,8 @@ - `pnpm dev:web` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` -- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (отдельная БД `peppa_test`, свой tmux `-L`, свой `PEPPA_HOME`) +- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **Перед мержем PR платформы**: `scripts/ci.sh --pr <N>` — проверка головы PR во временном worktree, статус `peppa/ci` в Gitea; мержить только при `success`. `scripts/mock-act-runner.sh [--loop 120]` — заменитель act_runner (проходит по открытым PR без статуса); настоящий workflow лежит в `infra/ci/peppa-ci.yml` и ждёт раннера +- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`) - **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу diff --git a/infra/ci/peppa-ci.yml b/infra/ci/peppa-ci.yml new file mode 100644 index 00000000..a8fd843f --- /dev/null +++ b/infra/ci/peppa-ci.yml @@ -0,0 +1,16 @@ +# Gitea Actions workflow for Peppa itself (PEP-22). Not active yet: there is no act_runner for +# peppa-bot/peppa. To enable, register a runner with label `peppa-host` (host mode: e2e needs +# tmux, docker exec into peppa-postgres and Postgres on 127.0.0.1:5433) and copy this file to +# .gitea/workflows/ci.yml. Until then scripts/mock-act-runner.sh sets the same `peppa/ci` status. +name: peppa/ci +on: + pull_request: + push: + branches: [main] +jobs: + ci: + runs-on: peppa-host + steps: + - uses: actions/checkout@v4 + - run: pnpm install --frozen-lockfile --prefer-offline + - run: bash scripts/ci.sh diff --git a/openspec/changes/pep-22-peppa-ci/proposal.md b/openspec/changes/pep-22-peppa-ci/proposal.md new file mode 100644 index 00000000..6d2591e7 --- /dev/null +++ b/openspec/changes/pep-22-peppa-ci/proposal.md @@ -0,0 +1,52 @@ +# Proposal: PEP-22 — CI для самой Пеппы и стабильность тестов + +Задача Пеппы: **PEP-22** · Цель #6 «Безопасность и эксплуатация». + +## Why + +e2e-набор гоняется руками перед мержем, PR в `peppa-bot/peppa` не несут никакой отметки о +проверке, а параллельные сессии в разных worktree делили одну тестовую БД и роняли друг +другу тесты. Нужна одна команда проверки, отметка статуса в PR и стабильный набор. + +## What Changes + +- **`scripts/ci.sh`** (и `pnpm run ci`): `pnpm -r typecheck` → `next build` веба → e2e на + моках. Каждый прогон — своя БД `peppa_test_ci_<pid>`, удаляется при выходе. + `--repeat N` гоняет e2e N раз подряд (поиск флаков), `--skip-build` пропускает сборку. +- **`scripts/ci.sh --pr N`**: проверка головы PR в отдельном временном worktree, статус + коммита `peppa/ci` в Gitea (`pending` → `success`/`failure` с длительностью или упавшим + шагом), лог в `~/.peppa/ci/<sha>.log`. Статус виден в PR. +- **`scripts/mock-act-runner.sh`**: заменитель act_runner, пока раннер Gitea Actions не + зарегистрирован, — проходит по открытым PR без статуса `peppa/ci` и запускает для них + `ci.sh --pr`. Не сервис: разовый проход или `--loop` в терминале. +- **`infra/ci/peppa-ci.yml`**: готовый workflow Gitea Actions (тот же `scripts/ci.sh`) — + лежит вне `.gitea/workflows`, иначе без раннера каждый PR висел бы в «Waiting». +- **Стабильность**: `PEPPA_TEST_DB` (уже в main) + починка найденных флаков; набор гоняется + несколько раз подряд. +- **Правила**: в `AGENTS.md` — перед мержем PR платформы `scripts/ci.sh --pr N`, мерж + только при `success`. + +## Решения PM (стоппер для настоящего CI в Gitea) + +Раннер Gitea Actions требует установки сервиса на машину (act_runner в docker/launchd с +доступом к docker и Postgres) — без PM не ставим. Что нужно: +1. Разрешить запуск `act_runner` (контейнер рядом с `gitea`, label `peppa-host`, host-режим — + e2e нужны tmux и Postgres на 127.0.0.1:5433). +2. Получить registration token репозитория (бот — админ репо, токен выдаётся API) и + зарегистрировать раннер. +3. Перенести `infra/ci/peppa-ci.yml` в `.gitea/workflows/ci.yml`; при желании — защита + ветки `main` с обязательной проверкой. + +Это не PEP-57 (CI/CD для проектов фабрики) — здесь только сама Пеппа. + +## Capabilities + +### New Capabilities +- `peppa-ci`: проверка платформы одной командой, статус проверки в PR, изоляция тестовых прогонов. + +### Modified Capabilities + +## Impact + +`scripts/` (ci.sh, mock-act-runner.sh, lib/ci-env.sh), `package.json` (`ci`), `infra/ci/`, +`packages/testkit` (флаки), `AGENTS.md`. БД, сервисы и launchd не меняются. diff --git a/openspec/changes/pep-22-peppa-ci/specs/peppa-ci/spec.md b/openspec/changes/pep-22-peppa-ci/specs/peppa-ci/spec.md new file mode 100644 index 00000000..b3fd21f1 --- /dev/null +++ b/openspec/changes/pep-22-peppa-ci/specs/peppa-ci/spec.md @@ -0,0 +1,77 @@ +# Spec Delta: peppa-ci + +## ADDED Requirements + +### Requirement: Проверка платформы одной командой +`scripts/ci.sh` (`pnpm run ci`) SHALL выполнять typecheck всех пакетов, сборку веба и e2e-набор +на моках, останавливаться на первом упавшем шаге с ненулевым кодом и использовать для e2e +собственную тестовую БД, которую удаляет по завершении. + +#### Scenario: Всё зелёное +- **GIVEN** рабочая копия без ошибок типов и с проходящими тестами +- **WHEN** разработчик запускает `scripts/ci.sh` +- **THEN** выводятся строки «ci: ok typecheck», «ci: ok web build», «ci: ok e2e 1/1» и «ci: all green» +- **AND** код выхода 0, БД `peppa_test_ci_<pid>` после выхода не существует + +#### Scenario: Ошибка типов +- **GIVEN** в пакете есть ошибка TypeScript +- **WHEN** разработчик запускает `scripts/ci.sh` +- **THEN** выводится «ci: FAIL typecheck», сборка и e2e не запускаются +- **AND** код выхода 1 + +#### Scenario: Поиск флаков +- **GIVEN** набор проходит стабильно +- **WHEN** разработчик запускает `scripts/ci.sh --skip-build --repeat 3` +- **THEN** e2e выполняется три раза подряд («ci: ok e2e 1/3» … «ci: ok e2e 3/3»), сборка веба пропущена + +### Requirement: Статус проверки в PR +`scripts/ci.sh --pr <N>` SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном +временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем +`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. + +#### Scenario: Зелёный PR +- **GIVEN** открыт PR 15, его голова проходит все проверки +- **WHEN** запускается `scripts/ci.sh --pr 15` +- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in <N> min» +- **AND** лог прогона лежит в `~/.peppa/ci/<sha>.log`, временный worktree удалён + +#### Scenario: Красный PR +- **GIVEN** открыт PR 16, в его голове падает e2e +- **WHEN** запускается `scripts/ci.sh --pr 16` +- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу +- **AND** код выхода 1 + +#### Scenario: Нет такого PR +- **GIVEN** в репозитории нет PR 999 +- **WHEN** запускается `scripts/ci.sh --pr 999` +- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 + +### Requirement: Заменитель раннера Gitea Actions +Пока act_runner не зарегистрирован, `scripts/mock-act-runner.sh` SHALL находить открытые PR, +у головного коммита которых нет статуса `peppa/ci`, и запускать для каждого `ci.sh --pr`; +PR, уже имеющие статус, повторно не проверяются. + +#### Scenario: Новый PR +- **GIVEN** открыт PR 17 без статуса `peppa/ci` +- **WHEN** запускается `scripts/mock-act-runner.sh` +- **THEN** выводится «mock-act-runner: PR 17 @ <sha>» и у коммита появляется статус `peppa/ci` + +#### Scenario: Уже проверенный PR +- **GIVEN** у головы PR 17 уже есть статус `peppa/ci` +- **WHEN** запускается `scripts/mock-act-runner.sh --dry-run` +- **THEN** PR 17 в выводе отсутствует + +### Requirement: Изоляция тестовых прогонов +e2e-набор SHALL работать в БД из `PEPPA_TEST_DB` (по умолчанию `peppa_test`), со своим tmux-сервером +и `PEPPA_HOME`, так что наборы из разных worktree идут одновременно без взаимных падений, и +SHALL проходить несколько раз подряд без флаков. + +#### Scenario: Два набора одновременно +- **GIVEN** в одном worktree идёт набор с `PEPPA_TEST_DB=peppa_test_a` +- **WHEN** в другом запускается набор с `PEPPA_TEST_DB=peppa_test_b` +- **THEN** оба набора зелёные + +#### Scenario: Повторные прогоны +- **GIVEN** main без изменений +- **WHEN** набор прогоняется 5 раз подряд +- **THEN** все 5 прогонов зелёные diff --git a/openspec/changes/pep-22-peppa-ci/tasks.md b/openspec/changes/pep-22-peppa-ci/tasks.md new file mode 100644 index 00000000..21c9a5d7 --- /dev/null +++ b/openspec/changes/pep-22-peppa-ci/tasks.md @@ -0,0 +1,10 @@ +# Tasks: PEP-22 + +- [ ] 1.1 `PEPPA_TEST_DB` в testkit (своя БД на прогон) +- [ ] 1.2 `scripts/ci.sh` (typecheck, web build, e2e, `--repeat`, `--skip-build`) и `pnpm run ci` +- [ ] 1.3 `scripts/ci.sh --pr N`: временный worktree, статус `peppa/ci` в Gitea, лог в `~/.peppa/ci` +- [ ] 1.4 `scripts/mock-act-runner.sh` — заменитель act_runner +- [ ] 1.5 `infra/ci/peppa-ci.yml` + инструкция для PM по раннеру +- [ ] 2.1 Прогнать набор 5 раз подряд, найти и починить флаки +- [ ] 2.2 Правило в `AGENTS.md`: перед мержем `ci.sh --pr N`, мерж только при `success` +- [ ] 2.3 `openspec validate`, проверка на своём PR, archive diff --git a/package.json b/package.json index 6e14f012..af1109a4 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "db:down": "docker compose -f infra/docker-compose.yml down", "db:generate": "pnpm --filter @peppa/db generate", "db:migrate": "pnpm --filter @peppa/db migrate", - "typecheck": "pnpm -r typecheck" + "typecheck": "pnpm -r typecheck", + "ci": "bash scripts/ci.sh" }, "devDependencies": { "@types/node": "26.6.6", diff --git a/scripts/ci.sh b/scripts/ci.sh new file mode 100755 index 00000000..b2ebb9e9 --- /dev/null +++ b/scripts/ci.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# CI for Peppa itself (PEP-22): typecheck, web build, e2e on mocks. +# +# scripts/ci.sh checks of this checkout (also `pnpm run ci`) +# scripts/ci.sh --pr <N> checks of PR head N in peppa-bot/peppa in a temp worktree, +# with commit status `peppa/ci` in Gitea (pending → success/failure) +# scripts/ci.sh --repeat <N> run the e2e suite N times in a row (flake hunting) +# scripts/ci.sh --skip-build skip `next build` +# +# Every run uses its own database peppa_test_ci_<pid> (dropped at exit), so it can run next +# to other worktrees' suites. Logs of --pr runs: ~/.peppa/ci/<sha>.log. +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +PR="" REPEAT=1 BUILD=1 +while [ $# -gt 0 ]; do + case "$1" in + --pr) PR=$2; shift 2 ;; + --repeat) REPEAT=$2; shift 2 ;; + --skip-build) BUILD=0; shift ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +if [ -n "$PR" ]; then + . "$ROOT/scripts/lib/ci-env.sh" + . "$ROOT/scripts/gitea-lib.sh" + REPO="${PEPPA_CI_REPO:-peppa-bot/peppa}" + CONTEXT="peppa/ci" + SHA=$(gitea_api "$GITEA_URL/api/v1/repos/$REPO/pulls/$PR" | python3 -c 'import json,sys;print(json.load(sys.stdin)["head"]["sha"])') \ + || { echo "PR $PR not found in $REPO" >&2; exit 2; } + status() { # <state> <description> + gitea_api -X POST "$GITEA_URL/api/v1/repos/$REPO/statuses/$SHA" \ + -d "{\"state\":\"$1\",\"context\":\"$CONTEXT\",\"description\":\"$2\"}" >/dev/null \ + || echo "warning: could not set commit status" >&2 + } + mkdir -p "$HOME/.peppa/ci" + LOG="$HOME/.peppa/ci/$SHA.log" + WT="$(mktemp -d)/peppa-ci" + git -C "$ROOT" fetch -q origin "refs/pull/$PR/head" || { echo "cannot fetch PR $PR" >&2; exit 2; } + git -C "$ROOT" worktree add -q --detach "$WT" "$SHA" || exit 2 + trap 'git -C "$ROOT" worktree remove --force "$WT" >/dev/null 2>&1' EXIT + ln -s "$ENV_FILE" "$WT/.env" 2>/dev/null + status pending "running typecheck, build, e2e" + start=$(date +%s) + args=(--repeat "$REPEAT"); [ "$BUILD" = 0 ] && args+=(--skip-build) + (cd "$WT" && pnpm install --frozen-lockfile --prefer-offline >/dev/null && bash scripts/ci.sh "${args[@]}") >"$LOG" 2>&1 + rc=$? + took=$(( ($(date +%s) - start) / 60 )) + if [ $rc = 0 ]; then + status success "passed in ${took} min" + else + status failure "$(grep -E '^ci: (FAIL|ok)' "$LOG" | tail -1 | cut -c5-) — log $LOG" + fi + tail -20 "$LOG" + echo "PR $PR @ ${SHA:0:8}: $([ $rc = 0 ] && echo success || echo failure), log $LOG" + exit $rc +fi + +cd "$ROOT" +DB="peppa_test_ci_$$" +cleanup() { docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; } +trap cleanup EXIT + +step() { # <name> <command...> + local name=$1; shift + echo "ci: ▶ $name" + local t=$(date +%s) + if "$@"; then echo "ci: ok $name ($(( $(date +%s) - t ))s)"; else echo "ci: FAIL $name"; exit 1; fi +} + +step typecheck pnpm -r typecheck +[ "$BUILD" = 1 ] && step "web build" pnpm --filter @peppa/web build +for i in $(seq 1 "$REPEAT"); do + step "e2e $i/$REPEAT" env PEPPA_TEST_DB="$DB" pnpm --filter @peppa/testkit test +done +echo "ci: all green" diff --git a/scripts/lib/ci-env.sh b/scripts/lib/ci-env.sh new file mode 100644 index 00000000..0365e0b5 --- /dev/null +++ b/scripts/lib/ci-env.sh @@ -0,0 +1,6 @@ +# Loads .env for the CI scripts: this checkout's, else the main checkout's (worktrees have none). +_ci_env="$ROOT/.env" +[ -f "$_ci_env" ] || _ci_env="$(dirname "$(git -C "$ROOT" rev-parse --path-format=absolute --git-common-dir)")/.env" +[ -f "$_ci_env" ] && set -a && . "$_ci_env" && set +a +ENV_FILE="$_ci_env" +unset _ci_env diff --git a/scripts/mock-act-runner.sh b/scripts/mock-act-runner.sh new file mode 100755 index 00000000..b8545a43 --- /dev/null +++ b/scripts/mock-act-runner.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Stand-in for Gitea Actions' act_runner until one is registered for peppa-bot/peppa (PEP-22): +# picks up open PRs whose head commit has no `peppa/ci` status yet and runs scripts/ci.sh --pr +# for each, which reports the status back like a workflow job would. +# +# scripts/mock-act-runner.sh one pass over open PRs +# scripts/mock-act-runner.sh --loop 120 keep polling every 120 s (foreground; not a service) +# scripts/mock-act-runner.sh --dry-run only list PRs that would be checked +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +. "$ROOT/scripts/lib/ci-env.sh" +. "$ROOT/scripts/gitea-lib.sh" +REPO="${PEPPA_CI_REPO:-peppa-bot/peppa}" +LOOP="" DRY=0 +while [ $# -gt 0 ]; do + case "$1" in + --loop) LOOP=$2; shift 2 ;; + --dry-run) DRY=1; shift ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +# Prints "<number> <sha>" for open PRs without a peppa/ci status on their head. +pending_prs() { + gitea_api "$GITEA_URL/api/v1/repos/$REPO/pulls?state=open&limit=50" | + python3 -c 'import json,sys +for p in json.load(sys.stdin): print(p["number"], p["head"]["sha"])' | + while read -r n sha; do + gitea_api "$GITEA_URL/api/v1/repos/$REPO/commits/$sha/statuses" | + python3 -c 'import json,sys; sys.exit(0 if any(s["context"]=="peppa/ci" for s in json.load(sys.stdin)) else 1)' || + echo "$n $sha" + done +} + +pass() { + pending_prs | while read -r n sha; do + echo "mock-act-runner: PR $n @ ${sha:0:8}" + [ "$DRY" = 1 ] || bash "$ROOT/scripts/ci.sh" --pr "$n" </dev/null + done +} + +pass +while [ -n "$LOOP" ]; do sleep "$LOOP"; pass; done -- 2.45.2 From 93f38bbcba45d7d0bc46f85d01564eb21b657567 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:24:11 +0500 Subject: [PATCH 006/536] PEP-22: harden timing-sensitive e2e steps, archive change Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../2026-11-13-pep-22-peppa-ci}/proposal.md | 0 .../specs/peppa-ci/spec.md | 0 .../2026-11-13-pep-22-peppa-ci/tasks.md | 16 ++++ openspec/changes/pep-22-peppa-ci/tasks.md | 10 --- openspec/specs/peppa-ci/spec.md | 80 +++++++++++++++++++ packages/testkit/src/mock-agent.ts | 1 + packages/testkit/test/cjm.test.ts | 9 ++- packages/testkit/test/limits.test.ts | 9 ++- scripts/ci.sh | 2 +- 9 files changed, 108 insertions(+), 19 deletions(-) rename openspec/changes/{pep-22-peppa-ci => archive/2026-11-13-pep-22-peppa-ci}/proposal.md (100%) rename openspec/changes/{pep-22-peppa-ci => archive/2026-11-13-pep-22-peppa-ci}/specs/peppa-ci/spec.md (100%) create mode 100644 openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md delete mode 100644 openspec/changes/pep-22-peppa-ci/tasks.md create mode 100644 openspec/specs/peppa-ci/spec.md diff --git a/openspec/changes/pep-22-peppa-ci/proposal.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/proposal.md similarity index 100% rename from openspec/changes/pep-22-peppa-ci/proposal.md rename to openspec/changes/archive/2026-11-13-pep-22-peppa-ci/proposal.md diff --git a/openspec/changes/pep-22-peppa-ci/specs/peppa-ci/spec.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/specs/peppa-ci/spec.md similarity index 100% rename from openspec/changes/pep-22-peppa-ci/specs/peppa-ci/spec.md rename to openspec/changes/archive/2026-11-13-pep-22-peppa-ci/specs/peppa-ci/spec.md diff --git a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md new file mode 100644 index 00000000..0dc19119 --- /dev/null +++ b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md @@ -0,0 +1,16 @@ +# Tasks: PEP-22 + +- [x] 1.1 `PEPPA_TEST_DB` в testkit (своя БД на прогон) +- [x] 1.2 `scripts/ci.sh` (typecheck, web build, e2e, `--repeat`, `--skip-build`) и `pnpm run ci` +- [x] 1.3 `scripts/ci.sh --pr N`: временный worktree, статус `peppa/ci` в Gitea, лог в `~/.peppa/ci` +- [x] 1.4 `scripts/mock-act-runner.sh` — заменитель act_runner +- [x] 1.5 `infra/ci/peppa-ci.yml` + инструкция для PM по раннеру +- [x] 2.1 Прогнать набор 5 раз подряд, найти и починить флаки +- [x] 2.2 Правило в `AGENTS.md`: перед мержем `ci.sh --pr N`, мерж только при `success` +- [x] 2.3 `openspec validate`, проверка на своём PR, archive + +Итог 2.1: 9 прогонов подряд зелёные (82/82, ~165 с), флак не воспроизвёлся. Убраны гонки +«фиксированная пауза → один тик → assert»: ожидание диалога разрешения по событию `dialog` +мока, баннер лимита (Codex) — `waitFor` с тиком вачдога. +Решение: БД на прогон (`PEPPA_TEST_DB`), а не на файл — файлы идут последовательно +(`--test-concurrency=1`), изоляции на прогон хватает для параллельных worktree. diff --git a/openspec/changes/pep-22-peppa-ci/tasks.md b/openspec/changes/pep-22-peppa-ci/tasks.md deleted file mode 100644 index 21c9a5d7..00000000 --- a/openspec/changes/pep-22-peppa-ci/tasks.md +++ /dev/null @@ -1,10 +0,0 @@ -# Tasks: PEP-22 - -- [ ] 1.1 `PEPPA_TEST_DB` в testkit (своя БД на прогон) -- [ ] 1.2 `scripts/ci.sh` (typecheck, web build, e2e, `--repeat`, `--skip-build`) и `pnpm run ci` -- [ ] 1.3 `scripts/ci.sh --pr N`: временный worktree, статус `peppa/ci` в Gitea, лог в `~/.peppa/ci` -- [ ] 1.4 `scripts/mock-act-runner.sh` — заменитель act_runner -- [ ] 1.5 `infra/ci/peppa-ci.yml` + инструкция для PM по раннеру -- [ ] 2.1 Прогнать набор 5 раз подряд, найти и починить флаки -- [ ] 2.2 Правило в `AGENTS.md`: перед мержем `ci.sh --pr N`, мерж только при `success` -- [ ] 2.3 `openspec validate`, проверка на своём PR, archive diff --git a/openspec/specs/peppa-ci/spec.md b/openspec/specs/peppa-ci/spec.md new file mode 100644 index 00000000..9f6b56e6 --- /dev/null +++ b/openspec/specs/peppa-ci/spec.md @@ -0,0 +1,80 @@ +# peppa-ci Specification + +## Purpose +TBD - created by archiving change pep-22-peppa-ci. Update Purpose after archive. + +## Requirements + +### Requirement: Проверка платформы одной командой +`scripts/ci.sh` (`pnpm run ci`) SHALL выполнять typecheck всех пакетов, сборку веба и e2e-набор +на моках, останавливаться на первом упавшем шаге с ненулевым кодом и использовать для e2e +собственную тестовую БД, которую удаляет по завершении. + +#### Scenario: Всё зелёное +- **GIVEN** рабочая копия без ошибок типов и с проходящими тестами +- **WHEN** разработчик запускает `scripts/ci.sh` +- **THEN** выводятся строки «ci: ok typecheck», «ci: ok web build», «ci: ok e2e 1/1» и «ci: all green» +- **AND** код выхода 0, БД `peppa_test_ci_<pid>` после выхода не существует + +#### Scenario: Ошибка типов +- **GIVEN** в пакете есть ошибка TypeScript +- **WHEN** разработчик запускает `scripts/ci.sh` +- **THEN** выводится «ci: FAIL typecheck», сборка и e2e не запускаются +- **AND** код выхода 1 + +#### Scenario: Поиск флаков +- **GIVEN** набор проходит стабильно +- **WHEN** разработчик запускает `scripts/ci.sh --skip-build --repeat 3` +- **THEN** e2e выполняется три раза подряд («ci: ok e2e 1/3» … «ci: ok e2e 3/3»), сборка веба пропущена + +### Requirement: Статус проверки в PR +`scripts/ci.sh --pr <N>` SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном +временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем +`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. + +#### Scenario: Зелёный PR +- **GIVEN** открыт PR 15, его голова проходит все проверки +- **WHEN** запускается `scripts/ci.sh --pr 15` +- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in <N> min» +- **AND** лог прогона лежит в `~/.peppa/ci/<sha>.log`, временный worktree удалён + +#### Scenario: Красный PR +- **GIVEN** открыт PR 16, в его голове падает e2e +- **WHEN** запускается `scripts/ci.sh --pr 16` +- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу +- **AND** код выхода 1 + +#### Scenario: Нет такого PR +- **GIVEN** в репозитории нет PR 999 +- **WHEN** запускается `scripts/ci.sh --pr 999` +- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 + +### Requirement: Заменитель раннера Gitea Actions +Пока act_runner не зарегистрирован, `scripts/mock-act-runner.sh` SHALL находить открытые PR, +у головного коммита которых нет статуса `peppa/ci`, и запускать для каждого `ci.sh --pr`; +PR, уже имеющие статус, повторно не проверяются. + +#### Scenario: Новый PR +- **GIVEN** открыт PR 17 без статуса `peppa/ci` +- **WHEN** запускается `scripts/mock-act-runner.sh` +- **THEN** выводится «mock-act-runner: PR 17 @ <sha>» и у коммита появляется статус `peppa/ci` + +#### Scenario: Уже проверенный PR +- **GIVEN** у головы PR 17 уже есть статус `peppa/ci` +- **WHEN** запускается `scripts/mock-act-runner.sh --dry-run` +- **THEN** PR 17 в выводе отсутствует + +### Requirement: Изоляция тестовых прогонов +e2e-набор SHALL работать в БД из `PEPPA_TEST_DB` (по умолчанию `peppa_test`), со своим tmux-сервером +и `PEPPA_HOME`, так что наборы из разных worktree идут одновременно без взаимных падений, и +SHALL проходить несколько раз подряд без флаков. + +#### Scenario: Два набора одновременно +- **GIVEN** в одном worktree идёт набор с `PEPPA_TEST_DB=peppa_test_a` +- **WHEN** в другом запускается набор с `PEPPA_TEST_DB=peppa_test_b` +- **THEN** оба набора зелёные + +#### Scenario: Повторные прогоны +- **GIVEN** main без изменений +- **WHEN** набор прогоняется 5 раз подряд +- **THEN** все 5 прогонов зелёные diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index 79fb9b01..f283efd0 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -193,6 +193,7 @@ async function nextPrompt(): Promise<string> { function dialog(): Promise<string> { mode = "dialog"; + log("dialog"); return new Promise((r) => (dialogResolve = r)); } diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts index 4d3209f3..b00d7132 100644 --- a/packages/testkit/test/cjm.test.ts +++ b/packages/testkit/test/cjm.test.ts @@ -159,7 +159,7 @@ describe("Claude: permissions", () => { const sid = await p.start(); const q = await p.waitQuestion(sid, "permission"); await waitFor("hook released", async () => !(await core.getQuestion(db, q.id)).awaitingHook, 15000); - await new Promise((r) => setTimeout(r, 500)); // dialog drawn + await p.waitLog("dialog drawn", (e) => e.ev === "dialog"); const { delivered } = await runner.answerAndDeliver(db, q.id, "allow", PM); assert.ok(delivered); const e = await p.waitLog("decision in terminal", (x) => x.ev === "permission"); @@ -292,9 +292,10 @@ describe("Codex", () => { const p = await project({ turns: [[{ limit: true }]] }); const sid = await p.start({ provider: "codex" }); await p.waitLog("limit shown", (e) => e.ev === "limit"); - await new Promise((r) => setTimeout(r, 300)); - await tick(); - assert.equal((await p.session(sid)).status, "rate_limited"); + await waitFor("rate_limited", async () => { + await tick(); + return (await p.session(sid)).status === "rate_limited"; + }); assert.ok((await p.pending(sid)).some((q) => /лимит/.test(q.text))); await runner.stopSession(db, sid); }); diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts index 5c384674..a10baa05 100644 --- a/packages/testkit/test/limits.test.ts +++ b/packages/testkit/test/limits.test.ts @@ -134,10 +134,11 @@ describe("Codex", () => { const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Codex продолжил." }]] }); const sid = await p.start({ provider: "codex" }); await p.waitLog("banner", (e) => e.ev === "limit"); - await new Promise((r) => setTimeout(r, 300)); - await tick(); - const s = await sess(sid); - assert.equal(s.status, "rate_limited"); + const s = await waitFor("rate_limited", async () => { + await tick(); + const x = await sess(sid); + return x.status === "rate_limited" && x; + }); assert.ok(s.resumeAt); await tickAt(new Date(s.resumeAt!.getTime() + 1000)); await p.waitLog("codex nudged", isPrompt("Лимит сброшен")); diff --git a/scripts/ci.sh b/scripts/ci.sh index b2ebb9e9..a31c73f0 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -26,7 +26,7 @@ if [ -n "$PR" ]; then . "$ROOT/scripts/gitea-lib.sh" REPO="${PEPPA_CI_REPO:-peppa-bot/peppa}" CONTEXT="peppa/ci" - SHA=$(gitea_api "$GITEA_URL/api/v1/repos/$REPO/pulls/$PR" | python3 -c 'import json,sys;print(json.load(sys.stdin)["head"]["sha"])') \ + SHA=$(gitea_api "$GITEA_URL/api/v1/repos/$REPO/pulls/$PR" 2>/dev/null | python3 -c 'import json,sys;print(json.load(sys.stdin)["head"]["sha"])' 2>/dev/null) \ || { echo "PR $PR not found in $REPO" >&2; exit 2; } status() { # <state> <description> gitea_api -X POST "$GITEA_URL/api/v1/repos/$REPO/statuses/$SHA" \ -- 2.45.2 From 8fee68f8eb2da1ea069b0a09746168f41c46857a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:25:52 +0500 Subject: [PATCH 007/536] PEP-22: Gitea Actions workflow for Peppa on the PEP-57 runner; testkit creates its DB over SQL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .gitea/workflows/ci.yml | 35 ++++++++++++++++++++++++++ infra/ci/peppa-ci.yml | 16 ------------ packages/testkit/package.json | 3 ++- packages/testkit/test/helpers.ts | 18 ++++++++----- pnpm-lock.yaml | 3 +++ scripts/ci.sh | 3 ++- scripts/mock-act-runner.sh | 43 -------------------------------- 7 files changed, 54 insertions(+), 67 deletions(-) create mode 100644 .gitea/workflows/ci.yml delete mode 100644 infra/ci/peppa-ci.yml delete mode 100755 scripts/mock-act-runner.sh diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 00000000..ba165286 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,35 @@ +# CI for Peppa itself (PEP-22): typecheck, web build and the e2e suite on mocks — the same +# scripts/ci.sh that runs locally. Runs on Peppa's act_runner (`peppa-trusted`, registered for +# peppa-bot's repos, PEP-57); Postgres is a throwaway service container, tmux is installed in the job. +name: peppa-ci +on: + pull_request: + push: + branches: [main] +jobs: + ci: + # The runner has the host's docker.sock: only branches of this repository, never forks. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: peppa-trusted + timeout-minutes: 30 + services: + postgres: + image: postgres:17-alpine + env: + POSTGRES_USER: peppa + POSTGRES_PASSWORD: peppa + env: + PEPPA_TEST_PG: postgres://peppa:peppa@postgres:5432 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "26" + - name: tools + run: | + apt-get update -qq && apt-get install -y -qq tmux >/dev/null + npm install -g pnpm@12.18.0 >/dev/null + - name: install + run: pnpm install --frozen-lockfile + - name: ci + run: bash scripts/ci.sh diff --git a/infra/ci/peppa-ci.yml b/infra/ci/peppa-ci.yml deleted file mode 100644 index a8fd843f..00000000 --- a/infra/ci/peppa-ci.yml +++ /dev/null @@ -1,16 +0,0 @@ -# Gitea Actions workflow for Peppa itself (PEP-22). Not active yet: there is no act_runner for -# peppa-bot/peppa. To enable, register a runner with label `peppa-host` (host mode: e2e needs -# tmux, docker exec into peppa-postgres and Postgres on 127.0.0.1:5433) and copy this file to -# .gitea/workflows/ci.yml. Until then scripts/mock-act-runner.sh sets the same `peppa/ci` status. -name: peppa/ci -on: - pull_request: - push: - branches: [main] -jobs: - ci: - runs-on: peppa-host - steps: - - uses: actions/checkout@v4 - - run: pnpm install --frozen-lockfile --prefer-offline - - run: bash scripts/ci.sh diff --git a/packages/testkit/package.json b/packages/testkit/package.json index da3b5555..cc45f2b5 100644 --- a/packages/testkit/package.json +++ b/packages/testkit/package.json @@ -16,6 +16,7 @@ "@peppa/shared": "workspace:*", "drizzle-orm": "0.45.4", "@peppa/bot": "workspace:*", - "@peppa/mcp": "workspace:*" + "@peppa/mcp": "workspace:*", + "postgres": "4.1.1" } } diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 87ff6cd4..7e101a40 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -7,15 +7,19 @@ import { mkdirSync, mkdtempSync, readFileSync, existsSync, writeFileSync } from import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import postgres from "postgres"; import type { Scenario, MockLogEntry } from "../src/scenario.ts"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-cjm-")); -// PEPPA_TEST_DB lets parallel sessions (one per worktree) run the suite without sharing a database. +// PEPPA_TEST_DB lets parallel sessions (one per worktree) run the suite without sharing a database; +// PEPPA_TEST_PG points at another Postgres server (CI job: a service container). const TEST_DB = process.env.PEPPA_TEST_DB ?? "peppa_test"; +const TEST_PG = process.env.PEPPA_TEST_PG ?? "postgres://peppa:peppa@127.0.0.1:5433"; +if (!/^[a-z0-9_]+$/.test(TEST_DB)) throw new Error(`bad PEPPA_TEST_DB: ${TEST_DB}`); Object.assign(process.env, { - DATABASE_URL: `postgres://peppa:peppa@127.0.0.1:5433/${TEST_DB}`, + DATABASE_URL: `${TEST_PG}/${TEST_DB}`, PEPPA_HOME: join(TMP, "home"), PEPPA_TMUX_SOCKET: `peppa-test-${process.pid}`, PEPPA_CLAUDE_BIN: join(ROOT, "packages/testkit/bin/mock-claude"), @@ -30,10 +34,12 @@ Object.assign(process.env, { }); mkdirSync(process.env.PEPPA_HOME!, { recursive: true }); -execFileSync("bash", [ - "-c", - `docker exec peppa-postgres psql -U peppa -tAc "select 1 from pg_database where datname='${TEST_DB}'" | grep -q 1 || docker exec peppa-postgres createdb -U peppa ${TEST_DB}`, -]); +{ + const admin = postgres(`${TEST_PG}/postgres`, { max: 1, onnotice: () => {} }); + const [exists] = await admin`select 1 from pg_database where datname = ${TEST_DB}`; + if (!exists) await admin.unsafe(`create database ${TEST_DB}`); + await admin.end(); +} // Import after the env is set: these modules read it at load time. export const core = await import("@peppa/core"); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 58164673..43b95916 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -362,6 +362,9 @@ importers: drizzle-orm: specifier: 0.45.4 version: 0.45.4(postgres@4.1.1) + postgres: + specifier: 4.1.1 + version: 4.1.1 packages: diff --git a/scripts/ci.sh b/scripts/ci.sh index a31c73f0..fdfc1100 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -58,7 +58,8 @@ fi cd "$ROOT" DB="peppa_test_ci_$$" -cleanup() { docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; } +# A CI job's Postgres (PEPPA_TEST_PG) is a throwaway service container: nothing to drop there. +cleanup() { [ -n "${PEPPA_TEST_PG:-}" ] || docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; } trap cleanup EXIT step() { # <name> <command...> diff --git a/scripts/mock-act-runner.sh b/scripts/mock-act-runner.sh deleted file mode 100755 index b8545a43..00000000 --- a/scripts/mock-act-runner.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash -# Stand-in for Gitea Actions' act_runner until one is registered for peppa-bot/peppa (PEP-22): -# picks up open PRs whose head commit has no `peppa/ci` status yet and runs scripts/ci.sh --pr -# for each, which reports the status back like a workflow job would. -# -# scripts/mock-act-runner.sh one pass over open PRs -# scripts/mock-act-runner.sh --loop 120 keep polling every 120 s (foreground; not a service) -# scripts/mock-act-runner.sh --dry-run only list PRs that would be checked -set -uo pipefail -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -. "$ROOT/scripts/lib/ci-env.sh" -. "$ROOT/scripts/gitea-lib.sh" -REPO="${PEPPA_CI_REPO:-peppa-bot/peppa}" -LOOP="" DRY=0 -while [ $# -gt 0 ]; do - case "$1" in - --loop) LOOP=$2; shift 2 ;; - --dry-run) DRY=1; shift ;; - *) echo "unknown argument: $1" >&2; exit 2 ;; - esac -done - -# Prints "<number> <sha>" for open PRs without a peppa/ci status on their head. -pending_prs() { - gitea_api "$GITEA_URL/api/v1/repos/$REPO/pulls?state=open&limit=50" | - python3 -c 'import json,sys -for p in json.load(sys.stdin): print(p["number"], p["head"]["sha"])' | - while read -r n sha; do - gitea_api "$GITEA_URL/api/v1/repos/$REPO/commits/$sha/statuses" | - python3 -c 'import json,sys; sys.exit(0 if any(s["context"]=="peppa/ci" for s in json.load(sys.stdin)) else 1)' || - echo "$n $sha" - done -} - -pass() { - pending_prs | while read -r n sha; do - echo "mock-act-runner: PR $n @ ${sha:0:8}" - [ "$DRY" = 1 ] || bash "$ROOT/scripts/ci.sh" --pr "$n" </dev/null - done -} - -pass -while [ -n "$LOOP" ]; do sleep "$LOOP"; pass; done -- 2.45.2 From 961cb558a495060fdb76bf3f67fd8f3dda3a17b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:34:04 +0500 Subject: [PATCH 008/536] PEP-22: CI job uses host Postgres with a per-run database, installs openspec Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .gitea/workflows/ci.yml | 15 ++++++--------- scripts/ci.sh | 8 ++++---- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ba165286..e97b18e6 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,6 +1,6 @@ # CI for Peppa itself (PEP-22): typecheck, web build and the e2e suite on mocks — the same # scripts/ci.sh that runs locally. Runs on Peppa's act_runner (`peppa-trusted`, registered for -# peppa-bot's repos, PEP-57); Postgres is a throwaway service container, tmux is installed in the job. +# peppa-bot's repos, PEP-57); tmux and the openspec CLI are installed in the job. name: peppa-ci on: pull_request: @@ -12,14 +12,11 @@ jobs: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository runs-on: peppa-trusted timeout-minutes: 30 - services: - postgres: - image: postgres:17-alpine - env: - POSTGRES_USER: peppa - POSTGRES_PASSWORD: peppa env: - PEPPA_TEST_PG: postgres://peppa:peppa@postgres:5432 + # Peppa's Postgres on the host, a database per run (dropped by ci.sh). A service container + # doesn't isolate here: every job shares the traefik_default network and its `postgres` alias. + PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433 + PEPPA_TEST_DB: peppa_test_ci_r${{ github.run_id }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -28,7 +25,7 @@ jobs: - name: tools run: | apt-get update -qq && apt-get install -y -qq tmux >/dev/null - npm install -g pnpm@12.18.0 >/dev/null + npm install -g pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null - name: install run: pnpm install --frozen-lockfile - name: ci diff --git a/scripts/ci.sh b/scripts/ci.sh index fdfc1100..5349a5f3 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -7,7 +7,7 @@ # scripts/ci.sh --repeat <N> run the e2e suite N times in a row (flake hunting) # scripts/ci.sh --skip-build skip `next build` # -# Every run uses its own database peppa_test_ci_<pid> (dropped at exit), so it can run next +# Every run uses its own database peppa_test_ci_<pid> or $PEPPA_TEST_DB (dropped at exit), so it can run next # to other worktrees' suites. Logs of --pr runs: ~/.peppa/ci/<sha>.log. set -uo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" @@ -57,9 +57,9 @@ if [ -n "$PR" ]; then fi cd "$ROOT" -DB="peppa_test_ci_$$" -# A CI job's Postgres (PEPPA_TEST_PG) is a throwaway service container: nothing to drop there. -cleanup() { [ -n "${PEPPA_TEST_PG:-}" ] || docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; } +# The Actions job passes PEPPA_TEST_DB per run: pids inside job containers repeat. +DB="${PEPPA_TEST_DB:-peppa_test_ci_$$}" +cleanup() { docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; } trap cleanup EXIT step() { # <name> <command...> -- 2.45.2 From 6cbac2bf4cdb031c8ad4bea2387917d5a4cb0664 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:37:46 +0500 Subject: [PATCH 009/536] PEP-22: runner waits for tmux to reap the agent before reading its exit status Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/runner/src/tmux.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index fedf053f..5f14e7bf 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -45,9 +45,15 @@ export interface PaneState { } export async function paneState(name: string): Promise<PaneState> { - const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status}")).trim(); - const [dead, status] = out.split(" "); - return { dead: dead === "1", exitStatus: status ? Number(status) : null }; + // tmux marks the pane dead when the pty closes, which can come before it reaps the child: + // for a moment there is neither an exit status nor a signal. Give it a second to catch up. + for (let attempt = 0; ; attempt++) { + const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status} #{pane_dead_signal}")).trim(); + const [dead, status, signal] = out.split(" "); + if (dead !== "1") return { dead: false, exitStatus: null }; + if (status || signal || attempt >= 10) return { dead: true, exitStatus: status ? Number(status) : null }; + await new Promise((r) => setTimeout(r, 100)); + } } /** Visible screen (plus `history` lines of scrollback) as plain text. */ -- 2.45.2 From 83b222b9e2908c83864d77b3766dde58d19b921f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:41:30 +0500 Subject: [PATCH 010/536] PEP-22: docs and spec reflect the real Actions workflow Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 2 +- .../2026-11-13-pep-22-peppa-ci/proposal.md | 35 ++++++++----------- .../specs/peppa-ci/spec.md | 33 ++++++++++------- .../2026-11-13-pep-22-peppa-ci/tasks.md | 10 +++--- openspec/specs/peppa-ci/spec.md | 33 ++++++++++------- 5 files changed, 62 insertions(+), 51 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fe144519..8e93a422 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,7 @@ - `pnpm dev:web` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` -- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **Перед мержем PR платформы**: `scripts/ci.sh --pr <N>` — проверка головы PR во временном worktree, статус `peppa/ci` в Gitea; мержить только при `success`. `scripts/mock-act-runner.sh [--loop 120]` — заменитель act_runner (проходит по открытым PR без статуса); настоящий workflow лежит в `infra/ci/peppa-ci.yml` и ждёт раннера +- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: `.gitea/workflows/ci.yml` гоняет `scripts/ci.sh` на каждый PR и push в main на раннере PEP-57 (`peppa-trusted`, Postgres хоста, БД `peppa_test_ci_r<run_id>`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`); статус `peppa-ci / ci (pull_request)` в PR, мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`) - `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`) - **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу diff --git a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/proposal.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/proposal.md index 6d2591e7..7b3f1510 100644 --- a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/proposal.md +++ b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/proposal.md @@ -16,28 +16,22 @@ e2e-набор гоняется руками перед мержем, PR в `pep - **`scripts/ci.sh --pr N`**: проверка головы PR в отдельном временном worktree, статус коммита `peppa/ci` в Gitea (`pending` → `success`/`failure` с длительностью или упавшим шагом), лог в `~/.peppa/ci/<sha>.log`. Статус виден в PR. -- **`scripts/mock-act-runner.sh`**: заменитель act_runner, пока раннер Gitea Actions не - зарегистрирован, — проходит по открытым PR без статуса `peppa/ci` и запускает для них - `ci.sh --pr`. Не сервис: разовый проход или `--loop` в терминале. -- **`infra/ci/peppa-ci.yml`**: готовый workflow Gitea Actions (тот же `scripts/ci.sh`) — - лежит вне `.gitea/workflows`, иначе без раннера каждый PR висел бы в «Waiting». +- **`.gitea/workflows/ci.yml`**: Gitea Actions на раннере `peppa-trusted`, который поднял PEP-57 + (зарегистрирован на репозитории peppa-bot, значит и на `peppa-bot/peppa`): на каждый PR и push в + `main` — `scripts/ci.sh`. БД — Postgres хоста (`host.docker.internal:5433`), своя на прогон + (`peppa_test_ci_r<run_id>`): service-контейнер не изолирует — все job'ы в общей сети + `traefik_default` с одним алиасом `postgres`. В job ставятся tmux и openspec CLI. - **Стабильность**: `PEPPA_TEST_DB` (уже в main) + починка найденных флаков; набор гоняется несколько раз подряд. -- **Правила**: в `AGENTS.md` — перед мержем PR платформы `scripts/ci.sh --pr N`, мерж - только при `success`. +- **Правила**: в `AGENTS.md` — мерж PR платформы только при зелёном `peppa-ci`. -## Решения PM (стоппер для настоящего CI в Gitea) +## Стоппер снят -Раннер Gitea Actions требует установки сервиса на машину (act_runner в docker/launchd с -доступом к docker и Postgres) — без PM не ставим. Что нужно: -1. Разрешить запуск `act_runner` (контейнер рядом с `gitea`, label `peppa-host`, host-режим — - e2e нужны tmux и Postgres на 127.0.0.1:5433). -2. Получить registration token репозитория (бот — админ репо, токен выдаётся API) и - зарегистрировать раннер. -3. Перенести `infra/ci/peppa-ci.yml` в `.gitea/workflows/ci.yml`; при желании — защита - ветки `main` с обязательной проверкой. - -Это не PEP-57 (CI/CD для проектов фабрики) — здесь только сама Пеппа. +В начале работы раннера Gitea Actions не было (нужна установка сервиса — стоппер, план был: +`scripts/mock-act-runner.sh` + локальный `ci.sh --pr`). Во время работы в main пришёл PEP-57 с +`peppa-act-runner`, зарегистрированным на пользователя peppa-bot, — Пеппа подключена к нему без +новых сервисов; заменитель раннера не понадобился. `ci.sh --pr N` остался запасным путём. +Защиту ветки `main` (обязательная проверка) не включали — решение PM. ## Capabilities @@ -48,5 +42,6 @@ e2e-набор гоняется руками перед мержем, PR в `pep ## Impact -`scripts/` (ci.sh, mock-act-runner.sh, lib/ci-env.sh), `package.json` (`ci`), `infra/ci/`, -`packages/testkit` (флаки), `AGENTS.md`. БД, сервисы и launchd не меняются. +`.gitea/workflows/ci.yml`, `scripts/` (ci.sh, lib/ci-env.sh), `package.json` (`ci`), `packages/testkit` +(БД по SQL через `PEPPA_TEST_PG`, флаки), `packages/runner/src/tmux.ts` (код выхода), `AGENTS.md`. +БД, сервисы и launchd не меняются. diff --git a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/specs/peppa-ci/spec.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/specs/peppa-ci/spec.md index b3fd21f1..248ec240 100644 --- a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/specs/peppa-ci/spec.md +++ b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/specs/peppa-ci/spec.md @@ -25,7 +25,7 @@ - **THEN** e2e выполняется три раза подряд («ci: ok e2e 1/3» … «ci: ok e2e 3/3»), сборка веба пропущена ### Requirement: Статус проверки в PR -`scripts/ci.sh --pr <N>` SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном +`scripts/ci.sh --pr <N>` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем `success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. @@ -46,20 +46,27 @@ - **WHEN** запускается `scripts/ci.sh --pr 999` - **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 -### Requirement: Заменитель раннера Gitea Actions -Пока act_runner не зарегистрирован, `scripts/mock-act-runner.sh` SHALL находить открытые PR, -у головного коммита которых нет статуса `peppa/ci`, и запускать для каждого `ci.sh --pr`; -PR, уже имеющие статус, повторно не проверяются. +### Requirement: Проверки на каждый PR в Gitea Actions +Workflow `.gitea/workflows/ci.yml` репозитория `peppa-bot/peppa` SHALL на каждый PR из ветки этого +репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57), +с тестовой БД `peppa_test_ci_r<run_id>` на Postgres хоста, и выставлять статус коммита +`peppa-ci / ci (pull_request)`; PR из форков не запускаются. -#### Scenario: Новый PR -- **GIVEN** открыт PR 17 без статуса `peppa/ci` -- **WHEN** запускается `scripts/mock-act-runner.sh` -- **THEN** выводится «mock-act-runner: PR 17 @ <sha>» и у коммита появляется статус `peppa/ci` +#### Scenario: PR зелёный +- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят +- **WHEN** ветка пушится +- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in <N>m<S>s») +- **AND** БД `peppa_test_ci_r<run_id>` после job не существует -#### Scenario: Уже проверенный PR -- **GIVEN** у головы PR 17 уже есть статус `peppa/ci` -- **WHEN** запускается `scripts/mock-act-runner.sh --dry-run` -- **THEN** PR 17 в выводе отсутствует +#### Scenario: PR красный +- **GIVEN** в голове PR падает один e2e-тест +- **WHEN** job доходит до шага `ci` +- **THEN** статус = `failure` («Failing after <N>m<S>s»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста + +#### Scenario: PR из форка +- **GIVEN** PR открыт из форка репозитория +- **WHEN** Gitea обрабатывает событие `pull_request` +- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется ### Requirement: Изоляция тестовых прогонов e2e-набор SHALL работать в БД из `PEPPA_TEST_DB` (по умолчанию `peppa_test`), со своим tmux-сервером diff --git a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md index 0dc19119..44ba928e 100644 --- a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md +++ b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md @@ -3,13 +3,15 @@ - [x] 1.1 `PEPPA_TEST_DB` в testkit (своя БД на прогон) - [x] 1.2 `scripts/ci.sh` (typecheck, web build, e2e, `--repeat`, `--skip-build`) и `pnpm run ci` - [x] 1.3 `scripts/ci.sh --pr N`: временный worktree, статус `peppa/ci` в Gitea, лог в `~/.peppa/ci` -- [x] 1.4 `scripts/mock-act-runner.sh` — заменитель act_runner -- [x] 1.5 `infra/ci/peppa-ci.yml` + инструкция для PM по раннеру +- [x] 1.4 `.gitea/workflows/ci.yml` на раннере PEP-57 (`peppa-trusted`), БД хоста на прогон, tmux + openspec в job +- [x] 1.5 testkit создаёт БД по SQL (`PEPPA_TEST_PG`), без `docker exec` - [x] 2.1 Прогнать набор 5 раз подряд, найти и починить флаки -- [x] 2.2 Правило в `AGENTS.md`: перед мержем `ci.sh --pr N`, мерж только при `success` +- [x] 2.2 Правило в `AGENTS.md`: мерж PR платформы только при зелёном `peppa-ci` - [x] 2.3 `openspec validate`, проверка на своём PR, archive -Итог 2.1: 9 прогонов подряд зелёные (82/82, ~165 с), флак не воспроизвёлся. Убраны гонки +Итог 2.1: локально 10 прогонов подряд зелёные (82→113 тестов после rebase, ~165 с), в job PR зелёный. +В job всплыл настоящий баг: tmux помечает панель мёртвой раньше, чем знает код выхода → «упал (код null)»; +`paneState` теперь дожидается статуса или сигнала (до 1 с). Убраны гонки «фиксированная пауза → один тик → assert»: ожидание диалога разрешения по событию `dialog` мока, баннер лимита (Codex) — `waitFor` с тиком вачдога. Решение: БД на прогон (`PEPPA_TEST_DB`), а не на файл — файлы идут последовательно diff --git a/openspec/specs/peppa-ci/spec.md b/openspec/specs/peppa-ci/spec.md index 9f6b56e6..2d85f8db 100644 --- a/openspec/specs/peppa-ci/spec.md +++ b/openspec/specs/peppa-ci/spec.md @@ -28,7 +28,7 @@ TBD - created by archiving change pep-22-peppa-ci. Update Purpose after archive. - **THEN** e2e выполняется три раза подряд («ci: ok e2e 1/3» … «ci: ok e2e 3/3»), сборка веба пропущена ### Requirement: Статус проверки в PR -`scripts/ci.sh --pr <N>` SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном +`scripts/ci.sh --pr <N>` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория `peppa-bot/peppa` в отдельном временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем `success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется. @@ -49,20 +49,27 @@ TBD - created by archiving change pep-22-peppa-ci. Update Purpose after archive. - **WHEN** запускается `scripts/ci.sh --pr 999` - **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2 -### Requirement: Заменитель раннера Gitea Actions -Пока act_runner не зарегистрирован, `scripts/mock-act-runner.sh` SHALL находить открытые PR, -у головного коммита которых нет статуса `peppa/ci`, и запускать для каждого `ci.sh --pr`; -PR, уже имеющие статус, повторно не проверяются. +### Requirement: Проверки на каждый PR в Gitea Actions +Workflow `.gitea/workflows/ci.yml` репозитория `peppa-bot/peppa` SHALL на каждый PR из ветки этого +репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57), +с тестовой БД `peppa_test_ci_r<run_id>` на Postgres хоста, и выставлять статус коммита +`peppa-ci / ci (pull_request)`; PR из форков не запускаются. -#### Scenario: Новый PR -- **GIVEN** открыт PR 17 без статуса `peppa/ci` -- **WHEN** запускается `scripts/mock-act-runner.sh` -- **THEN** выводится «mock-act-runner: PR 17 @ <sha>» и у коммита появляется статус `peppa/ci` +#### Scenario: PR зелёный +- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят +- **WHEN** ветка пушится +- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in <N>m<S>s») +- **AND** БД `peppa_test_ci_r<run_id>` после job не существует -#### Scenario: Уже проверенный PR -- **GIVEN** у головы PR 17 уже есть статус `peppa/ci` -- **WHEN** запускается `scripts/mock-act-runner.sh --dry-run` -- **THEN** PR 17 в выводе отсутствует +#### Scenario: PR красный +- **GIVEN** в голове PR падает один e2e-тест +- **WHEN** job доходит до шага `ci` +- **THEN** статус = `failure` («Failing after <N>m<S>s»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста + +#### Scenario: PR из форка +- **GIVEN** PR открыт из форка репозитория +- **WHEN** Gitea обрабатывает событие `pull_request` +- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется ### Requirement: Изоляция тестовых прогонов e2e-набор SHALL работать в БД из `PEPPA_TEST_DB` (по умолчанию `peppa_test`), со своим tmux-сервером -- 2.45.2 From d1c555a03816ffced15aed054706fbe28f365695 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 14:51:13 +0500 Subject: [PATCH 011/536] PEP-22: read a zombie agent's exit code from /proc when tmux never reaps it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../2026-11-13-pep-22-peppa-ci/tasks.md | 8 +++--- packages/runner/src/tmux.ts | 25 ++++++++++++++++--- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md index 44ba928e..87a2bbcd 100644 --- a/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md +++ b/openspec/changes/archive/2026-11-13-pep-22-peppa-ci/tasks.md @@ -10,9 +10,9 @@ - [x] 2.3 `openspec validate`, проверка на своём PR, archive Итог 2.1: локально 10 прогонов подряд зелёные (82→113 тестов после rebase, ~165 с), в job PR зелёный. -В job всплыл настоящий баг: tmux помечает панель мёртвой раньше, чем знает код выхода → «упал (код null)»; -`paneState` теперь дожидается статуса или сигнала (до 1 с). Убраны гонки -«фиксированная пауза → один тик → assert»: ожидание диалога разрешения по событию `dialog` -мока, баннер лимита (Codex) — `waitFor` с тиком вачдога. +В job всплыл настоящий баг: tmux на Linux помечает панель мёртвой, но иногда так и не забирает +процесс агента (зомби, родитель — сервер tmux), и код выхода неизвестен → «упал (код null)». +`paneState` ждёт статус до 1 с, а для зомби берёт код из `/proc/<pid>/stat` (exit_code). На macOS +(прод) не воспроизводится, но поведение то же. Решение: БД на прогон (`PEPPA_TEST_DB`), а не на файл — файлы идут последовательно (`--test-concurrency=1`), изоляции на прогон хватает для параллельных worktree. diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 5f14e7bf..cc8125e9 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -1,4 +1,5 @@ import { execFile, spawn } from "node:child_process"; +import { readFileSync } from "node:fs"; import { promisify } from "node:util"; const run = promisify(execFile); @@ -46,16 +47,32 @@ export interface PaneState { export async function paneState(name: string): Promise<PaneState> { // tmux marks the pane dead when the pty closes, which can come before it reaps the child: - // for a moment there is neither an exit status nor a signal. Give it a second to catch up. + // then there is neither an exit status nor a signal yet. On Linux tmux sometimes never reaps + // it at all (seen in CI containers) — the zombie still holds its status in /proc. for (let attempt = 0; ; attempt++) { - const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status} #{pane_dead_signal}")).trim(); - const [dead, status, signal] = out.split(" "); + const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status} #{pane_dead_signal} #{pane_pid}")).trim(); + const [dead, status, signal, pid] = out.split(" "); if (dead !== "1") return { dead: false, exitStatus: null }; - if (status || signal || attempt >= 10) return { dead: true, exitStatus: status ? Number(status) : null }; + if (status || signal) return { dead: true, exitStatus: status ? Number(status) : null }; + const zombie = zombieExitStatus(Number(pid)); + if (zombie !== undefined || attempt >= 10) return { dead: true, exitStatus: zombie ?? null }; await new Promise((r) => setTimeout(r, 100)); } } +/** Exit code of a not-yet-reaped process from /proc (Linux); null if it died by a signal. */ +function zombieExitStatus(pid: number): number | null | undefined { + try { + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + if (fields[0] !== "Z") return undefined; + const wait = Number(fields[49]); // field 52: exit_code, in waitpid() format + return (wait & 0x7f) === 0 ? (wait >> 8) & 0xff : null; + } catch { + return undefined; + } +} + /** Visible screen (plus `history` lines of scrollback) as plain text. */ export async function capturePane(name: string, history = 0): Promise<string> { return tmux("capture-pane", "-p", "-J", "-t", `=${name}:`, "-S", String(-history)); -- 2.45.2 From 8073a27f9d47735e3966f769cf32f653334633e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 15:01:00 +0500 Subject: [PATCH 012/536] Fix stray argument in incidents test (broken in c964a00, main didn't typecheck) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/testkit/test/incidents.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/testkit/test/incidents.test.ts b/packages/testkit/test/incidents.test.ts index b82bb807..fd07e926 100644 --- a/packages/testkit/test/incidents.test.ts +++ b/packages/testkit/test/incidents.test.ts @@ -503,8 +503,7 @@ describe("MCP для PM", () => { await bugsink.capture(c.api, { ...AMOUNT, value: "via mcp" }); const i = await waitIncident(c, "TypeError: via mcp", (x) => x.status === "pending"); assert.match(await call("list_incidents", { project: c.key, status: "pending" }), new RegExp(`#${i.id} \\[pending\\] TypeError: via mcp`)); - assert.match(await call("decide_incident", - "deploy", { id: i.id, action: "backlog" }), /created in the backlog/); + assert.match(await call("decide_incident", { id: i.id, action: "backlog" }), /created in the backlog/); assert.match(await call("resolve_incident", { id: i.id }), /Incident #\d+ resolved/); await waitFor("ask message closed", async () => pmMessages("via mcp").some((m) => m.text.includes("Решено (mock-pm): в бэклог"))); }); -- 2.45.2 From 28fbde4addc0dcf2edad85a220ff87a57de9353d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:21:43 +0500 Subject: [PATCH 013/536] =?UTF-8?q?PEP-38:=20console=20foundation=20?= =?UTF-8?q?=E2=80=94=20Tailwind=20v4,=20shadcn/ui=20components,=20dark=20t?= =?UTF-8?q?heme,=20three-panel=20layout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 2 +- apps/web/app/(app)/help/page.tsx | 3 + apps/web/app/(app)/layout.tsx | 27 +- apps/web/app/(app)/p/[key]/page.tsx | 5 +- apps/web/app/(app)/page.tsx | 6 +- apps/web/app/(app)/projects/new/page.tsx | 3 + apps/web/app/(app)/projects/page.tsx | 5 +- apps/web/app/(app)/runners/page.tsx | 5 +- apps/web/app/(app)/settings/page.tsx | 3 + apps/web/app/(app)/t/[key]/page.tsx | 5 +- apps/web/app/app.css | 104 ++++ apps/web/app/layout.tsx | 13 +- apps/web/app/{globals.css => legacy.css} | 127 ++--- apps/web/components/ActivityAside.tsx | 64 +++ apps/web/components/Footer.tsx | 2 +- apps/web/components/Nav.tsx | 33 -- apps/web/components/Sidebar.tsx | 77 +++ apps/web/components/ThemeToggle.tsx | 19 + apps/web/components/Workspace.tsx | 27 + apps/web/components/ui/badge.tsx | 29 ++ apps/web/components/ui/button.tsx | 42 ++ apps/web/components/ui/card.tsx | 24 + apps/web/components/ui/input.tsx | 24 + apps/web/components/ui/separator.tsx | 8 + apps/web/lib/auth.ts | 6 +- apps/web/lib/queries.ts | 11 +- apps/web/lib/status.ts | 42 ++ apps/web/lib/theme.ts | 2 + apps/web/lib/utils.ts | 6 + apps/web/package.json | 20 +- apps/web/postcss.config.mjs | 1 + apps/web/scripts/mock-ui-seed.ts | 112 +++++ .../changes/pep-38-factory-console/design.md | 56 +++ .../pep-38-factory-console/proposal.md | 39 ++ .../specs/web-workspace/spec.md | 85 ++++ .../changes/pep-38-factory-console/tasks.md | 25 + pnpm-lock.yaml | 472 +++++++++++++++++- 37 files changed, 1364 insertions(+), 170 deletions(-) create mode 100644 apps/web/app/app.css rename apps/web/app/{globals.css => legacy.css} (52%) create mode 100644 apps/web/components/ActivityAside.tsx delete mode 100644 apps/web/components/Nav.tsx create mode 100644 apps/web/components/Sidebar.tsx create mode 100644 apps/web/components/ThemeToggle.tsx create mode 100644 apps/web/components/Workspace.tsx create mode 100644 apps/web/components/ui/badge.tsx create mode 100644 apps/web/components/ui/button.tsx create mode 100644 apps/web/components/ui/card.tsx create mode 100644 apps/web/components/ui/input.tsx create mode 100644 apps/web/components/ui/separator.tsx create mode 100644 apps/web/lib/status.ts create mode 100644 apps/web/lib/theme.ts create mode 100644 apps/web/lib/utils.ts create mode 100644 apps/web/postcss.config.mjs create mode 100644 apps/web/scripts/mock-ui-seed.ts create mode 100644 openspec/changes/pep-38-factory-console/design.md create mode 100644 openspec/changes/pep-38-factory-console/proposal.md create mode 100644 openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-38-factory-console/tasks.md diff --git a/AGENTS.md b/AGENTS.md index 8e93a422..267cec7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Текущее состояние и порядок работ: `docs/HANDOFF.md`. ## Структура -- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web` +- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web` - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433) - `packages/shared` — env, ключи задач (`PEP-42`) diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 21c302e8..24fde4df 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -1,5 +1,6 @@ import Link from "next/link"; import { publicOrigin } from "@/lib/auth"; +import { Workspace } from "@/components/Workspace"; const TOOLS: Array<[string, string]> = [ ["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько задач в каждой колонке"], @@ -37,6 +38,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [ export default async function Help() { const mcp = `${await publicOrigin()}/mcp`; return ( + <Workspace> <section className="narrow help"> <h1>Помощь</h1> @@ -111,5 +113,6 @@ export default async function Help() { проекта: сообщением, задачей или с кнопками «В бэклог / В работу / Игнорировать». </p> </section> + </Workspace> ); } diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index 7647b372..edb6e78a 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,29 +1,18 @@ -import Link from "next/link"; import type { ReactNode } from "react"; import { requireUser } from "@/lib/auth"; -import { Footer } from "@/components/Footer"; -import { Nav, SettingsLink } from "@/components/Nav"; +import { navCounts } from "@/lib/queries"; +import { Sidebar } from "@/components/Sidebar"; export const dynamic = "force-dynamic"; +/** Console layout (PEP-38): navigation on the left, each page renders centre + right panel via <Workspace>. */ export default async function AppLayout({ children }: { children: ReactNode }) { const user = await requireUser(); + const counts = await navCounts(user.id); return ( - <> - <header className="top"> - <Link href="/" className="brand">🐷 Peppa</Link> - <Nav /> - <div className="me"> - <SettingsLink /> - {user.avatarUrl && <img src={user.avatarUrl} alt="" width={24} height={24} />} - <span>{user.login}</span> - <form action="/logout" method="post"> - <button className="link">Выйти</button> - </form> - </div> - </header> - <main>{children}</main> - <Footer /> - </> + <div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]"> + <Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} /> + <div className="flex min-w-0 flex-col pb-16 md:pb-0">{children}</div> + </div> ); } diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 154de0aa..f77a7464 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -10,6 +10,7 @@ import { bugsinkWebhookBase } from "@peppa/runner"; import { IncidentsSection } from "@/components/Incidents"; import { db } from "@/lib/db"; import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; +import { Workspace } from "@/components/Workspace"; const RELEASE_STATUS: Record<Release["status"], string> = { deploying: "⏳ выкатывается", @@ -53,7 +54,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null, })); return ( - <> + <Workspace> <AutoRefresh /> <Flash error={error} /> {created && !error && ( @@ -225,6 +226,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr <h2>Сессии</h2> {sessions.length === 0 ? <p className="empty">Сессий ещё не было.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)} </section> - </> + </Workspace> ); } diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 2f1c44f2..46337a96 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -5,13 +5,15 @@ import { Flash, ProjectList, QuestionCard, SessionCard } from "@/components/ui"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { activeSessions, inbox } from "@/lib/queries"; +import { Workspace } from "@/components/Workspace"; +import { ActivityAside } from "@/components/ActivityAside"; export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); const { error } = await searchParams; const [items, sessions, projects] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id)]); return ( - <> + <Workspace aside={<ActivityAside questions={false} />}> <AutoRefresh /> <Flash error={error} /> <h1>Главная</h1> @@ -31,6 +33,6 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e </h2> <ProjectList projects={projects} userId={user.id} /> </section> - </> + </Workspace> ); } diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx index 08cee554..520a6fa6 100644 --- a/apps/web/app/(app)/projects/new/page.tsx +++ b/apps/web/app/(app)/projects/new/page.tsx @@ -4,6 +4,7 @@ import { Flash } from "@/components/ui"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { createProjectAction } from "../../actions"; +import { Workspace } from "@/components/Workspace"; export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -17,6 +18,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi giteaError = (e as Error).message; } return ( + <Workspace> <section className="narrow"> <h1>Новый проект</h1> <Flash error={error ?? giteaError} /> @@ -75,5 +77,6 @@ export default async function NewProject({ searchParams }: { searchParams: Promi <button className="primary">Создать проект</button> </form> </section> + </Workspace> ); } diff --git a/apps/web/app/(app)/projects/page.tsx b/apps/web/app/(app)/projects/page.tsx index 2921b74f..4fc5d361 100644 --- a/apps/web/app/(app)/projects/page.tsx +++ b/apps/web/app/(app)/projects/page.tsx @@ -3,13 +3,14 @@ import { listUserProjects } from "@peppa/core"; import { Flash, ProjectList } from "@/components/ui"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; +import { Workspace } from "@/components/Workspace"; export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); const { error } = await searchParams; const projects = await listUserProjects(db, user.id); return ( - <> + <Workspace> <Flash error={error} /> <h1> Проекты{" "} @@ -18,6 +19,6 @@ export default async function Projects({ searchParams }: { searchParams: Promise </Link> </h1> <ProjectList projects={projects} userId={user.id} /> - </> + </Workspace> ); } diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx index b7490824..7f90ce4b 100644 --- a/apps/web/app/(app)/runners/page.tsx +++ b/apps/web/app/(app)/runners/page.tsx @@ -4,6 +4,7 @@ import { AutoRefresh } from "@/components/AutoRefresh"; import { Flash, SessionCard } from "@/components/ui"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; +import { Workspace } from "@/components/Workspace"; const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [ { key: undefined, label: "Все" }, @@ -22,7 +23,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise< const shown = filter ? all.filter((s) => (RUNNER_FILTERS[filter] as string[]).includes(s.status)) : all; const back = filter ? `/runners?f=${filter}` : "/runners"; return ( - <> + <Workspace> <AutoRefresh /> <Flash error={error} /> <h1>Раннеры</h1> @@ -35,6 +36,6 @@ export default async function Runners({ searchParams }: { searchParams: Promise< ))} </nav> {shown.length === 0 ? <p className="empty">{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</p> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} - </> + </Workspace> ); } diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 901efd6f..13c3717c 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -4,6 +4,7 @@ import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { pendingClaudeSetup } from "@peppa/runner"; import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions"; +import { Workspace } from "@/components/Workspace"; export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) { const user = await requireUser(); @@ -12,6 +13,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); return ( + <Workspace> <section className="narrow"> <Flash error={error} /> <h1>Настройки</h1> @@ -112,5 +114,6 @@ export default async function Settings({ searchParams }: { searchParams: Promise )) )} </section> + </Workspace> ); } diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index c46919d0..93f4e933 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -9,6 +9,7 @@ import { goals } from "@peppa/db"; import { taskCiSummary } from "@peppa/core"; import { eq } from "drizzle-orm"; import { startTaskSession } from "../../actions"; +import { Workspace } from "@/components/Workspace"; export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -23,7 +24,7 @@ export default async function TaskPage({ params, searchParams }: { params: Promi const ci = await taskCiSummary(db, ref); const back = `/t/${ref.key}`; return ( - <> + <Workspace> <AutoRefresh /> <Flash error={error} /> <p className="crumbs"> @@ -98,6 +99,6 @@ export default async function TaskPage({ params, searchParams }: { params: Promi ))} </ul> </section> - </> + </Workspace> ); } diff --git a/apps/web/app/app.css b/apps/web/app/app.css new file mode 100644 index 00000000..bc13d895 --- /dev/null +++ b/apps/web/app/app.css @@ -0,0 +1,104 @@ +@import "tailwindcss"; +@import "./legacy.css" layer(base); + +/* Theme tokens (shadcn/ui naming): light in :root, dark — the default — in .dark (PEP-38). */ +@custom-variant dark (&:where(.dark, .dark *)); + +:root { + --radius: 0.625rem; + --background: oklch(0.985 0.002 265); + --foreground: oklch(0.21 0.02 265); + --card: oklch(1 0 0); + --card-foreground: oklch(0.21 0.02 265); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.21 0.02 265); + --primary: oklch(0.6 0.21 355); + --primary-foreground: oklch(0.99 0 0); + --secondary: oklch(0.955 0.005 265); + --secondary-foreground: oklch(0.25 0.02 265); + --muted: oklch(0.955 0.005 265); + --muted-foreground: oklch(0.5 0.02 265); + --accent: oklch(0.94 0.008 265); + --accent-foreground: oklch(0.21 0.02 265); + --destructive: oklch(0.58 0.22 27); + --border: oklch(0.9 0.006 265); + --input: oklch(0.88 0.008 265); + --ring: oklch(0.6 0.21 355); + --sidebar: oklch(0.97 0.004 265); + --ok: oklch(0.55 0.15 150); + --warn: oklch(0.62 0.15 65); + --info: oklch(0.55 0.15 245); + --danger: var(--destructive); + color-scheme: light; +} + +.dark { + --background: oklch(0.16 0.012 265); + --foreground: oklch(0.95 0.006 265); + --card: oklch(0.195 0.014 265); + --card-foreground: oklch(0.95 0.006 265); + --popover: oklch(0.2 0.014 265); + --popover-foreground: oklch(0.95 0.006 265); + --primary: oklch(0.72 0.19 352); + --primary-foreground: oklch(0.17 0.03 352); + --secondary: oklch(0.25 0.014 265); + --secondary-foreground: oklch(0.93 0.006 265); + --muted: oklch(0.235 0.014 265); + --muted-foreground: oklch(0.69 0.018 265); + --accent: oklch(0.26 0.016 265); + --accent-foreground: oklch(0.96 0.006 265); + --destructive: oklch(0.66 0.2 25); + --border: oklch(1 0 0 / 9%); + --input: oklch(1 0 0 / 13%); + --ring: oklch(0.72 0.19 352); + --sidebar: oklch(0.135 0.011 265); + --ok: oklch(0.76 0.16 152); + --warn: oklch(0.8 0.14 75); + --info: oklch(0.74 0.12 240); + color-scheme: dark; +} + +@theme inline { + --font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif; + --font-mono: var(--font-geist-mono), ui-monospace, "SF Mono", Menlo, monospace; + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-sidebar: var(--sidebar); + --color-ok: var(--ok); + --color-warn: var(--warn); + --color-info: var(--info); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground font-sans antialiased; + font-size: 15px; + line-height: 1.5; + } + ::selection { + @apply bg-primary/30; + } +} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 2c26d8ee..aa8316fd 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -1,11 +1,18 @@ import type { ReactNode } from "react"; -import "./globals.css"; +import { cookies } from "next/headers"; +import { GeistSans } from "geist/font/sans"; +import { GeistMono } from "geist/font/mono"; +import { cn } from "@/lib/utils"; +import { THEME_COOKIE } from "@/lib/theme"; +import "./app.css"; export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, задачи и агенты" }; -export default function RootLayout({ children }: { children: ReactNode }) { +export default async function RootLayout({ children }: { children: ReactNode }) { + // Dark by default; the cookie is read on the server so a light choice renders without a dark flash. + const light = (await cookies()).get(THEME_COOKIE)?.value === "light"; return ( - <html lang="ru"> + <html lang="ru" className={cn(GeistSans.variable, GeistMono.variable, !light && "dark")}> <body>{children}</body> </html> ); diff --git a/apps/web/app/globals.css b/apps/web/app/legacy.css similarity index 52% rename from apps/web/app/globals.css rename to apps/web/app/legacy.css index 19107c91..3cfee729 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/legacy.css @@ -1,90 +1,38 @@ -:root { - --bg: #f7f6f3; - --surface: #ffffff; - --text: #1f1d1a; - --muted: #6f6a62; - --border: #e4e0d8; - --accent: #d6457a; - --accent-text: #ffffff; - --danger: #b4332b; - --ok: #2f7d4f; - --warn: #a8661b; - --info: #3460a8; - --code-bg: #f0ede7; - --radius: 10px; - color-scheme: light; -} -@media (prefers-color-scheme: dark) { - :root { - --bg: #151412; - --surface: #1e1d1a; - --text: #ece8e1; - --muted: #a39d93; - --border: #34312c; - --accent: #ec6b9a; - --accent-text: #1a0d12; - --danger: #e0675e; - --ok: #6cc28f; - --warn: #e0a05a; - --info: #7fa6ea; - --code-bg: #26241f; - color-scheme: dark; - } -} +/* Pre-PEP-38 page styles, imported into the `base` layer so Tailwind utilities win. Removed page by page in stage 2. */ -* { box-sizing: border-box; } -html, body { margin: 0; } -body { - background: var(--bg); - color: var(--text); - font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; -} -a { color: var(--accent); text-decoration: none; } +a { color: var(--primary); text-decoration: none; } a:hover { text-decoration: underline; } h1 { font-size: 1.5rem; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } h2 { font-size: 1.1rem; margin: 28px 0 10px; } -.mono, code, pre { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 0.9em; } -.muted { color: var(--muted); } -.empty { color: var(--muted); padding: 12px 0; } +.mono, code, pre { font-family: var(--font-mono); font-size: 0.9em; } +.muted { color: var(--muted-foreground); } +.empty { color: var(--muted-foreground); padding: 12px 0; } -.top { - display: flex; align-items: center; gap: 20px; padding: 10px 24px; - background: var(--surface); border-bottom: 1px solid var(--border); - position: sticky; top: 0; z-index: 1; -} -.brand { font-weight: 700; color: var(--text); } -.top nav { display: flex; gap: 16px; flex: 1; } -.top nav a, .me > a { color: var(--muted); } -.top nav a.active, .me > a.active { color: var(--text); font-weight: 600; box-shadow: inset 0 -2px 0 var(--accent); } -.top nav a:hover, .me > a:hover { color: var(--text); text-decoration: none; } h2 .more { font-size: 0.85rem; font-weight: 400; margin-left: 8px; } .filters { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0 4px; } -.filters a { padding: 4px 12px; border: 1px solid var(--border); border-radius: 999px; color: var(--text); background: var(--surface); } -.filters a:hover { text-decoration: none; border-color: var(--muted); } -.filters a.active { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } +.filters a { padding: 4px 12px; border: 1px solid var(--border); border-radius: 999px; color: var(--foreground); background: var(--card); } +.filters a:hover { text-decoration: none; border-color: var(--muted-foreground); } +.filters a.active { border-color: var(--primary); box-shadow: inset 0 0 0 1px var(--primary); } .session header.row { flex-wrap: wrap; row-gap: 2px; } .session header .mono { white-space: nowrap; } .session .title { flex: 1 1 12em; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.me { display: flex; align-items: center; gap: 8px; color: var(--muted); } -.me img { border-radius: 50%; } -main { max-width: 960px; margin: 0 auto; padding: 24px; } .narrow { max-width: 560px; } -.crumbs { margin: 0 0 4px; color: var(--muted); } +.crumbs { margin: 0 0 4px; color: var(--muted-foreground); } .desc { white-space: pre-wrap; } .card { - background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); + background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 16px; margin: 10px 0; } .q { border-left: 4px solid var(--info); } -.q-approval { border-left-color: var(--accent); } +.q-approval { border-left-color: var(--primary); } .q-permission { border-left-color: var(--warn); } .q-attention { border-left-color: var(--ok); } .q.answered { opacity: 0.7; border-left-color: var(--border); } .kind { font-weight: 600; } .qtext { white-space: pre-wrap; margin: 8px 0; max-height: 18em; overflow: auto; } -.attach { display: block; color: var(--muted); margin: 6px 0; overflow-x: auto; } -.count { background: var(--accent); color: var(--accent-text); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; } +.attach { display: block; color: var(--muted-foreground); margin: 6px 0; overflow-x: auto; } +.count { background: var(--primary); color: var(--primary-foreground); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; } .row { display: flex; gap: 8px; align-items: center; } .row.wrap { flex-wrap: wrap; } @@ -97,57 +45,57 @@ fieldset { border: 1px solid var(--border); border-radius: var(--radius); paddin .answer { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; } input[type=text], textarea, select { - font: inherit; color: var(--text); background: var(--bg); + font: inherit; color: var(--foreground); background: var(--background); border: 1px solid var(--border); border-radius: 8px; padding: 7px 10px; width: 100%; } input.short { width: 8em; } textarea { resize: vertical; } -input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--primary); outline-offset: 1px; } button, .button { font: inherit; cursor: pointer; border-radius: 8px; padding: 7px 14px; - border: 1px solid var(--border); background: var(--surface); color: var(--text); white-space: nowrap; + border: 1px solid var(--border); background: var(--card); color: var(--foreground); white-space: nowrap; display: inline-block; } -button:hover, .button:hover { border-color: var(--muted); text-decoration: none; } -.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); } +button:hover, .button:hover { border-color: var(--muted-foreground); text-decoration: none; } +.primary { background: var(--primary); color: var(--primary-foreground); border-color: var(--primary); } .danger { color: var(--danger); } -button.link { border: 0; background: none; padding: 0; color: var(--muted); } +button.link { border: 0; background: none; padding: 0; color: var(--muted-foreground); } .badge { font-size: 0.75rem; font-weight: 600; border-radius: 999px; padding: 2px 9px; - background: var(--code-bg); color: var(--muted); white-space: nowrap; + background: var(--muted); color: var(--muted-foreground); white-space: nowrap; } .s-in_progress, .s-running { color: var(--info); } -.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--accent); } +.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--primary); } .s-review, .s-done { color: var(--ok); } .s-blocked, .s-failed, .s-stalled, .s-rate_limited { color: var(--danger); } -.notice { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } -.flash { background: color-mix(in srgb, var(--danger) 12%, var(--surface)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; } +.notice { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } +.flash { background: color-mix(in srgb, var(--danger) 12%, var(--card)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; } ul.tasks, ul.projects, ul.events { list-style: none; padding: 0; margin: 0; } ul.tasks li, ul.projects li { display: flex; gap: 10px; align-items: center; justify-content: space-between; - padding: 8px 12px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0; + padding: 8px 12px; background: var(--card); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0; } -ul.tasks li a, ul.projects li a { color: var(--text); min-width: 0; overflow: hidden; text-overflow: ellipsis; } +ul.tasks li a, ul.projects li a { color: var(--foreground); min-width: 0; overflow: hidden; text-overflow: ellipsis; } ul.events li { padding: 3px 0; border-bottom: 1px dashed var(--border); overflow-wrap: anywhere; } details { margin: 8px 0; } -summary { cursor: pointer; color: var(--accent); } +summary { cursor: pointer; color: var(--primary); } pre.md { - white-space: pre-wrap; background: var(--code-bg); border-radius: 8px; padding: 12px; + white-space: pre-wrap; background: var(--muted); border-radius: 8px; padding: 12px; max-height: 32em; overflow: auto; } .board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin: 16px 0; } .board.busy { opacity: 0.6; pointer-events: none; } -.col { background: color-mix(in srgb, var(--border) 35%, var(--bg)); border-radius: var(--radius); padding: 8px; min-height: 120px; } -.col.over { outline: 2px dashed var(--accent); } -.col h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; margin: 4px 4px 8px; color: var(--muted); } +.col { background: color-mix(in srgb, var(--border) 35%, var(--background)); border-radius: var(--radius); padding: 8px; min-height: 120px; } +.col.over { outline: 2px dashed var(--primary); } +.col h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; margin: 4px 4px 8px; color: var(--muted-foreground); } .hint { font-size: 0.75rem; margin: -4px 4px 8px; } -.tcard { background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 6px 0; cursor: grab; display: flex; flex-direction: column; gap: 6px; } -.tcard a { color: var(--text); } +.tcard { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 6px 0; cursor: grab; display: flex; flex-direction: column; gap: 6px; } +.tcard a { color: var(--foreground); } .tcard .goal { font-size: 0.75rem; flex-basis: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .small { font-size: 0.78rem; padding: 3px 8px; } details.add { margin: 4px 0; } @@ -155,10 +103,6 @@ details.add { margin: 4px 0; } .login h1 { font-size: 2rem; justify-content: center; } @media (max-width: 640px) { - main { padding: 16px; } - .top { padding: 10px 16px; gap: 12px; flex-wrap: wrap; } - .top nav { order: 3; flex-basis: 100%; overflow-x: auto; } - .me span { display: none; } .session form.grow { flex-basis: 100%; } ul.tasks li { flex-direction: column; align-items: flex-start; } .board { grid-template-columns: 1fr; } @@ -167,9 +111,9 @@ details.add { margin: 4px 0; } .consent { text-align: left; align-items: stretch; } .consent h1 { justify-content: flex-start; } .scopes { margin: 0; padding-left: 20px; } -.mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; } +.mcp-url { display: block; padding: 10px 12px; background: var(--muted); border-radius: 8px; overflow-x: auto; } -.ok { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } +.ok { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } .help ul { padding-left: 20px; } .help li { margin: 4px 0; } @@ -182,8 +126,7 @@ table.tools td.mono { white-space: nowrap; } ul.members { list-style: none; padding: 0; margin: 0 0 10px; } ul.members li { display: flex; gap: 10px; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed var(--border); } -.foot { max-width: 960px; margin: 0 auto; padding: 16px 24px 32px; font-size: 0.8rem; text-align: center; } dl.repo { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0 0 10px; } -dl.repo dt { color: var(--muted); } +dl.repo dt { color: var(--muted-foreground); } dl.repo dd { margin: 0; } diff --git a/apps/web/components/ActivityAside.tsx b/apps/web/components/ActivityAside.tsx new file mode 100644 index 00000000..f078ea1e --- /dev/null +++ b/apps/web/components/ActivityAside.tsx @@ -0,0 +1,64 @@ +import Link from "next/link"; +import { ago } from "@/components/ui"; +import { requireUser } from "@/lib/auth"; +import { activeSessions, inbox } from "@/lib/queries"; +import { SESSION_STATUS, TONE_BG } from "@/lib/status"; +import { cn } from "@/lib/utils"; + +/** Default right panel: what waits for the PM and what is running now. */ +export async function ActivityAside({ questions = true }: { questions?: boolean }) { + const user = await requireUser(); + const [items, sessions] = await Promise.all([questions ? inbox(user.id) : [], activeSessions(user.id)]); + return ( + <div className="flex flex-col gap-6"> + {questions && ( + <PanelSection title="Ждут тебя" count={items.length} href="/" more="на Главную"> + {items.length === 0 ? ( + <p className="text-sm text-muted-foreground">Агентам ничего не нужно.</p> + ) : ( + items.slice(0, 6).map((q) => ( + <Link key={q.id} href={q.taskKey ? `/t/${q.taskKey}` : "/"} className="block rounded-md border border-primary/25 bg-primary/5 px-3 py-2 text-sm text-foreground hover:border-primary/50 hover:no-underline"> + <span className="font-mono text-xs text-primary">{q.taskKey ?? `#${q.id}`}</span>{" "} + <span className="line-clamp-2 text-muted-foreground">{q.text}</span> + </Link> + )) + )} + </PanelSection> + )} + <PanelSection title="Активные раннеры" count={sessions.length} href="/runners" more="все"> + {sessions.length === 0 ? ( + <p className="text-sm text-muted-foreground">Сейчас ничего не запущено.</p> + ) : ( + sessions.slice(0, 12).map((s) => { + const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const }; + return ( + <Link key={s.id} href={`/runners?id=${s.id}`} className="flex items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground hover:bg-accent hover:no-underline"> + <span className={cn("size-2 shrink-0 rounded-full", TONE_BG[st.tone], s.status === "running" && "animate-pulse")} title={st.label} /> + <span className="shrink-0 font-mono text-xs">{s.taskKey ?? s.projectKey}</span> + <span className="min-w-0 flex-1 truncate text-muted-foreground">{s.taskTitle}</span> + <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{ago(s.lastActivityAt)}</span> + </Link> + ); + }) + )} + </PanelSection> + </div> + ); +} + +export function PanelSection({ title, count, href, more, children }: { title: string; count?: number; href?: string; more?: string; children: React.ReactNode }) { + return ( + <section className="flex flex-col gap-2"> + <h2 className="m-0 flex items-center gap-2 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase"> + {title} + {count != null && count > 0 && <span className="rounded bg-muted px-1.5 text-foreground tabular-nums">{count}</span>} + {href && more && ( + <Link href={href} className="ml-auto font-sans text-xs font-normal tracking-normal normal-case text-muted-foreground hover:text-foreground"> + {more} → + </Link> + )} + </h2> + {children} + </section> + ); +} diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx index 5ea89464..eab5f3be 100644 --- a/apps/web/components/Footer.tsx +++ b/apps/web/components/Footer.tsx @@ -8,7 +8,7 @@ export function Footer() { const date = process.env.NEXT_PUBLIC_PEPPA_COMMIT_DATE; const dirty = process.env.NEXT_PUBLIC_PEPPA_DIRTY; return ( - <footer className="foot muted"> + <footer className="px-4 py-6 text-center text-xs text-muted-foreground"> Peppa v{version} {commit && ( <> diff --git a/apps/web/components/Nav.tsx b/apps/web/components/Nav.tsx deleted file mode 100644 index 350d8119..00000000 --- a/apps/web/components/Nav.tsx +++ /dev/null @@ -1,33 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { usePathname } from "next/navigation"; - -const ITEMS = [ - { href: "/", label: "Главная", match: (p: string) => p === "/" }, - { href: "/projects", label: "Проекты", match: (p: string) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, - { href: "/runners", label: "Раннеры", match: (p: string) => p.startsWith("/runners") }, - { href: "/help", label: "Помощь", match: (p: string) => p.startsWith("/help") }, -]; - -export function Nav() { - const path = usePathname(); - return ( - <nav> - {ITEMS.map((i) => ( - <Link key={i.href} href={i.href} className={i.match(path) ? "active" : undefined} aria-current={i.match(path) ? "page" : undefined}> - {i.label} - </Link> - ))} - </nav> - ); -} - -export function SettingsLink() { - const active = usePathname().startsWith("/settings"); - return ( - <Link href="/settings" className={active ? "active" : undefined} aria-current={active ? "page" : undefined}> - Настройки - </Link> - ); -} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx new file mode 100644 index 00000000..a6b9c43e --- /dev/null +++ b/apps/web/components/Sidebar.tsx @@ -0,0 +1,77 @@ +"use client"; + +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, type LucideIcon } from "lucide-react"; +import { ThemeToggle } from "@/components/ThemeToggle"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +interface Item { + href: string; + label: string; + icon: LucideIcon; + match: (p: string) => boolean; + count?: "questions" | "waitingRunners"; +} + +const ITEMS: Item[] = [ + { href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" }, + { href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, + { href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, + { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, + { href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") }, +]; +const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" }; + +/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */ +export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number> }) { + const path = usePathname(); + return ( + <header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-sidebar px-3 md:h-dvh md:flex-col md:items-stretch md:gap-1 md:border-r md:border-b-0 md:px-3 md:py-4"> + <Link href="/" className="flex shrink-0 items-center gap-2 rounded-md px-1 text-foreground hover:no-underline md:mb-4 md:px-2"> + <span className="grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]">P</span> + <span className="font-mono text-[15px] font-semibold tracking-tight">peppa</span> + <span className="hidden font-mono text-[11px] text-muted-foreground md:inline">фабрика</span> + </Link> + <nav + aria-label="Разделы" + className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur md:static md:flex md:flex-col md:gap-0.5 md:border-0 md:bg-transparent md:pb-0 md:backdrop-blur-none" + > + {ITEMS.map((i) => { + const active = i.match(path); + const n = i.count ? counts[i.count] : 0; + return ( + <Link + key={i.href} + href={i.href} + aria-current={active ? "page" : undefined} + className={cn( + "relative flex flex-col items-center gap-0.5 px-1 pt-2 pb-1.5 text-[10px] text-muted-foreground transition-colors hover:text-foreground hover:no-underline md:flex-row md:gap-2 md:rounded-md md:px-2.5 md:py-1.5 md:text-sm md:hover:bg-accent", + active && "font-medium text-foreground md:bg-accent md:before:absolute md:before:inset-y-1.5 md:before:-left-3 md:before:w-0.5 md:before:rounded-full md:before:bg-primary", + )} + > + <i.icon className={cn("size-5 md:size-4", active && "text-primary")} /> + <span>{i.label}</span> + {n > 0 && ( + <span title={`${n} ${COUNT_TITLE[i.count!]}`} className="absolute top-1 left-[calc(50%+6px)] min-w-4 rounded-full bg-primary px-1 text-center font-mono text-[10px] font-semibold leading-4 text-primary-foreground tabular-nums md:static md:ml-auto md:min-w-5 md:px-1.5 md:text-[11px] md:leading-5"> + {n} + </span> + )} + </Link> + ); + })} + </nav> + <div className="ml-auto flex shrink-0 items-center gap-1 md:mt-auto md:ml-0 md:border-t md:pt-3"> + {avatarUrl && <img src={avatarUrl} alt="" width={24} height={24} className="hidden size-6 rounded-full md:block" />} + <span className="hidden min-w-0 flex-1 truncate text-sm md:block" title={login}>{login}</span> + <ThemeToggle /> + <form action="/logout" method="post"> + <Button variant="ghost" size="icon-sm" aria-label="Выйти" title="Выйти"> + <LogOut /> + </Button> + </form> + </div> + </header> + ); +} diff --git a/apps/web/components/ThemeToggle.tsx b/apps/web/components/ThemeToggle.tsx new file mode 100644 index 00000000..daf812fe --- /dev/null +++ b/apps/web/components/ThemeToggle.tsx @@ -0,0 +1,19 @@ +"use client"; + +import { Moon, Sun } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { THEME_COOKIE } from "@/lib/theme"; + +/** Dark ⇄ light; the choice lives in a cookie for a year (the root layout reads it). */ +export function ThemeToggle() { + const toggle = () => { + const dark = document.documentElement.classList.toggle("dark"); + document.cookie = `${THEME_COOKIE}=${dark ? "dark" : "light"}; path=/; max-age=31536000; samesite=lax`; + }; + return ( + <Button variant="ghost" size="icon-sm" onClick={toggle} aria-label="Сменить тему" title="Сменить тему"> + <Sun className="hidden dark:block" /> + <Moon className="dark:hidden" /> + </Button> + ); +} diff --git a/apps/web/components/Workspace.tsx b/apps/web/components/Workspace.tsx new file mode 100644 index 00000000..2ea900f4 --- /dev/null +++ b/apps/web/components/Workspace.tsx @@ -0,0 +1,27 @@ +import type { ReactNode } from "react"; +import { ActivityAside } from "@/components/ActivityAside"; +import { Footer } from "@/components/Footer"; + +/** + * Centre + right panel of the console (PEP-38). The page decides what the right panel shows; + * without `aside` it gets the default activity panel, `aside={null}` hides it. + * Below xl the panel goes under the page content, the footer is always last. + */ +export function Workspace({ children, aside }: { children: ReactNode; aside?: ReactNode }) { + const panel = aside === undefined ? <ActivityAside /> : aside; + return ( + <div className="grid flex-1 xl:grid-cols-[minmax(0,1fr)_360px] xl:grid-rows-[1fr_auto]"> + <main className="min-w-0 px-4 py-5 md:px-8 md:py-7"> + <div className="mx-auto w-full max-w-5xl">{children}</div> + </main> + {panel && ( + <aside aria-label="Панель" className="min-w-0 border-t bg-sidebar/60 px-4 py-5 xl:sticky xl:top-0 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:h-dvh xl:overflow-y-auto xl:border-t-0 xl:border-l"> + {panel} + </aside> + )} + <div className="xl:col-start-1"> + <Footer /> + </div> + </div> + ); +} diff --git a/apps/web/components/ui/badge.tsx b/apps/web/components/ui/badge.tsx new file mode 100644 index 00000000..9ba16729 --- /dev/null +++ b/apps/web/components/ui/badge.tsx @@ -0,0 +1,29 @@ +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "@/lib/utils"; + +const badgeVariants = cva( + "inline-flex w-fit shrink-0 items-center gap-1 whitespace-nowrap rounded-full border px-2 py-0.5 text-xs font-medium [&>svg]:size-3", + { + variants: { + variant: { + default: "border-transparent bg-primary text-primary-foreground", + secondary: "border-transparent bg-secondary text-secondary-foreground", + outline: "border-border text-muted-foreground", + primary: "border-primary/30 bg-primary/12 text-primary", + ok: "border-ok/30 bg-ok/12 text-ok", + warn: "border-warn/30 bg-warn/12 text-warn", + info: "border-info/30 bg-info/12 text-info", + danger: "border-destructive/30 bg-destructive/12 text-destructive", + muted: "border-transparent bg-muted text-muted-foreground", + }, + }, + defaultVariants: { variant: "secondary" }, + }, +); + +function Badge({ className, variant, ...props }: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) { + return <span data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />; +} + +export { Badge, badgeVariants }; diff --git a/apps/web/components/ui/button.tsx b/apps/web/components/ui/button.tsx new file mode 100644 index 00000000..24b1aa75 --- /dev/null +++ b/apps/web/components/ui/button.tsx @@ -0,0 +1,42 @@ +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "@/lib/utils"; + +const buttonVariants = cva( + "inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md border border-transparent text-sm font-medium transition-colors outline-none hover:no-underline focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 cursor-pointer", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", + destructive: "border-destructive/40 bg-destructive/10 text-destructive hover:bg-destructive/20", + outline: "border-border bg-card text-foreground shadow-xs hover:bg-accent", + secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "bg-transparent text-foreground hover:bg-accent", + link: "h-auto border-0 bg-transparent p-0 text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2", + sm: "h-8 gap-1.5 px-3 text-[13px]", + xs: "h-7 gap-1 rounded-md px-2 text-xs", + lg: "h-10 px-6", + icon: "size-9", + "icon-sm": "size-8", + }, + }, + defaultVariants: { variant: "outline", size: "default" }, + }, +); + +function Button({ + className, + variant, + size, + asChild = false, + ...props +}: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & { asChild?: boolean }) { + const Comp = asChild ? Slot : "button"; + return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />; +} + +export { Button, buttonVariants }; diff --git a/apps/web/components/ui/card.tsx b/apps/web/components/ui/card.tsx new file mode 100644 index 00000000..914fd1e0 --- /dev/null +++ b/apps/web/components/ui/card.tsx @@ -0,0 +1,24 @@ +import * as React from "react"; +import { cn } from "@/lib/utils"; + +function Card({ className, ...props }: React.ComponentProps<"div">) { + return <div data-slot="card" className={cn("flex flex-col gap-3 rounded-lg border bg-card p-4 text-card-foreground", className)} {...props} />; +} + +function CardHeader({ className, ...props }: React.ComponentProps<"div">) { + return <div data-slot="card-header" className={cn("flex flex-wrap items-center gap-x-2 gap-y-1", className)} {...props} />; +} + +function CardTitle({ className, ...props }: React.ComponentProps<"div">) { + return <div data-slot="card-title" className={cn("font-semibold leading-tight", className)} {...props} />; +} + +function CardDescription({ className, ...props }: React.ComponentProps<"div">) { + return <div data-slot="card-description" className={cn("text-sm text-muted-foreground", className)} {...props} />; +} + +function CardContent({ className, ...props }: React.ComponentProps<"div">) { + return <div data-slot="card-content" className={cn("text-sm", className)} {...props} />; +} + +export { Card, CardHeader, CardTitle, CardDescription, CardContent }; diff --git a/apps/web/components/ui/input.tsx b/apps/web/components/ui/input.tsx new file mode 100644 index 00000000..91f2c845 --- /dev/null +++ b/apps/web/components/ui/input.tsx @@ -0,0 +1,24 @@ +import * as React from "react"; +import { cn } from "@/lib/utils"; + +const fieldClass = + "w-full min-w-0 rounded-md border border-input bg-background/60 px-3 text-sm text-foreground shadow-xs outline-none transition-[color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40 disabled:opacity-50"; + +function Input({ className, type = "text", ...props }: React.ComponentProps<"input">) { + return <input type={type} data-slot="input" className={cn(fieldClass, "h-9 py-1", className)} {...props} />; +} + +function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { + return <textarea data-slot="textarea" className={cn(fieldClass, "min-h-16 resize-y py-2", className)} {...props} />; +} + +/** Native select styled like the inputs: no client JS, works inside server-action forms. */ +function NativeSelect({ className, ...props }: React.ComponentProps<"select">) { + return <select data-slot="select" className={cn(fieldClass, "h-9 py-1 pr-8", className)} {...props} />; +} + +function Label({ className, ...props }: React.ComponentProps<"label">) { + return <label data-slot="label" className={cn("flex flex-col gap-1.5 text-sm font-medium", className)} {...props} />; +} + +export { Input, Textarea, NativeSelect, Label, fieldClass }; diff --git a/apps/web/components/ui/separator.tsx b/apps/web/components/ui/separator.tsx new file mode 100644 index 00000000..9db84437 --- /dev/null +++ b/apps/web/components/ui/separator.tsx @@ -0,0 +1,8 @@ +import * as React from "react"; +import { cn } from "@/lib/utils"; + +function Separator({ className, ...props }: React.ComponentProps<"hr">) { + return <hr data-slot="separator" className={cn("my-4 border-0 border-t border-border", className)} {...props} />; +} + +export { Separator }; diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index 25ba05a2..12261d7c 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -2,6 +2,7 @@ import { getUser, isUserAllowed, sign, verify, type User } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { cookies, headers } from "next/headers"; import { redirect } from "next/navigation"; +import { cache } from "react"; import { db } from "./db"; export const SESSION_COOKIE = "peppa_session"; @@ -17,13 +18,14 @@ interface SessionPayload { exp: number; } -export async function currentUser(): Promise<User | null> { +/** Memoized per request: the layout, the page and the side panel all ask for the user. */ +export const currentUser = cache(async (): Promise<User | null> => { const p = verify<SessionPayload>((await cookies()).get(SESSION_COOKIE)?.value); if (!p || p.exp < Date.now()) return null; const user = await getUser(db, p.uid); // Removed from the allowlist → the session stops working right away. return user && (await isUserAllowed(db, user)) ? user : null; -} +}); /** For pages and server actions: the logged-in user, or a redirect to /login. */ export async function requireUser(): Promise<User> { diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index 3ac1e0d4..8c72f872 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { listSessions, PeppaError, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core"; import { events, goals, projects, questions, sessions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { and, asc, desc, eq, inArray, isNull } from "drizzle-orm"; +import { and, asc, count, desc, eq, inArray, isNull } from "drizzle-orm"; import { db } from "./db"; export type InboxItem = Awaited<ReturnType<typeof inbox>>[number]; @@ -76,3 +76,12 @@ export function openspecArtifacts(p: Project, change: string | null): Array<{ na .map((f) => ({ name: f, text: readFileSync(join(dir, f), "utf8") })); } + +/** Counters of the side navigation (PEP-38): open PM questions and runners waiting for the PM. */ +export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number }> { + const ids = await userProjectIds(db, userId); + if (!ids.length) return { questions: 0, waitingRunners: 0 }; + const [q] = await db.select({ n: count() }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))); + const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input"))); + return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0 }; +} diff --git a/apps/web/lib/status.ts b/apps/web/lib/status.ts new file mode 100644 index 00000000..19a42d1c --- /dev/null +++ b/apps/web/lib/status.ts @@ -0,0 +1,42 @@ +// Labels and colour tones of task and runner statuses, shared by badges, rows and the side panel. +export type Tone = "primary" | "ok" | "warn" | "info" | "danger" | "muted"; + +export const TASK_STATUS: Record<string, { label: string; tone: Tone }> = { + backlog: { label: "Бэклог", tone: "muted" }, + proposing: { label: "Proposal", tone: "primary" }, + awaiting_approval: { label: "Ждёт одобрения", tone: "primary" }, + in_progress: { label: "В работе", tone: "info" }, + review: { label: "Ревью", tone: "ok" }, + done: { label: "Готово", tone: "ok" }, + blocked: { label: "Блок", tone: "danger" }, +}; + +export const SESSION_STATUS: Record<string, { label: string; tone: Tone }> = { + starting: { label: "запуск", tone: "info" }, + running: { label: "работает", tone: "info" }, + waiting_input: { label: "ждёт тебя", tone: "primary" }, + idle: { label: "простаивает", tone: "muted" }, + stalled: { label: "зависла?", tone: "warn" }, + rate_limited: { label: "лимит", tone: "warn" }, + done: { label: "завершена", tone: "ok" }, + failed: { label: "упала", tone: "danger" }, +}; + +/** Text colour per tone, e.g. for status dots. */ +export const TONE_TEXT: Record<Tone, string> = { + primary: "text-primary", + ok: "text-ok", + warn: "text-warn", + info: "text-info", + danger: "text-destructive", + muted: "text-muted-foreground", +}; + +export const TONE_BG: Record<Tone, string> = { + primary: "bg-primary", + ok: "bg-ok", + warn: "bg-warn", + info: "bg-info", + danger: "bg-destructive", + muted: "bg-muted-foreground", +}; diff --git a/apps/web/lib/theme.ts b/apps/web/lib/theme.ts new file mode 100644 index 00000000..3dac8b48 --- /dev/null +++ b/apps/web/lib/theme.ts @@ -0,0 +1,2 @@ +/** Cookie with the chosen theme: "light" or "dark" (default when missing). */ +export const THEME_COOKIE = "peppa_theme"; diff --git a/apps/web/lib/utils.ts b/apps/web/lib/utils.ts new file mode 100644 index 00000000..a5ef1935 --- /dev/null +++ b/apps/web/lib/utils.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from "clsx"; +import { twMerge } from "tailwind-merge"; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} diff --git a/apps/web/package.json b/apps/web/package.json index a2c02f27..81159059 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -10,20 +10,28 @@ "typecheck": "tsc -p ." }, "dependencies": { + "@modelcontextprotocol/sdk": "1.32.2", "@peppa/bugsink": "workspace:*", + "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", + "@peppa/mcp": "workspace:*", + "@peppa/runner": "workspace:*", "@peppa/shared": "workspace:*", + "@radix-ui/react-slot": "1.5.0", + "class-variance-authority": "0.7.1", + "clsx": "2.1.1", + "drizzle-orm": "0.45.4", + "geist": "1.9.2", + "lucide-react": "1.72.0", "next": "16.4.6", "react": "19.3.1", "react-dom": "19.3.1", - "@peppa/core": "workspace:*", - "@peppa/runner": "workspace:*", - "drizzle-orm": "0.45.4", - "@peppa/mcp": "workspace:*", - "@modelcontextprotocol/sdk": "1.32.2" + "tailwind-merge": "3.7.0" }, "devDependencies": { + "@tailwindcss/postcss": "4.3.5", "@types/react": "19.3.0", - "@types/react-dom": "19.3.0" + "@types/react-dom": "19.3.0", + "tailwindcss": "4.3.5" } } diff --git a/apps/web/postcss.config.mjs b/apps/web/postcss.config.mjs new file mode 100644 index 00000000..a9b5c43d --- /dev/null +++ b/apps/web/postcss.config.mjs @@ -0,0 +1 @@ +export default { plugins: { "@tailwindcss/postcss": {} } }; diff --git a/apps/web/scripts/mock-ui-seed.ts b/apps/web/scripts/mock-ui-seed.ts new file mode 100644 index 00000000..a5e81e4c --- /dev/null +++ b/apps/web/scripts/mock-ui-seed.ts @@ -0,0 +1,112 @@ +// Demo data for checking the web UI by eye (PEP-38): a user, two projects, goals, tasks on every board +// column, runners in every status (one hit the usage limit and resumes later), open questions, releases. +// Only for a throwaway database — refuses the production one: +// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login] +import { mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createDb, events, goals, projects, questions, releases, sessions, tasks, users } from "@peppa/db"; +import { eq } from "drizzle-orm"; + +const url = process.env.DATABASE_URL ?? ""; +if (!url || /\/peppa$/.test(url)) throw new Error("mock-ui-seed: point DATABASE_URL at a throwaway database, not the production one"); +const login = process.argv[2] ?? "mock-pm"; +const db = createDb(url); +const ago = (min: number) => new Date(Date.now() - min * 60_000); +const ws = join(tmpdir(), "peppa-mock-ui"); + +// Negative Gitea id = local account: allowed in without the allowlist. +const [user] = await db.insert(users).values({ giteaId: -900001, login }).onConflictDoUpdate({ target: users.login, set: { login } }).returning(); + +async function project(key: string, name: string, slug: string) { + mkdirSync(join(ws, slug), { recursive: true }); + const [p] = await db + .insert(projects) + .values({ key, name, slug, giteaOwner: login, giteaRepo: slug, workspacePath: join(ws, slug), ownerId: user!.id }) + .returning(); + return p!; +} + +const pay = await project("PAY", "Платёжный сервис", "mock-payments"); +const shop = await project("SHOP", "Витрина магазина", "mock-shop"); +const [g1, g2] = await db + .insert(goals) + .values([ + { projectId: pay.id, title: "Оплата картой", description: "Карты РФ и СБП" }, + { projectId: pay.id, title: "Стабильность", description: "Ошибки из прода" }, + ]) + .returning(); + +type T = { title: string; status: (typeof tasks.$inferInsert)["status"]; goalId?: number; description?: string; prUrl?: string }; +async function addTasks(projectId: number, list: T[]) { + const rows = await db + .insert(tasks) + .values(list.map((t, i) => ({ projectId, number: i + 1, ...t }))) + .returning(); + await db.update(projects).set({ nextTaskNumber: list.length + 1 }).where(eq(projects.id, projectId)); + return rows; +} +const pt = await addTasks(pay.id, [ + { title: "Оплата картой через ЮKassa", status: "in_progress", goalId: g1!.id, description: "Подключить ЮKassa, вебхуки статуса платежа." }, + { title: "Возвраты платежей", status: "awaiting_approval", goalId: g1!.id }, + { title: "Оплата по СБП", status: "in_progress", goalId: g1!.id }, + { title: "Чеки по 54-ФЗ", status: "review", goalId: g1!.id, prUrl: "https://git.telecom.quest/mock/mock-payments/pulls/4" }, + { title: "TypeError в форме оплаты", status: "backlog", goalId: g2!.id }, + { title: "Логи платежей в Bugsink", status: "done", goalId: g2!.id }, + { title: "Рефакторинг конфигурации", status: "proposing" }, +]); +const st = await addTasks(shop.id, [ + { title: "Каталог с фильтрами", status: "in_progress" }, + { title: "Корзина и промокоды", status: "blocked" }, + { title: "Поиск по товарам", status: "backlog" }, +]); + +type S = { task: (typeof pt)[number]; status: (typeof sessions.$inferInsert)["status"]; min: number; provider?: "claude" | "codex"; resumeAt?: Date; gen?: number }; +const runners: S[] = [ + { task: pt[1]!, status: "waiting_input", min: 3 }, + { task: pt[0]!, status: "running", min: 1 }, + { task: pt[2]!, status: "rate_limited", min: 42, resumeAt: new Date(Date.now() + 95 * 60_000), gen: 2 }, + { task: pt[3]!, status: "idle", min: 18 }, + { task: st[0]!, status: "running", min: 0, provider: "codex" }, + { task: st[1]!, status: "stalled", min: 27 }, + { task: pt[5]!, status: "done", min: 600 }, + { task: pt[4]!, status: "failed", min: 1500 }, +]; +const made = []; +for (const [i, r] of runners.entries()) { + const key = r.task.projectId === pay.id ? "pay" : "shop"; + const [s] = await db + .insert(sessions) + .values({ + projectId: r.task.projectId, + taskId: r.task.id, + tmuxName: `peppa-${key}-${r.task.number}-s${100 + i}`, + provider: r.provider ?? "claude", + status: r.status, + generation: r.gen ?? 1, + lastActivityAt: ago(r.min), + resumeAt: r.resumeAt ?? null, + limitResumes: r.resumeAt ? 1 : 0, + startedAt: ago(r.min + 30), + endedAt: r.status === "done" || r.status === "failed" ? ago(r.min) : null, + }) + .returning(); + made.push(s!); +} + +await db.insert(questions).values([ + { projectId: pay.id, taskId: pt[1]!.id, sessionId: made[0]!.id, kind: "approval", text: "Proposal pep-2-refunds: частичные возвраты через API ЮKassa, новая таблица refunds. Одобрить?" }, + { projectId: pay.id, taskId: pt[0]!.id, sessionId: made[1]!.id, kind: "permission", text: "Bash: pnpm add @yookassa/sdk@3.1.0" }, + { projectId: pay.id, taskId: pt[3]!.id, sessionId: made[3]!.id, kind: "attention", text: "PAY-4 готово к ревью: чеки уходят в АТОЛ, PR #4, проверки зелёные." }, + { projectId: shop.id, taskId: st[1]!.id, kind: "question", text: "Промокоды суммируются со скидкой на товар?", options: ["Да", "Нет, берём большую"] }, +]); +await db.insert(events).values([ + { projectId: pay.id, taskId: pt[0]!.id, sessionId: made[1]!.id, type: "progress", payload: { text: "Вебхук статуса платежа готов, пишу тесты" } }, + { projectId: pay.id, taskId: pt[0]!.id, type: "task_updated", payload: { to: { status: "in_progress" } } }, +]); +await db.insert(releases).values([ + { projectId: pay.id, env: "staging", sha: "a1b2c3d4e5f6", status: "healthy", host: "mock-payments-staging.telecom.quest", tasks: ["PAY-6"], deployedBy: "ci" }, + { projectId: pay.id, env: "prod", sha: "9f8e7d6c5b4a", status: "healthy", host: "mock-payments-prod.telecom.quest", tasks: ["PAY-5"], deployedBy: login }, +]); +console.log(`seeded: user ${login}, projects PAY and SHOP, ${made.length} runners`); +process.exit(0); diff --git a/openspec/changes/pep-38-factory-console/design.md b/openspec/changes/pep-38-factory-console/design.md new file mode 100644 index 00000000..608e0cce --- /dev/null +++ b/openspec/changes/pep-38-factory-console/design.md @@ -0,0 +1,56 @@ +# Дизайн: пульт фабрики + +## Стек +- **Tailwind v4** через `@tailwindcss/postcss` (`postcss.config.mjs`), конфиг в CSS + (`@theme inline`) — без `tailwind.config.js`. +- **shadcn/ui** — копируем исходники нужных компонентов в `components/ui/` (button, + badge, card, input, textarea, select, label, separator, kbd-подобные мелочи), без CLI и + без сети: компоненты — обычный код репо, правим под себя. Radix только `react-slot` + (для `asChild`); выпадашки/диалоги не нужны — формы остаются серверными (server + actions), без клиентского JS там, где его не было. +- **Иконки** — `lucide-react`. +- **Шрифты** — `geist` (локальные woff2 через `next/font/local` внутри пакета): сборка не + ходит в Google Fonts, CI работает без внешней сети. + +## Тема +CSS-переменные в стиле shadcn (`--background`, `--foreground`, `--card`, `--muted`, +`--primary`, `--border`, …) + свои статусные (`--ok`, `--warn`, `--danger`, `--info`). +`:root` — светлая, `.dark` — тёмная. Корневой layout читает cookie `peppa_theme` на +сервере и ставит `class="dark"` на `<html>`, если cookie не `light` — тёмная по +умолчанию, без мигания и без инлайн-скрипта. Переключатель в навигации меняет класс и +пишет cookie на год. + +Один яркий акцент — розовый Пеппы (`--primary`), остальное — нейтральные серо-синие +поверхности; моноширинный шрифт для ключей задач, tmux-имён и строк раннеров. + +## Раскладка +`app/(app)/layout.tsx`: грид `[nav 232px] [страница]`. Страница сама решает, есть ли у +неё правая панель: компонент `Workspace({ children, aside })` рисует центр и правую +колонку (`xl:grid-cols-[minmax(0,1fr)_360px]`). Так правая панель зависит от данных +страницы (выбранный раннер), без параллельных маршрутов Next. +- Без `aside` страница получает панель по умолчанию `ActivityAside`: «ждут тебя» + (сколько и ссылка на Главную) и активные раннеры коротким списком. +- Ниже `xl` правая панель уходит под центр; ниже `md` сверху остаётся полоса с логотипом, + темой и выходом, а разделы — панель вкладок внизу экрана (5 пунктов со счётчиками). +- Счётчик «ждут тебя» в навигации — число открытых вопросов PM (`inbox`), считается в + layout на каждый запрос (страницы и так `force-dynamic`), раннеры — число раннеров в + `waiting_input`. + +## Перенос (этап 2) +Каждая страница переписывается на компоненты; классы старого CSS исчезают вместе с +файлом. Функциональность и формы (server actions, скрытые поля `back`) — без изменений. +Этап 1 подключает старый CSS как `@import "./legacy.css" layer(base)`: в слое `base` он +проигрывает утилитам Tailwind, поэтому новые компоненты и старые страницы уживаются. + +## Пульт раннеров (этап 3) +- Фильтры — ссылки `?f=` со счётчиками (как в PEP-61), поиск — `?q=` (GET-форма, работает + без JS) по ключу задачи, названию, проекту, tmux-имени и номеру. +- Строка: цветная точка статуса, `KEY-N` моно, название, проект, агент, «N мин назад»; + `waiting_input` подсвечен акцентом; `rate_limited` с `resume_at` в будущем — + «остановлена · продолжит в HH:MM» (время в часовом поясе браузера: маленький клиентский + компонент, сервер отдаёт ISO). +- Выбор — `?id=<session>`; правая панель — детали: статус, задача, проект, агент, + поколение, tmux attach, лимит (продолжит в, сколько авто-продолжений сегодня), открытые + вопросы этого раннера с формой ответа, сообщение в сессию, остановить/resume и + заглушка «Терминал — PEP-9». На мобильной ширине выбранный раннер показывается + над списком. diff --git a/openspec/changes/pep-38-factory-console/proposal.md b/openspec/changes/pep-38-factory-console/proposal.md new file mode 100644 index 00000000..d364a85d --- /dev/null +++ b/openspec/changes/pep-38-factory-console/proposal.md @@ -0,0 +1,39 @@ +# PEP-38: Новый UI «пульт фабрики» + +## Зачем +Веб Пеппы вырос из одной страницы входящих: верхнее меню, страницы-простыни, свой CSS +на 190 строк. PM хочет пульт: всё важное на одном экране — навигация со счётчиком «ждут +тебя», список раннеров, детали выбранного раннера (позже — живой терминал, PEP-9). +Референс — detachbox. Решение PM (2026-11-13): shadcn/ui + Tailwind, иконки lucide, +тёмная тема по умолчанию. + +## Что меняется +- **Основа**: Tailwind CSS v4 и компоненты в стиле shadcn/ui (`apps/web/components/ui/*`, + исходники в репо, без рантайм-библиотеки), lucide-react, шрифты Geist Sans/Mono + (пакет `geist`, без загрузки из сети при сборке). Токены темы — CSS-переменные; тёмная + тема по умолчанию, светлая — переключателем (cookie `peppa_theme`). +- **Раскладка в три панели** на десктопе: слева навигация (Главная со счётчиком «ждут + тебя», Проекты, Раннеры со счётчиком, Помощь, Настройки, пользователь), в центре + страница, справа контекстная панель. На мобильной ширине — панель вкладок снизу, + правая панель уходит под центр. +- **Перенос всех страниц** (Главная, проекты, доска, задача, раннеры, настройки, + помощь, ошибки PEP-58, релизы и проверки PEP-57, вход, экран согласия OAuth) на + компоненты; старый `globals.css` удаляется. +- **Пульт раннеров**: список в центре с фильтрами-счётчиками (ждут тебя / работают / + упали / готово), поиском, цветными статусами, подсветкой строк, где нужен PM, и + «остановлена · продолжит в HH:MM» для лимита (`sessions.resume_at`, PEP-56). Справа — + детали выбранного раннера с действиями и местом под терминал (PEP-9). + +## Вне задачи +PEP-9 (терминал — только заглушка), PEP-5 (полоса лимитов — только место), PEP-52 (⌘K), +PEP-62 (чаты), PEP-39/PEP-33 (аккаунт агента и «что делает сейчас» в строке раннера). + +## Этапы (отдельные PR) +1. Основа + раскладка; старые стили продолжают работать в слое `base`. +2. Перенос страниц, удаление `globals.css`. +3. Пульт раннеров. + +## Влияние +Только `apps/web`. Модель данных, сервер и API не меняются. Новые зависимости веба: +`tailwindcss`, `@tailwindcss/postcss`, `lucide-react`, `class-variance-authority`, +`clsx`, `tailwind-merge`, `geist`, `@radix-ui/react-slot`. diff --git a/openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md b/openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md new file mode 100644 index 00000000..a29a2df8 --- /dev/null +++ b/openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md @@ -0,0 +1,85 @@ +# Spec Delta: web-workspace + +## ADDED Requirements + +### Requirement: Раскладка пульта +Веб SHALL показывать вошедшему пользователю раскладку в три панели: слева навигация, в центре страница, справа контекстная панель; на узком экране разделы — панель вкладок снизу, а правая панель уходит под центр. + +#### Scenario: Десктоп +- **GIVEN** вошедший пользователь на экране шириной 1440 px +- **WHEN** он открывает любую страницу за входом +- **THEN** слева видна навигация «Главная», «Проекты», «Раннеры», «Помощь», «Настройки», в центре — страница, справа — контекстная панель + +#### Scenario: Телефон +- **GIVEN** вошедший пользователь на экране шириной 390 px +- **WHEN** он открывает Главную +- **THEN** разделы — панель вкладок внизу экрана, страница не прокручивается по горизонтали, правая панель — под содержимым + +### Requirement: Счётчик «ждут тебя» +Навигация SHALL показывать у пункта «Главная» число открытых вопросов агентов по проектам пользователя, а у пункта «Раннеры» — число раннеров, ждущих PM. + +#### Scenario: Есть вопросы +- **GIVEN** в проектах пользователя 3 неотвеченных вопроса и 1 раннер в статусе «ждёт тебя» +- **WHEN** он открывает любую страницу +- **THEN** у «Главная» стоит счётчик 3, у «Раннеры» — 1 + +#### Scenario: Ничего не ждёт +- **GIVEN** открытых вопросов и ждущих раннеров нет +- **WHEN** пользователь открывает любую страницу +- **THEN** счётчиков в навигации нет + +### Requirement: Тема оформления +Веб SHALL открываться в тёмной теме по умолчанию и позволять переключиться на светлую; выбор SHALL сохраняться между визитами. + +#### Scenario: Первый визит +- **GIVEN** пользователь ни разу не переключал тему +- **WHEN** он открывает веб +- **THEN** страница в тёмной теме + +#### Scenario: Светлая тема сохраняется +- **GIVEN** пользователь переключил тему на светлую +- **WHEN** он закрывает и снова открывает веб +- **THEN** страница в светлой теме без мигания тёмной + +## MODIFIED Requirements + +### Requirement: Верхнее меню +Веб SHALL показывать меню навигации с пунктами «Главная», «Проекты», «Раннеры», «Помощь», «Настройки» и подсвечивать текущий раздел; на десктопе меню — левая панель, на узком экране — панель вкладок снизу. + +#### Scenario: Главная +- **GIVEN** вошедший пользователь +- **WHEN** он открывает корень сайта +- **THEN** в меню подсвечен пункт «Главная», пункта «Входящие» нет + +#### Scenario: Задача проекта +- **GIVEN** вошедший пользователь +- **WHEN** он открывает страницу задачи «PAY-3» +- **THEN** в меню подсвечен пункт «Проекты» + +### Requirement: Список раннеров +Страница «Раннеры» SHALL показывать в центре раннеры всех проектов пользователя (своих и общих) со статусом, проектом и задачей, агентом и временем последней активности, с фильтрами-счётчиками по состоянию и поиском, а справа — детали выбранного раннера с действиями. + +#### Scenario: Раннер ждёт ответа +- **GIVEN** у пользователя раннер по задаче PAY-3 в статусе «ждёт тебя» и раннер по PAY-4 «работает» +- **WHEN** он открывает «Раннеры» и выбирает фильтр «ждут тебя» +- **THEN** в списке только раннер PAY-3, строка подсвечена, у фильтра счётчик 1 + +#### Scenario: Чужие раннеры +- **GIVEN** раннер в проекте, где пользователь не владелец и не участник +- **WHEN** пользователь открывает «Раннеры» +- **THEN** этого раннера в списке нет + +#### Scenario: Поиск +- **GIVEN** раннеры по задачам PAY-3 «Оплата картой» и PAY-4 «Возвраты» +- **WHEN** пользователь ищет «возвр» +- **THEN** в списке только раннер PAY-4 + +#### Scenario: Лимит +- **GIVEN** раннер в статусе «лимит» с временем продолжения 03:10 +- **WHEN** пользователь открывает «Раннеры» +- **THEN** в строке раннера написано «остановлена · продолжит в 03:10» + +#### Scenario: Детали раннера +- **GIVEN** раннер по задаче PAY-3 ждёт ответа на вопрос +- **WHEN** пользователь выбирает его в списке +- **THEN** справа видны статус, задача, агент, команда tmux attach, вопрос с формой ответа, кнопки «Остановить» и сообщение в сессию, и место под терминал diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/pep-38-factory-console/tasks.md new file mode 100644 index 00000000..cf8e8886 --- /dev/null +++ b/openspec/changes/pep-38-factory-console/tasks.md @@ -0,0 +1,25 @@ +# Задачи PEP-38 + +## 1. Основа (PR 1) +- [x] 1.1 Tailwind v4 + PostCSS, токены темы (тёмная по умолчанию, светлая), шрифты Geist +- [x] 1.2 Компоненты `components/ui/*` в стиле shadcn/ui, `cn()`, lucide-react +- [x] 1.3 Раскладка: левая навигация со счётчиками, `Workspace` с правой панелью, `ActivityAside`, мобильная полоса +- [x] 1.4 Переключатель темы (cookie `peppa_theme`, без мигания) +- [x] 1.5 Старый CSS в слое `base`, все маршруты открываются; проверка в браузере (desktop + 390 px) + +## 2. Перенос страниц (PR 2) +- [ ] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer +- [ ] 2.2 Главная, Проекты, Новый проект +- [ ] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий +- [ ] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события +- [ ] 2.5 Настройки, Помощь, вход, согласие OAuth +- [ ] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере + +## 3. Пульт раннеров (PR 3) +- [ ] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой +- [ ] 3.2 «остановлена · продолжит в HH:MM» по `resume_at` +- [ ] 3.3 Правая панель: детали выбранного раннера, вопросы, действия, заглушка терминала +- [ ] 3.4 Помощь обновлена; проверка в браузере + +## 4. Завершение +- [ ] 4.1 `openspec archive`, задача в review с pr_url diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 43b95916..1bbe1444 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -217,9 +217,24 @@ importers: '@peppa/shared': specifier: workspace:* version: link:../../packages/shared + '@radix-ui/react-slot': + specifier: 1.5.0 + version: 1.5.0(@types/react@19.3.0)(react@19.3.1) + class-variance-authority: + specifier: 0.7.1 + version: 0.7.1 + clsx: + specifier: 2.1.1 + version: 2.1.1 drizzle-orm: specifier: 0.45.4 version: 0.45.4(postgres@4.1.1) + geist: + specifier: 1.9.2 + version: 1.9.2(next@16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)) + lucide-react: + specifier: 1.72.0 + version: 1.72.0(@types/react@19.3.0)(react@19.3.1) next: specifier: 16.4.6 version: 16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -229,13 +244,22 @@ importers: react-dom: specifier: 19.3.1 version: 19.3.1(react@19.3.1) + tailwind-merge: + specifier: 3.7.0 + version: 3.7.0 devDependencies: + '@tailwindcss/postcss': + specifier: 4.3.5 + version: 4.3.5 '@types/react': specifier: 19.3.0 version: 19.3.0 '@types/react-dom': specifier: 19.3.0 version: 19.3.0(@types/react@19.3.0) + tailwindcss: + specifier: 4.3.5 + version: 4.3.5 packages/bugsink: {} @@ -368,6 +392,10 @@ importers: packages: + '@alloc/quick-lru@5.3.0': + resolution: {integrity: sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==} + engines: {node: '>=10'} + '@drizzle-team/brocli@0.10.2': resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} @@ -994,6 +1022,22 @@ packages: cpu: [x64] os: [win32] + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@modelcontextprotocol/sdk@1.32.2': resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} engines: {node: '>=18'} @@ -1059,9 +1103,118 @@ packages: cpu: [x64] os: [win32] + '@radix-ui/react-compose-refs@1.1.5': + resolution: {integrity: sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-slot@1.5.0': + resolution: {integrity: sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@swc/helpers@0.5.23': resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} + '@tailwindcss/node@4.3.5': + resolution: {integrity: sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==} + + '@tailwindcss/oxide-android-arm64@4.3.5': + resolution: {integrity: sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [android] + + '@tailwindcss/oxide-darwin-arm64@4.3.5': + resolution: {integrity: sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [darwin] + + '@tailwindcss/oxide-darwin-x64@4.3.5': + resolution: {integrity: sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [darwin] + + '@tailwindcss/oxide-freebsd-x64@4.3.5': + resolution: {integrity: sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [freebsd] + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5': + resolution: {integrity: sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==} + engines: {node: '>= 20'} + cpu: [arm] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.5': + resolution: {integrity: sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-arm64-musl@4.3.5': + resolution: {integrity: sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-linux-x64-gnu@4.3.5': + resolution: {integrity: sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-x64-musl@4.3.5': + resolution: {integrity: sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-wasm32-wasi@4.3.5': + resolution: {integrity: sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + bundledDependencies: + - '@napi-rs/wasm-runtime' + - '@emnapi/core' + - '@emnapi/runtime' + - '@tybys/wasm-util' + - '@emnapi/wasi-threads' + - tslib + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.5': + resolution: {integrity: sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [win32] + + '@tailwindcss/oxide-win32-x64-msvc@4.3.5': + resolution: {integrity: sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [win32] + + '@tailwindcss/oxide@4.3.5': + resolution: {integrity: sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==} + engines: {node: '>= 20'} + + '@tailwindcss/postcss@4.3.5': + resolution: {integrity: sha512-FAV37Tlx9wBiT/hkfgVD0Q6CWsP2oUX3lf28nrfjW8+ksILjnpuFulUqWDfNR4/ZiEHHDRBX8DUTzD1Rys687A==} + '@types/node@26.6.6': resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} @@ -1115,9 +1268,16 @@ packages: caniuse-lite@1.0.30001826: resolution: {integrity: sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==} + class-variance-authority@0.7.1: + resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} + client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + content-disposition@2.0.1: resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==} engines: {node: '>=18'} @@ -1276,6 +1436,10 @@ packages: resolution: {integrity: sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==} engines: {node: '>= 0.8'} + enhanced-resolve@5.26.1: + resolution: {integrity: sha512-PPnnSJq3azKOIewXR/uppBV/6h98dprBJ/WaQ9Qgj10xX1lJLNfg+XShpbsrSqcDSy2yYYyhfXM1wWhftqgyzw==} + engines: {node: '>=10.13.0'} + es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -1354,6 +1518,11 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + geist@1.9.2: + resolution: {integrity: sha512-UU1x2q5Khob0+i4csFvXk1Ki4DePdu7xISuXyEcj1tzQMg64oN7Kbuy4e5z5QhcUWbbvOMJNs3ZxYQqpsEMV3w==} + peerDependencies: + next: '>=13.2.0' + get-intrinsic@1.3.0: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} @@ -1369,6 +1538,9 @@ packages: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -1406,6 +1578,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + jose@6.2.17: resolution: {integrity: sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==} @@ -1415,6 +1591,92 @@ packages: json-schema-typed@8.0.2: resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lucide-react@1.72.0: + resolution: {integrity: sha512-fbF5i1GU8GODETa3Q7rXqrJrcx3iPYrQtxthom103zGx+Z0BGwKYAW9s+9435ohYJ7hQm0av0PoZcqI1CRwNrg==} + peerDependencies: + '@types/react': '*' + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -1505,6 +1767,10 @@ packages: resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==} engines: {node: ^10 || ^12 || >=14} + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + postgres@4.1.1: resolution: {integrity: sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug==} engines: {node: '>=18'} @@ -1628,6 +1894,16 @@ packages: babel-plugin-macros: optional: true + tailwind-merge@3.7.0: + resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==} + + tailwindcss@4.3.5: + resolution: {integrity: sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==} + + tapable@2.3.3: + resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} + engines: {node: '>=6'} + toidentifier@1.0.1: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} @@ -1678,6 +1954,8 @@ packages: snapshots: + '@alloc/quick-lru@5.3.0': {} + '@drizzle-team/brocli@0.10.2': {} '@emnapi/runtime@1.11.3': @@ -2028,6 +2306,25 @@ snapshots: '@img/sharp-win32-x64@0.35.5': optional: true + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + '@modelcontextprotocol/sdk@1.32.2(zod@4.6.7)': dependencies: '@hono/node-server': 2.1.7(hono@4.13.18) @@ -2076,10 +2373,92 @@ snapshots: '@next/swc-win32-x64-msvc@16.4.6': optional: true + '@radix-ui/react-compose-refs@1.1.5(@types/react@19.3.0)(react@19.3.1)': + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-slot@1.5.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + '@swc/helpers@0.5.23': dependencies: tslib: 2.9.1 + '@tailwindcss/node@4.3.5': + dependencies: + '@jridgewell/remapping': 2.3.5 + enhanced-resolve: 5.26.1 + jiti: 2.7.0 + lightningcss: 1.33.0 + magic-string: 1.4.5 + source-map-js: 1.2.2 + tailwindcss: 4.3.5 + + '@tailwindcss/oxide-android-arm64@4.3.5': + optional: true + + '@tailwindcss/oxide-darwin-arm64@4.3.5': + optional: true + + '@tailwindcss/oxide-darwin-x64@4.3.5': + optional: true + + '@tailwindcss/oxide-freebsd-x64@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-arm64-musl@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-x64-gnu@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-x64-musl@4.3.5': + optional: true + + '@tailwindcss/oxide-wasm32-wasi@4.3.5': + optional: true + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.5': + optional: true + + '@tailwindcss/oxide-win32-x64-msvc@4.3.5': + optional: true + + '@tailwindcss/oxide@4.3.5': + optionalDependencies: + '@tailwindcss/oxide-android-arm64': 4.3.5 + '@tailwindcss/oxide-darwin-arm64': 4.3.5 + '@tailwindcss/oxide-darwin-x64': 4.3.5 + '@tailwindcss/oxide-freebsd-x64': 4.3.5 + '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.5 + '@tailwindcss/oxide-linux-arm64-gnu': 4.3.5 + '@tailwindcss/oxide-linux-arm64-musl': 4.3.5 + '@tailwindcss/oxide-linux-x64-gnu': 4.3.5 + '@tailwindcss/oxide-linux-x64-musl': 4.3.5 + '@tailwindcss/oxide-wasm32-wasi': 4.3.5 + '@tailwindcss/oxide-win32-arm64-msvc': 4.3.5 + '@tailwindcss/oxide-win32-x64-msvc': 4.3.5 + + '@tailwindcss/postcss@4.3.5': + dependencies: + '@alloc/quick-lru': 5.3.0 + '@tailwindcss/node': 4.3.5 + '@tailwindcss/oxide': 4.3.5 + postcss: 8.5.32 + tailwindcss: 4.3.5 + '@types/node@26.6.6': dependencies: undici-types: 8.9.0 @@ -2140,8 +2519,14 @@ snapshots: caniuse-lite@1.0.30001826: {} + class-variance-authority@0.7.1: + dependencies: + clsx: 2.1.1 + client-only@0.0.1: {} + clsx@2.1.1: {} + content-disposition@2.0.1: {} content-type@1.0.5: {} @@ -2171,8 +2556,7 @@ snapshots: depd@2.0.0: {} - detect-libc@2.1.2: - optional: true + detect-libc@2.1.2: {} drizzle-kit@0.31.11: dependencies: @@ -2195,6 +2579,11 @@ snapshots: encodeurl@2.0.1: {} + enhanced-resolve@5.26.1: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.3 + es-define-property@1.0.1: {} es-errors@1.3.0: {} @@ -2361,6 +2750,10 @@ snapshots: function-bind@1.1.2: {} + geist@1.9.2(next@16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)): + dependencies: + next: 16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + get-intrinsic@1.3.0: dependencies: call-bind-apply-helpers: 1.0.2 @@ -2385,6 +2778,8 @@ snapshots: gopd@1.2.0: {} + graceful-fs@4.2.11: {} + has-symbols@1.1.0: {} hasown@2.0.4: @@ -2415,12 +2810,73 @@ snapshots: isexe@2.0.0: {} + jiti@2.7.0: {} + jose@6.2.17: {} json-schema-traverse@1.0.0: {} json-schema-typed@8.0.2: {} + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1): + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + math-intrinsics@1.1.0: {} media-typer@1.1.1: {} @@ -2494,6 +2950,12 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + postgres@4.1.1: {} proxy-addr@2.0.8: @@ -2654,6 +3116,12 @@ snapshots: client-only: 0.0.1 react: 19.3.1 + tailwind-merge@3.7.0: {} + + tailwindcss@4.3.5: {} + + tapable@2.3.3: {} + toidentifier@1.0.1: {} tslib@2.9.1: {} -- 2.45.2 From c03b679a1d1acd87db2d37eb2f23eb24ff620311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:21:24 +0500 Subject: [PATCH 014/536] PEP-38: all pages on the console components, globals.css removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/app/(app)/help/page.tsx | 75 ++-- apps/web/app/(app)/p/[key]/page.tsx | 373 ++++++++++-------- apps/web/app/(app)/page.tsx | 33 +- apps/web/app/(app)/projects/new/page.tsx | 124 +++--- apps/web/app/(app)/projects/page.tsx | 26 +- apps/web/app/(app)/runners/page.tsx | 24 +- apps/web/app/(app)/settings/page.tsx | 234 ++++++----- apps/web/app/(app)/t/[key]/page.tsx | 169 ++++---- apps/web/app/app.css | 1 - apps/web/app/legacy.css | 132 ------- apps/web/app/login/page.tsx | 20 +- apps/web/app/oauth/authorize/page.tsx | 59 +-- apps/web/components/ActivityAside.tsx | 2 +- apps/web/components/Board.tsx | 109 ++--- apps/web/components/Brand.tsx | 11 + apps/web/components/Footer.tsx | 2 +- apps/web/components/Incidents.tsx | 165 ++++---- apps/web/components/Sidebar.tsx | 4 +- apps/web/components/cards.tsx | 161 ++++++++ apps/web/components/common.tsx | 101 +++++ apps/web/components/ui.tsx | 160 -------- apps/web/scripts/mock-ui-seed.ts | 25 +- .../changes/pep-38-factory-console/tasks.md | 12 +- 23 files changed, 1104 insertions(+), 918 deletions(-) delete mode 100644 apps/web/app/legacy.css create mode 100644 apps/web/components/Brand.tsx create mode 100644 apps/web/components/cards.tsx create mode 100644 apps/web/components/common.tsx delete mode 100644 apps/web/components/ui.tsx diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 24fde4df..6c792523 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -1,6 +1,7 @@ import Link from "next/link"; import { publicOrigin } from "@/lib/auth"; import { Workspace } from "@/components/Workspace"; +import { PageHeader, Section } from "@/components/common"; const TOOLS: Array<[string, string]> = [ ["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько задач в каждой колонке"], @@ -39,13 +40,13 @@ export default async function Help() { const mcp = `${await publicOrigin()}/mcp`; return ( <Workspace> - <section className="narrow help"> - <h1>Помощь</h1> + <div className="max-w-3xl text-sm leading-relaxed [&_a]:text-primary [&_code]:font-mono [&_code]:text-[0.92em] [&_li]:my-1 [&_ul]:m-0 [&_ul]:list-disc [&_ul]:pl-5"> + <PageHeader title="Помощь">Понятия Пеппы, подключение MCP-клиентов и что можно попросить.</PageHeader> - <h2>Как устроена Пеппа</h2> + <Section title="Как устроена Пеппа"> <ul> <li><b>Проект</b> — репозиторий в Gitea с ключом задач (например, PEP). Создаётся из веба или через MCP.</li> - <li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="mono"><ваш логин>/<slug></span>) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), <span className="mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.</li> + <li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="font-mono"><ваш логин>/<slug></span>) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), <span className="font-mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.</li> <li><b>Цель</b> — верхнеуровневый результат («Мультипользовательская платформа»). Группирует задачи и даёт агенту контекст «зачем».</li> <li><b>Задача</b> (PEP-12) — один результат с описанием и условиями готовности.</li> <li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.</li> @@ -54,65 +55,73 @@ export default async function Help() { <li><b>Раннер</b> — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, задача, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры «ждут тебя / работают / остановлены (упали) / завершены».</li> <li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li> </ul> + </Section> - <h2>Подключить MCP</h2> - <p>Адрес сервера:</p> - <code className="mcp-url">{mcp}</code> + <Section title="Подключить MCP"> + <p className="m-0">Адрес сервера:</p> + <code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code> <ul> <li><b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через Gitea и нажмите «Разрешить». В чате включите коннектор Peppa.</li> <li><b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.</li> <li>Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <Link href="/settings">Настройках</Link>.</li> <li>Чтобы агенты работали на вашей подписке, подключите Claude в <Link href="/settings">Настройках</Link>.</li> </ul> + </Section> - <h2>Сценарии</h2> + <Section title="Сценарии"> {CASES.map((c) => ( - <article key={c.title} className="card"> + <article key={c.title} className="flex flex-col gap-1 rounded-lg border bg-card px-4 py-3"> <b>{c.title}</b> - <p className="say">«{c.say}»</p> - <p className="muted">{c.how}</p> + <p className="m-0 italic">«{c.say}»</p> + <p className="m-0 text-muted-foreground">{c.how}</p> </article> ))} + </Section> - <h2>Инструменты MCP</h2> - <table className="tools"> + <Section title="Инструменты MCP"> + <div className="overflow-x-auto rounded-lg border"> + <table className="w-full border-collapse"> <tbody> {TOOLS.map(([name, what]) => ( - <tr key={name}> - <td className="mono">{name}</td> - <td>{what}</td> + <tr key={name} className="border-b align-top last:border-0"> + <td className="px-3 py-2 font-mono text-xs [overflow-wrap:anywhere] sm:whitespace-nowrap">{name}</td> + <td className="px-3 py-2">{what}</td> </tr> ))} </tbody> </table> + </div> + </Section> - <h2>CI/CD</h2> - <p className="muted"> - Каждый PR агента проверяет Gitea Actions: <span className="mono">install</span>, <span className="mono">lint</span>,{" "} - <span className="mono">typecheck</span>, <span className="mono">test</span>, <span className="mono">build</span>. Команды — - в <span className="mono">.peppa/project.json → checks</span> (заполняет агент на первой задаче), workflow приходит из - шаблона; в старый проект — командой <span className="mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в + <Section title="CI/CD"> + <p className="m-0 text-muted-foreground"> + Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "} + <span className="font-mono">typecheck</span>, <span className="font-mono">test</span>, <span className="font-mono">build</span>. Команды — + в <span className="font-mono">.peppa/project.json → checks</span> (заполняет агент на первой задаче), workflow приходит из + шаблона; в старый проект — командой <span className="font-mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без - конфликтов. PR, меняющий конвейер (<span className="mono">.gitea/</span>, <span className="mono">checks</span>,{" "} - <span className="mono">deploy</span>), сам не мержится никогда. + конфликтов. PR, меняющий конвейер (<span className="font-mono">.gitea/</span>, <span className="font-mono">checks</span>,{" "} + <span className="font-mono">deploy</span>), сам не мержится никогда. </p> - <p className="muted"> - Деплой — <span className="mono">deploy</span> в project.json и <span className="mono">Dockerfile</span> (заготовки в{" "} - <span className="mono">deploy/</span>): PR получает preview <span className="mono">slug-prN.telecom.quest</span> (удаляется при - закрытии), мерж выкатывает staging <span className="mono">slug-staging.telecom.quest</span>, прод{" "} - <span className="mono">slug-prod.telecom.quest</span> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "} - <span className="mono">deploy</span>). После каждого деплоя — проверка <span className="mono">/healthz</span> до 2 минут; не + <p className="m-0 text-muted-foreground"> + Деплой — <span className="font-mono">deploy</span> в project.json и <span className="font-mono">Dockerfile</span> (заготовки в{" "} + <span className="font-mono">deploy/</span>): PR получает preview <span className="font-mono">slug-prN.telecom.quest</span> (удаляется при + закрытии), мерж выкатывает staging <span className="font-mono">slug-staging.telecom.quest</span>, прод{" "} + <span className="font-mono">slug-prod.telecom.quest</span> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "} + <span className="font-mono">deploy</span>). После каждого деплоя — проверка <span className="font-mono">/healthz</span> до 2 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта. </p> + </Section> - <h2>Telegram</h2> - <p className="muted"> + <Section title="Telegram"> + <p className="m-0 text-muted-foreground"> Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике проекта: сообщением, задачей или с кнопками «В бэклог / В работу / Игнорировать». </p> - </section> + </Section> + </div> </Workspace> ); } diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index f77a7464..1ff408b1 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,25 +1,50 @@ import { notFound } from "next/navigation"; -import { AutoRefresh } from "@/components/AutoRefresh"; -import { Flash, Notice, SessionCard } from "@/components/ui"; -import { Board, type Card } from "@/components/Board"; -import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner"; -import { requireUser } from "@/lib/auth"; -import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; +import { ExternalLink, Plus, Rocket, Target } from "lucide-react"; +import { columnOf, currentReleases, describeRepo, listReleases, bugsinkWebhookBase, type Release } from "@peppa/runner"; import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core"; -import { bugsinkWebhookBase } from "@peppa/runner"; +import { AutoRefresh } from "@/components/AutoRefresh"; +import { PanelSection } from "@/components/ActivityAside"; +import { Board, type Card } from "@/components/Board"; +import { Hidden, SessionCard } from "@/components/cards"; +import { Disclosure, Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common"; import { IncidentsSection } from "@/components/Incidents"; -import { db } from "@/lib/db"; -import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input, Textarea } from "@/components/ui/input"; import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; +import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; -const RELEASE_STATUS: Record<Release["status"], string> = { - deploying: "⏳ выкатывается", - healthy: "✅ работает", - rolled_back: "↩️ откат", - failed: "❌ не поднялся", - removed: "🗑 удалён", +const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = { + deploying: { label: "выкатывается", tone: "info" }, + healthy: { label: "работает", tone: "ok" }, + rolled_back: { label: "откат", tone: "warn" }, + failed: { label: "не поднялся", tone: "danger" }, + removed: { label: "удалён", tone: "muted" }, }; +function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) { + return ( + <div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2"> + <span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">{name}</span> + {r ? ( + <span className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm"> + <span className="font-mono">{r.sha.slice(0, 7)}</span> + {r.host && ( + <a href={`https://${r.host}`} className="truncate text-primary"> + {r.host} + </a> + )} + </span> + ) : ( + <span className="text-sm text-muted-foreground">нет</span> + )} + </div> + ); +} + export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) { const user = await requireUser(); const { key } = await params; @@ -53,83 +78,197 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr column: columnOf(t.status), goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null, })); + + const aside = ( + <div className="flex flex-col gap-6"> + <PanelSection title="Репозиторий"> + <dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm"> + <dt className="text-muted-foreground">Где</dt> + <dd className="m-0 truncate"> + <a href={repo.url} className="text-primary">{repo.fullName}</a> + </dd> + <dt className="text-muted-foreground">Пространство</dt> + <dd className="m-0"> + {p.giteaOwner} + {repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`} + </dd> + <dt className="text-muted-foreground">Видимость</dt> + <dd className="m-0">{repoVisibilityLabel(repo.private)}</dd> + <dt className="text-muted-foreground">Кто видит</dt> + <dd className="m-0">{repoAudience(repo)}</dd> + <dt className="text-muted-foreground">Рабочая копия</dt> + <dd className="m-0 font-mono text-xs break-all">{p.workspacePath}</dd> + </dl> + <Button asChild size="sm" className="self-start"> + <a href={repo.url}> + Открыть в Gitea <ExternalLink /> + </a> + </Button> + </PanelSection> + + <PanelSection title="Участники" count={team.members.length + 1}> + <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm"> + <li className="flex flex-col rounded-md px-2 py-1.5"> + <span className="font-medium">{team.owner?.login ?? "—"}</span> + <span className="text-xs text-muted-foreground">владелец · агенты работают на его подписке Claude</span> + </li> + {team.members.map((m) => ( + <li key={m.id} className="flex items-center gap-2 rounded-md px-2 py-1.5"> + <span className="flex min-w-0 flex-1 flex-col"> + <span>{m.login}</span> + <span className="text-xs text-muted-foreground">участник{noRepoAccess(m.login) && " · нет доступа к репозиторию"}</span> + </span> + {(isOwner || m.id === user.id) && ( + <form action={removeProjectMember}> + <Hidden fields={{ projectId: p.id, login: m.login, back }} /> + <Button size="xs" variant="destructive">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</Button> + </form> + )} + </li> + ))} + {team.invites.map((login) => ( + <li key={login} className="flex items-center gap-2 rounded-md px-2 py-1.5"> + <span className="flex min-w-0 flex-1 flex-col"> + <span>{login}</span> + <span className="text-xs text-muted-foreground">приглашён · появится после первого входа в Пеппу</span> + </span> + {isOwner && ( + <form action={removeProjectMember}> + <Hidden fields={{ projectId: p.id, login, back }} /> + <Button size="xs" variant="destructive">Отозвать</Button> + </form> + )} + </li> + ))} + </ul> + {isOwner && ( + <form action={addProjectMember} className="flex gap-2"> + <Hidden fields={{ projectId: p.id, back }} /> + <Input name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" className="h-8" /> + <Button size="sm">Добавить участника</Button> + </form> + )} + {isOwner && missingAccess && ( + <form action={grantRepoAccessToMembers}> + <Hidden fields={{ projectId: p.id, back }} /> + <Button size="sm">Выдать доступ участникам</Button> + </form> + )} + {isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>} + </PanelSection> + </div> + ); + return ( - <Workspace> + <Workspace aside={aside}> <AutoRefresh /> <Flash error={error} /> {created && !error && ( <Notice> - Репозиторий создан: <a href={repo.url}>{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).{" "} - <a href={repo.url} className="button small">Открыть в Gitea</a> + Репозиторий создан: <a href={repo.url} className="text-primary">{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}). + <Button asChild size="xs"> + <a href={repo.url}>Открыть в Gitea</a> + </Button> </Notice> )} - <h1> - <span className="mono">{p.key}</span> {p.name} - </h1> - <p className="muted"> - <a href={repo.url}>{repo.fullName}</a> · {repoVisibilityLabel(repo.private)} - </p> + <PageHeader + crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">Проекты</a>} + title={ + <> + <span className="rounded-md bg-muted px-2 font-mono text-primary">{p.key}</span> {p.name} + </> + } + > + <a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)} + </PageHeader> <Board cards={cards} back={back} /> - {groups.map(({ goal }) => ( - <details key={goal?.id ?? "none"} className="add"> - <summary>+ Задача{goal ? ` · 🎯 ${goal.title}` : " без цели"}</summary> - <form action={addTask} className="stack"> - <input type="hidden" name="projectId" value={p.id} /> - <input type="hidden" name="back" value={back} /> - {goal && <input type="hidden" name="goalId" value={goal.id} />} - <input type="text" name="title" required placeholder="Что сделать" aria-label="Название задачи" /> - <textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" /> - <button className="primary">Создать задачу</button> + <div className="mt-3 grid gap-2 md:grid-cols-2"> + {groups.map(({ goal }) => ( + <Disclosure + key={goal?.id ?? "none"} + summary={ + <span className="flex min-w-0 items-center gap-1.5"> + <Plus className="size-3.5 text-primary" /> + Задача + <span className="truncate text-muted-foreground">{goal ? `· ◎ ${goal.title}` : "без цели"}</span> + </span> + } + > + <form action={addTask} className="flex flex-col gap-2"> + <Hidden fields={{ projectId: p.id, back, goalId: goal?.id }} /> + <Input name="title" required placeholder="Что сделать" aria-label="Название задачи" /> + <Textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" /> + <Button variant="default" size="sm" className="self-start">Создать задачу</Button> + </form> + </Disclosure> + ))} + <Disclosure + summary={ + <span className="flex items-center gap-1.5"> + <Target className="size-3.5 text-primary" /> + Цель + </span> + } + > + <form action={addGoal} className="flex flex-col gap-2"> + <Hidden fields={{ projectId: p.id, back }} /> + <Input name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" /> + <Textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" /> + <Button variant="default" size="sm" className="self-start">Создать цель</Button> </form> - </details> - ))} + </Disclosure> + </div> - <section> - <details> - <summary>+ Цель</summary> - <form action={addGoal} className="stack"> - <input type="hidden" name="projectId" value={p.id} /> - <input type="hidden" name="back" value={back} /> - <input type="text" name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" /> - <textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" /> - <button className="primary">Создать цель</button> - </form> - </details> - </section> - - <section> - <h2>Релизы</h2> - <p> - Staging: {current.staging ? <><span className="mono">{current.staging.sha.slice(0, 7)}</span>{current.staging.host && <> · <a href={`https://${current.staging.host}`}>{current.staging.host}</a></>}</> : <span className="muted">нет</span>} - {" · "}Прод: {current.prod ? <><span className="mono">{current.prod.sha.slice(0, 7)}</span>{current.prod.host && <> · <a href={`https://${current.prod.host}`}>{current.prod.host}</a></>}</> : <span className="muted">нет</span>} - </p> + <Section title="Релизы"> + <div className="flex flex-col gap-2 sm:flex-row"> + <EnvLine name="staging" r={current.staging} /> + <EnvLine name="прод" r={current.prod} /> + </div> {current.staging && current.staging.sha !== current.prod?.sha && ( - <form action={deployProdAction} className="row"> - <input type="hidden" name="projectKey" value={p.key} /> - <input type="hidden" name="back" value={back} /> - <button className="primary">🚀 Выкатить в прод {current.staging.sha.slice(0, 7)}</button> + <form action={deployProdAction}> + <Hidden fields={{ projectKey: p.key, back }} /> + <Button variant="default" size="sm"> + <Rocket /> + Выкатить в прод {current.staging.sha.slice(0, 7)} + </Button> </form> )} {releases.length === 0 ? ( - <p className="empty">Деплоев ещё не было. Настройка — <span className="mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).</p> + <Empty> + Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»). + </Empty> ) : ( - <table className="releases"> - <tbody> - {releases.map((r) => ( - <tr key={r.id}> - <td>{r.env}{r.prNumber ? ` #${r.prNumber}` : ""}</td> - <td className="mono">{r.sha.slice(0, 7)}</td> - <td>{RELEASE_STATUS[r.status]}{r.reason ? <span className="muted"> — {r.reason}</span> : null}</td> - <td>{r.tasks.join(", ")}</td> - <td className="muted">{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}</td> - </tr> - ))} - </tbody> - </table> + <div className="overflow-x-auto rounded-lg border"> + <table className="w-full border-collapse text-sm"> + <tbody> + {releases.map((r) => ( + <tr key={r.id} className="border-b last:border-0"> + <td className="px-3 py-2 whitespace-nowrap"> + {r.env} + {r.prNumber ? ` #${r.prNumber}` : ""} + </td> + <td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td> + <td className="px-3 py-2"> + <Badge variant={RELEASE_STATUS[r.status].tone}>{RELEASE_STATUS[r.status].label}</Badge> + {r.reason && <span className="ml-1.5 text-muted-foreground">{r.reason}</span>} + </td> + <td className="px-3 py-2"> + {r.tasks.map((t) => ( + <Key key={t} href={`/t/${t}`} className="mr-1.5">{t}</Key> + ))} + </td> + <td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground"> + {r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })} + </td> + </tr> + ))} + </tbody> + </table> + </div> )} - </section> + </Section> <IncidentsSection projectId={p.id} @@ -143,89 +282,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null} /> - <section> - <h2>Участники</h2> - <ul className="members"> - <li> - <span><b>{team.owner?.login ?? "—"}</b> <span className="muted">владелец · агенты работают на его подписке Claude</span></span> - </li> - {team.members.map((m) => ( - <li key={m.id}> - <span> - {m.login} <span className="muted">участник</span> - {noRepoAccess(m.login) && <span className="muted"> · нет доступа к репозиторию</span>} - </span> - {(isOwner || m.id === user.id) && ( - <form action={removeProjectMember}> - <input type="hidden" name="projectId" value={p.id} /> - <input type="hidden" name="login" value={m.login} /> - <input type="hidden" name="back" value={back} /> - <button className="small danger">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</button> - </form> - )} - </li> - ))} - {team.invites.map((login) => ( - <li key={login}> - <span>{login} <span className="muted">приглашён · появится после первого входа в Пеппу</span></span> - {isOwner && ( - <form action={removeProjectMember}> - <input type="hidden" name="projectId" value={p.id} /> - <input type="hidden" name="login" value={login} /> - <input type="hidden" name="back" value={back} /> - <button className="small danger">Отозвать</button> - </form> - )} - </li> - ))} - </ul> - {isOwner && ( - <form action={addProjectMember} className="row"> - <input type="hidden" name="projectId" value={p.id} /> - <input type="hidden" name="back" value={back} /> - <input type="text" name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" /> - <button>Добавить участника</button> - </form> - )} - {isOwner && missingAccess && ( - <form action={grantRepoAccessToMembers}> - <input type="hidden" name="projectId" value={p.id} /> - <input type="hidden" name="back" value={back} /> - <button>Выдать доступ участникам</button> - </form> - )} - {isOwner && ( - <p className="muted"> - Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию. - </p> - )} - </section> - - <section> - <h2>Репозиторий</h2> - <dl className="repo"> - <dt>Где</dt> - <dd> - <a href={repo.url}>{repo.fullName}</a> · <a href={repo.url}>Открыть в Gitea</a> - </dd> - <dt>Пространство</dt> - <dd> - {p.giteaOwner} - {repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`} - </dd> - <dt>Видимость</dt> - <dd>{repoVisibilityLabel(repo.private)}</dd> - <dt>Кто видит</dt> - <dd>{repoAudience(repo)}</dd> - <dt>Рабочая копия</dt> - <dd className="mono">{p.workspacePath}</dd> - </dl> - </section> - - <section> - <h2>Сессии</h2> - {sessions.length === 0 ? <p className="empty">Сессий ещё не было.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)} - </section> + <Section title="Сессии"> + {sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} + </Section> </Workspace> ); } diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 46337a96..4a9d6330 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -1,12 +1,12 @@ -import Link from "next/link"; import { listUserProjects } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; -import { Flash, ProjectList, QuestionCard, SessionCard } from "@/components/ui"; +import { ActivityAside } from "@/components/ActivityAside"; +import { ProjectList, QuestionCard, SessionCard } from "@/components/cards"; +import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common"; +import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { activeSessions, inbox } from "@/lib/queries"; -import { Workspace } from "@/components/Workspace"; -import { ActivityAside } from "@/components/ActivityAside"; export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -16,23 +16,16 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e <Workspace aside={<ActivityAside questions={false} />}> <AutoRefresh /> <Flash error={error} /> - <h1>Главная</h1> - <section> - <h2>Вопросы агентов {items.length > 0 && <span className="count">{items.length}</span>}</h2> - {items.length === 0 ? <p className="empty">Агентам от тебя ничего не нужно.</p> : items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)} - </section> - <section> - <h2> - Активные раннеры <Link href="/runners" className="more">все раннеры →</Link> - </h2> - {sessions.length === 0 ? <p className="empty">Сейчас ничего не запущено.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back="/" />)} - </section> - <section> - <h2> - Мои проекты <Link href="/projects" className="more">все проекты →</Link> - </h2> + <PageHeader title="Главная">{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}</PageHeader> + <Section title="Вопросы агентов" count={items.length}> + {items.length === 0 ? <Empty>Агентам от тебя ничего не нужно.</Empty> : items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)} + </Section> + <Section title="Активные раннеры" actions={<MoreLink href="/runners">все раннеры</MoreLink>}> + {sessions.length === 0 ? <Empty>Сейчас ничего не запущено.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back="/" showTitle />)} + </Section> + <Section title="Мои проекты" actions={<MoreLink href="/projects">все проекты</MoreLink>}> <ProjectList projects={projects} userId={user.id} /> - </section> + </Section> </Workspace> ); } diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx index 520a6fa6..d216fda7 100644 --- a/apps/web/app/(app)/projects/new/page.tsx +++ b/apps/web/app/(app)/projects/new/page.tsx @@ -1,10 +1,22 @@ import { giteaForUser, type GiteaOrg } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; -import { Flash } from "@/components/ui"; +import { Flash, PageHeader } from "@/components/common"; +import { Hidden } from "@/components/cards"; +import { Button } from "@/components/ui/button"; +import { Input, Label, NativeSelect } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { createProjectAction } from "../../actions"; -import { Workspace } from "@/components/Workspace"; + +function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) { + return ( + <label className="flex cursor-pointer items-start gap-2.5 rounded-md border bg-background/40 px-3 py-2 text-sm has-checked:border-primary/60 has-checked:bg-primary/5"> + <input type="radio" name={name} value={value} defaultChecked={checked} className="mt-1 accent-primary" /> + <span>{children}</span> + </label> + ); +} export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -19,64 +31,56 @@ export default async function NewProject({ searchParams }: { searchParams: Promi } return ( <Workspace> - <section className="narrow"> - <h1>Новый проект</h1> - <Flash error={error ?? giteaError} /> - <form action={createProjectAction} className="stack"> - <input type="hidden" name="back" value="/projects/new" /> - <label> - Название - <input type="text" name="name" required placeholder="Платёжный сервис" /> - </label> - <div className="row"> - <label className="grow"> - Репозиторий (slug) - <input type="text" name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" /> - </label> - <label> - Ключ задач - <input type="text" name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="short" /> - </label> - </div> - <label> - Пространство в Gitea - <select name="owner" defaultValue={user.login}> - <option value={user.login}>{user.login} — личное</option> - {orgs.map((o) => ( - <option key={o.id} value={o.username}>{o.username} — организация</option> - ))} - </select> - </label> - <p className="muted"> - Репозиторий будет <span className="mono">{giteaUrl}/<пространство>/<slug></span>. В личном пространстве приватный репозиторий видите - только вы, <span className="mono">peppa-bot</span> и участники проекта; в организации — ещё её участники с доступом к репозиториям. - {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."} - </p> - <fieldset> - <legend>Видимость</legend> - <label className="inline"> - <input type="radio" name="visibility" value="private" defaultChecked /> Приватный — только те, кому выдан доступ - </label> - <label className="inline"> - <input type="radio" name="visibility" value="public" /> Публичный — все, у кого есть доступ к Gitea - </label> - </fieldset> - <fieldset> - <legend>Репозиторий</legend> - <label className="inline"> - <input type="radio" name="mode" value="new" defaultChecked /> Создать новый - </label> - <label className="inline"> - <input type="radio" name="mode" value="existing" /> Подключить существующий (нужны права админа; видимость не меняется) - </label> - </fieldset> - <p className="muted"> - Пеппа добавит <span className="mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит - openspec init. Занимает до ~15 секунд. - </p> - <button className="primary">Создать проект</button> - </form> - </section> + <div className="max-w-xl"> + <PageHeader title="Новый проект" /> + <Flash error={error ?? giteaError} /> + <form action={createProjectAction} className="flex flex-col gap-4"> + <Hidden fields={{ back: "/projects/new" }} /> + <Label> + Название + <Input name="name" required placeholder="Платёжный сервис" /> + </Label> + <div className="flex gap-3"> + <Label className="flex-1"> + Репозиторий (slug) + <Input name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" className="font-mono" /> + </Label> + <Label className="w-32"> + Ключ задач + <Input name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="font-mono uppercase" /> + </Label> + </div> + <Label> + Пространство в Gitea + <NativeSelect name="owner" defaultValue={user.login}> + <option value={user.login}>{user.login} — личное</option> + {orgs.map((o) => ( + <option key={o.id} value={o.username}>{o.username} — организация</option> + ))} + </NativeSelect> + </Label> + <p className="m-0 text-sm text-muted-foreground"> + Репозиторий будет <span className="font-mono">{giteaUrl}/<пространство>/<slug></span>. В личном пространстве приватный репозиторий видите + только вы, <span className="font-mono">peppa-bot</span> и участники проекта; в организации — ещё её участники с доступом к репозиториям. + {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."} + </p> + <fieldset className="m-0 flex flex-col gap-2 border-0 p-0"> + <legend className="mb-2 text-sm font-medium">Видимость</legend> + <Choice name="visibility" value="private" checked>Приватный — только те, кому выдан доступ</Choice> + <Choice name="visibility" value="public">Публичный — все, у кого есть доступ к Gitea</Choice> + </fieldset> + <fieldset className="m-0 flex flex-col gap-2 border-0 p-0"> + <legend className="mb-2 text-sm font-medium">Репозиторий</legend> + <Choice name="mode" value="new" checked>Создать новый</Choice> + <Choice name="mode" value="existing">Подключить существующий (нужны права админа; видимость не меняется)</Choice> + </fieldset> + <p className="m-0 text-sm text-muted-foreground"> + Пеппа добавит <span className="font-mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит + openspec init. Занимает до ~15 секунд. + </p> + <Button variant="default" className="self-start">Создать проект</Button> + </form> + </div> </Workspace> ); } diff --git a/apps/web/app/(app)/projects/page.tsx b/apps/web/app/(app)/projects/page.tsx index 4fc5d361..d5cddd57 100644 --- a/apps/web/app/(app)/projects/page.tsx +++ b/apps/web/app/(app)/projects/page.tsx @@ -1,9 +1,12 @@ import Link from "next/link"; +import { Plus } from "lucide-react"; import { listUserProjects } from "@peppa/core"; -import { Flash, ProjectList } from "@/components/ui"; +import { ProjectList } from "@/components/cards"; +import { Flash, PageHeader } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { Workspace } from "@/components/Workspace"; export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -12,12 +15,19 @@ export default async function Projects({ searchParams }: { searchParams: Promise return ( <Workspace> <Flash error={error} /> - <h1> - Проекты{" "} - <Link href="/projects/new" className="button primary small"> - Новый проект - </Link> - </h1> + <PageHeader + title="Проекты" + actions={ + <Button asChild variant="default" size="sm"> + <Link href="/projects/new"> + <Plus /> + Новый проект + </Link> + </Button> + } + > + Свои и общие проекты: доска задач, релизы, ошибки из прода, участники. + </PageHeader> <ProjectList projects={projects} userId={user.id} /> </Workspace> ); diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx index 7f90ce4b..9644c1b3 100644 --- a/apps/web/app/(app)/runners/page.tsx +++ b/apps/web/app/(app)/runners/page.tsx @@ -1,10 +1,12 @@ import Link from "next/link"; import { listUserSessions, RUNNER_FILTERS, type RunnerFilter } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; -import { Flash, SessionCard } from "@/components/ui"; +import { SessionCard } from "@/components/cards"; +import { Empty, Flash, PageHeader } from "@/components/common"; +import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { Workspace } from "@/components/Workspace"; +import { cn } from "@/lib/utils"; const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [ { key: undefined, label: "Все" }, @@ -26,16 +28,22 @@ export default async function Runners({ searchParams }: { searchParams: Promise< <Workspace> <AutoRefresh /> <Flash error={error} /> - <h1>Раннеры</h1> - <p className="muted">Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.</p> - <nav className="filters" aria-label="Фильтр раннеров"> + <PageHeader title="Раннеры">Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.</PageHeader> + <nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Фильтр раннеров"> {FILTERS.map((x) => ( - <Link key={x.label} href={x.key ? `/runners?f=${x.key}` : "/runners"} className={x.key === filter ? "active" : undefined} aria-current={x.key === filter ? "page" : undefined}> - {x.label} <span className="muted">{count(x.key)}</span> + <Link + key={x.label} + href={x.key ? `/runners?f=${x.key}` : "/runners"} + aria-current={x.key === filter ? "page" : undefined} + className={cn("rounded-full border px-3 py-1 text-sm text-foreground hover:border-muted-foreground hover:no-underline", x.key === filter && "border-primary bg-primary/10")} + > + {x.label} <span className="font-mono text-xs text-muted-foreground">{count(x.key)}</span> </Link> ))} </nav> - {shown.length === 0 ? <p className="empty">{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</p> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} + <div className="flex flex-col gap-2.5"> + {shown.length === 0 ? <Empty>{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</Empty> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} + </div> </Workspace> ); } diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 13c3717c..7cf42ad8 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,10 +1,30 @@ +import { ExternalLink } from "lucide-react"; import { connectedApps } from "@peppa/core"; -import { ago, Flash } from "@/components/ui"; +import { pendingClaudeSetup } from "@peppa/runner"; +import { Hidden } from "@/components/cards"; +import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { pendingClaudeSetup } from "@peppa/runner"; import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions"; -import { Workspace } from "@/components/Workspace"; + +const back = { back: "/settings" }; + +/** A connected thing: title + details on the left, actions on the right. */ +function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) { + return ( + <Card className="flex-row flex-wrap items-center gap-3"> + <div className="min-w-0 flex-[1_1_16rem]"> + <div className="font-medium">{title}</div> + {children && <div className="text-sm text-muted-foreground">{children}</div>} + </div> + {actions && <div className="flex gap-2">{actions}</div>} + </Card> + ); +} export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) { const user = await requireUser(); @@ -14,106 +34,118 @@ export default async function Settings({ searchParams }: { searchParams: Promise const origin = await publicOrigin(); return ( <Workspace> - <section className="narrow"> - <Flash error={error} /> - <h1>Настройки</h1> - <h2>Claude</h2> - {claude === "connected" && <p className="ok">Claude подключён ✅</p>} - {setup ? ( - <div className="card stack"> - <p> - 1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка): - </p> - <a className="button primary" href={setup.url} target="_blank" rel="noreferrer">Войти в Claude ↗</a> - <p>2. Claude покажет код — вставьте его сюда:</p> - <form action={submitClaudeCode} className="row"> - <input type="hidden" name="back" value="/settings" /> - <input type="text" name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required /> - <button className="primary">Подключить</button> - </form> - <form action={cancelClaude}> - <input type="hidden" name="back" value="/settings" /> - <button className="link">Отменить</button> - </form> - </div> - ) : user.claudeTokenEnc ? ( - <article className="card row"> - <div className="grow"> - <b>Claude подключён</b> - <div className="muted"> + <div className="max-w-2xl"> + <Flash error={error} /> + <PageHeader title="Настройки" /> + <Section title="Claude"> + {claude === "connected" && <Notice>Claude подключён</Notice>} + {setup ? ( + <Card> + <p className="m-0 text-sm">1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):</p> + <Button asChild variant="default" className="self-start"> + <a href={setup.url} target="_blank" rel="noreferrer"> + Войти в Claude <ExternalLink /> + </a> + </Button> + <p className="m-0 text-sm">2. Claude покажет код — вставьте его сюда:</p> + <form action={submitClaudeCode} className="flex gap-2"> + <Hidden fields={back} /> + <Input name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required className="font-mono" /> + <Button variant="default">Подключить</Button> + </form> + <form action={cancelClaude}> + <Hidden fields={back} /> + <Button variant="link" className="text-muted-foreground">Отменить</Button> + </form> + </Card> + ) : user.claudeTokenEnc ? ( + <Row + title="Claude подключён" + actions={ + <> + <form action={connectClaude}> + <Hidden fields={back} /> + <Button size="sm">Переподключить</Button> + </form> + <form action={disconnectClaude}> + <Hidden fields={back} /> + <Button size="sm" variant="destructive">Отключить</Button> + </form> + </> + } + > с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке - </div> - </div> - <form action={connectClaude}> - <input type="hidden" name="back" value="/settings" /> - <button>Переподключить</button> - </form> - <form action={disconnectClaude}> - <input type="hidden" name="back" value="/settings" /> - <button className="danger">Отключить</button> - </form> - </article> - ) : ( - <div className="stack"> - <p className="muted"> - Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой - токен через <span className="mono">claude setup-token</span>, вход делаете вы сами по ссылке. + </Row> + ) : ( + <Row + title="Claude не подключён" + actions={ + <form action={connectClaude}> + <Hidden fields={back} /> + <Button variant="default" size="sm">Подключить Claude</Button> + </form> + } + > + Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой токен через{" "} + <span className="font-mono">claude setup-token</span>, вход делаете вы сами по ссылке. + </Row> + )} + </Section> + <Section title="Telegram"> + {user.telegramChatId ? ( + <Row + title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`} + actions={ + <form action={unpairTelegramAction}> + <Hidden fields={back} /> + <Button size="sm" variant="destructive">Отвязать</Button> + </form> + } + > + Вопросы агентов из ваших и общих проектов приходят в этот чат. + </Row> + ) : ( + <Row + title="Telegram не привязан" + actions={ + <form action={pairTelegram}> + <Hidden fields={back} /> + <Button variant="default" size="sm">Привязать Telegram</Button> + </form> + } + > + Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start. + </Row> + )} + </Section> + <Section title="MCP для ChatGPT и других клиентов"> + <p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p> + <code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code> + <p className="m-0 text-sm text-muted-foreground"> + Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>. </p> - <form action={connectClaude}> - <input type="hidden" name="back" value="/settings" /> - <button className="primary">Подключить Claude</button> - </form> - </div> - )} - <h2>Telegram</h2> - {user.telegramChatId ? ( - <article className="card row"> - <div className="grow"> - <b>Telegram привязан{user.telegramUsername ? ` (@${user.telegramUsername})` : ""}</b> - <div className="muted">Вопросы агентов из ваших и общих проектов приходят в этот чат.</div> - </div> - <form action={unpairTelegramAction}> - <input type="hidden" name="back" value="/settings" /> - <button className="danger">Отвязать</button> - </form> - </article> - ) : ( - <div className="stack"> - <p className="muted"> - Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start. - </p> - <form action={pairTelegram}> - <input type="hidden" name="back" value="/settings" /> - <button className="primary">Привязать Telegram</button> - </form> - </div> - )} - <h2>MCP для ChatGPT и других клиентов</h2> - <p> - Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент - зарегистрируется сам, вы подтвердите доступ на экране Пеппы. - </p> - <code className="mcp-url">{origin}/mcp</code> - <p className="muted">Как подключить и что спрашивать — в <a href="/help">Помощи</a>.</p> - <h2>Подключённые приложения</h2> - {apps.length === 0 ? ( - <p className="empty">Нет подключённых приложений.</p> - ) : ( - apps.map((a) => ( - <article key={a.clientId} className="card row"> - <div className="grow"> - <b>{a.name}</b> - <div className="muted">с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}</div> - </div> - <form action={revokeConnectedApp}> - <input type="hidden" name="clientId" value={a.clientId} /> - <input type="hidden" name="back" value="/settings" /> - <button className="danger">Отозвать</button> - </form> - </article> - )) - )} - </section> + </Section> + <Section title="Подключённые приложения"> + {apps.length === 0 ? ( + <Empty>Нет подключённых приложений.</Empty> + ) : ( + apps.map((a) => ( + <Row + key={a.clientId} + title={a.name} + actions={ + <form action={revokeConnectedApp}> + <Hidden fields={{ clientId: a.clientId, ...back }} /> + <Button size="sm" variant="destructive">Отозвать</Button> + </form> + } + > + с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)} + </Row> + )) + )} + </Section> + </div> </Workspace> ); } diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index 93f4e933..c95764ca 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -1,15 +1,22 @@ import Link from "next/link"; import { notFound } from "next/navigation"; -import { AutoRefresh } from "@/components/AutoRefresh"; -import { ago, Badge, Flash, QuestionCard, SessionCard } from "@/components/ui"; -import { requireUser } from "@/lib/auth"; -import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries"; -import { db } from "@/lib/db"; +import { eq } from "drizzle-orm"; +import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react"; import { goals } from "@peppa/db"; import { taskCiSummary } from "@peppa/core"; -import { eq } from "drizzle-orm"; -import { startTaskSession } from "../../actions"; +import { AutoRefresh } from "@/components/AutoRefresh"; +import { PanelSection } from "@/components/ActivityAside"; +import { Hidden, QuestionCard, SessionCard } from "@/components/cards"; +import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Input, NativeSelect } from "@/components/ui/input"; import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries"; +import { startTaskSession } from "../../actions"; + +const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> }; export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -23,82 +30,108 @@ export default async function TaskPage({ params, searchParams }: { params: Promi const artifacts = openspecArtifacts(project, task.openspecChange); const ci = await taskCiSummary(db, ref); const back = `/t/${ref.key}`; + + const aside = ( + <div className="flex flex-col gap-6"> + <PanelSection title="Проверки"> + <div className="flex flex-wrap items-center gap-2 text-sm"> + {CI_ICON[ci.state as keyof typeof CI_ICON]} + {ci.runUrl ? <a href={ci.runUrl} className="text-primary">{ci.label}</a> : ci.label} + {ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>} + </div> + {task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">красных подряд: {task.ciAttempts}</p>} + {ci.failed.map((f) => ( + <Disclosure + key={f.check} + summary={ + <span className="flex items-center gap-1.5"> + <CircleX className="size-3.5 text-destructive" /> + <span className="font-mono">{f.check}</span> + {f.runUrl && <a href={f.runUrl} className="text-xs text-primary">лог</a>} + </span> + } + > + {f.logTail && <pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{f.logTail.split("\n").slice(-60).join("\n")}</pre>} + </Disclosure> + ))} + </PanelSection> + <PanelSection title="События"> + {events.length === 0 ? ( + <p className="m-0 text-sm text-muted-foreground">Событий нет.</p> + ) : ( + <ol className="m-0 flex list-none flex-col gap-1.5 border-l p-0 pl-3"> + {events.map((e) => ( + <li key={e.id} className="text-xs [overflow-wrap:anywhere]"> + <span className="font-mono text-muted-foreground">{ago(e.createdAt)}</span> <span className="font-mono text-primary">{e.type}</span>{" "} + {e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""} + </li> + ))} + </ol> + )} + </PanelSection> + </div> + ); + return ( - <Workspace> + <Workspace aside={aside}> <AutoRefresh /> <Flash error={error} /> - <p className="crumbs"> - <Link href={`/p/${project.key}`}>{project.name}</Link> - {goal && <> · 🎯 {goal.title}</>} - </p> - <h1> - <span className="mono">{ref.key}</span> {task.title} <Badge status={task.status} /> - </h1> - {task.prUrl && <p><a href={task.prUrl}>PR</a></p>} - <section className="checks"> - <h2>Проверки</h2> - <p> - {ci.state === "success" ? "✅ " : ci.state === "failure" ? "❌ " : ci.state === "pending" ? "⏳ " : ""} - {ci.runUrl ? <a href={ci.runUrl}>{ci.label}</a> : ci.label} - {ci.sha && <span className="mono muted"> · {ci.sha.slice(0, 7)}</span>} - {task.ciAttempts > 0 && <span className="muted"> · красных подряд: {task.ciAttempts}</span>} - </p> - {ci.failed.map((f) => ( - <details key={f.check}> - <summary> - ❌ <span className="mono">{f.check}</span> {f.runUrl && <a href={f.runUrl}>лог</a>} - </summary> - {f.logTail && <pre className="md">{f.logTail.split("\n").slice(-60).join("\n")}</pre>} - </details> - ))} - </section> - <p className="desc">{task.description || <span className="muted">Без описания</span>}</p> + <PageHeader + crumbs={ + <> + <Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link> + {goal && <span>· ◎ {goal.title}</span>} + </> + } + title={ + <> + <span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} /> + </> + } + actions={ + task.prUrl && ( + <Button asChild size="sm"> + <a href={task.prUrl}> + <GitPullRequest /> + PR + </a> + </Button> + ) + } + /> + <div className="rounded-lg border bg-card p-4 text-sm whitespace-pre-wrap">{task.description || <span className="text-muted-foreground">Без описания</span>}</div> - <section> - <h2>Сессии</h2> - <form action={startTaskSession} className="row wrap"> - <input type="hidden" name="taskKey" value={ref.key} /> - <input type="hidden" name="back" value={back} /> - <select name="provider" defaultValue="claude" aria-label="Агент"> + <Section title="Сессии"> + <form action={startTaskSession} className="flex flex-wrap gap-2"> + <Hidden fields={{ taskKey: ref.key, back }} /> + <NativeSelect name="provider" defaultValue="claude" aria-label="Агент" className="w-auto"> <option value="claude">Claude Code</option> <option value="codex">Codex</option> - </select> - <input type="text" name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="grow" /> - <button className="primary">Запустить агента</button> + </NativeSelect> + <Input name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="flex-[1_1_14rem]" /> + <Button variant="default"> + <Play /> + Запустить агента + </Button> </form> {sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)} - </section> + </Section> - <section> - <h2>Вопросы</h2> - {questions.length === 0 ? <p className="empty">Вопросов не было.</p> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)} - </section> + <Section title="Вопросы"> + {questions.length === 0 ? <Empty>Вопросов не было.</Empty> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)} + </Section> - <section> - <h2>OpenSpec {task.openspecChange && <span className="mono muted">{task.openspecChange}</span>}</h2> + <Section title={<>OpenSpec {task.openspecChange && <span className="ml-1 font-mono text-xs font-normal text-muted-foreground">{task.openspecChange}</span>}</>}> {artifacts?.length ? ( artifacts.map((a) => ( - <details key={a.name} open={a.name === "proposal.md"}> - <summary className="mono">{a.name}</summary> - <pre className="md">{a.text}</pre> - </details> + <Disclosure key={a.name} open={a.name === "proposal.md"} summary={<span className="font-mono">{a.name}</span>}> + <pre className="m-0 max-h-[32em] overflow-auto font-mono text-xs leading-relaxed whitespace-pre-wrap">{a.text}</pre> + </Disclosure> )) ) : ( - <p className="empty">Change ещё не создан.</p> + <Empty>Change ещё не создан.</Empty> )} - </section> - - <section> - <h2>События</h2> - <ul className="events"> - {events.map((e) => ( - <li key={e.id}> - <span className="muted">{ago(e.createdAt)}</span> <span className="mono">{e.type}</span>{" "} - {e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""} - </li> - ))} - </ul> - </section> + </Section> </Workspace> ); } diff --git a/apps/web/app/app.css b/apps/web/app/app.css index bc13d895..f150bd47 100644 --- a/apps/web/app/app.css +++ b/apps/web/app/app.css @@ -1,5 +1,4 @@ @import "tailwindcss"; -@import "./legacy.css" layer(base); /* Theme tokens (shadcn/ui naming): light in :root, dark — the default — in .dark (PEP-38). */ @custom-variant dark (&:where(.dark, .dark *)); diff --git a/apps/web/app/legacy.css b/apps/web/app/legacy.css deleted file mode 100644 index 3cfee729..00000000 --- a/apps/web/app/legacy.css +++ /dev/null @@ -1,132 +0,0 @@ -/* Pre-PEP-38 page styles, imported into the `base` layer so Tailwind utilities win. Removed page by page in stage 2. */ - -a { color: var(--primary); text-decoration: none; } -a:hover { text-decoration: underline; } -h1 { font-size: 1.5rem; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } -h2 { font-size: 1.1rem; margin: 28px 0 10px; } -.mono, code, pre { font-family: var(--font-mono); font-size: 0.9em; } -.muted { color: var(--muted-foreground); } -.empty { color: var(--muted-foreground); padding: 12px 0; } - -h2 .more { font-size: 0.85rem; font-weight: 400; margin-left: 8px; } -.filters { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0 4px; } -.filters a { padding: 4px 12px; border: 1px solid var(--border); border-radius: 999px; color: var(--foreground); background: var(--card); } -.filters a:hover { text-decoration: none; border-color: var(--muted-foreground); } -.filters a.active { border-color: var(--primary); box-shadow: inset 0 0 0 1px var(--primary); } -.session header.row { flex-wrap: wrap; row-gap: 2px; } -.session header .mono { white-space: nowrap; } -.session .title { flex: 1 1 12em; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.narrow { max-width: 560px; } -.crumbs { margin: 0 0 4px; color: var(--muted-foreground); } -.desc { white-space: pre-wrap; } - -.card { - background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); - padding: 14px 16px; margin: 10px 0; -} -.q { border-left: 4px solid var(--info); } -.q-approval { border-left-color: var(--primary); } -.q-permission { border-left-color: var(--warn); } -.q-attention { border-left-color: var(--ok); } -.q.answered { opacity: 0.7; border-left-color: var(--border); } -.kind { font-weight: 600; } -.qtext { white-space: pre-wrap; margin: 8px 0; max-height: 18em; overflow: auto; } -.attach { display: block; color: var(--muted-foreground); margin: 6px 0; overflow-x: auto; } -.count { background: var(--primary); color: var(--primary-foreground); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; } - -.row { display: flex; gap: 8px; align-items: center; } -.row.wrap { flex-wrap: wrap; } -.grow { flex: 1; min-width: 0; } -.row > input[type=text] { flex: 1; min-width: 0; } -.stack { display: flex; flex-direction: column; gap: 12px; margin: 10px 0; } -label { display: flex; flex-direction: column; gap: 4px; font-weight: 500; } -label.inline { flex-direction: row; align-items: center; font-weight: 400; } -fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 8px 12px; } -.answer { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; } - -input[type=text], textarea, select { - font: inherit; color: var(--foreground); background: var(--background); - border: 1px solid var(--border); border-radius: 8px; padding: 7px 10px; width: 100%; -} -input.short { width: 8em; } -textarea { resize: vertical; } -input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--primary); outline-offset: 1px; } - -button, .button { - font: inherit; cursor: pointer; border-radius: 8px; padding: 7px 14px; - border: 1px solid var(--border); background: var(--card); color: var(--foreground); white-space: nowrap; - display: inline-block; -} -button:hover, .button:hover { border-color: var(--muted-foreground); text-decoration: none; } -.primary { background: var(--primary); color: var(--primary-foreground); border-color: var(--primary); } -.danger { color: var(--danger); } -button.link { border: 0; background: none; padding: 0; color: var(--muted-foreground); } - -.badge { - font-size: 0.75rem; font-weight: 600; border-radius: 999px; padding: 2px 9px; - background: var(--muted); color: var(--muted-foreground); white-space: nowrap; -} -.s-in_progress, .s-running { color: var(--info); } -.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--primary); } -.s-review, .s-done { color: var(--ok); } -.s-blocked, .s-failed, .s-stalled, .s-rate_limited { color: var(--danger); } - -.notice { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } -.flash { background: color-mix(in srgb, var(--danger) 12%, var(--card)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; } - -ul.tasks, ul.projects, ul.events { list-style: none; padding: 0; margin: 0; } -ul.tasks li, ul.projects li { - display: flex; gap: 10px; align-items: center; justify-content: space-between; - padding: 8px 12px; background: var(--card); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0; -} -ul.tasks li a, ul.projects li a { color: var(--foreground); min-width: 0; overflow: hidden; text-overflow: ellipsis; } -ul.events li { padding: 3px 0; border-bottom: 1px dashed var(--border); overflow-wrap: anywhere; } -details { margin: 8px 0; } -summary { cursor: pointer; color: var(--primary); } -pre.md { - white-space: pre-wrap; background: var(--muted); border-radius: 8px; padding: 12px; - max-height: 32em; overflow: auto; -} - -.board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin: 16px 0; } -.board.busy { opacity: 0.6; pointer-events: none; } -.col { background: color-mix(in srgb, var(--border) 35%, var(--background)); border-radius: var(--radius); padding: 8px; min-height: 120px; } -.col.over { outline: 2px dashed var(--primary); } -.col h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; margin: 4px 4px 8px; color: var(--muted-foreground); } -.hint { font-size: 0.75rem; margin: -4px 4px 8px; } -.tcard { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 6px 0; cursor: grab; display: flex; flex-direction: column; gap: 6px; } -.tcard a { color: var(--foreground); } -.tcard .goal { font-size: 0.75rem; flex-basis: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.small { font-size: 0.78rem; padding: 3px 8px; } -details.add { margin: 4px 0; } -.login { max-width: 420px; margin: 18vh auto; text-align: center; display: flex; flex-direction: column; gap: 14px; align-items: center; } -.login h1 { font-size: 2rem; justify-content: center; } - -@media (max-width: 640px) { - .session form.grow { flex-basis: 100%; } - ul.tasks li { flex-direction: column; align-items: flex-start; } - .board { grid-template-columns: 1fr; } -} - -.consent { text-align: left; align-items: stretch; } -.consent h1 { justify-content: flex-start; } -.scopes { margin: 0; padding-left: 20px; } -.mcp-url { display: block; padding: 10px 12px; background: var(--muted); border-radius: 8px; overflow-x: auto; } - -.ok { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } - -.help ul { padding-left: 20px; } -.help li { margin: 4px 0; } -.say { margin: 6px 0; font-style: italic; } -table.tools { width: 100%; border-collapse: collapse; } -table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; } -table.tools td.mono { white-space: nowrap; } -@media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } } - -ul.members { list-style: none; padding: 0; margin: 0 0 10px; } -ul.members li { display: flex; gap: 10px; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed var(--border); } - - -dl.repo { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0 0 10px; } -dl.repo dt { color: var(--muted-foreground); } -dl.repo dd { margin: 0; } diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 667e146d..cceff97a 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -1,7 +1,9 @@ import { redirect } from "next/navigation"; import { currentUser, safeNext } from "@/lib/auth"; -import { Flash } from "@/components/ui"; +import { Brand } from "@/components/Brand"; +import { Flash } from "@/components/common"; import { Footer } from "@/components/Footer"; +import { Button } from "@/components/ui/button"; export const dynamic = "force-dynamic"; @@ -9,12 +11,16 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ const { error, next } = await searchParams; if (await currentUser()) redirect(safeNext(next)); return ( - <main className="login"> - <h1>🐷 Peppa</h1> - <p className="muted">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p> - <Flash error={error} /> - <a className="button primary" href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a> - <Footer /> + <main className="grid min-h-dvh place-items-center px-4"> + <div className="flex w-full max-w-sm flex-col items-center gap-5 text-center"> + <Brand large /> + <p className="m-0 text-sm text-muted-foreground">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p> + <Flash error={error} /> + <Button asChild variant="default" size="lg" className="w-full"> + <a href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a> + </Button> + <Footer /> + </div> </main> ); } diff --git a/apps/web/app/oauth/authorize/page.tsx b/apps/web/app/oauth/authorize/page.tsx index ce003176..086ce7fd 100644 --- a/apps/web/app/oauth/authorize/page.tsx +++ b/apps/web/app/oauth/authorize/page.tsx @@ -3,6 +3,9 @@ import { redirect } from "next/navigation"; import { currentUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { approve, deny } from "./actions"; +import { Brand } from "@/components/Brand"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; export const dynamic = "force-dynamic"; @@ -29,33 +32,35 @@ export default async function Authorize({ searchParams }: { searchParams: Promis } const host = p.redirect_uri ? new URL(p.redirect_uri).host : ""; return ( - <main className="login consent"> - <h1>🐷 Peppa</h1> - {error || !client ? ( - <p className="flash">Запрос авторизации некорректен: {error}</p> - ) : ( - <> - <p> - <b>{client.name}</b> <span className="muted">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>. - </p> - <ul className="scopes"> - <li>видеть ваши проекты, цели, задачи и вопросы агентов;</li> - <li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li> - <li>отвечать на вопросы агентов и принимать ревью.</li> - </ul> - <p className="muted">Отозвать доступ можно в «Настройки → Подключённые приложения».</p> - <div className="row"> - <form action={approve}> - <Hidden p={p} /> - <button className="primary">Разрешить</button> - </form> - <form action={deny}> - <Hidden p={p} /> - <button>Отклонить</button> - </form> - </div> - </> - )} + <main className="grid min-h-dvh place-items-center px-4"> + <Card className="w-full max-w-md gap-4 p-6"> + <Brand /> + {error || !client ? ( + <p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm">Запрос авторизации некорректен: {error}</p> + ) : ( + <> + <p className="m-0 text-sm"> + <b>{client.name}</b> <span className="text-muted-foreground">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>. + </p> + <ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-sm"> + <li>видеть ваши проекты, цели, задачи и вопросы агентов;</li> + <li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li> + <li>отвечать на вопросы агентов и принимать ревью.</li> + </ul> + <p className="m-0 text-xs text-muted-foreground">Отозвать доступ можно в «Настройки → Подключённые приложения».</p> + <div className="flex gap-2"> + <form action={approve}> + <Hidden p={p} /> + <Button variant="default">Разрешить</Button> + </form> + <form action={deny}> + <Hidden p={p} /> + <Button>Отклонить</Button> + </form> + </div> + </> + )} + </Card> </main> ); } diff --git a/apps/web/components/ActivityAside.tsx b/apps/web/components/ActivityAside.tsx index f078ea1e..d7a274b5 100644 --- a/apps/web/components/ActivityAside.tsx +++ b/apps/web/components/ActivityAside.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import { ago } from "@/components/ui"; +import { ago } from "@/components/common"; import { requireUser } from "@/lib/auth"; import { activeSessions, inbox } from "@/lib/queries"; import { SESSION_STATUS, TONE_BG } from "@/lib/status"; diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx index cdd94f94..32b17faa 100644 --- a/apps/web/components/Board.tsx +++ b/apps/web/components/Board.tsx @@ -3,6 +3,9 @@ import Link from "next/link"; import { useState, useTransition } from "react"; import { moveTaskCard } from "@/app/(app)/actions"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { cn } from "@/lib/utils"; export type Column = "backlog" | "in_progress" | "review" | "done"; export interface Card { @@ -13,13 +16,18 @@ export interface Card { goal: string | null; } -const COLUMNS: Array<{ id: Column; title: string; hint: string }> = [ - { id: "backlog", title: "Бэклог", hint: "" }, - { id: "in_progress", title: "В работе", hint: "сюда — запустить агента" }, - { id: "review", title: "Ревью", hint: "" }, - { id: "done", title: "Готово", hint: "" }, +const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [ + { id: "backlog", title: "Бэклог", hint: "", dot: "bg-muted-foreground" }, + { id: "in_progress", title: "В работе", hint: "сюда — запустить агента", dot: "bg-info" }, + { id: "review", title: "Ревью", hint: "", dot: "bg-ok" }, + { id: "done", title: "Готово", hint: "", dot: "bg-ok" }, ]; -const STATUS: Record<string, string> = { proposing: "proposal", awaiting_approval: "ждёт PM", blocked: "блок", in_progress: "агент" }; +const STATUS: Record<string, { label: string; tone: "primary" | "danger" | "info" }> = { + proposing: { label: "proposal", tone: "primary" }, + awaiting_approval: { label: "ждёт PM", tone: "primary" }, + blocked: { label: "блок", tone: "danger" }, + in_progress: { label: "агент", tone: "info" }, +}; const NEXT: Partial<Record<Column, { to: Column; label: string }>> = { backlog: { to: "in_progress", label: "В работу →" }, review: { to: "done", label: "Принять ✓" }, @@ -37,48 +45,59 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) { start(() => moveTaskCard(f)); }; return ( - <div className={`board${pending ? " busy" : ""}`}> - {COLUMNS.map((c) => ( - <section - key={c.id} - className={`col${over === c.id ? " over" : ""}`} - onDragOver={(e) => { - e.preventDefault(); - setOver(c.id); - }} - onDragLeave={() => setOver(null)} - onDrop={(e) => { - e.preventDefault(); - setOver(null); - const key = e.dataTransfer.getData("text/plain"); - const card = cards.find((x) => x.key === key); - if (card && card.column !== c.id) move(key, c.id); - }} - > - <h3> - {c.title} <span className="muted">{cards.filter((x) => x.column === c.id).length}</span> - </h3> - {c.hint && <p className="hint muted">{c.hint}</p>} - {cards - .filter((x) => x.column === c.id) - .map((card) => ( - <article key={card.key} className="tcard" draggable onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}> - <Link href={`/t/${card.key}`}> - <span className="mono">{card.key}</span> {card.title} + <div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-2 min-[1600px]:grid-cols-4", pending && "pointer-events-none opacity-60")}> + {COLUMNS.map((c) => { + const list = cards.filter((x) => x.column === c.id); + return ( + <section + key={c.id} + aria-label={c.title} + className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5")} + onDragOver={(e) => { + e.preventDefault(); + setOver(c.id); + }} + onDragLeave={() => setOver(null)} + onDrop={(e) => { + e.preventDefault(); + setOver(null); + const key = e.dataTransfer.getData("text/plain"); + const card = cards.find((x) => x.key === key); + if (card && card.column !== c.id) move(key, c.id); + }} + > + <h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase"> + <span className={cn("size-1.5 rounded-full", c.dot)} /> + {c.title} + <span className="ml-auto tabular-nums">{list.length}</span> + </h3> + {c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>} + {list.map((card) => ( + <article + key={card.key} + draggable + onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)} + className="flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing" + > + <Link href={`/t/${card.key}`} className="text-foreground hover:no-underline"> + <span className="font-mono text-xs text-primary">{card.key}</span> {card.title} </Link> - <div className="row wrap"> - {card.goal && <span className="goal muted">🎯 {card.goal}</span>} - {STATUS[card.status] && <span className={`badge s-${card.status}`}>{STATUS[card.status]}</span>} - {NEXT[c.id] && ( - <button className="small" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}> - {NEXT[c.id]!.label} - </button> - )} - </div> + {(card.goal || STATUS[card.status] || NEXT[c.id]) && ( + <div className="flex flex-wrap items-center gap-1.5"> + {card.goal && <span className="min-w-0 basis-full truncate text-xs text-muted-foreground">◎ {card.goal}</span>} + {STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>} + {NEXT[c.id] && ( + <Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}> + {NEXT[c.id]!.label} + </Button> + )} + </div> + )} </article> ))} - </section> - ))} + </section> + ); + })} </div> ); } diff --git a/apps/web/components/Brand.tsx b/apps/web/components/Brand.tsx new file mode 100644 index 00000000..f32319b5 --- /dev/null +++ b/apps/web/components/Brand.tsx @@ -0,0 +1,11 @@ +/** Peppa mark: pink tile with a glow + mono word. */ +export function Brand({ large = false }: { large?: boolean }) { + return ( + <span className="flex items-center gap-2.5"> + <span className={large ? "grid size-10 place-items-center rounded-lg bg-primary font-mono text-lg font-bold text-primary-foreground shadow-[0_0_28px_-4px_var(--primary)]" : "grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]"}> + P + </span> + <span className={large ? "font-mono text-2xl font-semibold tracking-tight" : "font-mono text-[15px] font-semibold tracking-tight"}>peppa</span> + </span> + ); +} diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx index eab5f3be..5be0d18b 100644 --- a/apps/web/components/Footer.tsx +++ b/apps/web/components/Footer.tsx @@ -13,7 +13,7 @@ export function Footer() { {commit && ( <> {" · "} - <a href={`${loadEnv().GITEA_URL}/peppa-bot/peppa/commit/${full}`} className="mono"> + <a href={`${loadEnv().GITEA_URL}/peppa-bot/peppa/commit/${full}`} className="font-mono text-primary"> {commit} </a> {dirty && <span title="Собрано с незакоммиченными изменениями"> +изменения</span>} diff --git a/apps/web/components/Incidents.tsx b/apps/web/components/Incidents.tsx index 061bb3ba..84bb6ae5 100644 --- a/apps/web/components/Incidents.tsx +++ b/apps/web/components/Incidents.tsx @@ -1,14 +1,18 @@ // Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list. +import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react"; import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core"; import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions"; -import { ago } from "./ui"; +import { Hidden } from "@/components/cards"; +import { ago, Disclosure, Empty, Key, Section } from "@/components/common"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input, Label, NativeSelect, Textarea } from "@/components/ui/input"; -const Hidden = ({ projectId, back }: { projectId: number; back: string }) => ( - <> - <input type="hidden" name="projectId" value={projectId} /> - <input type="hidden" name="back" value={back} /> - </> -); +const STATUS_TONE: Record<Incident["status"], "danger" | "warn" | "info" | "ok" | "muted"> = { new: "danger", open: "warn", pending: "warn", task: "info", ignored: "muted", resolved: "ok", regressed: "danger" }; + +function Code({ children }: { children: React.ReactNode }) { + return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs">{children}</code>; +} export function IncidentsSection(props: { projectId: number; @@ -24,138 +28,143 @@ export function IncidentsSection(props: { const { projectId, back, settings: s } = props; if (!s) { return ( - <section> - <h2>Ошибки</h2> - <p className="muted">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.</p> + <Section title="Ошибки"> + <p className="m-0 text-sm text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.</p> {props.isOwner ? ( <form action={connectErrorTrackingAction}> - <Hidden projectId={projectId} back={back} /> - <button className="primary">Подключить отслеживание ошибок</button> + <Hidden fields={{ projectId, back }} /> + <Button variant="default" size="sm"> + <Bug /> + Подключить отслеживание ошибок + </Button> </form> ) : ( - <p className="empty">Не подключено — подключает владелец проекта.</p> + <Empty>Не подключено — подключает владелец проекта.</Empty> )} - </section> + </Section> ); } const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status)); const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status)); return ( - <section> - <h2> - Ошибки <span className="muted small">политика: {POLICY_RU[s.policy]}</span> - </h2> - {active.length === 0 ? <p className="empty">Открытых ошибок нет.</p> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)} + <Section title="Ошибки" count={active.length} actions={<span className="text-xs text-muted-foreground">политика: {POLICY_RU[s.policy]}</span>}> + {active.length === 0 ? <Empty>Открытых ошибок нет.</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)} {rest.length > 0 && ( - <details> - <summary>Исправленные и игнорируемые ({rest.length})</summary> - {rest.map((i) => ( - <IncidentCard key={i.id} i={i} {...props} /> - ))} - </details> + <Disclosure summary={`Исправленные и игнорируемые (${rest.length})`}> + <div className="flex flex-col gap-2"> + {rest.map((i) => ( + <IncidentCard key={i.id} i={i} {...props} /> + ))} + </div> + </Disclosure> )} - <details> - <summary>Настройки ошибок</summary> - <div className="stack"> + <Disclosure summary="Настройки ошибок"> + <div className="flex flex-col gap-3 text-sm"> {props.sources.map((src) => ( - <div key={src.id}> - <b>DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</b> - <code className="mcp-url">{src.dsn}</code> + <div key={src.id} className="flex flex-col gap-1"> + <span className="font-medium">DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</span> + <Code>{src.dsn}</Code> </div> ))} - <p className="muted"> - В коде: <code>{"NEXT_PUBLIC_SENTRY_DSN"}</code> / <code>SENTRY_DSN</code> из окружения, <code>release</code> = SHA деплоя, <code>environment</code> = prod, <code>sendDefaultPii: false</code>. + <p className="m-0 text-muted-foreground"> + В коде: <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> из окружения, <code className="font-mono">release</code> = SHA деплоя,{" "} + <code className="font-mono">environment</code> = prod, <code className="font-mono">sendDefaultPii: false</code>. </p> {!s.webhookAuto && props.webhookUrl && ( - <div> - <b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook: - <code className="mcp-url">{props.webhookUrl}</code> - <span className="muted">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span> + <div className="flex flex-col gap-1"> + <span><b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:</span> + <Code>{props.webhookUrl}</Code> + <span className="text-muted-foreground">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span> </div> )} - <form action={saveIncidentSettings} className="stack"> - <Hidden projectId={projectId} back={back} /> - <label> - Политика инцидентов{" "} - <select name="policy" defaultValue={s.policy} aria-label="Политика инцидентов"> + <form action={saveIncidentSettings} className="flex flex-col gap-2.5"> + <Hidden fields={{ projectId, back }} /> + <Label> + Политика инцидентов + <NativeSelect name="policy" defaultValue={s.policy} aria-label="Политика инцидентов"> {incidentPolicies.map((p) => ( <option key={p} value={p}> {p} — {POLICY_RU[p]} </option> ))} - </select> - </label> - <textarea + </NativeSelect> + </Label> + <Textarea name="triagePrompt" rows={3} defaultValue={s.triagePrompt ?? ""} aria-label="Как принимать решение (для триажёра)" placeholder="Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»" /> - <div className="row"> - <input type="text" name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" /> - <input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Задач в сутки" style={{ width: "6em" }} /> + <div className="flex gap-2"> + <Input name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" /> + <Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Задач в сутки" className="w-24" /> </div> - <input type="text" name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" /> - <button>Сохранить</button> + <Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" /> + <Button size="sm" className="self-start">Сохранить</Button> </form> </div> - </details> - </section> + </Disclosure> + </Section> ); } function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string> }) { const taskKey = i.taskId ? taskKeys.get(i.taskId) : null; - const decide = (action: string, label: string) => ( + const decide = (action: string, label: string, icon: React.ReactNode) => ( <form action={decideIncidentAction}> - <Hidden projectId={projectId} back={back} /> - <input type="hidden" name="incidentId" value={i.id} /> - <input type="hidden" name="action" value={action} /> - <button className="small">{label}</button> + <Hidden fields={{ projectId, back, incidentId: i.id, action }} /> + <Button size="xs"> + {icon} + {label} + </Button> </form> ); return ( - <div className="card"> - <div className="row"> - <span className="badge">{INCIDENT_STATUS_RU[i.status]}</span> - <b className="grow">{i.title}</b> - <span className="muted small">{ago(i.lastSeen)}</span> + <article className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm"> + <div className="flex items-start gap-2"> + <Badge variant={STATUS_TONE[i.status]}>{INCIDENT_STATUS_RU[i.status]}</Badge> + <b className="min-w-0 flex-1 font-mono text-[13px] font-medium [overflow-wrap:anywhere]">{i.title}</b> + <span className="shrink-0 font-mono text-xs text-muted-foreground">{ago(i.lastSeen)}</span> </div> - <div className="muted small"> + <div className="flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground"> {i.source} · {i.environment ?? "—"} · релиз {i.lastRelease ?? "—"} · событий {i.events} - {i.culprit && <> · 📍 {i.culprit}</>} + {i.culprit && ( + <span className="inline-flex items-center gap-1"> + · <MapPin className="size-3" /> {i.culprit} + </span> + )} {i.url && ( <> - {" · "} - <a href={i.url}>Bugsink</a> + · <a href={i.url} className="text-primary">Bugsink</a> </> )} {taskKey && ( <> - {" · "} - <a href={`/t/${taskKey}`}>{taskKey}</a> + · <Key href={`/t/${taskKey}`}>{taskKey}</Key> </> )} </div> - {i.decisionReason && <div className="muted small">{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}</div>} - <div className="row"> + {i.decisionReason && <div className="text-xs text-muted-foreground">{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}</div>} + <div className="flex flex-wrap gap-1.5"> {!i.taskId && i.status !== "resolved" && ( <> - {decide("backlog", "📥 В бэклог")} - {decide("start", "▶️ В работу")} - {i.status !== "ignored" && decide("ignore", "🙈 Игнорировать")} + {decide("backlog", "В бэклог", <Inbox />)} + {decide("start", "В работу", <Play />)} + {i.status !== "ignored" && decide("ignore", "Игнорировать", <EyeOff />)} </> )} {i.status !== "resolved" && i.status !== "ignored" && ( - <form action={resolveIncidentAction} className="row"> - <Hidden projectId={projectId} back={back} /> - <input type="hidden" name="incidentId" value={i.id} /> - <button className="small">✅ Исправлено</button> + <form action={resolveIncidentAction}> + <Hidden fields={{ projectId, back, incidentId: i.id }} /> + <Button size="xs"> + <CircleCheck /> + Исправлено + </Button> </form> )} </div> - </div> + </article> ); } diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index a6b9c43e..61d3d5ab 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -3,6 +3,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, type LucideIcon } from "lucide-react"; +import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; @@ -30,8 +31,7 @@ export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl return ( <header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-sidebar px-3 md:h-dvh md:flex-col md:items-stretch md:gap-1 md:border-r md:border-b-0 md:px-3 md:py-4"> <Link href="/" className="flex shrink-0 items-center gap-2 rounded-md px-1 text-foreground hover:no-underline md:mb-4 md:px-2"> - <span className="grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]">P</span> - <span className="font-mono text-[15px] font-semibold tracking-tight">peppa</span> + <Brand /> <span className="hidden font-mono text-[11px] text-muted-foreground md:inline">фабрика</span> </Link> <nav diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx new file mode 100644 index 00000000..dc81e057 --- /dev/null +++ b/apps/web/components/cards.tsx @@ -0,0 +1,161 @@ +// Domain cards shared by pages: agent questions, runners, project list. +import Link from "next/link"; +import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square } from "lucide-react"; +import type { Project, Question, SessionView } from "@peppa/core"; +import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { ago, Empty, Key, StatusBadge } from "@/components/common"; +import { cn } from "@/lib/utils"; + +const KIND = { + approval: { label: "Одобрение proposal", icon: FileCheck, border: "border-l-primary" }, + question: { label: "Вопрос", icon: CircleHelp, border: "border-l-info" }, + permission: { label: "Разрешение", icon: ShieldQuestion, border: "border-l-warn" }, + attention: { label: "Сессия ждёт тебя", icon: BellRing, border: "border-l-ok" }, +} as const; + +/** Hidden inputs of a server-action form. */ +export function Hidden({ fields }: { fields: Record<string, string | number | null | undefined> }) { + return ( + <> + {Object.entries(fields).map(([k, v]) => (v == null ? null : <input key={k} type="hidden" name={k} value={v} />))} + </> + ); +} + +export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean }) { + const review = q.kind === "attention" && taskStatus === "review"; + const answered = !!q.answeredAt; + const k = KIND[q.kind]; + const Icon = review ? CircleCheck : k.icon; + return ( + <article id={`q-${q.id}`} className={cn("flex flex-col gap-2.5 rounded-lg border border-l-2 bg-card p-4", answered ? "border-l-border opacity-70" : k.border)}> + <header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm"> + <Icon className="size-4 text-muted-foreground" /> + <span className="font-medium">{review ? "Готово к ревью" : k.label}</span> + {taskKey && <Key href={`/t/${taskKey}`}>{taskKey}</Key>} + <span className="ml-auto font-mono text-xs text-muted-foreground"> + #{q.id} · {ago(q.createdAt)} + </span> + </header> + <p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{q.text}</p> + {answered ? ( + <p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground"> + {q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />} + {q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`} + </p> + ) : ( + <form action={answerQuestion} className="flex flex-col gap-2"> + <Hidden fields={{ questionId: q.id, back }} /> + <div className="flex flex-wrap gap-2"> + {q.kind === "approval" && <Button name="choice" value="ок" variant="default" size="sm">Одобрить</Button>} + {q.kind === "permission" && ( + <> + <Button name="choice" value="allow" variant="default" size="sm">Разрешить</Button> + <Button name="choice" value="always" size="sm">Всегда</Button> + <Button name="choice" value="deny" variant="destructive" size="sm">Запретить</Button> + </> + )} + {review && <Button name="choice" value="__accept" variant="default" size="sm">Принять</Button>} + {q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">Продолжай</Button>} + {(q.options ?? []).map((o) => ( + <Button key={o} name="choice" value={o} size="sm">{o}</Button> + ))} + </div> + {q.kind !== "permission" && ( + <div className="flex gap-2"> + <Input name="answer" placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" /> + <Button size="sm">Ответить</Button> + </div> + )} + </form> + )} + </article> + ); +} + +/** Message / stop / resume controls of one runner. */ +export function SessionActions({ s, back }: { s: SessionView; back: string }) { + const alive = !["done", "failed"].includes(s.status); + return ( + <div className="flex flex-wrap gap-2"> + {alive && ( + <form action={messageSession} className="flex min-w-0 flex-[1_1_16rem] gap-2"> + <Hidden fields={{ sessionId: s.id, back }} /> + <Input name="text" placeholder="Сообщение в сессию" aria-label="Сообщение в сессию" className="h-8" /> + <Button size="sm" aria-label="Отправить" title="Отправить"> + <Send /> + <span className="max-sm:hidden">Отправить</span> + </Button> + </form> + )} + {alive && ( + <form action={stopTaskSession}> + <Hidden fields={{ sessionId: s.id, back }} /> + <Button variant="destructive" size="sm"> + <Square /> + Остановить + </Button> + </form> + )} + {(!alive || ["rate_limited", "stalled"].includes(s.status)) && ( + <form action={resumeTaskSession}> + <Hidden fields={{ sessionId: s.id, back }} /> + <Button size="sm"> + {alive ? <RotateCcw /> : <Play />} + Resume + </Button> + </form> + )} + </div> + ); +} + +export function AttachCommand({ name }: { name: string }) { + return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs whitespace-nowrap text-muted-foreground">tmux attach -t {name}</code>; +} + +export function SessionCard({ s, back, showTitle = false }: { s: SessionView; back: string; showTitle?: boolean }) { + return ( + <article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5"> + <header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm"> + <StatusBadge status={s.status} kind="session" /> + {s.taskKey ? <Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key> : <Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>} + {showTitle && s.taskTitle && <span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle}</span>} + <span className="ml-auto font-mono text-xs text-muted-foreground"> + <Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider} · пок. {s.generation} · {ago(s.lastActivityAt)} + </span> + </header> + <AttachCommand name={s.tmuxName} /> + <SessionActions s={s} back={back} /> + </article> + ); +} + +export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) { + if (!projects.length) + return ( + <Empty> + Проектов пока нет. <Link href="/projects/new" className="text-primary">Создать первый</Link> + </Empty> + ); + return ( + <ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2"> + {projects.map((p) => ( + <li key={p.id}> + <Link href={`/p/${p.key}`} className="flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 text-foreground transition-colors hover:border-primary/50 hover:no-underline"> + <span className="flex items-center gap-2"> + <span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span> + <span className="min-w-0 truncate font-medium">{p.name}</span> + {p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">общий</span>} + </span> + <span className="truncate font-mono text-xs text-muted-foreground"> + {p.giteaOwner}/{p.giteaRepo} + </span> + </Link> + </li> + ))} + </ul> + ); +} diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx new file mode 100644 index 00000000..ace2ab0a --- /dev/null +++ b/apps/web/components/common.tsx @@ -0,0 +1,101 @@ +// Page building blocks of the console (PEP-38): header, sections, empty states, status badges, alerts. +import Link from "next/link"; +import type { ReactNode } from "react"; +import { CircleAlert, CircleCheck } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status"; +import { cn } from "@/lib/utils"; + +export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) { + return ( + <header className="mb-6 flex flex-col gap-1.5"> + {crumbs && <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">{crumbs}</div>} + <div className="flex flex-wrap items-center gap-x-3 gap-y-2"> + <h1 className="m-0 flex min-w-0 flex-wrap items-center gap-2 text-xl font-semibold tracking-tight md:text-2xl">{title}</h1> + {actions && <div className="ml-auto flex flex-wrap items-center gap-2">{actions}</div>} + </div> + {children && <div className="text-sm text-muted-foreground">{children}</div>} + </header> + ); +} + +export function Section({ title, count, actions, children, className, id }: { title: ReactNode; count?: number; actions?: ReactNode; children: ReactNode; className?: string; id?: string }) { + return ( + <section id={id} className={cn("mt-8 flex flex-col gap-3 first:mt-0", className)}> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="m-0 text-[15px] font-semibold">{title}</h2> + {count != null && count > 0 && <span className="rounded-full bg-primary px-2 font-mono text-[11px] leading-5 font-semibold text-primary-foreground tabular-nums">{count}</span>} + {actions && <div className="ml-auto flex items-center gap-2 text-sm">{actions}</div>} + </div> + {children} + </section> + ); +} + +export function MoreLink({ href, children }: { href: string; children: ReactNode }) { + return ( + <Link href={href} className="text-xs text-muted-foreground hover:text-foreground"> + {children} → + </Link> + ); +} + +export function Empty({ children }: { children: ReactNode }) { + return <p className="m-0 rounded-lg border border-dashed px-4 py-5 text-center text-sm text-muted-foreground">{children}</p>; +} + +/** Monospace task/project key, optionally a link. */ +export function Key({ children, href, className }: { children: ReactNode; href?: string; className?: string }) { + const cls = cn("font-mono text-[0.9em] whitespace-nowrap", href ? "text-primary hover:underline" : "text-muted-foreground", className); + return href ? <Link href={href} className={cls}>{children}</Link> : <span className={cls}>{children}</span>; +} + +export function StatusBadge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) { + const s = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? { label: status, tone: "muted" as const }; + return ( + <Badge variant={s.tone}> + {kind === "session" && <span className={cn("size-1.5 rounded-full", TONE_BG[s.tone], status === "running" && "animate-pulse")} />} + {s.label} + </Badge> + ); +} + +export function Flash({ error }: { error?: string }) { + return error ? ( + <p role="alert" className="mb-4 flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-foreground"> + <CircleAlert className="mt-0.5 size-4 shrink-0 text-destructive" /> + <span>{error}</span> + </p> + ) : null; +} + +export function Notice({ children }: { children: ReactNode }) { + return ( + <div role="status" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-ok/40 bg-ok/10 px-4 py-3 text-sm"> + <CircleCheck className="size-4 shrink-0 text-ok" /> + {children} + </div> + ); +} + +/** Collapsible block styled as a card (native <details>: no client JS). */ +export function Disclosure({ summary, children, open, className }: { summary: ReactNode; children: ReactNode; open?: boolean; className?: string }) { + return ( + <details open={open} className={cn("group rounded-lg border bg-card", className)}> + <summary className="flex cursor-pointer list-none items-center gap-2 px-4 py-2.5 text-sm font-medium select-none [&::-webkit-details-marker]:hidden"> + <span className="text-muted-foreground transition-transform group-open:rotate-90">›</span> + {summary} + </summary> + <div className="border-t px-4 py-3">{children}</div> + </details> + ); +} + +export function ago(d: Date | null | undefined): string { + if (!d) return "—"; + const s = Math.round((Date.now() - d.getTime()) / 1000); + if (s < 60) return `${s} с назад`; + if (s < 3600) return `${Math.round(s / 60)} мин назад`; + if (s < 86400) return `${Math.round(s / 3600)} ч назад`; + return d.toLocaleDateString("ru-RU"); +} diff --git a/apps/web/components/ui.tsx b/apps/web/components/ui.tsx deleted file mode 100644 index 6dcc24be..00000000 --- a/apps/web/components/ui.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import Link from "next/link"; -import type { ReactNode } from "react"; -import type { Project, Question, SessionView } from "@peppa/core"; -import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; - -const TASK_STATUS: Record<string, string> = { - backlog: "Бэклог", - proposing: "Proposal", - awaiting_approval: "Ждёт одобрения", - in_progress: "В работе", - review: "Ревью", - done: "Готово", - blocked: "Блок", -}; -const SESSION_STATUS: Record<string, string> = { - starting: "запуск", - running: "работает", - waiting_input: "ждёт тебя", - idle: "простаивает", - stalled: "зависла?", - rate_limited: "лимит", - done: "завершена", - failed: "упала", -}; -const KIND: Record<string, string> = { approval: "Одобрение proposal", question: "Вопрос", permission: "Разрешение", attention: "Сессия ждёт тебя" }; - -export function Badge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) { - const label = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? status; - return <span className={`badge s-${status}`}>{label}</span>; -} - -export function Flash({ error }: { error?: string }) { - return error ? <p className="flash" role="alert">{error}</p> : null; -} - -export function Notice({ children }: { children: ReactNode }) { - return <p className="notice" role="status">{children}</p>; -} - -export function ago(d: Date | null | undefined): string { - if (!d) return "—"; - const s = Math.round((Date.now() - d.getTime()) / 1000); - if (s < 60) return `${s} с назад`; - if (s < 3600) return `${Math.round(s / 60)} мин назад`; - if (s < 86400) return `${Math.round(s / 3600)} ч назад`; - return d.toLocaleDateString("ru-RU"); -} - -export function QuestionCard({ q, taskKey, taskStatus, back }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string }) { - const review = q.kind === "attention" && taskStatus === "review"; - const answered = !!q.answeredAt; - return ( - <article className={`card q q-${q.kind}${answered ? " answered" : ""}`}> - <header className="row"> - <span className="kind">{review ? "Готово к ревью" : KIND[q.kind]}</span> - {taskKey && ( - <Link href={`/t/${taskKey}`} className="mono"> - {taskKey} - </Link> - )} - <span className="muted">#{q.id} · {ago(q.createdAt)}</span> - </header> - <p className="qtext">{q.text}</p> - {answered ? ( - <p className="muted"> - {q.answeredVia === "system" ? "⌛ " : "✅ "} - {q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`} - </p> - ) : ( - <form action={answerQuestion} className="answer"> - <input type="hidden" name="questionId" value={q.id} /> - <input type="hidden" name="back" value={back} /> - <div className="row wrap"> - {q.kind === "approval" && <button name="choice" value="ок" className="primary">Одобрить</button>} - {q.kind === "permission" && ( - <> - <button name="choice" value="allow" className="primary">Разрешить</button> - <button name="choice" value="always">Всегда</button> - <button name="choice" value="deny" className="danger">Запретить</button> - </> - )} - {review && <button name="choice" value="__accept" className="primary">Принять</button>} - {q.kind === "attention" && !review && <button name="choice" value="Продолжай." className="primary">Продолжай</button>} - {(q.options ?? []).map((o) => ( - <button key={o} name="choice" value={o}>{o}</button> - ))} - </div> - {q.kind !== "permission" && ( - <div className="row"> - <input type="text" name="answer" placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" /> - <button>Ответить</button> - </div> - )} - </form> - )} - </article> - ); -} - -export function SessionCard({ s, back, showTitle = false }: { s: SessionView; back: string; showTitle?: boolean }) { - const alive = !["done", "failed"].includes(s.status); - return ( - <article className="card session"> - <header className="row"> - <Badge status={s.status} kind="session" /> - {s.taskKey ? <Link href={`/t/${s.taskKey}`} className="mono">{s.taskKey}</Link> : <Link href={`/p/${s.projectKey}`} className="mono">{s.projectKey}</Link>} - {showTitle && s.taskTitle && <span className="title">{s.taskTitle}</span>} - <span className="muted">#{s.id} · {s.provider} · поколение {s.generation} · {ago(s.lastActivityAt)}</span> - </header> - <code className="attach">tmux attach -t {s.tmuxName}</code> - <div className="row wrap"> - {alive && ( - <form action={messageSession} className="row grow"> - <input type="hidden" name="sessionId" value={s.id} /> - <input type="hidden" name="back" value={back} /> - <input type="text" name="text" placeholder="Сообщение в сессию" aria-label="Сообщение в сессию" /> - <button>Отправить</button> - </form> - )} - {alive ? ( - <form action={stopTaskSession}> - <input type="hidden" name="sessionId" value={s.id} /> - <input type="hidden" name="back" value={back} /> - <button className="danger">Остановить</button> - </form> - ) : null} - {(!alive || ["rate_limited", "stalled"].includes(s.status)) && ( - <form action={resumeTaskSession}> - <input type="hidden" name="sessionId" value={s.id} /> - <input type="hidden" name="back" value={back} /> - <button>Resume</button> - </form> - )} - </div> - </article> - ); -} - -export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) { - if (!projects.length) - return ( - <p className="empty"> - Проектов пока нет. <Link href="/projects/new">Создать первый</Link> - </p> - ); - return ( - <ul className="projects"> - {projects.map((p) => ( - <li key={p.id}> - <Link href={`/p/${p.key}`}> - <span className="mono">{p.key}</span> {p.name} - </Link> - <span className="muted"> - {p.ownerId !== userId && <span className="badge">общий</span>} {p.giteaOwner}/{p.giteaRepo} - </span> - </li> - ))} - </ul> - ); -} diff --git a/apps/web/scripts/mock-ui-seed.ts b/apps/web/scripts/mock-ui-seed.ts index a5e81e4c..fa281db0 100644 --- a/apps/web/scripts/mock-ui-seed.ts +++ b/apps/web/scripts/mock-ui-seed.ts @@ -2,10 +2,10 @@ // column, runners in every status (one hit the usage limit and resumes later), open questions, releases. // Only for a throwaway database — refuses the production one: // DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login] -import { mkdirSync } from "node:fs"; +import { mkdirSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { createDb, events, goals, projects, questions, releases, sessions, tasks, users } from "@peppa/db"; +import { checkRuns, createDb, errorSources, events, goals, incidents, incidentSettings, projects, questions, releases, sessions, tasks, users } from "@peppa/db"; import { eq } from "drizzle-orm"; const url = process.env.DATABASE_URL ?? ""; @@ -19,7 +19,9 @@ const ws = join(tmpdir(), "peppa-mock-ui"); const [user] = await db.insert(users).values({ giteaId: -900001, login }).onConflictDoUpdate({ target: users.login, set: { login } }).returning(); async function project(key: string, name: string, slug: string) { - mkdirSync(join(ws, slug), { recursive: true }); + mkdirSync(join(ws, slug, ".peppa"), { recursive: true }); + const checks = { typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" }; + writeFileSync(join(ws, slug, ".peppa", "project.json"), JSON.stringify({ key, slug, checks })); const [p] = await db .insert(projects) .values({ key, name, slug, giteaOwner: login, giteaRepo: slug, workspacePath: join(ws, slug), ownerId: user!.id }) @@ -108,5 +110,22 @@ await db.insert(releases).values([ { projectId: pay.id, env: "staging", sha: "a1b2c3d4e5f6", status: "healthy", host: "mock-payments-staging.telecom.quest", tasks: ["PAY-6"], deployedBy: "ci" }, { projectId: pay.id, env: "prod", sha: "9f8e7d6c5b4a", status: "healthy", host: "mock-payments-prod.telecom.quest", tasks: ["PAY-5"], deployedBy: login }, ]); +// CI of PAY-1 (one red check with a log tail) and PAY-4 (green), PEP-57. +await db.insert(checkRuns).values([ + ...["typecheck", "build"].map((check) => ({ projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check, state: "success" as const })), + { projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check: "test", state: "failure" as const, logTail: "FAIL src/webhook.test.ts\n ✕ marks the payment paid (12 ms)\n expected 'paid', got 'pending'" }, + ...["typecheck", "test", "build"].map((check) => ({ projectId: pay.id, taskId: pt[3]!.id, sha: "beef5678", check, state: "success" as const })), +]); +// Error tracking (PEP-58): settings, DSNs, an open incident, one with a task, one ignored. +await db.insert(incidentSettings).values({ projectId: pay.id, hookSecret: "mock-hook-secret", policy: "ask", webhookAuto: false }); +await db.insert(errorSources).values([ + { projectId: pay.id, kind: "web", bugsinkProjectId: 9001, dsn: "https://mock-key@bugsink.example/9001" }, + { projectId: pay.id, kind: "api", bugsinkProjectId: 9002, dsn: "https://mock-key@bugsink.example/9002" }, +]); +await db.insert(incidents).values([ + { projectId: pay.id, source: "web", bugsinkIssueId: "mock-1", title: "TypeError: Cannot read properties of undefined (reading 'amount')", culprit: "PaymentForm.tsx in submit", environment: "prod", lastRelease: "9f8e7d6", events: 14, firstSeen: ago(300), lastSeen: ago(6), status: "pending", decidedBy: "triage", decisionReason: "Падает оплата у части пользователей — нужен PM" }, + { projectId: pay.id, source: "api", bugsinkIssueId: "mock-2", title: "TimeoutError: YooKassa did not answer in 10s", environment: "prod", events: 3, firstSeen: ago(900), lastSeen: ago(90), status: "task", taskId: pt[4]!.id }, + { projectId: pay.id, source: "web", bugsinkIssueId: "mock-3", title: "ResizeObserver loop limit exceeded", environment: "prod", events: 120, firstSeen: ago(5000), lastSeen: ago(30), status: "ignored" }, +]); console.log(`seeded: user ${login}, projects PAY and SHOP, ${made.length} runners`); process.exit(0); diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/pep-38-factory-console/tasks.md index cf8e8886..82c64687 100644 --- a/openspec/changes/pep-38-factory-console/tasks.md +++ b/openspec/changes/pep-38-factory-console/tasks.md @@ -8,12 +8,12 @@ - [x] 1.5 Старый CSS в слое `base`, все маршруты открываются; проверка в браузере (desktop + 390 px) ## 2. Перенос страниц (PR 2) -- [ ] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer -- [ ] 2.2 Главная, Проекты, Новый проект -- [ ] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий -- [ ] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события -- [ ] 2.5 Настройки, Помощь, вход, согласие OAuth -- [ ] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере +- [x] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer +- [x] 2.2 Главная, Проекты, Новый проект +- [x] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий +- [x] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события +- [x] 2.5 Настройки, Помощь, вход, согласие OAuth +- [x] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере ## 3. Пульт раннеров (PR 3) - [ ] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой -- 2.45.2 From 50b1d1afecd39807a50d0f7ca5684c39d19a23c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:03:43 +0500 Subject: [PATCH 015/536] PEP-36: benchmark SQLite vs Postgres and propose Bun + SQLite stack bench/sqlite (outside the workspace): Peppa-like load with 10/20 runners, a hook process per event, MCP, bot, web and watchdog; bun:sqlite, node:sqlite, better-sqlite3, a single-writer service and Postgres; notify replacements (cursor polling, fs.watch on WAL, unix-socket push); a ceiling test; a schema port to sqlite with a data copy from Postgres and a check of drizzle transactions. openspec/changes/pep-36-lightweight-stack: proposal, design with the numbers, specs (platform-storage, service-monitoring), phased tasks. No product code changes; the move waits for the PM's decision. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- bench/sqlite/.gitignore | 2 + bench/sqlite/README.md | 62 + bench/sqlite/RESULTS.md | 70 + bench/sqlite/contention.ts | 76 + bench/sqlite/lib/db.ts | 172 ++ bench/sqlite/lib/notify.ts | 49 + bench/sqlite/lib/schema.ts | 34 + bench/sqlite/matrix.sh | 32 + bench/sqlite/package.json | 15 + bench/sqlite/pnpm-lock.yaml | 40 + bench/sqlite/report.ts | 48 + bench/sqlite/roles.ts | 336 +++ bench/sqlite/run.ts | 128 ++ bench/sqlite/schema-port/copy-from-pg.ts | 53 + bench/sqlite/schema-port/drizzle.config.ts | 2 + .../schema-port/migrations/0000_baseline.sql | 271 +++ .../migrations/meta/0000_snapshot.json | 1947 +++++++++++++++++ .../schema-port/migrations/meta/_journal.json | 13 + bench/sqlite/schema-port/schema.ts | 357 +++ bench/sqlite/schema-port/tx-check.ts | 35 + .../pep-36-lightweight-stack/design.md | 215 ++ .../pep-36-lightweight-stack/proposal.md | 67 + .../specs/platform-storage/spec.md | 95 + .../specs/service-monitoring/spec.md | 16 + .../changes/pep-36-lightweight-stack/tasks.md | 41 + 25 files changed, 4176 insertions(+) create mode 100644 bench/sqlite/.gitignore create mode 100644 bench/sqlite/README.md create mode 100644 bench/sqlite/RESULTS.md create mode 100644 bench/sqlite/contention.ts create mode 100644 bench/sqlite/lib/db.ts create mode 100644 bench/sqlite/lib/notify.ts create mode 100644 bench/sqlite/lib/schema.ts create mode 100755 bench/sqlite/matrix.sh create mode 100644 bench/sqlite/package.json create mode 100644 bench/sqlite/pnpm-lock.yaml create mode 100644 bench/sqlite/report.ts create mode 100644 bench/sqlite/roles.ts create mode 100644 bench/sqlite/run.ts create mode 100644 bench/sqlite/schema-port/copy-from-pg.ts create mode 100644 bench/sqlite/schema-port/drizzle.config.ts create mode 100644 bench/sqlite/schema-port/migrations/0000_baseline.sql create mode 100644 bench/sqlite/schema-port/migrations/meta/0000_snapshot.json create mode 100644 bench/sqlite/schema-port/migrations/meta/_journal.json create mode 100644 bench/sqlite/schema-port/schema.ts create mode 100644 bench/sqlite/schema-port/tx-check.ts create mode 100644 openspec/changes/pep-36-lightweight-stack/design.md create mode 100644 openspec/changes/pep-36-lightweight-stack/proposal.md create mode 100644 openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md create mode 100644 openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md create mode 100644 openspec/changes/pep-36-lightweight-stack/tasks.md diff --git a/bench/sqlite/.gitignore b/bench/sqlite/.gitignore new file mode 100644 index 00000000..2be94185 --- /dev/null +++ b/bench/sqlite/.gitignore @@ -0,0 +1,2 @@ +node_modules +results/ diff --git a/bench/sqlite/README.md b/bench/sqlite/README.md new file mode 100644 index 00000000..db7c344a --- /dev/null +++ b/bench/sqlite/README.md @@ -0,0 +1,62 @@ +# PEP-36: замер SQLite vs Postgres под нагрузкой Пеппы + +Не часть продукта: отдельный `package.json` вне pnpm-воркспейса, свои зависимости. +Результаты и выводы — в `openspec/changes/pep-36-lightweight-stack/design.md`. + +```bash +cd bench/sqlite +pnpm install --ignore-workspace # better-sqlite3 под Node 26 собирается из исходников (node-gyp) +# один прогон +node run.ts --backend bun --runners 10 --load 1 --duration 90 --notify poll:1000 +# вся матрица (~35 мин); Postgres — только одноразовая БД peppa_bench +BENCH_PG_URL=postgres://peppa:…@127.0.0.1:5433/peppa_bench ./matrix.sh +``` + +`results/<прогон>/summary.json` — перцентили по каждой операции (в git не кладутся). + +## Модель нагрузки + +Частоты сняты с боевой БД `peppa` (только чтение, 2026-11-13): за сутки 107 событий, +медианный промежуток между событиями одной сессии 16 с, пик 6 событий в минуту на сессию. +Хуки Claude у Пеппы срабатывают на prompt / notification / stop / permission, не на каждый +вызов инструмента. Модель с запасом: + +| Процесс | Что делает | Частота (×1) | +|---|---|---| +| хук (`peppa-hook`) | **новый процесс на каждое событие**: открыть БД, прочитать сессию, транзакция «update sessions + insert events» | экспоненциально, в среднем раз в 10 с на раннер | +| хук-вопрос | 10 % хуков: insert questions + update sessions + insert events, затем опрос ответа раз в 1,5 с (как PermissionRequest) и снятие `awaiting_hook` | — | +| MCP (`peppa-mcp`) | долгоживущий на раннер: `report_progress` (insert events + update tasks), `get_task` (2 чтения) | 30 с / 15 с | +| бот | outbox раз в 1 с, reconcile раз в 2 с, ответ «PM» через 2–8 с (insert telegram_updates → update questions), heartbeat 30 с; потребитель событий | — | +| веб | 3 открытые доски, 4 запроса раз в 5 с; потребитель событий | — | +| вачдог | tick раз в 30 с: список сессий, 10 % — stalled (update + insert), heartbeat | — | + +`--load 10` умножает частоты хуков и MCP в 10 раз (стресс). `--runners` — 10 или 20. + +## Варианты (`--backend`) + +- `bun` — `bun:sqlite`, каждый процесс открывает файл сам; WAL, `busy_timeout=5000`, + `synchronous=NORMAL`, транзакции записи `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`. +- `node` — то же на `node:sqlite` (Node 26). +- `better` — то же на `better-sqlite3` 13 (Node). +- `writer` — один процесс-писатель (Bun) владеет записью, остальные шлют транзакции по + HTTP через unix-сокет; чтения идут прямо в файл (читатели WAL не блокируются). +- `pg` — текущий стек: Postgres 17 (docker), postgres.js, Node; хук открывает соединение. + +## Доставка событий (`--notify`) + +Потребитель (бот, веб) будится и читает `events where id > cursor`. Задержка — от момента +перед записью события до момента, когда потребитель его прочитал. + +- `pg` — LISTEN/NOTIFY (как сейчас в боте) +- `poll:N` — опрос с курсором каждые N мс +- `fswatch` — `fs.watch` на `-wal` файле (+ страховочный опрос раз в 5 с) +- `push` — писатель (или маленький хаб) рассылает id новых событий подписчикам по unix-сокету + +## Найденные ловушки + +- `PRAGMA busy_timeout` должен идти **первым** после открытия. Если раньше выполнить хоть + что-то (даже `journal_mode`), при одновременном открытии файла многими процессами + прилетает `SQLITE_BUSY_RECOVERY` сразу, без ожидания. `journal_mode=WAL` постоянный — + ставится один раз при создании файла. +- Путь unix-сокета на macOS ограничен 104 байтами — сокеты держать в коротком каталоге. +- На Bun `fetch(..., { unix })` заметно быстрее `node:http` для одноразовых процессов. diff --git a/bench/sqlite/RESULTS.md b/bench/sqlite/RESULTS.md new file mode 100644 index 00000000..72e9576a --- /dev/null +++ b/bench/sqlite/RESULTS.md @@ -0,0 +1,70 @@ +# PEP-36: результаты замера (2026-11-13, Mac Пеппы, Bun 1.4.4, Node 26.8.1, Postgres 17.11) + +Сгенерировано `node report.ts` после `./matrix.sh`; потолок — `contention.ts`. + +## Записи и доставка + +| раннеры | нагрузка | вариант | записей | p50 мс | p95 | p99 | max | BUSY-повторы | ошибки | хук целиком p50/p95 | старт хука p50 | доставка боту p50/p95/p99 | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| 10 | ×1 | bun:sqlite | 126 | 0.32 | 1.61 | 2.34 | 2.68 | 0 | 0 | 35.77 / 38.68 | 31.94 | 459 / 974 / 993 (poll:1000) | +| 10 | ×1 | node:sqlite | 192 | 0.20 | 0.70 | 1.18 | 1.27 | 0 | 0 | 98.08 / 9112 | 96.21 | 421 / 906 / 950 (poll:1000) | +| 10 | ×1 | better-sqlite3 | 169 | 0.19 | 0.95 | 2.02 | 2.21 | 0 | 0 | 103 / 6117 | 97.01 | 556 / 981 / 987 (poll:1000) | +| 10 | ×1 | один писатель (Bun) | 140 | 1.21 | 2.35 | 3.89 | 8.19 | 0 | 0 | 31.10 / 6036 | 22.56 | 0.97 / 3.20 / 1547 (push) | +| 10 | ×1 | Postgres (Node) | 177 | 9.60 | 18.11 | 36.05 | 38.15 | 0 | 0 | 132 / 6156 | 92.00 | 13.32 / 23.25 / 39.90 (pg) | +| 10 | ×10 | bun:sqlite | 728 | 0.24 | 0.78 | 1.22 | 5.96 | 0 | 0 | 30.37 / 7535 | 24.86 | 478 / 937 / 992 (poll:1000) | +| 10 | ×10 | node:sqlite | 696 | 0.14 | 0.38 | 0.94 | 1.76 | 0 | 0 | 77.71 / 7573 | 74.67 | 519 / 960 / 996 (poll:1000) | +| 10 | ×10 | better-sqlite3 | 698 | 0.17 | 0.49 | 1.41 | 2.51 | 0 | 0 | 81.82 / 6091 | 73.97 | 508 / 951 / 987 (poll:1000) | +| 10 | ×10 | один писатель (Bun) | 719 | 1.16 | 2.12 | 2.60 | 6.55 | 0 | 0 | 30.22 / 7530 | 23.42 | 0.81 / 2.05 / 3.50 (push) | +| 10 | ×10 | Postgres (Node) | 691 | 8.03 | 12.61 | 16.25 | 24.60 | 0 | 0 | 114 / 7628 | 74.03 | 11.21 / 16.51 / 19.12 (pg) | +| 20 | ×1 | bun:sqlite | 327 | 0.29 | 1.34 | 2.21 | 3.06 | 0 | 0 | 33.67 / 6035 | 28.45 | 454 / 925 / 991 (poll:1000) | +| 20 | ×1 | node:sqlite | 324 | 0.16 | 0.71 | 1.33 | 2.00 | 0 | 0 | 73.96 / 7562 | 71.88 | 553 / 982 / 1013 (poll:1000) | +| 20 | ×1 | better-sqlite3 | 314 | 0.19 | 0.82 | 1.53 | 2.20 | 0 | 0 | 96.47 / 9084 | 87.91 | 497 / 944 / 985 (poll:1000) | +| 20 | ×1 | один писатель (Bun) | 305 | 1.34 | 2.38 | 4.16 | 7.41 | 0 | 0 | 31.33 / 6050 | 25.39 | 1.11 / 2.94 / 5.29 (push) | +| 20 | ×1 | Postgres (Node) | 306 | 8.06 | 17.16 | 29.14 | 36.39 | 0 | 0 | 121 / 7621 | 85.12 | 11.42 / 20.32 / 32.03 (pg) | +| 20 | ×10 | bun:sqlite | 1510 | 0.20 | 0.46 | 1.75 | 6.17 | 0 | 0 | 23.34 / 6035 | 19.45 | 503 / 945 / 991 (poll:1000) | +| 20 | ×10 | node:sqlite | 1424 | 0.13 | 0.24 | 1.32 | 2.29 | 0 | 0 | 70.15 / 6074 | 68.68 | 480 / 941 / 993 (poll:1000) | +| 20 | ×10 | better-sqlite3 | 1471 | 0.16 | 0.27 | 1.17 | 7.86 | 0 | 0 | 75.04 / 6085 | 68.83 | 509 / 946 / 993 (poll:1000) | +| 20 | ×10 | один писатель (Bun) | 1438 | 1.07 | 2.02 | 2.63 | 8.42 | 0 | 0 | 24.81 / 6033 | 19.62 | 0.71 / 1.30 / 2.35 (push) | +| 20 | ×10 | Postgres (Node) | 1345 | 6.98 | 11.89 | 17.85 | 43.83 | 0 | 0 | 102 / 6120 | 67.98 | 9.76 / 15.06 / 17.73 (pg) | +| 20 | ×50 | bun:sqlite | 3172 | 0.15 | 0.35 | 1.83 | 7.48 | 0 | 0 | 18.78 / 6029 | 15.53 | 515 / 949 / 994 (poll:1000) | +| 20 | ×50 | один писатель (Bun) | 3093 | 0.30 | 1.58 | 2.23 | 9.16 | 0 | 0 | 19.89 / 6032 | 15.64 | 0.39 / 0.85 / 1.48 (push) | +| 20 | ×50 | Postgres (Node) | 2910 | 4.58 | 9.19 | 12.13 | 29.31 | 0 | 0 | 96.66 / 6116 | 68.14 | 6.17 / 11.37 / 14.30 (pg) | + +## Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10) + +| способ | доставка боту p50 | p95 | p99 | max | веб p50 | p95 | +|---|---|---|---|---|---|---| +| fswatch | 26.29 | 192 | 300 | 508 | 26.29 | 193 | +| poll:1000 | 503 | 945 | 991 | 1002 | 509 | 947 | +| poll:200 | 100 | 192 | 200 | 204 | 103 | 192 | +| push | 0.80 | 1.42 | 2.48 | 46.85 | 0.83 | 1.47 | +| Postgres LISTEN/NOTIFY (для сравнения) | 9.76 | 15.06 | 17.73 | 28.17 | 9.72 | 14.71 | + +## Самые медленные операции записи (p99, мс) при 20 раннерах ×10 + +| операция | bun:sqlite | node:sqlite | better-sqlite3 | один писатель (Bun) | Postgres (Node) | +|---|---|---|---|---|---| +| bot.answer | 0.50 | 0.49 | 0.14 | 5.32 | 9.32 | +| bot.enqueue | 5.15 | 1.32 | 0.13 | 0.93 | 9.33 | +| bot.heartbeat | 2.93 | 0.15 | 0.71 | 7.01 | 43.83 | +| bot.sent | 0.18 | 0.91 | 0.08 | 1.10 | 10.21 | +| bot.update | 0.45 | 0.48 | 0.52 | 1.56 | 9.55 | +| hook.answered | 6.17 | 2.29 | 7.86 | 4.07 | 30.26 | +| hook.event | 0.64 | 0.30 | 1.47 | 2.47 | 14.20 | +| hook.question | 5.43 | 0.33 | 1.06 | 2.40 | 14.27 | +| mcp.progress | 1.71 | 0.81 | 0.60 | 2.75 | 19.55 | +| wd.heartbeat | 0.15 | 0.07 | 0.06 | 0.92 | 5.60 | +| wd.stalled | 5.48 | 0.66 | 0.20 | 8.42 | 17.87 | + +## Потолок (contention.ts, 10 с, без пауз) + +``` +{"backend":"bun","procs":20,"seconds":10,"txPerSec":33537,"p50":"0.02","p95":"0.08","p99":"4.24","max":"2710.8","busyRetries":0,"errors":0} +{"backend":"bun","procs":40,"seconds":10,"txPerSec":27223,"p50":"0.03","p95":"0.31","p99":"21.96","max":"2930.6","busyRetries":0,"errors":0} +{"backend":"node","procs":20,"seconds":10,"txPerSec":48578,"p50":"0.02","p95":"0.03","p99":"0.05","max":"5405.9","busyRetries":1,"errors":0} +{"backend":"node","procs":40,"seconds":10,"txPerSec":47694,"p50":"0.02","p95":"0.03","p99":"0.06","max":"6413.2","busyRetries":3,"errors":0} +{"backend":"better","procs":20,"seconds":10,"txPerSec":47456,"p50":"0.02","p95":"0.03","p99":"0.05","max":"5359.5","busyRetries":1,"errors":0} +{"backend":"better","procs":40,"seconds":10,"txPerSec":45076,"p50":"0.02","p95":"0.03","p99":"0.06","max":"5937.5","busyRetries":2,"errors":0} +{"backend":"pg","procs":20,"seconds":10,"txPerSec":4890,"p50":"3.88","p95":"6.82","p99":"9.01","max":"97.1","busyRetries":0,"errors":0} +{"backend":"pg","procs":40,"seconds":10,"txPerSec":7555,"p50":"5.47","p95":"6.95","p99":"8.33","max":"210.2","busyRetries":0,"errors":0} +``` diff --git a/bench/sqlite/contention.ts b/bench/sqlite/contention.ts new file mode 100644 index 00000000..9b4129a3 --- /dev/null +++ b/bench/sqlite/contention.ts @@ -0,0 +1,76 @@ +// Ceiling test: P processes write hook-like transactions back to back, no pauses. +// Far beyond Peppa's real load; shows where each backend starts to bend. +// node contention.ts --backend bun --procs 20 --seconds 10 +import { spawn } from "node:child_process"; +import { homedir } from "node:os"; +import { parseArgs } from "node:util"; +import { openDb, openPg, openSqlite, type Backend } from "./lib/db.ts"; +import { pgSchema, seedStmts, sqliteSchema } from "./lib/schema.ts"; + +const { values: a } = parseArgs({ options: { backend: { type: "string", default: "bun" }, procs: { type: "string", default: "20" }, seconds: { type: "string", default: "10" }, worker: { type: "boolean" } } }); +const backend = a.backend as Backend; +const now = () => performance.timeOrigin + performance.now(); + +if (a.worker) { + const db = await openDb(backend); + const sid = Number(process.env.BENCH_SESSION); + const end = Number(process.env.BENCH_END); + const ms: number[] = []; + let busy = 0; + let errors = 0; + while (Date.now() < end) { + const t = now(); + try { + await db.tx([ + ["update sessions set status = 'running', last_activity_at = ? where id = ?", [Date.now(), sid]], + ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'turn_end', ?, ?) returning id", [sid, sid, JSON.stringify({ t0: t }), Date.now()]], + ]); + } catch { + errors++; + } + busy += db.lastBusy; + ms.push(now() - t); + } + await db.close(); + // A file, not stdout: process.exit() can cut a large pipe write short. + (await import("node:fs")).writeFileSync(`${process.env.BENCH_DB}.${sid}.json`, JSON.stringify({ ms, busy, errors })); + process.exit(0); +} + +const procs = Number(a.procs); +const runtime = backend === "pg" || backend === "node" || backend === "better" ? process.execPath : `${homedir()}/.bun/bin/bun`; +const work = `${process.env.BENCH_TMP ?? "/tmp"}/peppa-contention-${process.pid}`; +const env = { ...process.env, BENCH_BACKEND: backend, BENCH_DB: `${work}.db` } as Record<string, string>; +if (backend === "pg") { + if (!/\/peppa_bench(\?|$)/.test(env.BENCH_PG_URL ?? "")) throw new Error("BENCH_PG_URL must point at peppa_bench"); + const db = await openPg(env.BENCH_PG_URL); + await db.all("drop schema public cascade"); + await db.all("create schema public"); + for (const s of pgSchema) await db.all(s); + await db.tx(seedStmts(procs)); + await db.close(); +} else { + const db = await openSqlite("node", env.BENCH_DB); + await db.all("PRAGMA journal_mode = WAL"); + for (const s of sqliteSchema) await db.all(s); + await db.tx(seedStmts(procs)); + await db.close(); +} +const end = Date.now() + 1000 + Number(a.seconds) * 1000; +const results = await Promise.all( + Array.from({ length: procs }, (_, i) => + new Promise<{ ms: number[]; busy: number; errors: number }>((resolve) => { + const p = spawn(runtime, [new URL(import.meta.url).pathname, "--worker", "--backend", backend], { env: { ...env, BENCH_SESSION: String(i + 1), BENCH_END: String(end) }, stdio: ["ignore", "inherit", "inherit"] }); + p.on("exit", async () => { + const fs = await import("node:fs"); + const f = `${env.BENCH_DB}.${i + 1}.json`; + resolve(fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, "utf8")) : { ms: [], busy: 0, errors: 1 }); + fs.rmSync(f, { force: true }); + }); + }), + ), +); +const ms = results.flatMap((r) => r.ms).sort((x, y) => x - y); +const pct = (p: number) => ms[Math.min(ms.length - 1, Math.floor((p / 100) * ms.length))].toFixed(2); +console.log(JSON.stringify({ backend, procs, seconds: Number(a.seconds), txPerSec: Math.round(ms.length / Number(a.seconds)), p50: pct(50), p95: pct(95), p99: pct(99), max: ms.at(-1)!.toFixed(1), busyRetries: results.reduce((s, r) => s + r.busy, 0), errors: results.reduce((s, r) => s + r.errors, 0) })); +for (const s of ["", "-wal", "-shm"]) (await import("node:fs")).rmSync(env.BENCH_DB + s, { force: true }); diff --git a/bench/sqlite/lib/db.ts b/bench/sqlite/lib/db.ts new file mode 100644 index 00000000..b731a46b --- /dev/null +++ b/bench/sqlite/lib/db.ts @@ -0,0 +1,172 @@ +// Uniform async DB access for the benchmark: bun:sqlite, node:sqlite, better-sqlite3, +// Postgres (postgres.js) and a "writer" client that sends writes to one writer process. +// SQL is written in SQLite dialect with `?` params; the Postgres adapter renumbers them. +import { request } from "node:http"; + +export type Stmt = [sql: string, params?: unknown[]]; +export type Row = Record<string, unknown>; + +export interface Db { + all(sql: string, params?: unknown[]): Promise<Row[]>; + /** Runs statements in one write transaction; returns each statement's rows. */ + tx(stmts: Stmt[]): Promise<Row[][]>; + /** SQLITE_BUSY retries made by the last tx (0 for Postgres/writer). */ + lastBusy: number; + close(): Promise<void>; + /** Postgres only: raw client for LISTEN/NOTIFY. */ + pg?: any; +} + +export type Backend = "bun" | "node" | "better" | "pg" | "writer"; + +export const BUSY_TIMEOUT_MS = Number(process.env.BENCH_BUSY_TIMEOUT_MS ?? 5000); + +// busy_timeout must come first: with 20 hook processes opening the file at once, any +// statement before it (even journal_mode) can fail at once with SQLITE_BUSY_RECOVERY. +// journal_mode=WAL is persistent, so it is set once when the file is created (run.ts). +const PRAGMAS = [ + `PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`, + "PRAGMA synchronous = NORMAL", + "PRAGMA foreign_keys = ON", +]; + +function isBusy(e: unknown) { + const s = String((e as any)?.code ?? "") + " " + String((e as any)?.message ?? e); + return /SQLITE_BUSY|database is locked/i.test(s); +} + +/** Wraps a synchronous SQLite driver: BEGIN IMMEDIATE + retry on SQLITE_BUSY. */ +function syncSqlite(exec: (sql: string) => void, all: (sql: string, p: unknown[]) => Row[], close: () => void): Db { + const db: Db = { + lastBusy: 0, + async all(sql, params = []) { + return all(sql, params); + }, + async tx(stmts) { + db.lastBusy = 0; + for (;;) { + try { + exec("BEGIN IMMEDIATE"); + try { + const out = stmts.map(([s, p]) => all(s, p ?? [])); + exec("COMMIT"); + return out; + } catch (e) { + try { exec("ROLLBACK"); } catch {} + throw e; + } + } catch (e) { + // busy_timeout already waited BUSY_TIMEOUT_MS; count it and give up after 3. + if (!isBusy(e) || ++db.lastBusy >= 3) throw e; + } + } + }, + async close() { + close(); + }, + }; + return db; +} + +export async function openSqlite(kind: "bun" | "node" | "better", path: string, readonly = false): Promise<Db> { + if (kind === "bun") { + const { Database } = await import("bun:sqlite" as string); + const d = new Database(path, readonly ? { readonly: true } : { create: true }); + for (const p of PRAGMAS) d.exec(p); + return syncSqlite((s) => d.exec(s), (s, p) => d.query(s).all(...p), () => d.close()); + } + if (kind === "node") { + const { DatabaseSync } = await import("node:sqlite"); + const d = new DatabaseSync(path, { readOnly: readonly }); + for (const p of PRAGMAS) d.exec(p); + const cache = new Map<string, any>(); + const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s)); + return syncSqlite((s) => d.exec(s), (s, p) => prep(s).all(...(p as any[])) as Row[], () => d.close()); + } + const { default: Better } = await import("better-sqlite3"); + const d = new Better(path, { readonly }); + for (const p of PRAGMAS) d.exec(p); + const cache = new Map<string, any>(); + const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s)); + return syncSqlite( + (s) => d.exec(s), + (s, p) => { + const st = prep(s); + return st.reader ? st.all(...p) : (st.run(...p), []); + }, + () => d.close(), + ); +} + +const toPg = (s: string) => { + let i = 0; + return s.replace(/\?/g, () => `$${++i}`); +}; + +export async function openPg(url: string, max = 1): Promise<Db> { + const { default: postgres } = await import("postgres"); + const sql = postgres(url, { max, onnotice: () => {} }); + return { + lastBusy: 0, + pg: sql, + async all(s, p = []) { + return (await sql.unsafe(toPg(s), p as any[])) as unknown as Row[]; + }, + async tx(stmts) { + return (await sql.begin(async (t: any) => { + const out: Row[][] = []; + for (const [s, p] of stmts) out.push(await t.unsafe(toPg(s), p ?? [])); + return out; + })) as Row[][]; + }, + async close() { + await sql.end({ timeout: 1 }); + }, + }; +} + +export async function httpUnix(socketPath: string, path: string, body: unknown): Promise<any> { + // Bun's fetch speaks unix sockets natively and starts much faster than node:http there. + if (typeof (globalThis as any).Bun !== "undefined") { + const r = await fetch(`http://writer${path}`, { method: "POST", body: JSON.stringify(body), unix: socketPath } as RequestInit); + const j = await r.json(); + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j; + } + return new Promise((resolve, reject) => { + const data = JSON.stringify(body); + const req = request( + { socketPath, path, method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data) } }, + (res) => { + let buf = ""; + res.setEncoding("utf8"); + res.on("data", (c) => (buf += c)); + res.on("end", () => { + const j = buf ? JSON.parse(buf) : null; + res.statusCode === 200 ? resolve(j) : reject(new Error(j?.error ?? `HTTP ${res.statusCode}`)); + }); + }, + ); + req.on("error", reject); + req.end(data); + }); +} + +/** Writes go to the writer process over a unix socket; reads go straight to the file (WAL readers never block). */ +export async function openWriterClient(socketPath: string, dbPath: string, readKind: "bun" | "node"): Promise<Db> { + const reader = await openSqlite(readKind, dbPath, true); + return { + lastBusy: 0, + all: (s, p) => reader.all(s, p), + async tx(stmts) { + return (await httpUnix(socketPath, "/tx", { stmts })).rows; + }, + close: () => reader.close(), + }; +} + +export async function openDb(backend: Backend, env = process.env): Promise<Db> { + if (backend === "pg") return openPg(env.BENCH_PG_URL!); + if (backend === "writer") return openWriterClient(env.BENCH_WRITER_SOCK!, env.BENCH_DB!, (env.BENCH_READ_KIND as any) ?? "bun"); + return openSqlite(backend, env.BENCH_DB!); +} diff --git a/bench/sqlite/lib/notify.ts b/bench/sqlite/lib/notify.ts new file mode 100644 index 00000000..13fafb66 --- /dev/null +++ b/bench/sqlite/lib/notify.ts @@ -0,0 +1,49 @@ +// Replacements for Postgres LISTEN/NOTIFY, all measured the same way: the consumer is +// woken up somehow, then reads new events after its cursor from the database. +// pg — LISTEN/NOTIFY (today's Peppa) +// poll:N — select events where id > cursor every N ms +// fswatch — fs.watch on the -wal file (+5 s safety poll) +// push — the writer (or a tiny hub) pushes event ids over a unix socket +import { watch } from "node:fs"; +import { request } from "node:http"; +import type { Db } from "./db.ts"; +import { httpUnix } from "./db.ts"; + +export const CHANNEL = "peppa_events"; + +/** Called by event producers after commit. */ +export async function publish(db: Db, mode: string, eventId: number, env = process.env) { + if (mode === "pg") await db.pg.unsafe(`select pg_notify('${CHANNEL}', $1)`, [JSON.stringify({ type: "progress", eventId })]); + else if (mode === "push" && env.BENCH_BACKEND !== "writer") await httpUnix(env.BENCH_HUB_SOCK!, "/publish", { ids: [eventId] }).catch(() => {}); + // writer backend publishes itself after commit; poll/fswatch need nothing. +} + +/** Subscribes `wake` to new events; returns a stop function. */ +export function subscribe(db: Db, mode: string, wake: () => void, env = process.env): () => void { + if (mode === "pg") { + let l: any; + db.pg.listen(CHANNEL, () => wake()).then((x: any) => (l = x)); + return () => l?.unlisten(); + } + if (mode.startsWith("poll:")) { + const t = setInterval(wake, Number(mode.slice(5))); + return () => clearInterval(t); + } + if (mode === "fswatch") { + const w = watch(env.BENCH_DB! + "-wal", () => wake()); + const t = setInterval(wake, 5000); + return () => (w.close(), clearInterval(t)); + } + if (mode === "push") { + const sock = env.BENCH_BACKEND === "writer" ? env.BENCH_WRITER_SOCK! : env.BENCH_HUB_SOCK!; + const req = request({ socketPath: sock, path: "/subscribe", method: "GET" }, (res) => { + res.setEncoding("utf8"); + res.on("data", () => wake()); + }); + req.on("error", () => {}); + req.end(); + const t = setInterval(wake, 5000); + return () => (req.destroy(), clearInterval(t)); + } + throw new Error(`unknown notify mode ${mode}`); +} diff --git a/bench/sqlite/lib/schema.ts b/bench/sqlite/lib/schema.ts new file mode 100644 index 00000000..a75dcac2 --- /dev/null +++ b/bench/sqlite/lib/schema.ts @@ -0,0 +1,34 @@ +// The hot part of Peppa's schema (packages/db/src/schema.ts), in both dialects. +// Timestamps are epoch milliseconds passed as params so the same SQL runs on both. + +const tables = (pg: boolean) => { + const id = pg ? "serial primary key" : "integer primary key autoincrement"; + const json = pg ? "jsonb" : "text"; + const ts = pg ? "bigint" : "integer"; + return [ + `create table projects (id ${id}, key text not null unique, name text not null, next_task_number integer not null default 1, updated_at ${ts})`, + `create table tasks (id ${id}, project_id integer not null references projects(id) on delete cascade, number integer not null, title text not null, status text not null default 'backlog', updated_at ${ts}, unique(project_id, number))`, + `create table sessions (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete set null, tmux_name text not null unique, generation integer not null default 0, auto_nudges integer not null default 0, status text not null default 'starting', last_activity_at ${ts}, started_at ${ts})`, + `create table questions (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete cascade, session_id integer references sessions(id) on delete set null, kind text not null, text text not null, options ${json}, answer text, answered_via text, telegram_message_id integer, awaiting_hook boolean not null default false, created_at ${ts}, answered_at ${ts})`, + `create table events (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete cascade, session_id integer references sessions(id) on delete set null, type text not null, payload ${json}, created_at ${ts})`, + `create index events_task on events(task_id, id)`, + `create table settings (key text primary key, value ${json} not null, updated_at ${ts})`, + `create table telegram_outbox (id ${id}, dedupe_key text not null unique, method text not null, params ${json} not null, question_id integer references questions(id) on delete set null, status text not null default 'pending', attempts integer not null default 0, next_attempt_at ${ts} not null, telegram_message_id integer, created_at ${ts}, sent_at ${ts})`, + `create index outbox_pending on telegram_outbox(status, next_attempt_at)`, + `create table telegram_updates (update_id integer primary key, status text not null, created_at ${ts})`, + ]; +}; + +export const sqliteSchema = tables(false); +export const pgSchema = tables(true); + +/** One project, `runners` tasks in progress, one live session per task. */ +export function seedStmts(runners: number): [string, unknown[]][] { + const now = Date.now(); + const out: [string, unknown[]][] = [["insert into projects (key, name, next_task_number, updated_at) values ('PEP', 'Peppa', ?, ?)", [runners + 1, now]]]; + for (let i = 1; i <= runners; i++) { + out.push(["insert into tasks (project_id, number, title, status, updated_at) values (1, ?, ?, 'in_progress', ?)", [i, `Task ${i}`, now]]); + out.push(["insert into sessions (project_id, task_id, tmux_name, generation, status, last_activity_at, started_at) values (1, ?, ?, 1, 'running', ?, ?)", [i, `peppa-PEP-${i}-s${i}`, now, now]]); + } + return out; +} diff --git a/bench/sqlite/matrix.sh b/bench/sqlite/matrix.sh new file mode 100755 index 00000000..efad8770 --- /dev/null +++ b/bench/sqlite/matrix.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Full PEP-36 matrix. BENCH_PG_URL must point at the throwaway peppa_bench database. +# BENCH_PG_URL=postgres://…/peppa_bench ./matrix.sh [smoke] +set -u +cd "$(dirname "$0")" +DUR1=${DUR1:-90}; DUR10=${DUR10:-60} +run() { node run.ts "$@" 2>&1 | grep -vE "^\[bench\]"; } +if [ "${1:-}" = smoke ]; then + for b in "--backend bun --notify push" "--backend writer --notify push" "--backend node --notify fswatch" "--backend pg"; do + run $b --runners 3 --load 5 --duration 12 --name smoke | grep -E "==|write ALL|deliver|rror" + done + exit +fi +# 1. Write contention: every backend at 10/20 runners, real load (x1) and x10. +for r in 10 20; do + for x in 1 10; do + d=$([ $x = 1 ] && echo $DUR1 || echo $DUR10) + run --backend bun --runners $r --load $x --duration $d --notify poll:1000 + run --backend node --runners $r --load $x --duration $d --notify poll:1000 + run --backend better --runners $r --load $x --duration $d --notify poll:1000 + run --backend writer --runners $r --load $x --duration $d --notify push + run --backend pg --runners $r --load $x --duration $d --notify pg + done +done +# 2. LISTEN/NOTIFY replacements on bun:sqlite, 20 runners x10. +for n in poll:200 poll:1000 fswatch push; do + run --backend bun --runners 20 --load 10 --duration $DUR10 --notify $n +done +# 3. Saturation: 20 runners at x50 (≈ 100 hook processes/s) — where does each one bend? +for b in "--backend bun --notify poll:1000" "--backend writer --notify push" "--backend pg --notify pg"; do + run $b --runners 20 --load 50 --duration 45 +done diff --git a/bench/sqlite/package.json b/bench/sqlite/package.json new file mode 100644 index 00000000..dd910a75 --- /dev/null +++ b/bench/sqlite/package.json @@ -0,0 +1,15 @@ +{ + "name": "peppa-bench-sqlite", + "private": true, + "type": "module", + "description": "PEP-36: SQLite vs Postgres write/notify benchmark under Peppa-like load. Not part of the product.", + "dependencies": { + "better-sqlite3": "13.1.1", + "postgres": "4.1.1" + }, + "pnpm": { + "onlyBuiltDependencies": [ + "better-sqlite3" + ] + } +} diff --git a/bench/sqlite/pnpm-lock.yaml b/bench/sqlite/pnpm-lock.yaml new file mode 100644 index 00000000..b12da76e --- /dev/null +++ b/bench/sqlite/pnpm-lock.yaml @@ -0,0 +1,40 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + better-sqlite3: + specifier: 13.1.1 + version: 13.1.1 + postgres: + specifier: 4.1.1 + version: 4.1.1 + +packages: + + better-sqlite3@13.1.1: + resolution: {integrity: sha512-JjyLCATp+VLxZVFyWkicyzKYwpEFLCrV4MmshW97xv3JXdhw5jBDcsbEWRGm2L/96E+k7rtjON8q9nml05h3Pw==} + engines: {node: '>=22'} + + node-addon-api@8.9.2: + resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==} + engines: {node: ^18 || ^20 || >= 21} + + postgres@4.1.1: + resolution: {integrity: sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug==} + engines: {node: '>=18'} + +snapshots: + + better-sqlite3@13.1.1: + dependencies: + node-addon-api: 8.9.2 + + node-addon-api@8.9.2: {} + + postgres@4.1.1: {} diff --git a/bench/sqlite/report.ts b/bench/sqlite/report.ts new file mode 100644 index 00000000..8328b37f --- /dev/null +++ b/bench/sqlite/report.ts @@ -0,0 +1,48 @@ +// Markdown tables from results/*/summary.json: `node report.ts > results/report.md`. +import { readdirSync, readFileSync, existsSync } from "node:fs"; + +const dir = new URL("results/", import.meta.url).pathname; +const runs = readdirSync(dir) + .filter((d) => existsSync(`${dir}${d}/summary.json`)) + .map((d) => JSON.parse(readFileSync(`${dir}${d}/summary.json`, "utf8"))); + +const order = ["bun", "node", "better", "writer", "pg"]; +const label: Record<string, string> = { bun: "bun:sqlite", node: "node:sqlite", better: "better-sqlite3", writer: "один писатель (Bun)", pg: "Postgres (Node)" }; +const f = (v: number) => (Number.isFinite(v) ? (v >= 100 ? v.toFixed(0) : v.toFixed(2)) : "—"); +const row = (r: any, k: string) => r.rows[k] ?? { n: 0, p50: NaN, p95: NaN, p99: NaN, max: NaN, busy: 0, errors: 0 }; + +console.log("## Записи и доставка\n"); +console.log("| раннеры | нагрузка | вариант | записей | p50 мс | p95 | p99 | max | BUSY-повторы | ошибки | хук целиком p50/p95 | старт хука p50 | доставка боту p50/p95/p99 |"); +console.log("|---|---|---|---|---|---|---|---|---|---|---|---|---|"); +for (const r of runs.filter((r) => r.notify === "pg" || r.notify === "poll:1000" || (r.backend === "writer" && r.notify === "push")).sort((a, b) => a.runners - b.runners || a.load - b.load || order.indexOf(a.backend) - order.indexOf(b.backend))) { + if (r.backend === "bun" && r.notify !== "poll:1000") continue; + const w = { ...row(r, "write ALL") }; + // Runs before the fix counted hooks killed by the end-of-run SIGTERM as crashes. + if (r.errors.every((e: string) => e === "hook exited with null")) w.errors -= row(r, "write hook.crashed").errors; + const h = row(r, "total hook"); + const s = row(r, "startup hook"); + const d = row(r, "deliver bot"); + console.log(`| ${r.runners} | ×${r.load} | ${label[r.backend]} | ${w.n} | ${f(w.p50)} | ${f(w.p95)} | ${f(w.p99)} | ${f(w.max)} | ${w.busy} | ${w.errors} | ${f(h.p50)} / ${f(h.p95)} | ${f(s.p50)} | ${f(d.p50)} / ${f(d.p95)} / ${f(d.p99)} (${r.notify}) |`); +} + +console.log("\n## Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10)\n"); +console.log("| способ | доставка боту p50 | p95 | p99 | max | веб p50 | p95 |"); +console.log("|---|---|---|---|---|---|---|"); +for (const r of runs.filter((r) => r.backend === "bun" && r.runners === 20 && r.load === 10)) { + const b = row(r, "deliver bot"); + const w = row(r, "deliver web"); + console.log(`| ${r.notify} | ${f(b.p50)} | ${f(b.p95)} | ${f(b.p99)} | ${f(b.max)} | ${f(w.p50)} | ${f(w.p95)} |`); +} +const pg = runs.find((r) => r.backend === "pg" && r.runners === 20 && r.load === 10); +if (pg) { + const b = row(pg, "deliver bot"); + console.log(`| Postgres LISTEN/NOTIFY (для сравнения) | ${f(b.p50)} | ${f(b.p95)} | ${f(b.p99)} | ${f(b.max)} | ${f(row(pg, "deliver web").p50)} | ${f(row(pg, "deliver web").p95)} |`); +} + +console.log("\n## Самые медленные операции записи (p99, мс) при 20 раннерах ×10\n"); +console.log("| операция | " + order.map((b) => label[b]).join(" | ") + " |"); +console.log("|---|" + order.map(() => "---|").join("")); +const at = (b: string) => runs.find((r) => r.backend === b && r.runners === 20 && r.load === 10 && (b !== "bun" || r.notify === "poll:1000")); +const ops = new Set<string>(); +for (const b of order) for (const k of Object.keys(at(b)?.rows ?? {})) if (k.startsWith("write ") && k !== "write ALL" && k !== "write hook.crashed") ops.add(k); +for (const k of [...ops].sort()) console.log(`| ${k.slice(6)} | ` + order.map((b) => f(at(b)?.rows[k]?.p99 ?? NaN)).join(" | ") + " |"); diff --git a/bench/sqlite/roles.ts b/bench/sqlite/roles.ts new file mode 100644 index 00000000..18dc0d67 --- /dev/null +++ b/bench/sqlite/roles.ts @@ -0,0 +1,336 @@ +// One process of the simulated Peppa: `<runtime> roles.ts <role>`; run.ts starts them. +// Load per runner is taken from the live peppa DB (see README.md): a hook every ~10 s +// (a new process each time, like Claude's command hooks), 10 % of them a blocking +// question polled every 1.5 s, MCP progress every ~30 s and get_task every ~15 s. +// BENCH_LOAD multiplies these rates for the stress runs. +import { spawn } from "node:child_process"; +import { appendFileSync, rmSync } from "node:fs"; +import { createServer, type ServerResponse } from "node:http"; +import { openDb, openSqlite, type Backend, type Db, type Row } from "./lib/db.ts"; +import { publish, subscribe } from "./lib/notify.ts"; + +const env = process.env; +const role = process.argv[2]; +const backend = env.BENCH_BACKEND as Backend; +const mode = env.BENCH_NOTIFY ?? "poll:1000"; +const load = Number(env.BENCH_LOAD ?? 1); +const now = () => performance.timeOrigin + performance.now(); +// Sleeps end early on SIGTERM so every process stops right after the run. +const wakers = new Set<() => void>(); +const sleep = (ms: number) => + new Promise<void>((r) => { + const done = () => (clearTimeout(t), wakers.delete(done), r()); + const t = setTimeout(done, ms); + wakers.add(done); + }); +const expo = (mean: number) => -Math.log(1 - Math.random()) * mean; + +const samples: unknown[] = []; +const rec = (kind: string, op: string, ms: number, extra: object = {}) => samples.push({ kind, op, ms: +ms.toFixed(3), ...extra }); +function flush() { + if (samples.length) appendFileSync(`${env.BENCH_OUT}/${role}-${process.pid}.jsonl`, samples.map((s) => JSON.stringify(s)).join("\n") + "\n"); + samples.length = 0; +} + +let stopping = false; +const stops: (() => void)[] = []; +process.on("SIGTERM", () => { + stopping = true; + stops.forEach((f) => f()); + wakers.forEach((f) => f()); +}); + +/** A write transaction with latency, busy retries and errors recorded. */ +async function write(db: Db, op: string, stmts: [string, unknown[]][]): Promise<Row[][] | null> { + const t = now(); + try { + const r = await db.tx(stmts); + rec("write", op, now() - t, db.lastBusy ? { busy: db.lastBusy } : {}); + return r; + } catch (e) { + rec("write", op, now() - t, { busy: db.lastBusy, error: String((e as Error).message).slice(0, 80) }); + return null; + } +} +async function read(db: Db, op: string, sql: string, params: unknown[] = []) { + const t = now(); + const r = await db.all(sql, params); + rec("read", op, now() - t); + return r; +} + +/** Reads events after the cursor whenever woken; records event→consumer latency. */ +function consume(db: Db, who: string) { + let cursor = 0; + let busy = false; + let again = false; + const check = async () => { + if (busy) return void (again = true); + busy = true; + try { + do { + again = false; + const rows = await db.all("select id, payload from events where id > ? order by id limit 500", [cursor]); + for (const r of rows) { + cursor = Number(r.id); + const p = typeof r.payload === "string" ? JSON.parse(r.payload) : r.payload; + if (p?.t0) rec("deliver", who, now() - p.t0); + } + } while (again); + } finally { + busy = false; + } + }; + db.all("select coalesce(max(id), 0) m from events").then((r) => (cursor = Number(r[0].m))); + stops.push(subscribe(db, mode, () => void check().catch(() => {}))); +} + +async function hook() { + const t0 = Number(env.BENCH_SPAWN_T); + rec("startup", "hook", now() - t0); + process.on("exit", flush); + const sid = Number(env.BENCH_SESSION); + const tOpen = now(); + const db = await openDb(backend); + rec("open", "hook", now() - tOpen); + const [s] = await read(db, "hook.session", "select id, task_id, generation from sessions where id = ?", [sid]); + const ts = Date.now(); + if (Math.random() < 0.1) { + const r = await write(db, "hook.question", [ + ["insert into questions (project_id, task_id, session_id, kind, text, options, awaiting_hook, created_at) values (1, ?, ?, 'permission', 'Allow Bash(rm -rf build)', ?, true, ?) returning id", [s.task_id, sid, JSON.stringify(["Да", "Нет"]), ts]], + ["update sessions set status = 'waiting_input', last_activity_at = ? where id = ?", [ts, sid]], + ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'question', ?, ?) returning id", [s.task_id, sid, JSON.stringify({ t0: now() }), ts]], + ]); + if (r) { + await publish(db, mode, Number(r[2][0].id)); + const qid = Number(r[0][0].id); + const tAsk = now(); + // Blocking PermissionRequest hook: poll for the PM's answer (hook.ts, every 1.5 s). + for (let i = 0; i < 40 && !stopping; i++) { + const [q] = await read(db, "hook.poll", "select answer from questions where id = ?", [qid]); + if (q?.answer) break; + await sleep(1500); + } + rec("roundtrip", "question", now() - tAsk); + await write(db, "hook.answered", [ + ["update questions set awaiting_hook = false where id = ?", [qid]], + ["update sessions set status = 'running', auto_nudges = 0, last_activity_at = ? where id = ?", [Date.now(), sid]], + ]); + } + } else { + const r = await write(db, "hook.event", [ + ["update sessions set status = 'running', last_activity_at = ? where id = ? and generation = ?", [ts, sid, s.generation]], + ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'turn_end', ?, ?) returning id", [s.task_id, sid, JSON.stringify({ t0: now(), hook: "Stop" }), ts]], + ]); + if (r) await publish(db, mode, Number(r[1][0].id)); + } + await db.close(); + rec("total", "hook", now() - t0); + flush(); +} + +/** Plays Claude for one session: fires hooks one after another, each a new process. */ +async function runner() { + const sid = env.BENCH_SESSION!; + while (!stopping) { + await sleep(expo(10_000 / load)); + if (stopping) break; + const child = spawn(process.execPath, [new URL(import.meta.url).pathname, "hook"], { + env: { ...env, BENCH_SPAWN_T: String(now()), BENCH_SESSION: sid }, + stdio: ["ignore", "ignore", "inherit"], + }); + const kill = () => child.kill("SIGTERM"); + stops.push(kill); + const code = await new Promise((r) => child.on("exit", r)); + stops.splice(stops.indexOf(kill), 1); + // A hook killed by our own SIGTERM at the end of the run is not a failure. + if (code !== 0 && !(code === null && stopping)) rec("write", "hook.crashed", 0, { error: `hook exited with ${code}` }); + } + flush(); +} + +async function mcp() { + const sid = Number(env.BENCH_SESSION); + const db = await openDb(backend); + const progress = async () => { + while (!stopping) { + await sleep(expo(30_000 / load)); + if (stopping) break; + const ts = Date.now(); + const r = await write(db, "mcp.progress", [ + ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'progress', ?, ?) returning id", [sid, sid, JSON.stringify({ t0: now(), text: "Сделал шаг 3 из 7" }), ts]], + ["update tasks set updated_at = ? where id = ?", [ts, sid]], + ]); + if (r) await publish(db, mode, Number(r[0][0].id)); + } + }; + const getTask = async () => { + while (!stopping) { + await sleep(expo(15_000 / load)); + if (stopping) break; + await read(db, "mcp.get_task", "select * from tasks where id = ?", [sid]); + await read(db, "mcp.get_task", "select * from events where task_id = ? order by id desc limit 20", [sid]); + } + }; + await Promise.all([progress(), getTask()]); + await db.close(); + flush(); +} + +/** Telegram bot: outbox loop (1 s), reconcile (10 s + on events), heartbeat, PM answers. */ +async function bot() { + const db = await openDb(backend); + consume(db, "bot"); + let updateId = 1; + const answering = new Set<number>(); + const reconcile = async () => { + const qs = await read(db, "bot.reconcile", "select id from questions where answer is null and telegram_message_id is null"); + for (const q of qs) { + const id = Number(q.id); + await write(db, "bot.enqueue", [ + ["insert into telegram_outbox (dedupe_key, method, params, question_id, next_attempt_at, created_at) values (?, 'sendMessage', ?, ?, ?, ?) on conflict (dedupe_key) do nothing", [`q:${id}`, JSON.stringify({ chat_id: 1, text: "?" }), id, Date.now(), Date.now()]], + ]); + if (answering.has(id)) continue; + answering.add(id); + // The PM taps a button 2–8 s later: record the update first, then answer (bot.ts). + setTimeout(async () => { + const u = updateId++; + await write(db, "bot.update", [["insert into telegram_updates (update_id, status, created_at) values (?, 'dispatching', ?)", [u, Date.now()]]]); + const r = await write(db, "bot.answer", [ + ["update questions set answer = 'Да', answered_via = 'telegram', answered_at = ? where id = ? and answer is null", [Date.now(), id]], + ["update telegram_updates set status = 'done' where update_id = ?", [u]], + ["insert into events (project_id, type, payload, created_at) values (1, 'question_answered', ?, ?) returning id", [JSON.stringify({ t0: now() }), Date.now()]], + ]); + if (r) await publish(db, mode, Number(r[2][0].id)); + }, 2000 + Math.random() * 6000); + } + }; + const loops = [ + (async () => { + while (!stopping) { + const rows = await read(db, "bot.outbox", "select id, question_id from telegram_outbox where status = 'pending' and next_attempt_at <= ? order by id limit 20", [Date.now()]); + for (const o of rows) + await write(db, "bot.sent", [ + ["update telegram_outbox set status = 'sent', attempts = attempts + 1, telegram_message_id = ?, sent_at = ? where id = ?", [Number(o.id) + 1000, Date.now(), o.id]], + ["update questions set telegram_message_id = ? where id = ?", [Number(o.id) + 1000, o.question_id]], + ]); + await sleep(1000); + } + })(), + (async () => { + while (!stopping) { + await reconcile(); + await sleep(2000); + } + })(), + (async () => { + while (!stopping) { + await write(db, "bot.heartbeat", [["insert into settings (key, value, updated_at) values ('heartbeat:bot', ?, ?) on conflict (key) do update set value = excluded.value, updated_at = excluded.updated_at", [JSON.stringify({ at: Date.now() }), Date.now()]]]); + await sleep(30_000); + } + })(), + ]; + await new Promise<void>((r) => stops.push(r)); + await Promise.race([Promise.all(loops), sleep(3000)]); + flush(); + await db.close(); +} + +/** Web: 3 open boards refreshing every 5 s + a live-update consumer. */ +async function web() { + const db = await openDb(backend); + consume(db, "web"); + const viewer = async () => { + await sleep(Math.random() * 5000); + while (!stopping) { + const t = now(); + await db.all("select id, number, title, status, updated_at from tasks where project_id = 1 order by number"); + await db.all("select id, task_id, status, last_activity_at from sessions where status in ('starting','running','waiting_input','idle','stalled','rate_limited')"); + await db.all("select count(*) c from questions where answer is null"); + await db.all("select id, type, created_at from events where project_id = 1 order by id desc limit 30"); + rec("read", "web.board", now() - t); + await sleep(5000); + } + }; + await Promise.all([viewer(), viewer(), viewer()]); + flush(); + await db.close(); +} + +/** Watchdog tick every 30 s: list sessions, touch some, heartbeat. */ +async function watchdog() { + const db = await openDb(backend); + while (!stopping) { + const ss = await read(db, "wd.sessions", "select id, task_id, status, last_activity_at from sessions where status not in ('done','failed')"); + for (const s of ss) { + if (Math.random() >= 0.1) continue; + const r = await write(db, "wd.stalled", [ + ["update sessions set status = 'stalled' where id = ? and status = 'running'", [s.id]], + ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'stalled', ?, ?) returning id", [s.task_id, s.id, JSON.stringify({ t0: now() }), Date.now()]], + ]); + if (r) await publish(db, mode, Number(r[1][0].id)); + } + await write(db, "wd.heartbeat", [["insert into settings (key, value, updated_at) values ('heartbeat:watchdog', ?, ?) on conflict (key) do update set value = excluded.value, updated_at = excluded.updated_at", [JSON.stringify({ at: Date.now() }), Date.now()]]]); + for (let i = 0; i < 30 && !stopping; i++) await sleep(1000); + } + flush(); + await db.close(); +} + +/** + * The only process that opens the SQLite file for writing (backend=writer), or just a + * notify hub (notify=push with direct SQLite). Pushes new event ids to /subscribe. + */ +async function writer() { + const sock = env.BENCH_SOCK!; + rmSync(sock, { force: true }); + const db = env.BENCH_HUB_ONLY ? null : await openSqlite((env.BENCH_WRITER_KIND as any) ?? "bun", env.BENCH_DB!); + const subs = new Set<ServerResponse>(); + const push = (ids: unknown[]) => { + const line = JSON.stringify(ids) + "\n"; + for (const s of subs) s.write(line); + }; + const server = createServer((req, res) => { + if (req.url === "/subscribe") { + res.writeHead(200, { "content-type": "text/plain" }); + res.flushHeaders(); + subs.add(res); + req.on("close", () => subs.delete(res)); + return; + } + let body = ""; + req.setEncoding("utf8"); + req.on("data", (c) => (body += c)); + req.on("end", async () => { + const j = JSON.parse(body); + try { + if (req.url === "/publish") { + push(j.ids); + return void res.end("null"); + } + const rows = await db!.tx(j.stmts); + const ids = j.stmts.flatMap(([s]: [string], i: number) => (s.startsWith("insert into events") ? rows[i].map((r) => r.id) : [])); + res.end(JSON.stringify({ rows })); + if (ids.length) push(ids); + } catch (e) { + res.statusCode = 500; + res.end(JSON.stringify({ error: (e as Error).message })); + } + }); + }); + server.listen(sock); + await new Promise<void>((r) => stops.push(r)); + server.close(); + for (const s of subs) s.end(); + await db?.close(); +} + +const roles: Record<string, () => Promise<void>> = { hook, runner, mcp, bot, web, watchdog, writer }; +roles[role]().then( + () => process.exit(0), + (e) => { + console.error(`[${role}]`, e); + flush(); + process.exit(1); + }, +); diff --git a/bench/sqlite/run.ts b/bench/sqlite/run.ts new file mode 100644 index 00000000..b63360ad --- /dev/null +++ b/bench/sqlite/run.ts @@ -0,0 +1,128 @@ +// Orchestrator: fresh database, then N runners (+ their hook processes) and N MCP +// servers, bot, web, watchdog (and the writer/hub when needed) for --duration seconds. +// node run.ts --backend bun --runtime bun --runners 10 --load 1 --duration 90 --notify poll:1000 +// Prints and saves (results/<name>/summary.json) latency percentiles per operation. +import { spawn, type ChildProcess } from "node:child_process"; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { parseArgs } from "node:util"; +import { openPg, openSqlite } from "./lib/db.ts"; +import { pgSchema, seedStmts, sqliteSchema } from "./lib/schema.ts"; + +const here = new URL(".", import.meta.url).pathname; +const { values: a } = parseArgs({ + options: { + backend: { type: "string", default: "bun" }, + runtime: { type: "string" }, + runners: { type: "string", default: "10" }, + load: { type: "string", default: "1" }, + duration: { type: "string", default: "90" }, + notify: { type: "string" }, + name: { type: "string" }, + }, +}); +const backend = a.backend!; +const runtime = a.runtime ?? (backend === "node" || backend === "better" || backend === "pg" ? "node" : "bun"); +const notify = a.notify ?? (backend === "pg" ? "pg" : "poll:1000"); +const runners = Number(a.runners); +const name = a.name ?? `${backend}-${runtime}-r${runners}-x${a.load}-${notify.replace(":", "")}`; +const bin = runtime === "bun" ? `${homedir()}/.bun/bin/bun` : process.execPath; + +const work = `${process.env.BENCH_TMP ?? "/tmp"}/peppa-bench-${process.pid}`; +const out = `${here}results/${name}`; +rmSync(out, { recursive: true, force: true }); +mkdirSync(out, { recursive: true }); +mkdirSync(work, { recursive: true }); +const sockDir = `/tmp/pb-${process.pid}`; +mkdirSync(sockDir, { recursive: true }); + +const env: Record<string, string> = { + ...(process.env as Record<string, string>), + BENCH_BACKEND: backend, + BENCH_NOTIFY: notify, + BENCH_LOAD: a.load!, + BENCH_OUT: out, + BENCH_DB: `${work}/peppa.db`, + // macOS caps unix socket paths at 104 bytes, so sockets live in a short /tmp dir. + BENCH_WRITER_SOCK: `${sockDir}/writer.sock`, + BENCH_HUB_SOCK: `${sockDir}/hub.sock`, + BENCH_READ_KIND: runtime === "bun" ? "bun" : "node", + BENCH_WRITER_KIND: runtime === "bun" ? "bun" : "node", +}; + +// Fresh database with the seed. +if (backend === "pg") { + if (!env.BENCH_PG_URL) throw new Error("BENCH_PG_URL (…/peppa_bench) is required"); + if (!/\/peppa_bench(\?|$)/.test(env.BENCH_PG_URL)) throw new Error("refusing to use a database other than peppa_bench"); + const db = await openPg(env.BENCH_PG_URL); + await db.all("drop schema public cascade"); + await db.all("create schema public"); + for (const s of pgSchema) await db.all(s); + await db.tx(seedStmts(runners)); + await db.close(); +} else { + const db = await openSqlite("node", env.BENCH_DB); + await db.all("PRAGMA journal_mode = WAL"); + for (const s of sqliteSchema) await db.all(s); + await db.tx(seedStmts(runners)); + await db.close(); +} + +const procs: ChildProcess[] = []; +const start = (role: string, extra: Record<string, string> = {}) => { + const p = spawn(bin, [`${here}roles.ts`, role], { env: { ...env, ...extra }, stdio: ["ignore", "inherit", "inherit"] }); + procs.push(p); + return p; +}; +const waitSock = async (s: string) => { + for (let i = 0; i < 100 && !existsSync(s); i++) await new Promise((r) => setTimeout(r, 50)); +}; + +const servers: ChildProcess[] = []; +if (backend === "writer") { + servers.push(start("writer", { BENCH_SOCK: env.BENCH_WRITER_SOCK })); + await waitSock(env.BENCH_WRITER_SOCK); +} else if (notify === "push") { + servers.push(start("writer", { BENCH_SOCK: env.BENCH_HUB_SOCK, BENCH_HUB_ONLY: "1" })); + await waitSock(env.BENCH_HUB_SOCK); +} +procs.length = 0; +const clients = [start("bot"), start("web"), start("watchdog")]; +for (let i = 1; i <= runners; i++) clients.push(start("mcp", { BENCH_SESSION: String(i) }), start("runner", { BENCH_SESSION: String(i) })); + +console.error(`[bench] ${name}: ${clients.length} processes for ${a.duration}s`); +await new Promise((r) => setTimeout(r, Number(a.duration) * 1000)); +const exited = (ps: ChildProcess[]) => Promise.all(ps.map((p) => (p.exitCode !== null ? null : new Promise((r) => p.on("exit", r))))); +for (const p of clients) p.kill("SIGTERM"); +await Promise.race([exited(clients), new Promise((r) => setTimeout(r, 90_000).unref())]); +for (const p of servers) p.kill("SIGTERM"); +await exited(servers); + +// Aggregate. +type S = { kind: string; op: string; ms: number; busy?: number; error?: string }; +const all: S[] = readdirSync(out) + .filter((f) => f.endsWith(".jsonl")) + .flatMap((f) => readFileSync(`${out}/${f}`, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l))); +const pct = (xs: number[], p: number) => (xs.length ? xs[Math.min(xs.length - 1, Math.floor((p / 100) * xs.length))] : NaN); +const summarize = (xs: S[]) => { + const ms = xs.map((x) => x.ms).sort((x, y) => x - y); + const r = (v: number) => +v.toFixed(2); + return { n: ms.length, p50: r(pct(ms, 50)), p95: r(pct(ms, 95)), p99: r(pct(ms, 99)), max: r(ms.at(-1) ?? NaN), busy: xs.reduce((s, x) => s + (x.busy ?? 0), 0), errors: xs.filter((x) => x.error).length }; +}; +const groups = new Map<string, S[]>(); +for (const s of all) { + const k = `${s.kind} ${s.op}`; + groups.set(k, [...(groups.get(k) ?? []), s]); +} +const rows: Record<string, ReturnType<typeof summarize>> = {}; +rows["write ALL"] = summarize(all.filter((s) => s.kind === "write")); +for (const k of [...groups.keys()].sort()) rows[k] = summarize(groups.get(k)!); +const errors = [...new Set(all.filter((s) => s.error).map((s) => s.error))]; +const summary = { name, backend, runtime, notify, runners, load: Number(a.load), duration: Number(a.duration), rows, errors, at: new Date().toISOString() }; +writeFileSync(`${out}/summary.json`, JSON.stringify(summary, null, 2)); +for (const f of readdirSync(out)) if (f.endsWith(".jsonl")) rmSync(`${out}/${f}`); +console.log(`\n== ${name}`); +console.table(rows); +if (errors.length) console.log("errors:", errors); +rmSync(work, { recursive: true, force: true }); +rmSync(sockDir, { recursive: true, force: true }); diff --git a/bench/sqlite/schema-port/copy-from-pg.ts b/bench/sqlite/schema-port/copy-from-pg.ts new file mode 100644 index 00000000..60bf8a77 --- /dev/null +++ b/bench/sqlite/schema-port/copy-from-pg.ts @@ -0,0 +1,53 @@ +// PEP-36 prototype: copy a Peppa Postgres database into a fresh SQLite file using the +// ported schema, then read it back through drizzle and compare row counts. +// bun copy-from-pg.ts <postgres-url> <out.db> +// The Postgres session is read-only (default_transaction_read_only), so pointing it at +// the live database cannot change anything there. +import { Database } from "bun:sqlite"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import postgres from "postgres"; +import * as schema from "./schema.ts"; + +const [url, out] = process.argv.slice(2); +if (!url || !out) throw new Error("usage: bun copy-from-pg.ts <postgres-url> <out.db>"); + +const pg = postgres(url, { max: 1, connection: { default_transaction_read_only: "on" } as any }); +const file = new Database(out, { create: true }); +file.exec("PRAGMA busy_timeout = 5000"); +file.exec("PRAGMA journal_mode = WAL"); +const db = drizzle(file, { schema }); +migrate(db, { migrationsFolder: new URL("migrations", import.meta.url).pathname }); + +// Parents before children (foreign keys are enforced). +const order = [ + "users", "projects", "project_members", "project_invites", "goals", "tasks", "sessions", "questions", "events", + "settings", "telegram_outbox", "telegram_updates", "oauth_clients", "oauth_codes", "oauth_tokens", + "incident_settings", "error_sources", "incidents", +]; +const toSqlite = (v: unknown) => + v instanceof Date ? v.getTime() : typeof v === "boolean" ? (v ? 1 : 0) : v !== null && typeof v === "object" ? JSON.stringify(v) : typeof v === "bigint" ? Number(v) : v; + +file.exec("PRAGMA foreign_keys = ON"); +const t0 = performance.now(); +const counts: Record<string, [number, number]> = {}; +for (const t of order) { + const rows = await pg.unsafe(`select * from ${t}`); + if (rows.length) { + const cols = Object.keys(rows[0]); + const ins = file.prepare(`insert into ${t} (${cols.map((c) => `"${c}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`); + file.transaction(() => { + for (const r of rows) ins.run(...(cols.map((c) => toSqlite(r[c])) as any[])); + })(); + } + const [{ n }] = file.query(`select count(*) n from ${t}`).all() as { n: number }[]; + counts[t] = [rows.length, n]; +} +const ms = performance.now() - t0; +await pg.end(); + +// Read back through drizzle: relations, timestamps as Date, json as objects, enums as text. +const tasks = await db.query.tasks.findMany({ with: { project: true, sessions: true }, limit: 3 }); +const q = await db.query.questions.findFirst({ where: (q, { isNotNull }) => isNotNull(q.options) }); +const fk = file.query("PRAGMA foreign_key_check").all(); +console.log(JSON.stringify({ ms: Math.round(ms), counts, mismatched: Object.entries(counts).filter(([, [a, b]]) => a !== b), fkViolations: fk.length, sample: { task: tasks[0] && { key: `${tasks[0].project.key}-${tasks[0].number}`, createdAt: tasks[0].createdAt, isDate: tasks[0].createdAt instanceof Date, sessions: tasks[0].sessions.length }, questionOptions: q?.options, optionsIsArray: Array.isArray(q?.options) } }, null, 2)); diff --git a/bench/sqlite/schema-port/drizzle.config.ts b/bench/sqlite/schema-port/drizzle.config.ts new file mode 100644 index 00000000..308c2681 --- /dev/null +++ b/bench/sqlite/schema-port/drizzle.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "drizzle-kit"; +export default defineConfig({ dialect: "sqlite", schema: "./schema.ts", out: "./migrations" }); diff --git a/bench/sqlite/schema-port/migrations/0000_baseline.sql b/bench/sqlite/schema-port/migrations/0000_baseline.sql new file mode 100644 index 00000000..ab29ddb1 --- /dev/null +++ b/bench/sqlite/schema-port/migrations/0000_baseline.sql @@ -0,0 +1,271 @@ +CREATE TABLE `error_sources` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `kind` text NOT NULL, + `bugsink_project_id` integer NOT NULL, + `dsn` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `error_sources_bugsink_project_id_unique` ON `error_sources` (`bugsink_project_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `error_sources_project_kind` ON `error_sources` (`project_id`,`kind`);--> statement-breakpoint +CREATE TABLE `events` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `session_id` integer, + `type` text NOT NULL, + `payload` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `goals` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `title` text NOT NULL, + `description` text, + `status` text DEFAULT 'open' NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `incident_settings` ( + `project_id` integer PRIMARY KEY NOT NULL, + `hook_secret` text NOT NULL, + `policy` text DEFAULT 'backlog' NOT NULL, + `triage_prompt` text, + `environments` text DEFAULT '["prod","production"]' NOT NULL, + `daily_limit` integer DEFAULT 5 NOT NULL, + `ignore_pattern` text, + `goal_id` integer, + `webhook_auto` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `incident_settings_hook_secret_unique` ON `incident_settings` (`hook_secret`);--> statement-breakpoint +CREATE TABLE `incidents` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `source` text NOT NULL, + `bugsink_issue_id` text NOT NULL, + `friendly_id` text, + `title` text NOT NULL, + `culprit` text, + `level` text, + `environment` text, + `first_release` text, + `last_release` text, + `events` integer DEFAULT 1 NOT NULL, + `first_seen` integer NOT NULL, + `last_seen` integer NOT NULL, + `url` text, + `stack` text, + `status` text DEFAULT 'new' NOT NULL, + `decision` text, + `decided_by` text, + `decision_reason` text, + `task_id` integer, + `task_created_at` integer, + `resolved_release` text, + `resolved_at` integer, + `regressions` integer DEFAULT 0 NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `incidents_bugsink_issue_id_unique` ON `incidents` (`bugsink_issue_id`);--> statement-breakpoint +CREATE TABLE `oauth_clients` ( + `id` text PRIMARY KEY NOT NULL, + `name` text NOT NULL, + `redirect_uris` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `oauth_codes` ( + `code_hash` text PRIMARY KEY NOT NULL, + `client_id` text NOT NULL, + `user_id` integer NOT NULL, + `redirect_uri` text NOT NULL, + `code_challenge` text NOT NULL, + `scope` text, + `expires_at` integer NOT NULL, + `used_at` integer, + FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `oauth_tokens` ( + `token_hash` text PRIMARY KEY NOT NULL, + `kind` text NOT NULL, + `client_id` text NOT NULL, + `user_id` integer NOT NULL, + `scope` text, + `expires_at` integer NOT NULL, + `revoked_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_used_at` integer, + FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `project_invites` ( + `project_id` integer NOT NULL, + `login` text NOT NULL, + `invited_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`project_id`, `login`), + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`invited_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `project_members` ( + `project_id` integer NOT NULL, + `user_id` integer NOT NULL, + `added_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`project_id`, `user_id`), + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`added_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `projects` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `slug` text NOT NULL, + `key` text NOT NULL, + `name` text NOT NULL, + `description` text, + `gitea_owner` text NOT NULL, + `gitea_repo` text NOT NULL, + `default_branch` text DEFAULT 'main' NOT NULL, + `workspace_path` text NOT NULL, + `owner_id` integer, + `next_task_number` integer DEFAULT 1 NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `projects_slug_unique` ON `projects` (`slug`);--> statement-breakpoint +CREATE UNIQUE INDEX `projects_key_unique` ON `projects` (`key`);--> statement-breakpoint +CREATE TABLE `questions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `session_id` integer, + `kind` text NOT NULL, + `text` text NOT NULL, + `options` text, + `answer` text, + `answered_via` text, + `telegram_message_id` integer, + `awaiting_hook` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `answered_at` integer, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `sessions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `tmux_name` text NOT NULL, + `provider` text DEFAULT 'claude' NOT NULL, + `claude_session_id` text, + `generation` integer DEFAULT 0 NOT NULL, + `auto_nudges` integer DEFAULT 0 NOT NULL, + `resume_at` integer, + `limit_probe_min` integer, + `limit_resumes` integer DEFAULT 0 NOT NULL, + `limit_resumes_day` text, + `limit_resumed_at` integer, + `status` text DEFAULT 'starting' NOT NULL, + `last_activity_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `ended_at` integer, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `sessions_tmux_name_unique` ON `sessions` (`tmux_name`);--> statement-breakpoint +CREATE TABLE `settings` ( + `key` text PRIMARY KEY NOT NULL, + `value` text NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `tasks` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `goal_id` integer, + `number` integer NOT NULL, + `title` text NOT NULL, + `description` text, + `status` text DEFAULT 'backlog' NOT NULL, + `openspec_change` text, + `pr_url` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `tasks_project_number` ON `tasks` (`project_id`,`number`);--> statement-breakpoint +CREATE TABLE `telegram_outbox` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `dedupe_key` text NOT NULL, + `method` text NOT NULL, + `params` text NOT NULL, + `question_id` integer, + `status` text DEFAULT 'pending' NOT NULL, + `attempts` integer DEFAULT 0 NOT NULL, + `next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `telegram_message_id` integer, + `error` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `sent_at` integer, + FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `telegram_outbox_dedupe_key_unique` ON `telegram_outbox` (`dedupe_key`);--> statement-breakpoint +CREATE TABLE `telegram_updates` ( + `update_id` integer PRIMARY KEY NOT NULL, + `status` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `users` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `gitea_id` integer NOT NULL, + `login` text NOT NULL, + `name` text, + `email` text, + `avatar_url` text, + `access_token_enc` text, + `refresh_token_enc` text, + `token_expires_at` integer, + `claude_token_enc` text, + `claude_token_set_at` integer, + `telegram_chat_id` integer, + `telegram_user_id` integer, + `telegram_username` text, + `telegram_paired_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_login_at` integer +); +--> statement-breakpoint +CREATE UNIQUE INDEX `users_gitea_id_unique` ON `users` (`gitea_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `users_login_unique` ON `users` (`login`);--> statement-breakpoint +CREATE UNIQUE INDEX `users_telegram_chat_id_unique` ON `users` (`telegram_chat_id`); \ No newline at end of file diff --git a/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json b/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json new file mode 100644 index 00000000..01d02036 --- /dev/null +++ b/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json @@ -0,0 +1,1947 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "d623ae37-1edf-4383-bd4f-443a1954867e", + "prevId": "00000000-0000-0000-0000-000000000000", + "tables": { + "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 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "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" + } + }, + "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": {} + }, + "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 + }, + "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" + } + }, + "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 + }, + "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 + }, + "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": {}, + "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": {} + }, + "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'" + }, + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {} + }, + "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 + }, + "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 + } + }, + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {}, + "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 + }, + "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 + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/bench/sqlite/schema-port/migrations/meta/_journal.json b/bench/sqlite/schema-port/migrations/meta/_journal.json new file mode 100644 index 00000000..82b04f9e --- /dev/null +++ b/bench/sqlite/schema-port/migrations/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "6", + "when": 1794565466624, + "tag": "0000_baseline", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/bench/sqlite/schema-port/schema.ts b/bench/sqlite/schema-port/schema.ts new file mode 100644 index 00000000..4b36f55e --- /dev/null +++ b/bench/sqlite/schema-port/schema.ts @@ -0,0 +1,357 @@ +import { relations } from "drizzle-orm"; +import { sql } from "drizzle-orm"; +import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; + +// PEP-36 prototype: the Peppa schema mechanically ported to SQLite (not used by the product). +const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`; + +const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs); +const updatedAt = () => + integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date()); + +/** People who log into the web, one per Gitea account. */ +export const users = sqliteTable("users", { + id: integer("id").primaryKey({ autoIncrement: true }), + giteaId: integer("gitea_id").notNull().unique(), + login: text("login").notNull().unique(), + name: text("name"), + email: text("email"), + avatarUrl: text("avatar_url"), + // OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts). + accessTokenEnc: text("access_token_enc"), + refreshTokenEnc: text("refresh_token_enc"), + tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }), + // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the + // Claude sessions of this user's projects. + claudeTokenEnc: text("claude_token_enc"), + claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }), + // Telegram chat paired from Settings; agent questions of this user's projects go there. + telegramChatId: integer("telegram_chat_id").unique(), + telegramUserId: integer("telegram_user_id"), + telegramUsername: text("telegram_username"), + telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }), + createdAt: createdAt(), + lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }), +}); + +export const projects = sqliteTable("projects", { + id: integer("id").primaryKey({ autoIncrement: true }), + slug: text("slug").notNull().unique(), + // Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2… + key: text("key").notNull().unique(), + name: text("name").notNull(), + description: text("description"), + giteaOwner: text("gitea_owner").notNull(), + giteaRepo: text("gitea_repo").notNull(), + defaultBranch: text("default_branch").notNull().default("main"), + workspacePath: text("workspace_path").notNull(), + // Null for projects created by the bot/CLI; only the owner sees a project in the web. + ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }), + // Next task number to hand out; bumped atomically on task creation. + nextTaskNumber: integer("next_task_number").notNull().default(1), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +/** People who work on a project besides its owner (projects.owner_id). */ +export const projectMembers = sqliteTable( + "project_members", + { + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + addedBy: integer("added_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.projectId, t.userId] })], +); + +/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */ +export const projectInvites = sqliteTable( + "project_invites", + { + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + login: text("login").notNull(), // lower-cased Gitea login + invitedBy: integer("invited_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.projectId, t.login] })], +); + +export const goalStatusValues = ["open", "done", "archived"] as const; + +/** Top-level objectives set by the PM; tasks are broken out of them. */ +export const goals = sqliteTable("goals", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + title: text("title").notNull(), + description: text("description"), + status: text("status", { enum: goalStatusValues }).notNull().default("open"), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +export const taskStatusValues = [ + "backlog", // created, nobody working on it + "proposing", // agent is writing the OpenSpec change + "awaiting_approval", // proposal ready, PM must approve + "in_progress", // agent applying the change + "review", // PR open in Gitea + "done", // change archived, merged + "blocked", +] as const; + +export const tasks = sqliteTable( + "tasks", + { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }), + number: integer("number").notNull(), + title: text("title").notNull(), + description: text("description"), + status: text("status", { enum: taskStatusValues }).notNull().default("backlog"), + // OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth" + openspecChange: text("openspec_change"), + prUrl: text("pr_url"), + createdAt: createdAt(), + updatedAt: updatedAt(), + }, + (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], +); + +export const sessionStatusValues = [ + "starting", + "running", + "waiting_input", // Claude asked something / needs permission + "idle", // turn finished, nothing pending + "stalled", // watchdog saw no activity + "rate_limited", // StopFailure with error=rate_limit, or limit banner on screen + "done", + "failed", +] as const; + +/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */ +export const sessions = sqliteTable("sessions", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), + tmuxName: text("tmux_name").notNull().unique(), + provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"), + // Claude session id or Codex thread id — the resume target. + conversationId: text("claude_session_id"), + // Bumped on every launch/resume; hooks from an older generation are ignored. + generation: integer("generation").notNull().default(0), + // Consecutive "keep going" nudges from the Stop hook; reset when a human answers. + autoNudges: integer("auto_nudges").notNull().default(0), + // Usage limit recovery (PEP-56): when to continue, current probe interval if the reset + // time is unknown, auto-resumes today (cap), and when the last auto-resume happened. + resumeAt: integer("resume_at", { mode: "timestamp_ms" }), + limitProbeMin: integer("limit_probe_min"), + limitResumes: integer("limit_resumes").notNull().default(0), + limitResumesDay: text("limit_resumes_day"), + limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }), + status: text("status", { enum: sessionStatusValues }).notNull().default("starting"), + lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }), + startedAt: createdAt(), + endedAt: integer("ended_at", { mode: "timestamp_ms" }), +}); + +/** Questions routed to the PM (Telegram / web) and their answers. */ +export const questions = sqliteTable("questions", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }), + // Null when asked from a session Peppa did not start (manual `claude`). + sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }), + kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(), + text: text("text").notNull(), + options: text("options", { mode: "json" }).$type<string[]>(), + answer: text("answer"), + // "system": closed by Peppa itself (session stopped/resumed), not by a person. + answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }), + telegramMessageId: integer("telegram_message_id"), + // A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer, + // so it must not also be typed into the terminal. + awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false), + createdAt: createdAt(), + answeredAt: integer("answered_at", { mode: "timestamp_ms" }), +}); + +/** Event log: hook / watchdog events, progress reports, status changes. */ +export const events = sqliteTable("events", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }), + sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }), + type: text("type").notNull(), + payload: text("payload", { mode: "json" }), + createdAt: createdAt(), +}); + +/** Small key/value store for service state (Telegram offset, pairing, binding). */ +export const settings = sqliteTable("settings", { + key: text("key").primaryKey(), + value: text("value", { mode: "json" }).notNull(), + updatedAt: updatedAt(), +}); + +/** + * Durable Telegram outbox: every message/edit is queued here first, then delivered with + * retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message). + */ +export const telegramOutbox = sqliteTable("telegram_outbox", { + id: integer("id").primaryKey({ autoIncrement: true }), + dedupeKey: text("dedupe_key").notNull().unique(), + method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(), + params: text("params", { mode: "json" }).$type<Record<string, unknown>>().notNull(), + questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }), + status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"), + attempts: integer("attempts").notNull().default(0), + nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs), + telegramMessageId: integer("telegram_message_id"), + error: text("error"), + createdAt: createdAt(), + sentAt: integer("sent_at", { mode: "timestamp_ms" }), +}); + +/** Telegram updates already taken: recorded before acting, so a restart never replays one. */ +export const telegramUpdates = sqliteTable("telegram_updates", { + updateId: integer("update_id").primaryKey(), + status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(), + createdAt: createdAt(), +}); + +/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */ +export const oauthClients = sqliteTable("oauth_clients", { + id: text("id").primaryKey(), + name: text("name").notNull(), + redirectUris: text("redirect_uris", { mode: "json" }).$type<string[]>().notNull(), + createdAt: createdAt(), +}); + +/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */ +export const oauthCodes = sqliteTable("oauth_codes", { + codeHash: text("code_hash").primaryKey(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + redirectUri: text("redirect_uri").notNull(), + codeChallenge: text("code_challenge").notNull(), + scope: text("scope"), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + usedAt: integer("used_at", { mode: "timestamp_ms" }), +}); + +/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */ +export const oauthTokens = sqliteTable("oauth_tokens", { + tokenHash: text("token_hash").primaryKey(), + kind: text("kind", { enum: ["access", "refresh"] }).notNull(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + scope: text("scope"), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + revokedAt: integer("revoked_at", { mode: "timestamp_ms" }), + createdAt: createdAt(), + lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), +}); + +export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const; +export type IncidentPolicy = (typeof incidentPolicies)[number]; + +/** Error tracking of a project (PEP-58): webhook secret and how new errors are handled. */ +export const incidentSettings = sqliteTable("incident_settings", { + projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }), + // Part of the webhook URL Bugsink posts alerts to: /api/hooks/bugsink/<hookSecret>. + hookSecret: text("hook_secret").notNull().unique(), + policy: text("policy", { enum: incidentPolicies }).notNull().default("backlog"), + // The PM's mini-prompt for the triage agent ("how to decide"). + triagePrompt: text("triage_prompt"), + environments: text("environments", { mode: "json" }).$type<string[]>().notNull().default(["prod", "production"]), + dailyLimit: integer("daily_limit").notNull().default(5), + ignorePattern: text("ignore_pattern"), + goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }), + // False: the alert webhook still has to be added in Bugsink by hand (polling covers it). + webhookAuto: integer("webhook_auto", { mode: "boolean" }).notNull().default(false), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +/** Bugsink projects feeding a Peppa project: one for the frontend, one for the backend. */ +export const errorSources = sqliteTable( + "error_sources", + { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + kind: text("kind", { enum: ["web", "api"] }).notNull(), + bugsinkProjectId: integer("bugsink_project_id").notNull().unique(), + dsn: text("dsn").notNull(), + createdAt: createdAt(), + }, + (t) => [uniqueIndex("error_sources_project_kind").on(t.projectId, t.kind)], +); + +export const incidentStatuses = ["new", "open", "pending", "task", "ignored", "resolved", "regressed"] as const; + +/** A Bugsink issue seen in Peppa. Repeated events update the same row. */ +export const incidents = sqliteTable("incidents", { + id: integer("id").primaryKey({ autoIncrement: true }), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + source: text("source", { enum: ["web", "api"] }).notNull(), + bugsinkIssueId: text("bugsink_issue_id").notNull().unique(), + friendlyId: text("friendly_id"), + title: text("title").notNull(), + culprit: text("culprit"), + level: text("level"), + environment: text("environment"), + firstRelease: text("first_release"), + lastRelease: text("last_release"), + events: integer("events").notNull().default(1), + firstSeen: integer("first_seen", { mode: "timestamp_ms" }).notNull(), + lastSeen: integer("last_seen", { mode: "timestamp_ms" }).notNull(), + url: text("url"), + stack: text("stack"), + // new → open | pending | task | ignored; task → resolved → regressed (see design.md) + status: text("status", { enum: incidentStatuses }).notNull().default("new"), + decision: text("decision", { enum: ["notify", "backlog", "start", "ask", "ignore"] }), + decidedBy: text("decided_by", { enum: ["policy", "triage", "pm"] }), + decisionReason: text("decision_reason"), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), + taskCreatedAt: integer("task_created_at", { mode: "timestamp_ms" }), + resolvedRelease: text("resolved_release"), + resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }), + regressions: integer("regressions").notNull().default(0), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + +export const projectsRelations = relations(projects, ({ many }) => ({ + goals: many(goals), + tasks: many(tasks), + sessions: many(sessions), +})); +export const goalsRelations = relations(goals, ({ one, many }) => ({ + project: one(projects, { fields: [goals.projectId], references: [projects.id] }), + tasks: many(tasks), +})); +export const tasksRelations = relations(tasks, ({ one, many }) => ({ + project: one(projects, { fields: [tasks.projectId], references: [projects.id] }), + goal: one(goals, { fields: [tasks.goalId], references: [goals.id] }), + sessions: many(sessions), + questions: many(questions), + events: many(events), +})); +export const sessionsRelations = relations(sessions, ({ one, many }) => ({ + project: one(projects, { fields: [sessions.projectId], references: [projects.id] }), + task: one(tasks, { fields: [sessions.taskId], references: [tasks.id] }), + questions: many(questions), + events: many(events), +})); +export const questionsRelations = relations(questions, ({ one }) => ({ + project: one(projects, { fields: [questions.projectId], references: [projects.id] }), + task: one(tasks, { fields: [questions.taskId], references: [tasks.id] }), + session: one(sessions, { fields: [questions.sessionId], references: [sessions.id] }), +})); +export const eventsRelations = relations(events, ({ one }) => ({ + project: one(projects, { fields: [events.projectId], references: [projects.id] }), + task: one(tasks, { fields: [events.taskId], references: [tasks.id] }), + session: one(sessions, { fields: [events.sessionId], references: [sessions.id] }), +})); diff --git a/bench/sqlite/schema-port/tx-check.ts b/bench/sqlite/schema-port/tx-check.ts new file mode 100644 index 00000000..2182f226 --- /dev/null +++ b/bench/sqlite/schema-port/tx-check.ts @@ -0,0 +1,35 @@ +// PEP-36 prototype: does drizzle's bun:sqlite driver keep `await` inside db.transaction()? +// core/tasks.ts (createTask) is written that way for postgres-js. +import { Database } from "bun:sqlite"; +import { eq, sql } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import * as schema from "./schema.ts"; + +const db = drizzle(new Database(":memory:"), { schema }); +migrate(db, { migrationsFolder: new URL("migrations", import.meta.url).pathname }); +await db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp" }); + +// 1. Async callback, as in core/tasks.ts. +try { + await db.transaction(async (tx) => { + const [p] = await tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning(); + await tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title: "t" }); + throw new Error("rollback please"); + }); +} catch (e) { + console.log("async tx threw:", (e as Error).message); +} +const [p1] = await db.select().from(schema.projects); +const t1 = await db.select().from(schema.tasks); +console.log("after async tx + throw: next_task_number =", p1.nextTaskNumber, "tasks =", t1.length, t1.length || p1.nextTaskNumber !== 1 ? "→ NOT rolled back" : "→ rolled back"); + +// 2. Sync callback (what the sqlite drivers expect). +try { + db.transaction((tx) => { + tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run(); + throw new Error("rollback please"); + }); +} catch {} +const [p2] = await db.select().from(schema.projects); +console.log("after sync tx + throw: next_task_number =", p2.nextTaskNumber, p2.nextTaskNumber === 100 ? "→ NOT rolled back" : "→ rolled back"); diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md new file mode 100644 index 00000000..955ed09c --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/design.md @@ -0,0 +1,215 @@ +# Design: PEP-36 — Bun + SQLite + +## Контекст + +В базу Пеппы пишут одновременно: веб (server actions, OAuth, health), бот (outbox, +telegram_updates, ответы), вачдог (tick раз в 30 с, heartbeat, лимиты, Bugsink), **хук +каждого события Claude — отдельный короткий процесс**, MCP-сервер каждого раннера и CLI. +Бот узнаёт о новых событиях через Postgres LISTEN/NOTIFY (`core/notify.ts`, +`apps/bot/src/bot.ts`). Вопрос этапа: тянет ли это SQLite, чем заменить NOTIFY и что +сломается под Bun. + +Всё ниже измерено на Mac Пеппы (Apple Silicon, Node 26.8, Bun 1.4.4, Postgres 17.11 в +docker) бенчмарком `bench/sqlite` (методика — `bench/sqlite/README.md`). + +## Реальная нагрузка (боевая БД, только чтение) + +- 107 событий за сутки на 5 сессиях; медианный промежуток между событиями одной сессии + 16 с, пик — 6 событий в минуту на сессию. +- Хуки срабатывают на prompt / notification / stop / permission, не на каждый tool use. +- База — 9 МБ. Самые «горячие» таблицы по числу изменений: sessions, oauth_tokens, tasks, + events, settings, telegram_outbox. + +Модель бенчмарка берёт это с запасом (хук раз в 10 с на раннер, 10 % — блокирующий вопрос +с опросом раз в 1,5 с, MCP progress раз в 30 с, get_task раз в 15 с, бот, 3 доски веба +раз в 5 с, вачдог), плюс стресс ×10 и ×50. + +## Результаты + +### Запись при параллельной работе раннеров + +p50/p95/p99/max — время транзакции записи в мс (включая ожидание блокировки); «хук» — +время старта процесса хука до первой строки кода (без tsx, см. ниже). + +| раннеры | нагрузка | вариант | записей | p50 | p95 | p99 | max | SQLITE_BUSY | ошибки | старт хука p50 | +|---|---|---|---|---|---|---|---|---|---|---| +| 10 | ×1 | bun:sqlite | 126 | 0.32 | 1.61 | 2.34 | 2.68 | 0 | 0 | 32 мс | +| 10 | ×1 | node:sqlite | 192 | 0.20 | 0.70 | 1.18 | 1.27 | 0 | 0 | 96 мс | +| 10 | ×1 | better-sqlite3 | 169 | 0.19 | 0.95 | 2.02 | 2.21 | 0 | 0 | 97 мс | +| 10 | ×1 | один писатель | 140 | 1.21 | 2.35 | 3.89 | 8.19 | 0 | 0 | 23 мс | +| 10 | ×1 | **Postgres (сейчас)** | 177 | 9.60 | 18.11 | 36.05 | 38.15 | — | 0 | 92 мс | +| 20 | ×1 | bun:sqlite | 327 | 0.29 | 1.34 | 2.21 | 3.06 | 0 | 0 | 28 мс | +| 20 | ×1 | node:sqlite | 324 | 0.16 | 0.71 | 1.33 | 2.00 | 0 | 0 | 72 мс | +| 20 | ×1 | better-sqlite3 | 314 | 0.19 | 0.82 | 1.53 | 2.20 | 0 | 0 | 88 мс | +| 20 | ×1 | один писатель | 305 | 1.34 | 2.38 | 4.16 | 7.41 | 0 | 0 | 25 мс | +| 20 | ×1 | **Postgres (сейчас)** | 306 | 8.06 | 17.16 | 29.14 | 36.39 | — | 0 | 85 мс | +| 20 | ×10 | bun:sqlite | 1510 | 0.20 | 0.46 | 1.75 | 6.17 | 0 | 0 | 19 мс | +| 20 | ×10 | node:sqlite | 1424 | 0.13 | 0.24 | 1.32 | 2.29 | 0 | 0 | 69 мс | +| 20 | ×10 | better-sqlite3 | 1471 | 0.16 | 0.27 | 1.17 | 7.86 | 0 | 0 | 69 мс | +| 20 | ×10 | один писатель | 1438 | 1.07 | 2.02 | 2.63 | 8.42 | 0 | 0 | 20 мс | +| 20 | ×10 | **Postgres (сейчас)** | 1345 | 6.98 | 11.89 | 17.85 | 43.83 | — | 0 | 68 мс | +| 20 | ×50 | bun:sqlite | 3172 | 0.15 | 0.35 | 1.83 | 7.48 | 0 | 0 | 16 мс | +| 20 | ×50 | один писатель | 3093 | 0.30 | 1.58 | 2.23 | 9.16 | 0 | 0 | 16 мс | +| 20 | ×50 | **Postgres (сейчас)** | 2910 | 4.58 | 9.19 | 12.13 | 29.31 | — | 0 | 68 мс | + +Полные таблицы по каждой операции — `node bench/sqlite/report.ts` после прогона. +Чтения: доска веба (4 запроса) p99 0,2 мс на SQLite против 5,8 мс на Postgres; опрос +ответа хуком p99 0,2 мс против 2,2 мс. + +**Вывод:** при реальной нагрузке и даже при ×50 (≈ 70 записей/с — больше упирается в +запуск процессов хука, чем в базу) SQLite в WAL не дал ни одного SQLITE_BUSY и ни одной +ошибки; запись в 25–50 раз быстрее Postgres по медиане и в 6–15 раз по p99. Причина — +нет сетевого хопа и соединения: процесс хука открывает файл за 2 мс против 8 мс на +соединение с Postgres. + +### Потолок: все процессы пишут без пауз + +`bench/sqlite/contention.ts`: N процессов пишут транзакцию хука (update + insert) подряд, +10 секунд. Это в ~1000 раз выше реальной нагрузки. + +| вариант | процессов | транзакций/с | p50 | p95 | p99 | max | BUSY-повторы | ошибки | +|---|---|---|---|---|---|---|---|---| +| bun:sqlite | 20 | 33 537 | 0.02 | 0.08 | 4.24 | 2711 | 0 | 0 | +| bun:sqlite | 40 | 27 223 | 0.03 | 0.31 | 21.96 | 2931 | 0 | 0 | +| node:sqlite | 20 | 48 578 | 0.02 | 0.03 | 0.05 | 5406 | 1 | 0 | +| node:sqlite | 40 | 47 694 | 0.02 | 0.03 | 0.06 | 6413 | 3 | 0 | +| better-sqlite3 | 20 | 47 456 | 0.02 | 0.03 | 0.05 | 5360 | 1 | 0 | +| better-sqlite3 | 40 | 45 076 | 0.02 | 0.03 | 0.06 | 5938 | 2 | 0 | +| Postgres | 20 | 4 890 | 3.88 | 6.82 | 9.01 | 97 | — | 0 | +| Postgres | 40 | 7 555 | 5.47 | 6.95 | 8.33 | 210 | — | 0 | + +**Вывод:** запас по пропускной способности — три-четыре порядка. Слабое место SQLite — +**хвост при насыщении**: блокировка записи не очередь FIFO, а повторные попытки с паузами, +поэтому единичные транзакции ждут секунды (max 3–6 с), а при `busy_timeout=5000` бывают +единичные SQLITE_BUSY (повтор спасает, ошибок 0). Postgres в насыщении предсказуемее +(max 0,1–0,2 с). Для Пеппы это не актуально, пока запись — короткие транзакции раз в +секунды; это и есть граница, где Postgres «как дополнение» имеет смысл (см. ниже). + +Наблюдение: `bun:sqlite` на macOS использует системную SQLite 3.43 (Node 26 — встроенную +3.53, better-sqlite3 — 3.54), отсюда хуже p99 в насыщении. В Docker на Linux Bun несёт +свою свежую SQLite; на Mac можно подключить свежую через `Database.setCustomSQLite`. + +### Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10) + +Задержка от момента записи события до момента, когда бот/веб его прочитали. + +| способ | бот p50 | p95 | p99 | max | +|---|---|---|---|---| +| **push** (сигнал по unix-сокету) | 0.80 | 1.42 | 2.48 | 47 | +| fs.watch на `-wal` | 26 | 192 | 300 | 508 | +| опрос с курсором 200 мс | 100 | 192 | 200 | 204 | +| опрос с курсором 1000 мс | 503 | 945 | 991 | 1002 | +| Postgres LISTEN/NOTIFY (сейчас) | 9.76 | 15.06 | 17.73 | 28 | + +- **push** быстрее NOTIFY в 10 раз; при недоступном сокете подписчик не узнаёт о событии + до страховочного опроса. +- **fs.watch** на macOS склеивает и теряет уведомления (в смоуке единичные события + доходили только страховочным опросом через 3 с), в Docker с bind-mount с хоста Mac не + работает совсем (inotify не проходит через VM). Отвергнут. +- **опрос** надёжен и прост, 200 мс — дешёвый запрос по индексу (0,1 мс), но всегда + добавляет задержку. + +### Bun на текущем коде (без изменений кода) + +| что | результат | +|---|---| +| `peppa` CLI (`help`, `project add`, `goal add`, `task add/list`) | работает; старт 0,04 с против 0,47 с у tsx | +| `peppa-hook` | работает (запись события + `pg_notify`); старт **0,04 с против 0,44 с у tsx** | +| `peppa-mcp` (stdio, SDK MCP) | работает: `tools/list`, `list_goals`, `list_tasks`, `get_task` | +| drizzle + postgres.js, мигратор | работает: все 12 миграций применены под Bun | +| бот (`bot.test.ts`, LISTEN, mock-telegram) | 13/13 тестов под `bun test` | +| весь e2e под `bun test` (13 файлов, по одному) | **134 прошли, 0 упали** (1 пропущен, как и под tsx); бинари внутри тестов (mock-claude, peppa-mcp, peppa-hook) пока через tsx | +| `bun --bun next dev` (Next 16.4, Turbopack) | работает: готов за 0,2 с, `/api/health` 200, вход по login-link, доска `/p/BUN`, задача `/t/BUN-1`, раннеры, настройки, помощь — 200; `node_modules/.bin/next` — shell-шим pnpm, запускать `next/dist/bin/next` | +| node:test | `bun test` понимает `node:test` (`describe/it/before`); прямой запуск файла `bun x.test.ts` — нет, нужен `bun test` | +| tsx-специфика | не нужна: Bun исполняет `.ts` с импортами `.ts` как есть | + +Хук — главный выигрыш: Claude ждёт хук на каждом событии, а PermissionRequest/ +AskUserQuestion — ещё и человека; 0,4 с на старт tsx сейчас — это 90 % времени хука. + +### Схема и данные на SQLite (`bench/sqlite/schema-port`) + +- Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`, + `serial` → `integer primaryKey autoIncrement`, `timestamp withTimezone` → + `integer mode timestamp_ms` (drizzle отдаёт `Date`, как сейчас), `jsonb` → `text mode + json` (отдаёт объекты), `pgEnum` → `text enum` (типы в TS те же), `boolean` → + `integer mode boolean`, `bigint` → `integer` (64 бита), `defaultNow()` → + `unixepoch('subsec')*1000`. drizzle-kit генерирует одну базовую миграцию (18 таблиц, + 270 строк) вместо 12 миграций Postgres — историю миграций Postgres не переносим. +- **Перенос боевых данных** (Postgres только на чтение → новый файл): 57 мс, все 18 таблиц + совпали по числу строк, 0 нарушений внешних ключей; drizzle читает `Date`, массивы JSON, + связи (`db.query.tasks.findMany({ with: … })`). +- **Ловушка: асинхронные транзакции.** sqlite-драйверы drizzle (`bun-sqlite`, + `better-sqlite3`) синхронные: `db.transaction(async tx => { await …; await … })` + коммитит после первого `await`, остальное идёт вне транзакции, и **откат не работает** + (проверено: `tx-check.ts`, `next_task_number` и задача остались после исключения). + В коде такой одна — `createTask` (core/tasks.ts); переписать на синхронную и запретить + `transaction(async` проверкой. +- Прочая Postgres-специфика: `pg_notify` (core/notify.ts), `$client.listen` (бот), + `for update skip locked` (core/incidents.ts — не нужно, `BEGIN IMMEDIATE` и так + сериализует писателей), `count(*)::int` (monitor/incidents). `->>`, `lower()`, `like`, + `returning`, `on conflict` в SQLite есть. + +## Решения + +### 1. Переезжать целиком, Postgres не держать + +Замер не нашёл места, где Postgres нужен Пеппе: по задержке SQLite лучше на всех +режимах, ошибок блокировки нет, запас по пропускной способности — тысячи раз. Гибрид +(SQLite + Postgres для части таблиц) добавил бы два драйвера, два способа уведомлений и +распределённые транзакции между базами ради нагрузки, которой нет. Чаты PM решил долго не +хранить — их объём тоже не повод. Postgres «как дополнение» возвращаем точечно, если +появится поток записей на сотни в секунду длинными транзакциями (там, где у SQLite +хвост блокировок) — например, хранение логов терминалов раннеров (PEP-9). + +Отвергнуто: «не переезжать» — Postgres медленнее на нашей нагрузке и требует отдельного +контейнера; «гибрид сейчас» — сложность без измеренной причины. + +### 2. Каждый процесс пишет сам, без сервиса-писателя + +Вариант «один писатель» (все записи по HTTP через unix-сокет) медленнее прямой записи в +4–6 раз по медиане (1,1–1,3 мс против 0,2–0,3), добавляет точку отказа (упал писатель — +встали хуки всех раннеров) и процесс, который нужно поднимать раньше всех. Его плюс — +FIFO-очередь записи без хвостов — нужен только при насыщении, которого нет. + +Правила для всех процессов (обёртка в `packages/db`): +- `PRAGMA busy_timeout = 5000` **первой** командой — иначе при одновременном открытии + файла многими процессами бывает `SQLITE_BUSY_RECOVERY` без ожидания (поймано в смоуке); +- `journal_mode=WAL` один раз при создании файла; `synchronous=NORMAL`, `foreign_keys=ON`; +- запись — `BEGIN IMMEDIATE`, транзакции короткие и синхронные, до 3 повторов на BUSY; +- база только на локальном диске (WAL не работает на сетевых ФС). + +### 3. LISTEN/NOTIFY → журнал событий + сигнал + страховочный опрос + +Источник правды — таблица `events` и курсор подписчика (`settings`, ключ +`cursor:<service>`), так бот после рестарта дочитывает пропущенное (сейчас NOTIFY, +пришедший во время рестарта, теряется, спасает только reconcile раз в 10 с). Записавший +процесс шлёт датаграмму «есть новое» в unix-сокет `~/.peppa/events.sock` каждого +подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в +секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала. + +### 4. Поэтапно: Bun → SQLite → Docker + +Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; даёт ускорение хука в +10 раз сразу. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме +только чтения как откатом. Этап 3 зависит от PEP-17/PEP-18: раннеры (tmux + claude + +рабочие копии) должны видеть тот же файл базы на локальном диске; самый простой вариант — +сервисы и раннеры в одном контейнере с томами хоста. + +## Риски + +- **Хвост блокировок при насыщении** (max секунды) — не проявился на нагрузке ×50; следим + метрикой «время записи p99» в heartbeat, порог алерта 1 с. +- **Повреждение/потеря файла** — WAL устойчив к падению процесса; ежедневная копия + `VACUUM INTO` (7 штук) и копия перед переносом. +- **Next.js под Bun** — dev-режим работает (проверено), но `bun --bun` для Next официально + экспериментальный; запасной вариант — веб на Node, остальное на Bun: SQLite это не мешает + (`node:sqlite` в Node 26 работает с тем же файлом, замерено). +- **Bugsink** держит свою базу в контейнере `peppa-postgres` — контейнер нельзя удалить, + пока Bugsink не переведён (отдельная задача; Bugsink умеет SQLite). +- `better-sqlite3` под Node 26 нет готовых бинарников (сборка node-gyp из исходников, + версия 12.x не собирается вовсе) — в Docker на Node это лишняя сборка; `bun:sqlite` и + `node:sqlite` встроены. + +## Открытые вопросы + +См. «Решения PM» в proposal.md. diff --git a/openspec/changes/pep-36-lightweight-stack/proposal.md b/openspec/changes/pep-36-lightweight-stack/proposal.md new file mode 100644 index 00000000..1e084be8 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/proposal.md @@ -0,0 +1,67 @@ +# Proposal: PEP-36 — легковесный стек: Bun + SQLite, запуск одной командой + +Задача Пеппы: **PEP-36** · Цель «Безопасность и эксплуатация». + +## Why + +Пеппу сейчас поднимают Node + tsx + pnpm + Postgres в docker + `next build`. Для одной +машины это тяжело: отдельный контейнер БД, сборка веба после каждой правки, медленный +старт процессов (хук Claude — это новый процесс tsx на каждое событие, ~0,44 с только на +старт). PM решил (2026-11-13): вся Пеппа на Bun + SQLite (WAL), Postgres — только как +дополнение там, где SQLite не тянет параллельные записи; переписку чатов долго не храним. + +Перед переездом нужно было ответить на вопрос: выдержит ли один файл SQLite записи из +многих процессов (веб, бот, вачдог, хуки и MCP каждого раннера), чем заменить +LISTEN/NOTIFY и что сломается под Bun. Замер сделан (`bench/sqlite`, цифры в design.md). + +## What Changes + +Рекомендация по замеру — **переезжать целиком, поэтапно**; Postgres для Пеппы не нужен. + +- **Этап 1 — Bun вместо tsx** (без смены БД): обёртки бинарей, launchd, тесты на + `bun test`. Текущий код уже работает под Bun без правок (CLI, хук, MCP, бот, e2e бота). + Хук стартует за 0,04 с вместо 0,44 с. +- **Этап 2 — SQLite вместо Postgres**: схема на `sqlite-core` (одна базовая миграция + вместо 12), каждый процесс открывает файл сам (WAL + `busy_timeout`), без отдельного + сервиса-писателя; LISTEN/NOTIFY → журнал `events` с курсором + сигнал по unix-сокету + + опрос раз в секунду как страховка; перенос данных командой со сверкой; ежедневная копия. +- **Этап 3 — `docker compose up`**: один образ на Bun для веба, бота и вачдога; база и + рабочие копии в томах хоста. Связан с PEP-17 (песочница) и PEP-18 (деплой). + +Вне scope: переезд Bugsink (у него своя база в контейнере Postgres, см. «Решения PM»), +хранение чатов (PM: долго не храним). + +## Capabilities + +### New Capabilities +- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Bun, запуск одной командой. + +### Modified Capabilities +- `service-monitoring`: health-эндпоинт проверяет файл SQLite вместо Postgres. + +## Impact + +- `packages/db` (схема, клиент, миграции), `packages/core/src/notify.ts`, `core/tasks.ts` + (транзакция), `core/incidents.ts` (`for update skip locked`), `apps/bot` (подписка), + `apps/web` (живые обновления, health), `packages/testkit` (БД тестов), bin-обёртки, + `scripts/install-launchd.sh`, `infra/`. +- Зависимости: −`postgres`, −`tsx` (после этапа 1), +Bun ≥ 1.4 на машине или в образе. +- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос занимает доли секунды). + +## Решения PM + +1. **Переезд целиком или гибрид?** Рекомендация: целиком. Замер не нашёл места, где + Postgres нужен: при 20 раннерах и нагрузке до ×50 запись в SQLite в 25–50 раз (по медиане) + быстрее, без единой блокировки. Postgres можно вернуть точечно, если появится + нагрузка другого порядка (например, хранение чатов в больших объёмах). +2. **Как развести записи многих процессов?** Рекомендация: каждый процесс пишет сам + (WAL + `busy_timeout` + `BEGIN IMMEDIATE`), без сервиса-писателя. Писатель по сокету + медленнее (лишний переход), добавляет точку отказа и не нужен при наших частотах. +3. **Замена LISTEN/NOTIFY**: журнал `events` с курсором + сигнал по unix-сокету от + записавшего процесса + опрос раз в секунду. fs.watch отвергнут: на macOS теряет события. +4. **Bugsink**: его база `bugsink` живёт в том же контейнере `peppa-postgres`. Оставить + контейнер только под Bugsink или перевести Bugsink на его встроенный SQLite (отдельная + задача)? Рекомендация: отдельная задача, контейнер пока остаётся для Bugsink. +5. **Порядок**: этап 1 (Bun) можно делать сразу — он обратим и не трогает данные. Этап 2 + — после этапа 1, с неделей отката на Postgres в режиме только чтения. Этап 3 — после + решений PEP-17/PEP-18 о том, где живут раннеры. diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md new file mode 100644 index 00000000..1a43aad8 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md @@ -0,0 +1,95 @@ +# Spec Delta: platform-storage + +## Purpose + +Описывает, где Пеппа хранит свои данные после переезда на Bun + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой. + +## ADDED Requirements + +### Requirement: Одна база SQLite для всех процессов +Все процессы Пеппы (веб, бот, вачдог, `peppa-hook`, `peppa-mcp`, CLI) SHALL хранить данные в одном файле SQLite в режиме WAL. Каждый процесс SHALL открывать файл сам, первой командой выставлять ожидание блокировки не меньше 5 секунд и писать короткими транзакциями с немедленным захватом записи. Запись, которая не получила блокировку за время ожидания, SHALL повторяться до 3 раз и только потом считаться ошибкой; ошибка SHALL попадать в лог процесса с именем операции. + +#### Scenario: 20 раннеров пишут одновременно +- **GIVEN** 20 раннеров в работе, у каждого свои процессы хуков и MCP, бот, веб и вачдог запущены +- **WHEN** за 10 минут хуки, MCP, бот и вачдог записывают 6000 событий, вопросов и обновлений сессий +- **THEN** в базе ровно 6000 новых записей, ни одна запись не завершилась ошибкой «database is locked», 99 % записей заняли меньше 20 мс + +#### Scenario: Много процессов открывают базу одновременно +- **GIVEN** файл базы существует и в нём идут записи +- **WHEN** 20 процессов хука стартуют в одну и ту же секунду +- **THEN** все 20 открывают базу и записывают свои события, ни один не завершается с кодом `SQLITE_BUSY_RECOVERY` + +#### Scenario: Блокировка держится дольше ожидания +- **GIVEN** посторонний процесс держит транзакцию записи 20 секунд +- **WHEN** хук раннера «PEP-42» пытается записать событие `turn_end` +- **THEN** хук делает 3 попытки, затем пишет в `~/.peppa/hook.log` строку с `hook.event` и `SQLITE_BUSY` и завершается без зависания Claude дольше 30 секунд + +### Requirement: Живые обновления без Postgres +Бот и веб SHALL узнавать о новых событиях, вопросах и изменениях задач, читая журнал `events` по курсору (id последнего прочитанного события). Процесс, записавший событие, SHALL будить подписчиков коротким сигналом по локальному сокету; если сигнал не дошёл, подписчик SHALL всё равно найти событие опросом не реже раза в секунду. + +#### Scenario: Вопрос агента доходит до PM +- **GIVEN** бот запущен, PM привязал Telegram +- **WHEN** агент раннера «PEP-42» задаёт вопрос «Удалить build?» +- **THEN** бот видит вопрос и ставит сообщение PM в очередь в среднем быстрее 50 мс и в 99 % случаев быстрее 1 секунды + +#### Scenario: Сокет подписки недоступен +- **GIVEN** бот запущен, сокет сигналов не создан или упал +- **WHEN** MCP раннера «PEP-42» пишет `report_progress` «Сделал шаг 3 из 7» +- **THEN** бот читает это событие не позже чем через 1 секунду после записи + +#### Scenario: Бот перезапустился +- **GIVEN** бот остановлен, курсор бота — событие 120, за время простоя записаны события 121–125 +- **WHEN** бот запускается +- **THEN** бот обрабатывает события 121–125 по одному разу и сохраняет курсор 125 + +### Requirement: Перенос данных из Postgres +Переезд SHALL выполняться командой, которая читает боевую базу Postgres только на чтение, создаёт новый файл SQLite по актуальной схеме, переносит все таблицы и сверяет число строк и внешние ключи. При любом расхождении команда SHALL удалять новый файл, оставлять Postgres без изменений и печатать, в какой таблице расхождение. + +#### Scenario: Успешный перенос +- **GIVEN** в Postgres 18 таблиц Пеппы, среди них 107 событий, 18 вопросов и 47 сообщений outbox +- **WHEN** администратор запускает `peppa db migrate-to-sqlite ~/.peppa/peppa.db` +- **THEN** создан файл `~/.peppa/peppa.db`, в нём 107 событий, 18 вопросов и 47 сообщений outbox, проверка внешних ключей без нарушений, команда печатает «перенесено, расхождений нет» + +#### Scenario: Расхождение при переносе +- **GIVEN** в таблице `questions` есть строка, ссылающаяся на несуществующую сессию +- **WHEN** администратор запускает перенос +- **THEN** файл SQLite не создан, Postgres не изменён, команда печатает «questions: нарушение внешнего ключа» и завершается с кодом 1 + +### Requirement: Резервная копия базы +Вачдог SHALL раз в сутки делать согласованную копию файла базы без остановки сервисов и хранить последние 7 копий; копия SHALL открываться как самостоятельная база. + +#### Scenario: Ночная копия +- **GIVEN** сервисы работают, раннеры пишут события +- **WHEN** наступает время ежедневной копии +- **THEN** в `~/.peppa/backups/` появляется файл с датой, он открывается и содержит все задачи на момент копии, копий не больше 7 + +#### Scenario: Нет места на диске +- **GIVEN** на диске меньше места, чем размер базы +- **WHEN** вачдог делает копию +- **THEN** неполная копия удалена, админы платформы получают сообщение «резервная копия не сделана: нет места», сервисы продолжают работать + +### Requirement: Сервисы Пеппы на Bun +Веб (режим разработки Next.js без сборки), бот, вачдог, `peppa-hook`, `peppa-mcp` и CLI SHALL запускаться под Bun без tsx и pnpm. Хук SHALL стартовать и закончить запись события быстрее 150 мс. + +#### Scenario: Хук на каждое событие +- **GIVEN** раннер «PEP-42» работает, Claude вызывает хук Stop +- **WHEN** `peppa-hook stop` получает событие +- **THEN** событие `turn_end` записано, хук завершился быстрее 150 мс + +#### Scenario: Нет Bun на машине +- **GIVEN** на машине не установлен Bun +- **WHEN** администратор запускает `peppa status` +- **THEN** команда печатает «нужен Bun ≥ 1.4: https://bun.sh» и завершается с кодом 1 + +### Requirement: Запуск одной командой +Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Bun: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске. + +#### Scenario: Первый запуск +- **GIVEN** чистая машина с Docker, заполненный `.env` +- **WHEN** администратор выполняет `docker compose up -d` +- **THEN** через минуту `GET /api/health` отвечает 200, `db.ok: true`, бот и вачдог в сводке «работает» + +#### Scenario: База на сетевом диске +- **GIVEN** том с базой смонтирован как сетевая папка (NFS/SMB) +- **WHEN** сервис Пеппы стартует +- **THEN** сервис не запускается и пишет «файл базы на сетевом диске: SQLite WAL требует локальный диск» diff --git a/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md new file mode 100644 index 00000000..6b7dd9d8 --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md @@ -0,0 +1,16 @@ +# Spec Delta: service-monitoring + +## MODIFIED Requirements + +### Requirement: Health-эндпоинт +Веб SHALL отвечать на `GET /api/health` JSON-сводкой: доступность БД, версия и коммит, состояние сервисов; код ответа 200, если БД доступна, иначе 503. Сводка не содержит логинов и чатов пользователей. + +#### Scenario: Всё работает +- **GIVEN** БД доступна, версия Пеппы 0.15.0 +- **WHEN** запрошен `/api/health` +- **THEN** ответ 200 с `ok: true`, `db.ok: true`, `version: "0.15.0"` и списком сервисов web, bot, watchdog + +#### Scenario: БД недоступна +- **GIVEN** файл базы SQLite не открывается (удалён, нет прав или повреждён) +- **WHEN** запрошен `/api/health` +- **THEN** ответ 503 с `ok: false`, `db.ok: false` и текстом ошибки, не дольше чем за 3 секунды diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md new file mode 100644 index 00000000..18d162fe --- /dev/null +++ b/openspec/changes/pep-36-lightweight-stack/tasks.md @@ -0,0 +1,41 @@ +# Tasks: PEP-36 + +## 0. Замер и решение (этот этап) + +- [x] 0.1 Частоты записи из боевой БД (только чтение): события, вопросы, сессии, outbox +- [x] 0.2 Бенчмарк `bench/sqlite`: 10 и 20 раннеров, ×1 и ×10; bun:sqlite, node:sqlite, better-sqlite3, один писатель, Postgres +- [x] 0.3 Прототипы замены LISTEN/NOTIFY: опрос с курсором, fs.watch WAL, push по unix-сокету +- [x] 0.4 Текущий код под Bun: CLI, `peppa-hook`, `peppa-mcp`, бот, e2e (`bun test`), `next dev` +- [x] 0.5 Прототип схемы на sqlite (`bench/sqlite/schema-port`): базовая миграция, перенос боевых данных, проверка транзакций drizzle +- [ ] 0.6 Решение PM по «Решениям PM» в proposal.md (request_approval) + +## 1. Этап 1 — Bun вместо tsx (без смены БД) + +- [ ] 1.1 Обёртки `packages/*/bin/*` и `apps/bot/bin/*`: `bun` вместо `tsx`, проверка версии Bun (≥ 1.4) с понятной ошибкой +- [ ] 1.2 Тесты: `bun test` вместо `tsx --test` (node:test работает в Bun); прогнать весь e2e, починить расхождения +- [ ] 1.3 launchd-агенты бота и вачдога на Bun; веб — `bun --bun next dev`/`next start` по итогам проверки 0.4 +- [ ] 1.4 Замер хука на живой машине: старт и запись события (цель < 150 мс) + +## 2. Этап 2 — SQLite вместо Postgres + +- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `bun:sqlite`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON` +- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции +- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async` +- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` и `lower()` работают как есть +- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме +- [ ] 2.6 `peppa db migrate-to-sqlite <file>`: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении +- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл +- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude) +- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (Bugsink остаётся на своём Postgres или переезжает отдельно) + +## 3. Этап 3 — запуск одной командой + +- [ ] 3.1 Образ на `oven/bun` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста +- [ ] 3.2 Согласовать с PEP-17 (песочница) и PEP-18 (деплой): где живут раннеры, как контейнер видит рабочие копии и токены +- [ ] 3.3 `docker compose up` на чистой машине → health 200 за минуту; документация в README и `/help` +- [ ] 3.4 Отказ запуска, если база на сетевом диске + +## 4. Завершение + +- [ ] 4.1 AGENTS.md, docs/HANDOFF.md, `/help` — новый стек и команды +- [ ] 4.2 Архив change, PR -- 2.45.2 From eeb326cc4fb4e6e5af39008be6cd5a0779e3bcf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:28:59 +0500 Subject: [PATCH 016/536] =?UTF-8?q?PEP-36:=20PM=20decision=20=E2=80=94=20N?= =?UTF-8?q?ode=2026=20+=20node:sqlite;=20drizzle=20shim=20and=20check?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- bench/sqlite/README.md | 4 +- bench/sqlite/RESULTS.md | 9 ++ bench/sqlite/schema-port/drizzle-check.ts | 96 +++++++++++++++++++ .../sqlite/schema-port/node-sqlite-driver.ts | 93 ++++++++++++++++++ .../pep-36-lightweight-stack/design.md | 64 ++++++++++--- .../pep-36-lightweight-stack/proposal.md | 77 +++++++-------- .../specs/platform-storage/spec.md | 21 ++-- .../changes/pep-36-lightweight-stack/tasks.md | 24 +++-- 8 files changed, 312 insertions(+), 76 deletions(-) create mode 100644 bench/sqlite/schema-port/drizzle-check.ts create mode 100644 bench/sqlite/schema-port/node-sqlite-driver.ts diff --git a/bench/sqlite/README.md b/bench/sqlite/README.md index db7c344a..ac8249e3 100644 --- a/bench/sqlite/README.md +++ b/bench/sqlite/README.md @@ -1,7 +1,9 @@ # PEP-36: замер SQLite vs Postgres под нагрузкой Пеппы Не часть продукта: отдельный `package.json` вне pnpm-воркспейса, свои зависимости. -Результаты и выводы — в `openspec/changes/pep-36-lightweight-stack/design.md`. +Результаты — `RESULTS.md`, выводы — `openspec/changes/pep-36-lightweight-stack/design.md`. +Решение PM: Node 26 + `node:sqlite` (Bun замерен для сравнения). Прототип драйвера drizzle +на `node:sqlite` — `schema-port/node-sqlite-driver.ts`, проверки — `node schema-port/drizzle-check.ts`. ```bash cd bench/sqlite diff --git a/bench/sqlite/RESULTS.md b/bench/sqlite/RESULTS.md index 72e9576a..c12b7993 100644 --- a/bench/sqlite/RESULTS.md +++ b/bench/sqlite/RESULTS.md @@ -68,3 +68,12 @@ {"backend":"pg","procs":20,"seconds":10,"txPerSec":4890,"p50":"3.88","p95":"6.82","p99":"9.01","max":"97.1","busyRetries":0,"errors":0} {"backend":"pg","procs":40,"seconds":10,"txPerSec":7555,"p50":"5.47","p95":"6.95","p99":"8.33","max":"210.2","busyRetries":0,"errors":0} ``` + +## drizzle на node:sqlite и bun:sqlite (`schema-port/drizzle-check.ts`) + +Транзакция хука (update sessions + insert events) через drizzle, 20 000 подряд в одном процессе: + +| драйвер | мкс на транзакцию | +|---|---| +| node:sqlite (Node 26.8, прослойка `node-sqlite-driver.ts`) | 53.0 | +| bun:sqlite (Bun 1.4.4, `drizzle-orm/bun-sqlite`) | 62.9 | diff --git a/bench/sqlite/schema-port/drizzle-check.ts b/bench/sqlite/schema-port/drizzle-check.ts new file mode 100644 index 00000000..00ba80fb --- /dev/null +++ b/bench/sqlite/schema-port/drizzle-check.ts @@ -0,0 +1,96 @@ +// PEP-36 prototype: Peppa's ported schema through drizzle on node:sqlite (Node 26) or +// bun:sqlite (Bun) — migrations, typed round trips, transactions, and the cost of a +// hook-like write through the ORM. +// node drizzle-check.ts bun drizzle-check.ts +import { eq, sql } from "drizzle-orm"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as schema from "./schema.ts"; + +const isBun = typeof (globalThis as any).Bun !== "undefined"; +const dir = mkdtempSync(join(tmpdir(), "pep36-")); +const file = join(dir, "peppa.db"); +const migrationsFolder = new URL("migrations", import.meta.url).pathname; + +let db: any; +if (isBun) { + const { Database } = await import("bun:sqlite" as string); + const { drizzle } = await import("drizzle-orm/bun-sqlite"); + const { migrate } = await import("drizzle-orm/bun-sqlite/migrator"); + const d = new Database(file, { create: true }); + for (const p of ["PRAGMA busy_timeout = 5000", "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA foreign_keys = ON"]) d.exec(p); + db = drizzle(d, { schema }); + migrate(db, { migrationsFolder }); +} else { + const { drizzleNodeSqlite } = await import("./node-sqlite-driver.ts"); + const { migrate } = await import("drizzle-orm/better-sqlite3/migrator"); + db = drizzleNodeSqlite(file, schema); + migrate(db, { migrationsFolder }); +} +const ok = (name: string, cond: boolean, extra = "") => console.log(`${cond ? "ok " : "FAIL"} ${name}${extra ? ` — ${extra}` : ""}`); + +const [user] = db.insert(schema.users).values({ giteaId: 1, login: "mock-pm", telegramChatId: 9007199254740991 }).returning().all(); +const [project] = db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp", ownerId: user.id }).returning().all(); +ok("insert … returning", project.id === 1 && project.createdAt instanceof Date, `createdAt ${project.createdAt.toISOString()}`); +ok("bigint chat id round trip", db.select().from(schema.users).get().telegramChatId === 9007199254740991); + +// createTask as it has to look on SQLite: synchronous transaction, BEGIN IMMEDIATE. +const createTask = (title: string) => + db.transaction( + (tx: any) => { + const [p] = tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning().all(); + return tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title }).returning().get(); + }, + { behavior: "immediate" }, + ); +const t1 = createTask("Первая"); +const t2 = createTask("Вторая"); +ok("sync transaction", t1.number === 1 && t2.number === 2 && t2.status === "backlog"); + +try { + db.transaction((tx: any) => { + tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run(); + throw new Error("boom"); + }); +} catch {} +ok("rollback on throw", db.select().from(schema.projects).get().nextTaskNumber === 3); + +let asyncRefused = false; +try { + await db.transaction(async (tx: any) => { + await tx.update(schema.projects).set({ nextTaskNumber: 200 }).where(eq(schema.projects.id, 1)); + }); +} catch (e) { + asyncRefused = /synchronous/.test((e as Error).message); +} +ok("async transaction", isBun ? true : asyncRefused, isBun ? "bun-sqlite: commits after the first await (not refused) — see tx-check.ts" : "refused with a clear error"); + +const [sess] = db.insert(schema.sessions).values({ projectId: 1, taskId: t1.id, tmuxName: "peppa-P-1-s1" }).returning().all(); +db.insert(schema.questions).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, kind: "permission", text: "Удалить build?", options: ["Да", "Нет"], awaitingHook: true }).run(); +const q = db.query.questions.findFirst({ with: { session: true, task: true } }).sync(); +ok("json + boolean + relations", Array.isArray(q.options) && q.options[1] === "Нет" && q.awaitingHook === true && q.session.tmuxName === "peppa-P-1-s1" && q.task.title === "Первая"); +db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 1 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 2 } } }).run(); +db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 3 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 3 } } }).run(); +ok("upsert json", db.select().from(schema.settings).get().value.at === 3); +db.insert(schema.telegramOutbox).values({ dedupeKey: "q:1", method: "sendMessage", params: { chat_id: 42, text: "?" } }).run(); +// core/telegram.ts compares params->>'chat_id' with a string. Postgres ->> returns text; +// SQLite ->> returns the JSON number as a number, so the same SQL finds nothing. +const asText = db.select().from(schema.telegramOutbox).where(sql`${schema.telegramOutbox.params}->>'chat_id' = ${"42"}`).all(); +const asCast = db.select().from(schema.telegramOutbox).where(sql`cast(${schema.telegramOutbox.params}->>'chat_id' as text) = ${"42"}`).all(); +ok("json ->> as in core/telegram.ts differs from Postgres", asText.length === 0 && asCast.length === 1, "needs cast(… as text) on SQLite"); + +// Cost of the hook's write through the ORM (update session + insert event), one process. +const n = 20000; +const t0 = performance.now(); +for (let i = 0; i < n; i++) + db.transaction( + (tx: any) => { + tx.update(schema.sessions).set({ status: "running", lastActivityAt: new Date() }).where(eq(schema.sessions.id, sess.id)).run(); + tx.insert(schema.events).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, type: "turn_end", payload: { i } }).run(); + }, + { behavior: "immediate" }, + ); +const us = ((performance.now() - t0) / n) * 1000; +console.log(`${isBun ? "bun:sqlite" : "node:sqlite"} via drizzle: ${us.toFixed(1)} µs per hook transaction (${n} in one process)`); +rmSync(dir, { recursive: true, force: true }); diff --git a/bench/sqlite/schema-port/node-sqlite-driver.ts b/bench/sqlite/schema-port/node-sqlite-driver.ts new file mode 100644 index 00000000..94a35c7e --- /dev/null +++ b/bench/sqlite/schema-port/node-sqlite-driver.ts @@ -0,0 +1,93 @@ +// PEP-36 prototype: drizzle on Node's built-in node:sqlite. drizzle-orm 0.45 has no +// node:sqlite driver (it exists only in 1.0 beta/rc), but node:sqlite's API is close to +// better-sqlite3's, so a thin client shim lets drizzle's better-sqlite3 *session* run on it: +// prepare() → run/all/get/raw(), transaction(fn) → .deferred/.immediate/.exclusive. +// drizzle-orm/better-sqlite3 itself is not imported: its driver.js imports the native +// better-sqlite3 package at load time. construct() below mirrors that driver. +import { DatabaseSync, type StatementSync } from "node:sqlite"; +import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session"; +import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations"; +import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db"; +import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect"; + +type Params = unknown[]; + +class Statement { + stmt: StatementSync; + rawStmt: StatementSync | null = null; + db: DatabaseSync; + sql: string; + constructor(db: DatabaseSync, sql: string) { + this.db = db; + this.sql = sql; + this.stmt = db.prepare(sql); + } + run(...p: Params) { + return this.stmt.run(...(p as any[])); + } + all(...p: Params) { + return this.stmt.all(...(p as any[])); + } + get(...p: Params) { + return this.stmt.get(...(p as any[])); + } + /** Rows as arrays (drizzle maps columns by position). */ + raw() { + if (!this.rawStmt) { + this.rawStmt = this.db.prepare(this.sql); + this.rawStmt.setReturnArrays(true); + } + return this.rawStmt; + } +} + +export class NodeSqliteClient { + db: DatabaseSync; + cache = new Map<string, Statement>(); + constructor(path: string, opts: { busyTimeoutMs?: number } = {}) { + this.db = new DatabaseSync(path); + // busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY + // when many processes open the file together (see bench/sqlite/README.md). + this.db.exec(`PRAGMA busy_timeout = ${opts.busyTimeoutMs ?? 5000}`); + this.db.exec("PRAGMA journal_mode = WAL"); + this.db.exec("PRAGMA synchronous = NORMAL"); + this.db.exec("PRAGMA foreign_keys = ON"); + } + prepare(sql: string) { + let s = this.cache.get(sql); + if (!s) this.cache.set(sql, (s = new Statement(this.db, sql))); + return s; + } + exec(sql: string) { + this.db.exec(sql); + } + transaction<T>(fn: (...a: any[]) => T) { + const run = (begin: string) => (...a: any[]) => { + this.db.exec(begin); + try { + const r = fn(...a); + if (r && typeof (r as any).then === "function") throw new Error("SQLite transactions must be synchronous (no async callback)"); + this.db.exec("COMMIT"); + return r; + } catch (e) { + if (this.db.isTransaction) this.db.exec("ROLLBACK"); + throw e; + } + }; + return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") }; + } + close() { + this.db.close(); + } +} + +export function drizzleNodeSqlite<S extends Record<string, unknown>>(path: string, fullSchema: S) { + const client = new NodeSqliteClient(path); + const dialect = new SQLiteSyncDialect(); + const tables = extractTablesRelationalConfig(fullSchema, createTableRelationsHelpers); + const schema = { fullSchema, schema: tables.tables, tableNamesMap: tables.tableNamesMap }; + const session = new BetterSQLiteSession(client as any, dialect, schema as any); + const db = new BaseSQLiteDatabase("sync", dialect, session as any, schema as any) as any; + db.$client = client; + return db as BaseSQLiteDatabase<"sync", unknown, S>; +} diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md index 955ed09c..b889c006 100644 --- a/openspec/changes/pep-36-lightweight-stack/design.md +++ b/openspec/changes/pep-36-lightweight-stack/design.md @@ -1,4 +1,4 @@ -# Design: PEP-36 — Bun + SQLite +# Design: PEP-36 — Node 26 без сборки + SQLite ## Контекст @@ -7,7 +7,7 @@ telegram_updates, ответы), вачдог (tick раз в 30 с, heartbeat, каждого события Claude — отдельный короткий процесс**, MCP-сервер каждого раннера и CLI. Бот узнаёт о новых событиях через Postgres LISTEN/NOTIFY (`core/notify.ts`, `apps/bot/src/bot.ts`). Вопрос этапа: тянет ли это SQLite, чем заменить NOTIFY и что -сломается под Bun. +сломается без tsx (замер делался для Bun и Node; PM выбрал Node 26, см. «Решение PM»). Всё ниже измерено на Mac Пеппы (Apple Silicon, Node 26.8, Bun 1.4.4, Postgres 17.11 в docker) бенчмарком `bench/sqlite` (методика — `bench/sqlite/README.md`). @@ -109,7 +109,7 @@ p50/p95/p99/max — время транзакции записи в мс (вкл - **опрос** надёжен и прост, 200 мс — дешёвый запрос по индексу (0,1 мс), но всегда добавляет задержку. -### Bun на текущем коде (без изменений кода) +### Bun на текущем коде (проверено до решения PM; Node без tsx — этап 1) | что | результат | |---|---| @@ -126,6 +126,37 @@ p50/p95/p99/max — время транзакции записи в мс (вкл Хук — главный выигрыш: Claude ждёт хук на каждом событии, а PermissionRequest/ AskUserQuestion — ещё и человека; 0,4 с на старт tsx сейчас — это 90 % времени хука. +### Node 26 вместо Bun (решение PM) + +PM выбрал Node 26 со встроенным снятием типов и `node:sqlite`. По замеру это не хуже Bun +там, где важно: + +- **Запись** на той же нагрузке (таблица выше, строки `node:sqlite`): p50 0,13–0,20 мс, + p99 0,9–1,3 мс — не хуже `bun:sqlite` (0,20–0,32 / 1,2–2,3); в потолке — 48 тыс. + транзакций/с против 27–34 тыс. и p99 0,05 мс против 4–22 мс (у Node 26 встроенная + SQLite 3.53, у Bun на macOS — системная 3.43). +- **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert, + 20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс. +- **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против + 16–32 мс; но против tsx (0,44 с) это всё равно в 4–6 раз быстрее. Реальный старт + `peppa-hook` на Node без tsx замеряется в этапе 1. +- `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего + лишнего. + +**Драйвер drizzle.** В стабильном drizzle 0.45 драйвера `node:sqlite` нет (только в +1.0 beta/rc — мажорное обновление ради одного драйвера не берём). `sqlite-proxy` не +подходит: он асинхронный, транзакции через него не атомарны для нескольких процессов. +better-sqlite3 под Node 26 собирается из исходников (готовых бинарников нет, 12.x не +собирается вовсе). Решение — **тонкая прослойка** (`schema-port/node-sqlite-driver.ts`, +~80 строк): клиент `node:sqlite` с API better-sqlite3 (`prepare → run/all/get/raw`, +`transaction(fn).immediate`) под сессию drizzle `better-sqlite3/session`; сам +`drizzle-orm/better-sqlite3` не импортируется (его driver.js тянет нативный пакет). +Проверено: мигратор drizzle, `returning`, `Date`, JSON, boolean, bigint (id чата +9007199254740991), связи `db.query…with`, upsert, синхронная транзакция с откатом; +**async-колбэк транзакции прослойка отклоняет с понятной ошибкой** (вместо тихой потери +атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется +штатным `drizzle-orm/node-sqlite`. + ### Схема и данные на SQLite (`bench/sqlite/schema-port`) - Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`, @@ -148,6 +179,10 @@ AskUserQuestion — ещё и человека; 0,4 с на старт tsx се `for update skip locked` (core/incidents.ts — не нужно, `BEGIN IMMEDIATE` и так сериализует писателей), `count(*)::int` (monitor/incidents). `->>`, `lower()`, `like`, `returning`, `on conflict` в SQLite есть. +- **Ловушка: `->>` возвращает число.** В Postgres `params->>'chat_id'` — текст, в SQLite — + значение JSON-типа (число). `core/telegram.ts` сравнивает его со строкой — на SQLite + такой фильтр ничего не найдёт; нужен `cast(… as text)` или сравнение с числом + (проверено в `drizzle-check.ts`). ## Решения @@ -187,10 +222,11 @@ FIFO-очередь записи без хвостов — нужен тольк подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала. -### 4. Поэтапно: Bun → SQLite → Docker +### 4. Поэтапно: Node без tsx → SQLite → Docker -Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; даёт ускорение хука в -10 раз сразу. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме +Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; ускоряет старт каждого +процесса (хук — в разы). Код должен проходить `erasableSyntaxOnly`: Node снимает только +типы, parameter properties, `enum`, `namespace` с кодом не поддерживаются. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме только чтения как откатом. Этап 3 зависит от PEP-17/PEP-18: раннеры (tmux + claude + рабочие копии) должны видеть тот же файл базы на локальном диске; самый простой вариант — сервисы и раннеры в одном контейнере с томами хоста. @@ -201,15 +237,17 @@ FIFO-очередь записи без хвостов — нужен тольк метрикой «время записи p99» в heartbeat, порог алерта 1 с. - **Повреждение/потеря файла** — WAL устойчив к падению процесса; ежедневная копия `VACUUM INTO` (7 штук) и копия перед переносом. -- **Next.js под Bun** — dev-режим работает (проверено), но `bun --bun` для Next официально - экспериментальный; запасной вариант — веб на Node, остальное на Bun: SQLite это не мешает - (`node:sqlite` в Node 26 работает с тем же файлом, замерено). +- **Next.js** остаётся как есть (свой компилятор TS); `node:sqlite` работает в серверном + коде Next на Node 26 так же, как в остальных процессах. +- **Прослойка drizzle ↔ node:sqlite** — своя, хоть и маленькая; покрыта проверками + `drizzle-check.ts`, при переходе на drizzle 1.0 заменяется штатным драйвером. - **Bugsink** держит свою базу в контейнере `peppa-postgres` — контейнер нельзя удалить, пока Bugsink не переведён (отдельная задача; Bugsink умеет SQLite). - `better-sqlite3` под Node 26 нет готовых бинарников (сборка node-gyp из исходников, - версия 12.x не собирается вовсе) — в Docker на Node это лишняя сборка; `bun:sqlite` и - `node:sqlite` встроены. + версия 12.x не собирается вовсе) — поэтому `node:sqlite`, он встроен. -## Открытые вопросы +## Решение PM -См. «Решения PM» в proposal.md. +Одобрено 2026-11-13 (approval #41) с изменением рантайма: Node 26 + `node:sqlite` вместо +Bun; каждый процесс пишет сам; Postgres остаётся только для Bugsink (перевод — отдельная +задача). Этап 2 начинается после мержа PEP-38 (переделка `apps/web`). diff --git a/openspec/changes/pep-36-lightweight-stack/proposal.md b/openspec/changes/pep-36-lightweight-stack/proposal.md index 1e084be8..a4a91726 100644 --- a/openspec/changes/pep-36-lightweight-stack/proposal.md +++ b/openspec/changes/pep-36-lightweight-stack/proposal.md @@ -1,67 +1,56 @@ -# Proposal: PEP-36 — легковесный стек: Bun + SQLite, запуск одной командой +# Proposal: PEP-36 — легковесный стек: Node 26 без сборки + SQLite, запуск одной командой Задача Пеппы: **PEP-36** · Цель «Безопасность и эксплуатация». ## Why Пеппу сейчас поднимают Node + tsx + pnpm + Postgres в docker + `next build`. Для одной -машины это тяжело: отдельный контейнер БД, сборка веба после каждой правки, медленный -старт процессов (хук Claude — это новый процесс tsx на каждое событие, ~0,44 с только на -старт). PM решил (2026-11-13): вся Пеппа на Bun + SQLite (WAL), Postgres — только как -дополнение там, где SQLite не тянет параллельные записи; переписку чатов долго не храним. +машины это тяжело: отдельный контейнер БД, медленный старт процессов (хук Claude — новый +процесс tsx на каждое событие, ~0,44 с только на старт). Перед переездом нужно было +ответить: выдержит ли один файл SQLite записи из многих процессов (веб, бот, вачдог, хуки +и MCP каждого раннера), чем заменить LISTEN/NOTIFY и что сломается без tsx. Замер сделан +(`bench/sqlite`, цифры в design.md). -Перед переездом нужно было ответить на вопрос: выдержит ли один файл SQLite записи из -многих процессов (веб, бот, вачдог, хуки и MCP каждого раннера), чем заменить -LISTEN/NOTIFY и что сломается под Bun. Замер сделан (`bench/sqlite`, цифры в design.md). +## Решение PM (2026-11-13, approval #41) + +- Вся Пеппа на **SQLite (WAL)**; **каждый процесс пишет сам** (WAL + `busy_timeout`), без + сервиса-писателя. +- Рантайм — **Node 26 со встроенным TypeScript** (снятие типов) и **`node:sqlite`**, не Bun. + От tsx уходим. Next.js остаётся как есть. +- Postgres остаётся **только для Bugsink**; перевод Bugsink — отдельная задача. ## What Changes -Рекомендация по замеру — **переезжать целиком, поэтапно**; Postgres для Пеппы не нужен. - -- **Этап 1 — Bun вместо tsx** (без смены БД): обёртки бинарей, launchd, тесты на - `bun test`. Текущий код уже работает под Bun без правок (CLI, хук, MCP, бот, e2e бота). - Хук стартует за 0,04 с вместо 0,44 с. +- **Этап 1 — Node без tsx** (без смены БД): `erasableSyntaxOnly` в tsconfig и правка кода, + который Node не может просто очистить от типов (parameter properties и т. п.); bin-обёртки, + скрипты, CI и `install-launchd.sh` — `node` вместо `tsx`; тесты — `node --test`. - **Этап 2 — SQLite вместо Postgres**: схема на `sqlite-core` (одна базовая миграция - вместо 12), каждый процесс открывает файл сам (WAL + `busy_timeout`), без отдельного - сервиса-писателя; LISTEN/NOTIFY → журнал `events` с курсором + сигнал по unix-сокету + - опрос раз в секунду как страховка; перенос данных командой со сверкой; ежедневная копия. -- **Этап 3 — `docker compose up`**: один образ на Bun для веба, бота и вачдога; база и + вместо 12), драйвер `node:sqlite` через тонкую прослойку под сессию drizzle (готового + драйвера в стабильном drizzle 0.45 нет, better-sqlite3 под Node 26 собирается из + исходников — не берём); каждый процесс открывает файл сам; LISTEN/NOTIFY → журнал + `events` с курсором + сигнал по unix-сокету + опрос раз в секунду; перенос данных + командой со сверкой; ежедневная копия. Начинается после мержа PEP-38 (переделка `apps/web`). +- **Этап 3 — `docker compose up`**: один образ `node:26` для веба, бота и вачдога; база и рабочие копии в томах хоста. Связан с PEP-17 (песочница) и PEP-18 (деплой). -Вне scope: переезд Bugsink (у него своя база в контейнере Postgres, см. «Решения PM»), -хранение чатов (PM: долго не храним). +Вне scope: перевод Bugsink с Postgres (PEP-63), хранение чатов (PM: долго не храним). ## Capabilities ### New Capabilities -- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Bun, запуск одной командой. +- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Node без сборки, запуск одной командой. ### Modified Capabilities - `service-monitoring`: health-эндпоинт проверяет файл SQLite вместо Postgres. ## Impact -- `packages/db` (схема, клиент, миграции), `packages/core/src/notify.ts`, `core/tasks.ts` - (транзакция), `core/incidents.ts` (`for update skip locked`), `apps/bot` (подписка), - `apps/web` (живые обновления, health), `packages/testkit` (БД тестов), bin-обёртки, - `scripts/install-launchd.sh`, `infra/`. -- Зависимости: −`postgres`, −`tsx` (после этапа 1), +Bun ≥ 1.4 на машине или в образе. -- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос занимает доли секунды). - -## Решения PM - -1. **Переезд целиком или гибрид?** Рекомендация: целиком. Замер не нашёл места, где - Postgres нужен: при 20 раннерах и нагрузке до ×50 запись в SQLite в 25–50 раз (по медиане) - быстрее, без единой блокировки. Postgres можно вернуть точечно, если появится - нагрузка другого порядка (например, хранение чатов в больших объёмах). -2. **Как развести записи многих процессов?** Рекомендация: каждый процесс пишет сам - (WAL + `busy_timeout` + `BEGIN IMMEDIATE`), без сервиса-писателя. Писатель по сокету - медленнее (лишний переход), добавляет точку отказа и не нужен при наших частотах. -3. **Замена LISTEN/NOTIFY**: журнал `events` с курсором + сигнал по unix-сокету от - записавшего процесса + опрос раз в секунду. fs.watch отвергнут: на macOS теряет события. -4. **Bugsink**: его база `bugsink` живёт в том же контейнере `peppa-postgres`. Оставить - контейнер только под Bugsink или перевести Bugsink на его встроенный SQLite (отдельная - задача)? Рекомендация: отдельная задача, контейнер пока остаётся для Bugsink. -5. **Порядок**: этап 1 (Bun) можно делать сразу — он обратим и не трогает данные. Этап 2 - — после этапа 1, с неделей отката на Postgres в режиме только чтения. Этап 3 — после - решений PEP-17/PEP-18 о том, где живут раннеры. +- Этап 1: `tsconfig.base.json`, классы с parameter properties, `packages/*/bin/*`, + `apps/bot/bin/*`, `package.json` (скрипты), `.gitea/workflows/ci.yml`, `scripts/ci.sh`, + `scripts/install-launchd.sh`. Перевыкатка launchd-агентов — PM. +- Этап 2: `packages/db` (схема, клиент, миграции), `core/notify.ts`, `core/tasks.ts` + (транзакция), `core/incidents.ts` (`for update skip locked`), `core/telegram.ts` + (`->>` возвращает число), `apps/bot` (подписка), `apps/web` (живые обновления, health), + `packages/testkit` (БД тестов). +- Зависимости: −`tsx` (этап 1), −`postgres` (этап 2); нужен Node ≥ 26. +- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос — доли секунды). diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md index 1a43aad8..14bf7044 100644 --- a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md +++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md @@ -2,7 +2,7 @@ ## Purpose -Описывает, где Пеппа хранит свои данные после переезда на Bun + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой. +Описывает, где Пеппа хранит свои данные после переезда на Node 26 + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой. ## ADDED Requirements @@ -68,21 +68,26 @@ - **WHEN** вачдог делает копию - **THEN** неполная копия удалена, админы платформы получают сообщение «резервная копия не сделана: нет места», сервисы продолжают работать -### Requirement: Сервисы Пеппы на Bun -Веб (режим разработки Next.js без сборки), бот, вачдог, `peppa-hook`, `peppa-mcp` и CLI SHALL запускаться под Bun без tsx и pnpm. Хук SHALL стартовать и закончить запись события быстрее 150 мс. +### Requirement: Сервисы Пеппы на Node без сборки +Бот, вачдог, `peppa-hook`, `peppa-mcp`, CLI и тесты SHALL запускаться командой `node` (Node ≥ 26) прямо из исходников на TypeScript, без tsx и без шага сборки; веб SHALL работать на Next.js как раньше. Код SHALL проходить проверку типов с `erasableSyntaxOnly`. Хук SHALL стартовать и закончить запись события быстрее 300 мс. #### Scenario: Хук на каждое событие - **GIVEN** раннер «PEP-42» работает, Claude вызывает хук Stop - **WHEN** `peppa-hook stop` получает событие -- **THEN** событие `turn_end` записано, хук завершился быстрее 150 мс +- **THEN** событие `turn_end` записано, хук завершился быстрее 300 мс, в stderr хука нет предупреждений Node -#### Scenario: Нет Bun на машине -- **GIVEN** на машине не установлен Bun +#### Scenario: Старый Node на машине +- **GIVEN** на машине Node 22 - **WHEN** администратор запускает `peppa status` -- **THEN** команда печатает «нужен Bun ≥ 1.4: https://bun.sh» и завершается с кодом 1 +- **THEN** команда печатает «нужен Node ≥ 26» и завершается с кодом 1 + +#### Scenario: Синтаксис, который Node не умеет снять +- **GIVEN** в `packages/core` добавлен класс с parameter property `constructor(private db: Db)` +- **WHEN** запускается проверка типов +- **THEN** проверка падает с ошибкой `erasableSyntaxOnly` на этой строке ### Requirement: Запуск одной командой -Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Bun: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске. +Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Node 26: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске. #### Scenario: Первый запуск - **GIVEN** чистая машина с Docker, заполненный `.env` diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md index 18d162fe..50e05236 100644 --- a/openspec/changes/pep-36-lightweight-stack/tasks.md +++ b/openspec/changes/pep-36-lightweight-stack/tasks.md @@ -7,30 +7,34 @@ - [x] 0.3 Прототипы замены LISTEN/NOTIFY: опрос с курсором, fs.watch WAL, push по unix-сокету - [x] 0.4 Текущий код под Bun: CLI, `peppa-hook`, `peppa-mcp`, бот, e2e (`bun test`), `next dev` - [x] 0.5 Прототип схемы на sqlite (`bench/sqlite/schema-port`): базовая миграция, перенос боевых данных, проверка транзакций drizzle -- [ ] 0.6 Решение PM по «Решениям PM» в proposal.md (request_approval) +- [x] 0.6 Решение PM (approval #41): SQLite, каждый процесс пишет сам; рантайм Node 26 + `node:sqlite` вместо Bun; Postgres только для Bugsink +- [x] 0.7 Драйвер drizzle ↔ `node:sqlite`: прослойка `schema-port/node-sqlite-driver.ts` + `drizzle-check.ts`; замер node:sqlite против bun:sqlite через drizzle +- [x] 0.8 Отдельная задача: перевод Bugsink с Postgres — PEP-63 -## 1. Этап 1 — Bun вместо tsx (без смены БД) +## 1. Этап 1 — Node 26 без tsx (без смены БД) -- [ ] 1.1 Обёртки `packages/*/bin/*` и `apps/bot/bin/*`: `bun` вместо `tsx`, проверка версии Bun (≥ 1.4) с понятной ошибкой -- [ ] 1.2 Тесты: `bun test` вместо `tsx --test` (node:test работает в Bun); прогнать весь e2e, починить расхождения -- [ ] 1.3 launchd-агенты бота и вачдога на Bun; веб — `bun --bun next dev`/`next start` по итогам проверки 0.4 -- [ ] 1.4 Замер хука на живой машине: старт и запись события (цель < 150 мс) +- [ ] 1.1 `erasableSyntaxOnly` в `tsconfig.base.json`; переписать parameter properties, `enum` и прочее, что Node не может очистить от типов; `typecheck` зелёный +- [ ] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx`; проверка версии Node (≥ 26) с понятной ошибкой +- [ ] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`.gitea/workflows/ci.yml`, `scripts/ci.sh`); `tsx` убрать из зависимостей +- [ ] 1.4 `scripts/install-launchd.sh` — без tsx; на машине не перевыкатывать (деплой — PM), в PR перечислить, что перевыкатить +- [ ] 1.5 Весь e2e на своей `PEPPA_TEST_DB`; замер старта `peppa-hook` (цель < 300 мс) ## 2. Этап 2 — SQLite вместо Postgres -- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `bun:sqlite`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON` +- [ ] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`) +- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON` - [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции - [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async` -- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` и `lower()` работают как есть +- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть - [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме - [ ] 2.6 `peppa db migrate-to-sqlite <file>`: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении - [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл - [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude) -- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (Bugsink остаётся на своём Postgres или переезжает отдельно) +- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63) ## 3. Этап 3 — запуск одной командой -- [ ] 3.1 Образ на `oven/bun` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста +- [ ] 3.1 Образ на `node:26` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста - [ ] 3.2 Согласовать с PEP-17 (песочница) и PEP-18 (деплой): где живут раннеры, как контейнер видит рабочие копии и токены - [ ] 3.3 `docker compose up` на чистой машине → health 200 за минуту; документация в README и `/help` - [ ] 3.4 Отказ запуска, если база на сетевом диске -- 2.45.2 From d3a54fc8458b465eaf1c1849c6d12d542cde3c8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:25:05 +0500 Subject: [PATCH 017/536] =?UTF-8?q?PEP-38:=20runners=20console=20=E2=80=94?= =?UTF-8?q?=20filter=20counters,=20search,=20limit=20resume=20time,=20deta?= =?UTF-8?q?ils=20panel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/app/(app)/help/page.tsx | 2 +- apps/web/app/(app)/runners/page.tsx | 110 +++++++++---- apps/web/components/LocalTime.tsx | 24 +++ apps/web/components/RunnerConsole.tsx | 146 ++++++++++++++++++ apps/web/components/Workspace.tsx | 7 +- apps/web/lib/queries.ts | 5 + .../changes/pep-38-factory-console/tasks.md | 8 +- 7 files changed, 265 insertions(+), 37 deletions(-) create mode 100644 apps/web/components/LocalTime.tsx create mode 100644 apps/web/components/RunnerConsole.tsx diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 6c792523..d1375129 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -52,7 +52,7 @@ export default async function Help() { <li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.</li> <li><b>Агент</b> — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.</li> <li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.</li> - <li><b>Раннер</b> — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, задача, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры «ждут тебя / работают / остановлены (упали) / завершены».</li> + <li><b>Раннер</b> — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, задача, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).</li> <li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li> </ul> </Section> diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx index 9644c1b3..dca587f2 100644 --- a/apps/web/app/(app)/runners/page.tsx +++ b/apps/web/app/(app)/runners/page.tsx @@ -1,49 +1,101 @@ import Link from "next/link"; -import { listUserSessions, RUNNER_FILTERS, type RunnerFilter } from "@peppa/core"; +import { Search } from "lucide-react"; +import { listUserSessions, RUNNER_FILTERS, type RunnerFilter, type SessionView } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; -import { SessionCard } from "@/components/cards"; import { Empty, Flash, PageHeader } from "@/components/common"; +import { RunnerDetails, RunnerRow } from "@/components/RunnerConsole"; +import { Input } from "@/components/ui/input"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; +import { inbox, sessionEvents } from "@/lib/queries"; import { cn } from "@/lib/utils"; const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [ - { key: undefined, label: "Все" }, - { key: "waiting", label: "Ждут тебя" }, - { key: "working", label: "Работают" }, - { key: "stopped", label: "Остановлены" }, - { key: "finished", label: "Завершены" }, + { key: undefined, label: "все" }, + { key: "waiting", label: "ждут тебя" }, + { key: "working", label: "работают" }, + { key: "stopped", label: "упали" }, + { key: "finished", label: "готово" }, ]; +const inFilter = (s: SessionView, f: RunnerFilter) => (RUNNER_FILTERS[f] as string[]).includes(s.status); +const matches = (s: SessionView, q: string) => + [s.taskKey, s.taskTitle, s.projectKey, s.tmuxName, `#${s.id}`].some((v) => v?.toLowerCase().includes(q)); -export default async function Runners({ searchParams }: { searchParams: Promise<{ error?: string; f?: string }> }) { +type Params = { error?: string; f?: string; q?: string; id?: string }; + +export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) { const user = await requireUser(); - const { error, f } = await searchParams; + const { error, f, q: rawQ, id } = await searchParams; const filter = f && f in RUNNER_FILTERS ? (f as RunnerFilter) : undefined; - const all = await listUserSessions(db, user.id); - const count = (k: RunnerFilter | undefined) => (k ? all.filter((s) => (RUNNER_FILTERS[k] as string[]).includes(s.status)).length : all.length); - const shown = filter ? all.filter((s) => (RUNNER_FILTERS[filter] as string[]).includes(s.status)) : all; - const back = filter ? `/runners?f=${filter}` : "/runners"; + const q = rawQ?.trim().toLowerCase() ?? ""; + const [all, open] = await Promise.all([listUserSessions(db, user.id), inbox(user.id)]); + const asking = new Map<number, typeof open>(); + for (const x of open) if (x.sessionId) asking.set(x.sessionId, [...(asking.get(x.sessionId) ?? []), x]); + const needsPm = (s: SessionView) => s.status === "waiting_input" || asking.has(s.id); + + const found = q ? all.filter((s) => matches(s, q)) : all; + const count = (k: RunnerFilter | undefined) => (k ? found.filter((s) => inFilter(s, k)).length : found.length); + // Who needs the PM first, then live runners, then finished ones; newest first inside each group. + const rank = (s: SessionView) => (needsPm(s) ? 0 : ["done", "failed"].includes(s.status) ? 2 : 1); + const shown = (filter ? found.filter((s) => inFilter(s, filter)) : found).sort((a, b) => rank(a) - rank(b) || b.id - a.id); + + const url = (p: { f?: string; q?: string; id?: number | string }) => { + const sp = new URLSearchParams(); + if (p.f) sp.set("f", p.f); + if (p.q) sp.set("q", p.q); + if (p.id) sp.set("id", String(p.id)); + const s = sp.toString(); + return s ? `/runners?${s}` : "/runners"; + }; + const base = { f: filter, q: rawQ?.trim() || undefined }; + const selected = (id && all.find((s) => s.id === Number(id))) || shown[0]; + const back = url({ ...base, id: selected?.id }); + const aside = selected ? ( + <RunnerDetails s={selected} questions={asking.get(selected.id) ?? []} events={await sessionEvents(selected.id)} back={back} closeHref={url(base)} chosen={!!id} /> + ) : null; + return ( - <Workspace> + <Workspace aside={aside} asideWideOnly={!id}> <AutoRefresh /> <Flash error={error} /> - <PageHeader title="Раннеры">Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.</PageHeader> - <nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Фильтр раннеров"> - {FILTERS.map((x) => ( - <Link - key={x.label} - href={x.key ? `/runners?f=${x.key}` : "/runners"} - aria-current={x.key === filter ? "page" : undefined} - className={cn("rounded-full border px-3 py-1 text-sm text-foreground hover:border-muted-foreground hover:no-underline", x.key === filter && "border-primary bg-primary/10")} - > - {x.label} <span className="font-mono text-xs text-muted-foreground">{count(x.key)}</span> - </Link> - ))} - </nav> - <div className="flex flex-col gap-2.5"> - {shown.length === 0 ? <Empty>{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</Empty> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} + <PageHeader title="Раннеры">Агенты в tmux по задачам твоих и общих проектов: кто ждёт тебя, кто работает, что готово.</PageHeader> + <div className="mb-3 flex flex-col gap-3 lg:flex-row lg:items-center"> + <nav className="flex flex-wrap gap-1.5" aria-label="Фильтр раннеров"> + {FILTERS.map((x) => { + const n = count(x.key); + const active = x.key === filter; + return ( + <Link + key={x.label} + href={url({ ...base, f: x.key })} + aria-current={active ? "page" : undefined} + className={cn( + "flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline", + active && "border-primary/60 bg-primary/10 text-foreground", + )} + > + <span className={cn("font-mono font-semibold tabular-nums", x.key === "waiting" && n > 0 ? "text-primary" : "text-foreground")}>{n}</span> + {x.label} + </Link> + ); + })} + </nav> + <form action="/runners" className="relative lg:ml-auto lg:w-64" role="search"> + {filter && <input type="hidden" name="f" value={filter} />} + <Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" /> + <Input type="search" name="q" defaultValue={rawQ ?? ""} placeholder="Задача, проект, tmux…" aria-label="Поиск раннеров" className="h-8 pl-8" /> + </form> </div> + {shown.length === 0 ? ( + <Empty>{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</Empty> + ) : ( + <ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5"> + {shown.map((s) => ( + <RunnerRow key={s.id} s={s} href={url({ ...base, id: s.id })} selected={s.id === selected?.id && (id ? true : "wide")} needsPm={needsPm(s)} /> + ))} + </ul> + )} </Workspace> ); } diff --git a/apps/web/components/LocalTime.tsx b/apps/web/components/LocalTime.tsx new file mode 100644 index 00000000..9bd49e62 --- /dev/null +++ b/apps/web/components/LocalTime.tsx @@ -0,0 +1,24 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +/** HH:MM (with the date when not today) in the viewer's time zone; the server renders its own zone first. */ +export function LocalTime({ iso }: { iso: string }) { + const d = new Date(iso); + const today = new Date().toDateString() === d.toDateString(); + const time = d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }); + return ( + <time dateTime={iso} suppressHydrationWarning> + {today ? time : `${d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" })} ${time}`} + </time> + ); +} + +/** On narrow screens the side panel sits under the list: bring the chosen runner into view. */ +export function ScrollIntoViewOnNarrow({ id }: { id: string | number }) { + const ref = useRef<HTMLSpanElement>(null); + useEffect(() => { + if (window.matchMedia("(max-width: 1279px)").matches) ref.current?.scrollIntoView({ block: "start" }); + }, [id]); + return <span ref={ref} className="block scroll-mt-16" />; +} diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx new file mode 100644 index 00000000..7fd70724 --- /dev/null +++ b/apps/web/components/RunnerConsole.tsx @@ -0,0 +1,146 @@ +// Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner. +import Link from "next/link"; +import { SquareTerminal, X } from "lucide-react"; +import type { SessionView } from "@peppa/core"; +import { MAX_LIMIT_RESUMES_PER_DAY } from "@peppa/runner"; +import { PanelSection } from "@/components/ActivityAside"; +import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards"; +import { ago, Key, StatusBadge } from "@/components/common"; +import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime"; +import type { InboxItem } from "@/lib/queries"; +import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status"; +import { cn } from "@/lib/utils"; + +/** «остановлена · продолжит в 03:10» for a runner that hit the usage limit (PEP-56). */ +export function LimitNote({ s }: { s: SessionView }) { + if (s.status !== "rate_limited") return null; + if (!s.resumeAt) return <>остановлена · лимит</>; + if (s.resumeAt.getTime() <= Date.now()) return <>остановлена · продолжит сейчас</>; + return ( + <> + остановлена · продолжит в <LocalTime iso={s.resumeAt.toISOString()} /> + </> + ); +} + +/** `selected`: "wide" — picked by default, highlighted only where the side panel is visible. */ +export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) { + const limited = s.status === "rate_limited"; + const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const }; + return ( + <li> + <Link + href={href} + scroll={false} + aria-current={selected === true ? "true" : undefined} + className={cn( + "group grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 gap-y-0.5 rounded-md border border-transparent px-3 py-2.5 text-sm text-foreground transition-colors hover:bg-accent hover:no-underline", + needsPm && "bg-primary/[0.07] shadow-[inset_2px_0_0_var(--primary)]", + selected === true && "border-border bg-accent", + selected === "wide" && "xl:border-border xl:bg-accent", + )} + > + <span className={cn("row-span-2 size-2 self-start mt-1.5 rounded-full", TONE_BG[st.tone], (s.status === "running" || s.status === "starting") && "animate-pulse")} /> + <span className="flex min-w-0 items-baseline gap-2"> + <span className="shrink-0 font-mono text-xs text-primary">{s.taskKey ?? s.projectKey}</span> + <span className="truncate">{s.taskTitle ?? "без задачи"}</span> + </span> + <span className={cn("text-right font-mono text-xs whitespace-nowrap", TONE_TEXT[st.tone])}>{limited ? ( + <> + <span className="sm:hidden">{st.label}</span> + <span className="max-sm:hidden"> + <LimitNote s={s} /> + </span> + </> + ) : ( + st.label + )} + </span> + <span className="truncate font-mono text-[11px] text-muted-foreground"> + {s.projectKey} · {s.provider} · #{s.id} · {s.tmuxName} + </span> + <span className="text-right font-mono text-[11px] whitespace-nowrap text-muted-foreground">{ago(s.lastActivityAt)}</span> + {limited && ( + <span className="col-span-2 col-start-2 font-mono text-[11px] text-warn sm:hidden"> + <LimitNote s={s} /> + </span> + )} + </Link> + </li> + ); +} + +export function RunnerDetails({ s, questions, events, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; back: string; closeHref: string; chosen: boolean }) { + return ( + <div className="flex flex-col gap-5"> + {/* Picked from the list: on narrow screens the panel is under it, scroll there. */} + {chosen && <ScrollIntoViewOnNarrow id={s.id} />} + <header className="flex flex-col gap-2"> + <div className="flex items-center gap-2"> + <StatusBadge status={s.status} kind="session" /> + <span className="font-mono text-xs text-muted-foreground">#{s.id}</span> + <Link href={closeHref} scroll={false} aria-label="Закрыть" title="Закрыть" className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"> + <X className="size-4" /> + </Link> + </div> + <h2 className="m-0 text-base leading-snug font-semibold"> + {s.taskKey && <Key href={`/t/${s.taskKey}`} className="mr-1.5">{s.taskKey}</Key>} + {s.taskTitle ?? "без задачи"} + </h2> + {s.status === "rate_limited" && ( + <p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm"> + <LimitNote s={s} /> + <span className="block text-xs text-muted-foreground"> + авто-продолжений сегодня: {s.limitResumes} из {MAX_LIMIT_RESUMES_PER_DAY} + </span> + </p> + )} + </header> + + <dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm"> + <dt className="text-muted-foreground">Проект</dt> + <dd className="m-0"> + <Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key> + </dd> + <dt className="text-muted-foreground">Агент</dt> + <dd className="m-0">{s.provider === "codex" ? "Codex" : "Claude Code"} · поколение {s.generation}</dd> + <dt className="text-muted-foreground">Запущен</dt> + <dd className="m-0">{ago(s.startedAt)}</dd> + <dt className="text-muted-foreground">Активность</dt> + <dd className="m-0">{ago(s.lastActivityAt)}</dd> + </dl> + + <AttachCommand name={s.tmuxName} /> + <SessionActions s={s} back={back} /> + + {questions.length > 0 && ( + <PanelSection title="Ждёт ответа" count={questions.length}> + {questions.map((q) => ( + <QuestionCard key={q.id} q={q} taskKey={s.taskKey} taskStatus={q.taskStatus} back={back} compact /> + ))} + </PanelSection> + )} + + <PanelSection title="Терминал"> + <div className="flex min-h-40 flex-col items-center justify-center gap-2 rounded-lg border border-dashed bg-background/60 p-4 text-center font-mono text-xs text-muted-foreground"> + <SquareTerminal className="size-6" /> + Живой терминал раннера появится здесь (PEP-9). + <span>Пока — команда tmux attach выше, на машине Пеппы.</span> + </div> + </PanelSection> + + {events.length > 0 && ( + <PanelSection title="События"> + <ol className="m-0 flex list-none flex-col gap-1.5 border-l p-0 pl-3"> + {events.map((e) => ( + <li key={e.id} className="text-xs [overflow-wrap:anywhere]"> + <span className="font-mono text-muted-foreground">{ago(e.createdAt)}</span> <span className="font-mono text-primary">{e.type}</span>{" "} + {e.type === "progress" ? (e.payload as { text: string }).text : ""} + </li> + ))} + </ol> + </PanelSection> + )} + </div> + ); +} diff --git a/apps/web/components/Workspace.tsx b/apps/web/components/Workspace.tsx index 2ea900f4..30bb2a48 100644 --- a/apps/web/components/Workspace.tsx +++ b/apps/web/components/Workspace.tsx @@ -1,13 +1,14 @@ import type { ReactNode } from "react"; import { ActivityAside } from "@/components/ActivityAside"; import { Footer } from "@/components/Footer"; +import { cn } from "@/lib/utils"; /** * Centre + right panel of the console (PEP-38). The page decides what the right panel shows; * without `aside` it gets the default activity panel, `aside={null}` hides it. - * Below xl the panel goes under the page content, the footer is always last. + * Below xl the panel goes under the page content (`asideWideOnly`: shown on xl only), the footer is always last. */ -export function Workspace({ children, aside }: { children: ReactNode; aside?: ReactNode }) { +export function Workspace({ children, aside, asideWideOnly = false }: { children: ReactNode; aside?: ReactNode; asideWideOnly?: boolean }) { const panel = aside === undefined ? <ActivityAside /> : aside; return ( <div className="grid flex-1 xl:grid-cols-[minmax(0,1fr)_360px] xl:grid-rows-[1fr_auto]"> @@ -15,7 +16,7 @@ export function Workspace({ children, aside }: { children: ReactNode; aside?: Re <div className="mx-auto w-full max-w-5xl">{children}</div> </main> {panel && ( - <aside aria-label="Панель" className="min-w-0 border-t bg-sidebar/60 px-4 py-5 xl:sticky xl:top-0 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:h-dvh xl:overflow-y-auto xl:border-t-0 xl:border-l"> + <aside aria-label="Панель" className={cn(asideWideOnly && "max-xl:hidden", "min-w-0 border-t bg-sidebar/60 px-4 py-5 xl:sticky xl:top-0 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:h-dvh xl:overflow-y-auto xl:border-t-0 xl:border-l")}> {panel} </aside> )} diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index 8c72f872..cac7be72 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -85,3 +85,8 @@ export async function navCounts(userId: number): Promise<{ questions: number; wa const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input"))); return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0 }; } + +/** Latest events of one runner, newest first (runner details panel, PEP-38). */ +export async function sessionEvents(sessionId: number, limit = 12) { + return db.select().from(events).where(eq(events.sessionId, sessionId)).orderBy(desc(events.id)).limit(limit); +} diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/pep-38-factory-console/tasks.md index 82c64687..f769d0ec 100644 --- a/openspec/changes/pep-38-factory-console/tasks.md +++ b/openspec/changes/pep-38-factory-console/tasks.md @@ -16,10 +16,10 @@ - [x] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере ## 3. Пульт раннеров (PR 3) -- [ ] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой -- [ ] 3.2 «остановлена · продолжит в HH:MM» по `resume_at` -- [ ] 3.3 Правая панель: детали выбранного раннера, вопросы, действия, заглушка терминала -- [ ] 3.4 Помощь обновлена; проверка в браузере +- [x] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой +- [x] 3.2 «остановлена · продолжит в HH:MM» по `resume_at` +- [x] 3.3 Правая панель: детали выбранного раннера, вопросы, действия, заглушка терминала +- [x] 3.4 Помощь обновлена; проверка в браузере ## 4. Завершение - [ ] 4.1 `openspec archive`, задача в review с pr_url -- 2.45.2 From 4c4b3a482fbce417ffbffce41c302a9a6ba65276 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:44:58 +0500 Subject: [PATCH 018/536] PEP-38: archive OpenSpec change pep-38-factory-console Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../design.md | 0 .../proposal.md | 0 .../specs/web-workspace/spec.md | 0 .../tasks.md | 2 +- openspec/specs/web-workspace/spec.md | 65 ++++++++++++++++++- 5 files changed, 63 insertions(+), 4 deletions(-) rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/design.md (100%) rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/proposal.md (100%) rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/specs/web-workspace/spec.md (100%) rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/tasks.md (96%) diff --git a/openspec/changes/pep-38-factory-console/design.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/design.md similarity index 100% rename from openspec/changes/pep-38-factory-console/design.md rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/design.md diff --git a/openspec/changes/pep-38-factory-console/proposal.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/proposal.md similarity index 100% rename from openspec/changes/pep-38-factory-console/proposal.md rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/proposal.md diff --git a/openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/specs/web-workspace/spec.md similarity index 100% rename from openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/specs/web-workspace/spec.md diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/tasks.md similarity index 96% rename from openspec/changes/pep-38-factory-console/tasks.md rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/tasks.md index f769d0ec..1c00b4f6 100644 --- a/openspec/changes/pep-38-factory-console/tasks.md +++ b/openspec/changes/archive/2026-11-13-pep-38-factory-console/tasks.md @@ -22,4 +22,4 @@ - [x] 3.4 Помощь обновлена; проверка в браузере ## 4. Завершение -- [ ] 4.1 `openspec archive`, задача в review с pr_url +- [x] 4.1 `openspec archive`, задача в review с pr_url diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md index 548e579e..1ccc4c4d 100644 --- a/openspec/specs/web-workspace/spec.md +++ b/openspec/specs/web-workspace/spec.md @@ -100,22 +100,81 @@ - **THEN** рядом с хэшем видна пометка «+изменения» ### Requirement: Верхнее меню -Веб SHALL показывать верхнее меню с пунктами «Главная», «Проекты», «Раннеры», «Помощь» и подсвечивать текущий раздел. +Веб SHALL показывать меню навигации с пунктами «Главная», «Проекты», «Раннеры», «Помощь», «Настройки» и подсвечивать текущий раздел; на десктопе меню — левая панель, на узком экране — панель вкладок снизу. #### Scenario: Главная - **GIVEN** вошедший пользователь - **WHEN** он открывает корень сайта - **THEN** в меню подсвечен пункт «Главная», пункта «Входящие» нет +#### Scenario: Задача проекта +- **GIVEN** вошедший пользователь +- **WHEN** он открывает страницу задачи «PAY-3» +- **THEN** в меню подсвечен пункт «Проекты» + ### Requirement: Список раннеров -Страница «Раннеры» SHALL показывать раннеры всех проектов пользователя (своих и общих) со статусом, проектом и задачей, агентом, временем последней активности и действиями, с фильтрами по состоянию. +Страница «Раннеры» SHALL показывать в центре раннеры всех проектов пользователя (своих и общих) со статусом, проектом и задачей, агентом и временем последней активности, с фильтрами-счётчиками по состоянию и поиском, а справа — детали выбранного раннера с действиями. #### Scenario: Раннер ждёт ответа - **GIVEN** у пользователя раннер по задаче PAY-3 в статусе «ждёт тебя» и раннер по PAY-4 «работает» - **WHEN** он открывает «Раннеры» и выбирает фильтр «ждут тебя» -- **THEN** в списке только раннер PAY-3 со ссылкой на задачу и кнопкой ответа +- **THEN** в списке только раннер PAY-3, строка подсвечена, у фильтра счётчик 1 #### Scenario: Чужие раннеры - **GIVEN** раннер в проекте, где пользователь не владелец и не участник - **WHEN** пользователь открывает «Раннеры» - **THEN** этого раннера в списке нет + +#### Scenario: Поиск +- **GIVEN** раннеры по задачам PAY-3 «Оплата картой» и PAY-4 «Возвраты» +- **WHEN** пользователь ищет «возвр» +- **THEN** в списке только раннер PAY-4 + +#### Scenario: Лимит +- **GIVEN** раннер в статусе «лимит» с временем продолжения 03:10 +- **WHEN** пользователь открывает «Раннеры» +- **THEN** в строке раннера написано «остановлена · продолжит в 03:10» + +#### Scenario: Детали раннера +- **GIVEN** раннер по задаче PAY-3 ждёт ответа на вопрос +- **WHEN** пользователь выбирает его в списке +- **THEN** справа видны статус, задача, агент, команда tmux attach, вопрос с формой ответа, кнопки «Остановить» и сообщение в сессию, и место под терминал + +### Requirement: Раскладка пульта +Веб SHALL показывать вошедшему пользователю раскладку в три панели: слева навигация, в центре страница, справа контекстная панель; на узком экране разделы — панель вкладок снизу, а правая панель уходит под центр. + +#### Scenario: Десктоп +- **GIVEN** вошедший пользователь на экране шириной 1440 px +- **WHEN** он открывает любую страницу за входом +- **THEN** слева видна навигация «Главная», «Проекты», «Раннеры», «Помощь», «Настройки», в центре — страница, справа — контекстная панель + +#### Scenario: Телефон +- **GIVEN** вошедший пользователь на экране шириной 390 px +- **WHEN** он открывает Главную +- **THEN** разделы — панель вкладок внизу экрана, страница не прокручивается по горизонтали, правая панель — под содержимым + +### Requirement: Счётчик «ждут тебя» +Навигация SHALL показывать у пункта «Главная» число открытых вопросов агентов по проектам пользователя, а у пункта «Раннеры» — число раннеров, ждущих PM. + +#### Scenario: Есть вопросы +- **GIVEN** в проектах пользователя 3 неотвеченных вопроса и 1 раннер в статусе «ждёт тебя» +- **WHEN** он открывает любую страницу +- **THEN** у «Главная» стоит счётчик 3, у «Раннеры» — 1 + +#### Scenario: Ничего не ждёт +- **GIVEN** открытых вопросов и ждущих раннеров нет +- **WHEN** пользователь открывает любую страницу +- **THEN** счётчиков в навигации нет + +### Requirement: Тема оформления +Веб SHALL открываться в тёмной теме по умолчанию и позволять переключиться на светлую; выбор SHALL сохраняться между визитами. + +#### Scenario: Первый визит +- **GIVEN** пользователь ни разу не переключал тему +- **WHEN** он открывает веб +- **THEN** страница в тёмной теме + +#### Scenario: Светлая тема сохраняется +- **GIVEN** пользователь переключил тему на светлую +- **WHEN** он закрывает и снова открывает веб +- **THEN** страница в светлой теме без мигания тёмной -- 2.45.2 From 8dc82859c7396ba728b0b9a2a8acb5b09a1f214b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:51:22 +0500 Subject: [PATCH 019/536] PEP-36 stage 1: run Peppa with Node 26 type stripping instead of tsx - tsconfig: erasableSyntaxOnly + verbatimModuleSyntax; parameter properties rewritten (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError, TelegramApi, MockGitea) - bin wrappers (peppa, peppa-mcp, peppa-hook, peppa-bot, testkit mocks, peppa-dev): `node --import scripts/lib/require-node.mjs` (clear error on Node < 26, PEPPA_NODE overrides the binary); package scripts and tests on `node` / `node --test`; tsx removed - install-launchd.sh pins PEPPA_NODE (checked absolute path) in the plists - fix a race the faster hooks exposed: the prompt hook answered every pending question, including a PM question raised after Peppa itself pasted text into the terminal; sendToSession now logs `input_sent` and the hook only answers questions older than that input - change pep-36-lightweight-stack: stage 1 done, hook start numbers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 6 ++--- apps/bot/bin/peppa-bot | 2 +- apps/bot/package.json | 2 +- apps/bot/src/telegram.ts | 25 +++++++++++-------- apps/web/scripts/mock-ui-seed.ts | 2 +- .../pep-36-lightweight-stack/design.md | 18 +++++++++++-- .../changes/pep-36-lightweight-stack/tasks.md | 10 ++++---- package.json | 1 - packages/bugsink/src/index.ts | 7 +++--- packages/cli/bin/peppa | 2 +- packages/cli/package.json | 2 +- packages/core/src/gitea.ts | 17 +++++++------ packages/core/src/oauth.ts | 9 ++++--- packages/core/src/sessions.ts | 22 ++++++++++++++-- packages/mcp/bin/peppa-mcp | 2 +- packages/mcp/package.json | 2 +- packages/mcp/scripts/call.ts | 2 +- packages/mcp/scripts/smoke.ts | 2 +- packages/runner/bin/peppa-hook | 2 +- packages/runner/src/hook.ts | 8 ++++-- packages/runner/src/sessions.ts | 2 ++ packages/testkit/bin/mock-claude | 2 +- packages/testkit/bin/mock-codex | 2 +- packages/testkit/bin/mock-telegram | 2 +- packages/testkit/bin/mock-triage | 2 +- packages/testkit/bin/peppa-dev | 2 +- packages/testkit/package.json | 2 +- packages/testkit/src/mock-gitea.ts | 4 ++- packages/testkit/test/monitor.test.ts | 2 +- pnpm-lock.yaml | 3 --- scripts/install-launchd.sh | 10 +++++++- scripts/lib/require-node.mjs | 9 +++++++ tsconfig.base.json | 2 ++ 33 files changed, 124 insertions(+), 63 deletions(-) create mode 100644 scripts/lib/require-node.mjs diff --git a/AGENTS.md b/AGENTS.md index 267cec7b..8ce96f26 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ - `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы - `peppa web login-link <login>` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea - `pnpm typecheck` -- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера +- `node packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера - `pnpm dev:web` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` @@ -65,7 +65,7 @@ - **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу -TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`. +TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`. ## Автономный режим (PEP-7) PM двигает карточки на доске (веб, `/p/<KEY>`): «В работе» запускает агента (`moveTask`), @@ -82,4 +82,4 @@ PM двигает карточки на доске (веб, `/p/<KEY>`): «В р (`template/RULES.md`, MCP `get_rules`): proposal → `request_approval` → одобрение PM → apply → archive → PR/коммит. Работу вне задачи не делаем; новое — `create_task`. Вызов MCP-инструмента из shell (для этой сессии без tmux): -`tsx packages/mcp/scripts/call.ts <tool> '<json>'`. +`node packages/mcp/scripts/call.ts <tool> '<json>'`. diff --git a/apps/bot/bin/peppa-bot b/apps/bot/bin/peppa-bot index 1f7067b7..5a96f3c4 100755 --- a/apps/bot/bin/peppa-bot +++ b/apps/bot/bin/peppa-bot @@ -1,4 +1,4 @@ #!/usr/bin/env bash PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" . "$PEPPA_ROOT/scripts/lib/load-env.sh" -exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@" +exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@" diff --git a/apps/bot/package.json b/apps/bot/package.json index 1dca122c..5e87285a 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -5,7 +5,7 @@ "type": "module", "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, "bin": { "peppa-bot": "./bin/peppa-bot" }, - "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, + "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts index bea22d50..fad604cc 100644 --- a/apps/bot/src/telegram.ts +++ b/apps/bot/src/telegram.ts @@ -31,21 +31,26 @@ export interface InlineButton { } export class TelegramError extends Error { - constructor( - readonly method: string, - readonly code: number, - readonly description: string, - readonly retryAfter?: number, - ) { + readonly method: string; + readonly code: number; + readonly description: string; + readonly retryAfter?: number; + constructor(method: string, code: number, description: string, retryAfter?: number) { super(`${method}: ${code} ${description}`); + this.method = method; + this.code = code; + this.description = description; + this.retryAfter = retryAfter; } } export class TelegramApi { - constructor( - private readonly token: string, - private readonly baseUrl = "https://api.telegram.org", - ) {} + private readonly token: string; + private readonly baseUrl: string; + constructor(token: string, baseUrl = "https://api.telegram.org") { + this.token = token; + this.baseUrl = baseUrl; + } async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> { let res: Response; diff --git a/apps/web/scripts/mock-ui-seed.ts b/apps/web/scripts/mock-ui-seed.ts index fa281db0..68a2246e 100644 --- a/apps/web/scripts/mock-ui-seed.ts +++ b/apps/web/scripts/mock-ui-seed.ts @@ -1,7 +1,7 @@ // Demo data for checking the web UI by eye (PEP-38): a user, two projects, goals, tasks on every board // column, runners in every status (one hit the usage limit and resumes later), open questions, releases. // Only for a throwaway database — refuses the production one: -// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login] +// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui node apps/web/scripts/mock-ui-seed.ts [login] import { mkdirSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md index b889c006..c2b3968c 100644 --- a/openspec/changes/pep-36-lightweight-stack/design.md +++ b/openspec/changes/pep-36-lightweight-stack/design.md @@ -138,8 +138,12 @@ PM выбрал Node 26 со встроенным снятием типов и ` - **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert, 20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс. - **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против - 16–32 мс; но против tsx (0,44 с) это всё равно в 4–6 раз быстрее. Реальный старт - `peppa-hook` на Node без tsx замеряется в этапе 1. + 16–32 мс. Реальный `peppa-hook` на Node 26 без tsx (этап 1): **0,31 с против 0,44 с у + tsx** (Bun — 0,04 с). Почти всё время — загрузка drizzle-orm: `drizzle-orm` ~105 мс + + `pg-core` ~90 мс (сотни мелких ESM-файлов; `NODE_COMPILE_CACHE` даёт лишь ~0,03 с), + `postgres` — 10 мс, свой код — ~40 мс. С `sqlite-core` вместо `pg-core` картина та же + (~75 мс). Если 0,3 с на хук окажется заметным, в этапе 2 хук пишет через `node:sqlite` + напрямую (две-три команды SQL, без drizzle) — оценка ~0,1 с. - `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего лишнего. @@ -157,6 +161,16 @@ better-sqlite3 под Node 26 собирается из исходников (г атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется штатным `drizzle-orm/node-sqlite`. +### Этап 1: найденная гонка «промпт закрывает чужой вопрос» + +С быстрым стартом хука на Node e2e `ci-feedback` («Три неудачи подряд») стал падать в +3 из 5 прогонов (на tsx — 0 из 5). Причина в коде, не в тесте: хук `UserPromptSubmit` +закрывал **все** открытые вопросы сессии ответом «из терминала», в том числе вопрос PM, +созданный уже после того, как Пеппа сама вставила текст (отчёт о красном CI) в терминал. +Исправлено: `sendToSession` пишет событие `input_sent` с текстом до ввода, хук, узнав +этот текст в промпте, закрывает только вопросы, созданные раньше ввода; текст, +набранный человеком, закрывает всё, как раньше. После правки — 6 из 6. + ### Схема и данные на SQLite (`bench/sqlite/schema-port`) - Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`, diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md index 50e05236..ab312704 100644 --- a/openspec/changes/pep-36-lightweight-stack/tasks.md +++ b/openspec/changes/pep-36-lightweight-stack/tasks.md @@ -13,11 +13,11 @@ ## 1. Этап 1 — Node 26 без tsx (без смены БД) -- [ ] 1.1 `erasableSyntaxOnly` в `tsconfig.base.json`; переписать parameter properties, `enum` и прочее, что Node не может очистить от типов; `typecheck` зелёный -- [ ] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx`; проверка версии Node (≥ 26) с понятной ошибкой -- [ ] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`.gitea/workflows/ci.yml`, `scripts/ci.sh`); `tsx` убрать из зависимостей -- [ ] 1.4 `scripts/install-launchd.sh` — без tsx; на машине не перевыкатывать (деплой — PM), в PR перечислить, что перевыкатить -- [ ] 1.5 Весь e2e на своей `PEPPA_TEST_DB`; замер старта `peppa-hook` (цель < 300 мс) +- [x] 1.1 `erasableSyntaxOnly` + `verbatimModuleSyntax` в `tsconfig.base.json`; parameter properties переписаны (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError, TelegramApi, MockGitea); `typecheck` зелёный +- [x] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx` (`PEPPA_NODE` переопределяет); проверка версии Node ≥ 26 — `scripts/lib/require-node.mjs` через `node --import` +- [x] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`ci.yml` уже ставит Node 26, `ci.sh` вызывает скрипт пакета — правок не потребовали); `tsx` убран из зависимостей +- [x] 1.4 `scripts/install-launchd.sh`: плисты и так вызывают bin-обёртки; добавлен закреплённый `PEPPA_NODE` (абсолютный путь, проверка версии при установке); на машине не перевыкатывал — список в PR +- [x] 1.5 Весь e2e на своей `PEPPA_TEST_DB` (`node --test`); старт `peppa-hook` 0,31 с (tsx 0,44 с) — см. design; гонка «промпт закрывает чужой вопрос» найдена и исправлена (`input_sent`) ## 2. Этап 2 — SQLite вместо Postgres diff --git a/package.json b/package.json index af1109a4..624b8c79 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,6 @@ }, "devDependencies": { "@types/node": "26.6.6", - "tsx": "4.23.15", "typescript": "6.0.3" } } diff --git a/packages/bugsink/src/index.ts b/packages/bugsink/src/index.ts index 3295ead8..3bf91640 100644 --- a/packages/bugsink/src/index.ts +++ b/packages/bugsink/src/index.ts @@ -129,11 +129,10 @@ export function parseWebhook(body: unknown): BugsinkIssueJson | null { } export class BugsinkError extends Error { - constructor( - message: string, - readonly status?: number, - ) { + readonly status?: number; + constructor(message: string, status?: number) { super(message); + this.status = status; } } diff --git a/packages/cli/bin/peppa b/packages/cli/bin/peppa index 9ee84182..442bd3ae 100755 --- a/packages/cli/bin/peppa +++ b/packages/cli/bin/peppa @@ -1,4 +1,4 @@ #!/usr/bin/env bash PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" . "$PEPPA_ROOT/scripts/lib/load-env.sh" -exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@" +exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@" diff --git a/packages/cli/package.json b/packages/cli/package.json index 09fa8af9..abaa8675 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -7,7 +7,7 @@ "peppa": "./bin/peppa" }, "scripts": { - "start": "tsx src/index.ts", + "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index 8ea94ac3..07bab961 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -62,19 +62,20 @@ export interface OAuthTokens { } export class GiteaError extends PeppaError { - constructor( - readonly status: number, - message: string, - ) { + readonly status: number; + constructor(status: number, message: string) { super(message); + this.status = status; } } export class GiteaClient { - constructor( - readonly baseUrl: string, - private readonly token: string, - ) {} + readonly baseUrl: string; + private readonly token: string; + constructor(baseUrl: string, token: string) { + this.baseUrl = baseUrl; + this.token = token; + } async request<T>(method: string, path: string, body?: unknown): Promise<T> { const res = await fetch(`${this.baseUrl}/api/v1${path}`, { diff --git a/packages/core/src/oauth.ts b/packages/core/src/oauth.ts index 942e7154..4396e2bf 100644 --- a/packages/core/src/oauth.ts +++ b/packages/core/src/oauth.ts @@ -12,12 +12,13 @@ export const ACCESS_TTL_SEC = 3600; const REFRESH_TTL_SEC = 30 * 86400; const CODE_TTL_MS = 10 * 60_000; +type OAuthErrorCode = "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied"; + export class OAuthError extends PeppaError { - constructor( - readonly error: "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied", - description: string, - ) { + readonly error: OAuthErrorCode; + constructor(error: OAuthErrorCode, description: string) { super(description); + this.error = error; } } diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index 6cf865d7..ad19e314 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -1,6 +1,6 @@ import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { and, desc, eq, inArray, isNull, notInArray } from "drizzle-orm"; +import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import type { Question, QuestionKind } from "./tasks.ts"; @@ -89,7 +89,7 @@ export async function logSessionEvent(db: Db, s: Session, type: string, payload? export async function pendingSessionQuestions( db: Db, sessionId: number, - opts: { excludeHook?: boolean } = {}, + opts: { excludeHook?: boolean; createdBefore?: Date } = {}, ): Promise<Question[]> { return db .select() @@ -99,10 +99,28 @@ export async function pendingSessionQuestions( eq(questions.sessionId, sessionId), isNull(questions.answeredAt), opts.excludeHook ? eq(questions.awaitingHook, false) : undefined, + opts.createdBefore ? lte(questions.createdAt, opts.createdBefore) : undefined, ), ); } +const sameText = (a: string, b: string) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim(); + +/** + * When Peppa itself typed `prompt` into the session's terminal (an `input_sent` event), + * the time it did so; null if the prompt came from a person. + */ +export async function peppaInputSentAt(db: Db, sessionId: number, prompt: string): Promise<Date | null> { + const sent = await db + .select() + .from(events) + .where(and(eq(events.sessionId, sessionId), eq(events.type, "input_sent"))) + .orderBy(desc(events.id)) + .limit(10); + const hit = sent.find((e) => sameText(String((e.payload as { text?: string } | null)?.text ?? ""), prompt)); + return hit?.createdAt ?? null; +} + export async function getQuestion(db: Db, id: number): Promise<Question> { const [row] = await db.select().from(questions).where(eq(questions.id, id)); if (!row) throw new PeppaError(`Question #${id} not found`); diff --git a/packages/mcp/bin/peppa-mcp b/packages/mcp/bin/peppa-mcp index bb1ffdb6..837073f1 100755 --- a/packages/mcp/bin/peppa-mcp +++ b/packages/mcp/bin/peppa-mcp @@ -2,4 +2,4 @@ # Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves. PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" . "$PEPPA_ROOT/scripts/lib/load-env.sh" -exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@" +exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@" diff --git a/packages/mcp/package.json b/packages/mcp/package.json index f38906c2..4c6995bd 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -7,7 +7,7 @@ "peppa-mcp": "./bin/peppa-mcp" }, "scripts": { - "start": "tsx src/index.ts", + "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { diff --git a/packages/mcp/scripts/call.ts b/packages/mcp/scripts/call.ts index 97ba10a3..05301615 100644 --- a/packages/mcp/scripts/call.ts +++ b/packages/mcp/scripts/call.ts @@ -1,5 +1,5 @@ // Calls one peppa MCP tool from the current directory, as an agent would. -// Usage: tsx packages/mcp/scripts/call.ts <tool> '<json args>' +// Usage: node packages/mcp/scripts/call.ts <tool> '<json args>' import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { fileURLToPath } from "node:url"; diff --git a/packages/mcp/scripts/smoke.ts b/packages/mcp/scripts/smoke.ts index 7d8b5e2a..4d31af3c 100644 --- a/packages/mcp/scripts/smoke.ts +++ b/packages/mcp/scripts/smoke.ts @@ -1,5 +1,5 @@ // Smoke test: spawns peppa-mcp in the given project dir and calls a few tools. -// Usage: tsx packages/mcp/scripts/smoke.ts <project-dir> <task> +// Usage: node packages/mcp/scripts/smoke.ts <project-dir> <task> import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { fileURLToPath } from "node:url"; diff --git a/packages/runner/bin/peppa-hook b/packages/runner/bin/peppa-hook index 3bda0f3d..38dc361f 100755 --- a/packages/runner/bin/peppa-hook +++ b/packages/runner/bin/peppa-hook @@ -4,4 +4,4 @@ PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" [ -z "${PEPPA_SESSION_ID:-}" ] && { [ "${1:-}" = codex-notify ] || cat >/dev/null; exit 0; } . "$PEPPA_ROOT/scripts/lib/load-env.sh" mkdir -p "${PEPPA_HOME:-$HOME/.peppa}" -exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@" +exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@" diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index fa558deb..db61e007 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -10,6 +10,7 @@ import { getQuestion, getSession, logSessionEvent, + peppaInputSentAt, pendingSessionQuestions, raiseSessionQuestion, releaseHookQuestion, @@ -214,8 +215,11 @@ async function handle(event: string, input: HookInput): Promise<void> { case "prompt": // Someone typed into the terminal (or Peppa pasted an answer): anything still - // pending for this session is now answered — except hook-held questions. - for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true })) { + // pending for this session is now answered — except hook-held questions, and, + // when Peppa typed this text itself, questions raised after it did (e.g. a CI + // failure pasted while the PM is being asked about the next one). + const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null; + for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) { await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); } await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now }); diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 86601e24..669a48dd 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -136,6 +136,8 @@ async function launch( export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> { const s = await getSession(db, sessionId); if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`); + // Recorded before typing: the prompt hook answers only questions older than this input. + await logSessionEvent(db, s, "input_sent", { text }); await tmux.sendText(s.tmuxName, text); await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() }); } diff --git a/packages/testkit/bin/mock-claude b/packages/testkit/bin/mock-claude index c24821f4..d6d407a7 100755 --- a/packages/testkit/bin/mock-claude +++ b/packages/testkit/bin/mock-claude @@ -1,4 +1,4 @@ #!/usr/bin/env bash # Mock claude CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts). ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" -exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@" diff --git a/packages/testkit/bin/mock-codex b/packages/testkit/bin/mock-codex index 3616fe4f..c26c43a9 100755 --- a/packages/testkit/bin/mock-codex +++ b/packages/testkit/bin/mock-codex @@ -1,4 +1,4 @@ #!/usr/bin/env bash # Mock codex CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts). ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" -exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@" diff --git a/packages/testkit/bin/mock-telegram b/packages/testkit/bin/mock-telegram index 19b2bf9f..e7875044 100755 --- a/packages/testkit/bin/mock-telegram +++ b/packages/testkit/bin/mock-telegram @@ -1,3 +1,3 @@ #!/usr/bin/env bash ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" -exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-telegram-server.ts" "$@" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-telegram-server.ts" "$@" diff --git a/packages/testkit/bin/mock-triage b/packages/testkit/bin/mock-triage index 22cfbdb3..4f3bc6fc 100755 --- a/packages/testkit/bin/mock-triage +++ b/packages/testkit/bin/mock-triage @@ -1,3 +1,3 @@ #!/usr/bin/env bash ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" -exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-triage.ts" "$@" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-triage.ts" "$@" diff --git a/packages/testkit/bin/peppa-dev b/packages/testkit/bin/peppa-dev index 5cd5c5b4..6ce87b5f 100755 --- a/packages/testkit/bin/peppa-dev +++ b/packages/testkit/bin/peppa-dev @@ -53,6 +53,6 @@ case "${1:-}" in down) "${TM[@]}" kill-server 2>/dev/null || true; echo "stand is down" ;; status) status ;; peppa) shift; exec "$PEPPA" "$@" ;; - tg) shift; exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/peppa-dev-tg.ts" "$@" ;; + tg) shift; exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/peppa-dev-tg.ts" "$@" ;; *) sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;; esac diff --git a/packages/testkit/package.json b/packages/testkit/package.json index cc45f2b5..48887c51 100644 --- a/packages/testkit/package.json +++ b/packages/testkit/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "typecheck": "tsc -p .", - "test": "tsx --test --test-concurrency=1 test/*.test.ts" + "test": "node --test --test-concurrency=1 test/*.test.ts" }, "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 1fa3591f..e7091460 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -50,8 +50,10 @@ export class MockGitea { private seq = 1; private server: Server | null = null; url = ""; + private readonly dir: string; - constructor(private readonly dir: string) { + constructor(dir: string) { + this.dir = dir; mkdirSync(dir, { recursive: true }); } diff --git a/packages/testkit/test/monitor.test.ts b/packages/testkit/test/monitor.test.ts index 0c586174..b1bb5ba9 100644 --- a/packages/testkit/test/monitor.test.ts +++ b/packages/testkit/test/monitor.test.ts @@ -219,7 +219,7 @@ describe("Без спама", () => { describe("Сводка в CLI", () => { const cli = (...args: string[]) => - execFileSync(join(ROOT, "node_modules/.bin/tsx"), [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env }); + execFileSync(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env }); test("Сводка", async () => { const now = Date.now(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1bbe1444..768ee51a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -169,9 +169,6 @@ importers: '@types/node': specifier: 26.6.6 version: 26.6.6 - tsx: - specifier: 4.23.15 - version: 4.23.15 typescript: specifier: 6.0.3 version: 6.0.3 diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index ce102372..d729363e 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -9,6 +9,11 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa" PATH_ENV="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" +# Bot and watchdog run TypeScript straight from source with Node's type stripping (PEP-36): +# pin the Node that was checked here, so launchd does not depend on what PATH finds later. +NODE_BIN="${PEPPA_NODE:-$(PATH="$PATH_ENV" command -v node || true)}" +[ -x "$NODE_BIN" ] || { echo "node not found (set PEPPA_NODE)" >&2; exit 1; } +"$NODE_BIN" --import "$ROOT/scripts/lib/require-node.mjs" -e 0 || exit 1 install_agent() { # label log workdir args... local label=$1 log=$2 workdir=$3; shift 3 @@ -25,7 +30,10 @@ install_agent() { # label log workdir args... $args </array> <key>WorkingDirectory</key><string>$workdir</string> <key>EnvironmentVariables</key> - <dict><key>PATH</key><string>$PATH_ENV</string></dict> + <dict> + <key>PATH</key><string>$PATH_ENV</string> + <key>PEPPA_NODE</key><string>$NODE_BIN</string> + </dict> <key>RunAtLoad</key><true/> <key>KeepAlive</key><true/> <key>StandardOutPath</key><string>$HOME/.peppa/$log</string> diff --git a/scripts/lib/require-node.mjs b/scripts/lib/require-node.mjs new file mode 100644 index 00000000..0245f378 --- /dev/null +++ b/scripts/lib/require-node.mjs @@ -0,0 +1,9 @@ +// Preloaded by Peppa's bin wrappers (`node --import`): Peppa runs its TypeScript straight +// from source with Node's built-in type stripping, which older Node versions lack — say so +// before the first .ts file fails to load with a cryptic error. +const MIN_MAJOR = 26; +const major = Number(process.versions.node.split(".")[0]); +if (major < MIN_MAJOR) { + process.stderr.write(`peppa: нужен Node ≥ ${MIN_MAJOR} (сейчас ${process.versions.node}): https://nodejs.org\n`); + process.exit(1); +} diff --git a/tsconfig.base.json b/tsconfig.base.json index cf45cb83..d7025976 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -8,6 +8,8 @@ "skipLibCheck": true, "resolveJsonModule": true, "isolatedModules": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, "noEmit": true, "types": ["node"] } -- 2.45.2 From 5120b97a0be45d5047c4180d50d46ae0026fa02d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:44:17 +0500 Subject: [PATCH 020/536] =?UTF-8?q?PEP-57:=20Peppa=20on=20its=20own=20pipe?= =?UTF-8?q?line=20=E2=80=94=20CI=20via=20project=20checks=20and=20peppa-ch?= =?UTF-8?q?eck.sh;=204.2=20moved=20to=20PEP-18?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .gitea/peppa-check.sh | 1 + .gitea/workflows/ci.yml | 38 +++++++++++++++++++------ .peppa/project.json | 13 ++++++++- AGENTS.md | 2 +- openspec/changes/pep-57-ci-cd/design.md | 26 +++++++++++++++++ openspec/changes/pep-57-ci-cd/tasks.md | 4 +-- 6 files changed, 72 insertions(+), 12 deletions(-) create mode 120000 .gitea/peppa-check.sh diff --git a/.gitea/peppa-check.sh b/.gitea/peppa-check.sh new file mode 120000 index 00000000..b87cf46a --- /dev/null +++ b/.gitea/peppa-check.sh @@ -0,0 +1 @@ +../template/.gitea/peppa-check.sh \ No newline at end of file diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index e97b18e6..5f6574a9 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,11 +1,20 @@ -# CI for Peppa itself (PEP-22): typecheck, web build and the e2e suite on mocks — the same -# scripts/ci.sh that runs locally. Runs on Peppa's act_runner (`peppa-trusted`, registered for -# peppa-bot's repos, PEP-57); tmux and the openspec CLI are installed in the job. +# CI for Peppa itself (PEP-22): typecheck, web build and the e2e suite on mocks. Runs on Peppa's +# act_runner (`peppa-trusted`, registered for peppa-bot's repos, PEP-57); tmux and the openspec +# CLI are installed in the job. Each check is a step of the factory's own pipeline (PEP-57): +# the commands are `checks` in .peppa/project.json, .gitea/peppa-check.sh (the template's) sets +# the `peppa/<check>` commit status and reports to Peppa, so PEP tasks get the same card, review +# gate and red-check feedback as any factory project. `scripts/ci.sh` runs the same locally. name: peppa-ci on: pull_request: push: branches: [main] +env: + PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }} + PEPPA_PR: ${{ github.event.pull_request.number }} + PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }} + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} jobs: ci: # The runner has the host's docker.sock: only branches of this repository, never forks. @@ -13,12 +22,14 @@ jobs: runs-on: peppa-trusted timeout-minutes: 30 env: - # Peppa's Postgres on the host, a database per run (dropped by ci.sh). A service container + # Peppa's Postgres on the host, a database per run (dropped in the last step). A service container # doesn't isolate here: every job shares the traefik_default network and its `postgres` alias. PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433 PEPPA_TEST_DB: peppa_test_ci_r${{ github.run_id }} steps: - uses: actions/checkout@v4 + with: + ref: ${{ env.PEPPA_SHA }} - uses: actions/setup-node@v4 with: node-version: "26" @@ -26,7 +37,18 @@ jobs: run: | apt-get update -qq && apt-get install -y -qq tmux >/dev/null npm install -g pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null - - name: install - run: pnpm install --frozen-lockfile - - name: ci - run: bash scripts/ci.sh + - id: install + name: install + run: bash .gitea/peppa-check.sh install + - name: typecheck + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh typecheck + - name: build + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh build + - name: test + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh test + - name: drop test database + if: always() + run: docker exec peppa-postgres dropdb -U peppa --if-exists "$PEPPA_TEST_DB" || true diff --git a/.peppa/project.json b/.peppa/project.json index 830a0620..77a81fb8 100644 --- a/.peppa/project.json +++ b/.peppa/project.json @@ -1 +1,12 @@ -{ "slug": "peppa", "key": "PEP", "name": "Peppa", "peppaUrl": "https://peppa.telecom.quest" } +{ + "slug": "peppa", + "key": "PEP", + "name": "Peppa", + "peppaUrl": "https://peppa.telecom.quest", + "checks": { + "install": "pnpm install --frozen-lockfile", + "typecheck": "pnpm -r typecheck", + "build": "pnpm --filter @peppa/web build", + "test": "pnpm --filter @peppa/testkit test" + } +} diff --git a/AGENTS.md b/AGENTS.md index 8ce96f26..79255c61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,7 @@ - `pnpm dev:web` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` -- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: `.gitea/workflows/ci.yml` гоняет `scripts/ci.sh` на каждый PR и push в main на раннере PEP-57 (`peppa-trusted`, Postgres хоста, БД `peppa_test_ci_r<run_id>`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`); статус `peppa-ci / ci (pull_request)` в PR, мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`) +- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста, БД `peppa_test_ci_r<run_id>`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`) - `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`) - **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md index 03d79ade..8a0094e8 100644 --- a/openspec/changes/pep-57-ci-cd/design.md +++ b/openspec/changes/pep-57-ci-cd/design.md @@ -90,3 +90,29 @@ Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не н присылает их); для прода по кнопке — задачи staging-релизов с прошлого прода. - **Сообщения PM** — вопросы без задачи (`askPmProject`): «staging обновлён» с кнопкой «🚀 Выкатить в прод» (прежние такие предложения закрываются), откат/провал, прод выкачен. +- **Откат при смене health-пути** — откат проверяется тем же `deploy.health`, что и новый релиз. + Если релиз сам меняет путь проверки на неработающий, старый образ поднимается, но отчёт — + `failed` («откат тоже не поднялся»). Проверено вживую на SBX; редкий случай, оставлено так. + +## Этап 4 + +- **4.1 (сделано)** — workflow Пеппы из PEP-22 гоняет `checks` из `.peppa/project.json` через + шаблонный `peppa-check.sh` (симлинк `.gitea/peppa-check.sh`): статусы `peppa/<проверка>` и + отчёты в Пеппу, гейт ревью и обратная связь для PEP-задач как у любого проекта. Секрет и вебхук + на `peppa-bot/peppa` — `setupCi` (раннер peppa-bot уже есть). `scripts/ci.sh` — то же локально. +- **4.2 (перенесено в PEP-18, нужно решение PM)** — деплой Пеппы её же конвейером меняет + launchd и рабочую копию `/Users/telecom/Dev/Peppa`. План: + 1. Релизный каталог `~/peppa/releases/<sha>` (git worktree от `peppa-bot/peppa`) + симлинк + `~/peppa/current`; `.env` — один файл вне релизов (симлинк в каждый релиз). + 2. launchd web/bot/watchdog и `~/.local/bin` смотрят в `~/peppa/current`, не в рабочую копию + разработки (разработка остаётся в `/Users/telecom/Dev/Peppa`, сессии в worktree). + 3. `scripts/peppa-release.sh <sha>`: checkout → `pnpm install --frozen-lockfile` → бэкап БД + (`pg_dump`) → `pnpm db:migrate` → `next build` → переключить симлинк → `launchctl kickstart` + трёх сервисов → health `https://peppa.telecom.quest/healthz` (+ вачдог жив) → при провале + симлинк назад и kickstart (миграции только аддитивные, отката схемы нет — восстановление из + бэкапа вручную). + 4. Запуск: push в main → job `deploy` на `peppa-trusted`, но релиз выполняется на хосте (job в + контейнере не может делать `launchctl`) — через launchd-агент-слушатель, который берёт + подписанный запрос «выкатить <sha>»; прод Пеппы — по кнопке PM, как у проектов + (`releases` с project PEP). + 5. Ежедневный бэкап Postgres и проверка восстановления (остальное из PEP-18). diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md index 3638fdc1..c11b3726 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -28,8 +28,8 @@ ## 4. Пеппа на собственном конвейере -- [ ] 4.1 CI Пеппы: typecheck, build, e2e (закрывает PEP-22) -- [ ] 4.2 CD Пеппы: релизный checkout вместо рабочей копии, миграции, перезапуск сервисов, health, откат (закрывает PEP-18) +- [x] 4.1 CI Пеппы: typecheck, build, e2e (закрывает PEP-22) — workflow PEP-22 переведён на `checks` + `peppa-check.sh`, секрет и вебхук `setupCi` на peppa-bot/peppa +- [ ] 4.2 CD Пеппы: релизный checkout вместо рабочей копии, миграции, перезапуск сервисов, health, откат (закрывает PEP-18) — **перенесено в PEP-18**: меняет launchd и рабочую копию `/Users/telecom/Dev/Peppa`, нужно решение PM (план — в design.md, «Этап 4.2») ## 5. Завершение -- 2.45.2 From ae37ba90d529e5c31f9fbed6d8076adc7e9c39c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:44:39 +0500 Subject: [PATCH 021/536] PEP-57: archive OpenSpec change pep-57-ci-cd (spec delivery-pipeline) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../2026-11-13-pep-57-ci-cd}/.openspec.yaml | 0 .../2026-11-13-pep-57-ci-cd}/design.md | 0 .../2026-11-13-pep-57-ci-cd}/proposal.md | 0 .../specs/delivery-pipeline/spec.md | 0 .../2026-11-13-pep-57-ci-cd}/tasks.md | 2 +- openspec/specs/delivery-pipeline/spec.md | 83 +++++++++++++++++++ 6 files changed, 84 insertions(+), 1 deletion(-) rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/.openspec.yaml (100%) rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/design.md (100%) rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/proposal.md (100%) rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/specs/delivery-pipeline/spec.md (100%) rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/tasks.md (98%) create mode 100644 openspec/specs/delivery-pipeline/spec.md diff --git a/openspec/changes/pep-57-ci-cd/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/.openspec.yaml similarity index 100% rename from openspec/changes/pep-57-ci-cd/.openspec.yaml rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/.openspec.yaml diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/design.md similarity index 100% rename from openspec/changes/pep-57-ci-cd/design.md rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/design.md diff --git a/openspec/changes/pep-57-ci-cd/proposal.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/proposal.md similarity index 100% rename from openspec/changes/pep-57-ci-cd/proposal.md rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/proposal.md diff --git a/openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/specs/delivery-pipeline/spec.md similarity index 100% rename from openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/specs/delivery-pipeline/spec.md diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/tasks.md similarity index 98% rename from openspec/changes/pep-57-ci-cd/tasks.md rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/tasks.md index c11b3726..1fffd27a 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/tasks.md @@ -33,4 +33,4 @@ ## 5. Завершение -- [ ] 5.1 Помощь в вебе: раздел «CI/CD»; AGENTS.md; `openspec validate pep-57-ci-cd`; весь e2e-набор зелёный +- [x] 5.1 Помощь в вебе: раздел «CI/CD»; AGENTS.md; `openspec validate pep-57-ci-cd`; весь e2e-набор зелёный diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..b143d246 --- /dev/null +++ b/openspec/specs/delivery-pipeline/spec.md @@ -0,0 +1,83 @@ +# delivery-pipeline Specification + +## Purpose +Описывает путь изменения от PR агента до работающего продукта: автоматические проверки, условия ревью и мержа, деплой по окружениям, проверку здоровья и откат. + +## Requirements + +### Requirement: Проверки на каждый PR +Для каждого PR проекта с настроенными проверками SHALL автоматически выполняться lint, typecheck, test и build, а их результат — отображаться в карточке задачи. + +#### Scenario: Зелёные проверки +- **GIVEN** проект «PAY» с настроенными командами проверок и задача PAY-7 в работе +- **WHEN** раннер открывает PR по задаче PAY-7 и все проверки проходят +- **THEN** в карточке PAY-7 видно «Проверки: 4 из 4 пройдены» со ссылкой на прогон + +#### Scenario: Проверки не настроены +- **GIVEN** проект без команд проверок +- **WHEN** раннер открывает PR +- **THEN** в карточке задачи видно «проверки не настроены», а переход в «Ревью» не блокируется + +### Requirement: Красные проверки возвращаются агенту +Проваленная проверка SHALL возвращать задачу раннеру с названием шага и фрагментом лога; после 3 неудачных попыток подряд Пеппа SHALL спросить PM. + +#### Scenario: Агент чинит сам +- **GIVEN** PR задачи PAY-7 с проваленным шагом «test» и работающим раннером +- **WHEN** Пеппа получает результат проверки +- **THEN** раннер получает сообщение с шагом «test» и последними строками лога +- **AND** задача остаётся в «В работе», PM ничего не получает + +#### Scenario: Три неудачи подряд +- **GIVEN** проверки PR задачи PAY-7 провалились 3 раза подряд после исправлений агента +- **WHEN** приходит третий красный результат +- **THEN** PM получает вопрос по задаче PAY-7 со ссылкой на лог +- **AND** раннер ждёт ответа + +### Requirement: Гейт ревью и мержа +Задача SHALL попадать в «Ревью», а её PR — мержиться (вручную или автоматически) только при зелёных проверках последнего коммита и отсутствии конфликтов. + +#### Scenario: Мерж при красных проверках +- **GIVEN** PR задачи PAY-7 с проваленной проверкой последнего коммита +- **WHEN** PM нажимает «Принять» +- **THEN** мерж не выполняется +- **AND** PM видит причину «проверки не пройдены» + +#### Scenario: Приёмка +- **GIVEN** PR задачи PAY-7 с зелёными проверками и без конфликтов +- **WHEN** PM нажимает «Принять» +- **THEN** PR смержен в основную ветку +- **AND** задача PAY-7 в «Готово» + +### Requirement: Деплой по окружениям +Мерж в основную ветку SHALL выкатывать проект на staging; прод SHALL выкатываться по действию PM или автоматически, если это включено в настройках проекта; для открытого PR SHALL быть доступен preview-стенд. + +#### Scenario: Staging после мержа +- **GIVEN** проект «PAY» с настроенным деплоем +- **WHEN** PR задачи PAY-7 смержен +- **THEN** собран образ с тегом коммита и выкачен на staging +- **AND** в Пеппе появился релиз staging со списком задач «PAY-7» + +#### Scenario: Прод по кнопке +- **GIVEN** здоровый релиз на staging и ручной режим прода +- **WHEN** PM нажимает «Выкатить в прод» +- **THEN** тот же образ выкачен в прод +- **AND** релиз прода записан с автором «PM» + +### Requirement: Проверка здоровья и откат +После каждого деплоя SHALL выполняться проверка здоровья; при провале окружение SHALL возвращаться к предыдущему релизу, а PM — получать сообщение. + +#### Scenario: Неудачный релиз +- **GIVEN** в проде работает релиз «a1b2c3» +- **WHEN** выкачен релиз «d4e5f6» и проверка `/healthz` не проходит за 2 минуты +- **THEN** прод возвращён на «a1b2c3» +- **AND** релиз «d4e5f6» помечен «откат» +- **AND** PM получает сообщение с причиной и ссылкой на лог + +### Requirement: Изменение конвейера требует ревью +Изменения файлов конвейера и команд проверок в PR агента SHALL явно показываться PM и не мержиться автоматически. + +#### Scenario: Агент отключил тесты +- **GIVEN** проект в автоматическом режиме мержа +- **WHEN** PR агента меняет команду «test» в настройках проверок +- **THEN** PR не мержится автоматически +- **AND** PM получает вопрос с описанием изменения конвейера -- 2.45.2 From 07e2caa3933762040fa5d2b36c5e3b40439ad3aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:54:30 +0500 Subject: [PATCH 022/536] PEP-57: PM question on red CI is not closed by the agent's prompts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After three red runs Peppa asked the PM with the session attached, then pasted "wait for the PM" into that session — its prompt hook closed the question as answered in the terminal. The question is now task-only; answers to task questions without a session go to the task's active session. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/runner/src/ci-feedback.ts | 3 ++- packages/runner/src/sessions.ts | 8 ++++++-- packages/testkit/test/ci-feedback.test.ts | 6 ++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 030cc42f..09ac608a 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -68,9 +68,10 @@ export async function recordCheck(db: Db, project: Project, r: CheckReport): Pro if (attempts >= MAX_CI_ATTEMPTS) { if (!newRun) return { task: ref.key, action: "none" }; // the PM already has this commit + // Not tied to the session: the "wait for the PM" paste below (and any prompt of the agent) + // would close it as answered in the terminal. The answer still reaches the task's agent. await askPm(db, ref, { kind: "question", - sessionId: sessionId ?? undefined, text: `❌ ${ref.key}: проверки PR красные ${attempts} раза подряд — агент не справился сам. Упала «${r.check}» (коммит ${r.sha.slice(0, 7)}).${link ? `\nЛог: ${link}` : ""}\n\nЧто делать? Ответ уйдёт агенту.`, }); if (sessionId) { diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 669a48dd..95ba8b51 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -6,6 +6,7 @@ import { createSession, expireSessionQuestions, getSession, + listSessions, loadSharedRules, PeppaError, resolveTask, @@ -184,8 +185,11 @@ export async function answerAndDeliver( // "Deploy to prod" on a "staging updated" message (PEP-57). if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q }; - if (!q.sessionId) return { delivered: false, question: q }; - const s = await getSession(db, q.sessionId); + // A task question asked outside a session (red CI, a manual session) goes to the agent + // working on the task now, if any. + const sessionId = q.sessionId ?? (q.taskId ? (await listSessions(db, { active: true, taskId: q.taskId }))[0]?.id : undefined); + if (!sessionId) return { delivered: false, question: q }; + const s = await getSession(db, sessionId); if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q }; if (q.kind === "permission") { diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts index bdea79c1..398e189f 100644 --- a/packages/testkit/test/ci-feedback.test.ts +++ b/packages/testkit/test/ci-feedback.test.ts @@ -133,6 +133,12 @@ describe("Красные проверки возвращаются агенту" assert.equal(q.taskId, (await t.ref()).task.id); assert.match(q.text, new RegExp(`красные 3 раза подряд[\\s\\S]*Лог: ${gitea.url}/`)); await t.p.waitLog("runner told to wait", (e) => e.ev === "prompt" && String(e.prompt).includes("жди ответа PM")); + // The agent's prompts (the "wait" paste included) don't close the PM's question… + await new Promise((r) => setTimeout(r, 1500)); + assert.ok((await core.pendingQuestions(db, t.proj.id)).some((x) => x.id === q.id), "question still open after the agent's prompt"); + // …and the answer reaches the agent of the task. + assert.equal((await runner.answerAndDeliver(db, q.id, "откати последний коммит", "web")).delivered, true); + await t.p.waitLog("answer delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("откати последний коммит")); // Green again → the counter starts over. const sha = t.push(); for (const c of Object.keys(CHECKS)) await t.report(sha, c, "success"); -- 2.45.2 From 048006fd32a71d48ce24902942a422be7fd5eee2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 16:55:17 +0500 Subject: [PATCH 023/536] PEP-57: re-run CI (runner DNS hiccup) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> -- 2.45.2 From 3a282b8054b3d66a483d8e1de270cb7f9bb8a038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 17:22:47 +0500 Subject: [PATCH 024/536] PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of Postgres MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text, booleans 0/1), one baseline migration; node:sqlite client under drizzle's better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB (default ~/.peppa/peppa.db) - live updates: notify() pokes the bot over a unix socket; the bot also watches PRAGMA data_version every second (writes by other processes) - Postgres specifics ported: createTask transaction is synchronous, no `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each instead of @> - `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only snapshot of Postgres, FK order from the schema, row count + foreign key checks, file appears only when they pass); old Postgres schema kept in packages/cli/legacy-pg-migrations for the migration and its test - daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure) - tests: a temp SQLite file per test file; storage.test.ts (20 processes, per-project numbering across processes, socket/data_version, migration from Postgres incl. a dangling foreign key, backups); two test races fixed - CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .env.example | 6 +- .gitea/workflows/ci.yml | 8 +- AGENTS.md | 14 +- README.md | 2 +- apps/bot/src/bot.ts | 23 +- apps/bot/src/index.ts | 2 +- .../pep-36-lightweight-stack/design.md | 17 +- .../specs/platform-storage/spec.md | 14 +- .../changes/pep-36-lightweight-stack/tasks.md | 20 +- .../0000_safe_shiver_man.sql | 0 .../0001_chunky_dreadnoughts.sql | 0 .../0002_happy_preak.sql | 0 .../0003_material_wild_child.sql | 0 .../0004_loving_wasp.sql | 0 .../0005_sloppy_blue_marvel.sql | 0 .../0006_crazy_stellaris.sql | 0 .../0007_empty_crystal.sql | 0 .../0008_wandering_jetstream.sql | 0 .../0009_steady_preak.sql | 0 .../0010_glamorous_ego.sql | 0 .../0011_pep58_incidents.sql | 0 .../0012_faithful_matthew_murdock.sql | 0 .../0013_pep57_releases.sql | 0 packages/cli/package.json | 3 +- packages/cli/src/index.ts | 30 +- packages/cli/src/migrate-to-sqlite.ts | 69 + packages/core/src/backup.ts | 52 + packages/core/src/incidents.ts | 6 +- packages/core/src/index.ts | 1 + packages/core/src/monitor.ts | 4 +- packages/core/src/notify.ts | 67 +- packages/core/src/tasks.ts | 36 +- packages/core/src/telegram.ts | 3 +- packages/db/drizzle.config.ts | 4 +- packages/db/migrations/0000_baseline.sql | 313 +++ .../db/migrations/meta/0000_snapshot.json | 1948 +++++++++++++-- .../db/migrations/meta/0001_snapshot.json | 706 ------ .../db/migrations/meta/0002_snapshot.json | 713 ------ .../db/migrations/meta/0003_snapshot.json | 888 ------- .../db/migrations/meta/0004_snapshot.json | 1003 -------- .../db/migrations/meta/0005_snapshot.json | 1010 -------- .../db/migrations/meta/0006_snapshot.json | 1231 --------- .../db/migrations/meta/0007_snapshot.json | 1243 ---------- .../db/migrations/meta/0008_snapshot.json | 1402 ----------- .../db/migrations/meta/0009_snapshot.json | 1433 ----------- .../db/migrations/meta/0010_snapshot.json | 1464 ----------- .../db/migrations/meta/0011_snapshot.json | 1893 -------------- .../db/migrations/meta/0012_snapshot.json | 2061 ---------------- .../db/migrations/meta/0013_snapshot.json | 2189 ----------------- packages/db/migrations/meta/_journal.json | 99 +- packages/db/package.json | 15 +- packages/db/src/client.ts | 121 + packages/db/src/index.ts | 72 +- packages/db/src/schema.ts | 153 +- packages/runner/src/deploy.ts | 2 +- packages/runner/src/sessions.ts | 2 +- packages/runner/src/watchdog.ts | 3 + packages/shared/src/env.ts | 10 +- packages/testkit/bin/peppa-dev | 8 +- packages/testkit/src/storage-worker.ts | 18 + packages/testkit/test/helpers.ts | 26 +- packages/testkit/test/incidents.test.ts | 5 +- packages/testkit/test/monitor.test.ts | 11 +- packages/testkit/test/storage.test.ts | 197 ++ pnpm-lock.yaml | 6 +- scripts/ci.sh | 11 +- 66 files changed, 2902 insertions(+), 17735 deletions(-) rename packages/{db/migrations => cli/legacy-pg-migrations}/0000_safe_shiver_man.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0001_chunky_dreadnoughts.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0002_happy_preak.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0003_material_wild_child.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0004_loving_wasp.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0005_sloppy_blue_marvel.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0006_crazy_stellaris.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0007_empty_crystal.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0008_wandering_jetstream.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0009_steady_preak.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0010_glamorous_ego.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0011_pep58_incidents.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0012_faithful_matthew_murdock.sql (100%) rename packages/{db/migrations => cli/legacy-pg-migrations}/0013_pep57_releases.sql (100%) create mode 100644 packages/cli/src/migrate-to-sqlite.ts create mode 100644 packages/core/src/backup.ts create mode 100644 packages/db/migrations/0000_baseline.sql delete mode 100644 packages/db/migrations/meta/0001_snapshot.json delete mode 100644 packages/db/migrations/meta/0002_snapshot.json delete mode 100644 packages/db/migrations/meta/0003_snapshot.json delete mode 100644 packages/db/migrations/meta/0004_snapshot.json delete mode 100644 packages/db/migrations/meta/0005_snapshot.json delete mode 100644 packages/db/migrations/meta/0006_snapshot.json delete mode 100644 packages/db/migrations/meta/0007_snapshot.json delete mode 100644 packages/db/migrations/meta/0008_snapshot.json delete mode 100644 packages/db/migrations/meta/0009_snapshot.json delete mode 100644 packages/db/migrations/meta/0010_snapshot.json delete mode 100644 packages/db/migrations/meta/0011_snapshot.json delete mode 100644 packages/db/migrations/meta/0012_snapshot.json delete mode 100644 packages/db/migrations/meta/0013_snapshot.json create mode 100644 packages/db/src/client.ts create mode 100644 packages/testkit/src/storage-worker.ts create mode 100644 packages/testkit/test/storage.test.ts diff --git a/.env.example b/.env.example index 690070bb..ee5cfd5e 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,7 @@ -# Postgres (infra/docker-compose.yml) -DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa +# SQLite database file (default ~/.peppa/peppa.db) +# PEPPA_DB=/Users/me/.peppa/peppa.db +# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36) +# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa # Gitea (git.telecom.quest) — token with repo + org scope GITEA_URL=https://git.telecom.quest diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 5f6574a9..a523b9f9 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -22,10 +22,9 @@ jobs: runs-on: peppa-trusted timeout-minutes: 30 env: - # Peppa's Postgres on the host, a database per run (dropped in the last step). A service container - # doesn't isolate here: every job shares the traefik_default network and its `postgres` alias. + # Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source + # for the Postgres → SQLite migration test, which makes and drops its own database. PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433 - PEPPA_TEST_DB: peppa_test_ci_r${{ github.run_id }} steps: - uses: actions/checkout@v4 with: @@ -49,6 +48,3 @@ jobs: - name: test if: (success() || failure()) && steps.install.outcome == 'success' run: bash .gitea/peppa-check.sh test - - name: drop test database - if: always() - run: docker exec peppa-postgres dropdb -U peppa --if-exists "$PEPPA_TEST_DB" || true diff --git a/AGENTS.md b/AGENTS.md index 79255c61..671748aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,9 +8,9 @@ ## Структура - `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web` - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта -- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433) +- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36) - `packages/shared` — env, ключи задач (`PEP-42`) -- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё +- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM); живые обновления — `notify()` будит подписчика (бота) через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот вдобавок раз в секунду смотрит `PRAGMA data_version`; ежедневная копия базы (`backupDb`, `VACUUM INTO`, `~/.peppa/backups`, 7 штук) из вачдога; всё ходит через неё - `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов - **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, create_project, list_goals, create_goal, update_goal, list_tasks, get_task, create_task, update_task (название/описание/цель, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question; `instructions` сервера объясняют модель клиенту. Пользовательская документация — `/help` в вебе (держать в актуальном состоянии при изменении инструментов) - `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM @@ -25,7 +25,7 @@ - агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP) - **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp` - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member -- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres Пеппы, `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` +- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u<id>` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:<service>`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon:<service>:…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect <KEY>` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) @@ -51,7 +51,7 @@ интеграции (какой доступ, у кого). ## Команды -- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate` +- `pnpm db:generate` (новая миграция из схемы) / `pnpm db:migrate` (= `peppa db migrate`); `peppa db migrate-to-sqlite <file>` — одноразовый перенос из Postgres `DATABASE_URL` (только чтение, сверка строк и внешних ключей; старая pg-схема — `packages/cli/legacy-pg-migrations`); `pnpm db:up` — Postgres для Bugsink - `peppa project create <slug> <KEY> <name> [--existing]` — проект в Gitea (`provisionProject` в runner, тот же код, что у веба); `peppa project owner <KEY> <login>` - `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы - `peppa web login-link <login>` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea @@ -60,9 +60,9 @@ - `pnpm dev:web` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` -- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста, БД `peppa_test_ci_r<run_id>`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`) -- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`) -- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` +- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`) +- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (у каждого файла свой временный SQLite-файл, свой tmux `-L`, свой `PEPPA_HOME` — параллельные worktree не мешают друг другу) +- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`. diff --git a/README.md b/README.md index db2ad338..75041df9 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ```bash pnpm install cp .env.example .env # GITEA_TOKEN и т.д. -pnpm db:up && pnpm db:migrate +pnpm db:migrate # SQLite в ~/.peppa/peppa.db (PEPPA_DB) scripts/push-template.sh # залить template/ в Gitea peppa project create demo DEMO "Demo project" ``` diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 3bebe1c8..5d6b8ed5 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -9,8 +9,8 @@ import { claimUpdate, dueOutbox, enqueueTelegram, - EVENTS_CHANNEL, finishUpdate, + listenEvents, answeredQuestionMessages, projectForUser, questionRecipients, @@ -50,6 +50,8 @@ export interface BotOptions { reconcileIntervalMs?: number; /** Heartbeat + check on the watchdog and the web (PEP-20). */ heartbeatIntervalMs?: number; + // How often to check PRAGMA data_version for writes the notify() poke missed. + changesIntervalMs?: number; log?: (msg: string) => void; } @@ -320,6 +322,20 @@ export function createBot(o: BotOptions) { } } + // Writes by other processes the poke missed (PRAGMA data_version moves on every commit + // from another connection): at most a second late instead of waiting for reconcileLoop. + async function changesLoop() { + let seen = db.$client.dataVersion(); + while (!abort.signal.aborted) { + await sleep(o.changesIntervalMs ?? 1000); + const v = db.$client.dataVersion(); + if (v !== seen) { + seen = v; + scheduleReconcile(); + } + } + } + async function monitorLoop() { while (!abort.signal.aborted) { try { @@ -343,9 +359,8 @@ export function createBot(o: BotOptions) { const me = await api.getMe(); await setSetting(db, "telegram.bot", { id: me.id, username: me.username }); log(`bot @${me.username} started`); - const l = await db.$client.listen(EVENTS_CHANNEL, () => scheduleReconcile()); - unlisten = () => l.unlisten(); - loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), monitorLoop()]); + unlisten = await listenEvents("bot", () => scheduleReconcile()); + loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]); return me; }, async stop() { diff --git a/apps/bot/src/index.ts b/apps/bot/src/index.ts index 2fc21e3a..270725ed 100644 --- a/apps/bot/src/index.ts +++ b/apps/bot/src/index.ts @@ -10,7 +10,7 @@ if (!env.TELEGRAM_BOT_TOKEN) { process.exit(1); } const bot = createBot({ - db: createDb(env.DATABASE_URL), + db: createDb(env.PEPPA_DB), api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL), secret: env.TELEGRAM_BOT_TOKEN, webUrl: env.PEPPA_WEB_URL, diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md index c2b3968c..076b8060 100644 --- a/openspec/changes/pep-36-lightweight-stack/design.md +++ b/openspec/changes/pep-36-lightweight-stack/design.md @@ -227,14 +227,17 @@ FIFO-очередь записи без хвостов — нужен тольк - запись — `BEGIN IMMEDIATE`, транзакции короткие и синхронные, до 3 повторов на BUSY; - база только на локальном диске (WAL не работает на сетевых ФС). -### 3. LISTEN/NOTIFY → журнал событий + сигнал + страховочный опрос +### 3. LISTEN/NOTIFY → сигнал по сокету + `PRAGMA data_version` -Источник правды — таблица `events` и курсор подписчика (`settings`, ключ -`cursor:<service>`), так бот после рестарта дочитывает пропущенное (сейчас NOTIFY, -пришедший во время рестарта, теряется, спасает только reconcile раз в 10 с). Записавший -процесс шлёт датаграмму «есть новое» в unix-сокет `~/.peppa/events.sock` каждого -подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в -секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала. +Сделано в этапе 2 проще, чем планировалось: бот и сейчас не читает содержимое NOTIFY, +а по любому сигналу сверяет очередь с базой (reconcile), поэтому курсор по `events` не +нужен. `notify()` после записи подключается к unix-сокету `$PEPPA_HOME/bot.events.sock` +и пишет строку JSON (сокета нет — сразу возвращается). Бот, кроме того, раз в секунду +читает `PRAGMA data_version` — он меняется при каждом коммите **другого** соединения, — +и при изменении делает reconcile; плюс прежний reconcile раз в 10 с и при старте. Итог: +~1 мс в норме, ≤ 1 с при пропущенном сигнале, после рестарта бот находит всё сам. +(UDP-датаграммы по unix-сокету в Node нет — поэтому короткое stream-соединение.) Веб +живых обновлений не имел и не получает; SSE — отдельной задачей. ### 4. Поэтапно: Node без tsx → SQLite → Docker diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md index 14bf7044..a1a35875 100644 --- a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md +++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md @@ -25,22 +25,22 @@ - **THEN** хук делает 3 попытки, затем пишет в `~/.peppa/hook.log` строку с `hook.event` и `SQLITE_BUSY` и завершается без зависания Claude дольше 30 секунд ### Requirement: Живые обновления без Postgres -Бот и веб SHALL узнавать о новых событиях, вопросах и изменениях задач, читая журнал `events` по курсору (id последнего прочитанного события). Процесс, записавший событие, SHALL будить подписчиков коротким сигналом по локальному сокету; если сигнал не дошёл, подписчик SHALL всё равно найти событие опросом не реже раза в секунду. +Процесс, записавший вопрос, ответ, событие или изменение задачи, SHALL будить бота коротким сигналом по локальному unix-сокету; бот по сигналу SHALL сверять очередь сообщений с базой. Если сигнал не дошёл (сокета нет, бот перезапускался), бот SHALL замечать запись другого процесса по счётчику изменений базы не позже чем через секунду. #### Scenario: Вопрос агента доходит до PM - **GIVEN** бот запущен, PM привязал Telegram - **WHEN** агент раннера «PEP-42» задаёт вопрос «Удалить build?» -- **THEN** бот видит вопрос и ставит сообщение PM в очередь в среднем быстрее 50 мс и в 99 % случаев быстрее 1 секунды +- **THEN** бот ставит сообщение PM в очередь в 99 % случаев быстрее 1 секунды #### Scenario: Сокет подписки недоступен -- **GIVEN** бот запущен, сокет сигналов не создан или упал -- **WHEN** MCP раннера «PEP-42» пишет `report_progress` «Сделал шаг 3 из 7» -- **THEN** бот читает это событие не позже чем через 1 секунду после записи +- **GIVEN** бот запущен, сокет сигналов удалён +- **WHEN** MCP раннера «PEP-42» в другом процессе пишет `report_progress` «Сделал шаг 3 из 7» +- **THEN** бот замечает изменение базы не позже чем через 1 секунду после записи #### Scenario: Бот перезапустился -- **GIVEN** бот остановлен, курсор бота — событие 120, за время простоя записаны события 121–125 +- **GIVEN** бот остановлен, за время простоя агенты задали 3 вопроса - **WHEN** бот запускается -- **THEN** бот обрабатывает события 121–125 по одному разу и сохраняет курсор 125 +- **THEN** PM получает 3 сообщения, по одному на вопрос ### Requirement: Перенос данных из Postgres Переезд SHALL выполняться командой, которая читает боевую базу Postgres только на чтение, создаёт новый файл SQLite по актуальной схеме, переносит все таблицы и сверяет число строк и внешние ключи. При любом расхождении команда SHALL удалять новый файл, оставлять Postgres без изменений и печатать, в какой таблице расхождение. diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md index ab312704..89b73913 100644 --- a/openspec/changes/pep-36-lightweight-stack/tasks.md +++ b/openspec/changes/pep-36-lightweight-stack/tasks.md @@ -21,16 +21,16 @@ ## 2. Этап 2 — SQLite вместо Postgres -- [ ] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`) -- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON` -- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции -- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async` -- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть -- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме -- [ ] 2.6 `peppa db migrate-to-sqlite <file>`: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении -- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл -- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude) -- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63) +- [x] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`) — смержен (#24–#26) +- [x] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON` +- [x] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции +- [x] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) переписан; async-колбэк драйвер отклоняет с ошибкой (вместо lint-проверки) +- [x] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть +- [x] 2.5 Живые обновления: `notify()` будит бота через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот раз в секунду смотрит `PRAGMA data_version` (запись другого процесса) + прежний reconcile раз в 10 с; веб без живых обновлений, как и раньше (SSE — отдельной задачей) +- [x] 2.6 `peppa db migrate-to-sqlite <file>`: чтение Postgres в read-only снапшоте, порядок таблиц по внешним ключам из схемы, сверка строк и `foreign_key_check`, файл появляется только после проверок; проверено на копии боевой БД (20 таблиц, 64 мс, расхождений нет) +- [x] 2.7 Ежедневная копия (`backupDb`, `VACUUM INTO`) из вачдога, 7 копий, алерт админам при ошибке; health проверяет таблицы базы +- [x] 2.8 testkit: временный файл базы на каждый файл тестов вместо `peppa_test`; `storage.test.ts` (20 процессов, нумерация задач из разных процессов, сокет/`data_version`, перенос из Postgres, копии) +- [ ] 2.9 Переключение прода (деплой — PM, шаги в PR): остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63) ## 3. Этап 3 — запуск одной командой diff --git a/packages/db/migrations/0000_safe_shiver_man.sql b/packages/cli/legacy-pg-migrations/0000_safe_shiver_man.sql similarity index 100% rename from packages/db/migrations/0000_safe_shiver_man.sql rename to packages/cli/legacy-pg-migrations/0000_safe_shiver_man.sql diff --git a/packages/db/migrations/0001_chunky_dreadnoughts.sql b/packages/cli/legacy-pg-migrations/0001_chunky_dreadnoughts.sql similarity index 100% rename from packages/db/migrations/0001_chunky_dreadnoughts.sql rename to packages/cli/legacy-pg-migrations/0001_chunky_dreadnoughts.sql diff --git a/packages/db/migrations/0002_happy_preak.sql b/packages/cli/legacy-pg-migrations/0002_happy_preak.sql similarity index 100% rename from packages/db/migrations/0002_happy_preak.sql rename to packages/cli/legacy-pg-migrations/0002_happy_preak.sql diff --git a/packages/db/migrations/0003_material_wild_child.sql b/packages/cli/legacy-pg-migrations/0003_material_wild_child.sql similarity index 100% rename from packages/db/migrations/0003_material_wild_child.sql rename to packages/cli/legacy-pg-migrations/0003_material_wild_child.sql diff --git a/packages/db/migrations/0004_loving_wasp.sql b/packages/cli/legacy-pg-migrations/0004_loving_wasp.sql similarity index 100% rename from packages/db/migrations/0004_loving_wasp.sql rename to packages/cli/legacy-pg-migrations/0004_loving_wasp.sql diff --git a/packages/db/migrations/0005_sloppy_blue_marvel.sql b/packages/cli/legacy-pg-migrations/0005_sloppy_blue_marvel.sql similarity index 100% rename from packages/db/migrations/0005_sloppy_blue_marvel.sql rename to packages/cli/legacy-pg-migrations/0005_sloppy_blue_marvel.sql diff --git a/packages/db/migrations/0006_crazy_stellaris.sql b/packages/cli/legacy-pg-migrations/0006_crazy_stellaris.sql similarity index 100% rename from packages/db/migrations/0006_crazy_stellaris.sql rename to packages/cli/legacy-pg-migrations/0006_crazy_stellaris.sql diff --git a/packages/db/migrations/0007_empty_crystal.sql b/packages/cli/legacy-pg-migrations/0007_empty_crystal.sql similarity index 100% rename from packages/db/migrations/0007_empty_crystal.sql rename to packages/cli/legacy-pg-migrations/0007_empty_crystal.sql diff --git a/packages/db/migrations/0008_wandering_jetstream.sql b/packages/cli/legacy-pg-migrations/0008_wandering_jetstream.sql similarity index 100% rename from packages/db/migrations/0008_wandering_jetstream.sql rename to packages/cli/legacy-pg-migrations/0008_wandering_jetstream.sql diff --git a/packages/db/migrations/0009_steady_preak.sql b/packages/cli/legacy-pg-migrations/0009_steady_preak.sql similarity index 100% rename from packages/db/migrations/0009_steady_preak.sql rename to packages/cli/legacy-pg-migrations/0009_steady_preak.sql diff --git a/packages/db/migrations/0010_glamorous_ego.sql b/packages/cli/legacy-pg-migrations/0010_glamorous_ego.sql similarity index 100% rename from packages/db/migrations/0010_glamorous_ego.sql rename to packages/cli/legacy-pg-migrations/0010_glamorous_ego.sql diff --git a/packages/db/migrations/0011_pep58_incidents.sql b/packages/cli/legacy-pg-migrations/0011_pep58_incidents.sql similarity index 100% rename from packages/db/migrations/0011_pep58_incidents.sql rename to packages/cli/legacy-pg-migrations/0011_pep58_incidents.sql diff --git a/packages/db/migrations/0012_faithful_matthew_murdock.sql b/packages/cli/legacy-pg-migrations/0012_faithful_matthew_murdock.sql similarity index 100% rename from packages/db/migrations/0012_faithful_matthew_murdock.sql rename to packages/cli/legacy-pg-migrations/0012_faithful_matthew_murdock.sql diff --git a/packages/db/migrations/0013_pep57_releases.sql b/packages/cli/legacy-pg-migrations/0013_pep57_releases.sql similarity index 100% rename from packages/db/migrations/0013_pep57_releases.sql rename to packages/cli/legacy-pg-migrations/0013_pep57_releases.sql diff --git a/packages/cli/package.json b/packages/cli/package.json index abaa8675..e5cf0316 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -14,6 +14,7 @@ "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*", - "@peppa/runner": "workspace:*" + "@peppa/runner": "workspace:*", + "postgres": "4.1.1" } } diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 4635b0ef..a1db5dba 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -38,7 +38,7 @@ import { updateTask, type TaskStatus, } from "@peppa/core"; -import { createDb } from "@peppa/db"; +import { createDb, migrateDb } from "@peppa/db"; import { answerAndDeliver, connectCi, deployProd, listReleases, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { loadEnv } from "@peppa/shared"; @@ -73,6 +73,8 @@ const USAGE = `peppa — Peppa software factory CLI peppa user ensure mock-<name> (local test user) peppa web login-link <gitea-login> (one-time admin login, 10 minutes) peppa watchdog [--once] [--interval <sec>] [--stall <min>] + peppa db migrate (apply schema migrations to PEPPA_DB) + peppa db migrate-to-sqlite <file> (one-time copy from Postgres DATABASE_URL, read-only) KEY defaults to the project of the current directory (.peppa/project.json). Statuses: ${TASK_STATUSES.join(", ")}`; @@ -101,7 +103,31 @@ const { values: opts, positionals } = parseArgs({ }); const env = loadEnv(); -const db = createDb(env.DATABASE_URL); + +// `db` commands run before the database is opened: they create or replace the file. +if (positionals[0] === "db") { + try { + if (positionals[1] === "migrate") { + migrateDb(createDb(env.PEPPA_DB)); + console.log(`migrated ${env.PEPPA_DB}`); + } else if (positionals[1] === "migrate-to-sqlite" && positionals[2]) { + if (!env.DATABASE_URL) throw new PeppaError("DATABASE_URL (the Postgres source) is not set"); + const { migrateToSqlite } = await import("./migrate-to-sqlite.ts"); + const r = await migrateToSqlite(env.DATABASE_URL, resolve(positionals[2])); + for (const t of r.tables) console.log(`${t.name.padEnd(20)} ${t.copied}`); + console.log(`перенесено, расхождений нет: ${r.file} (${r.ms} мс)`); + } else { + console.error(USAGE); + process.exit(1); + } + process.exit(0); + } catch (e) { + console.error(`peppa: ${(e as Error).message}`); + process.exit(1); + } +} + +const db = createDb(env.PEPPA_DB); const here = findProjectFile(process.cwd())?.data.key; const [group, cmd, ...args] = positionals; diff --git a/packages/cli/src/migrate-to-sqlite.ts b/packages/cli/src/migrate-to-sqlite.ts new file mode 100644 index 00000000..d02ee5cc --- /dev/null +++ b/packages/cli/src/migrate-to-sqlite.ts @@ -0,0 +1,69 @@ +// One-time move of Peppa's data from Postgres to SQLite (PEP-36): +// peppa db migrate-to-sqlite <file> (source: DATABASE_URL) +// The Postgres session is read-only, so the source cannot change. The new file is built +// next to the target and renamed into place only after row counts and foreign keys check +// out; on any mismatch it is deleted and nothing else is touched. +import { createDb, migrateDb, tablesInFkOrder } from "@peppa/db"; +import { existsSync, renameSync, rmSync } from "node:fs"; +import postgres from "postgres"; + +const toSqlite = (v: unknown, c: { json: boolean; ms: boolean; bool: boolean }) => { + if (v === null || v === undefined) return null; + if (c.ms) return v instanceof Date ? v.getTime() : new Date(String(v)).getTime(); + if (c.bool) return v ? 1 : 0; + if (c.json) return JSON.stringify(v); + if (typeof v === "bigint") return Number(v); + if (v instanceof Date) return v.getTime(); + return v as string | number; +}; + +export interface MigrationReport { + file: string; + tables: { name: string; source: number; copied: number }[]; + ms: number; +} + +export async function migrateToSqlite(sourceUrl: string, file: string): Promise<MigrationReport> { + if (existsSync(file)) throw new Error(`${file} уже существует — переложите его`); + const tmp = `${file}.migrating`; + for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true }); + const pg = postgres(sourceUrl, { max: 1, onnotice: () => {}, connection: { default_transaction_read_only: "on" } as never }); + const t0 = Date.now(); + const db = createDb(tmp); + try { + migrateDb(db); + // Copy first, then check: foreign_key_check names the table with a dangling reference. + db.$client.db.exec("PRAGMA foreign_keys = OFF"); + const report: MigrationReport["tables"] = []; + // One read-only snapshot of Postgres for all tables. + await pg.begin("isolation level repeatable read read only", async (tx) => { + for (const t of tablesInFkOrder()) { + const rows = await tx.unsafe(`select * from "${t.name}"`); + const cols = t.columns.filter((c) => rows.length === 0 || c.name in rows[0]!); + if (rows.length) { + const stmt = db.$client.db.prepare(`insert into "${t.name}" (${cols.map((c) => `"${c.name}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`); + db.$client.transaction(() => { + for (const r of rows) stmt.run(...cols.map((c) => toSqlite(r[c.name], c))); + }).immediate(); + } + const [{ n }] = db.$client.db.prepare(`select count(*) n from "${t.name}"`).all() as { n: number }[]; + report.push({ name: t.name, source: rows.length, copied: Number(n) }); + } + }); + const bad = report.filter((t) => t.source !== t.copied); + if (bad.length) throw new Error(`расходится число строк: ${bad.map((t) => `${t.name} ${t.source}→${t.copied}`).join(", ")}`); + const fk = db.$client.db.prepare("PRAGMA foreign_key_check").all() as { table: string }[]; + if (fk.length) throw new Error(`${[...new Set(fk.map((r) => r.table))].join(", ")}: нарушение внешнего ключа`); + db.$client.db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + db.$client.close(); + renameSync(tmp, file); + for (const s of ["-wal", "-shm"]) rmSync(tmp + s, { force: true }); + return { file, tables: report, ms: Date.now() - t0 }; + } catch (e) { + db.$client.close(); + for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true }); + throw e; + } finally { + await pg.end({ timeout: 1 }); + } +} diff --git a/packages/core/src/backup.ts b/packages/core/src/backup.ts new file mode 100644 index 00000000..5660459d --- /dev/null +++ b/packages/core/src/backup.ts @@ -0,0 +1,52 @@ +import type { Db } from "@peppa/db"; +import { peppaHome } from "@peppa/shared"; +import { mkdirSync, readdirSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { alertAdmins } from "./monitor.ts"; +import { getSetting, setSetting } from "./settings.ts"; + +const DAY_MS = 24 * 3600_000; +const KEY = "backup:last"; + +export interface BackupOptions { + now?: Date; + dir?: string; + keep?: number; + /** Back up even if the last copy is younger than a day. */ + force?: boolean; + log?: (m: string) => void; +} + +/** + * Daily consistent copy of the database (`VACUUM INTO`, no need to stop anything) into + * ~/.peppa/backups/peppa-YYYY-MM-DD.db, keeping the newest `keep` (7). A failed copy is + * removed and the platform admins are told; the services keep running either way. + */ +export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: string; error?: string; skipped?: boolean }> { + const now = o.now ?? new Date(); + const log = o.log ?? (() => {}); + const last = await getSetting<{ at: number }>(db, KEY); + if (!o.force && last && now.getTime() - last.at < DAY_MS) return { skipped: true }; + const dir = o.dir ?? join(peppaHome(), "backups"); + const day = now.toLocaleDateString("sv-SE"); + const file = join(dir, `peppa-${day}.db`); + try { + mkdirSync(dir, { recursive: true }); + rmSync(file, { force: true }); // VACUUM INTO refuses to overwrite + db.$client.db.prepare("VACUUM INTO ?").run(file); + } catch (e) { + try { + rmSync(file, { force: true }); + } catch {} + const msg = (e as Error).message; + const reason = /SQLITE_FULL|ENOSPC|disk is full/i.test(msg) ? "нет места на диске" : msg; + await alertAdmins(db, `backup:fail:${day}`, `⚠️ Резервная копия базы Пеппы не сделана: ${reason}`, log); + return { error: reason }; + } + const keep = o.keep ?? 7; + const copies = readdirSync(dir).filter((f) => /^peppa-\d{4}-\d{2}-\d{2}\.db$/.test(f)).sort(); + for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true }); + await setSetting(db, KEY, { at: now.getTime(), file }); + log(`backup: ${file}`); + return { file }; +} diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts index 107b7d4f..80c9adf9 100644 --- a/packages/core/src/incidents.ts +++ b/packages/core/src/incidents.ts @@ -202,12 +202,12 @@ export async function updateIncident(db: Db, id: number, patch: Partial<Omit<Inc return row; } -/** Takes incidents nobody has applied the policy to yet; each one is returned once. */ +/** Takes incidents nobody has applied the policy to yet; each one is returned once (one statement: SQLite runs writers one at a time). */ export async function claimNewIncidents(db: Db, limit = 20): Promise<Incident[]> { return db .update(incidents) .set({ status: "pending" }) - .where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit} for update skip locked)`)) + .where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit})`)) .returning(); } @@ -216,7 +216,7 @@ export async function autoIncidentTasksToday(db: Db, projectId: number, now = ne const midnight = new Date(now); midnight.setHours(0, 0, 0, 0); const [r] = await db - .select({ n: sql<number>`count(*)::int` }) + .select({ n: sql<number>`count(*)` }) .from(incidents) .where(and(eq(incidents.projectId, projectId), gte(incidents.taskCreatedAt, midnight), inArray(incidents.decidedBy, ["policy", "triage"]))); return r?.n ?? 0; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c224e041..651f1cd7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,6 +13,7 @@ export * from "./users.ts"; export * from "./oauth.ts"; export * from "./access.ts"; export * from "./monitor.ts"; +export * from "./backup.ts"; export * from "./repo-info.ts"; export * from "./incidents.ts"; export * from "./ci.ts"; diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts index 9c274dfc..33e0b686 100644 --- a/packages/core/src/monitor.ts +++ b/packages/core/src/monitor.ts @@ -121,7 +121,7 @@ export async function adminRecipients(db: Db): Promise<User[]> { // ── checks ───────────────────────────────────────────────────────────────────────── -async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise<number> { +export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise<number> { const to = await adminRecipients(db); if (!to.length) { log(`monitor: ${text} (нет админа с Telegram)`); @@ -203,7 +203,7 @@ export async function healthReport(db: Db, o: { now?: Date; version?: string; co let timer: NodeJS.Timeout | undefined; try { await Promise.race([ - db.execute(sql`select 1`), + (async () => db.get(sql`select 1 from settings limit 1`))(), new Promise((_, rej) => (timer = setTimeout(() => rej(new Error("database timeout")), o.timeoutMs ?? 3000))), ]); } catch (e) { diff --git a/packages/core/src/notify.ts b/packages/core/src/notify.ts index a3a4d7bc..96b272b3 100644 --- a/packages/core/src/notify.ts +++ b/packages/core/src/notify.ts @@ -1,7 +1,8 @@ import type { Db } from "@peppa/db"; -import { sql } from "drizzle-orm"; - -export const EVENTS_CHANNEL = "peppa_events"; +import { peppaHome } from "@peppa/shared"; +import { existsSync, rmSync } from "node:fs"; +import { connect, createServer } from "node:net"; +import { join } from "node:path"; export type PeppaNotification = | { type: "question"; questionId: number } @@ -11,7 +12,61 @@ export type PeppaNotification = | { type: "session_updated"; sessionId: number } | { type: "incident"; incidentId: number }; -/** Broadcasts via Postgres NOTIFY; the bot and web listen on EVENTS_CHANNEL. */ -export async function notify(db: Db, n: PeppaNotification): Promise<void> { - await db.execute(sql`select pg_notify(${EVENTS_CHANNEL}, ${JSON.stringify(n)})`); +/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME. */ +export const SUBSCRIBERS = ["bot"] as const; +export type Subscriber = (typeof SUBSCRIBERS)[number]; + +export const eventsSocket = (service: Subscriber) => join(peppaHome(), `${service}.events.sock`); + +/** + * Wakes the subscribers after a write (replaces Postgres NOTIFY, PEP-36). Fire and forget: + * the data is already in the database, and a subscriber that misses the poke finds the + * change by its own polling (PRAGMA data_version) within a second. + */ +export async function notify(_db: Db, n: PeppaNotification): Promise<void> { + const line = `${JSON.stringify(n)}\n`; + await Promise.all( + SUBSCRIBERS.map( + (service) => + new Promise<void>((resolve) => { + const path = eventsSocket(service); + if (!existsSync(path)) return resolve(); + const sock = connect(path); + const done = () => (sock.destroy(), resolve()); + sock.setTimeout(200, done); + sock.on("error", done); + sock.end(line, done); + }), + ), + ); +} + +/** Listens for notify() pokes; returns a function that stops listening. */ +export async function listenEvents(service: Subscriber, onEvent: (n: PeppaNotification) => void): Promise<() => Promise<void>> { + const path = eventsSocket(service); + rmSync(path, { force: true }); // left over from a crashed run + const server = createServer((sock) => { + let buf = ""; + sock.setEncoding("utf8"); + sock.on("data", (c) => { + buf += c; + for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) { + const line = buf.slice(0, i); + buf = buf.slice(i + 1); + try { + onEvent(JSON.parse(line)); + } catch {} + } + }); + sock.on("error", () => {}); + }); + await new Promise<void>((resolve, reject) => { + server.once("error", reject); + server.listen(path, resolve); + }); + return () => + new Promise<void>((resolve) => { + server.close(() => resolve()); + rmSync(path, { force: true }); + }); } diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index f392e3e1..40f1b93d 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -46,21 +46,27 @@ export interface NewTask { } export async function createTask(db: Db, t: NewTask): Promise<TaskRef> { - return db.transaction(async (tx) => { - // Hand out the per-project number atomically. - const [project] = await tx - .update(projects) - .set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` }) - .where(eq(projects.id, t.projectId)) - .returning(); - if (!project) throw new PeppaError(`Project #${t.projectId} not found`); - if (t.goalId != null) await getGoal(tx as unknown as Db, t.projectId, t.goalId); - const [task] = await tx - .insert(tasks) - .values({ ...t, number: project.nextTaskNumber - 1 }) - .returning(); - return { project, task: task!, key: formatTaskKey(project.key, task!.number) }; - }); + if (t.goalId != null) await getGoal(db, t.projectId, t.goalId); + // Hand out the per-project number atomically. SQLite transactions are synchronous: no + // await inside (the driver refuses an async callback). + return db.transaction( + (tx) => { + const [project] = tx + .update(projects) + .set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` }) + .where(eq(projects.id, t.projectId)) + .returning() + .all(); + if (!project) throw new PeppaError(`Project #${t.projectId} not found`); + const task = tx + .insert(tasks) + .values({ ...t, number: project.nextTaskNumber - 1 }) + .returning() + .get(); + return { project, task, key: formatTaskKey(project.key, task.number) }; + }, + { behavior: "immediate" }, + ); } export interface TaskFilter { diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts index 60b7c251..05e1e8fe 100644 --- a/packages/core/src/telegram.ts +++ b/packages/core/src/telegram.ts @@ -142,7 +142,8 @@ export async function questionByTelegramMessage(db: Db, chatId: number, messageI and( eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.telegramMessageId, messageId), - sql`${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`, + // json_extract, not ->>: chat_id may be stored as a number or a string. + sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`, ), ); return row?.q ?? null; diff --git a/packages/db/drizzle.config.ts b/packages/db/drizzle.config.ts index 8ccff936..0c5e92f3 100644 --- a/packages/db/drizzle.config.ts +++ b/packages/db/drizzle.config.ts @@ -1,8 +1,8 @@ import { defineConfig } from "drizzle-kit"; +// `drizzle-kit generate` only; migrations are applied by `peppa db migrate` (node:sqlite). export default defineConfig({ - dialect: "postgresql", + dialect: "sqlite", schema: "./src/schema.ts", out: "./migrations", - dbCredentials: { url: process.env.DATABASE_URL ?? "postgres://peppa:peppa@127.0.0.1:5433/peppa" }, }); diff --git a/packages/db/migrations/0000_baseline.sql b/packages/db/migrations/0000_baseline.sql new file mode 100644 index 00000000..3e9a1aec --- /dev/null +++ b/packages/db/migrations/0000_baseline.sql @@ -0,0 +1,313 @@ +CREATE TABLE `check_runs` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `sha` text NOT NULL, + `branch` text, + `pr_number` integer, + `check` text NOT NULL, + `state` text NOT NULL, + `run_url` text, + `log_tail` text, + `duration_sec` integer, + `source` text DEFAULT 'report' NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `check_runs_project_sha_check` ON `check_runs` (`project_id`,`sha`,`check`);--> statement-breakpoint +CREATE TABLE `error_sources` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `kind` text NOT NULL, + `bugsink_project_id` integer NOT NULL, + `dsn` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `error_sources_bugsink_project_id_unique` ON `error_sources` (`bugsink_project_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `error_sources_project_kind` ON `error_sources` (`project_id`,`kind`);--> statement-breakpoint +CREATE TABLE `events` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `session_id` integer, + `type` text NOT NULL, + `payload` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `goals` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `title` text NOT NULL, + `description` text, + `status` text DEFAULT 'open' NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `incident_settings` ( + `project_id` integer PRIMARY KEY NOT NULL, + `hook_secret` text NOT NULL, + `policy` text DEFAULT 'backlog' NOT NULL, + `triage_prompt` text, + `environments` text DEFAULT '["prod","production"]' NOT NULL, + `daily_limit` integer DEFAULT 5 NOT NULL, + `ignore_pattern` text, + `goal_id` integer, + `webhook_auto` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `incident_settings_hook_secret_unique` ON `incident_settings` (`hook_secret`);--> statement-breakpoint +CREATE TABLE `incidents` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `source` text NOT NULL, + `bugsink_issue_id` text NOT NULL, + `friendly_id` text, + `title` text NOT NULL, + `culprit` text, + `level` text, + `environment` text, + `first_release` text, + `last_release` text, + `events` integer DEFAULT 1 NOT NULL, + `first_seen` integer NOT NULL, + `last_seen` integer NOT NULL, + `url` text, + `stack` text, + `status` text DEFAULT 'new' NOT NULL, + `decision` text, + `decided_by` text, + `decision_reason` text, + `task_id` integer, + `task_created_at` integer, + `resolved_release` text, + `resolved_at` integer, + `regressions` integer DEFAULT 0 NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `incidents_bugsink_issue_id_unique` ON `incidents` (`bugsink_issue_id`);--> statement-breakpoint +CREATE TABLE `oauth_clients` ( + `id` text PRIMARY KEY NOT NULL, + `name` text NOT NULL, + `redirect_uris` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `oauth_codes` ( + `code_hash` text PRIMARY KEY NOT NULL, + `client_id` text NOT NULL, + `user_id` integer NOT NULL, + `redirect_uri` text NOT NULL, + `code_challenge` text NOT NULL, + `scope` text, + `expires_at` integer NOT NULL, + `used_at` integer, + FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `oauth_tokens` ( + `token_hash` text PRIMARY KEY NOT NULL, + `kind` text NOT NULL, + `client_id` text NOT NULL, + `user_id` integer NOT NULL, + `scope` text, + `expires_at` integer NOT NULL, + `revoked_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_used_at` integer, + FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `project_invites` ( + `project_id` integer NOT NULL, + `login` text NOT NULL, + `invited_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`project_id`, `login`), + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`invited_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `project_members` ( + `project_id` integer NOT NULL, + `user_id` integer NOT NULL, + `added_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`project_id`, `user_id`), + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`added_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `projects` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `slug` text NOT NULL, + `key` text NOT NULL, + `name` text NOT NULL, + `description` text, + `gitea_owner` text NOT NULL, + `gitea_repo` text NOT NULL, + `default_branch` text DEFAULT 'main' NOT NULL, + `workspace_path` text NOT NULL, + `owner_id` integer, + `next_task_number` integer DEFAULT 1 NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `projects_slug_unique` ON `projects` (`slug`);--> statement-breakpoint +CREATE UNIQUE INDEX `projects_key_unique` ON `projects` (`key`);--> statement-breakpoint +CREATE TABLE `questions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `session_id` integer, + `kind` text NOT NULL, + `text` text NOT NULL, + `options` text, + `answer` text, + `answered_via` text, + `telegram_message_id` integer, + `awaiting_hook` integer DEFAULT false NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `answered_at` integer, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE TABLE `releases` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `env` text NOT NULL, + `sha` text NOT NULL, + `previous_sha` text, + `image` text, + `host` text, + `pr_number` integer, + `tasks` text DEFAULT '[]' NOT NULL, + `status` text DEFAULT 'deploying' NOT NULL, + `deployed_by` text DEFAULT 'ci' NOT NULL, + `reason` text, + `run_url` text, + `log_tail` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `sessions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `task_id` integer, + `tmux_name` text NOT NULL, + `provider` text DEFAULT 'claude' NOT NULL, + `claude_session_id` text, + `generation` integer DEFAULT 0 NOT NULL, + `auto_nudges` integer DEFAULT 0 NOT NULL, + `resume_at` integer, + `limit_probe_min` integer, + `limit_resumes` integer DEFAULT 0 NOT NULL, + `limit_resumes_day` text, + `limit_resumed_at` integer, + `status` text DEFAULT 'starting' NOT NULL, + `last_activity_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `ended_at` integer, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `sessions_tmux_name_unique` ON `sessions` (`tmux_name`);--> statement-breakpoint +CREATE TABLE `settings` ( + `key` text PRIMARY KEY NOT NULL, + `value` text NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `tasks` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `project_id` integer NOT NULL, + `goal_id` integer, + `number` integer NOT NULL, + `title` text NOT NULL, + `description` text, + `status` text DEFAULT 'backlog' NOT NULL, + `openspec_change` text, + `pr_url` text, + `ci_attempts` integer DEFAULT 0 NOT NULL, + `ci_failed_sha` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `tasks_project_number` ON `tasks` (`project_id`,`number`);--> statement-breakpoint +CREATE TABLE `telegram_outbox` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `dedupe_key` text NOT NULL, + `method` text NOT NULL, + `params` text NOT NULL, + `question_id` integer, + `status` text DEFAULT 'pending' NOT NULL, + `attempts` integer DEFAULT 0 NOT NULL, + `next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `telegram_message_id` integer, + `error` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `sent_at` integer, + FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `telegram_outbox_dedupe_key_unique` ON `telegram_outbox` (`dedupe_key`);--> statement-breakpoint +CREATE TABLE `telegram_updates` ( + `update_id` integer PRIMARY KEY NOT NULL, + `status` text NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL +); +--> statement-breakpoint +CREATE TABLE `users` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `gitea_id` integer NOT NULL, + `login` text NOT NULL, + `name` text, + `email` text, + `avatar_url` text, + `access_token_enc` text, + `refresh_token_enc` text, + `token_expires_at` integer, + `claude_token_enc` text, + `claude_token_set_at` integer, + `telegram_chat_id` integer, + `telegram_user_id` integer, + `telegram_username` text, + `telegram_paired_at` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_login_at` integer +); +--> statement-breakpoint +CREATE UNIQUE INDEX `users_gitea_id_unique` ON `users` (`gitea_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `users_login_unique` ON `users` (`login`);--> statement-breakpoint +CREATE UNIQUE INDEX `users_telegram_chat_id_unique` ON `users` (`telegram_chat_id`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0000_snapshot.json b/packages/db/migrations/meta/0000_snapshot.json index a2548dc1..14467986 100644 --- a/packages/db/migrations/meta/0000_snapshot.json +++ b/packages/db/migrations/meta/0000_snapshot.json @@ -1,55 +1,292 @@ { - "id": "2281ab22-b150-4664-9ffc-a0bb54103d9c", + "version": "6", + "dialect": "sqlite", + "id": "7fd81ecb-0ba2-4d0d-9ee9-d1239d6d9725", "prevId": "00000000-0000-0000-0000-000000000000", - "version": "7", - "dialect": "postgresql", "tables": { - "public.events": { - "name": "events", - "schema": "", + "check_runs": { + "name": "check_runs", "columns": { "id": { "name": "id", - "type": "serial", + "type": "integer", "primaryKey": true, - "notNull": true + "notNull": true, + "autoincrement": true }, "project_id": { "name": "project_id", "type": "integer", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "task_id": { "name": "task_id", "type": "integer", "primaryKey": false, - "notNull": 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 + } + }, + "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": {} + }, + "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 + "notNull": false, + "autoincrement": false }, "type": { "name": "type", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "payload": { "name": "payload", - "type": "jsonb", + "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "created_at": { "name": "created_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" } }, "indexes": {}, @@ -96,59 +333,62 @@ }, "compositePrimaryKeys": {}, "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false + "checkConstraints": {} }, - "public.goals": { + "goals": { "name": "goals", - "schema": "", "columns": { "id": { "name": "id", - "type": "serial", + "type": "integer", "primaryKey": true, - "notNull": true + "notNull": true, + "autoincrement": true }, "project_id": { "name": "project_id", "type": "integer", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "title": { "name": "title", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "description": { "name": "description", "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "status": { "name": "status", - "type": "goal_status", - "typeSchema": "public", + "type": "text", "primaryKey": false, "notNull": true, + "autoincrement": false, "default": "'open'" }, "created_at": { "name": "created_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" }, "updated_at": { "name": "updated_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" } }, "indexes": {}, @@ -169,190 +409,998 @@ }, "compositePrimaryKeys": {}, "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false + "checkConstraints": {} }, - "public.projects": { - "name": "projects", - "schema": "", + "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": "serial", + "type": "integer", "primaryKey": true, - "notNull": true + "notNull": true, + "autoincrement": true }, - "slug": { - "name": "slug", + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, - "key": { - "name": "key", + "bugsink_issue_id": { + "name": "bugsink_issue_id", "type": "text", "primaryKey": false, - "notNull": true + "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 + "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": {} + }, + "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 + "notNull": false, + "autoincrement": false }, "gitea_owner": { "name": "gitea_owner", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "gitea_repo": { "name": "gitea_repo", "type": "text", "primaryKey": false, - "notNull": true + "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 + "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 }, "created_at": { "name": "created_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" }, "updated_at": { "name": "updated_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" } }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { + "indexes": { "projects_slug_unique": { "name": "projects_slug_unique", - "nullsNotDistinct": false, "columns": [ "slug" - ] + ], + "isUnique": true }, "projects_key_unique": { "name": "projects_key_unique", - "nullsNotDistinct": false, "columns": [ "key" - ] + ], + "isUnique": true } }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} }, - "public.questions": { + "questions": { "name": "questions", - "schema": "", "columns": { "id": { "name": "id", - "type": "serial", + "type": "integer", "primaryKey": true, - "notNull": true + "notNull": true, + "autoincrement": true }, "project_id": { "name": "project_id", "type": "integer", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "task_id": { "name": "task_id", "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "session_id": { "name": "session_id", "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "kind": { "name": "kind", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "text": { "name": "text", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "options": { "name": "options", - "type": "jsonb", + "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "answer": { "name": "answer", "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "answered_via": { "name": "answered_via", "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "telegram_message_id": { "name": "telegram_message_id", "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false }, "created_at": { "name": "created_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" }, "answered_at": { "name": "answered_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false } }, "indexes": {}, @@ -399,73 +1447,287 @@ }, "compositePrimaryKeys": {}, "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false + "checkConstraints": {} }, - "public.sessions": { - "name": "sessions", - "schema": "", + "releases": { + "name": "releases", "columns": { "id": { "name": "id", - "type": "serial", + "type": "integer", "primaryKey": true, - "notNull": true + "notNull": true, + "autoincrement": true }, "project_id": { "name": "project_id", "type": "integer", "primaryKey": false, - "notNull": true + "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 + }, + "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": {} + }, + "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 + "notNull": false, + "autoincrement": false }, "tmux_name": { "name": "tmux_name", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" }, "claude_session_id": { "name": "claude_session_id", "type": "text", "primaryKey": false, - "notNull": 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 }, "status": { "name": "status", - "type": "session_status", - "typeSchema": "public", + "type": "text", "primaryKey": false, "notNull": true, + "autoincrement": false, "default": "'starting'" }, "last_activity_at": { "name": "last_activity_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "created_at": { "name": "created_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" }, "ended_at": { "name": "ended_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true } }, - "indexes": {}, "foreignKeys": { "sessions_project_id_projects_id_fk": { "name": "sessions_project_id_projects_id_fk", @@ -495,115 +1757,148 @@ } }, "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] + "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))" } }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} }, - "public.tasks": { + "tasks": { "name": "tasks", - "schema": "", "columns": { "id": { "name": "id", - "type": "serial", + "type": "integer", "primaryKey": true, - "notNull": true + "notNull": true, + "autoincrement": true }, "project_id": { "name": "project_id", "type": "integer", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "goal_id": { "name": "goal_id", "type": "integer", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "number": { "name": "number", "type": "integer", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "title": { "name": "title", "type": "text", "primaryKey": false, - "notNull": true + "notNull": true, + "autoincrement": false }, "description": { "name": "description", "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "status": { "name": "status", - "type": "task_status", - "typeSchema": "public", + "type": "text", "primaryKey": false, "notNull": true, + "autoincrement": false, "default": "'backlog'" }, "openspec_change": { "name": "openspec_change", "type": "text", "primaryKey": false, - "notNull": false + "notNull": false, + "autoincrement": false }, "pr_url": { "name": "pr_url", "type": "text", "primaryKey": false, - "notNull": 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 }, "created_at": { "name": "created_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" }, "updated_at": { "name": "updated_at", - "type": "timestamp with time zone", + "type": "integer", "primaryKey": false, "notNull": true, - "default": "now()" + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" } }, "indexes": { "tasks_project_number": { "name": "tasks_project_number", "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } + "project_id", + "number" ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} + "isUnique": true } }, "foreignKeys": { @@ -636,56 +1931,321 @@ }, "compositePrimaryKeys": {}, "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {}, + "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 + }, + "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 + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} } }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, "views": {}, + "enums": {}, "_meta": { - "columns": {}, "schemas": {}, - "tables": {} + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} } } \ No newline at end of file diff --git a/packages/db/migrations/meta/0001_snapshot.json b/packages/db/migrations/meta/0001_snapshot.json deleted file mode 100644 index bcd77562..00000000 --- a/packages/db/migrations/meta/0001_snapshot.json +++ /dev/null @@ -1,706 +0,0 @@ -{ - "id": "7e63ed2b-721c-4506-a2ab-21922112a126", - "prevId": "2281ab22-b150-4664-9ffc-a0bb54103d9c", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0002_snapshot.json b/packages/db/migrations/meta/0002_snapshot.json deleted file mode 100644 index 2a1ec5e3..00000000 --- a/packages/db/migrations/meta/0002_snapshot.json +++ /dev/null @@ -1,713 +0,0 @@ -{ - "id": "93b4fb9b-40f7-4af5-9ff7-b89be76777ed", - "prevId": "7e63ed2b-721c-4506-a2ab-21922112a126", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json deleted file mode 100644 index 2abf1302..00000000 --- a/packages/db/migrations/meta/0003_snapshot.json +++ /dev/null @@ -1,888 +0,0 @@ -{ - "id": "6c02c03e-025e-4f66-83bc-fbb2ac391ed4", - "prevId": "93b4fb9b-40f7-4af5-9ff7-b89be76777ed", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0004_snapshot.json b/packages/db/migrations/meta/0004_snapshot.json deleted file mode 100644 index 9d06fd40..00000000 --- a/packages/db/migrations/meta/0004_snapshot.json +++ /dev/null @@ -1,1003 +0,0 @@ -{ - "id": "1e918b46-e483-457b-8af7-6234a462627c", - "prevId": "6c02c03e-025e-4f66-83bc-fbb2ac391ed4", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0005_snapshot.json b/packages/db/migrations/meta/0005_snapshot.json deleted file mode 100644 index 4bf59ff2..00000000 --- a/packages/db/migrations/meta/0005_snapshot.json +++ /dev/null @@ -1,1010 +0,0 @@ -{ - "id": "62fecad8-73cc-4298-a603-a38021323859", - "prevId": "1e918b46-e483-457b-8af7-6234a462627c", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0006_snapshot.json b/packages/db/migrations/meta/0006_snapshot.json deleted file mode 100644 index c656e4b6..00000000 --- a/packages/db/migrations/meta/0006_snapshot.json +++ /dev/null @@ -1,1231 +0,0 @@ -{ - "id": "141bce5b-54a3-438f-b6c9-edf22525ab7b", - "prevId": "62fecad8-73cc-4298-a603-a38021323859", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0007_snapshot.json b/packages/db/migrations/meta/0007_snapshot.json deleted file mode 100644 index 3d6d1c5d..00000000 --- a/packages/db/migrations/meta/0007_snapshot.json +++ /dev/null @@ -1,1243 +0,0 @@ -{ - "id": "d7d79655-c98d-4cc6-b49b-b8db3ce22738", - "prevId": "141bce5b-54a3-438f-b6c9-edf22525ab7b", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0008_snapshot.json b/packages/db/migrations/meta/0008_snapshot.json deleted file mode 100644 index 4c6b99ff..00000000 --- a/packages/db/migrations/meta/0008_snapshot.json +++ /dev/null @@ -1,1402 +0,0 @@ -{ - "id": "69625371-6b59-41c2-8555-4582c3e311fa", - "prevId": "d7d79655-c98d-4cc6-b49b-b8db3ce22738", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_invites": { - "name": "project_invites", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "invited_by": { - "name": "invited_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_invites_project_id_login_pk", - "columns": [ - "project_id", - "login" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_members": { - "name": "project_members", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "added_by": { - "name": "added_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_members_project_id_user_id_pk", - "columns": [ - "project_id", - "user_id" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0009_snapshot.json b/packages/db/migrations/meta/0009_snapshot.json deleted file mode 100644 index c55b0666..00000000 --- a/packages/db/migrations/meta/0009_snapshot.json +++ /dev/null @@ -1,1433 +0,0 @@ -{ - "id": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4", - "prevId": "69625371-6b59-41c2-8555-4582c3e311fa", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_invites": { - "name": "project_invites", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "invited_by": { - "name": "invited_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_invites_project_id_login_pk", - "columns": [ - "project_id", - "login" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_members": { - "name": "project_members", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "added_by": { - "name": "added_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_members_project_id_user_id_pk", - "columns": [ - "project_id", - "user_id" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "telegram_chat_id": { - "name": "telegram_chat_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_user_id": { - "name": "telegram_user_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_username": { - "name": "telegram_username", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_paired_at": { - "name": "telegram_paired_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - }, - "users_telegram_chat_id_unique": { - "name": "users_telegram_chat_id_unique", - "nullsNotDistinct": false, - "columns": [ - "telegram_chat_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0010_snapshot.json b/packages/db/migrations/meta/0010_snapshot.json deleted file mode 100644 index 38b990ca..00000000 --- a/packages/db/migrations/meta/0010_snapshot.json +++ /dev/null @@ -1,1464 +0,0 @@ -{ - "id": "d5839a22-0118-42d7-9632-545e36e36848", - "prevId": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_invites": { - "name": "project_invites", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "invited_by": { - "name": "invited_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_invites_project_id_login_pk", - "columns": [ - "project_id", - "login" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_members": { - "name": "project_members", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "added_by": { - "name": "added_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_members_project_id_user_id_pk", - "columns": [ - "project_id", - "user_id" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "resume_at": { - "name": "resume_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "limit_probe_min": { - "name": "limit_probe_min", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "limit_resumes": { - "name": "limit_resumes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "limit_resumes_day": { - "name": "limit_resumes_day", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "limit_resumed_at": { - "name": "limit_resumed_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "telegram_chat_id": { - "name": "telegram_chat_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_user_id": { - "name": "telegram_user_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_username": { - "name": "telegram_username", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_paired_at": { - "name": "telegram_paired_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - }, - "users_telegram_chat_id_unique": { - "name": "users_telegram_chat_id_unique", - "nullsNotDistinct": false, - "columns": [ - "telegram_chat_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0011_snapshot.json b/packages/db/migrations/meta/0011_snapshot.json deleted file mode 100644 index 3823a4fc..00000000 --- a/packages/db/migrations/meta/0011_snapshot.json +++ /dev/null @@ -1,1893 +0,0 @@ -{ - "id": "47a9fc06-6fdb-42ad-8a5f-d80e76193258", - "prevId": "d5839a22-0118-42d7-9632-545e36e36848", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.error_sources": { - "name": "error_sources", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "bugsink_project_id": { - "name": "bugsink_project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "dsn": { - "name": "dsn", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "error_sources_project_kind": { - "name": "error_sources_project_kind", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "kind", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": { - "error_sources_bugsink_project_id_unique": { - "name": "error_sources_bugsink_project_id_unique", - "nullsNotDistinct": false, - "columns": [ - "bugsink_project_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.incident_settings": { - "name": "incident_settings", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "hook_secret": { - "name": "hook_secret", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "policy": { - "name": "policy", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "triage_prompt": { - "name": "triage_prompt", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "environments": { - "name": "environments", - "type": "jsonb", - "primaryKey": false, - "notNull": true, - "default": "'[\"prod\",\"production\"]'::jsonb" - }, - "daily_limit": { - "name": "daily_limit", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 5 - }, - "ignore_pattern": { - "name": "ignore_pattern", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "webhook_auto": { - "name": "webhook_auto", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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": { - "incident_settings_hook_secret_unique": { - "name": "incident_settings_hook_secret_unique", - "nullsNotDistinct": false, - "columns": [ - "hook_secret" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.incidents": { - "name": "incidents", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "source": { - "name": "source", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "bugsink_issue_id": { - "name": "bugsink_issue_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "friendly_id": { - "name": "friendly_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "culprit": { - "name": "culprit", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "level": { - "name": "level", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "environment": { - "name": "environment", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "first_release": { - "name": "first_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "last_release": { - "name": "last_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "events": { - "name": "events", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "first_seen": { - "name": "first_seen", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "last_seen": { - "name": "last_seen", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "url": { - "name": "url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "stack": { - "name": "stack", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'new'" - }, - "decision": { - "name": "decision", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "decided_by": { - "name": "decided_by", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "decision_reason": { - "name": "decision_reason", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "task_created_at": { - "name": "task_created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "resolved_release": { - "name": "resolved_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "resolved_at": { - "name": "resolved_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "regressions": { - "name": "regressions", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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": { - "incidents_bugsink_issue_id_unique": { - "name": "incidents_bugsink_issue_id_unique", - "nullsNotDistinct": false, - "columns": [ - "bugsink_issue_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_invites": { - "name": "project_invites", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "invited_by": { - "name": "invited_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_invites_project_id_login_pk", - "columns": [ - "project_id", - "login" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_members": { - "name": "project_members", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "added_by": { - "name": "added_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_members_project_id_user_id_pk", - "columns": [ - "project_id", - "user_id" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "resume_at": { - "name": "resume_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "limit_probe_min": { - "name": "limit_probe_min", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "limit_resumes": { - "name": "limit_resumes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "limit_resumes_day": { - "name": "limit_resumes_day", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "limit_resumed_at": { - "name": "limit_resumed_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "telegram_chat_id": { - "name": "telegram_chat_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_user_id": { - "name": "telegram_user_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_username": { - "name": "telegram_username", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_paired_at": { - "name": "telegram_paired_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - }, - "users_telegram_chat_id_unique": { - "name": "users_telegram_chat_id_unique", - "nullsNotDistinct": false, - "columns": [ - "telegram_chat_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0012_snapshot.json b/packages/db/migrations/meta/0012_snapshot.json deleted file mode 100644 index c30f3501..00000000 --- a/packages/db/migrations/meta/0012_snapshot.json +++ /dev/null @@ -1,2061 +0,0 @@ -{ - "id": "ca89d235-ea51-4284-95fe-50b24621c88a", - "prevId": "47a9fc06-6fdb-42ad-8a5f-d80e76193258", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.check_runs": { - "name": "check_runs", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "sha": { - "name": "sha", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "branch": { - "name": "branch", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_number": { - "name": "pr_number", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "check": { - "name": "check", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "run_url": { - "name": "run_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "log_tail": { - "name": "log_tail", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "duration_sec": { - "name": "duration_sec", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "source": { - "name": "source", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'report'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "check_runs_project_sha_check": { - "name": "check_runs_project_sha_check", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "sha", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "check", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.error_sources": { - "name": "error_sources", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "bugsink_project_id": { - "name": "bugsink_project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "dsn": { - "name": "dsn", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "error_sources_project_kind": { - "name": "error_sources_project_kind", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "kind", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": { - "error_sources_bugsink_project_id_unique": { - "name": "error_sources_bugsink_project_id_unique", - "nullsNotDistinct": false, - "columns": [ - "bugsink_project_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.incident_settings": { - "name": "incident_settings", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "hook_secret": { - "name": "hook_secret", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "policy": { - "name": "policy", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "triage_prompt": { - "name": "triage_prompt", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "environments": { - "name": "environments", - "type": "jsonb", - "primaryKey": false, - "notNull": true, - "default": "'[\"prod\",\"production\"]'::jsonb" - }, - "daily_limit": { - "name": "daily_limit", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 5 - }, - "ignore_pattern": { - "name": "ignore_pattern", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "webhook_auto": { - "name": "webhook_auto", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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": { - "incident_settings_hook_secret_unique": { - "name": "incident_settings_hook_secret_unique", - "nullsNotDistinct": false, - "columns": [ - "hook_secret" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.incidents": { - "name": "incidents", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "source": { - "name": "source", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "bugsink_issue_id": { - "name": "bugsink_issue_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "friendly_id": { - "name": "friendly_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "culprit": { - "name": "culprit", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "level": { - "name": "level", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "environment": { - "name": "environment", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "first_release": { - "name": "first_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "last_release": { - "name": "last_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "events": { - "name": "events", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "first_seen": { - "name": "first_seen", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "last_seen": { - "name": "last_seen", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "url": { - "name": "url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "stack": { - "name": "stack", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'new'" - }, - "decision": { - "name": "decision", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "decided_by": { - "name": "decided_by", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "decision_reason": { - "name": "decision_reason", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "task_created_at": { - "name": "task_created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "resolved_release": { - "name": "resolved_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "resolved_at": { - "name": "resolved_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "regressions": { - "name": "regressions", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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": { - "incidents_bugsink_issue_id_unique": { - "name": "incidents_bugsink_issue_id_unique", - "nullsNotDistinct": false, - "columns": [ - "bugsink_issue_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_invites": { - "name": "project_invites", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "invited_by": { - "name": "invited_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_invites_project_id_login_pk", - "columns": [ - "project_id", - "login" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_members": { - "name": "project_members", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "added_by": { - "name": "added_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_members_project_id_user_id_pk", - "columns": [ - "project_id", - "user_id" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "resume_at": { - "name": "resume_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "limit_probe_min": { - "name": "limit_probe_min", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "limit_resumes": { - "name": "limit_resumes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "limit_resumes_day": { - "name": "limit_resumes_day", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "limit_resumed_at": { - "name": "limit_resumed_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "ci_attempts": { - "name": "ci_attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "ci_failed_sha": { - "name": "ci_failed_sha", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "telegram_chat_id": { - "name": "telegram_chat_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_user_id": { - "name": "telegram_user_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_username": { - "name": "telegram_username", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_paired_at": { - "name": "telegram_paired_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - }, - "users_telegram_chat_id_unique": { - "name": "users_telegram_chat_id_unique", - "nullsNotDistinct": false, - "columns": [ - "telegram_chat_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/0013_snapshot.json b/packages/db/migrations/meta/0013_snapshot.json deleted file mode 100644 index 56cb70cd..00000000 --- a/packages/db/migrations/meta/0013_snapshot.json +++ /dev/null @@ -1,2189 +0,0 @@ -{ - "id": "82ed94db-27de-4e8f-81c1-5440cb5f4011", - "prevId": "ca89d235-ea51-4284-95fe-50b24621c88a", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.check_runs": { - "name": "check_runs", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "sha": { - "name": "sha", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "branch": { - "name": "branch", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_number": { - "name": "pr_number", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "check": { - "name": "check", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "run_url": { - "name": "run_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "log_tail": { - "name": "log_tail", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "duration_sec": { - "name": "duration_sec", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "source": { - "name": "source", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'report'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "check_runs_project_sha_check": { - "name": "check_runs_project_sha_check", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "sha", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "check", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.error_sources": { - "name": "error_sources", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "bugsink_project_id": { - "name": "bugsink_project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "dsn": { - "name": "dsn", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "error_sources_project_kind": { - "name": "error_sources_project_kind", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "kind", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": { - "error_sources_bugsink_project_id_unique": { - "name": "error_sources_bugsink_project_id_unique", - "nullsNotDistinct": false, - "columns": [ - "bugsink_project_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.events": { - "name": "events", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "type": { - "name": "type", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "payload": { - "name": "payload", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.goals": { - "name": "goals", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "goal_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'open'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.incident_settings": { - "name": "incident_settings", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "hook_secret": { - "name": "hook_secret", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "policy": { - "name": "policy", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "triage_prompt": { - "name": "triage_prompt", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "environments": { - "name": "environments", - "type": "jsonb", - "primaryKey": false, - "notNull": true, - "default": "'[\"prod\",\"production\"]'::jsonb" - }, - "daily_limit": { - "name": "daily_limit", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 5 - }, - "ignore_pattern": { - "name": "ignore_pattern", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "webhook_auto": { - "name": "webhook_auto", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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": { - "incident_settings_hook_secret_unique": { - "name": "incident_settings_hook_secret_unique", - "nullsNotDistinct": false, - "columns": [ - "hook_secret" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.incidents": { - "name": "incidents", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "source": { - "name": "source", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "bugsink_issue_id": { - "name": "bugsink_issue_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "friendly_id": { - "name": "friendly_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "culprit": { - "name": "culprit", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "level": { - "name": "level", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "environment": { - "name": "environment", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "first_release": { - "name": "first_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "last_release": { - "name": "last_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "events": { - "name": "events", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "first_seen": { - "name": "first_seen", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "last_seen": { - "name": "last_seen", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "url": { - "name": "url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "stack": { - "name": "stack", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'new'" - }, - "decision": { - "name": "decision", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "decided_by": { - "name": "decided_by", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "decision_reason": { - "name": "decision_reason", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "task_created_at": { - "name": "task_created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "resolved_release": { - "name": "resolved_release", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "resolved_at": { - "name": "resolved_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "regressions": { - "name": "regressions", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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": { - "incidents_bugsink_issue_id_unique": { - "name": "incidents_bugsink_issue_id_unique", - "nullsNotDistinct": false, - "columns": [ - "bugsink_issue_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_clients": { - "name": "oauth_clients", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "redirect_uris": { - "name": "redirect_uris", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_codes": { - "name": "oauth_codes", - "schema": "", - "columns": { - "code_hash": { - "name": "code_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "redirect_uri": { - "name": "redirect_uri", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "code_challenge": { - "name": "code_challenge", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "used_at": { - "name": "used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.oauth_tokens": { - "name": "oauth_tokens", - "schema": "", - "columns": { - "token_hash": { - "name": "token_hash", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true - }, - "revoked_at": { - "name": "revoked_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_used_at": { - "name": "last_used_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": 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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_invites": { - "name": "project_invites", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "invited_by": { - "name": "invited_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_invites_project_id_login_pk", - "columns": [ - "project_id", - "login" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.project_members": { - "name": "project_members", - "schema": "", - "columns": { - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "added_by": { - "name": "added_by", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": { - "name": "project_members_project_id_user_id_pk", - "columns": [ - "project_id", - "user_id" - ] - } - }, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.projects": { - "name": "projects", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "key": { - "name": "key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "gitea_owner": { - "name": "gitea_owner", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "gitea_repo": { - "name": "gitea_repo", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "default_branch": { - "name": "default_branch", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'main'" - }, - "workspace_path": { - "name": "workspace_path", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "owner_id": { - "name": "owner_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "next_task_number": { - "name": "next_task_number", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 1 - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "projects_slug_unique": { - "name": "projects_slug_unique", - "nullsNotDistinct": false, - "columns": [ - "slug" - ] - }, - "projects_key_unique": { - "name": "projects_key_unique", - "nullsNotDistinct": false, - "columns": [ - "key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.questions": { - "name": "questions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "session_id": { - "name": "session_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "text": { - "name": "text", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "options": { - "name": "options", - "type": "jsonb", - "primaryKey": false, - "notNull": false - }, - "answer": { - "name": "answer", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "answered_via": { - "name": "answered_via", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "awaiting_hook": { - "name": "awaiting_hook", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "answered_at": { - "name": "answered_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.releases": { - "name": "releases", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "env": { - "name": "env", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "sha": { - "name": "sha", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "previous_sha": { - "name": "previous_sha", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "image": { - "name": "image", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "host": { - "name": "host", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_number": { - "name": "pr_number", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tasks": { - "name": "tasks", - "type": "jsonb", - "primaryKey": false, - "notNull": true, - "default": "'[]'::jsonb" - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'deploying'" - }, - "deployed_by": { - "name": "deployed_by", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'ci'" - }, - "reason": { - "name": "reason", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "run_url": { - "name": "run_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "log_tail": { - "name": "log_tail", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.sessions": { - "name": "sessions", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "task_id": { - "name": "task_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "tmux_name": { - "name": "tmux_name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider": { - "name": "provider", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'claude'" - }, - "claude_session_id": { - "name": "claude_session_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "generation": { - "name": "generation", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "auto_nudges": { - "name": "auto_nudges", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "resume_at": { - "name": "resume_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "limit_probe_min": { - "name": "limit_probe_min", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "limit_resumes": { - "name": "limit_resumes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "limit_resumes_day": { - "name": "limit_resumes_day", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "limit_resumed_at": { - "name": "limit_resumed_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "session_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'starting'" - }, - "last_activity_at": { - "name": "last_activity_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "ended_at": { - "name": "ended_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "sessions_tmux_name_unique": { - "name": "sessions_tmux_name_unique", - "nullsNotDistinct": false, - "columns": [ - "tmux_name" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.settings": { - "name": "settings", - "schema": "", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "value": { - "name": "value", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.tasks": { - "name": "tasks", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "project_id": { - "name": "project_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "goal_id": { - "name": "goal_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "number": { - "name": "number", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "task_status", - "typeSchema": "public", - "primaryKey": false, - "notNull": true, - "default": "'backlog'" - }, - "openspec_change": { - "name": "openspec_change", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "pr_url": { - "name": "pr_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "ci_attempts": { - "name": "ci_attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "ci_failed_sha": { - "name": "ci_failed_sha", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "tasks_project_number": { - "name": "tasks_project_number", - "columns": [ - { - "expression": "project_id", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "number", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "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": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_outbox": { - "name": "telegram_outbox", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "dedupe_key": { - "name": "dedupe_key", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "method": { - "name": "method", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "params": { - "name": "params", - "type": "jsonb", - "primaryKey": false, - "notNull": true - }, - "question_id": { - "name": "question_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "default": "'pending'" - }, - "attempts": { - "name": "attempts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "default": 0 - }, - "next_attempt_at": { - "name": "next_attempt_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "telegram_message_id": { - "name": "telegram_message_id", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "sent_at": { - "name": "sent_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "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" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "telegram_outbox_dedupe_key_unique": { - "name": "telegram_outbox_dedupe_key_unique", - "nullsNotDistinct": false, - "columns": [ - "dedupe_key" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.telegram_updates": { - "name": "telegram_updates", - "schema": "", - "columns": { - "update_id": { - "name": "update_id", - "type": "integer", - "primaryKey": true, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "gitea_id": { - "name": "gitea_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "login": { - "name": "login", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "avatar_url": { - "name": "avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_enc": { - "name": "access_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token_enc": { - "name": "refresh_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "token_expires_at": { - "name": "token_expires_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "claude_token_enc": { - "name": "claude_token_enc", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "claude_token_set_at": { - "name": "claude_token_set_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "telegram_chat_id": { - "name": "telegram_chat_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_user_id": { - "name": "telegram_user_id", - "type": "bigint", - "primaryKey": false, - "notNull": false - }, - "telegram_username": { - "name": "telegram_username", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "telegram_paired_at": { - "name": "telegram_paired_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "last_login_at": { - "name": "last_login_at", - "type": "timestamp with time zone", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_gitea_id_unique": { - "name": "users_gitea_id_unique", - "nullsNotDistinct": false, - "columns": [ - "gitea_id" - ] - }, - "users_login_unique": { - "name": "users_login_unique", - "nullsNotDistinct": false, - "columns": [ - "login" - ] - }, - "users_telegram_chat_id_unique": { - "name": "users_telegram_chat_id_unique", - "nullsNotDistinct": false, - "columns": [ - "telegram_chat_id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.goal_status": { - "name": "goal_status", - "schema": "public", - "values": [ - "open", - "done", - "archived" - ] - }, - "public.session_status": { - "name": "session_status", - "schema": "public", - "values": [ - "starting", - "running", - "waiting_input", - "idle", - "stalled", - "rate_limited", - "done", - "failed" - ] - }, - "public.task_status": { - "name": "task_status", - "schema": "public", - "values": [ - "backlog", - "proposing", - "awaiting_approval", - "in_progress", - "review", - "done", - "blocked" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 108d9a85..48cddda1 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -1,103 +1,12 @@ { "version": "7", - "dialect": "postgresql", + "dialect": "sqlite", "entries": [ { "idx": 0, - "version": "7", - "when": 1794492884912, - "tag": "0000_safe_shiver_man", - "breakpoints": true - }, - { - "idx": 1, - "version": "7", - "when": 1794493804069, - "tag": "0001_chunky_dreadnoughts", - "breakpoints": true - }, - { - "idx": 2, - "version": "7", - "when": 1794495121487, - "tag": "0002_happy_preak", - "breakpoints": true - }, - { - "idx": 3, - "version": "7", - "when": 1794496377868, - "tag": "0003_material_wild_child", - "breakpoints": true - }, - { - "idx": 4, - "version": "7", - "when": 1794498071152, - "tag": "0004_loving_wasp", - "breakpoints": true - }, - { - "idx": 5, - "version": "7", - "when": 1794499927803, - "tag": "0005_sloppy_blue_marvel", - "breakpoints": true - }, - { - "idx": 6, - "version": "7", - "when": 1794500991061, - "tag": "0006_crazy_stellaris", - "breakpoints": true - }, - { - "idx": 7, - "version": "7", - "when": 1794502693680, - "tag": "0007_empty_crystal", - "breakpoints": true - }, - { - "idx": 8, - "version": "7", - "when": 1794504595170, - "tag": "0008_wandering_jetstream", - "breakpoints": true - }, - { - "idx": 9, - "version": "7", - "when": 1794505063021, - "tag": "0009_steady_preak", - "breakpoints": true - }, - { - "idx": 10, - "version": "7", - "when": 1794523548954, - "tag": "0010_glamorous_ego", - "breakpoints": true - }, - { - "idx": 11, - "version": "7", - "when": 1794561166402, - "tag": "0011_pep58_incidents", - "breakpoints": true - }, - { - "idx": 12, - "version": "7", - "when": 1794562626634, - "tag": "0012_faithful_matthew_murdock", - "breakpoints": true - }, - { - "idx": 13, - "version": "7", - "when": 1794562970727, - "tag": "0013_pep57_releases", + "version": "6", + "when": 1794571062983, + "tag": "0000_baseline", "breakpoints": true } ] diff --git a/packages/db/package.json b/packages/db/package.json index c614d06c..a79173d2 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -3,17 +3,20 @@ "version": "0.0.0", "private": true, "type": "module", - "exports": { ".": "./src/index.ts", "./schema": "./src/schema.ts" }, + "exports": { + ".": "./src/index.ts", + "./schema": "./src/schema.ts" + }, "scripts": { "typecheck": "tsc -p .", "generate": "drizzle-kit generate", - "migrate": "drizzle-kit migrate", - "studio": "drizzle-kit studio" + "migrate": "node ../cli/src/index.ts db migrate" }, "dependencies": { "@peppa/shared": "workspace:*", - "drizzle-orm": "0.45.4", - "postgres": "4.1.1" + "drizzle-orm": "0.45.4" }, - "devDependencies": { "drizzle-kit": "0.31.11" } + "devDependencies": { + "drizzle-kit": "0.31.11" + } } diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts new file mode 100644 index 00000000..9f2f8082 --- /dev/null +++ b/packages/db/src/client.ts @@ -0,0 +1,121 @@ +// drizzle on Node's built-in node:sqlite (PEP-36). drizzle-orm 0.45 has no node:sqlite +// driver (only 1.0 beta/rc does), but node:sqlite's API is close to better-sqlite3's, so a +// thin client lets drizzle's better-sqlite3 *session* run on it. drizzle-orm/better-sqlite3 +// itself is not imported: its driver.js loads the native better-sqlite3 package. +// Every Peppa process (web, bot, watchdog, each hook and MCP server) opens the file itself; +// WAL lets readers run next to the single writer, busy_timeout makes writers queue. +import { DatabaseSync, type StatementSync } from "node:sqlite"; +import { mkdirSync } from "node:fs"; +import { dirname } from "node:path"; + +export const BUSY_TIMEOUT_MS = 5000; +const BUSY_RETRIES = 3; + +const isBusy = (e: unknown) => /SQLITE_BUSY|database is locked/i.test(String((e as Error)?.message ?? e)); + +/** SQLITE_BUSY after busy_timeout already waited: try a few more times before giving up. */ +function retryBusy<T>(fn: () => T): T { + for (let attempt = 1; ; attempt++) { + try { + return fn(); + } catch (e) { + if (!isBusy(e) || attempt >= BUSY_RETRIES) throw e; + } + } +} + +type Params = unknown[]; + +class Statement { + private stmt: StatementSync; + private rawStmt: StatementSync | null = null; + private db: DatabaseSync; + private sql: string; + constructor(db: DatabaseSync, sql: string) { + this.db = db; + this.sql = sql; + this.stmt = db.prepare(sql); + } + run(...p: Params) { + return retryBusy(() => this.stmt.run(...(p as never[]))); + } + all(...p: Params) { + return retryBusy(() => this.stmt.all(...(p as never[]))); + } + get(...p: Params) { + return retryBusy(() => this.stmt.get(...(p as never[]))); + } + /** The same statement returning rows as arrays (drizzle maps columns by position). */ + raw() { + if (!this.rawStmt) { + this.rawStmt = this.db.prepare(this.sql); + this.rawStmt.setReturnArrays(true); + } + const s = this.rawStmt; + return { all: (...p: Params) => retryBusy(() => s.all(...(p as never[]))), get: (...p: Params) => retryBusy(() => s.get(...(p as never[]))) }; + } +} + +export class SqliteClient { + readonly path: string; + private readOnly: boolean; + private conn: DatabaseSync | null = null; + private cache = new Map<string, Statement>(); + constructor(path: string, opts: { readOnly?: boolean } = {}) { + this.path = path; + this.readOnly = opts.readOnly ?? false; + } + /** + * The connection, opened on first use: importing a module that creates the client (the + * web's lib/db.ts during `next build`) must not create the database file. + */ + get db(): DatabaseSync { + if (this.conn) return this.conn; + if (this.path !== ":memory:" && !this.readOnly) mkdirSync(dirname(this.path), { recursive: true }); + const db = new DatabaseSync(this.path, { readOnly: this.readOnly }); + // busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY + // when many processes open the file together (bench/sqlite/README.md). + db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`); + if (!this.readOnly) retryBusy(() => db.exec("PRAGMA journal_mode = WAL")); + db.exec("PRAGMA synchronous = NORMAL"); + db.exec("PRAGMA foreign_keys = ON"); + return (this.conn = db); + } + prepare(sql: string) { + let s = this.cache.get(sql); + if (!s) this.cache.set(sql, (s = new Statement(this.db, sql))); + return s; + } + exec(sql: string) { + retryBusy(() => this.db.exec(sql)); + } + /** better-sqlite3's transaction API; the callback must be synchronous. */ + transaction<T>(fn: (...a: never[]) => T) { + const run = + (begin: string) => + (...a: never[]): T => { + retryBusy(() => this.db.exec(begin)); + try { + const r = fn(...a); + if (r && typeof (r as { then?: unknown }).then === "function") { + throw new Error("SQLite transactions must be synchronous: no async callback, no await inside db.transaction()"); + } + this.db.exec("COMMIT"); + return r; + } catch (e) { + if (this.db.isTransaction) this.db.exec("ROLLBACK"); + throw e; + } + }; + return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") }; + } + /** Changes committed by other connections since the last call (PRAGMA data_version). */ + dataVersion(): number { + return Number((this.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version); + } + close() { + if (this.conn?.isOpen) this.conn.close(); + this.conn = null; + this.cache.clear(); + } +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 8c7aab96..050427fc 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -1,14 +1,72 @@ import { loadEnv } from "@peppa/shared"; -import { drizzle } from "drizzle-orm/postgres-js"; -import postgres from "postgres"; +import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session"; +import { migrate as drizzleMigrate } from "drizzle-orm/better-sqlite3/migrator"; +import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations"; +import { is } from "drizzle-orm"; +import { getTableConfig, SQLiteTable } from "drizzle-orm/sqlite-core"; +import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db"; +import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect"; +import type { StatementResultingChanges } from "node:sqlite"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { SqliteClient } from "./client.ts"; import * as schema from "./schema.ts"; export * from "./schema.ts"; -export { schema }; +export { schema, SqliteClient }; -export function createDb(url = loadEnv().DATABASE_URL) { - const client = postgres(url, { max: 5 }); - return drizzle(client, { schema }); +export type Db = BaseSQLiteDatabase<"sync", StatementResultingChanges, typeof schema> & { $client: SqliteClient }; + +/** Opens Peppa's SQLite database (PEPPA_DB, default ~/.peppa/peppa.db). */ +export function createDb(path = loadEnv().PEPPA_DB, opts: { readOnly?: boolean } = {}): Db { + const client = new SqliteClient(path, opts); + const dialect = new SQLiteSyncDialect(); + const tables = extractTablesRelationalConfig(schema, createTableRelationsHelpers); + const relational = { fullSchema: schema, schema: tables.tables, tableNamesMap: tables.tableNamesMap }; + const session = new BetterSQLiteSession(client as never, dialect, relational as never); + const db = new BaseSQLiteDatabase("sync", dialect, session as never, relational as never) as Db; + db.$client = client; + return db; } -export type Db = ReturnType<typeof createDb>; +// Not `new URL(…, import.meta.url)`: Next's bundler would try to resolve it as an asset. +export const migrationsFolder = join(dirname(fileURLToPath(import.meta.url)), "..", "migrations"); + +/** Applies pending migrations (idempotent; safe to run from several processes). */ +export function migrateDb(db: Db) { + drizzleMigrate(db as never, { migrationsFolder }); +} + +export interface TableInfo { + name: string; + columns: { name: string; json: boolean; ms: boolean; bool: boolean }[]; +} + +/** Peppa's tables, parents before children by foreign keys (for copying data in). */ +export function tablesInFkOrder(): TableInfo[] { + const configs = new Map( + Object.values(schema) + .filter((t) => is(t, SQLiteTable)) + .map((t) => getTableConfig(t as SQLiteTable)) + .map((c) => [c.name, c]), + ); + const ordered: string[] = []; + const visit = (name: string, path: string[]) => { + if (ordered.includes(name) || path.includes(name)) return; + for (const fk of configs.get(name)!.foreignKeys) { + const parent = getTableConfig(fk.reference().foreignTable).name; + if (parent !== name) visit(parent, [...path, name]); + } + ordered.push(name); + }; + for (const name of [...configs.keys()].sort()) visit(name, []); + return ordered.map((name) => ({ + name, + columns: configs.get(name)!.columns.map((c) => ({ + name: c.name, + json: c.columnType === "SQLiteTextJson", + ms: c.columnType === "SQLiteTimestamp", + bool: c.columnType === "SQLiteBoolean", + })), + })); +} diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 3e6194fc..dc121e0c 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -1,13 +1,18 @@ import { relations } from "drizzle-orm"; -import { bigint, boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core"; +import { sql } from "drizzle-orm"; +import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; -const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow(); +// SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is +// text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only. +const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`; + +const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs); const updatedAt = () => - timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()); + integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date()); /** People who log into the web, one per Gitea account. */ -export const users = pgTable("users", { - id: serial("id").primaryKey(), +export const users = sqliteTable("users", { + id: integer("id").primaryKey({ autoIncrement: true }), giteaId: integer("gitea_id").notNull().unique(), login: text("login").notNull().unique(), name: text("name"), @@ -16,22 +21,22 @@ export const users = pgTable("users", { // OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts). accessTokenEnc: text("access_token_enc"), refreshTokenEnc: text("refresh_token_enc"), - tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }), + tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }), // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the // Claude sessions of this user's projects. claudeTokenEnc: text("claude_token_enc"), - claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }), + claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }), // Telegram chat paired from Settings; agent questions of this user's projects go there. - telegramChatId: bigint("telegram_chat_id", { mode: "number" }).unique(), - telegramUserId: bigint("telegram_user_id", { mode: "number" }), + telegramChatId: integer("telegram_chat_id").unique(), + telegramUserId: integer("telegram_user_id"), telegramUsername: text("telegram_username"), - telegramPairedAt: timestamp("telegram_paired_at", { withTimezone: true }), + telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }), createdAt: createdAt(), - lastLoginAt: timestamp("last_login_at", { withTimezone: true }), + lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }), }); -export const projects = pgTable("projects", { - id: serial("id").primaryKey(), +export const projects = sqliteTable("projects", { + id: integer("id").primaryKey({ autoIncrement: true }), slug: text("slug").notNull().unique(), // Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2… key: text("key").notNull().unique(), @@ -50,7 +55,7 @@ export const projects = pgTable("projects", { }); /** People who work on a project besides its owner (projects.owner_id). */ -export const projectMembers = pgTable( +export const projectMembers = sqliteTable( "project_members", { projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), @@ -62,7 +67,7 @@ export const projectMembers = pgTable( ); /** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */ -export const projectInvites = pgTable( +export const projectInvites = sqliteTable( "project_invites", { projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), @@ -73,20 +78,20 @@ export const projectInvites = pgTable( (t) => [primaryKey({ columns: [t.projectId, t.login] })], ); -export const goalStatus = pgEnum("goal_status", ["open", "done", "archived"]); +export const goalStatus = { enumValues: ["open", "done", "archived"] as const }; /** Top-level objectives set by the PM; tasks are broken out of them. */ -export const goals = pgTable("goals", { - id: serial("id").primaryKey(), +export const goals = sqliteTable("goals", { + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), title: text("title").notNull(), description: text("description"), - status: goalStatus("status").notNull().default("open"), + status: text("status", { enum: goalStatus.enumValues }).notNull().default("open"), createdAt: createdAt(), updatedAt: updatedAt(), }); -export const taskStatus = pgEnum("task_status", [ +export const taskStatus = { enumValues: [ "backlog", // created, nobody working on it "proposing", // agent is writing the OpenSpec change "awaiting_approval", // proposal ready, PM must approve @@ -94,18 +99,18 @@ export const taskStatus = pgEnum("task_status", [ "review", // PR open in Gitea "done", // change archived, merged "blocked", -]); +] as const }; -export const tasks = pgTable( +export const tasks = sqliteTable( "tasks", { - id: serial("id").primaryKey(), + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }), number: integer("number").notNull(), title: text("title").notNull(), description: text("description"), - status: taskStatus("status").notNull().default("backlog"), + status: text("status", { enum: taskStatus.enumValues }).notNull().default("backlog"), // OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth" openspecChange: text("openspec_change"), prUrl: text("pr_url"), @@ -119,8 +124,8 @@ export const tasks = pgTable( ); /** PEP-57: one deployment of a project to an environment (and its outcome). */ -export const releases = pgTable("releases", { - id: serial("id").primaryKey(), +export const releases = sqliteTable("releases", { + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), env: text("env", { enum: ["preview", "staging", "prod"] }).notNull(), sha: text("sha").notNull(), @@ -129,7 +134,7 @@ export const releases = pgTable("releases", { host: text("host"), prNumber: integer("pr_number"), // Task keys in the release ("PAY-7"), from the merged commits. - tasks: jsonb("tasks").$type<string[]>().notNull().default([]), + tasks: text("tasks", { mode: "json" }).$type<string[]>().notNull().default([]), status: text("status", { enum: ["deploying", "healthy", "rolled_back", "failed", "removed"] }).notNull().default("deploying"), // "ci" for automatic deploys, the PM's login for prod by the button. deployedBy: text("deployed_by").notNull().default("ci"), @@ -141,10 +146,10 @@ export const releases = pgTable("releases", { }); /** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */ -export const checkRuns = pgTable( +export const checkRuns = sqliteTable( "check_runs", { - id: serial("id").primaryKey(), + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), sha: text("sha").notNull(), @@ -163,7 +168,7 @@ export const checkRuns = pgTable( (t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)], ); -export const sessionStatus = pgEnum("session_status", [ +export const sessionStatus = { enumValues: [ "starting", "running", "waiting_input", // Claude asked something / needs permission @@ -172,11 +177,11 @@ export const sessionStatus = pgEnum("session_status", [ "rate_limited", // StopFailure with error=rate_limit, or limit banner on screen "done", "failed", -]); +] as const }; /** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */ -export const sessions = pgTable("sessions", { - id: serial("id").primaryKey(), +export const sessions = sqliteTable("sessions", { + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), tmuxName: text("tmux_name").notNull().unique(), @@ -189,53 +194,53 @@ export const sessions = pgTable("sessions", { autoNudges: integer("auto_nudges").notNull().default(0), // Usage limit recovery (PEP-56): when to continue, current probe interval if the reset // time is unknown, auto-resumes today (cap), and when the last auto-resume happened. - resumeAt: timestamp("resume_at", { withTimezone: true }), + resumeAt: integer("resume_at", { mode: "timestamp_ms" }), limitProbeMin: integer("limit_probe_min"), limitResumes: integer("limit_resumes").notNull().default(0), limitResumesDay: text("limit_resumes_day"), - limitResumedAt: timestamp("limit_resumed_at", { withTimezone: true }), - status: sessionStatus("status").notNull().default("starting"), - lastActivityAt: timestamp("last_activity_at", { withTimezone: true }), + limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }), + status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"), + lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }), startedAt: createdAt(), - endedAt: timestamp("ended_at", { withTimezone: true }), + endedAt: integer("ended_at", { mode: "timestamp_ms" }), }); /** Questions routed to the PM (Telegram / web) and their answers. */ -export const questions = pgTable("questions", { - id: serial("id").primaryKey(), +export const questions = sqliteTable("questions", { + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }), // Null when asked from a session Peppa did not start (manual `claude`). sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }), kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(), text: text("text").notNull(), - options: jsonb("options").$type<string[]>(), + options: text("options", { mode: "json" }).$type<string[]>(), answer: text("answer"), // "system": closed by Peppa itself (session stopped/resumed), not by a person. answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }), telegramMessageId: integer("telegram_message_id"), // A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer, // so it must not also be typed into the terminal. - awaitingHook: boolean("awaiting_hook").notNull().default(false), + awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false), createdAt: createdAt(), - answeredAt: timestamp("answered_at", { withTimezone: true }), + answeredAt: integer("answered_at", { mode: "timestamp_ms" }), }); /** Event log: hook / watchdog events, progress reports, status changes. */ -export const events = pgTable("events", { - id: serial("id").primaryKey(), +export const events = sqliteTable("events", { + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }), sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }), type: text("type").notNull(), - payload: jsonb("payload"), + payload: text("payload", { mode: "json" }), createdAt: createdAt(), }); /** Small key/value store for service state (Telegram offset, pairing, binding). */ -export const settings = pgTable("settings", { +export const settings = sqliteTable("settings", { key: text("key").primaryKey(), - value: jsonb("value").notNull(), + value: text("value", { mode: "json" }).notNull(), updatedAt: updatedAt(), }); @@ -243,87 +248,87 @@ export const settings = pgTable("settings", { * Durable Telegram outbox: every message/edit is queued here first, then delivered with * retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message). */ -export const telegramOutbox = pgTable("telegram_outbox", { - id: serial("id").primaryKey(), +export const telegramOutbox = sqliteTable("telegram_outbox", { + id: integer("id").primaryKey({ autoIncrement: true }), dedupeKey: text("dedupe_key").notNull().unique(), method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(), - params: jsonb("params").$type<Record<string, unknown>>().notNull(), + params: text("params", { mode: "json" }).$type<Record<string, unknown>>().notNull(), questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }), status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"), attempts: integer("attempts").notNull().default(0), - nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), + nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs), telegramMessageId: integer("telegram_message_id"), error: text("error"), createdAt: createdAt(), - sentAt: timestamp("sent_at", { withTimezone: true }), + sentAt: integer("sent_at", { mode: "timestamp_ms" }), }); /** Telegram updates already taken: recorded before acting, so a restart never replays one. */ -export const telegramUpdates = pgTable("telegram_updates", { +export const telegramUpdates = sqliteTable("telegram_updates", { updateId: integer("update_id").primaryKey(), status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(), createdAt: createdAt(), }); /** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */ -export const oauthClients = pgTable("oauth_clients", { +export const oauthClients = sqliteTable("oauth_clients", { id: text("id").primaryKey(), name: text("name").notNull(), - redirectUris: jsonb("redirect_uris").$type<string[]>().notNull(), + redirectUris: text("redirect_uris", { mode: "json" }).$type<string[]>().notNull(), createdAt: createdAt(), }); /** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */ -export const oauthCodes = pgTable("oauth_codes", { +export const oauthCodes = sqliteTable("oauth_codes", { codeHash: text("code_hash").primaryKey(), clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), redirectUri: text("redirect_uri").notNull(), codeChallenge: text("code_challenge").notNull(), scope: text("scope"), - expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), - usedAt: timestamp("used_at", { withTimezone: true }), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + usedAt: integer("used_at", { mode: "timestamp_ms" }), }); /** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */ -export const oauthTokens = pgTable("oauth_tokens", { +export const oauthTokens = sqliteTable("oauth_tokens", { tokenHash: text("token_hash").primaryKey(), kind: text("kind", { enum: ["access", "refresh"] }).notNull(), clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), scope: text("scope"), - expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), - revokedAt: timestamp("revoked_at", { withTimezone: true }), + expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(), + revokedAt: integer("revoked_at", { mode: "timestamp_ms" }), createdAt: createdAt(), - lastUsedAt: timestamp("last_used_at", { withTimezone: true }), + lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), }); export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const; export type IncidentPolicy = (typeof incidentPolicies)[number]; /** Error tracking of a project (PEP-58): webhook secret and how new errors are handled. */ -export const incidentSettings = pgTable("incident_settings", { +export const incidentSettings = sqliteTable("incident_settings", { projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }), // Part of the webhook URL Bugsink posts alerts to: /api/hooks/bugsink/<hookSecret>. hookSecret: text("hook_secret").notNull().unique(), policy: text("policy", { enum: incidentPolicies }).notNull().default("backlog"), // The PM's mini-prompt for the triage agent ("how to decide"). triagePrompt: text("triage_prompt"), - environments: jsonb("environments").$type<string[]>().notNull().default(["prod", "production"]), + environments: text("environments", { mode: "json" }).$type<string[]>().notNull().default(["prod", "production"]), dailyLimit: integer("daily_limit").notNull().default(5), ignorePattern: text("ignore_pattern"), goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }), // False: the alert webhook still has to be added in Bugsink by hand (polling covers it). - webhookAuto: boolean("webhook_auto").notNull().default(false), + webhookAuto: integer("webhook_auto", { mode: "boolean" }).notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), }); /** Bugsink projects feeding a Peppa project: one for the frontend, one for the backend. */ -export const errorSources = pgTable( +export const errorSources = sqliteTable( "error_sources", { - id: serial("id").primaryKey(), + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), kind: text("kind", { enum: ["web", "api"] }).notNull(), bugsinkProjectId: integer("bugsink_project_id").notNull().unique(), @@ -336,8 +341,8 @@ export const errorSources = pgTable( export const incidentStatuses = ["new", "open", "pending", "task", "ignored", "resolved", "regressed"] as const; /** A Bugsink issue seen in Peppa. Repeated events update the same row. */ -export const incidents = pgTable("incidents", { - id: serial("id").primaryKey(), +export const incidents = sqliteTable("incidents", { + id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), source: text("source", { enum: ["web", "api"] }).notNull(), bugsinkIssueId: text("bugsink_issue_id").notNull().unique(), @@ -349,8 +354,8 @@ export const incidents = pgTable("incidents", { firstRelease: text("first_release"), lastRelease: text("last_release"), events: integer("events").notNull().default(1), - firstSeen: timestamp("first_seen", { withTimezone: true }).notNull(), - lastSeen: timestamp("last_seen", { withTimezone: true }).notNull(), + firstSeen: integer("first_seen", { mode: "timestamp_ms" }).notNull(), + lastSeen: integer("last_seen", { mode: "timestamp_ms" }).notNull(), url: text("url"), stack: text("stack"), // new → open | pending | task | ignored; task → resolved → regressed (see design.md) @@ -359,9 +364,9 @@ export const incidents = pgTable("incidents", { decidedBy: text("decided_by", { enum: ["policy", "triage", "pm"] }), decisionReason: text("decision_reason"), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), - taskCreatedAt: timestamp("task_created_at", { withTimezone: true }), + taskCreatedAt: integer("task_created_at", { mode: "timestamp_ms" }), resolvedRelease: text("resolved_release"), - resolvedAt: timestamp("resolved_at", { withTimezone: true }), + resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }), regressions: integer("regressions").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 0ed7364f..c994b03a 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -61,7 +61,7 @@ async function expireProdOffers(db: Db, projectId: number) { const open = await db .select() .from(questions) - .where(and(eq(questions.projectId, projectId), isNull(questions.taskId), isNull(questions.answeredAt), sql`${questions.options} @> ${JSON.stringify([PROD_OPTION])}::jsonb`)); + .where(and(eq(questions.projectId, projectId), isNull(questions.taskId), isNull(questions.answeredAt), sql`exists (select 1 from json_each(${questions.options}) where value = ${PROD_OPTION})`)); for (const q of open) await answerQuestion(db, q.id, "(неактуально: на staging новый релиз)", "system").catch(() => {}); } diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 95ba8b51..57775101 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -112,7 +112,7 @@ async function launch( PEPPA_GENERATION: String(generation), PEPPA_PROJECT_DIR: cwd, // Hooks and the MCP server must talk to the same DB / state dir as the runner. - DATABASE_URL: loadEnv().DATABASE_URL, + PEPPA_DB: loadEnv().PEPPA_DB, ...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}), // The project owner's own Claude subscription, if they connected it (PEP-13). ...(claudeToken ? { CLAUDE_CODE_OAUTH_TOKEN: claudeToken } : {}), diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 425b127a..d52787e8 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -2,6 +2,7 @@ // session dies, stalls, or hits a usage limit. Run under launchd with caffeinate. import { createHash } from "node:crypto"; import { + backupDb, expireSessionQuestions, listSessions, logSessionEvent, @@ -136,6 +137,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS lastCiPoll = Date.now(); await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`)); } + // Daily copy of the SQLite database (PEP-36); a no-op until a day has passed. + await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`)); await new Promise((r) => setTimeout(r, opts.intervalMs)); } } diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index 62362cc4..3ec4b185 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -2,7 +2,10 @@ import { homedir } from "node:os"; import { z } from "zod"; const schema = z.object({ - DATABASE_URL: z.string().default("postgres://peppa:peppa@127.0.0.1:5433/peppa"), + // Peppa's SQLite database file (PEP-36); default ~/.peppa/peppa.db. + PEPPA_DB: z.string().optional(), + // The old Postgres database: only the source of `peppa db migrate-to-sqlite`. + DATABASE_URL: z.string().optional(), GITEA_URL: z.string().url().default("https://git.telecom.quest"), GITEA_TOKEN: z.string().optional(), GITEA_TEMPLATE_REPO: z.string().default("peppa-bot/template"), @@ -15,12 +18,13 @@ const schema = z.object({ GITEA_OAUTH_CLIENT_SECRET: z.string().optional(), }); -export type Env = z.infer<typeof schema>; +export type Env = z.infer<typeof schema> & { PEPPA_DB: string }; export function loadEnv(source: NodeJS.ProcessEnv = process.env): Env { const env = schema.parse(source); env.PEPPA_WORKSPACES = env.PEPPA_WORKSPACES.replace(/^~(?=$|\/)/, homedir()); - return env; + const db = (env.PEPPA_DB ?? `${source.PEPPA_HOME ?? `${homedir()}/.peppa`}/peppa.db`).replace(/^~(?=$|\/)/, homedir()); + return { ...env, PEPPA_DB: db }; } /** The Peppa checkout; bins, hooks and the template are resolved from it. */ diff --git a/packages/testkit/bin/peppa-dev b/packages/testkit/bin/peppa-dev index 6ce87b5f..44fa9f3b 100755 --- a/packages/testkit/bin/peppa-dev +++ b/packages/testkit/bin/peppa-dev @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Peppa dev stand: isolated DB (peppa_dev), tmux server (-L peppa-dev), state dir +# Peppa dev stand: isolated DB (~/.peppa-dev/peppa.db), tmux server (-L peppa-dev), state dir # (~/.peppa-dev), the Peppa bot against mock-telegram, mock agents by default. # Lets an agent play the PM in Telegram without a human and without touching prod. # @@ -11,8 +11,8 @@ set -euo pipefail ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" PORT="${PEPPA_DEV_TG_PORT:-3190}" export PEPPA_ROOT="$ROOT" -export DATABASE_URL="postgres://peppa:peppa@127.0.0.1:5433/peppa_dev" export PEPPA_HOME="$HOME/.peppa-dev" +export PEPPA_DB="$PEPPA_HOME/peppa.db" export PEPPA_WORKSPACES="$HOME/.peppa-dev/workspaces" export PEPPA_TMUX_SOCKET="peppa-dev" export TELEGRAM_BOT_TOKEN="mock-123:TOKEN" @@ -26,9 +26,7 @@ TM=(tmux -L peppa-dev) PEPPA="$ROOT/packages/cli/bin/peppa" up() { - docker exec peppa-postgres psql -U peppa -tAc "select 1 from pg_database where datname='peppa_dev'" | grep -q 1 \ - || docker exec peppa-postgres createdb -U peppa peppa_dev - (cd "$ROOT/packages/db" && "$ROOT/packages/db/node_modules/.bin/drizzle-kit" migrate >/dev/null) + "$PEPPA" db migrate >/dev/null "${TM[@]}" has-session -t dev-mock-tg 2>/dev/null || "${TM[@]}" new-session -d -s dev-mock-tg "$ROOT/packages/testkit/bin/mock-telegram --port $PORT" "${TM[@]}" set-option -s exit-empty off for _ in $(seq 1 40); do curl -sf "$TELEGRAM_API_URL/_mock/messages" >/dev/null && break; sleep 0.25; done diff --git a/packages/testkit/src/storage-worker.ts b/packages/testkit/src/storage-worker.ts new file mode 100644 index 00000000..43dac2a0 --- /dev/null +++ b/packages/testkit/src/storage-worker.ts @@ -0,0 +1,18 @@ +// A separate Peppa process for storage tests (PEP-36): opens PEPPA_DB itself, like a hook +// or an MCP server does, and writes. +// node storage-worker.ts settings <n> <tag> n settings writes (heartbeat-like) +// node storage-worker.ts task <projectId> one createTask (per-project numbering) +import { createDb } from "@peppa/db"; +import { createTask, setSetting } from "@peppa/core"; + +const [mode, a, b] = process.argv.slice(2); +const db = createDb(); +if (mode === "settings") { + for (let i = 0; i < Number(a); i++) await setSetting(db, `storage:${b}:${i}`, { i, pid: process.pid }); +} else if (mode === "task") { + const t = await createTask(db, { projectId: Number(a), title: `from ${process.pid}` }); + process.stdout.write(String(t.task.number)); +} else { + throw new Error(`unknown mode ${mode}`); +} +db.$client.close(); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 7e101a40..f61e4ad4 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -1,4 +1,4 @@ -// Test harness for the CJM suite: isolated Postgres database, tmux server, state dir and +// Test harness for the CJM suite: isolated SQLite database file, tmux server, state dir and // workspaces; mock agents instead of the real CLIs. // Import this before anything that pulls in @peppa/runner (statically or via @peppa/bot): // runner modules read PEPPA_TMUX_SOCKET / PEPPA_HOME when they load. @@ -7,19 +7,15 @@ import { mkdirSync, mkdtempSync, readFileSync, existsSync, writeFileSync } from import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import postgres from "postgres"; import type { Scenario, MockLogEntry } from "../src/scenario.ts"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-cjm-")); -// PEPPA_TEST_DB lets parallel sessions (one per worktree) run the suite without sharing a database; -// PEPPA_TEST_PG points at another Postgres server (CI job: a service container). -const TEST_DB = process.env.PEPPA_TEST_DB ?? "peppa_test"; -const TEST_PG = process.env.PEPPA_TEST_PG ?? "postgres://peppa:peppa@127.0.0.1:5433"; -if (!/^[a-z0-9_]+$/.test(TEST_DB)) throw new Error(`bad PEPPA_TEST_DB: ${TEST_DB}`); +// Every test file is its own process with its own temp dir, so its own database file: +// parallel suites (worktrees, CI jobs) never share state. Object.assign(process.env, { - DATABASE_URL: `${TEST_PG}/${TEST_DB}`, + PEPPA_DB: join(TMP, "peppa.db"), PEPPA_HOME: join(TMP, "home"), PEPPA_TMUX_SOCKET: `peppa-test-${process.pid}`, PEPPA_CLAUDE_BIN: join(ROOT, "packages/testkit/bin/mock-claude"), @@ -34,26 +30,16 @@ Object.assign(process.env, { }); mkdirSync(process.env.PEPPA_HOME!, { recursive: true }); -{ - const admin = postgres(`${TEST_PG}/postgres`, { max: 1, onnotice: () => {} }); - const [exists] = await admin`select 1 from pg_database where datname = ${TEST_DB}`; - if (!exists) await admin.unsafe(`create database ${TEST_DB}`); - await admin.end(); -} - // Import after the env is set: these modules read it at load time. export const core = await import("@peppa/core"); export const runner = await import("@peppa/runner"); const dbmod = await import("@peppa/db"); -const { migrate } = await import("drizzle-orm/postgres-js/migrator"); -const { sql } = await import("drizzle-orm"); export const db = dbmod.createDb(); -await migrate(db, { migrationsFolder: join(ROOT, "packages/db/migrations") }); -await db.execute(sql`truncate projects, users, settings, telegram_outbox, telegram_updates, oauth_clients restart identity cascade`); +dbmod.migrateDb(db); export async function teardown() { - await db.$client.end(); + db.$client.close(); try { execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-server"], { stdio: "ignore" }); } catch {} diff --git a/packages/testkit/test/incidents.test.ts b/packages/testkit/test/incidents.test.ts index fd07e926..d02e8401 100644 --- a/packages/testkit/test/incidents.test.ts +++ b/packages/testkit/test/incidents.test.ts @@ -249,8 +249,8 @@ describe("Политика инцидентов проекта", () => { const c = await connected({ policy: "start" }); await bugsink.capture(c.api, { ...AMOUNT, value: "start now" }); const i = await waitIncident(c, "TypeError: start now", (x) => x.status === "task"); - const t = (await tasksOf(c)).find((x) => x.id === i.taskId)!; - assert.equal(t.status, "in_progress"); + // The incident points at its task before the task is moved to work. + const t = await waitFor("task in progress", async () => (await tasksOf(c)).find((x) => x.id === i.taskId && x.status === "in_progress")); const s = await waitFor("runner started", async () => (await core.listSessions(db, { taskId: t.id }))[0]); assert.ok(s); await waitPm("TypeError: start now", (m) => /Агент взялся/.test(m.text)); @@ -502,6 +502,7 @@ describe("MCP для PM", () => { await call("set_incident_policy", { project: c.key, policy: "ask" }); await bugsink.capture(c.api, { ...AMOUNT, value: "via mcp" }); const i = await waitIncident(c, "TypeError: via mcp", (x) => x.status === "pending"); + await waitPm("TypeError: via mcp", (m) => /Что делаем\?/.test(m.text)); // the PM has the buttons assert.match(await call("list_incidents", { project: c.key, status: "pending" }), new RegExp(`#${i.id} \\[pending\\] TypeError: via mcp`)); assert.match(await call("decide_incident", { id: i.id, action: "backlog" }), /created in the backlog/); assert.match(await call("resolve_incident", { id: i.id }), /Incident #\d+ resolved/); diff --git a/packages/testkit/test/monitor.test.ts b/packages/testkit/test/monitor.test.ts index b1bb5ba9..8f72d6ed 100644 --- a/packages/testkit/test/monitor.test.ts +++ b/packages/testkit/test/monitor.test.ts @@ -2,6 +2,8 @@ // (controlled clock, mock-telegram, the real bot), `peppa status`. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, before, beforeEach, describe, test } from "node:test"; @@ -38,7 +40,7 @@ async function queued(chatId: number): Promise<string[]> { const rows = await db .select() .from(telegramOutbox) - .where(sql`${telegramOutbox.dedupeKey} like 'mon:%' and ${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`) + .where(sql`${telegramOutbox.dedupeKey} like 'mon:%' and cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`) .orderBy(telegramOutbox.id); return rows.map((r) => String(r.params.text)); } @@ -53,7 +55,7 @@ before(async () => { await core.setAllowedLogins(db, [ADMIN.login, OTHER.login]); }); beforeEach(async () => { - await db.execute(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`); + db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`); await db.delete(telegramOutbox); await core.setPlatformAdmins(db, [ADMIN.login]); await pair(ADMIN.login, ADMIN.chatId, 9001); @@ -103,14 +105,15 @@ describe("Health-эндпоинт", () => { }); test("БД недоступна", async () => { - const dead = createDb("postgres://peppa:peppa@127.0.0.1:9/nothing"); + // A database file without Peppa's tables (deleted and recreated, or the wrong file). + const dead = createDb(join(mkdtempSync(join(tmpdir(), "peppa-dead-")), "peppa.db")); const t0 = Date.now(); const r = await core.healthReport(dead, { version: "0.15.0" }); assert.ok(Date.now() - t0 < 3500); assert.equal(r.ok, false); assert.equal(r.db.ok, false); assert.ok(r.db.error); - await dead.$client.end({ timeout: 0 }).catch(() => {}); + dead.$client.close(); }); }); diff --git a/packages/testkit/test/storage.test.ts b/packages/testkit/test/storage.test.ts new file mode 100644 index 00000000..12388de3 --- /dev/null +++ b/packages/testkit/test/storage.test.ts @@ -0,0 +1,197 @@ +// PEP-36: one SQLite file for every Peppa process — concurrent writers, live updates +// without Postgres NOTIFY, and the one-time move of the data from Postgres. +import assert from "node:assert/strict"; +import { execFile, execFileSync } from "node:child_process"; +import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { after, describe, test } from "node:test"; +import { core, db, teardown } from "./helpers.ts"; +import { createDb, events, projects, settings } from "@peppa/db"; +import type { PeppaNotification } from "@peppa/core"; +import { like, sql } from "drizzle-orm"; +import postgres from "postgres"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const WORKER = join(ROOT, "packages/testkit/src/storage-worker.ts"); +const run = promisify(execFile); +const worker = (...args: string[]) => run(process.execPath, [WORKER, ...args], { env: process.env, encoding: "utf8" }); + +after(teardown); + +describe("Одна база SQLite для всех процессов", () => { + test("Scenario: 20 процессов открывают базу одновременно и пишут — ни одной ошибки, ни одной потерянной записи", async () => { + const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => worker("settings", "25", `p${i}`))); + const failed = results.filter((r) => r.status === "rejected"); + assert.equal(failed.length, 0, failed.map((r) => String((r as PromiseRejectedResult).reason)).join("\n")); + const [{ n }] = await db.select({ n: sql<number>`count(*)` }).from(settings).where(like(settings.key, "storage:%")); + assert.equal(n, 20 * 25); + }); + + test("Scenario: задачи из разных процессов получают разные номера подряд", async () => { + const [p] = await db + .insert(projects) + .values({ slug: "storage", key: "STO", name: "STO", giteaOwner: "o", giteaRepo: "storage", workspacePath: "/tmp/storage" }) + .returning(); + const numbers = (await Promise.all(Array.from({ length: 10 }, () => worker("task", String(p!.id))))).map((r) => Number(r.stdout)); + assert.deepEqual([...numbers].sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + }); + + // drizzle's SQLite transactions are synchronous: with an async callback everything after the + // first await would silently run outside the transaction. The driver makes it a loud error. + test("транзакция с async-колбэком отклоняется с понятной ошибкой", async () => { + assert.throws( + () => + db.transaction(async (tx) => { + await tx.insert(projects).values({ slug: "async", key: "ASY", name: "ASY", giteaOwner: "o", giteaRepo: "async", workspacePath: "/tmp/a" }); + }), + /must be synchronous/, + ); + }); +}); + +describe("Живые обновления без Postgres", () => { + test("notify() будит подписчика по сокету", async () => { + const got: PeppaNotification[] = []; + const stop = await core.listenEvents("bot", (n) => got.push(n)); + try { + await core.notify(db, { type: "question", questionId: 42 }); + for (let i = 0; i < 40 && got.length === 0; i++) await new Promise((r) => setTimeout(r, 25)); + assert.deepEqual(got, [{ type: "question", questionId: 42 }]); + } finally { + await stop(); + } + }); + + test("Scenario: сокет подписки недоступен — запись другого процесса видна по data_version", async () => { + assert.ok(!existsSync(core.eventsSocket("bot"))); + const t0 = Date.now(); + await core.notify(db, { type: "progress", eventId: 1 }); // nobody listens: returns at once + assert.ok(Date.now() - t0 < 100); + const v = db.$client.dataVersion(); + await worker("settings", "1", "dv"); + assert.notEqual(db.$client.dataVersion(), v); + }); +}); + +describe("Резервная копия базы", () => { + test("Scenario: ночная копия открывается сама по себе, копий не больше 7", async () => { + const dir = mkdtempSync(join(tmpdir(), "peppa-backups-")); + for (let d = 1; d <= 8; d++) writeFileSync(join(dir, `peppa-2026-10-0${d}.db`), "old"); + const r = await core.backupDb(db, { dir, now: new Date("2026-11-13T03:00:00Z") }); + assert.ok(r.file?.endsWith("peppa-2026-11-13.db")); + const copy = createDb(r.file!, { readOnly: true }); + assert.equal((await copy.select().from(projects)).length, (await db.select().from(projects)).length); + copy.$client.close(); + const left = readdirSync(dir).sort(); + assert.equal(left.length, 7); + assert.equal(left.at(-1), "peppa-2026-11-13.db"); + assert.deepEqual(await core.backupDb(db, { dir, now: new Date("2026-11-13T12:00:00Z") }), { skipped: true }); + }); + + test("Scenario: копия не удалась — неполного файла нет, база работает", async () => { + const base = mkdtempSync(join(tmpdir(), "peppa-backups-")); + const dir = join(base, "not-a-dir"); + writeFileSync(dir, "a file where the backup dir should be"); + const logs: string[] = []; + const r = await core.backupDb(db, { dir, force: true, log: (m) => logs.push(m) }); + assert.ok(r.error); + assert.match(logs.join("\n"), /Резервная копия базы Пеппы не сделана/); + assert.equal(readdirSync(base).length, 1); + await core.setSetting(db, "storage:after-backup", 1); + }); +}); + +// The move needs a Postgres server to read from (Peppa's own on the dev machine, the host's in CI). +const PG = process.env.PEPPA_TEST_PG ?? "postgres://peppa:peppa@127.0.0.1:5433"; +const pgReachable = await (async () => { + const c = postgres(`${PG}/postgres`, { max: 1, connect_timeout: 3, onnotice: () => {} }); + try { + await c`select 1`; + return true; + } catch { + return false; + } finally { + await c.end({ timeout: 1 }); + } +})(); + +describe("Перенос данных из Postgres", { skip: pgReachable ? false : `no Postgres at ${PG}` }, () => { + const name = `peppa_test_m2s_${process.pid}`; + const admin = () => postgres(`${PG}/postgres`, { max: 1, onnotice: () => {} }); + const legacy = join(ROOT, "packages/cli/legacy-pg-migrations"); + + /** A Postgres database with the last Postgres schema of Peppa and some data. */ + async function source(seed: (pg: postgres.Sql) => Promise<void>): Promise<string> { + const a = admin(); + await a.unsafe(`drop database if exists ${name}`); + await a.unsafe(`create database ${name}`); + await a.end(); + const pg = postgres(`${PG}/${name}`, { max: 1, onnotice: () => {} }); + for (const f of readdirSync(legacy).filter((f) => f.endsWith(".sql")).sort()) + for (const stmt of readFileSync(join(legacy, f), "utf8").split("--> statement-breakpoint")) if (stmt.trim()) await pg.unsafe(stmt); + await seed(pg); + await pg.end(); + return `${PG}/${name}`; + } + after(async () => { + const a = admin(); + await a.unsafe(`drop database if exists ${name}`); + await a.end(); + }); + + test("Scenario: успешный перенос — строки, даты, JSON, boolean и id чата на месте", async () => { + const url = await source(async (pg) => { + await pg`insert into users (gitea_id, login, telegram_chat_id) values (1, 'mock-pm', 9007199254740991)`; + await pg`insert into projects (slug, key, name, gitea_owner, gitea_repo, workspace_path, owner_id, next_task_number) values ('pay', 'PAY', 'Pay', 'o', 'pay', '/tmp/pay', 1, 2)`; + await pg`insert into tasks (project_id, number, title, status) values (1, 1, 'Первая', 'in_progress')`; + await pg`insert into sessions (project_id, task_id, tmux_name, status) values (1, 1, 'peppa-PAY-1-s1', 'running')`; + await pg`insert into questions (project_id, task_id, session_id, kind, text, options, awaiting_hook) values (1, 1, 1, 'permission', 'Удалить build?', '["Да","Нет"]', true)`; + for (let i = 0; i < 107; i++) await pg`insert into events (project_id, task_id, type, payload) values (1, 1, 'progress', ${pg.json({ i })})`; + await pg`insert into telegram_outbox (dedupe_key, method, params, question_id, status, telegram_message_id) values ('q:1', 'sendMessage', ${pg.json({ chat_id: 4242, text: "?" })}, 1, 'sent', 77)`; + }); + const file = join(mkdtempSync(join(tmpdir(), "peppa-m2s-")), "peppa.db"); + const out = execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["db", "migrate-to-sqlite", file], { + encoding: "utf8", + env: { ...process.env, DATABASE_URL: url }, + }); + assert.match(out, /перенесено, расхождений нет/); + assert.match(out, /events\s+107/); + const m = createDb(file); + const q = await m.query.questions.findFirst({ with: { session: true } }); + assert.deepEqual(q!.options, ["Да", "Нет"]); + assert.equal(q!.awaitingHook, true); + assert.ok(q!.createdAt instanceof Date && Math.abs(q!.createdAt.getTime() - Date.now()) < 60_000); + assert.equal(q!.session!.tmuxName, "peppa-PAY-1-s1"); + assert.equal((await m.query.users.findFirst())!.telegramChatId, 9007199254740991); + assert.equal((await m.select().from(events)).length, 107); + assert.equal((await core.questionByTelegramMessage(m, 4242, 77))?.id, q!.id); // json filter over migrated params + // The new file is a working Peppa database: numbering continues. + const t = await core.createTask(m, { projectId: 1, title: "Вторая" }); + assert.equal(t.key, "PAY-2"); + m.$client.close(); + }); + + test("Scenario: расхождение — нарушение внешнего ключа, файла нет, Postgres не тронут", async () => { + const url = await source(async (pg) => { + await pg`insert into projects (slug, key, name, gitea_owner, gitea_repo, workspace_path) values ('pay', 'PAY', 'Pay', 'o', 'pay', '/tmp/pay')`; + await pg`alter table questions drop constraint questions_session_id_sessions_id_fk`; + await pg`insert into questions (project_id, session_id, kind, text) values (1, 999, 'question', 'Висящая ссылка')`; + }); + const file = join(mkdtempSync(join(tmpdir(), "peppa-m2s-")), "peppa.db"); + let err = ""; + try { + execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["db", "migrate-to-sqlite", file], { encoding: "utf8", stdio: "pipe", env: { ...process.env, DATABASE_URL: url } }); + } catch (e) { + err = String((e as { stderr: string }).stderr); + assert.equal((e as { status: number }).status, 1); + } + assert.match(err, /questions: нарушение внешнего ключа/); + assert.ok(!existsSync(file) && !existsSync(`${file}.migrating`)); + const pg = postgres(url, { max: 1, onnotice: () => {} }); + assert.equal((await pg`select count(*)::int n from questions`)[0]!.n, 1); + await pg.end(); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 768ee51a..8dc0351c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -274,6 +274,9 @@ importers: '@peppa/shared': specifier: workspace:* version: link:../shared + postgres: + specifier: 4.1.1 + version: 4.1.1 packages/core: dependencies: @@ -298,9 +301,6 @@ importers: drizzle-orm: specifier: 0.45.4 version: 0.45.4(postgres@4.1.1) - postgres: - specifier: 4.1.1 - version: 4.1.1 devDependencies: drizzle-kit: specifier: 0.31.11 diff --git a/scripts/ci.sh b/scripts/ci.sh index 5349a5f3..c2c065b4 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -7,8 +7,9 @@ # scripts/ci.sh --repeat <N> run the e2e suite N times in a row (flake hunting) # scripts/ci.sh --skip-build skip `next build` # -# Every run uses its own database peppa_test_ci_<pid> or $PEPPA_TEST_DB (dropped at exit), so it can run next -# to other worktrees' suites. Logs of --pr runs: ~/.peppa/ci/<sha>.log. +# Every e2e test file uses its own SQLite file in a temp dir, so runs never share state; the +# Postgres → SQLite migration test makes (and drops) its own database on $PEPPA_TEST_PG. +# Logs of --pr runs: ~/.peppa/ci/<sha>.log. set -uo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" PR="" REPEAT=1 BUILD=1 @@ -57,10 +58,6 @@ if [ -n "$PR" ]; then fi cd "$ROOT" -# The Actions job passes PEPPA_TEST_DB per run: pids inside job containers repeat. -DB="${PEPPA_TEST_DB:-peppa_test_ci_$$}" -cleanup() { docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; } -trap cleanup EXIT step() { # <name> <command...> local name=$1; shift @@ -72,6 +69,6 @@ step() { # <name> <command...> step typecheck pnpm -r typecheck [ "$BUILD" = 1 ] && step "web build" pnpm --filter @peppa/web build for i in $(seq 1 "$REPEAT"); do - step "e2e $i/$REPEAT" env PEPPA_TEST_DB="$DB" pnpm --filter @peppa/testkit test + step "e2e $i/$REPEAT" pnpm --filter @peppa/testkit test done echo "ci: all green" -- 2.45.2 From 03aee432fb2bb8c9d5c8e41a45daf33f72d19ff4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 17:58:34 +0500 Subject: [PATCH 025/536] =?UTF-8?q?PEP-18:=20separate=20Peppa=20prod=20?= =?UTF-8?q?=E2=80=94=20release=20dir,=20PM=20button,=20DB=20backup,=20auto?= =?UTF-8?q?-rollback?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts/peppa-release.sh: ~/peppa/{repo.git,releases/<sha>,current,shared/.env}; install → next build → checked DB backup → migrate → switch current → kickstart → health (/api/health commit + fresh heartbeats) → rollback; --queue, --check, --no-restart - runner/platform-release.ts: deployProd for the platform project (PEPPA_PLATFORM_KEY=PEP) queues a request for launchd quest.telecom.peppa.release; offer after green main - CLI: peppa db backup [file], peppa release report; backupDb verifies the copy - install-launchd.sh: wait for unload after bootout (no "Bootstrap failed: 5"), release agent (QueueDirectories), PEPPA_ROOT in agents - bin wrappers: logical root so hooks/credential.helper point at ~/peppa/current - mock-launchctl, mock-pnpm; e2e platform-release.test.ts; OpenSpec pep-18-peppa-prod Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 5 +- apps/bot/bin/peppa-bot | 5 +- apps/web/app/(app)/help/page.tsx | 6 + apps/web/app/(app)/p/[key]/page.tsx | 8 +- docs/HANDOFF.md | 8 +- openspec/changes/pep-18-peppa-prod/design.md | 81 ++++++ .../changes/pep-18-peppa-prod/proposal.md | 59 ++++ .../specs/platform-release/spec.md | 74 +++++ openspec/changes/pep-18-peppa-prod/tasks.md | 15 + packages/cli/bin/git-credential-peppa | 5 +- packages/cli/bin/peppa | 5 +- packages/cli/src/index.ts | 35 ++- packages/core/src/backup.ts | 31 ++- packages/mcp/bin/peppa-mcp | 5 +- packages/mcp/src/manager.ts | 2 +- packages/runner/bin/peppa-hook | 5 +- packages/runner/src/ci-feedback.ts | 2 + packages/runner/src/deploy.ts | 8 +- packages/runner/src/index.ts | 1 + packages/runner/src/platform-release.ts | 98 +++++++ packages/testkit/bin/mock-launchctl | 40 +++ packages/testkit/bin/mock-pnpm | 16 ++ .../testkit/test/platform-release.test.ts | 261 ++++++++++++++++++ scripts/install-launchd.sh | 48 +++- scripts/peppa-release.sh | 227 +++++++++++++++ 25 files changed, 1017 insertions(+), 33 deletions(-) create mode 100644 openspec/changes/pep-18-peppa-prod/design.md create mode 100644 openspec/changes/pep-18-peppa-prod/proposal.md create mode 100644 openspec/changes/pep-18-peppa-prod/specs/platform-release/spec.md create mode 100644 openspec/changes/pep-18-peppa-prod/tasks.md create mode 100644 packages/runner/src/platform-release.ts create mode 100755 packages/testkit/bin/mock-launchctl create mode 100755 packages/testkit/bin/mock-pnpm create mode 100644 packages/testkit/test/platform-release.test.ts create mode 100755 scripts/peppa-release.sh diff --git a/AGENTS.md b/AGENTS.md index 671748aa..e368d42a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Текущее состояние и порядок работ: `docs/HANDOFF.md`. ## Структура -- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web` +- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. Прод — только через релиз (PEP-18, ниже), не `next build` в рабочей копии - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36) - `packages/shared` — env, ключи задач (`PEP-42`) @@ -34,7 +34,8 @@ - **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем -- `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) +- **Прод Пеппы (PEP-18)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/<sha>` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh <sha>`: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` +- `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh ## Внешние зависимости — через моки diff --git a/apps/bot/bin/peppa-bot b/apps/bot/bin/peppa-bot index 5a96f3c4..ce228df3 100755 --- a/apps/bot/bin/peppa-bot +++ b/apps/bot/bin/peppa-bot @@ -1,4 +1,7 @@ #!/usr/bin/env bash -PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch +# through ~/peppa/current keeps that path in hooks and git config instead of the release dir. +_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; } +PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l . "$PEPPA_ROOT/scripts/lib/load-env.sh" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@" diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index d1375129..2885ebf5 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -112,6 +112,12 @@ export default async function Help() { <span className="font-mono">deploy</span>). После каждого деплоя — проверка <span className="font-mono">/healthz</span> до 2 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта. </p> + <p className="m-0 text-muted-foreground"> + Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок{" "} + <span className="font-mono">main</span> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с + работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат + предыдущего релиза. + </p> </Section> <Section title="Telegram"> diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 1ff408b1..f2351ba8 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,6 +1,6 @@ import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket, Target } from "lucide-react"; -import { columnOf, currentReleases, describeRepo, listReleases, bugsinkWebhookBase, type Release } from "@peppa/runner"; +import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, type Release } from "@peppa/runner"; import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; @@ -62,6 +62,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr listReleases(db, p.id, 15), currentReleases(db, p.id), ]); + // Peppa itself has no staging: its prod candidate is the newest green main (PEP-18). + const prodCandidate = isPlatform(p) ? await platformReleaseCandidate(db, p) : (current.staging?.sha ?? null); const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase())); // Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway). const noRepoAccess = (login: string) => @@ -226,12 +228,12 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr <EnvLine name="staging" r={current.staging} /> <EnvLine name="прод" r={current.prod} /> </div> - {current.staging && current.staging.sha !== current.prod?.sha && ( + {prodCandidate && prodCandidate !== current.prod?.sha && ( <form action={deployProdAction}> <Hidden fields={{ projectKey: p.key, back }} /> <Button variant="default" size="sm"> <Rocket /> - Выкатить в прод {current.staging.sha.slice(0, 7)} + Выкатить в прод {prodCandidate.slice(0, 7)} </Button> </form> )} diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 135300ef..bb9793f6 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -39,8 +39,8 @@ ## Осторожно -- Бот, вачдог и веб запущены из этой рабочей копии: переключение ветки меняет код, - который подхватится при их перезапуске (PEP-18). Перед `launchctl kickstart` убедись, - что стоишь на `main`. -- После правок веба: `next build` в `apps/web` + перезапуск `quest.telecom.peppa.web`. +- Прод (PEP-18) — `~/peppa/current`, отдельно от рабочей копии: выкатывать кнопкой PM + («🚀 Выкатить в прод» после зелёного main, страница PEP, MCP `deploy`, `peppa deploy prod PEP`) + или `~/peppa/current/scripts/peppa-release.sh <sha>`; не `next build`/kickstart руками. + Пока боевые launchd не переключены на `~/peppa/current`, сервисы ещё в рабочей копии. - e2e: `pnpm --filter @peppa/testkit test` (~2 минуты, 64 теста на main). diff --git a/openspec/changes/pep-18-peppa-prod/design.md b/openspec/changes/pep-18-peppa-prod/design.md new file mode 100644 index 00000000..4d5ccf7e --- /dev/null +++ b/openspec/changes/pep-18-peppa-prod/design.md @@ -0,0 +1,81 @@ +# Design: PEP-18 — отдельный прод Пеппы + +## Раскладка `~/peppa` (`PEPPA_RELEASES_DIR`) + +``` +~/peppa/ + repo.git/ bare-клон peppa-bot/peppa (credential.helper peppa — локально в repo.git) + releases/<sha>/ git worktree --detach на коммит; .env → ../../shared/.env + current -> releases/<sha> + shared/.env единственный .env прода + logs/<sha>-<время>.log + .lock/ один релиз за раз (pid внутри; мёртвый pid — замок снимается) +``` + +`~/peppa/workspaces` (проекты фабрики) остаётся рядом и не пересекается. + +## Порядок шагов и почему не «бэкап → migrate → install → build» + +`peppa db migrate` — код релиза, ему нужны зависимости, поэтому install идёт первым. Сборка — +до бэкапа и миграций: упавшая сборка не меняет ни схему, ни сервисы, а окно, когда старый код +работает на новой схеме, сокращается до «migrate → kickstart» (секунды). Итог: + +1. fetch `repo.git`, коммит существует → `git worktree add --detach releases/<sha>` +2. `pnpm install --frozen-lockfile` · 3. `pnpm --filter @peppa/web build` +4. `peppa db backup ~/.peppa/backups/release-<время>-<sha7>.db` (VACUUM INTO + `quick_check` копии; + хранятся 5 последних релизных копий, ежедневные — отдельно, 7 штук) +5. `peppa db migrate` · 6. `ln -sfn releases/<sha> current` · 7. `launchctl kickstart -k` web, bot, watchdog +8. health до `PEPPA_RELEASE_HEALTH_TIMEOUT` (120 с): `/api/health` → 200, `commit` = префикс sha, + heartbeat бота и вачдога новее переключения; `peppa status` — в журнал +9. провал → `current` на предыдущий, kickstart, health предыдущего → `rolled_back` + (или `failed`, если предыдущего нет или он тоже нездоров). Схема не откатывается + (миграции аддитивные); причина и путь бэкапа — в `reason`. +10. успех → `healthy`, старые релизы удаляются (держим 5, `current` и предыдущий не трогаем). + +Отчёты — `peppa release report PEP --sha … --status … [--previous] [--reason] [--log-file] [--commits-file]` +через CLI собираемого релиза (после install), до него — через CLI `current`. `recordRelease` +находит открытый `deploying` по sha и дописывает его → те же уведомления PM, что у проектов. +Сбой самого скрипта (trap EXIT) — отчёт `failed` с хвостом журнала. Строка `deploying`, +зависшая дольше часа (скрипт убит), при следующей кнопке помечается `failed`. + +## Кто нажимает кнопку + +- `recordCheck`: зелёный отчёт по `branch=main` проекта платформы, все `checks` из + `.peppa/project.json` рабочей копии проекта зелёные → `expireProdOffers` + вопрос с + `PROD_OPTION`. Предложение одно на коммит. +- `deployProd(project)` для `PEPPA_PLATFORM_KEY` (по умолчанию `PEP`) → `deployPlatform`: + кандидат — последний коммит main с полностью зелёными проверками (по `check_runs`); + проверки: идёт ли деплой, есть ли кандидат, не он ли уже в проде → строка `releases` + (`deploying`, автор) + запрос `~/.peppa/release-queue/<id>.json` (`{releaseId, sha, by}`, + запись через временный файл + rename). +- launchd `quest.telecom.peppa.release`: `QueueDirectories` на очередь, `peppa-release.sh --queue` + обрабатывает файлы по порядку и переносит в `~/peppa/requests/` (launchd перезапускает job, + пока каталог не пуст). Мусор (не sha) отбрасывается с записью в журнал. + +## Стабильные пути + +`readlink -f` в bin-обёртках давал физический путь релиза; он записывался в хуки +(`run-settings.ts`) и `credential.helper` рабочих копий проектов (`git.ts`) и сломался бы +после удаления релиза. Теперь обёртки разворачивают только симлинк самого бинаря +(`~/.local/bin/peppa` → `~/peppa/current/packages/cli/bin/peppa`) и берут логический путь; +launchd-агенты получают `PEPPA_ROOT=$ROOT` (`~/peppa/current`). Существующие рабочие копии +проектов указывают на `/Users/telecom/Dev/Peppa/...` — работают, пока рабочая копия на месте. + +## install-launchd: гонка bootout/bootstrap + +`launchctl bootout` возвращается до выгрузки; `bootstrap` сразу за ним падает с +`5: Input/output error`. Ждём, пока `launchctl print gui/<uid>/<label>` не перестанет находить +агент (до `PEPPA_LAUNCHD_WAIT_SEC`, 10 с), затем bootstrap; если всё же «5» — одна повторная +попытка через секунду. + +## Тесты + +Только моки: `mock-launchctl` (состояние в `MOCK_LAUNCHCTL_STATE`: загружен/выгружается N +вызовов `print`, bootstrap во время выгрузки → «Bootstrap failed: 5»), `mock-pnpm` (install, +build, `MOCK_PNPM_FAIL=build`), локальный git-репо вместо Gitea, health — http-сервер теста, +отдающий коммит, на который указывает `current`; БД, CLI и `recordRelease` — настоящие +(временный SQLite). + +## Переключение прода (разово, координирующая сессия) + +См. отчёт PR: последовательность команд и откат. diff --git a/openspec/changes/pep-18-peppa-prod/proposal.md b/openspec/changes/pep-18-peppa-prod/proposal.md new file mode 100644 index 00000000..8e3146de --- /dev/null +++ b/openspec/changes/pep-18-peppa-prod/proposal.md @@ -0,0 +1,59 @@ +# Proposal: PEP-18 — отдельный прод Пеппы: релизный каталог, деплой по кнопке, бэкап БД + +Задача Пеппы: **PEP-18** · продолжение PEP-57 «Этап 4.2» (план одобрен PM, вопрос #49) · база — SQLite (PEP-36). + +## Why + +Веб, бот и вачдог запущены из рабочей копии разработки `/Users/telecom/Dev/Peppa`: +переключение ветки или незакоммиченный код попадают в прод при любом рестарте, миграции и +сборка делаются руками, отката нет. Проекты фабрики уже выкатываются по кнопке PM (PEP-57), +Пеппа — нет. + +## What Changes + +- **Релизный каталог** `~/peppa` (`PEPPA_RELEASES_DIR`): свой bare-клон `repo.git` репо + `peppa-bot/peppa`, релизы `releases/<sha>` (git worktree на конкретный коммит), симлинк + `current`, общий `shared/.env` (симлинк `.env` в каждый релиз), журналы `logs/`. +- **`scripts/peppa-release.sh <sha>`**: fetch → worktree → `pnpm install --frozen-lockfile` → + `next build` → бэкап БД (`peppa db backup`, `VACUUM INTO` + проверка копии) → + `peppa db migrate` → переключение `current` → `launchctl kickstart -k` web/bot/watchdog → + health (`/api/health` отдаёт коммит релиза, свежие heartbeat бота и вачдога, `peppa status` + в журнал) → при провале `current` назад и kickstart (схема не откатывается: миграции + аддитивные, бэкап — для ручного восстановления). Отчёт каждого шага — `peppa release report` + в ту же таблицу `releases` (проект PEP, окружение `prod`) → обычные уведомления PM. +- **Хостовый слушатель** `quest.telecom.peppa.release` (launchd, `QueueDirectories` + `~/.peppa/release-queue`): кнопка PM пишет туда запрос, launchd запускает + `peppa-release.sh --queue`. Подпись не нужна: очередь — каталог пользователя на этом же + хосте, писать в неё могут только процессы Пеппы (job в контейнере act_runner туда не пишет). +- **Кнопка «🚀 Выкатить в прод» для Пеппы**: после зелёных проверок `main` (CI Пеппы, + PEP-57 этап 4.1) PM получает предложение выкатить этот коммит; `deployProd` для проекта + платформы (`PEPPA_PLATFORM_KEY`, по умолчанию `PEP`) вместо тега ставит запрос в очередь. + Работает из веба («Релизы»), Telegram, MCP `deploy` и CLI `peppa deploy prod PEP`. +- **Стабильные пути**: launchd-агенты получают `PEPPA_ROOT=~/peppa/current`, bin-обёртки + считают корень по логическому пути (не `readlink -f`) — хуки раннеров и + `credential.helper` проектов указывают на `current`, а не на конкретный релиз, который + потом удалится. +- **`scripts/install-launchd.sh`**: ждёт фактической выгрузки агента после асинхронного + `bootout` (цикл с `launchctl print`) — нет «Bootstrap failed: 5: Input/output error»; + новый сервис `release`. +- **Бэкап**: копия проверяется (`PRAGMA quick_check` на копии) — и ежедневная из вачдога, и + релизная; `peppa db backup [файл]`. + +## Capabilities + +### New Capabilities +- `platform-release`: прод Пеппы из релизного каталога, деплой по кнопке PM, бэкап и откат. + +### Modified Capabilities +— + +## Impact + +- Новое: `scripts/peppa-release.sh`, `packages/runner/src/platform-release.ts`, + `packages/testkit/bin/mock-launchctl`, `mock-pnpm`, тест `platform-release.test.ts`. +- Меняется: `scripts/install-launchd.sh`, bin-обёртки (корень), `deploy.ts` (`deployProd`), + `ci-feedback.ts` (предложение после зелёного main), `core/backup.ts`, CLI + (`db backup`, `release report`). +- Миграций БД нет. +- Переключение боевых launchd на `~/peppa/current` — разовая операция координирующей сессии + (последовательность и откат — в design.md, «Переключение»). diff --git a/openspec/changes/pep-18-peppa-prod/specs/platform-release/spec.md b/openspec/changes/pep-18-peppa-prod/specs/platform-release/spec.md new file mode 100644 index 00000000..ee1480c9 --- /dev/null +++ b/openspec/changes/pep-18-peppa-prod/specs/platform-release/spec.md @@ -0,0 +1,74 @@ +# Spec Delta: platform-release + +## Purpose + +Определяет, как выкатывается сама Пеппа: из отдельного релизного каталога, по кнопке PM, с бэкапом базы, проверкой здоровья и автооткатом. + +## ADDED Requirements + +### Requirement: Прод из релизного каталога +Сервисы Пеппы (веб, бот, вачдог) SHALL запускаться из `~/peppa/current` — симлинка на релиз `~/peppa/releases/<sha>`, отдельный от рабочей копии разработки; пути в хуках раннеров и git-настройках проектов SHALL указывать на `current`, а не на конкретный релиз. + +#### Scenario: Ветка в рабочей копии не попадает в прод +- **GIVEN** в проде релиз «a1b2c3d», а в рабочей копии разработки открыта ветка «task/PEP-99» +- **WHEN** вачдог перезапускается +- **THEN** вачдог работает на коде «a1b2c3d» + +#### Scenario: Хук раннера переживает смену релиза +- **GIVEN** раннер запущен на релизе «a1b2c3d» +- **WHEN** выкачен релиз «e4f5a6b» и старые релизы удалены +- **THEN** хуки раннера по-прежнему вызываются через `~/peppa/current` + +### Requirement: Деплой Пеппы по кнопке PM +После зелёных проверок `main` Пеппы PM SHALL получать предложение «🚀 Выкатить в прод»; кнопка в вебе, Telegram, MCP или CLI SHALL ставить запрос хостовому слушателю, который выкатывает этот коммит. + +#### Scenario: Зелёный main — предложение PM +- **GIVEN** все проверки коммита «e4f5a6b» ветки main Пеппы прошли +- **WHEN** Пеппа получает последний зелёный отчёт CI +- **THEN** PM получает «✅ Peppa: main зелёный — e4f5a6b. Выкатить в прод?» с кнопкой «🚀 Выкатить в прод» + +#### Scenario: Кнопка ставит запрос слушателю +- **GIVEN** предложение выкатить «e4f5a6b» +- **WHEN** PM нажимает «🚀 Выкатить в прод» +- **THEN** появляется релиз прода «e4f5a6b» в статусе «deploying» с автором PM +- **AND** в очереди слушателя лежит запрос на «e4f5a6b» + +#### Scenario: Красный main не выкатывается +- **GIVEN** проверка «test» коммита main «e4f5a6b» упала +- **WHEN** PM вызывает «Выкатить в прод» для Пеппы +- **THEN** PM видит «main без зелёных проверок — выкатывать нечего», запроса нет + +#### Scenario: Второй запрос во время деплоя +- **GIVEN** релиз прода Пеппы «e4f5a6b» выкатывается +- **WHEN** PM снова нажимает «Выкатить в прод» +- **THEN** PM видит «прод уже выкатывается (e4f5a6b)» + +### Requirement: Релиз с бэкапом и автооткатом +Скрипт релиза SHALL собрать релиз до остановки сервисов, сделать проверенную копию базы до миграций, переключить `current`, перезапустить сервисы и проверить здоровье; при провале SHALL вернуть предыдущий релиз и сообщить PM причину. + +#### Scenario: Успешный релиз +- **GIVEN** в проде релиз «a1b2c3d» +- **WHEN** слушатель выкатывает «e4f5a6b», и после перезапуска веб отдаёт коммит «e4f5a6b», а бот и вачдог шлют heartbeat +- **THEN** `current` указывает на «e4f5a6b», релиз «healthy» со списком задач из коммитов +- **AND** перед миграцией в `~/.peppa/backups` появилась проверенная копия базы +- **AND** PM получает «🚀 Peppa в проде: e4f5a6b» + +#### Scenario: Нездоровый релиз откатывается +- **GIVEN** в проде релиз «a1b2c3d» +- **WHEN** после переключения на «e4f5a6b» веб не отвечает здоровым за отведённое время +- **THEN** `current` снова указывает на «a1b2c3d», сервисы перезапущены +- **AND** релиз «rolled_back» с причиной, PM получает «❌ … возвращён a1b2c3d» + +#### Scenario: Сборка упала — прод не тронут +- **GIVEN** в проде релиз «a1b2c3d» +- **WHEN** `next build` релиза «e4f5a6b» падает +- **THEN** сервисы не перезапускаются, миграции не применяются, `current` указывает на «a1b2c3d» +- **AND** релиз «failed» с хвостом журнала + +### Requirement: Установка launchd без гонки +`install-launchd.sh` SHALL дожидаться фактической выгрузки агента после `bootout` перед `bootstrap`. + +#### Scenario: Переустановка работающего агента +- **GIVEN** агент `quest.telecom.peppa.web` загружен, и launchd выгружает его не сразу +- **WHEN** запускается `install-launchd.sh web` +- **THEN** `bootstrap` вызывается только после того, как `launchctl print` перестал находить агент, и установка проходит без «Bootstrap failed: 5» diff --git a/openspec/changes/pep-18-peppa-prod/tasks.md b/openspec/changes/pep-18-peppa-prod/tasks.md new file mode 100644 index 00000000..cb77060b --- /dev/null +++ b/openspec/changes/pep-18-peppa-prod/tasks.md @@ -0,0 +1,15 @@ +# Tasks: PEP-18 + +## 1. Релиз +- [x] 1.1 `scripts/peppa-release.sh <sha>|--queue`: раскладка `~/peppa`, замок, worktree, install, build, бэкап, migrate, переключение, kickstart, health, автооткат, отчёты, чистка +- [x] 1.2 CLI: `peppa db backup [файл]`, `peppa release report`; `backupDb` проверяет копию +- [x] 1.3 runner: `deployPlatform` + очередь, `deployProd` для проекта платформы, предложение после зелёного main + +## 2. Хост +- [x] 2.1 `install-launchd.sh`: ожидание выгрузки, сервис `release` (QueueDirectories), `PEPPA_ROOT` в агентах +- [x] 2.2 bin-обёртки: логический корень вместо `readlink -f` + +## 3. Проверка +- [x] 3.1 `mock-launchctl`, `mock-pnpm`; тест `platform-release.test.ts` по сценариям спеки +- [x] 3.2 typecheck, весь e2e, `openspec validate` +- [x] 3.3 AGENTS.md, HANDOFF: прод из `~/peppa/current`, как выкатывать diff --git a/packages/cli/bin/git-credential-peppa b/packages/cli/bin/git-credential-peppa index baae3114..05c21aff 100755 --- a/packages/cli/bin/git-credential-peppa +++ b/packages/cli/bin/git-credential-peppa @@ -1,7 +1,10 @@ #!/usr/bin/env bash # Git credential helper: answers for the Peppa Gitea host with peppa-bot's token. # Enabled per repo (never globally): git config credential.helper peppa -PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch +# through ~/peppa/current keeps that path in hooks and git config instead of the release dir. +_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; } +PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l [ "$1" = "get" ] || exit 0 . "$PEPPA_ROOT/scripts/lib/load-env.sh" want="${GITEA_URL#*://}"; host="" diff --git a/packages/cli/bin/peppa b/packages/cli/bin/peppa index 442bd3ae..807684a3 100755 --- a/packages/cli/bin/peppa +++ b/packages/cli/bin/peppa @@ -1,4 +1,7 @@ #!/usr/bin/env bash -PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch +# through ~/peppa/current keeps that path in hooks and git config instead of the release dir. +_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; } +PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l . "$PEPPA_ROOT/scripts/lib/load-env.sh" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@" diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index a1db5dba..c760fc97 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -2,6 +2,7 @@ import { parseArgs } from "node:util"; import { resolve } from "node:path"; import { + backupDb, createGoal, createProject, createTask, @@ -39,8 +40,9 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb, migrateDb } from "@peppa/db"; -import { answerAndDeliver, connectCi, deployProd, listReleases, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, deployProd, listReleases, recordRelease, type ReleaseStatus, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; import { loadEnv } from "@peppa/shared"; const USAGE = `peppa — Peppa software factory CLI @@ -51,6 +53,8 @@ const USAGE = `peppa — Peppa software factory CLI peppa project list peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) peppa release list [KEY] + peppa release report [KEY] --sha <sha> -s <deploying|healthy|rolled_back|failed> [--previous <sha>] [--reason <text>] + [--log-file <f>] [--commits-file <f>] (prod release step, from scripts/peppa-release.sh) peppa ci connect [KEY] (runner + secret + PR with the CI workflow from the template) peppa goal add [KEY] <title> [-d <description>] peppa goal list [KEY] @@ -74,6 +78,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa web login-link <gitea-login> (one-time admin login, 10 minutes) peppa watchdog [--once] [--interval <sec>] [--stall <min>] peppa db migrate (apply schema migrations to PEPPA_DB) + peppa db backup [file] (checked VACUUM INTO copy; default: today's daily copy) peppa db migrate-to-sqlite <file> (one-time copy from Postgres DATABASE_URL, read-only) KEY defaults to the project of the current directory (.peppa/project.json). @@ -99,6 +104,11 @@ const { values: opts, positionals } = parseArgs({ once: { type: "boolean" }, interval: { type: "string", default: "30" }, stall: { type: "string", default: "15" }, + sha: { type: "string" }, + previous: { type: "string" }, + reason: { type: "string" }, + "log-file": { type: "string" }, + "commits-file": { type: "string" }, }, }); @@ -110,6 +120,12 @@ if (positionals[0] === "db") { if (positionals[1] === "migrate") { migrateDb(createDb(env.PEPPA_DB)); console.log(`migrated ${env.PEPPA_DB}`); + } else if (positionals[1] === "backup") { + const db = createDb(env.PEPPA_DB); + const r = await backupDb(db, { force: true, file: positionals[2] ? resolve(positionals[2]) : undefined, log: (m) => console.error(m) }); + db.$client.close(); + if (!r.file) throw new PeppaError(`backup failed: ${r.error}`); + console.log(r.file); } else if (positionals[1] === "migrate-to-sqlite" && positionals[2]) { if (!env.DATABASE_URL) throw new PeppaError("DATABASE_URL (the Postgres source) is not set"); const { migrateToSqlite } = await import("./migrate-to-sqlite.ts"); @@ -217,6 +233,23 @@ async function main(): Promise<void> { for (const r of await listReleases(db, p.id)) console.log(`#${r.id} ${r.env.padEnd(8)} ${r.sha.slice(0, 7)} ${r.status.padEnd(11)} ${r.tasks.join(",")} ${r.deployedBy} ${r.reason ?? ""}`); break; } + case "release report": { + const [key] = withKey(args, 0); + const p = await getProject(db, key); + if (!opts.sha || !opts.status) throw new PeppaError("usage: peppa release report [KEY] --sha <sha> -s <status>"); + const read = (f: string | undefined) => (f ? readFileSync(f, "utf8") : null); + const r = await recordRelease(db, p, { + env: "prod", + sha: opts.sha, + previousSha: opts.previous || null, + status: opts.status as ReleaseStatus, + reason: opts.reason || null, + logTail: read(opts["log-file"])?.trimEnd().split("\n").slice(-100).join("\n") || null, + commits: read(opts["commits-file"])?.split("\n").filter(Boolean), + }); + console.log(`#${r.id} ${r.env} ${r.sha.slice(0, 7)} ${r.status} ${r.tasks.join(",")}`); + break; + } case "goal add": { const [key, [title]] = withKey(args, 1); if (!title) throw new PeppaError("usage: peppa goal add [KEY] <title>"); diff --git a/packages/core/src/backup.ts b/packages/core/src/backup.ts index 5660459d..723d2ebb 100644 --- a/packages/core/src/backup.ts +++ b/packages/core/src/backup.ts @@ -1,7 +1,8 @@ import type { Db } from "@peppa/db"; import { peppaHome } from "@peppa/shared"; import { mkdirSync, readdirSync, rmSync } from "node:fs"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; import { alertAdmins } from "./monitor.ts"; import { getSetting, setSetting } from "./settings.ts"; @@ -14,26 +15,42 @@ export interface BackupOptions { keep?: number; /** Back up even if the last copy is younger than a day. */ force?: boolean; + /** One-off copy to this file (a release backup, PEP-18): no daily rotation or bookkeeping. */ + file?: string; log?: (m: string) => void; } +/** A copy is only a backup if it opens and passes `quick_check`; throws otherwise. */ +export function verifyBackup(file: string): void { + const copy = new DatabaseSync(file, { readOnly: true }); + try { + const r = copy.prepare("PRAGMA quick_check").get() as { quick_check?: string } | undefined; + if (r?.quick_check !== "ok") throw new Error(`копия повреждена: ${r?.quick_check ?? "нет ответа"}`); + copy.prepare("select count(*) from settings").get(); + } finally { + copy.close(); + } +} + /** * Daily consistent copy of the database (`VACUUM INTO`, no need to stop anything) into * ~/.peppa/backups/peppa-YYYY-MM-DD.db, keeping the newest `keep` (7). A failed copy is - * removed and the platform admins are told; the services keep running either way. + * checked (`verifyBackup`); a failed copy is removed and the platform admins are told; the + * services keep running either way. */ export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: string; error?: string; skipped?: boolean }> { const now = o.now ?? new Date(); const log = o.log ?? (() => {}); const last = await getSetting<{ at: number }>(db, KEY); - if (!o.force && last && now.getTime() - last.at < DAY_MS) return { skipped: true }; - const dir = o.dir ?? join(peppaHome(), "backups"); + if (!o.file && !o.force && last && now.getTime() - last.at < DAY_MS) return { skipped: true }; + const dir = o.file ? dirname(o.file) : (o.dir ?? join(peppaHome(), "backups")); const day = now.toLocaleDateString("sv-SE"); - const file = join(dir, `peppa-${day}.db`); + const file = o.file ?? join(dir, `peppa-${day}.db`); try { mkdirSync(dir, { recursive: true }); rmSync(file, { force: true }); // VACUUM INTO refuses to overwrite db.$client.db.prepare("VACUUM INTO ?").run(file); + verifyBackup(file); } catch (e) { try { rmSync(file, { force: true }); @@ -43,6 +60,10 @@ export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: await alertAdmins(db, `backup:fail:${day}`, `⚠️ Резервная копия базы Пеппы не сделана: ${reason}`, log); return { error: reason }; } + if (o.file) { + log(`backup: ${file}`); + return { file }; + } const keep = o.keep ?? 7; const copies = readdirSync(dir).filter((f) => /^peppa-\d{4}-\d{2}-\d{2}\.db$/.test(f)).sort(); for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true }); diff --git a/packages/mcp/bin/peppa-mcp b/packages/mcp/bin/peppa-mcp index 837073f1..5716a4b0 100755 --- a/packages/mcp/bin/peppa-mcp +++ b/packages/mcp/bin/peppa-mcp @@ -1,5 +1,8 @@ #!/usr/bin/env bash # Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves. -PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch +# through ~/peppa/current keeps that path in hooks and git config instead of the release dir. +_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; } +PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l . "$PEPPA_ROOT/scripts/lib/load-env.sh" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@" diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index c5f59784..e3a4424c 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -262,7 +262,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool( "deploy", - "Deploy the project's healthy staging release to prod (the same image). Only when the user asks; the result arrives as a release (list_releases) and a message.", + "Deploy the project's healthy staging release to prod (the same image); for Peppa itself (no staging) the newest commit of main with green checks, released on its host. Only when the user asks; the result arrives as a release (list_releases) and a message.", { project: projectArg, env: z.enum(["prod"]).default("prod") }, false, async ({ project }) => { diff --git a/packages/runner/bin/peppa-hook b/packages/runner/bin/peppa-hook index 38dc361f..24c530b4 100755 --- a/packages/runner/bin/peppa-hook +++ b/packages/runner/bin/peppa-hook @@ -1,5 +1,8 @@ #!/usr/bin/env bash -PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch +# through ~/peppa/current keeps that path in hooks and git config instead of the release dir. +_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; } +PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l # Not a Peppa session: nothing to do, skip node startup. [ -z "${PEPPA_SESSION_ID:-}" ] && { [ "${1:-}" = codex-notify ] || cat >/dev/null; exit 0; } . "$PEPPA_ROOT/scripts/lib/load-env.sh" diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 09ac608a..190a0891 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -24,6 +24,7 @@ import { and, eq, sql } from "drizzle-orm"; import { sendToSession } from "./sessions.ts"; import { moveTask } from "./flow.ts"; import { recordRelease } from "./deploy.ts"; +import { offerPlatformRelease } from "./platform-release.ts"; /** Red runs in a row after which the PM is asked instead of the agent. */ export const MAX_CI_ATTEMPTS = 3; @@ -45,6 +46,7 @@ export interface CheckOutcome { export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise<CheckOutcome> { const ref = await taskForCheck(db, project, r.branch, r.prNumber); const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r); + if (changed && r.state === "success" && r.branch === "main") await offerPlatformRelease(db, project, r.sha); if (!ref || !changed) return { task: ref?.key ?? null, action: "none" }; if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" }; diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index c994b03a..1f7b4ac7 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -5,6 +5,7 @@ import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; import { projects, questions, releases, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; +import { deployPlatform, isPlatform } from "./platform-release.ts"; export type Release = typeof releases.$inferSelect; export type ReleaseEnv = Release["env"]; @@ -57,7 +58,7 @@ export async function currentReleases(db: Db, projectId: number): Promise<Partia const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—"); /** Closes earlier unanswered "deploy to prod?" offers of the project: a newer staging is up. */ -async function expireProdOffers(db: Db, projectId: number) { +export async function expireProdOffers(db: Db, projectId: number) { const open = await db .select() .from(questions) @@ -128,8 +129,11 @@ async function notifyRelease(db: Db, project: Project, rel: Release) { /** * "Deploy to prod" (web, Telegram, MCP): the image of the latest healthy staging release * goes to prod — Peppa tags that commit `deploy-prod-<time>` and the workflow deploys it. + * Peppa itself has no staging: its green main goes to the host listener (PEP-18). */ -export async function deployProd(db: Db, project: Project, by: string, gitea: GiteaClient = giteaForBot()): Promise<Release> { +export async function deployProd(db: Db, project: Project, by: string, client?: GiteaClient): Promise<Release> { + if (isPlatform(project)) return deployPlatform(db, project, by); + const gitea = client ?? giteaForBot(); const { staging, prod } = await currentReleases(db, project.id); if (!staging) throw new PeppaError(`${project.key}: на staging нет здорового релиза — выкатывать нечего`); const [running] = await db diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 71e8ed88..6efa5781 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -15,3 +15,4 @@ export * from "./incidents.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; export * from "./deploy.ts"; +export * from "./platform-release.ts"; diff --git a/packages/runner/src/platform-release.ts b/packages/runner/src/platform-release.ts new file mode 100644 index 00000000..83aaf046 --- /dev/null +++ b/packages/runner/src/platform-release.ts @@ -0,0 +1,98 @@ +// Prod of Peppa itself (PEP-18). Peppa runs from ~/peppa/current, a release directory apart +// from the development checkout. A release can't go through a CI job (a container can't +// `launchctl`), so the PM's button queues a request on this host and the launchd agent +// quest.telecom.peppa.release runs scripts/peppa-release.sh, which reports back through +// `peppa release report` → recordRelease (same releases table and PM messages as projects). +import { askPmProject, configuredChecks, summarizeChecks, PeppaError, type Project } from "@peppa/core"; +import { checkRuns, releases, type Db } from "@peppa/db"; +import { peppaHome } from "@peppa/shared"; +import { and, desc, eq } from "drizzle-orm"; +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { currentReleases, expireProdOffers, PROD_OPTION, type Release } from "./deploy.ts"; + +/** A `deploying` row older than this means the release script died without a report. */ +const STALE_MS = 3600_000; + +/** Key of the project that is Peppa itself. */ +export const platformKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP"; +export const isPlatform = (project: Project) => project.key === platformKey(); + +/** Where the PM's button leaves requests for the host listener. */ +export const releaseQueueDir = () => process.env.PEPPA_RELEASE_QUEUE || join(peppaHome(), "release-queue"); + +export interface ReleaseRequest { + releaseId: number; + sha: string; + by: string; +} + +function projectChecks(project: Project): string[] { + const f = join(project.workspacePath, ".peppa/project.json"); + return configuredChecks(existsSync(f) ? readFileSync(f, "utf8") : null); +} + +/** The commit of main with all configured checks green, newest first; null if none. */ +async function greenMainSha(db: Db, project: Project, sha?: string): Promise<string | null> { + const configured = projectChecks(project); + if (!configured.length) return null; + const runs = await db + .select() + .from(checkRuns) + .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.branch, "main"), sha ? eq(checkRuns.sha, sha) : undefined)) + .orderBy(desc(checkRuns.updatedAt)); + // Newest commit first: the order its runs were last updated in. + const shas = [...new Set(runs.map((r) => r.sha))]; + for (const s of shas) { + if (summarizeChecks(configured, runs.filter((r) => r.sha === s), s).state === "success") return s; + } + return null; +} + +/** What the PM's button would release now: the newest green main commit. */ +export const platformReleaseCandidate = (db: Db, project: Project) => greenMainSha(db, project); + +const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—"); + +/** A green report of main: offer the PM to release that commit (once per commit). */ +export async function offerPlatformRelease(db: Db, project: Project, sha: string): Promise<boolean> { + if (!isPlatform(project) || (await greenMainSha(db, project, sha)) !== sha) return false; + const { prod } = await currentReleases(db, project.id); + if (prod?.sha === sha) return false; + await expireProdOffers(db, project.id); + await askPmProject(db, project, { + kind: "question", + options: [PROD_OPTION], + text: `✅ ${project.name}: main зелёный — ${short(sha)}. Выкатить в прод?`, + }); + return true; +} + +/** "Deploy to prod" for Peppa: the newest green main commit goes to the host listener's queue. */ +export async function deployPlatform(db: Db, project: Project, by: string, o: { now?: Date } = {}): Promise<Release> { + const now = o.now ?? new Date(); + const [running] = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))) + .orderBy(desc(releases.id)) + .limit(1); + if (running && now.getTime() - running.createdAt.getTime() < STALE_MS) throw new PeppaError(`${project.key}: прод уже выкатывается (${short(running.sha)})`); + if (running) await db.update(releases).set({ status: "failed", reason: "скрипт релиза не ответил за час" }).where(eq(releases.id, running.id)); + const sha = await greenMainSha(db, project); + if (!sha) throw new PeppaError(`${project.key}: main без зелёных проверок — выкатывать нечего`); + const { prod } = await currentReleases(db, project.id); + if (prod?.sha === sha) throw new PeppaError(`${project.key}: ${short(sha)} уже в проде`); + const [rel] = await db + .insert(releases) + .values({ projectId: project.id, env: "prod", sha, previousSha: prod?.sha ?? null, status: "deploying", deployedBy: by }) + .returning(); + const dir = releaseQueueDir(); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const req: ReleaseRequest = { releaseId: rel!.id, sha, by }; + // Written beside the queue and renamed in: launchd starts the listener on any file there. + const tmp = `${dir}.${rel!.id}.tmp`; + writeFileSync(tmp, JSON.stringify(req)); + renameSync(tmp, join(dir, `${rel!.id}.json`)); + return rel!; +} diff --git a/packages/testkit/bin/mock-launchctl b/packages/testkit/bin/mock-launchctl new file mode 100755 index 00000000..8f332e49 --- /dev/null +++ b/packages/testkit/bin/mock-launchctl @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# mock-launchctl — stands in for launchctl in install-launchd.sh / peppa-release.sh tests (first +# on PATH as `launchctl`). Same subcommands, messages and exit codes as the real one; state lives +# in $MOCK_LAUNCHCTL_STATE: loaded/<label> (its plist), unloading/<label> (`print` calls left +# until it is gone), calls.log. Like launchd, `bootout` returns before the agent is unloaded: +# it stays visible for $MOCK_LAUNCHCTL_UNLOAD_PRINTS (2) `print` calls, and a `bootstrap` of it +# meanwhile fails with "Bootstrap failed: 5: Input/output error". +# MOCK_LAUNCHCTL_KICKSTART_FAIL=<label> makes `kickstart` of that label fail. +set -uo pipefail +st="${MOCK_LAUNCHCTL_STATE:?MOCK_LAUNCHCTL_STATE is required}" +mkdir -p "$st/loaded" "$st/unloading" +echo "launchctl $*" >> "$st/calls.log" +label() { echo "${1##*/}"; } # gui/501/<label> → <label> +case "${1:-}" in + print) + l=$(label "$2") + if [[ -f "$st/unloading/$l" ]]; then + n=$(cat "$st/unloading/$l") + if (( n <= 0 )); then rm -f "$st/unloading/$l" "$st/loaded/$l" + else echo $((n - 1)) > "$st/unloading/$l"; echo "$2 = { state = exiting }"; exit 0; fi + fi + [[ -f "$st/loaded/$l" ]] || { echo "Bad request." >&2; echo "Could not find service \"$l\" in domain for user gui: ${2#gui/}" >&2; exit 113; } + echo "$2 = { state = running }" ;; + bootout) + l=$(label "$2") + [[ -f "$st/loaded/$l" && ! -f "$st/unloading/$l" ]] || { echo "Boot-out failed: 113: Could not find specified service" >&2; exit 113; } + echo "${MOCK_LAUNCHCTL_UNLOAD_PRINTS:-2}" > "$st/unloading/$l" ;; + bootstrap) + plist="$3" + l=$(/usr/bin/sed -n 's:.*<key>Label</key><string>\(.*\)</string>.*:\1:p' "$plist") + [[ -n "$l" ]] || { echo "Bootstrap failed: 22: Invalid argument" >&2; exit 22; } + if [[ -f "$st/loaded/$l" ]]; then echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi + cp "$plist" "$st/loaded/$l" ;; + kickstart) + l=$(label "${@: -1}") + [[ -f "$st/loaded/$l" ]] || { echo "Could not find service \"$l\" in domain for user gui" >&2; exit 113; } + [[ "${MOCK_LAUNCHCTL_KICKSTART_FAIL:-}" == "$l" ]] && { echo "Could not kickstart service \"$l\": 1: Operation not permitted" >&2; exit 1; } + echo "$l kickstarted" >> "$st/kickstarts.log" ;; + *) echo "mock-launchctl: unsupported: $*" >&2; exit 64 ;; +esac diff --git a/packages/testkit/bin/mock-pnpm b/packages/testkit/bin/mock-pnpm new file mode 100755 index 00000000..4da8af90 --- /dev/null +++ b/packages/testkit/bin/mock-pnpm @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# mock-pnpm — stands in for pnpm in peppa-release.sh tests (first on PATH as `pnpm`): the two +# calls the release makes, in the release directory. `install --frozen-lockfile` creates +# node_modules, `--filter @peppa/web build` writes apps/web/.next/BUILD_ID. Calls go to +# $MOCK_PNPM_LOG; MOCK_PNPM_FAIL=install|build makes that step fail like the real one. +set -uo pipefail +[[ -n "${MOCK_PNPM_LOG:-}" ]] && echo "pnpm $* (in $PWD)" >> "$MOCK_PNPM_LOG" +case "$*" in + "install --frozen-lockfile") + [[ "${MOCK_PNPM_FAIL:-}" == install ]] && { echo " ERR_PNPM_OUTDATED_LOCKFILE Cannot install with \"frozen-lockfile\"" >&2; exit 1; } + mkdir -p node_modules; echo "Done in 0.1s" ;; + "--filter @peppa/web build") + [[ "${MOCK_PNPM_FAIL:-}" == build ]] && { echo "Failed to compile." >&2; echo " ELIFECYCLE Command failed with exit code 1." >&2; exit 1; } + mkdir -p apps/web/.next; git rev-parse HEAD > apps/web/.next/BUILD_ID; echo "✓ Compiled successfully" ;; + *) echo "mock-pnpm: unsupported: $*" >&2; exit 64 ;; +esac diff --git a/packages/testkit/test/platform-release.test.ts b/packages/testkit/test/platform-release.test.ts new file mode 100644 index 00000000..de6a7cbd --- /dev/null +++ b/packages/testkit/test/platform-release.test.ts @@ -0,0 +1,261 @@ +// PEP-18, spec platform-release: Peppa's own prod from ~/peppa/current, the PM's button, the +// release script with backup and rollback, install-launchd without the bootout race. +// scripts/peppa-release.sh and install-launchd.sh run for real against mock-launchctl and +// mock-pnpm (first on PATH), a local git repo instead of Gitea and a mock /api/health that +// answers with the commit `current` points to; the CLI, the DB and recordRelease are real. +import assert from "node:assert/strict"; +import { execFile, execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, symlinkSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { basename, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-release-")); +const RELEASES = join(TMP, "peppa"); +const QUEUE = join(process.env.PEPPA_HOME!, "release-queue"); +const LAUNCHD = join(TMP, "launchd"); +const PNPM_LOG = join(TMP, "pnpm.log"); +process.env.PEPPA_RELEASE_QUEUE = QUEUE; + +// launchctl, pnpm → mocks, first on PATH for the scripts. +const BIN = join(TMP, "bin"); +mkdirSync(BIN); +symlinkSync(join(ROOT, "packages/testkit/bin/mock-launchctl"), join(BIN, "launchctl")); +symlinkSync(join(ROOT, "packages/testkit/bin/mock-pnpm"), join(BIN, "pnpm")); + +// The "Gitea" repo of Peppa: commits are merges of PEP-like task branches. +const REMOTE = join(TMP, "remote"); +const git = (...a: string[]) => execFileSync("git", ["-C", REMOTE, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim(); +mkdirSync(REMOTE); +git("init", "-q", "-b", "main"); +function merge(task: string): string { + writeFileSync(join(REMOTE, `${task}.txt`), task); + git("add", "-A"); + git("commit", "-qm", `Merge pull request '${task}' (#1) from task/${task} into main`); + return git("rev-parse", "HEAD"); +} + +let server: Server; +let healthUrl = ""; +/** Commits whose web never gets healthy. */ +const bad = new Set<string>(); +const currentSha = () => (existsSync(join(RELEASES, "current")) ? basename(readlinkSync(join(RELEASES, "current"))) : null); + +let pep: Awaited<ReturnType<typeof project>>; +let proj: Awaited<ReturnType<typeof core.getProject>>; + +before(async () => { + server = createServer((req, res) => { + const sha = currentSha(); + if (req.url !== "/api/health" || !sha || bad.has(sha)) return void res.writeHead(503).end(JSON.stringify({ ok: false })); + const now = new Date().toISOString(); + res.writeHead(200).end(JSON.stringify({ ok: true, commit: sha.slice(0, 7), services: [{ service: "bot", lastHeartbeat: now }, { service: "watchdog", lastHeartbeat: now }] })); + }); + await new Promise<void>((r) => server.listen(0, "127.0.0.1", r)); + healthUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/health`; + // The platform project: its workspace .peppa/project.json has the checks of main. + pep = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = pep.key; + proj = await core.getProject(db, pep.key); + writeFileSync(join(pep.dir, ".peppa/project.json"), JSON.stringify({ slug: proj.slug, key: pep.key, name: pep.key, checks: { typecheck: "x", test: "x", build: "x" } })); + // Prod services are loaded in (mock) launchd; the release dir has its one .env. + mkdirSync(join(LAUNCHD, "loaded"), { recursive: true }); + for (const s of ["web", "bot", "watchdog"]) writeFileSync(join(LAUNCHD, "loaded", `quest.telecom.peppa.${s}`), ""); + mkdirSync(join(RELEASES, "shared"), { recursive: true }); + writeFileSync(join(RELEASES, "shared/.env"), ""); +}); +after(async () => { + server.close(); + await teardown(); +}); + +const scriptEnv = (extra: Record<string, string> = {}) => ({ + ...process.env, + PATH: `${BIN}:${process.env.PATH}`, + MOCK_LAUNCHCTL_STATE: LAUNCHD, + MOCK_PNPM_LOG: PNPM_LOG, + PEPPA_RELEASES_DIR: RELEASES, + PEPPA_RELEASE_REMOTE: REMOTE, + PEPPA_RELEASE_CLI: join(ROOT, "packages/cli/bin/peppa"), + PEPPA_RELEASE_HEALTH_URL: healthUrl, + PEPPA_RELEASE_HEALTH_TIMEOUT: "2", + PEPPA_RELEASE_HEALTH_INTERVAL: "0.3", + ...extra, +}); + +function sh(script: string, args: string[], env: NodeJS.ProcessEnv): Promise<{ code: number; out: string }> { + return new Promise((done) => + execFile("bash", [join(ROOT, "scripts", script), ...args], { env, encoding: "utf8" }, (err, stdout, stderr) => + done({ code: err ? Number((err as { code?: number }).code ?? 1) : 0, out: stdout + stderr }), + ), + ); +} +const release = (args: string[], extra: Record<string, string> = {}) => sh("peppa-release.sh", args, scriptEnv(extra)); + +const kickstarts = () => (existsSync(join(LAUNCHD, "kickstarts.log")) ? readFileSync(join(LAUNCHD, "kickstarts.log"), "utf8").trim().split("\n").filter(Boolean) : []); +const releaseBackups = () => (existsSync(join(process.env.PEPPA_HOME!, "backups")) ? readdirSync(join(process.env.PEPPA_HOME!, "backups")).filter((f) => f.startsWith("release-")) : []); +const latestRelease = async () => (await runner.listReleases(db, proj.id, 1))[0]!; +const messages = async () => (await core.pendingQuestions(db, proj.id)).map((q) => q.text); + +async function greenMain(sha: string) { + for (const check of ["typecheck", "test", "build"]) await runner.recordCheck(db, proj, { sha, branch: "main", check, state: "success" }); +} + +describe("Деплой Пеппы по кнопке PM", () => { + test("Scenario: Зелёный main — предложение PM", async () => { + const sha = merge(`${pep.key}-5`); + await runner.recordCheck(db, proj, { sha, branch: "main", check: "typecheck", state: "success" }); + assert.ok(!(await core.pendingQuestions(db, proj.id)).some((q) => q.options?.includes(runner.PROD_OPTION)), "no offer until every check is green"); + await greenMain(sha); + const offers = (await core.pendingQuestions(db, proj.id)).filter((q) => q.options?.includes(runner.PROD_OPTION)); + assert.equal(offers.length, 1); + assert.match(offers[0]!.text, new RegExp(`main зелёный — ${sha.slice(0, 7)}\\. Выкатить в прод\\?`)); + }); + + test("Scenario: Кнопка ставит запрос слушателю", async () => { + const offer = (await core.pendingQuestions(db, proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION))!; + assert.equal(await runner.onReleaseAnswer(db, offer, runner.PROD_OPTION, "PM (telegram)"), true); + const rel = await latestRelease(); + assert.equal(rel.env, "prod"); + assert.equal(rel.status, "deploying"); + assert.equal(rel.deployedBy, "PM (telegram)"); + const req = JSON.parse(readFileSync(join(QUEUE, `${rel.id}.json`), "utf8")); + assert.deepEqual(req, { releaseId: rel.id, sha: rel.sha, by: "PM (telegram)" }); + }); + + test("Scenario: Второй запрос во время деплоя", async () => { + const rel = await latestRelease(); + await assert.rejects(runner.deployProd(db, proj, "mock-pm"), new RegExp(`прод уже выкатывается \\(${rel.sha.slice(0, 7)}\\)`)); + }); + + test("Scenario: Красный main не выкатывается", async () => { + const other = await project({ turns: [] }); + const p = await core.getProject(db, other.key); + writeFileSync(join(other.dir, ".peppa/project.json"), JSON.stringify({ slug: p.slug, key: other.key, name: other.key, checks: { typecheck: "x", test: "x" } })); + process.env.PEPPA_PLATFORM_KEY = other.key; + try { + await runner.recordCheck(db, p, { sha: "e4f5a6b0", branch: "main", check: "typecheck", state: "success" }); + await runner.recordCheck(db, p, { sha: "e4f5a6b0", branch: "main", check: "test", state: "failure" }); + await assert.rejects(runner.deployProd(db, p, "mock-pm"), /main без зелёных проверок — выкатывать нечего/); + assert.equal((await runner.listReleases(db, p.id)).length, 0); + } finally { + process.env.PEPPA_PLATFORM_KEY = pep.key; + } + }); +}); + +describe("Релиз с бэкапом и автооткатом", () => { + test("Scenario: Успешный релиз — запрос из очереди, бэкап до миграции, current на новом коммите", async () => { + const rel = await latestRelease(); + const r = await release(["--queue"]); + assert.equal(r.code, 0, r.out); + assert.equal(currentSha(), rel.sha); + assert.deepEqual(readdirSync(QUEUE), [], "the request left the queue"); + assert.deepEqual(kickstarts(), ["quest.telecom.peppa.web kickstarted", "quest.telecom.peppa.bot kickstarted", "quest.telecom.peppa.watchdog kickstarted"]); + assert.equal(releaseBackups().length, 1, "a checked backup before the migration"); + const done = await latestRelease(); + assert.equal(done.id, rel.id, "the button's release row is the one completed"); + assert.equal(done.status, "healthy"); + assert.deepEqual(done.tasks, [`${pep.key}-5`]); + assert.ok((await messages()).some((t) => t.includes(`в проде: ${rel.sha.slice(0, 7)}`)), "the PM is told"); + // The worktree is the commit; .env is the shared one. + assert.equal(readlinkSync(join(RELEASES, "releases", rel.sha, ".env")), join(RELEASES, "shared/.env")); + assert.ok(existsSync(join(RELEASES, "releases", rel.sha, "apps/web/.next/BUILD_ID"))); + }); + + test("Scenario: Нездоровый релиз откатывается", async () => { + const prev = currentSha()!; + const sha = merge(`${pep.key}-6`); + bad.add(sha); + const before = kickstarts().length; + const r = await release([sha]); + assert.equal(r.code, 1, r.out); + assert.equal(currentSha(), prev, "current is back on the previous release"); + assert.equal(kickstarts().length - before, 6, "restarted on the new release, then on the old one"); + const rel = await latestRelease(); + assert.equal(rel.sha, sha); + assert.equal(rel.status, "rolled_back"); + assert.equal(rel.previousSha, prev); + assert.match(rel.reason ?? "", /релиз нездоров: веб не отвечает/); + assert.ok(rel.logTail, "the log tail is kept"); + assert.ok((await messages()).some((t) => t.includes(`релиз ${sha.slice(0, 7)} в prod не прошёл — возвращён ${prev.slice(0, 7)}`))); + }); + + test("Scenario: Сборка упала — прод не тронут", async () => { + const prev = currentSha()!; + const sha = merge(`${pep.key}-8`); + const [k, b] = [kickstarts().length, releaseBackups().length]; + const r = await release([sha], { MOCK_PNPM_FAIL: "build" }); + assert.equal(r.code, 1, r.out); + assert.equal(currentSha(), prev); + assert.equal(kickstarts().length, k, "no service restarted"); + assert.equal(releaseBackups().length, b, "no backup, no migration"); + const rel = await latestRelease(); + assert.equal(rel.status, "failed"); + assert.match(rel.reason ?? "", /next build/); + assert.match(rel.logTail ?? "", /Failed to compile/); + }); + + test("Scenario: --check — здоровье текущего релиза", async () => { + const r = await release(["--check"]); + assert.equal(r.code, 0, r.out); + assert.match(r.out, new RegExp(`healthy ${currentSha()!.slice(0, 7)}`)); + }); +}); + +describe("Установка launchd без гонки", () => { + const install = (args: string[]) => { + const home = join(TMP, "home"); + mkdirSync(home, { recursive: true }); + return sh("install-launchd.sh", args, { ...scriptEnv(), HOME: home, PEPPA_HOME: join(home, ".peppa"), PEPPA_LAUNCHD_WAIT_SEC: "3", PEPPA_NODE: process.execPath }); + }; + + test("Scenario: Переустановка работающего агента", async () => { + // Loaded and slow to unload: `print` still finds it twice after bootout. + writeFileSync(join(LAUNCHD, "calls.log"), ""); + const r = await install(["web"]); + assert.equal(r.code, 0, r.out); + assert.doesNotMatch(r.out, /Bootstrap failed/); + const calls = readFileSync(join(LAUNCHD, "calls.log"), "utf8").trim().split("\n"); + const iOut = calls.findIndex((c) => c.startsWith("launchctl bootout")); + const iIn = calls.findIndex((c) => c.startsWith("launchctl bootstrap")); + assert.ok(iOut >= 0 && iIn > iOut, calls.join("\n")); + assert.equal(calls.slice(iOut + 1, iIn).filter((c) => c.startsWith("launchctl print")).length, 3, "waited until print no longer found it"); + const plist = readFileSync(join(LAUNCHD, "loaded/quest.telecom.peppa.web"), "utf8"); + assert.match(plist, new RegExp(`<key>PEPPA_ROOT</key><string>${ROOT}</string>`)); + assert.match(plist, /<key>KeepAlive<\/key><true\/>/); + }); + + test("Scenario: Слушатель релизов — запуск по очереди запросов", async () => { + const r = await install(["release"]); + assert.equal(r.code, 0, r.out); + const plist = readFileSync(join(LAUNCHD, "loaded/quest.telecom.peppa.release"), "utf8"); + assert.match(plist, /<key>QueueDirectories<\/key><array><string>.*\/\.peppa\/release-queue<\/string><\/array>/); + assert.match(plist, /scripts\/peppa-release\.sh<\/string>\s*<string>--queue<\/string>/); + assert.doesNotMatch(plist, /KeepAlive/); + }); +}); + +describe("Прод из релизного каталога", () => { + test("Scenario: Хук раннера переживает смену релиза — корень по пути current, не по релизу", () => { + // The wrappers' root lines, run as a bin inside the current release. + const wrapper = readFileSync(join(ROOT, "packages/runner/bin/peppa-hook"), "utf8"); + const rootLines = wrapper.split("\n").filter((l) => l.startsWith("_b=") || l.startsWith("PEPPA_ROOT=")); + assert.equal(rootLines.length, 2, wrapper); + const binDir = join(RELEASES, "releases", currentSha()!, "packages/runner/bin"); + mkdirSync(binDir, { recursive: true }); + writeFileSync(join(binDir, "probe"), `${rootLines.join("\n")}\necho "$PEPPA_ROOT"\n`); + const viaCurrent = join(RELEASES, "current/packages/runner/bin/probe"); + assert.equal(execFileSync("bash", [viaCurrent], { encoding: "utf8" }).trim(), join(RELEASES, "current")); + // ~/.local/bin/<bin> → ~/peppa/current/…: still current, not releases/<sha>. + const localBin = join(TMP, "local-bin"); + mkdirSync(localBin); + symlinkSync(viaCurrent, join(localBin, "probe")); + assert.equal(execFileSync("bash", [join(localBin, "probe")], { encoding: "utf8" }).trim(), join(RELEASES, "current")); + }); +}); diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index d729363e..b8053109 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -3,11 +3,16 @@ # quest.telecom.peppa.watchdog — session watchdog under caffeinate -i (no idle sleep) # quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`) # quest.telecom.peppa.bot — Telegram bot (TELEGRAM_BOT_TOKEN in .env) -# Usage: scripts/install-launchd.sh [watchdog] [web] [bot] (default: all) +# quest.telecom.peppa.release — Peppa's own prod releases (PEP-18): started by launchd while +# ~/.peppa/release-queue has requests (the PM's button) +# Prod runs from the release directory: ~/peppa/current/scripts/install-launchd.sh, so every +# path below (and PEPPA_ROOT for hooks and git config) is ~/peppa/current, not a release. +# Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [release] (default: all) # Remove: launchctl bootout gui/$(id -u)/<label> && rm ~/Library/LaunchAgents/<label>.plist set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" -mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa" +PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}" +mkdir -p "$HOME/Library/LaunchAgents" "$PEPPA_HOME" PATH_ENV="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" # Bot and watchdog run TypeScript straight from source with Node's type stripping (PEP-36): # pin the Node that was checked here, so launchd does not depend on what PATH finds later. @@ -15,6 +20,21 @@ NODE_BIN="${PEPPA_NODE:-$(PATH="$PATH_ENV" command -v node || true)}" [ -x "$NODE_BIN" ] || { echo "node not found (set PEPPA_NODE)" >&2; exit 1; } "$NODE_BIN" --import "$ROOT/scripts/lib/require-node.mjs" -e 0 || exit 1 +# `bootout` returns before launchd has unloaded the agent; a bootstrap right after it fails +# with "Bootstrap failed: 5: Input/output error". Wait until `print` no longer finds it. +wait_unloaded() { # label + local i tries=$(( ${PEPPA_LAUNCHD_WAIT_SEC:-10} * 5 )) + for (( i = 0; i < tries; i++ )); do + launchctl print "gui/$(id -u)/$1" >/dev/null 2>&1 || return 0 + sleep 0.2 + done + echo "warning: $1 is still loaded after ${PEPPA_LAUNCHD_WAIT_SEC:-10}s" >&2 +} + +# Extra plist keys for the next install_agent (default: start at login, restart on exit). +LIFECYCLE=' <key>RunAtLoad</key><true/> + <key>KeepAlive</key><true/>' + install_agent() { # label log workdir args... local label=$1 log=$2 workdir=$3; shift 3 local plist="$HOME/Library/LaunchAgents/$label.plist" args="" @@ -33,21 +53,22 @@ $args </array> <dict> <key>PATH</key><string>$PATH_ENV</string> <key>PEPPA_NODE</key><string>$NODE_BIN</string> + <key>PEPPA_ROOT</key><string>$ROOT</string> </dict> - <key>RunAtLoad</key><true/> - <key>KeepAlive</key><true/> - <key>StandardOutPath</key><string>$HOME/.peppa/$log</string> - <key>StandardErrorPath</key><string>$HOME/.peppa/$log</string> +$LIFECYCLE + <key>StandardOutPath</key><string>$PEPPA_HOME/$log</string> + <key>StandardErrorPath</key><string>$PEPPA_HOME/$log</string> </dict> </plist> PLIST - launchctl bootout "gui/$(id -u)/$label" 2>/dev/null || true - launchctl bootstrap "gui/$(id -u)" "$plist" - echo "installed $label (log: ~/.peppa/$log)" + launchctl bootout "gui/$(id -u)/$label" 2>/dev/null && wait_unloaded "$label" + # Still "5" (unloaded by something else meanwhile): one more try after a second. + launchctl bootstrap "gui/$(id -u)" "$plist" || { sleep 1; launchctl bootstrap "gui/$(id -u)" "$plist"; } + echo "installed $label (log: $PEPPA_HOME/$log)" } SERVICES=("$@") -[ ${#SERVICES[@]} -eq 0 ] && SERVICES=(watchdog web bot) +[ ${#SERVICES[@]} -eq 0 ] && SERVICES=(watchdog web bot release) for s in "${SERVICES[@]}"; do case "$s" in watchdog) @@ -58,6 +79,13 @@ for s in "${SERVICES[@]}"; do /bin/bash -c "set -a; . '$ROOT/.env'; set +a; exec '$ROOT/apps/web/node_modules/.bin/next' start -p 3100" ;; bot) install_agent quest.telecom.peppa.bot bot.log "$ROOT" "$ROOT/apps/bot/bin/peppa-bot" ;; + release) + mkdir -p "$PEPPA_HOME/release-queue" && chmod 700 "$PEPPA_HOME/release-queue" + LIFECYCLE=" <key>QueueDirectories</key><array><string>$PEPPA_HOME/release-queue</string></array>" + install_agent quest.telecom.peppa.release release.log "$HOME" \ + /bin/bash "$ROOT/scripts/peppa-release.sh" --queue + LIFECYCLE=' <key>RunAtLoad</key><true/> + <key>KeepAlive</key><true/>' ;; *) echo "unknown service $s" >&2; exit 1 ;; esac done diff --git a/scripts/peppa-release.sh b/scripts/peppa-release.sh new file mode 100755 index 00000000..40d79fb0 --- /dev/null +++ b/scripts/peppa-release.sh @@ -0,0 +1,227 @@ +#!/usr/bin/env bash +# Releases Peppa itself (PEP-18) from its own release directory, apart from the development +# checkout: +# ~/peppa/repo.git bare clone of peppa-bot/peppa +# ~/peppa/releases/<sha> git worktree at the commit (.env → ~/peppa/shared/.env) +# ~/peppa/current symlink to the release the services run (launchd, ~/.local/bin) +# +# Usage: +# peppa-release.sh <sha> release that commit: install → build → DB backup → +# migrate → switch current → kickstart → health; rollback +# to the previous release if it is not healthy +# peppa-release.sh --queue requests from ~/.peppa/release-queue (the PM's button; +# launchd agent quest.telecom.peppa.release) +# peppa-release.sh <sha> --no-restart everything up to the switch, no kickstart, no health +# and no reports (the first move of prod to ~/peppa) +# peppa-release.sh --check health of the current release (exit code) +# Every step is reported with `peppa release report` → releases table → PM messages. +set -uo pipefail + +RELEASES="${PEPPA_RELEASES_DIR:-$HOME/peppa}" +PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}" +QUEUE="${PEPPA_RELEASE_QUEUE:-$PEPPA_HOME/release-queue}" +REMOTE="${PEPPA_RELEASE_REMOTE:-https://git.telecom.quest/peppa-bot/peppa.git}" +KEY="${PEPPA_PLATFORM_KEY:-PEP}" +HEALTH_URL="${PEPPA_RELEASE_HEALTH_URL:-http://127.0.0.1:3100/api/health}" +HEALTH_TIMEOUT="${PEPPA_RELEASE_HEALTH_TIMEOUT:-120}" +HEALTH_INTERVAL="${PEPPA_RELEASE_HEALTH_INTERVAL:-3}" +SERVICES="${PEPPA_RELEASE_SERVICES:-web bot watchdog}" +KEEP="${PEPPA_RELEASE_KEEP:-5}" +NODE="${PEPPA_NODE:-node}" +CURRENT="$RELEASES/current" +mkdir -p "$RELEASES/releases" "$RELEASES/logs" "$RELEASES/requests" "$PEPPA_HOME/backups" + +say() { echo "[$(date '+%F %T')] $*" | tee -a "${LOG:-/dev/null}"; } +run() { "$@" >>"$LOG" 2>&1; } +git_repo() { git -C "$RELEASES/repo.git" "$@"; } +current_sha() { [ -L "$CURRENT" ] && basename "$(readlink "$CURRENT")" || true; } + +# The CLI that reports: the release being built once its deps are in, else the current one. +cli() { + local bin="${PEPPA_RELEASE_CLI:-}" + if [ -z "$bin" ]; then + if [ -n "${REL:-}" ] && [ -d "$REL/node_modules" ]; then bin="$REL/packages/cli/bin/peppa" + elif [ -e "$CURRENT/packages/cli/bin/peppa" ]; then bin="$CURRENT/packages/cli/bin/peppa" + else say "no peppa CLI to run: peppa $*"; return 1; fi + fi + (cd "$RELEASES" && "$bin" "$@") +} + +report() { # status [reason] + [ -n "${NO_RESTART:-}" ] && return 0 + local args=(release report "$KEY" --sha "$SHA" -s "$1") + [ -n "${PREV:-}" ] && args+=(--previous "$PREV") + [ -n "${2:-}" ] && args+=(--reason "$2") + [ "$1" != deploying ] && [ "$1" != healthy ] && args+=(--log-file "$LOG") + [ -s "${COMMITS:-}" ] && args+=(--commits-file "$COMMITS") + cli "${args[@]}" >>"$LOG" 2>&1 || say "report $1 failed (see log)" +} + +kickstart() { + local s ok=0 + for s in $SERVICES; do + say "kickstart quest.telecom.peppa.$s" + run launchctl kickstart -k "gui/$(id -u)/quest.telecom.peppa.$s" || ok=1 + done + return $ok +} + +# Healthy: /api/health answers 200 with this commit, the bot and the watchdog beat after `since`. +health() { # sha since-ms + local deadline=$(( $(date +%s) + HEALTH_TIMEOUT )) body why="" + while :; do + if body=$(curl -fsS --max-time 5 "$HEALTH_URL" 2>&1); then + why=$(printf '%s' "$body" | SHA="$1" SINCE="$2" WANT="$SERVICES" "$NODE" -e ' + let s = ""; process.stdin.on("data", (c) => (s += c)).on("end", () => { + const h = JSON.parse(s), sha = process.env.SHA, since = Number(process.env.SINCE); + const want = process.env.WANT.split(/\s+/).filter((x) => x === "bot" || x === "watchdog"); + if (!h.ok) return console.log("health: ok=false"); + if (!h.commit || !sha.startsWith(h.commit)) return console.log(`веб отдаёт коммит ${h.commit ?? "—"}`); + for (const w of want) { + const sv = (h.services ?? []).find((x) => x.service === w); + if (!sv?.lastHeartbeat || Date.parse(sv.lastHeartbeat) < since) return console.log(`${w}: нет свежего heartbeat`); + } + });' 2>&1) + [ -z "$why" ] && return 0 + else + why="веб не отвечает: ${body##*$'\n'}" + fi + [ "$(date +%s)" -ge "$deadline" ] && { HEALTH_WHY="$why"; return 1; } + sleep "$HEALTH_INTERVAL" + done +} + +now_ms() { "$NODE" -e 'console.log(Date.now())'; } + +switch_to() { # release dir + ln -sfn "$1" "$CURRENT" && [ "$(readlink "$CURRENT")" = "$1" ] +} + +# Not healthy after the switch: back to the previous release and restart it. +rollback() { # reason + local reason="$1" + if [ -z "$PREV" ] || [ ! -d "$RELEASES/releases/$PREV" ]; then + FINISHED=1; report failed "$reason; предыдущего релиза нет — откатывать некуда"; exit 1 + fi + say "rollback to $PREV: $reason" + switch_to "$RELEASES/releases/$PREV" + local since; since=$(now_ms) + kickstart + if health "$PREV" "$since"; then + FINISHED=1; report rolled_back "$reason (схема БД не откатывается; бэкап: ${BACKUP:-нет})"; exit 1 + fi + FINISHED=1; report failed "$reason; откат на ${PREV:0:7} тоже нездоров: $HEALTH_WHY"; exit 1 +} + +fail() { # reason — before the switch: prod untouched + say "failed: $1" + FINISHED=1; report failed "$1"; exit 1 +} + +on_exit() { + local code=$? + [ -n "${LOCKED:-}" ] && rm -rf "$RELEASES/.lock" + [ -z "${FINISHED:-}" ] && [ -n "${STARTED:-}" ] && report failed "скрипт релиза прервался (код $code)" +} + +lock() { + local waited=0 + until mkdir "$RELEASES/.lock" 2>/dev/null; do + local pid; pid=$(cat "$RELEASES/.lock/pid" 2>/dev/null || true) + if [ -n "$pid" ] && ! kill -0 "$pid" 2>/dev/null; then rm -rf "$RELEASES/.lock"; continue; fi + [ "$waited" -ge 3600 ] && { echo "another release holds $RELEASES/.lock" >&2; exit 1; } + sleep 5; waited=$((waited + 5)) + done + echo $$ > "$RELEASES/.lock/pid" + LOCKED=1 +} + +prune() { + local keep_dirs=("$REL" "$RELEASES/releases/${PREV:-none}") d n=0 + for d in $(ls -1td "$RELEASES"/releases/*/ 2>/dev/null); do + d="${d%/}"; n=$((n + 1)) + [[ " ${keep_dirs[*]} " == *" $d "* ]] && continue + [ "$n" -le "$KEEP" ] && continue + say "prune $(basename "$d")" + git_repo worktree remove --force "$d" >>"$LOG" 2>&1 || rm -rf "$d" + done + git_repo worktree prune >>"$LOG" 2>&1 + ls -1t "$PEPPA_HOME"/backups/release-*.db 2>/dev/null | tail -n +$((KEEP + 1)) | while read -r f; do rm -f "$f"; done +} + +release() { # sha + trap on_exit EXIT + lock + [[ "$1" =~ ^[0-9a-f]{7,40}$ ]] || { echo "not a commit sha: $1" >&2; exit 2; } + LOG="$RELEASES/logs/${1:0:12}-$(date +%Y%m%d%H%M%S).log" + if [ ! -d "$RELEASES/repo.git" ]; then + say "clone $REMOTE" + # Gitea over https: peppa-bot's token through git-credential-peppa, set in repo.git only. + local cred=(); [[ "$REMOTE" == http* ]] && cred=(-c credential.helper=peppa) + git ${cred[@]+"${cred[@]}"} clone -q --bare "$REMOTE" "$RELEASES/repo.git" >>"$LOG" 2>&1 || { echo "clone failed, see $LOG" >&2; exit 1; } + [[ "$REMOTE" == http* ]] && git_repo config credential.helper peppa + fi + git_repo fetch -q origin '+refs/heads/*:refs/heads/*' >>"$LOG" 2>&1 || say "fetch failed (using known commits)" + SHA=$(git_repo rev-parse --verify -q "$1^{commit}") || { say "commit $1 not found in $REMOTE"; exit 2; } + PREV=$(current_sha) + REL="$RELEASES/releases/$SHA" + COMMITS="$RELEASES/logs/${SHA:0:12}.commits" + if [ -n "$PREV" ] && git_repo cat-file -e "$PREV^{commit}" 2>/dev/null; then + git_repo log --format=%s "$PREV..$SHA" > "$COMMITS" + else + git_repo log -1 --format=%s "$SHA" > "$COMMITS" + fi + if [ "$PREV" = "$SHA" ]; then say "$SHA is already current"; FINISHED=1; exit 0; fi + STARTED=1 + say "release ${SHA:0:7} (current: ${PREV:-none}) log: $LOG" + report deploying + + if [ ! -d "$REL" ]; then + run git_repo worktree add -q --detach "$REL" "$SHA" || fail "git worktree не создан" + fi + [ -f "$RELEASES/shared/.env" ] || fail "нет $RELEASES/shared/.env" + ln -sfn "$RELEASES/shared/.env" "$REL/.env" + say "pnpm install" + (cd "$REL" && run pnpm install --frozen-lockfile) || fail "pnpm install упал" + say "build web" + (cd "$REL" && run pnpm --filter @peppa/web build) || fail "сборка веба (next build) упала" + BACKUP="$PEPPA_HOME/backups/release-$(date +%Y%m%d%H%M%S)-${SHA:0:7}.db" + say "backup → $BACKUP" + cli db backup "$BACKUP" >>"$LOG" 2>&1 || fail "бэкап БД не сделан — миграции не применялись" + say "migrate" + cli db migrate >>"$LOG" 2>&1 || fail "миграция БД упала (бэкап: $BACKUP)" + + say "switch current → ${SHA:0:7}" + switch_to "$REL" || fail "симлинк current не переключился" + if [ -n "${NO_RESTART:-}" ]; then say "switched without restart"; FINISHED=1; exit 0; fi + local since; since=$(now_ms) + kickstart || rollback "launchctl kickstart не прошёл" + say "health (${HEALTH_TIMEOUT}s)" + health "$SHA" "$since" || rollback "релиз нездоров: $HEALTH_WHY" + cli status >>"$LOG" 2>&1 || true + FINISHED=1 + report healthy + say "healthy ${SHA:0:7}" + prune +} + +case "${1:-}" in + --queue) + # launchd starts this while the queue has files; each request is moved out before it runs. + for f in "$QUEUE"/*.json; do + [ -e "$f" ] || continue + done_f="$RELEASES/requests/$(date +%Y%m%d%H%M%S)-$(basename "$f")" + mv "$f" "$done_f" || continue + sha=$("$NODE" -e 'try { const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); if (/^[0-9a-f]{7,40}$/.test(r.sha)) console.log(r.sha) } catch {}' "$done_f") + if [ -z "$sha" ]; then echo "[$(date '+%F %T')] bad request $(basename "$f") — skipped"; continue; fi + echo "[$(date '+%F %T')] request $(basename "$f"): $sha" + ( release "$sha" ) || echo "[$(date '+%F %T')] release $sha failed" + done ;; + --check) + SHA=$(current_sha); [ -n "$SHA" ] || { echo "no $CURRENT" >&2; exit 1; } + if health "$SHA" 0; then echo "healthy ${SHA:0:7}"; else echo "unhealthy ${SHA:0:7}: $HEALTH_WHY"; exit 1; fi ;; + ""|-h|--help) sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//'; [ -n "${1:-}" ] ;; + *) + [ "${2:-}" = "--no-restart" ] && NO_RESTART=1 + ( release "$1" ) ;; +esac -- 2.45.2 From 969ad886a8eb0e880bd64f0a2d8ad8980946bf9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 18:02:16 +0500 Subject: [PATCH 026/536] PEP-18: archive OpenSpec change pep-18-peppa-prod Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../2026-11-13-pep-18-peppa-prod}/design.md | 0 .../2026-11-13-pep-18-peppa-prod}/proposal.md | 0 .../specs/platform-release/spec.md | 0 .../2026-11-13-pep-18-peppa-prod}/tasks.md | 0 openspec/specs/platform-release/spec.md | 73 +++++++++++++++++++ 5 files changed, 73 insertions(+) rename openspec/changes/{pep-18-peppa-prod => archive/2026-11-13-pep-18-peppa-prod}/design.md (100%) rename openspec/changes/{pep-18-peppa-prod => archive/2026-11-13-pep-18-peppa-prod}/proposal.md (100%) rename openspec/changes/{pep-18-peppa-prod => archive/2026-11-13-pep-18-peppa-prod}/specs/platform-release/spec.md (100%) rename openspec/changes/{pep-18-peppa-prod => archive/2026-11-13-pep-18-peppa-prod}/tasks.md (100%) create mode 100644 openspec/specs/platform-release/spec.md diff --git a/openspec/changes/pep-18-peppa-prod/design.md b/openspec/changes/archive/2026-11-13-pep-18-peppa-prod/design.md similarity index 100% rename from openspec/changes/pep-18-peppa-prod/design.md rename to openspec/changes/archive/2026-11-13-pep-18-peppa-prod/design.md diff --git a/openspec/changes/pep-18-peppa-prod/proposal.md b/openspec/changes/archive/2026-11-13-pep-18-peppa-prod/proposal.md similarity index 100% rename from openspec/changes/pep-18-peppa-prod/proposal.md rename to openspec/changes/archive/2026-11-13-pep-18-peppa-prod/proposal.md diff --git a/openspec/changes/pep-18-peppa-prod/specs/platform-release/spec.md b/openspec/changes/archive/2026-11-13-pep-18-peppa-prod/specs/platform-release/spec.md similarity index 100% rename from openspec/changes/pep-18-peppa-prod/specs/platform-release/spec.md rename to openspec/changes/archive/2026-11-13-pep-18-peppa-prod/specs/platform-release/spec.md diff --git a/openspec/changes/pep-18-peppa-prod/tasks.md b/openspec/changes/archive/2026-11-13-pep-18-peppa-prod/tasks.md similarity index 100% rename from openspec/changes/pep-18-peppa-prod/tasks.md rename to openspec/changes/archive/2026-11-13-pep-18-peppa-prod/tasks.md diff --git a/openspec/specs/platform-release/spec.md b/openspec/specs/platform-release/spec.md new file mode 100644 index 00000000..0d8fcaa5 --- /dev/null +++ b/openspec/specs/platform-release/spec.md @@ -0,0 +1,73 @@ +# platform-release Specification + +## Purpose +Определяет, как выкатывается сама Пеппа: из отдельного релизного каталога, по кнопке PM, с бэкапом базы, проверкой здоровья и автооткатом. + +## Requirements + +### Requirement: Прод из релизного каталога +Сервисы Пеппы (веб, бот, вачдог) SHALL запускаться из `~/peppa/current` — симлинка на релиз `~/peppa/releases/<sha>`, отдельный от рабочей копии разработки; пути в хуках раннеров и git-настройках проектов SHALL указывать на `current`, а не на конкретный релиз. + +#### Scenario: Ветка в рабочей копии не попадает в прод +- **GIVEN** в проде релиз «a1b2c3d», а в рабочей копии разработки открыта ветка «task/PEP-99» +- **WHEN** вачдог перезапускается +- **THEN** вачдог работает на коде «a1b2c3d» + +#### Scenario: Хук раннера переживает смену релиза +- **GIVEN** раннер запущен на релизе «a1b2c3d» +- **WHEN** выкачен релиз «e4f5a6b» и старые релизы удалены +- **THEN** хуки раннера по-прежнему вызываются через `~/peppa/current` + +### Requirement: Деплой Пеппы по кнопке PM +После зелёных проверок `main` Пеппы PM SHALL получать предложение «🚀 Выкатить в прод»; кнопка в вебе, Telegram, MCP или CLI SHALL ставить запрос хостовому слушателю, который выкатывает этот коммит. + +#### Scenario: Зелёный main — предложение PM +- **GIVEN** все проверки коммита «e4f5a6b» ветки main Пеппы прошли +- **WHEN** Пеппа получает последний зелёный отчёт CI +- **THEN** PM получает «✅ Peppa: main зелёный — e4f5a6b. Выкатить в прод?» с кнопкой «🚀 Выкатить в прод» + +#### Scenario: Кнопка ставит запрос слушателю +- **GIVEN** предложение выкатить «e4f5a6b» +- **WHEN** PM нажимает «🚀 Выкатить в прод» +- **THEN** появляется релиз прода «e4f5a6b» в статусе «deploying» с автором PM +- **AND** в очереди слушателя лежит запрос на «e4f5a6b» + +#### Scenario: Красный main не выкатывается +- **GIVEN** проверка «test» коммита main «e4f5a6b» упала +- **WHEN** PM вызывает «Выкатить в прод» для Пеппы +- **THEN** PM видит «main без зелёных проверок — выкатывать нечего», запроса нет + +#### Scenario: Второй запрос во время деплоя +- **GIVEN** релиз прода Пеппы «e4f5a6b» выкатывается +- **WHEN** PM снова нажимает «Выкатить в прод» +- **THEN** PM видит «прод уже выкатывается (e4f5a6b)» + +### Requirement: Релиз с бэкапом и автооткатом +Скрипт релиза SHALL собрать релиз до остановки сервисов, сделать проверенную копию базы до миграций, переключить `current`, перезапустить сервисы и проверить здоровье; при провале SHALL вернуть предыдущий релиз и сообщить PM причину. + +#### Scenario: Успешный релиз +- **GIVEN** в проде релиз «a1b2c3d» +- **WHEN** слушатель выкатывает «e4f5a6b», и после перезапуска веб отдаёт коммит «e4f5a6b», а бот и вачдог шлют heartbeat +- **THEN** `current` указывает на «e4f5a6b», релиз «healthy» со списком задач из коммитов +- **AND** перед миграцией в `~/.peppa/backups` появилась проверенная копия базы +- **AND** PM получает «🚀 Peppa в проде: e4f5a6b» + +#### Scenario: Нездоровый релиз откатывается +- **GIVEN** в проде релиз «a1b2c3d» +- **WHEN** после переключения на «e4f5a6b» веб не отвечает здоровым за отведённое время +- **THEN** `current` снова указывает на «a1b2c3d», сервисы перезапущены +- **AND** релиз «rolled_back» с причиной, PM получает «❌ … возвращён a1b2c3d» + +#### Scenario: Сборка упала — прод не тронут +- **GIVEN** в проде релиз «a1b2c3d» +- **WHEN** `next build` релиза «e4f5a6b» падает +- **THEN** сервисы не перезапускаются, миграции не применяются, `current` указывает на «a1b2c3d» +- **AND** релиз «failed» с хвостом журнала + +### Requirement: Установка launchd без гонки +`install-launchd.sh` SHALL дожидаться фактической выгрузки агента после `bootout` перед `bootstrap`. + +#### Scenario: Переустановка работающего агента +- **GIVEN** агент `quest.telecom.peppa.web` загружен, и launchd выгружает его не сразу +- **WHEN** запускается `install-launchd.sh web` +- **THEN** `bootstrap` вызывается только после того, как `launchctl print` перестал находить агент, и установка проходит без «Bootstrap failed: 5» -- 2.45.2 From 52d861bbc7988cb39c8838bd26462df6ef22075a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 22:52:53 +0500 Subject: [PATCH 027/536] =?UTF-8?q?UI:=20board=20in=20one=20row,=20project?= =?UTF-8?q?=20panel=20moved=20into=20a=20=E2=8B=AF=20settings=20dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/app/(app)/p/[key]/page.tsx | 4 +++- apps/web/components/Board.tsx | 2 +- apps/web/components/SettingsDialog.tsx | 33 ++++++++++++++++++++++++++ apps/web/components/Workspace.tsx | 7 +++--- 4 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 apps/web/components/SettingsDialog.tsx diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index f2351ba8..1f808ac7 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -11,6 +11,7 @@ import { IncidentsSection } from "@/components/Incidents"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input, Textarea } from "@/components/ui/input"; +import { SettingsDialog } from "@/components/SettingsDialog"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; @@ -162,7 +163,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr ); return ( - <Workspace aside={aside}> + <Workspace aside={null} wide> <AutoRefresh /> <Flash error={error} /> {created && !error && ( @@ -174,6 +175,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr </Notice> )} <PageHeader + actions={<SettingsDialog title="Настройки проекта">{aside}</SettingsDialog>} crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">Проекты</a>} title={ <> diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx index 32b17faa..3db65ab7 100644 --- a/apps/web/components/Board.tsx +++ b/apps/web/components/Board.tsx @@ -45,7 +45,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) { start(() => moveTaskCard(f)); }; return ( - <div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-2 min-[1600px]:grid-cols-4", pending && "pointer-events-none opacity-60")}> + <div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}> {COLUMNS.map((c) => { const list = cards.filter((x) => x.column === c.id); return ( diff --git a/apps/web/components/SettingsDialog.tsx b/apps/web/components/SettingsDialog.tsx new file mode 100644 index 00000000..132f3e95 --- /dev/null +++ b/apps/web/components/SettingsDialog.tsx @@ -0,0 +1,33 @@ +"use client"; + +import { useRef, type ReactNode } from "react"; +import { Ellipsis, X } from "lucide-react"; +import { Button } from "@/components/ui/button"; + +/** "⋯" button that opens a side dialog (native <dialog>) with page settings rendered on the server. */ +export function SettingsDialog({ title, children }: { title: string; children: ReactNode }) { + const ref = useRef<HTMLDialogElement>(null); + return ( + <> + <Button variant="ghost" size="icon" aria-label={title} title={title} onClick={() => ref.current?.showModal()}> + <Ellipsis /> + </Button> + <dialog + ref={ref} + aria-label={title} + onClick={(e) => e.target === ref.current && ref.current.close()} + className="m-0 ml-auto h-dvh max-h-dvh w-[400px] max-w-full border-l bg-sidebar p-0 text-foreground backdrop:bg-black/50" + > + <div className="flex flex-col gap-4 px-4 py-5"> + <div className="flex items-center gap-2"> + <h2 className="m-0 text-[15px] font-semibold">{title}</h2> + <Button variant="ghost" size="icon" className="ml-auto" aria-label="Закрыть" onClick={() => ref.current?.close()}> + <X /> + </Button> + </div> + {children} + </div> + </dialog> + </> + ); +} diff --git a/apps/web/components/Workspace.tsx b/apps/web/components/Workspace.tsx index 30bb2a48..2cfb6220 100644 --- a/apps/web/components/Workspace.tsx +++ b/apps/web/components/Workspace.tsx @@ -6,14 +6,15 @@ import { cn } from "@/lib/utils"; /** * Centre + right panel of the console (PEP-38). The page decides what the right panel shows; * without `aside` it gets the default activity panel, `aside={null}` hides it. + * `wide` lets the centre grow past the reading width (the board page, with its panel moved into a dialog). * Below xl the panel goes under the page content (`asideWideOnly`: shown on xl only), the footer is always last. */ -export function Workspace({ children, aside, asideWideOnly = false }: { children: ReactNode; aside?: ReactNode; asideWideOnly?: boolean }) { +export function Workspace({ children, aside, asideWideOnly = false, wide = false }: { children: ReactNode; aside?: ReactNode; asideWideOnly?: boolean; wide?: boolean }) { const panel = aside === undefined ? <ActivityAside /> : aside; return ( - <div className="grid flex-1 xl:grid-cols-[minmax(0,1fr)_360px] xl:grid-rows-[1fr_auto]"> + <div className={cn("grid flex-1", panel && "xl:grid-cols-[minmax(0,1fr)_360px] xl:grid-rows-[1fr_auto]")}> <main className="min-w-0 px-4 py-5 md:px-8 md:py-7"> - <div className="mx-auto w-full max-w-5xl">{children}</div> + <div className={cn("mx-auto w-full", wide ? "max-w-[1600px]" : "max-w-5xl")}>{children}</div> </main> {panel && ( <aside aria-label="Панель" className={cn(asideWideOnly && "max-xl:hidden", "min-w-0 border-t bg-sidebar/60 px-4 py-5 xl:sticky xl:top-0 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:h-dvh xl:overflow-y-auto xl:border-t-0 xl:border-l")}> -- 2.45.2 From c4952b20114ee7a575e150ec0e337d6ccd932b8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 22:56:02 +0500 Subject: [PATCH 028/536] Pre-launch live mode: PEPPA_WEB_MODE=dev runs next dev (HMR) from the working copy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/next.config.ts | 2 ++ scripts/install-launchd.sh | 10 ++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index a686de13..8f1639b1 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -14,6 +14,8 @@ const version = (JSON.parse(readFileSync(new URL("../../package.json", import.me const config: NextConfig = { // Workspace packages ship TypeScript sources. + // `next dev` behind Traefik (pre-launch live mode): let the public host load dev assets and HMR. + allowedDevOrigins: ["peppa.telecom.quest"], transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], env: { NEXT_PUBLIC_PEPPA_VERSION: version, diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index b8053109..763f7b40 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -1,17 +1,23 @@ #!/usr/bin/env bash # Installs Peppa's launchd agents (start at login, restart on crash): # quest.telecom.peppa.watchdog — session watchdog under caffeinate -i (no idle sleep) -# quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`) +# quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`); +# PEPPA_WEB_MODE=dev runs `next dev` instead (HMR: edits in this +# checkout go live without build or release — the pre-launch setup) # quest.telecom.peppa.bot — Telegram bot (TELEGRAM_BOT_TOKEN in .env) # quest.telecom.peppa.release — Peppa's own prod releases (PEP-18): started by launchd while # ~/.peppa/release-queue has requests (the PM's button) # Prod runs from the release directory: ~/peppa/current/scripts/install-launchd.sh, so every # path below (and PEPPA_ROOT for hooks and git config) is ~/peppa/current, not a release. +# Pre-launch (everything is dev): PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot +# from the working copy — no release agent, so nothing replaces what this checkout serves. # Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [release] (default: all) # Remove: launchctl bootout gui/$(id -u)/<label> && rm ~/Library/LaunchAgents/<label>.plist set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}" +WEB_MODE="${PEPPA_WEB_MODE:-start}" +case "$WEB_MODE" in start|dev) ;; *) echo "PEPPA_WEB_MODE must be start or dev" >&2; exit 1 ;; esac mkdir -p "$HOME/Library/LaunchAgents" "$PEPPA_HOME" PATH_ENV="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" # Bot and watchdog run TypeScript straight from source with Node's type stripping (PEP-36): @@ -76,7 +82,7 @@ for s in "${SERVICES[@]}"; do /usr/bin/caffeinate -i "$ROOT/packages/cli/bin/peppa" watchdog ;; web) install_agent quest.telecom.peppa.web web.log "$ROOT/apps/web" \ - /bin/bash -c "set -a; . '$ROOT/.env'; set +a; exec '$ROOT/apps/web/node_modules/.bin/next' start -p 3100" ;; + /bin/bash -c "set -a; . '$ROOT/.env'; set +a; exec '$ROOT/apps/web/node_modules/.bin/next' $WEB_MODE -p 3100" ;; bot) install_agent quest.telecom.peppa.bot bot.log "$ROOT" "$ROOT/apps/bot/bin/peppa-bot" ;; release) -- 2.45.2 From ae9f2861ae3857657d260a83fac632bcab0a7b40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 23:00:11 +0500 Subject: [PATCH 029/536] AGENTS: pre-launch live mode (next dev from the working copy) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e368d42a..0ff1dc39 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Текущее состояние и порядок работ: `docs/HANDOFF.md`. ## Структура -- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. Прод — только через релиз (PEP-18, ниже), не `next build` в рабочей копии +- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже) - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36) - `packages/shared` — env, ключи задач (`PEP-42`) @@ -34,7 +34,8 @@ - **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем -- **Прод Пеппы (PEP-18)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/<sha>` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh <sha>`: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` +- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже +- **Прод Пеппы (PEP-18, для будущего официального прода)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/<sha>` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh <sha>`: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh ## Внешние зависимости — через моки -- 2.45.2 From 5df52468c3fdac17156a8093435fb12446c3fc2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 23:21:32 +0500 Subject: [PATCH 030/536] =?UTF-8?q?UI:=20project=20tabs=20(=D0=94=D0=BE?= =?UTF-8?q?=D1=81=D0=BA=D0=B0=20=C2=B7=20=D0=A0=D0=B5=D0=BB=D0=B8=D0=B7?= =?UTF-8?q?=D1=8B=20=C2=B7=20=D0=91=D0=B0=D0=B3=D0=B8=20=C2=B7=20=D0=A1?= =?UTF-8?q?=D0=B5=D1=81=D1=81=D0=B8=D0=B8),=20=C2=AB+=20=D0=A1=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B8=C2=BB=20dialog,=20goals=20into=20=E2=8B=AF=20setti?= =?UTF-8?q?ngs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/app/(app)/p/[key]/page.tsx | 241 ++++++++++++++----------- apps/web/components/SettingsDialog.tsx | 20 +- 2 files changed, 151 insertions(+), 110 deletions(-) diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 1f808ac7..a4125674 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,19 +1,20 @@ import { notFound } from "next/navigation"; -import { ExternalLink, Plus, Rocket, Target } from "lucide-react"; +import { ExternalLink, Plus, Rocket } from "lucide-react"; import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, type Release } from "@peppa/runner"; import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Board, type Card } from "@/components/Board"; import { Hidden, SessionCard } from "@/components/cards"; -import { Disclosure, Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common"; +import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common"; import { IncidentsSection } from "@/components/Incidents"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; -import { Input, Textarea } from "@/components/ui/input"; +import { Input, NativeSelect, Textarea } from "@/components/ui/input"; import { SettingsDialog } from "@/components/SettingsDialog"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; +import { cn } from "@/lib/utils"; import { db } from "@/lib/db"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; @@ -26,6 +27,13 @@ const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | removed: { label: "удалён", tone: "muted" }, }; +const TABS = [ + { id: "board", label: "Доска" }, + { id: "releases", label: "Релизы" }, + { id: "bugs", label: "Баги" }, + { id: "sessions", label: "Сессии" }, +] as const; + function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) { return ( <div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2"> @@ -46,10 +54,11 @@ function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) { ); } -export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) { +export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string }> }) { const user = await requireUser(); const { key } = await params; - const { error, created } = await searchParams; + const { error, created, tab: tabParam } = await searchParams; + const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board"; const p = await projectForUserByKey(user.id, key).catch(() => null); if (!p) notFound(); const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([ @@ -71,8 +80,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase()); const missingAccess = team.members.some((m) => noRepoAccess(m.login)); const isOwner = p.ownerId === user.id; - const back = `/p/${p.key}`; - const groups = [...goals.map((g) => ({ goal: g })), { goal: null }]; + const back = tab === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${tab}`; const goalTitle = new Map(goals.map((g) => [g.id, g.title])); const cards: Card[] = tasks.map((t) => ({ key: `${p.key}-${t.number}`, @@ -159,9 +167,39 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr )} {isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>} </PanelSection> + + <PanelSection title="Цели" count={goals.length}> + <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm"> + {goals.map((g) => ( + <li key={g.id} className="px-2">◎ {g.title}</li> + ))} + </ul> + <form action={addGoal} className="flex flex-col gap-2"> + <Hidden fields={{ projectId: p.id, back }} /> + <Input name="title" required placeholder="Новая цель" aria-label="Название цели" className="h-8" /> + <Textarea name="description" rows={2} placeholder="Зачем и какой результат" aria-label="Описание цели" /> + <Button size="sm" className="self-start">Создать цель</Button> + </form> + </PanelSection> </div> ); + const newTask = ( + <form action={addTask} className="flex flex-col gap-2"> + <Hidden fields={{ projectId: p.id, back }} /> + <Input name="title" required placeholder="Что сделать" aria-label="Название стори" /> + <Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label="Описание стори" /> + <NativeSelect name="goalId" aria-label="Цель" defaultValue=""> + <option value="">Без цели</option> + {goals.map((g) => ( + <option key={g.id} value={g.id}>◎ {g.title}</option> + ))} + </NativeSelect> + <Button variant="default" size="sm" className="self-start">Создать стори</Button> + </form> + ); + const tabCount: Partial<Record<(typeof TABS)[number]["id"], number>> = { board: tasks.length, bugs: incidents.length, sessions: sessions.length }; + return ( <Workspace aside={null} wide> <AutoRefresh /> @@ -175,7 +213,14 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr </Notice> )} <PageHeader - actions={<SettingsDialog title="Настройки проекта">{aside}</SettingsDialog>} + actions={ + <> + <SettingsDialog title="Новая стори" trigger={<><Plus />Стори</>}> + {newTask} + </SettingsDialog> + <SettingsDialog title="Настройки проекта">{aside}</SettingsDialog> + </> + } crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">Проекты</a>} title={ <> @@ -186,109 +231,95 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr <a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)} </PageHeader> - <Board cards={cards} back={back} /> - - <div className="mt-3 grid gap-2 md:grid-cols-2"> - {groups.map(({ goal }) => ( - <Disclosure - key={goal?.id ?? "none"} - summary={ - <span className="flex min-w-0 items-center gap-1.5"> - <Plus className="size-3.5 text-primary" /> - Задача - <span className="truncate text-muted-foreground">{goal ? `· ◎ ${goal.title}` : "без цели"}</span> - </span> - } + <nav aria-label="Разделы проекта" className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b"> + {TABS.map((t) => ( + <a + key={t.id} + href={t.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${t.id}`} + aria-current={tab === t.id ? "page" : undefined} + className={cn( + "-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline", + tab === t.id ? "border-primary text-foreground" : "border-transparent", + )} > - <form action={addTask} className="flex flex-col gap-2"> - <Hidden fields={{ projectId: p.id, back, goalId: goal?.id }} /> - <Input name="title" required placeholder="Что сделать" aria-label="Название задачи" /> - <Textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" /> - <Button variant="default" size="sm" className="self-start">Создать задачу</Button> - </form> - </Disclosure> + {t.label} + {!!tabCount[t.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[t.id]}</span>} + </a> ))} - <Disclosure - summary={ - <span className="flex items-center gap-1.5"> - <Target className="size-3.5 text-primary" /> - Цель - </span> - } - > - <form action={addGoal} className="flex flex-col gap-2"> - <Hidden fields={{ projectId: p.id, back }} /> - <Input name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" /> - <Textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" /> - <Button variant="default" size="sm" className="self-start">Создать цель</Button> - </form> - </Disclosure> - </div> + </nav> - <Section title="Релизы"> - <div className="flex flex-col gap-2 sm:flex-row"> - <EnvLine name="staging" r={current.staging} /> - <EnvLine name="прод" r={current.prod} /> - </div> - {prodCandidate && prodCandidate !== current.prod?.sha && ( - <form action={deployProdAction}> - <Hidden fields={{ projectKey: p.key, back }} /> - <Button variant="default" size="sm"> - <Rocket /> - Выкатить в прод {prodCandidate.slice(0, 7)} - </Button> - </form> - )} - {releases.length === 0 ? ( - <Empty> - Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»). - </Empty> - ) : ( - <div className="overflow-x-auto rounded-lg border"> - <table className="w-full border-collapse text-sm"> - <tbody> - {releases.map((r) => ( - <tr key={r.id} className="border-b last:border-0"> - <td className="px-3 py-2 whitespace-nowrap"> - {r.env} - {r.prNumber ? ` #${r.prNumber}` : ""} - </td> - <td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td> - <td className="px-3 py-2"> - <Badge variant={RELEASE_STATUS[r.status].tone}>{RELEASE_STATUS[r.status].label}</Badge> - {r.reason && <span className="ml-1.5 text-muted-foreground">{r.reason}</span>} - </td> - <td className="px-3 py-2"> - {r.tasks.map((t) => ( - <Key key={t} href={`/t/${t}`} className="mr-1.5">{t}</Key> - ))} - </td> - <td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground"> - {r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })} - </td> - </tr> - ))} - </tbody> - </table> + {tab === "board" && <Board cards={cards} back={back} />} + + {tab === "releases" && ( + <Section title="Релизы"> + <div className="flex flex-col gap-2 sm:flex-row"> + <EnvLine name="staging" r={current.staging} /> + <EnvLine name="прод" r={current.prod} /> </div> - )} - </Section> + {prodCandidate && prodCandidate !== current.prod?.sha && ( + <form action={deployProdAction}> + <Hidden fields={{ projectKey: p.key, back }} /> + <Button variant="default" size="sm"> + <Rocket /> + Выкатить в прод {prodCandidate.slice(0, 7)} + </Button> + </form> + )} + {releases.length === 0 ? ( + <Empty> + Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»). + </Empty> + ) : ( + <div className="overflow-x-auto rounded-lg border"> + <table className="w-full border-collapse text-sm"> + <tbody> + {releases.map((r) => ( + <tr key={r.id} className="border-b last:border-0"> + <td className="px-3 py-2 whitespace-nowrap"> + {r.env} + {r.prNumber ? ` #${r.prNumber}` : ""} + </td> + <td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td> + <td className="px-3 py-2"> + <Badge variant={RELEASE_STATUS[r.status].tone}>{RELEASE_STATUS[r.status].label}</Badge> + {r.reason && <span className="ml-1.5 text-muted-foreground">{r.reason}</span>} + </td> + <td className="px-3 py-2"> + {r.tasks.map((t) => ( + <Key key={t} href={`/t/${t}`} className="mr-1.5">{t}</Key> + ))} + </td> + <td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground"> + {r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })} + </td> + </tr> + ))} + </tbody> + </table> + </div> + )} + </Section> + )} - <IncidentsSection - projectId={p.id} - projectKey={p.key} - back={back} - isOwner={isOwner} - settings={incidentSettings} - sources={sources} - incidents={incidents} - taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} - webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null} - /> + {tab === "bugs" && ( + <IncidentsSection + projectId={p.id} + projectKey={p.key} + back={back} + isOwner={isOwner} + settings={incidentSettings} + sources={sources} + incidents={incidents} + taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} + webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null} + /> + )} - <Section title="Сессии"> - {sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} - </Section> + {tab === "sessions" && ( + <Section title="Сессии"> + {sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)} + </Section> + )} </Workspace> ); } diff --git a/apps/web/components/SettingsDialog.tsx b/apps/web/components/SettingsDialog.tsx index 132f3e95..da1fc9c3 100644 --- a/apps/web/components/SettingsDialog.tsx +++ b/apps/web/components/SettingsDialog.tsx @@ -4,14 +4,24 @@ import { useRef, type ReactNode } from "react"; import { Ellipsis, X } from "lucide-react"; import { Button } from "@/components/ui/button"; -/** "⋯" button that opens a side dialog (native <dialog>) with page settings rendered on the server. */ -export function SettingsDialog({ title, children }: { title: string; children: ReactNode }) { +/** + * Button that opens a side dialog (native <dialog>) with content rendered on the server. + * Default trigger is "⋯" (page settings); pass `trigger` for a labelled button such as "+ Задача". + */ +export function SettingsDialog({ title, trigger, children }: { title: string; trigger?: ReactNode; children: ReactNode }) { const ref = useRef<HTMLDialogElement>(null); + const open = () => ref.current?.showModal(); return ( <> - <Button variant="ghost" size="icon" aria-label={title} title={title} onClick={() => ref.current?.showModal()}> - <Ellipsis /> - </Button> + {trigger ? ( + <Button size="sm" onClick={open}> + {trigger} + </Button> + ) : ( + <Button variant="ghost" size="icon" aria-label={title} title={title} onClick={open}> + <Ellipsis /> + </Button> + )} <dialog ref={ref} aria-label={title} -- 2.45.2 From 2a276d601e8f268b2a8913a4bdc68f8a2f5fd9cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 23:36:32 +0500 Subject: [PATCH 031/536] Fix dev reload loop: forward only browser errors to the terminal Forwarded browser logs are written to .next/dev/logs; the watcher treated that as a change and the page reloaded in a loop behind peppa.telecom.quest (next dev, pre-launch live mode). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/next.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 8f1639b1..7b95f44a 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -16,6 +16,9 @@ const config: NextConfig = { // Workspace packages ship TypeScript sources. // `next dev` behind Traefik (pre-launch live mode): let the public host load dev assets and HMR. allowedDevOrigins: ["peppa.telecom.quest"], + // Forwarded browser logs land in .next/dev/logs; the watcher picked that up as a change and the + // page reloaded in a loop (every reload logs again). Errors still reach the terminal. + logging: { browserToTerminal: "error" }, transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], env: { NEXT_PUBLIC_PEPPA_VERSION: version, -- 2.45.2 From 847962d80e755f25343582af1f0e00c8d240c89d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Fri, 13 Nov 2026 23:37:23 +0500 Subject: [PATCH 032/536] CI rerun (toolcache race) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> -- 2.45.2 From b5170723629b4f87d4cc2b4c1b35c409768e07de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Sat, 14 Nov 2026 00:44:55 +0500 Subject: [PATCH 033/536] =?UTF-8?q?UI:=20stories=20only=20=E2=80=94=20goal?= =?UTF-8?q?s=20removed=20from=20the=20web=20(project=20page,=20board=20car?= =?UTF-8?q?ds,=20task=20page)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Goals stay in the DB and MCP for now (agent context, Bugsink); PEP-66 turns them into epic labels. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/app/(app)/actions.ts | 13 +------------ apps/web/app/(app)/p/[key]/page.tsx | 28 +++------------------------- apps/web/app/(app)/t/[key]/page.tsx | 4 ---- apps/web/components/Board.tsx | 4 +--- apps/web/lib/queries.ts | 5 ++--- 5 files changed, 7 insertions(+), 47 deletions(-) diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 2aca86d1..2e57b35b 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -1,7 +1,6 @@ "use server"; import { - createGoal, createTask, getQuestion, getSession, @@ -68,22 +67,12 @@ export async function answerQuestion(f: FormData) { }); } -export async function addGoal(f: FormData) { - const user = await requireUser(); - await attempt(f, async () => { - const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); - if (!str(f, "title")) throw new PeppaError("Нужно название цели"); - await createGoal(db, p.id, str(f, "title"), str(f, "description") || undefined); - }); -} - export async function addTask(f: FormData) { const user = await requireUser(); await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); if (!str(f, "title")) throw new PeppaError("Нужно название задачи"); - const goalId = str(f, "goalId") ? Number(str(f, "goalId")) : undefined; - const ref = await createTask(db, { projectId: p.id, goalId, title: str(f, "title"), description: str(f, "description") || undefined }); + const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined }); return `/t/${ref.key}`; }); } diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index a4125674..51a33231 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -10,14 +10,14 @@ import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/com import { IncidentsSection } from "@/components/Incidents"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; -import { Input, NativeSelect, Textarea } from "@/components/ui/input"; +import { Input, Textarea } from "@/components/ui/input"; import { SettingsDialog } from "@/components/SettingsDialog"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { cn } from "@/lib/utils"; import { db } from "@/lib/db"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; -import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; +import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = { deploying: { label: "выкатывается", tone: "info" }, @@ -61,7 +61,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board"; const p = await projectForUserByKey(user.id, key).catch(() => null); if (!p) notFound(); - const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([ + const [{ tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([ board(p.id), projectSessions(p.id), listMembers(db, p), @@ -81,13 +81,11 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const missingAccess = team.members.some((m) => noRepoAccess(m.login)); const isOwner = p.ownerId === user.id; const back = tab === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${tab}`; - const goalTitle = new Map(goals.map((g) => [g.id, g.title])); const cards: Card[] = tasks.map((t) => ({ key: `${p.key}-${t.number}`, title: t.title, status: t.status, column: columnOf(t.status), - goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null, })); const aside = ( @@ -167,20 +165,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr )} {isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>} </PanelSection> - - <PanelSection title="Цели" count={goals.length}> - <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm"> - {goals.map((g) => ( - <li key={g.id} className="px-2">◎ {g.title}</li> - ))} - </ul> - <form action={addGoal} className="flex flex-col gap-2"> - <Hidden fields={{ projectId: p.id, back }} /> - <Input name="title" required placeholder="Новая цель" aria-label="Название цели" className="h-8" /> - <Textarea name="description" rows={2} placeholder="Зачем и какой результат" aria-label="Описание цели" /> - <Button size="sm" className="self-start">Создать цель</Button> - </form> - </PanelSection> </div> ); @@ -189,12 +173,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr <Hidden fields={{ projectId: p.id, back }} /> <Input name="title" required placeholder="Что сделать" aria-label="Название стори" /> <Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label="Описание стори" /> - <NativeSelect name="goalId" aria-label="Цель" defaultValue=""> - <option value="">Без цели</option> - {goals.map((g) => ( - <option key={g.id} value={g.id}>◎ {g.title}</option> - ))} - </NativeSelect> <Button variant="default" size="sm" className="self-start">Создать стори</Button> </form> ); diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index c95764ca..bb27362b 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -1,8 +1,6 @@ import Link from "next/link"; import { notFound } from "next/navigation"; -import { eq } from "drizzle-orm"; import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react"; -import { goals } from "@peppa/db"; import { taskCiSummary } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; @@ -25,7 +23,6 @@ export default async function TaskPage({ params, searchParams }: { params: Promi const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null); if (!ref) notFound(); const { task, project } = ref; - const [goal] = task.goalId ? await db.select().from(goals).where(eq(goals.id, task.goalId)) : []; const { questions, sessions, events } = await taskActivity(task.id); const artifacts = openspecArtifacts(project, task.openspecChange); const ci = await taskCiSummary(db, ref); @@ -80,7 +77,6 @@ export default async function TaskPage({ params, searchParams }: { params: Promi crumbs={ <> <Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link> - {goal && <span>· ◎ {goal.title}</span>} </> } title={ diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx index 3db65ab7..7a12bfac 100644 --- a/apps/web/components/Board.tsx +++ b/apps/web/components/Board.tsx @@ -13,7 +13,6 @@ export interface Card { title: string; status: string; column: Column; - goal: string | null; } const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [ @@ -82,9 +81,8 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) { <Link href={`/t/${card.key}`} className="text-foreground hover:no-underline"> <span className="font-mono text-xs text-primary">{card.key}</span> {card.title} </Link> - {(card.goal || STATUS[card.status] || NEXT[c.id]) && ( + {(STATUS[card.status] || NEXT[c.id]) && ( <div className="flex flex-wrap items-center gap-1.5"> - {card.goal && <span className="min-w-0 basis-full truncate text-xs text-muted-foreground">◎ {card.goal}</span>} {STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>} {NEXT[c.id] && ( <Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}> diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index cac7be72..13f9772e 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -1,7 +1,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { listSessions, PeppaError, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core"; -import { events, goals, projects, questions, sessions, tasks } from "@peppa/db"; +import { events, projects, questions, sessions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, count, desc, eq, inArray, isNull } from "drizzle-orm"; import { db } from "./db"; @@ -36,9 +36,8 @@ export async function projectForUserByKey(userId: number, key: string): Promise< } export async function board(projectId: number) { - const gs = await db.select().from(goals).where(eq(goals.projectId, projectId)).orderBy(asc(goals.id)); const ts = await db.select().from(tasks).where(eq(tasks.projectId, projectId)).orderBy(asc(tasks.number)); - return { goals: gs, tasks: ts }; + return { tasks: ts }; } export async function projectSessions(projectId: number) { -- 2.45.2 From c55e9ce84019e2a0c9f863f259f01fa28fbcb1f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Sat, 14 Nov 2026 00:45:42 +0500 Subject: [PATCH 034/536] CI: install pnpm and openspec into a job-local prefix (concurrent jobs collided in the toolcache) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .gitea/workflows/ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index a523b9f9..ac6ffd4f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -35,7 +35,10 @@ jobs: - name: tools run: | apt-get update -qq && apt-get install -y -qq tmux >/dev/null - npm install -g pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null + # Job-local prefix: the node toolcache is shared between jobs running at the same time + # (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST). + npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null + echo "$RUNNER_TEMP/tools/bin" >> "$GITHUB_PATH" - id: install name: install run: bash .gitea/peppa-check.sh install -- 2.45.2 From ed49767c313e148f5278f5d9f74dfb510a26aa0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= <asel@asel.local> Date: Sat, 14 Nov 2026 01:14:10 +0500 Subject: [PATCH 035/536] PEP-65: eGov QR login through the KazEDS relay (sign.aitu.uz) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Login page and Settings → eGov: relay session with a server-side challenge/nonce, QR + eGov Mobile deep link, polling, one-shot completion; IIN from the signer's certificate (own DER reader), users.egov_iin. The relay is trusted (PM decision): no own XMLDSig check. CLI peppa user egov, mock-kazeds-relay, tests. Dev mode: /_next/static is no-store (Cloudflare cached stale chunks). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 3 +- apps/web/app/(app)/actions.ts | 8 + apps/web/app/(app)/settings/page.tsx | 31 +- apps/web/app/auth/egov/complete/route.ts | 29 + apps/web/app/auth/egov/start/route.ts | 20 + apps/web/app/auth/egov/status/route.ts | 14 + apps/web/app/login/page.tsx | 2 + apps/web/components/EgovSign.tsx | 76 + apps/web/lib/auth.ts | 4 + apps/web/next.config.ts | 5 + apps/web/package.json | 2 + docs/egov-reference/README.md | 67 + docs/egov-reference/mockDemo.js | 33 + docs/egov-reference/mockRelay.js | 39 + docs/egov-reference/package.json | 13 + docs/egov-reference/signWidget.js | 171 ++ docs/egov-reference/signWidget.server.js | 126 + openspec/changes/pep-65-egov-login/design.md | 60 + .../changes/pep-65-egov-login/proposal.md | 39 + .../pep-65-egov-login/specs/web-auth/spec.md | 40 + openspec/changes/pep-65-egov-login/tasks.md | 10 + packages/cli/src/index.ts | 12 + packages/core/src/egov.ts | 217 ++ packages/core/src/index.ts | 1 + packages/db/migrations/0001_egov_iin.sql | 3 + .../db/migrations/meta/0001_snapshot.json | 2272 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 3 + packages/shared/src/env.ts | 4 + packages/testkit/bin/mock-kazeds-relay | 3 + packages/testkit/src/mock-kazeds-relay.ts | 109 + packages/testkit/test/egov.test.ts | 109 + pnpm-lock.yaml | 226 ++ 33 files changed, 3753 insertions(+), 5 deletions(-) create mode 100644 apps/web/app/auth/egov/complete/route.ts create mode 100644 apps/web/app/auth/egov/start/route.ts create mode 100644 apps/web/app/auth/egov/status/route.ts create mode 100644 apps/web/components/EgovSign.tsx create mode 100644 docs/egov-reference/README.md create mode 100644 docs/egov-reference/mockDemo.js create mode 100644 docs/egov-reference/mockRelay.js create mode 100644 docs/egov-reference/package.json create mode 100644 docs/egov-reference/signWidget.js create mode 100644 docs/egov-reference/signWidget.server.js create mode 100644 openspec/changes/pep-65-egov-login/design.md create mode 100644 openspec/changes/pep-65-egov-login/proposal.md create mode 100644 openspec/changes/pep-65-egov-login/specs/web-auth/spec.md create mode 100644 openspec/changes/pep-65-egov-login/tasks.md create mode 100644 packages/core/src/egov.ts create mode 100644 packages/db/migrations/0001_egov_iin.sql create mode 100644 packages/db/migrations/meta/0001_snapshot.json create mode 100755 packages/testkit/bin/mock-kazeds-relay create mode 100644 packages/testkit/src/mock-kazeds-relay.ts create mode 100644 packages/testkit/test/egov.test.ts diff --git a/AGENTS.md b/AGENTS.md index 0ff1dc39..975a8a58 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,7 @@ - **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp` - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` +- **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ `<auth><challenge/><nonce/></auth>`, поток в `settings` `egov.flow:<hash>`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <login> <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u<id>` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:<service>`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon:<service>:…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect <KEY>` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) @@ -34,7 +35,7 @@ - **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем -- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже +- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже - **Прод Пеппы (PEP-18, для будущего официального прода)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/<sha>` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh <sha>`: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 2e57b35b..c99694e0 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -1,6 +1,7 @@ "use server"; import { + linkEgovIin, createTask, getQuestion, getSession, @@ -185,6 +186,13 @@ export async function disconnectClaude(f: FormData) { }); } +export async function unlinkEgov(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await linkEgovIin(db, user.id, null); + }); +} + export async function addProjectMember(f: FormData) { const user = await requireUser(); await attempt(f, async () => { diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 7cf42ad8..b63272f3 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,15 +1,16 @@ import { ExternalLink } from "lucide-react"; -import { connectedApps } from "@peppa/core"; +import { connectedApps, maskIin } from "@peppa/core"; import { pendingClaudeSetup } from "@peppa/runner"; import { Hidden } from "@/components/cards"; import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; +import { EgovSign } from "@/components/EgovSign"; import { Workspace } from "@/components/Workspace"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions"; +import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unlinkEgov, unpairTelegramAction } from "../actions"; const back = { back: "/settings" }; @@ -26,9 +27,9 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?: ); } -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string; egov?: string }> }) { const user = await requireUser(); - const { error, claude } = await searchParams; + const { error, claude, egov } = await searchParams; const setup = await pendingClaudeSetup(db, user.id); const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); @@ -91,6 +92,28 @@ export default async function Settings({ searchParams }: { searchParams: Promise </Row> )} </Section> + <Section title="eGov"> + {egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>} + {user.egovIin ? ( + <Card> + <p className="m-0 text-sm"> + Привязан ИИН <span className="font-mono">{maskIin(user.egovIin)}</span> — на странице входа можно войти через eGov QR. + </p> + <form action={unlinkEgov}> + <Hidden fields={back} /> + <Button variant="destructive" size="sm">Отвязать</Button> + </form> + </Card> + ) : ( + <Card> + <p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. После этого можно входить в Пеппу через eGov.</p> + <div className="max-w-xs"> + <EgovSign purpose="link" label="Привязать eGov" /> + </div> + </Card> + )} + </Section> + <Section title="Telegram"> {user.telegramChatId ? ( <Row diff --git a/apps/web/app/auth/egov/complete/route.ts b/apps/web/app/auth/egov/complete/route.ts new file mode 100644 index 00000000..c24778e9 --- /dev/null +++ b/apps/web/app/auth/egov/complete/route.ts @@ -0,0 +1,29 @@ +import { completeEgovFlow, isUserAllowed, PeppaError } from "@peppa/core"; +import { cookies } from "next/headers"; +import { NextResponse, type NextRequest } from "next/server"; +import { EGOV_COOKIE, egovCookieOptions, safeNext, sessionCookie } from "@/lib/auth"; +import { db } from "@/lib/db"; + +/** Finishes a signed eGov flow: logs in by the linked IIN, or links the IIN to the current account. */ +export async function POST(req: NextRequest) { + const { next } = (await req.json().catch(() => ({}))) as { next?: string }; + const handle = (await cookies()).get(EGOV_COOKIE)?.value ?? ""; + const done = (body: object, status = 200) => { + const res = NextResponse.json(body, { status }); + res.cookies.set(EGOV_COOKIE, "", egovCookieOptions(0)); + return res; + }; + try { + const r = await completeEgovFlow(db, handle); + // The handle lives only in the starter's httpOnly cookie, so a link flow is finished by the + // browser (and account) that started it. + if (r.purpose === "link") return done({ redirect: "/settings?egov=linked" }); + if (!(await isUserAllowed(db, r.user))) return done({ error: "Нет доступа к Пеппе — попросите администратора" }, 403); + const res = done({ redirect: safeNext(next) }); + const c = sessionCookie(r.user.id); + res.cookies.set(c.name, c.value, c.options); + return res; + } catch (e) { + return done({ error: e instanceof PeppaError ? e.message : "Не удалось войти через eGov" }, 400); + } +} diff --git a/apps/web/app/auth/egov/start/route.ts b/apps/web/app/auth/egov/start/route.ts new file mode 100644 index 00000000..5218e574 --- /dev/null +++ b/apps/web/app/auth/egov/start/route.ts @@ -0,0 +1,20 @@ +import { PeppaError, startEgovFlow, type EgovPurpose } from "@peppa/core"; +import { NextResponse, type NextRequest } from "next/server"; +import QRCode from "qrcode"; +import { currentUser, EGOV_COOKIE, egovCookieOptions } from "@/lib/auth"; +import { db } from "@/lib/db"; + +/** Starts an eGov QR flow (PEP-65): `login` from the login page, `link` from Settings (needs a session). */ +export async function POST(req: NextRequest) { + const { purpose } = (await req.json().catch(() => ({}))) as { purpose?: EgovPurpose }; + try { + const user = purpose === "link" ? await currentUser() : null; + const flow = await startEgovFlow(db, purpose === "link" ? "link" : "login", user?.id ?? null); + const qr = await QRCode.toDataURL(flow.qrContent, { errorCorrectionLevel: "M", margin: 2, width: 280 }); + const res = NextResponse.json({ qr, deeplink: flow.deeplink, expiresAt: flow.expiresAt }); + res.cookies.set(EGOV_COOKIE, flow.handle, egovCookieOptions(Math.ceil((flow.expiresAt - Date.now()) / 1000))); + return res; + } catch (e) { + return NextResponse.json({ error: e instanceof PeppaError ? e.message : "Не удалось создать QR eGov" }, { status: 502 }); + } +} diff --git a/apps/web/app/auth/egov/status/route.ts b/apps/web/app/auth/egov/status/route.ts new file mode 100644 index 00000000..c3496dc6 --- /dev/null +++ b/apps/web/app/auth/egov/status/route.ts @@ -0,0 +1,14 @@ +import { egovFlowStatus, PeppaError } from "@peppa/core"; +import { cookies } from "next/headers"; +import { NextResponse } from "next/server"; +import { EGOV_COOKIE } from "@/lib/auth"; +import { db } from "@/lib/db"; + +/** Status of this browser's eGov QR flow: pending | scanned | completed | expired | rejected. */ +export async function GET() { + try { + return NextResponse.json({ status: await egovFlowStatus(db, (await cookies()).get(EGOV_COOKIE)?.value ?? "") }); + } catch (e) { + return NextResponse.json({ error: e instanceof PeppaError ? e.message : "eGov недоступен" }, { status: 502 }); + } +} diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index cceff97a..2c11bff9 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -2,6 +2,7 @@ import { redirect } from "next/navigation"; import { currentUser, safeNext } from "@/lib/auth"; import { Brand } from "@/components/Brand"; import { Flash } from "@/components/common"; +import { EgovSign } from "@/components/EgovSign"; import { Footer } from "@/components/Footer"; import { Button } from "@/components/ui/button"; @@ -19,6 +20,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ <Button asChild variant="default" size="lg" className="w-full"> <a href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a> </Button> + <EgovSign purpose="login" next={safeNext(next)} label="Войти через eGov" /> <Footer /> </div> </main> diff --git a/apps/web/components/EgovSign.tsx b/apps/web/components/EgovSign.tsx new file mode 100644 index 00000000..c984bdec --- /dev/null +++ b/apps/web/components/EgovSign.tsx @@ -0,0 +1,76 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { QrCode, Smartphone } from "lucide-react"; +import { Button } from "@/components/ui/button"; + +type Phase = { at: "idle" } | { at: "qr"; qr: string; deeplink: string; status: string } | { at: "done" } | { at: "error"; message: string }; + +const STATUS: Record<string, string> = { + pending: "Отсканируйте QR в eGov Mobile", + scanned: "QR отсканирован — подпишите в eGov Mobile", + completed: "Подписано, входим…", +}; + +/** + * eGov QR (PEP-65): shows the relay's QR and a deep link for the same phone, polls the flow and + * finishes it. `login` signs in; `link` binds the IIN to the current account (Settings). + */ +export function EgovSign({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) { + const [phase, setPhase] = useState<Phase>({ at: "idle" }); + const alive = useRef(true); + // Set on mount too: StrictMode (dev) mounts, unmounts and mounts again. + useEffect(() => { + alive.current = true; + return () => void (alive.current = false); + }, []); + + const fail = (message: string) => alive.current && setPhase({ at: "error", message }); + + async function start() { + const r = await fetch("/auth/egov/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ purpose }) }); + const body = (await r.json()) as { qr?: string; deeplink?: string; error?: string }; + if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось создать QR"); + setPhase({ at: "qr", qr: body.qr, deeplink: body.deeplink ?? "", status: "pending" }); + for (;;) { + await new Promise((res) => setTimeout(res, 2000)); + const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string }; + if (!alive.current) return; + if (s.error) return fail(s.error); + if (s.status === "expired") return fail("QR-код истёк — начните заново"); + if (s.status === "rejected") return fail("Подписание отменено в eGov Mobile"); + setPhase((p) => (p.at === "qr" ? { ...p, status: s.status ?? p.status } : p)); + if (s.status === "completed") break; + } + const c = await fetch("/auth/egov/complete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ next }) }); + const done = (await c.json().catch(() => ({}))) as { redirect?: string; error?: string }; + if (!c.ok || !done.redirect) return fail(done.error ?? "Не удалось войти через eGov"); + setPhase({ at: "done" }); + window.location.assign(done.redirect); + } + + if (phase.at === "qr") { + return ( + <div className="flex w-full flex-col items-center gap-3 rounded-lg border bg-card p-4"> + {/* eslint-disable-next-line @next/next/no-img-element -- data URL from the server */} + <img src={phase.qr} alt="QR для eGov Mobile" width={220} height={220} className="rounded-md bg-white p-1" /> + <p className="m-0 text-sm text-muted-foreground" aria-live="polite">{STATUS[phase.status] ?? phase.status}</p> + {phase.deeplink && ( + <Button asChild variant="outline" size="sm" className="w-full"> + <a href={phase.deeplink}> + <Smartphone /> Открыть в eGov Mobile + </a> + </Button> + )} + </div> + ); + } + return ( + <div className="flex w-full flex-col gap-2"> + {phase.at === "error" && <p className="m-0 text-sm text-destructive">{phase.message}</p>} + <Button variant="outline" size="lg" className="w-full" disabled={phase.at === "done"} onClick={() => void start().catch((e: Error) => fail(e.message))}> + <QrCode /> {phase.at === "error" ? "Новый QR" : label} + </Button> + </div> + ); +} diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index 12261d7c..dcdeeec8 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -8,6 +8,8 @@ import { db } from "./db"; export const SESSION_COOKIE = "peppa_session"; export const STATE_COOKIE = "peppa_oauth_state"; export const NEXT_COOKIE = "peppa_next"; +/** eGov QR flow handle (PEP-65): httpOnly, only for /auth/egov, lives as long as the QR. */ +export const EGOV_COOKIE = "peppa_egov"; /** Only same-site relative paths are allowed as a post-login destination. */ export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/"); @@ -43,6 +45,8 @@ export function sessionCookie(uid: number) { }; } +export const egovCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/egov", maxAge: maxAgeSec }); + const isHttps = () => loadEnv().PEPPA_WEB_URL.startsWith("https://"); /** diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 7b95f44a..0c238560 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -19,6 +19,11 @@ const config: NextConfig = { // Forwarded browser logs land in .next/dev/logs; the watcher picked that up as a change and the // page reloaded in a loop (every reload logs again). Errors still reach the terminal. logging: { browserToTerminal: "error" }, + // Dev chunks keep their names between edits; Cloudflare turns the dev server's `no-cache` into a + // 4 h browser cache, so a reload ran stale code. `private, no-store` is passed through as is. + async headers() { + return process.env.NODE_ENV === "development" ? [{ source: "/_next/static/:path*", headers: [{ key: "Cache-Control", value: "private, no-store" }] }] : []; + }, transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], env: { NEXT_PUBLIC_PEPPA_VERSION: version, diff --git a/apps/web/package.json b/apps/web/package.json index 81159059..4939f09a 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -24,12 +24,14 @@ "geist": "1.9.2", "lucide-react": "1.72.0", "next": "16.4.6", + "qrcode": "1.5.4", "react": "19.3.1", "react-dom": "19.3.1", "tailwind-merge": "3.7.0" }, "devDependencies": { "@tailwindcss/postcss": "4.3.5", + "@types/qrcode": "1.5.5", "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "tailwindcss": "4.3.5" diff --git a/docs/egov-reference/README.md b/docs/egov-reference/README.md new file mode 100644 index 00000000..25e968fa --- /dev/null +++ b/docs/egov-reference/README.md @@ -0,0 +1,67 @@ +# KazEDS eGov sign-in widget + +This integration asks eGov Mobile to sign a short-lived XML challenge and gives the signed XML to the relying website. The website owns signature verification and the login decision. + +## Install the backend adapter + +Copy `signWidget.server.js` into the site's Node backend and install: + +```sh +npm install express qrcode +``` + +Mount it in an existing Express app: + +```js +const { makeRouter } = require('./signWidget.server'); +app.use('/api/egov-login', makeRouter({ + onComplete: async ({ challenge, nonce, signedDocuments, request }) => { + // Implement with YOUR XMLDSig verifier and account policy. + // 1. Verify the signature over the returned XML. + // 2. Confirm the signed XML contains this exact challenge and nonce. + // 3. Validate the certificate chain, validity and revocation. + // 4. Resolve/link the account and create YOUR site's session. + // `challenge` and `nonce` come from server memory, not the browser. + const identity = await verifyEgovLogin({ challenge, nonce, signedDocuments }); + if (!identity) throw new Error('Invalid eGov signature or challenge'); + await createSiteSession(request, identity); + return { authenticated: true }; + }, +})); +``` + +Set `KAZEDS_RELAY_BASE` if needed (default `https://sign.aitu.uz/relay/v1`), plus `EGOV_ORGANISATION_NAME` and `EGOV_ORGANISATION_BIN` for the relying site. Use the registered business identity and eGov-approved domain details required for your integration. + +## Add the browser widget + +Serve `signWidget.js` from the relying site and add: + +```html +<div id="egov-login"></div> +<script src="/signWidget.js"></script> +<script> + SignWidget.mount({ + container: '#egov-login', + apiBase: '/api/egov-login', + onSigned: async (result) => { + const response = await fetch('/api/egov-login/complete', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'same-origin', + body: JSON.stringify({ verificationHandle: result.verificationHandle }), + }); + if (!response.ok) throw new Error('The site could not verify this signature'); + // The relying site's configured onComplete callback decides whether to log in. + }, + onError: (error) => console.error('eGov login flow failed', error), + }); +</script> +``` + +Implement `/api/egov-login/verify` on the relying site's backend. Verify the XMLDSig cryptographically, ensure the signed content contains the exact server-side challenge and nonce, check the certificate chain, validity and revocation, and only then map the certified identity to an account or ask the user to link/create one. Do not trust identity fields sent by the browser, and do not create a login session just because the widget reports `completed`. + +The adapter stores short-lived correlation state in memory and is suitable for a single-process integration prototype. For multiple backend instances, replace its `Map` with shared storage and bind each flow to the site's authenticated/CSRF-protected browser session. The eGov Relay session store is also currently in memory. + +## Test mode + +The Relay's eGov routes are the real API shim, not a deployed mock signer. For local end-to-end UI testing, point `KAZEDS_RELAY_BASE` at a local mock implementing `POST /egov/sessions` and `GET /egov/:id/status`; have it return a completed sample XML document. Real signing still requires eGov Mobile and its domain allowlist. Never use a fabricated signature to grant an account login. diff --git a/docs/egov-reference/mockDemo.js b/docs/egov-reference/mockDemo.js new file mode 100644 index 00000000..117ee281 --- /dev/null +++ b/docs/egov-reference/mockDemo.js @@ -0,0 +1,33 @@ +// Entirely local, test-only journey. The owner callback checks challenge +// plumbing but does NOT validate a real XML signature or authenticate anyone. +const express = require('express'); +const { makeRouter } = require('./signWidget.server'); + +const app = express(); +app.get('/', (_req, res) => res.type('html').send(`<!doctype html> +<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>KazEDS local mock +

eGov widget mock journey

+

Local UI test only. The signature is fabricated.

+`)); +app.get('/signWidget.js', (_req, res) => res.sendFile(require('node:path').join(__dirname, 'signWidget.js'))); +app.use('/api/egov-login', makeRouter({ + onComplete: async ({ challenge, nonce, signedDocuments }) => { + const xml = signedDocuments?.[0]?.documentXml || ''; + if (!xml.includes(`${challenge}`) || !xml.includes(`${nonce}`)) { + throw new Error('Mock challenge/nonce mismatch'); + } + if (!xml.includes('NOT_A_SIGNATURE')) { + throw new Error('This demo expects the test mock response'); + } + return { mockOnly: true, message: 'Challenge handoff passed; no signature was verified.' }; + }, +})); + +const port = Number(process.env.PORT || 3102); +app.listen(port, '127.0.0.1', () => console.log(`TEST WIDGET ADAPTER ONLY at http://127.0.0.1:${port}`)); diff --git a/docs/egov-reference/mockRelay.js b/docs/egov-reference/mockRelay.js new file mode 100644 index 00000000..d4cc8956 --- /dev/null +++ b/docs/egov-reference/mockRelay.js @@ -0,0 +1,39 @@ +// LOCAL UI TEST ONLY. This returns fabricated XML and MUST NOT be used to +// authenticate users or be exposed publicly. +const express = require('express'); +const crypto = require('node:crypto'); + +const app = express(); +app.use(express.json()); +const sessions = new Map(); + +app.post('/v1/egov/sessions', (req, res) => { + const id = crypto.randomUUID(); + const source = req.body?.documentsToSign?.[0]?.documentXml || ''; + const challenge = source.match(/([^<]+)<\/challenge>/)?.[1] || 'MISSING_CHALLENGE'; + const nonce = source.match(/([^<]+)<\/nonce>/)?.[1] || 'MISSING_NONCE'; + sessions.set(id, { createdAt: Date.now(), polls: 0, challenge, nonce }); + res.status(201).json({ + session_id: id, + qr_content: `mobileSign:https://example.invalid/mgovSign/${id}`, + deeplink: `https://m.egov.kz/mobileSign?link=https%3A%2F%2Fexample.invalid%2FmgovSign%2F${id}`, + expires_at: new Date(Date.now() + 5 * 60_000).toISOString(), + }); +}); + +app.get('/v1/egov/:id/status', (req, res) => { + const session = sessions.get(req.params.id); + if (!session) return res.status(404).json({ error: 'Mock session not found' }); + session.polls += 1; + if (session.polls < 3) return res.json({ status: session.polls === 1 ? 'scanned' : 'pending', expires_in: 290 }); + sessions.delete(req.params.id); + const signed = `${session.challenge}${session.nonce}NOT_A_SIGNATURENOT_A_CERTIFICATE`; + return res.json({ + status: 'completed', + // Deliberately fabricated: only exercises UI plumbing; not a valid signature. + signedDocuments: [{ id: 1, nameRu: 'Mock response (not signed)', documentXml: signed }], + }); +}); + +const port = Number(process.env.MOCK_PORT || 3103); +app.listen(port, '127.0.0.1', () => console.log(`TEST MOCK ONLY at http://127.0.0.1:${port}/v1`)); diff --git a/docs/egov-reference/package.json b/docs/egov-reference/package.json new file mode 100644 index 00000000..68cb7313 --- /dev/null +++ b/docs/egov-reference/package.json @@ -0,0 +1,13 @@ +{ + "name": "kazeds-egov-sign-widget-example", + "private": true, + "scripts": { + "mock": "node mockRelay.js", + "adapter": "node signWidget.server.js", + "mock-demo": "node mockDemo.js" + }, + "dependencies": { + "express": "^4.21.2", + "qrcode": "^1.5.4" + } +} diff --git a/docs/egov-reference/signWidget.js b/docs/egov-reference/signWidget.js new file mode 100644 index 00000000..1f4429cc --- /dev/null +++ b/docs/egov-reference/signWidget.js @@ -0,0 +1,171 @@ +/* + * KazEDS eGov QR sign-in widget (browser side) + * + * Usage: + *
+ * + * + * + * QR images are generated by the site's backend. No QR payload is sent to + * a third-party image service. + */ +(function (global) { + 'use strict'; + + const DEFAULTS = { + apiBase: '/api/egov-login', + buttonText: 'Войти через eGov Mobile', + onSigned: null, + onError: null, + pollIntervalMs: 2000, + }; + + function mount(options) { + const config = Object.assign({}, DEFAULTS, options || {}); + const container = typeof config.container === 'string' + ? document.querySelector(config.container) + : config.container; + if (!container) throw new Error('SignWidget: container was not found'); + + container.replaceChildren(); + const root = document.createElement('div'); + root.className = 'kazeds-sign-widget'; + root.innerHTML = ` + + + `; + container.append(root); + + const button = root.querySelector('.kw-start'); + const panel = root.querySelector('.kw-panel'); + button.textContent = config.buttonText; + let timer = null; + let active = false; + let requestController = null; + + function showError(error) { + panel.hidden = false; + panel.replaceChildren(); + const message = document.createElement('p'); + message.className = 'kw-error'; + message.textContent = error && error.message ? error.message : String(error || 'Login failed'); + panel.append(message); + if (typeof config.onError === 'function') config.onError(error); + } + + async function jsonRequest(path, options) { + const response = await fetch(config.apiBase.replace(/\/$/, '') + path, Object.assign({ + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json' }, + }, options || {})); + const body = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(body.error || `Request failed (${response.status})`); + return body; + } + + async function poll(session) { + try { + while (active) { + await new Promise((resolve) => { timer = setTimeout(resolve, config.pollIntervalMs); }); + if (!active) return; + const state = await jsonRequest('/' + encodeURIComponent(session.clientSessionId), { + method: 'GET', + headers: {}, + }); + if (state.status === 'completed') { + active = false; + button.disabled = false; + panel.replaceChildren(); + const done = document.createElement('p'); + done.className = 'kw-status'; + done.textContent = 'Подпись получена. Проверка выполняется сайтом.'; + panel.append(done); + if (typeof config.onSigned === 'function') await config.onSigned(state); + return; + } + if (state.status === 'expired' || state.status === 'rejected') { + throw new Error(state.status === 'expired' ? 'QR-код истёк. Начните заново.' : 'Подписание отменено.'); + } + const status = panel.querySelector('.kw-status'); + if (status) status.textContent = state.status === 'scanned' + ? 'QR отсканирован. Подтвердите подписание в eGov Mobile…' + : 'Ожидание сканирования в eGov Mobile…'; + } + } catch (error) { + active = false; + button.disabled = false; + showError(error); + } + } + + async function start() { + if (active) return; + button.disabled = true; + panel.hidden = false; + panel.replaceChildren(); + const status = document.createElement('p'); + status.className = 'kw-status'; + status.textContent = 'Создаём запрос…'; + panel.append(status); + requestController = new AbortController(); + try { + const session = await jsonRequest('/start', { + method: 'POST', + body: '{}', + signal: requestController.signal, + }); + panel.replaceChildren(); + const heading = document.createElement('p'); + heading.className = 'kw-status'; + heading.textContent = 'Откройте eGov Mobile и отсканируйте QR-код'; + const image = document.createElement('img'); + image.src = session.qrDataUrl; + image.alt = 'eGov QR'; + const link = document.createElement('a'); + link.href = session.deeplink; + link.textContent = 'Открыть eGov Mobile'; + link.rel = 'noopener'; + link.target = '_blank'; + const progress = document.createElement('p'); + progress.className = 'kw-status'; + progress.textContent = 'Ожидание сканирования в eGov Mobile…'; + panel.append(heading, image, link, progress); + active = true; + poll(session); + } catch (error) { + button.disabled = false; + showError(error); + } + } + + button.addEventListener('click', start); + return { + destroy() { + active = false; + clearTimeout(timer); + if (requestController) requestController.abort(); + container.replaceChildren(); + }, + start, + }; + } + + global.SignWidget = { mount }; +})(window); diff --git a/docs/egov-reference/signWidget.server.js b/docs/egov-reference/signWidget.server.js new file mode 100644 index 00000000..772e51f0 --- /dev/null +++ b/docs/egov-reference/signWidget.server.js @@ -0,0 +1,126 @@ +/* + * Minimal Express adapter between a site's browser widget and KazEDS Relay. + * Requires Node 20+, Express, and qrcode: + * npm install express qrcode + * + * Mount this router only on the site that will verify the result. It returns + * the signed XML to that site's browser; it does not authenticate a user. + * The site MUST verify the XMLDSig, the exact challenge, certificate chain, + * validity/revocation, and apply its own account/linking policy before login. + */ +const crypto = require('node:crypto'); +const express = require('express'); +const QRCode = require('qrcode'); + +const RELAY_BASE = (process.env.KAZEDS_RELAY_BASE || 'https://sign.aitu.uz/relay/v1').replace(/\/$/, ''); +const ORGANISATION_NAME = process.env.EGOV_ORGANISATION_NAME || 'Вход на сайт'; +const ORGANISATION_BIN = process.env.EGOV_ORGANISATION_BIN || '000000000000'; +const SESSION_TTL_MS = 5 * 60 * 1000; +const sessions = new Map(); + +async function relay(path, init) { + const response = await fetch(RELAY_BASE + path, Object.assign({ + headers: { 'Content-Type': 'application/json' }, + }, init || {})); + const body = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(body.message || body.error || `KazEDS Relay returned ${response.status}`); + return body; +} + +function makeRouter(options) { + const settings = options || {}; + const router = express.Router(); + + // POST /api/egov-login/start + router.post('/start', express.json({ limit: '2kb' }), async (_req, res) => { + try { + const clientSessionId = crypto.randomUUID(); + const challenge = crypto.randomBytes(32).toString('base64url'); + // Keep this exact value in server memory; compare it after owner-side + // XMLDSig verification. Do not trust a challenge returned by the browser. + const challengeXml = `${challenge}${clientSessionId}`; + const relaySession = await relay('/egov/sessions', { + method: 'POST', + body: JSON.stringify({ + description: `Авторизация: ${ORGANISATION_NAME}`, + organisation: { nameRu: ORGANISATION_NAME, nameKz: ORGANISATION_NAME, nameEn: ORGANISATION_NAME, bin: ORGANISATION_BIN }, + signMethod: 'XML', + documentsToSign: [{ id: 1, nameRu: `Вход на ${ORGANISATION_NAME}`, documentXml: challengeXml }], + }), + }); + sessions.set(clientSessionId, { + relaySessionId: relaySession.session_id, + challenge, + nonce: clientSessionId, + expiresAt: Date.now() + SESSION_TTL_MS, + signedDocuments: null, + }); + const qrDataUrl = await QRCode.toDataURL(relaySession.qr_content, { errorCorrectionLevel: 'H', margin: 2, width: 280 }); + res.status(201).json({ clientSessionId, qrDataUrl, deeplink: relaySession.deeplink, expiresAt: relaySession.expires_at }); + } catch (error) { + res.status(502).json({ error: error.message || 'Could not create eGov QR session' }); + } + }); + + // GET /api/egov-login/:clientSessionId + router.get('/:clientSessionId', async (req, res) => { + const entry = sessions.get(req.params.clientSessionId); + if (!entry) return res.status(404).json({ error: 'Login session not found' }); + if (Date.now() >= entry.expiresAt) { + sessions.delete(req.params.clientSessionId); + return res.json({ status: 'expired' }); + } + try { + const state = await relay(`/egov/${encodeURIComponent(entry.relaySessionId)}/status`, { method: 'GET' }); + if (state.status === 'completed') { + // Keep the signed content and expected challenge on the server. The + // browser receives only a random handle and cannot replace either. + entry.signedDocuments = state.signedDocuments; + return res.json({ status: 'completed', verificationHandle: req.params.clientSessionId }); + } + return res.json({ status: state.status, expires_in: state.expires_in }); + } catch (error) { + return res.status(502).json({ error: error.message || 'Could not read eGov session status' }); + } + }); + + // POST /api/egov-login/complete { verificationHandle } + // The relying site supplies its own verifier/account policy via onComplete. + router.post('/complete', express.json({ limit: '2kb' }), async (req, res) => { + const handle = req.body && req.body.verificationHandle; + const entry = typeof handle === 'string' ? sessions.get(handle) : null; + if (!entry || !entry.signedDocuments) return res.status(404).json({ error: 'Completed login flow not found' }); + if (Date.now() >= entry.expiresAt) { + sessions.delete(handle); + return res.status(410).json({ error: 'Login flow expired' }); + } + if (typeof settings.onComplete !== 'function') { + return res.status(501).json({ error: 'Configure the relying site onComplete verifier before using this endpoint' }); + } + try { + const result = await settings.onComplete({ + challenge: entry.challenge, + nonce: entry.nonce, + signedDocuments: entry.signedDocuments, + request: req, + }); + sessions.delete(handle); + return res.json(result || { authenticated: true }); + } catch (error) { + sessions.delete(handle); + return res.status(401).json({ error: error.message || 'Signature verification failed' }); + } + }); + + return router; +} + +module.exports = { makeRouter }; + +// Optional standalone demo server: `node signWidget.server.js` +if (require.main === module) { + const app = express(); + app.use('/api/egov-login', makeRouter()); + const port = Number(process.env.PORT || 3102); + app.listen(port, () => console.log(`KazEDS eGov widget adapter listening on :${port}`)); +} diff --git a/openspec/changes/pep-65-egov-login/design.md b/openspec/changes/pep-65-egov-login/design.md new file mode 100644 index 00000000..2be108c4 --- /dev/null +++ b/openspec/changes/pep-65-egov-login/design.md @@ -0,0 +1,60 @@ +# Design: PEP-65 — вход через eGov QR + +## Доверие (решение PM 2026-11-14) + +Подпись XMLDSig Пеппа **сама криптографически не проверяет**: eGov Mobile подписывает +ключами НУЦ РК (ГОСТ), стандартные библиотеки Node ГОСТ не умеют, а отдельный сервис +проверки (NCANode) PM решил не поднимать. Доверяем relay `sign.aitu.uz`: + +- id сессии relay знает только сервер Пеппы, статус и подписанный XML Пеппа забирает сама + по HTTPS — браузер не может подсунуть чужой результат; +- в подписанном XML должен быть ровно наш challenge (32 случайных байта) и nonce потока; +- ИИН берётся из сертификата подписанта (`SERIALNUMBER=IIN…`) в этом XML. + +Риск: компрометация relay или TLS до него = возможность войти под любым привязанным ИИН. +Если понадобится строже — проверка через NCANode встаёт в `completeEgovFlow` без смены +потока (одна функция `verifySigned`). + +## Поток + +``` +браузер веб Пеппы (route handlers) relay sign.aitu.uz +«Войти через eGov» ──▶ POST /auth/egov/start {purpose} ──────▶ POST /egov/sessions + settings egov.flow: ◀── session_id, qr_content, +◀── {qr (data URL), deeplink, expiresAt} + cookie peppa_egov=handle deeplink, expires_at +опрос каждые 2 с ─────▶ GET /auth/egov/status ─────────────────▶ GET /egov/:id/status +◀── pending|scanned|completed|expired|rejected ◀── status, signedDocuments +completed ────────────▶ POST /auth/egov/complete + challenge+nonce в XML? ИИН из сертификата → пользователь → +◀── {redirect} + peppa_session (вход) или привязка ИИН (настройки) +``` + +- Handle — 24 случайных байта; в базе ключ — его хэш (`hashToken`), как у ссылок входа. + Handle живёт только в httpOnly cookie `peppa_egov` (path `/auth/egov`, 5 мин) — его + не видно скриптам и он не уходит в URL. +- `purpose`: `login` (без входа) или `link` (нужна сессия; поток запоминает userId). +- Поток одноразовый: `complete` удаляет запись при любом исходе. + +## Сертификат + +`documentXml` содержит `` (base64 DER). Разбор — свой мини-проход по +DER (OID `2.5.4.5` SERIALNUMBER, `2.5.4.3` CN, `2.5.4.4` SURNAME, `2.5.4.42` GIVENNAME), +без `X509Certificate` из node:crypto: он может не принять ГОСТ-ключ, а нам нужны только +поля субъекта. ИИН — 12 цифр после `IIN`, с проверкой контрольной цифры. Сертификат +юрлица (`BIN…` в OU) не мешает: берём ИИН подписанта. + +## Данные + +- `users.egov_iin` (text, unique, nullable) + `users.egov_linked_at`. Одна учётка — один ИИН. +- Потоки — в `settings` (ключ `egov.flow:`, JSON с `expiresAt`), просроченные + удаляются при обращении и раз в тик вачдога не нужны: записи мелкие, ключ одноразовый. + +## Окружение + +- `KAZEDS_RELAY_BASE` — по умолчанию `https://sign.aitu.uz/relay/v1`. +- `EGOV_ORGANISATION_NAME` — по умолчанию «Peppa»; `EGOV_ORGANISATION_BIN` — по умолчанию + `241140100000` (сгенерирован с верной контрольной цифрой, по решению PM). +- Мок: `mock-kazeds-relay` (`packages/testkit`), `KAZEDS_RELAY_BASE=http://127.0.0.1:/v1`. + Он сам «подписывает» на 3-м опросе и кладёт поддельный сертификат с ИИН из + `MOCK_EGOV_IIN`; можно отказать (`MOCK_EGOV_REJECT=1`) и подменить challenge + (`MOCK_EGOV_TAMPER=1`). diff --git a/openspec/changes/pep-65-egov-login/proposal.md b/openspec/changes/pep-65-egov-login/proposal.md new file mode 100644 index 00000000..fa629731 --- /dev/null +++ b/openspec/changes/pep-65-egov-login/proposal.md @@ -0,0 +1,39 @@ +# Proposal: PEP-65 — вход через eGov QR + +Задача Пеппы: **PEP-65**. + +## Why + +Войти в Пеппу сейчас можно только через Gitea. Людям из Казахстана привычнее и быстрее +войти через eGov Mobile: отсканировать QR и подписать. Relay KazEDS `sign.aitu.uz` уже +доверенный в eGov, поэтому регистрировать свой домен не нужно. + +## What Changes + +- Страница входа: «Войти через eGov». Пеппа создаёт сессию подписи в relay + (`POST /egov/sessions`, документ ``), показывает QR + и кнопку «Открыть в eGov Mobile» (для телефона), опрашивает статус; после подписи + сверяет challenge и nonce в подписанном XML, берёт ИИН и ФИО из сертификата и входит + под пользователем, к которому этот ИИН привязан. +- «Настройки → eGov»: привязать свой ИИН (та же подпись QR) и отвязать. Войти через eGov + может только пользователь с привязанным ИИН, которому разрешён вход (PEP-16). +- CLI: `peppa user egov <ИИН|->` — привязка вручную. +- Состояние потоков входа — в SQLite (`settings`, TTL 5 мин), браузер получает только + непрозрачный handle и cookie потока. +- Мок `mock-kazeds-relay` с контрактом relay для тестов и проверок без телефона. +- Пример интеграции из `apps/sign` переезжает в `docs/egov-reference/` (не пакет workspace). + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `web-auth`: вход через eGov QR, привязка ИИН. + +## Impact + +`packages/core/src/egov.ts` (relay, потоки, разбор сертификата), `packages/db` (колонка +`users.egov_iin`, миграция), `packages/shared` (env `KAZEDS_RELAY_BASE`, +`EGOV_ORGANISATION_NAME`, `EGOV_ORGANISATION_BIN`), `apps/web/app/auth/egov/*`, +страница входа и «Настройки», `packages/cli`, `packages/testkit` (мок и тесты), +зависимость `qrcode` в вебе. diff --git a/openspec/changes/pep-65-egov-login/specs/web-auth/spec.md b/openspec/changes/pep-65-egov-login/specs/web-auth/spec.md new file mode 100644 index 00000000..3da9cf56 --- /dev/null +++ b/openspec/changes/pep-65-egov-login/specs/web-auth/spec.md @@ -0,0 +1,40 @@ +# Spec Delta: web-auth + +## ADDED Requirements + +### Requirement: Вход через eGov QR +Страница входа SHALL предлагать «Войти через eGov»: Пеппа создаёт сессию подписи в relay +KazEDS, показывает QR и ссылку для eGov Mobile и после подписи входит под пользователем, +к которому привязан ИИН из сертификата подписанта. Подписанный документ SHALL содержать +ровно challenge и nonce, созданные сервером для этого потока; поток одноразовый и живёт +5 минут. + +#### Scenario: Вход по QR +- **GIVEN** у пользователя «asel» привязан ИИН 900101300126 и вход ему разрешён +- **WHEN** он выбирает «Войти через eGov» и подписывает QR в eGov Mobile +- **THEN** он входит в Пеппу как «asel» + +#### Scenario: ИИН не привязан +- **WHEN** QR подписал человек, чей ИИН не привязан ни к одному пользователю +- **THEN** вход отклонён с подсказкой привязать eGov в «Настройках» после входа через Gitea + +#### Scenario: Подменённый документ +- **WHEN** в подписанном XML нет challenge или nonce этого потока +- **THEN** вход отклонён, поток удалён + +#### Scenario: Отказ или истечение +- **WHEN** пользователь отменил подпись в eGov Mobile или QR истёк +- **THEN** страница входа показывает причину и предлагает новый QR + +### Requirement: Привязка ИИН +Пользователь SHALL привязывать к своей учётке ИИН, подписав QR в «Настройках → eGov», и +отвязывать его там же. Один ИИН привязан не больше чем к одной учётке. + +#### Scenario: Привязка +- **GIVEN** пользователь вошёл через Gitea +- **WHEN** он нажимает «Привязать eGov» и подписывает QR +- **THEN** в «Настройках» виден его ИИН (частично скрытый) и дальше он может входить через eGov + +#### Scenario: ИИН уже занят +- **WHEN** пользователь подписывает QR ИИН, привязанным к другой учётке +- **THEN** привязка отклонена diff --git a/openspec/changes/pep-65-egov-login/tasks.md b/openspec/changes/pep-65-egov-login/tasks.md new file mode 100644 index 00000000..d604c272 --- /dev/null +++ b/openspec/changes/pep-65-egov-login/tasks.md @@ -0,0 +1,10 @@ +# Tasks: PEP-65 + +- [x] 1.1 env (`KAZEDS_RELAY_BASE`, `EGOV_ORGANISATION_NAME`, `EGOV_ORGANISATION_BIN`), колонка `users.egov_iin`, миграция +- [x] 1.2 `core/egov.ts`: клиент relay, потоки в `settings`, проверка challenge/nonce, разбор сертификата, привязка ИИН +- [x] 1.3 Мок `mock-kazeds-relay` (testkit) по контракту relay +- [x] 1.4 Route handlers `/auth/egov/{start,status,complete}`, cookie потока +- [x] 1.5 UI: «Войти через eGov» на странице входа, «Настройки → eGov» (привязать / отвязать) +- [x] 1.6 CLI `peppa user egov <ИИН|->` +- [x] 1.7 Тесты (testkit): вход, не привязан, подмена, отказ, истечение, привязка, занятый ИИН +- [x] 1.8 `apps/sign` → `docs/egov-reference/`; AGENTS.md, «Помощь»; `openspec validate` diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index c760fc97..15d03db6 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -25,6 +25,8 @@ import { getSetting, setAllowedLogins, getUserByLogin, + linkEgovIin, + maskIin, giteaForBot, setProjectOwner, getTaskDetails, @@ -75,6 +77,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa status (services, outbox, runners, questions, admins) peppa telegram pair | status | unpair (users normally pair in web Settings) peppa user ensure mock- (local test user) + peppa user egov <ИИН|-> (eGov QR login: link the IIN, "-" unlinks; users link it in web Settings) peppa web login-link (one-time admin login, 10 minutes) peppa watchdog [--once] [--interval ] [--stall ] peppa db migrate (apply schema migrations to PEPPA_DB) @@ -404,6 +407,15 @@ async function main(): Promise { console.log(`${u.login} (#${u.id})`); break; } + case "user egov": { + // PEP-65: link (or unlink with "-") the IIN a user logs in with through eGov QR. + if (!args[0] || !args[1]) throw new PeppaError("usage: peppa user egov <ИИН|->"); + const u = await getUserByLogin(db, args[0]); + if (!u) throw new PeppaError(`нет пользователя ${args[0]}`); + const linked = await linkEgovIin(db, u.id, args[1] === "-" ? null : args[1]); + console.log(linked.egovIin ? `${u.login}: eGov ${maskIin(linked.egovIin)}` : `${u.login}: eGov отвязан`); + break; + } case "watchdog": { const wopts = { intervalMs: Number(opts.interval) * 1000, diff --git a/packages/core/src/egov.ts b/packages/core/src/egov.ts new file mode 100644 index 00000000..c513fda9 --- /dev/null +++ b/packages/core/src/egov.ts @@ -0,0 +1,217 @@ +// eGov QR login (PEP-65) through the KazEDS relay (sign.aitu.uz): Peppa asks eGov Mobile to sign a +// short-lived , reads the signed XML from the relay itself and takes +// the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is +// trusted (PM decision, see openspec design); the challenge and nonce never leave the server. +import { randomBytes, randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { users, type Db } from "@peppa/db"; +import { loadEnv } from "@peppa/shared"; +import { hashToken } from "./crypto.ts"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; +import { getUser, type User } from "./users.ts"; + +export const EGOV_FLOW_TTL_MS = 5 * 60_000; +export type EgovPurpose = "login" | "link"; +export type EgovStatus = "pending" | "scanned" | "completed" | "expired" | "rejected"; + +interface Flow { + purpose: EgovPurpose; + /** The account being linked (purpose "link"). */ + userId: number | null; + relaySessionId: string; + challenge: string; + nonce: string; + expiresAt: number; +} + +interface SignedDocument { + id: number; + nameRu?: string; + documentXml: string; +} + +const flowKey = (handle: string) => `egov.flow:${hashToken(handle)}`; + +async function relay(path: string, init?: RequestInit): Promise { + const base = loadEnv().KAZEDS_RELAY_BASE.replace(/\/$/, ""); + const res = await fetch(base + path, { ...init, headers: { "Content-Type": "application/json" }, signal: AbortSignal.timeout(15_000) }); + const body = (await res.json().catch(() => ({}))) as T & { message?: string; error?: string }; + if (!res.ok) throw new PeppaError(`eGov relay: ${body.message ?? body.error ?? `HTTP ${res.status}`}`); + return body; +} + +export interface EgovStart { + /** Opaque handle: kept by the browser in an httpOnly cookie, never in a URL. */ + handle: string; + /** What the QR encodes (eGov Mobile scans it). */ + qrContent: string; + /** Opens eGov Mobile on the same phone. */ + deeplink: string; + expiresAt: number; +} + +/** Starts a signing session in the relay for a login or for linking `userId`'s IIN. */ +export async function startEgovFlow(db: Db, purpose: EgovPurpose, userId: number | null = null): Promise { + if (purpose === "link" && !userId) throw new PeppaError("Привязать eGov можно только после входа"); + const env = loadEnv(); + const nonce = randomUUID(); + const challenge = randomBytes(32).toString("base64url"); + const org = env.EGOV_ORGANISATION_NAME; + const s = await relay<{ session_id: string; qr_content: string; deeplink: string; expires_at?: string }>("/egov/sessions", { + method: "POST", + body: JSON.stringify({ + description: purpose === "link" ? `Привязка eGov: ${org}` : `Авторизация: ${org}`, + organisation: { nameRu: org, nameKz: org, nameEn: org, bin: env.EGOV_ORGANISATION_BIN }, + signMethod: "XML", + documentsToSign: [{ id: 1, nameRu: `Вход в ${org}`, documentXml: `${challenge}${nonce}` }], + }), + }); + const relayExpiry = s.expires_at ? Date.parse(s.expires_at) : NaN; + const expiresAt = Math.min(Date.now() + EGOV_FLOW_TTL_MS, Number.isFinite(relayExpiry) ? relayExpiry : Infinity); + const handle = randomBytes(24).toString("base64url"); + const flow: Flow = { purpose, userId, relaySessionId: s.session_id, challenge, nonce, expiresAt }; + await setSetting(db, flowKey(handle), flow); + return { handle, qrContent: s.qr_content, deeplink: s.deeplink, expiresAt }; +} + +async function loadFlow(db: Db, handle: string): Promise { + if (!handle) return null; + const flow = await getSetting(db, flowKey(handle)); + if (flow && Date.now() >= flow.expiresAt) { + await deleteSetting(db, flowKey(handle)); + return null; + } + return flow; +} + +/** Relay status of a flow; "expired" once the flow is gone or past its TTL. */ +export async function egovFlowStatus(db: Db, handle: string): Promise { + const flow = await loadFlow(db, handle); + if (!flow) return "expired"; + const s = await relay<{ status: EgovStatus }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`); + return s.status; +} + +export interface EgovIdentity { + iin: string; + name: string | null; +} + +export type EgovResult = { purpose: "login"; user: User; identity: EgovIdentity } | { purpose: "link"; user: User; identity: EgovIdentity }; + +/** + * Finishes a signed flow (one-shot: the flow is removed whatever happens): checks that the + * signed XML carries this flow's challenge and nonce, reads the signer's IIN, then logs in the + * account the IIN is linked to, or links it to the flow's account. + */ +export async function completeEgovFlow(db: Db, handle: string): Promise { + const flow = await loadFlow(db, handle); + if (!flow) throw new PeppaError("QR-код истёк — начните заново"); + await deleteSetting(db, flowKey(handle)); + const s = await relay<{ status: EgovStatus; signedDocuments?: SignedDocument[] }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`); + if (s.status !== "completed") throw new PeppaError(s.status === "rejected" ? "Подписание отменено" : "Документ ещё не подписан"); + const identity = verifySigned(s.signedDocuments ?? [], flow); + + if (flow.purpose === "link") { + const user = await linkEgovIin(db, flow.userId!, identity.iin); + return { purpose: "link", user, identity }; + } + const [user] = await db.select().from(users).where(eq(users.egovIin, identity.iin)); + if (!user) throw new PeppaError("Этот ИИН не привязан к Пеппе — войдите через Gitea и привяжите eGov в «Настройках»"); + return { purpose: "login", user, identity }; +} + +/** The trust check (relay trusted): our challenge and nonce are in the signed XML; signer from the certificate. */ +function verifySigned(docs: SignedDocument[], flow: Flow): EgovIdentity { + const xml = docs[0]?.documentXml ?? ""; + if (!xml.includes(`${flow.challenge}`) || !xml.includes(`${flow.nonce}`)) { + throw new PeppaError("Подписан не тот документ — начните заново"); + } + const cert = /<(?:\w+:)?X509Certificate>\s*([A-Za-z0-9+/=\s]+?)\s*<\/(?:\w+:)?X509Certificate>/.exec(xml)?.[1]; + if (!cert) throw new PeppaError("В подписи нет сертификата"); + const subject = certificateSubject(Buffer.from(cert.replace(/\s+/g, ""), "base64")); + const iin = /^IIN(\d{12})$/.exec(subject.serialNumber ?? "")?.[1]; + if (!iin || !isValidIin(iin)) throw new PeppaError("В сертификате нет ИИН"); + const name = subject.commonName ?? ([subject.surname, subject.givenName].filter(Boolean).join(" ") || null); + return { iin, name }; +} + +export interface CertSubject { + serialNumber?: string; + commonName?: string; + surname?: string; + givenName?: string; +} + +const SUBJECT_OIDS: Record = { + "550405": "serialNumber", // 2.5.4.5 + "550403": "commonName", // 2.5.4.3 + "550404": "surname", // 2.5.4.4 + "55042a": "givenName", // 2.5.4.42 +}; + +/** + * Subject fields of an X.509 certificate (DER), read by walking the ASN.1 tree. node:crypto's + * X509Certificate is not used: it may refuse the GOST keys of NCA RK, and only the names matter. + * The issuer comes before the subject in the certificate, so the last value of each field wins. + */ +export function certificateSubject(der: Buffer): CertSubject { + const out: CertSubject = {}; + const walk = (start: number, end: number) => { + let i = start; + while (i < end) { + const tag = der[i]!; + let len = der[i + 1]!; + let off = i + 2; + if (len & 0x80) { + const n = len & 0x7f; + if (n === 0 || n > 4) return; + len = 0; + for (let k = 0; k < n; k++) len = len * 256 + der[off + k]!; + off += n; + } + const next = off + len; + if (next > end) return; + if (tag === 0x30 && len > 2 && der[off] === 0x06) { + // SEQUENCE { OID, value }: an AttributeTypeAndValue when the OID is a name attribute. + const oidLen = der[off + 1]!; + const field = SUBJECT_OIDS[der.subarray(off + 2, off + 2 + oidLen).toString("hex")]; + const v = off + 2 + oidLen; + if (field && v + 2 <= next) { + out[field] = der.subarray(v + 2, v + 2 + der[v + 1]!).toString(der[v] === 0x1e ? "utf16le" : "utf8"); + } + } + if (tag & 0x20) walk(off, next); // constructed: descend + i = next; + } + }; + walk(0, der.length); + return out; +} + +/** IIN control digit (the same algorithm as BIN). */ +export function isValidIin(iin: string): boolean { + if (!/^\d{12}$/.test(iin)) return false; + const d = [...iin].map(Number); + const sum = (w: number[]) => w.reduce((a, x, i) => a + x * d[i]!, 0) % 11; + let c = sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); + if (c === 10) c = sum([3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2]); + return c !== 10 && c === d[11]; +} + +/** Links an IIN to an account (or unlinks with null). One account per IIN. */ +export async function linkEgovIin(db: Db, userId: number, iin: string | null): Promise { + if (iin !== null && !isValidIin(iin)) throw new PeppaError("Неверный ИИН"); + if (iin) { + const [other] = await db.select().from(users).where(eq(users.egovIin, iin)); + if (other && other.id !== userId) throw new PeppaError("Этот ИИН уже привязан к другой учётке"); + } + await db.update(users).set({ egovIin: iin, egovLinkedAt: iin ? new Date() : null }).where(eq(users.id, userId)); + const user = await getUser(db, userId); + if (!user) throw new PeppaError("Пользователь не найден"); + return user; +} + +/** "9001****0123" — enough to recognise your own IIN on screen. */ +export const maskIin = (iin: string) => `${iin.slice(0, 4)}****${iin.slice(8)}`; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 651f1cd7..a91133a0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -17,3 +17,4 @@ export * from "./backup.ts"; export * from "./repo-info.ts"; export * from "./incidents.ts"; export * from "./ci.ts"; +export * from "./egov.ts"; diff --git a/packages/db/migrations/0001_egov_iin.sql b/packages/db/migrations/0001_egov_iin.sql new file mode 100644 index 00000000..7b789edd --- /dev/null +++ b/packages/db/migrations/0001_egov_iin.sql @@ -0,0 +1,3 @@ +ALTER TABLE `users` ADD `egov_iin` text;--> statement-breakpoint +ALTER TABLE `users` ADD `egov_linked_at` integer;--> statement-breakpoint +CREATE UNIQUE INDEX `users_egov_iin_unique` ON `users` (`egov_iin`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0001_snapshot.json b/packages/db/migrations/meta/0001_snapshot.json new file mode 100644 index 00000000..e440b375 --- /dev/null +++ b/packages/db/migrations/meta/0001_snapshot.json @@ -0,0 +1,2272 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "3df631c2-f7e3-47a6-b923-5f85677db9c3", + "prevId": "7fd81ecb-0ba2-4d0d-9ee9-d1239d6d9725", + "tables": { + "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 + } + }, + "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": {} + }, + "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 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "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" + } + }, + "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": {} + }, + "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 + }, + "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" + } + }, + "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 + }, + "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 + }, + "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": {}, + "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 + }, + "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": {} + }, + "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'" + }, + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {} + }, + "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 + }, + "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 + } + }, + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {}, + "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 + }, + "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 + }, + "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 + } + }, + "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 48cddda1..3e1f3981 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1794571062983, "tag": "0000_baseline", "breakpoints": true + }, + { + "idx": 1, + "version": "6", + "when": 1794600109462, + "tag": "0001_egov_iin", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index dc121e0c..e8ccca7e 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -31,6 +31,9 @@ export const users = sqliteTable("users", { telegramUserId: integer("telegram_user_id"), telegramUsername: text("telegram_username"), telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }), + // eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN. + egovIin: text("egov_iin").unique(), + egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }), createdAt: createdAt(), lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }), }); diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index 3ec4b185..c89a733b 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -16,6 +16,10 @@ const schema = z.object({ PEPPA_SECRET: z.string().optional(), GITEA_OAUTH_CLIENT_ID: z.string().optional(), GITEA_OAUTH_CLIENT_SECRET: z.string().optional(), + // eGov QR login (PEP-65) through the KazEDS relay, already trusted by eGov Mobile. + KAZEDS_RELAY_BASE: z.string().url().default("https://sign.aitu.uz/relay/v1"), + EGOV_ORGANISATION_NAME: z.string().default("Peppa"), + EGOV_ORGANISATION_BIN: z.string().regex(/^\d{12}$/).default("241140100000"), }); export type Env = z.infer & { PEPPA_DB: string }; diff --git a/packages/testkit/bin/mock-kazeds-relay b/packages/testkit/bin/mock-kazeds-relay new file mode 100755 index 00000000..49fa61db --- /dev/null +++ b/packages/testkit/bin/mock-kazeds-relay @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-kazeds-relay.ts" "$@" diff --git a/packages/testkit/src/mock-kazeds-relay.ts b/packages/testkit/src/mock-kazeds-relay.ts new file mode 100644 index 00000000..cd8b846d --- /dev/null +++ b/packages/testkit/src/mock-kazeds-relay.ts @@ -0,0 +1,109 @@ +// Mock KazEDS relay (PEP-65) for tests and checks without a phone: POST /v1/egov/sessions and +// GET /v1/egov/:id/status with the relay's JSON shapes. The "phone" scans on the 1st poll and +// signs on the 3rd; the signed XML echoes the document and carries a FAKE certificate whose +// subject has SERIALNUMBER=IIN — not a signature, only the plumbing is exercised. +// Standalone: `mock-kazeds-relay [port]` (MOCK_EGOV_IIN, MOCK_EGOV_NAME). +import { randomUUID } from "node:crypto"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +export interface MockEgovSigner { + iin: string; + name: string; + /** The phone declines to sign. */ + reject?: boolean; + /** The phone signs some other document (challenge replaced). */ + tamper?: boolean; +} + +interface Session { + documentXml: string; + polls: number; + signer: MockEgovSigner; + expiresAt: number; +} + +const der = (tag: number, body: Buffer) => { + const len = body.length < 0x80 ? Buffer.from([body.length]) : body.length < 0x100 ? Buffer.from([0x81, body.length]) : Buffer.from([0x82, body.length >> 8, body.length & 0xff]); + return Buffer.concat([Buffer.from([tag]), len, body]); +}; +const attr = (oidHex: string, value: string, tag = 0x0c) => + der(0x31, der(0x30, Buffer.concat([der(0x06, Buffer.from(oidHex, "hex")), der(tag, Buffer.from(value, "utf8"))]))); + +/** A certificate-shaped DER blob: issuer and subject names only (enough for Peppa's subject reader). */ +export function mockCertificate(signer: Pick): string { + const issuer = der(0x30, Buffer.concat([attr("550403", "MOCK NCA RK (not a CA)"), attr("550406", "KZ", 0x13)])); + const subject = der(0x30, Buffer.concat([attr("550403", signer.name), attr("550405", `IIN${signer.iin}`, 0x13), attr("550406", "KZ", 0x13)])); + const tbs = der(0x30, Buffer.concat([der(0x02, Buffer.from([1])), issuer, subject])); + return der(0x30, tbs).toString("base64"); +} + +export class MockKazedsRelay { + readonly sessions = new Map(); + /** Who signs the next sessions. */ + signer: MockEgovSigner; + private server: Server | null = null; + + constructor(signer: MockEgovSigner = { iin: "900101300126", name: "ТЕСТОВ ТЕСТ" }) { + this.signer = signer; + } + + async start(port = 0): Promise { + this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res)); + await new Promise((r) => this.server!.listen(port, "127.0.0.1", r)); + return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`; + } + + async stop(): Promise { + await new Promise((r) => (this.server ? this.server.close(() => r()) : r())); + } + + private async handle(method: string, url: string, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) { + const send = (code: number, body: unknown) => { + res.writeHead(code, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); + }; + if (method === "POST" && url === "/v1/egov/sessions") { + let raw = ""; + for await (const chunk of req) raw += chunk; + const body = JSON.parse(raw || "{}") as { signMethod?: string; organisation?: { bin?: string }; documentsToSign?: Array<{ documentXml?: string }> }; + const xml = body.documentsToSign?.[0]?.documentXml; + if (body.signMethod !== "XML" || !xml || !/^\d{12}$/.test(body.organisation?.bin ?? "")) { + return send(400, { error: "Bad request", message: "signMethod XML, organisation.bin and documentsToSign[0].documentXml are required" }); + } + const id = randomUUID(); + const expiresAt = Date.now() + 5 * 60_000; + this.sessions.set(id, { documentXml: xml, polls: 0, signer: { ...this.signer }, expiresAt }); + return send(201, { + session_id: id, + qr_content: `mobileSign:https://sign.aitu.uz/mock/mgovSign/${id}`, + deeplink: `https://m.egov.kz/mobileSign?link=${encodeURIComponent(`https://sign.aitu.uz/mock/mgovSign/${id}`)}`, + expires_at: new Date(expiresAt).toISOString(), + }); + } + const m = /^\/v1\/egov\/([^/]+)\/status$/.exec(url); + if (method === "GET" && m) { + const s = this.sessions.get(decodeURIComponent(m[1]!)); + if (!s) return send(404, { error: "Not found", message: "Session not found" }); + const expiresIn = Math.max(0, Math.round((s.expiresAt - Date.now()) / 1000)); + if (expiresIn === 0) return send(200, { status: "expired", expires_in: 0 }); + s.polls += 1; + if (s.polls < 3) return send(200, { status: s.polls === 1 ? "scanned" : "pending", expires_in: expiresIn }); + if (s.signer.reject) return send(200, { status: "rejected", expires_in: expiresIn }); + const doc = s.signer.tamper ? s.documentXml.replace(/[^<]*<\/challenge>/, "other") : s.documentXml; + const signed = doc.replace( + "", + `MOCK_NOT_A_SIGNATURE` + + `${mockCertificate(s.signer)}`, + ); + return send(200, { status: "completed", expires_in: expiresIn, signedDocuments: [{ id: 1, nameRu: "Mock (not signed)", documentXml: signed }] }); + } + send(404, { error: "Not found" }); + } +} + +if (import.meta.main) { + const relay = new MockKazedsRelay({ iin: process.env.MOCK_EGOV_IIN ?? "900101300126", name: process.env.MOCK_EGOV_NAME ?? "ТЕСТОВ ТЕСТ" }); + const url = await relay.start(Number(process.argv[2] ?? process.env.MOCK_PORT ?? 3103)); + console.log(`mock-kazeds-relay (TEST ONLY, fake signatures): KAZEDS_RELAY_BASE=${url}`); +} diff --git a/packages/testkit/test/egov.test.ts b/packages/testkit/test/egov.test.ts new file mode 100644 index 00000000..374704e6 --- /dev/null +++ b/packages/testkit/test/egov.test.ts @@ -0,0 +1,109 @@ +// PEP-65: eGov QR login through the KazEDS relay (mock-kazeds-relay): link an IIN, log in by it, +// unknown IIN, tampered document, refusal, expiry, IIN taken by another account. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { core, db, teardown } from "./helpers.ts"; +import { mockCertificate, MockKazedsRelay } from "../src/mock-kazeds-relay.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const relay = new MockKazedsRelay({ iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" }); + +let asel: Awaited>; +let dana: Awaited>; +before(async () => { + process.env.KAZEDS_RELAY_BASE = await relay.start(); + asel = await core.upsertUserFromGitea(db, { id: 651, login: "mock-asel" }, { access_token: "x" }); + dana = await core.upsertUserFromGitea(db, { id: 652, login: "mock-dana" }, { access_token: "x" }); +}); +after(async () => { + await relay.stop(); + await teardown(); +}); + +/** The phone scans and signs: the relay answers scanned, pending, then the result. */ +async function scanAndSign(handle: string) { + assert.equal(await core.egovFlowStatus(db, handle), "scanned"); + assert.equal(await core.egovFlowStatus(db, handle), "pending"); +} + +describe("eGov QR", () => { + test("certificate subject: IIN and name, issuer does not leak into the subject", () => { + const s = core.certificateSubject(Buffer.from(mockCertificate({ iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" }), "base64")); + assert.equal(s.serialNumber, "IIN900101300126"); + assert.equal(s.commonName, "ТЕСТОВА АСЕЛЬ"); + assert.ok(core.isValidIin("900101300126")); + assert.ok(!core.isValidIin("900101300123")); + }); + + test("unlinked IIN: signed, but no login", async () => { + const f = await core.startEgovFlow(db, "login"); + assert.match(f.qrContent, /^mobileSign:/); + assert.match(f.deeplink, /^https:\/\/m\.egov\.kz\//); + await scanAndSign(f.handle); + await assert.rejects(core.completeEgovFlow(db, f.handle), /не привязан к Пеппе/); + await assert.rejects(core.completeEgovFlow(db, f.handle), /истёк/, "one-shot"); + }); + + test("link from Settings, then log in by eGov", async () => { + await assert.rejects(core.startEgovFlow(db, "link", null), /после входа/); + const link = await core.startEgovFlow(db, "link", asel.id); + await scanAndSign(link.handle); + const r = await core.completeEgovFlow(db, link.handle); + assert.equal(r.purpose, "link"); + assert.equal(r.user.egovIin, "900101300126"); + assert.equal(r.identity.name, "ТЕСТОВА АСЕЛЬ"); + assert.equal(core.maskIin(r.user.egovIin!), "9001****0126"); + + const login = await core.startEgovFlow(db, "login"); + await scanAndSign(login.handle); + const l = await core.completeEgovFlow(db, login.handle); + assert.equal(l.purpose, "login"); + assert.equal(l.user.id, asel.id); + }); + + test("not signed yet → error, and the flow is spent", async () => { + const f = await core.startEgovFlow(db, "login"); + await assert.rejects(core.completeEgovFlow(db, f.handle), /ещё не подписан/); + assert.equal(await core.egovFlowStatus(db, f.handle), "expired"); + }); + + test("tampered document and refusal are rejected", async () => { + relay.signer = { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ", tamper: true }; + const t = await core.startEgovFlow(db, "login"); + await scanAndSign(t.handle); + await assert.rejects(core.completeEgovFlow(db, t.handle), /не тот документ/); + + relay.signer = { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ", reject: true }; + const r = await core.startEgovFlow(db, "login"); + await scanAndSign(r.handle); + assert.equal(await core.egovFlowStatus(db, r.handle), "rejected"); + await assert.rejects(core.completeEgovFlow(db, r.handle), /отменено/); + relay.signer = { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" }; + }); + + test("expired flow and unknown handle", async () => { + const f = await core.startEgovFlow(db, "login"); + const key = `egov.flow:${core.hashToken(f.handle)}`; + const saved = (await core.getSetting<{ expiresAt: number }>(db, key))!; + await core.setSetting(db, key, { ...saved, expiresAt: Date.now() - 1 }); + assert.equal(await core.egovFlowStatus(db, f.handle), "expired"); + await assert.rejects(core.completeEgovFlow(db, f.handle), /истёк/); + assert.equal(await core.egovFlowStatus(db, "no-such-handle"), "expired"); + }); + + test("an IIN links to one account only; unlink frees it", async () => { + const f = await core.startEgovFlow(db, "link", dana.id); + await scanAndSign(f.handle); + await assert.rejects(core.completeEgovFlow(db, f.handle), /уже привязан к другой учётке/); + await assert.rejects(core.linkEgovIin(db, dana.id, "123"), /Неверный ИИН/); + await core.linkEgovIin(db, asel.id, null); + assert.equal((await core.linkEgovIin(db, dana.id, "900101300126")).egovIin, "900101300126"); + }); + + test("relay errors surface as Peppa errors", async () => { + const real = process.env.KAZEDS_RELAY_BASE; + process.env.KAZEDS_RELAY_BASE = `${real}/missing`; + await assert.rejects(core.startEgovFlow(db, "login"), /eGov relay/); + process.env.KAZEDS_RELAY_BASE = real; + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8dc0351c..fd7784b5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -235,6 +235,9 @@ importers: next: specifier: 16.4.6 version: 16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + qrcode: + specifier: 1.5.4 + version: 1.5.4 react: specifier: 19.3.1 version: 19.3.1 @@ -248,6 +251,9 @@ importers: '@tailwindcss/postcss': specifier: 4.3.5 version: 4.3.5 + '@types/qrcode': + specifier: 1.5.5 + version: 1.5.5 '@types/react': specifier: 19.3.0 version: 19.3.0 @@ -1215,6 +1221,9 @@ packages: '@types/node@26.6.6': resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + '@types/qrcode@1.5.5': + resolution: {integrity: sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==} + '@types/react-dom@19.3.0': resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} peerDependencies: @@ -1238,6 +1247,14 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + baseline-browser-mapping@2.11.35: resolution: {integrity: sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ==} engines: {node: '>=6.0.0'} @@ -1262,6 +1279,10 @@ packages: resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} engines: {node: '>= 0.4'} + camelcase@5.3.1: + resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==} + engines: {node: '>=6'} + caniuse-lite@1.0.30001826: resolution: {integrity: sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==} @@ -1271,10 +1292,20 @@ packages: client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} + cliui@6.0.0: + resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==} + clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + content-disposition@2.0.1: resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==} engines: {node: '>=18'} @@ -1315,6 +1346,10 @@ packages: supports-color: optional: true + decamelize@1.2.0: + resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==} + engines: {node: '>=0.10.0'} + depd@2.0.0: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} @@ -1323,6 +1358,9 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dijkstrajs@1.0.3: + resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==} + drizzle-kit@0.31.11: resolution: {integrity: sha512-YCYqxTLIB2OCqf6w9/Vef13baBVbwQIPcbT4Y56AfO6B9ajZhDhD8Jkveg/hJvT/iuMloKD/IYYkyMMNhr7Kqg==} hasBin: true @@ -1429,6 +1467,9 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + encodeurl@2.0.1: resolution: {integrity: sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==} engines: {node: '>= 0.8'} @@ -1499,6 +1540,10 @@ packages: resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} engines: {node: '>= 18.0.0'} + find-up@4.1.0: + resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} + engines: {node: '>=8'} + forwarded@0.2.0: resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} engines: {node: '>= 0.6'} @@ -1520,6 +1565,10 @@ packages: peerDependencies: next: '>=13.2.0' + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + get-intrinsic@1.3.0: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} @@ -1569,6 +1618,10 @@ packages: resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} engines: {node: '>= 0.10'} + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + is-promise@4.0.0: resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} @@ -1662,6 +1715,10 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + locate-path@5.0.0: + resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} + engines: {node: '>=8'} + lucide-react@1.72.0: resolution: {integrity: sha512-fbF5i1GU8GODETa3Q7rXqrJrcx3iPYrQtxthom103zGx+Z0BGwKYAW9s+9435ohYJ7hQm0av0PoZcqI1CRwNrg==} peerDependencies: @@ -1742,10 +1799,26 @@ packages: once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + p-limit@2.3.0: + resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} + engines: {node: '>=6'} + + p-locate@4.1.0: + resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} + engines: {node: '>=8'} + + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + parseurl@1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} @@ -1760,6 +1833,10 @@ packages: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} + pngjs@5.0.0: + resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==} + engines: {node: '>=10.13.0'} + postcss@8.5.23: resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==} engines: {node: ^10 || ^12 || >=14} @@ -1776,6 +1853,11 @@ packages: resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} + qrcode@1.5.4: + resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==} + engines: {node: '>=10.13.0'} + hasBin: true + qs@6.17.1: resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} @@ -1797,10 +1879,17 @@ packages: resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} engines: {node: '>=0.10.0'} + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + require-from-string@2.0.2: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} + require-main-filename@2.0.0: + resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} + resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} @@ -1827,6 +1916,9 @@ packages: resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} engines: {node: '>= 18'} + set-blocking@2.0.0: + resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} + setprototypeof@1.2.0: resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} @@ -1878,6 +1970,14 @@ packages: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + styled-jsx@5.1.6: resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==} engines: {node: '>= 12.0.0'} @@ -1933,14 +2033,32 @@ packages: resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} engines: {node: '>= 0.8'} + which-module@2.0.1: + resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==} + which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} hasBin: true + wrap-ansi@6.2.0: + resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} + engines: {node: '>=8'} + wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + y18n@4.0.3: + resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} + + yargs-parser@18.1.3: + resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} + engines: {node: '>=6'} + + yargs@15.4.1: + resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==} + engines: {node: '>=8'} + zod-to-json-schema@3.25.2: resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} peerDependencies: @@ -2460,6 +2578,10 @@ snapshots: dependencies: undici-types: 8.9.0 + '@types/qrcode@1.5.5': + dependencies: + '@types/node': 26.6.6 + '@types/react-dom@19.3.0(@types/react@19.3.0)': dependencies: '@types/react': 19.3.0 @@ -2484,6 +2606,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + baseline-browser-mapping@2.11.35: {} body-parser@2.4.0: @@ -2514,6 +2642,8 @@ snapshots: call-bind-apply-helpers: 1.0.2 get-intrinsic: 1.3.0 + camelcase@5.3.1: {} + caniuse-lite@1.0.30001826: {} class-variance-authority@0.7.1: @@ -2522,8 +2652,20 @@ snapshots: client-only@0.0.1: {} + cliui@6.0.0: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 6.2.0 + clsx@2.1.1: {} + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + content-disposition@2.0.1: {} content-type@1.0.5: {} @@ -2551,10 +2693,14 @@ snapshots: dependencies: ms: 2.1.3 + decamelize@1.2.0: {} + depd@2.0.0: {} detect-libc@2.1.2: {} + dijkstrajs@1.0.3: {} + drizzle-kit@0.31.11: dependencies: '@drizzle-team/brocli': 0.10.2 @@ -2574,6 +2720,8 @@ snapshots: ee-first@1.1.1: {} + emoji-regex@8.0.0: {} + encodeurl@2.0.1: {} enhanced-resolve@5.26.1: @@ -2738,6 +2886,11 @@ snapshots: transitivePeerDependencies: - supports-color + find-up@4.1.0: + dependencies: + locate-path: 5.0.0 + path-exists: 4.0.0 + forwarded@0.2.0: {} fresh@2.0.0: {} @@ -2751,6 +2904,8 @@ snapshots: dependencies: next: 16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + get-caller-file@2.0.5: {} + get-intrinsic@1.3.0: dependencies: call-bind-apply-helpers: 1.0.2 @@ -2803,6 +2958,8 @@ snapshots: ipaddr.js@1.9.1: {} + is-fullwidth-code-point@3.0.0: {} + is-promise@4.0.0: {} isexe@2.0.0: {} @@ -2864,6 +3021,10 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + locate-path@5.0.0: + dependencies: + p-locate: 4.1.0 + lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1): dependencies: react: 19.3.1 @@ -2931,8 +3092,20 @@ snapshots: dependencies: wrappy: 1.0.2 + p-limit@2.3.0: + dependencies: + p-try: 2.2.0 + + p-locate@4.1.0: + dependencies: + p-limit: 2.3.0 + + p-try@2.2.0: {} + parseurl@1.3.3: {} + path-exists@4.0.0: {} + path-key@3.1.1: {} path-to-regexp@8.4.2: {} @@ -2941,6 +3114,8 @@ snapshots: pkce-challenge@5.0.1: {} + pngjs@5.0.0: {} + postcss@8.5.23: dependencies: nanoid: 3.3.20 @@ -2960,6 +3135,12 @@ snapshots: forwarded: 0.2.0 ipaddr.js: 1.9.1 + qrcode@1.5.4: + dependencies: + dijkstrajs: 1.0.3 + pngjs: 5.0.0 + yargs: 15.4.1 + qs@6.17.1: dependencies: es-define-property: 1.0.1 @@ -2981,8 +3162,12 @@ snapshots: react@19.3.1: {} + require-directory@2.1.1: {} + require-from-string@2.0.2: {} + require-main-filename@2.0.0: {} + resolve-pkg-maps@1.0.0: {} router@2.2.0: @@ -3027,6 +3212,8 @@ snapshots: transitivePeerDependencies: - supports-color + set-blocking@2.0.0: {} + setprototypeof@1.2.0: {} sharp@0.35.5(@types/node@26.6.6): @@ -3108,6 +3295,16 @@ snapshots: statuses@2.0.2: {} + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + styled-jsx@5.1.6(react@19.3.1): dependencies: client-only: 0.0.1 @@ -3143,12 +3340,41 @@ snapshots: vary@1.1.2: {} + which-module@2.0.1: {} + which@2.0.2: dependencies: isexe: 2.0.0 + wrap-ansi@6.2.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrappy@1.0.2: {} + y18n@4.0.3: {} + + yargs-parser@18.1.3: + dependencies: + camelcase: 5.3.1 + decamelize: 1.2.0 + + yargs@15.4.1: + dependencies: + cliui: 6.0.0 + decamelize: 1.2.0 + find-up: 4.1.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + require-main-filename: 2.0.0 + set-blocking: 2.0.0 + string-width: 4.2.3 + which-module: 2.0.1 + y18n: 4.0.3 + yargs-parser: 18.1.3 + zod-to-json-schema@3.25.2(zod@4.6.7): dependencies: zod: 4.6.7 -- 2.45.2 From f958777e1169e7ab8e251c3fcd0b19727ddf9fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 01:14:11 +0500 Subject: [PATCH 036/536] PEP-65: archive OpenSpec change pep-65-egov-login Co-Authored-By: Claude Opus 5.5 --- .../2026-11-14-pep-65-egov-login}/design.md | 0 .../2026-11-14-pep-65-egov-login}/proposal.md | 0 .../specs/web-auth/spec.md | 0 .../2026-11-14-pep-65-egov-login}/tasks.md | 0 openspec/specs/web-auth/spec.md | 37 +++++++++++++++++++ 5 files changed, 37 insertions(+) rename openspec/changes/{pep-65-egov-login => archive/2026-11-14-pep-65-egov-login}/design.md (100%) rename openspec/changes/{pep-65-egov-login => archive/2026-11-14-pep-65-egov-login}/proposal.md (100%) rename openspec/changes/{pep-65-egov-login => archive/2026-11-14-pep-65-egov-login}/specs/web-auth/spec.md (100%) rename openspec/changes/{pep-65-egov-login => archive/2026-11-14-pep-65-egov-login}/tasks.md (100%) diff --git a/openspec/changes/pep-65-egov-login/design.md b/openspec/changes/archive/2026-11-14-pep-65-egov-login/design.md similarity index 100% rename from openspec/changes/pep-65-egov-login/design.md rename to openspec/changes/archive/2026-11-14-pep-65-egov-login/design.md diff --git a/openspec/changes/pep-65-egov-login/proposal.md b/openspec/changes/archive/2026-11-14-pep-65-egov-login/proposal.md similarity index 100% rename from openspec/changes/pep-65-egov-login/proposal.md rename to openspec/changes/archive/2026-11-14-pep-65-egov-login/proposal.md diff --git a/openspec/changes/pep-65-egov-login/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-65-egov-login/specs/web-auth/spec.md similarity index 100% rename from openspec/changes/pep-65-egov-login/specs/web-auth/spec.md rename to openspec/changes/archive/2026-11-14-pep-65-egov-login/specs/web-auth/spec.md diff --git a/openspec/changes/pep-65-egov-login/tasks.md b/openspec/changes/archive/2026-11-14-pep-65-egov-login/tasks.md similarity index 100% rename from openspec/changes/pep-65-egov-login/tasks.md rename to openspec/changes/archive/2026-11-14-pep-65-egov-login/tasks.md diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md index 55893de9..537dd60b 100644 --- a/openspec/specs/web-auth/spec.md +++ b/openspec/specs/web-auth/spec.md @@ -81,3 +81,40 @@ - **WHEN** администратор убирает «dana» из списка разрешённых, а она не участник проектов - **THEN** её следующий запрос к вебу ведёт на страницу входа - **AND** запрос её MCP-клиента получает 401 + +### Requirement: Вход через eGov QR +Страница входа SHALL предлагать «Войти через eGov»: Пеппа создаёт сессию подписи в relay +KazEDS, показывает QR и ссылку для eGov Mobile и после подписи входит под пользователем, +к которому привязан ИИН из сертификата подписанта. Подписанный документ SHALL содержать +ровно challenge и nonce, созданные сервером для этого потока; поток одноразовый и живёт +5 минут. + +#### Scenario: Вход по QR +- **GIVEN** у пользователя «asel» привязан ИИН 900101300126 и вход ему разрешён +- **WHEN** он выбирает «Войти через eGov» и подписывает QR в eGov Mobile +- **THEN** он входит в Пеппу как «asel» + +#### Scenario: ИИН не привязан +- **WHEN** QR подписал человек, чей ИИН не привязан ни к одному пользователю +- **THEN** вход отклонён с подсказкой привязать eGov в «Настройках» после входа через Gitea + +#### Scenario: Подменённый документ +- **WHEN** в подписанном XML нет challenge или nonce этого потока +- **THEN** вход отклонён, поток удалён + +#### Scenario: Отказ или истечение +- **WHEN** пользователь отменил подпись в eGov Mobile или QR истёк +- **THEN** страница входа показывает причину и предлагает новый QR + +### Requirement: Привязка ИИН +Пользователь SHALL привязывать к своей учётке ИИН, подписав QR в «Настройках → eGov», и +отвязывать его там же. Один ИИН привязан не больше чем к одной учётке. + +#### Scenario: Привязка +- **GIVEN** пользователь вошёл через Gitea +- **WHEN** он нажимает «Привязать eGov» и подписывает QR +- **THEN** в «Настройках» виден его ИИН (частично скрытый) и дальше он может входить через eGov + +#### Scenario: ИИН уже занят +- **WHEN** пользователь подписывает QR ИИН, привязанным к другой учётке +- **THEN** привязка отклонена -- 2.45.2 From 0194f7f6e4cc30b6fc86a2ebdf978ea7c9219653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 01:25:16 +0500 Subject: [PATCH 037/536] testkit: remove each test file's temp dir on teardown (runs had piled up ~1 GB) Co-Authored-By: Claude Opus 5.5 --- packages/testkit/test/helpers.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index f61e4ad4..547ae835 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -3,7 +3,7 @@ // Import this before anything that pulls in @peppa/runner (statically or via @peppa/bot): // runner modules read PEPPA_TMUX_SOCKET / PEPPA_HOME when they load. import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, readFileSync, existsSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, existsSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -43,6 +43,9 @@ export async function teardown() { try { execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-server"], { stdio: "ignore" }); } catch {} + // Every run left its temp dir behind (~1 GB after a few hundred runs filled the disk); + // PEPPA_KEEP_TEST_TMP=1 keeps it for debugging. + if (!process.env.PEPPA_KEEP_TEST_TMP) rmSync(TMP, { recursive: true, force: true }); } export async function waitFor(label: string, fn: () => Promise, timeoutMs = 25000): Promise { -- 2.45.2 From 616ce28c70403c5e25e7605baf6808dc1b37676f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 02:10:53 +0500 Subject: [PATCH 038/536] =?UTF-8?q?infra:=20one=20compose=20project=20`pep?= =?UTF-8?q?pa`=20(postgres,=20bugsink,=20act-runner)=20=E2=80=94=20one=20g?= =?UTF-8?q?roup=20in=20OrbStack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runner and Bugsink ran from compose files in old worktrees (projects peppa-ci, peppa-bugsink). Container names and the runner's registration volume are kept. scripts/infra-up.sh, pnpm infra:up. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +-- infra/act-runner/docker-compose.yml | 30 --------------- infra/bugsink/docker-compose.yml | 31 ---------------- infra/docker-compose.yml | 57 +++++++++++++++++++++++++++++ package.json | 4 +- scripts/bugsink-up.sh | 2 +- scripts/infra-up.sh | 9 +++++ 7 files changed, 72 insertions(+), 67 deletions(-) delete mode 100644 infra/act-runner/docker-compose.yml delete mode 100644 infra/bugsink/docker-compose.yml create mode 100755 scripts/infra-up.sh diff --git a/AGENTS.md b/AGENTS.md index 975a8a58..ae2959b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,11 +25,11 @@ - агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP) - **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp` - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member -- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` +- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` - **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ``, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` -- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) +- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) - Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены») - **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH @@ -54,7 +54,7 @@ интеграции (какой доступ, у кого). ## Команды -- `pnpm db:generate` (новая миграция из схемы) / `pnpm db:migrate` (= `peppa db migrate`); `peppa db migrate-to-sqlite ` — одноразовый перенос из Postgres `DATABASE_URL` (только чтение, сверка строк и внешних ключей; старая pg-схема — `packages/cli/legacy-pg-migrations`); `pnpm db:up` — Postgres для Bugsink +- `pnpm db:generate` (новая миграция из схемы) / `pnpm db:migrate` (= `peppa db migrate`); `peppa db migrate-to-sqlite ` — одноразовый перенос из Postgres `DATABASE_URL` (только чтение, сверка строк и внешних ключей; старая pg-схема — `packages/cli/legacy-pg-migrations`); `scripts/infra-up.sh [сервис…]` (`pnpm infra:up`) — все docker-сервисы Пеппы одним compose-проектом `peppa` (`infra/docker-compose.yml`: postgres для Bugsink, bugsink, act-runner; секреты из `.env`). Gitea, Traefik и деплои проектов в него не входят - `peppa project create [--existing]` — проект в Gitea (`provisionProject` в runner, тот же код, что у веба); `peppa project owner ` - `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы - `peppa web login-link ` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea diff --git a/infra/act-runner/docker-compose.yml b/infra/act-runner/docker-compose.yml deleted file mode 100644 index 00395d56..00000000 --- a/infra/act-runner/docker-compose.yml +++ /dev/null @@ -1,30 +0,0 @@ -# act_runner для Gitea Actions проектов Пеппы (PEP-57). -# Метка `peppa-trusted`: job'ы идут в контейнерах с docker.sock хоста (сборка образов и -# деплой). Поэтому раннер регистрируется ТОЛЬКО на репозитории проектов Пеппы: на -# пользователя peppa-bot (его репо) и по одному на репо проекта другого владельца -# (`peppa ci connect`). Глобальной (инстанс) регистрации нет и быть не должно. -# docker compose -f infra/act-runner/docker-compose.yml up -d -# scripts/ci-runner-register.sh peppa-bot — регистрация на репо peppa-bot -name: peppa-ci -services: - act-runner: - image: gitea/act_runner:0.2.11 - container_name: peppa-act-runner - restart: unless-stopped - entrypoint: ["/sbin/tini", "--", "/peppa/supervise.sh"] - environment: - # Gitea в той же docker-сети Traefik — раннер ходит к ней напрямую, мимо Cloudflare. - GITEA_INSTANCE_URL: http://gitea:3000 - volumes: - - ./config.yaml:/etc/act_runner/config.yaml:ro - - ./supervise.sh:/peppa/supervise.sh:ro - - ./register.sh:/usr/local/bin/peppa-runner-register:ro - - peppa-act-runner:/data - - /var/run/docker.sock:/var/run/docker.sock - networks: - - traefik_default -volumes: - peppa-act-runner: -networks: - traefik_default: - external: true diff --git a/infra/bugsink/docker-compose.yml b/infra/bugsink/docker-compose.yml deleted file mode 100644 index 752f8b6f..00000000 --- a/infra/bugsink/docker-compose.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Bugsink (PEP-58): self-hosted error tracker, Sentry SDK compatible. -# Its database is `bugsink` in Peppa's Postgres (container peppa-postgres, network peppa_default). -# Secrets come from Peppa's .env: scripts/bugsink-up.sh runs -# docker compose --env-file /.env -f infra/bugsink/docker-compose.yml up -d -name: peppa-bugsink -services: - bugsink: - image: bugsink/bugsink:2.6.3 - container_name: peppa-bugsink - restart: unless-stopped - ports: - - "127.0.0.1:3180:8000" - environment: - SECRET_KEY: ${BUGSINK_SECRET_KEY:?BUGSINK_SECRET_KEY in .env} - DATABASE_URL: postgresql://bugsink:${BUGSINK_DB_PASSWORD:?BUGSINK_DB_PASSWORD in .env}@peppa-postgres:5432/bugsink - CREATE_SUPERUSER: ${BUGSINK_ADMIN_EMAIL:-admin@telecom.quest}:${BUGSINK_ADMIN_PASSWORD:?BUGSINK_ADMIN_PASSWORD in .env} - BASE_URL: ${BUGSINK_PUBLIC_URL:-https://bugsink.telecom.quest} - # Cloudflare terminates TLS, Traefik forwards plain HTTP. - BEHIND_HTTPS_PROXY: "true" - USER_REGISTRATION: "closed" - PHONEHOME: "false" - # Alerts go to Peppa on the host (http://host.docker.internal:3100/api/hooks/bugsink/…), a non-global address. - ALERTS_WEBHOOK_DENY_NON_GLOBAL: "false" - TIME_ZONE: Europe/Moscow - extra_hosts: - - "host.docker.internal:host-gateway" - networks: [peppa] -networks: - peppa: - name: peppa_default - external: true diff --git a/infra/docker-compose.yml b/infra/docker-compose.yml index 7c87a922..9e950b63 100644 --- a/infra/docker-compose.yml +++ b/infra/docker-compose.yml @@ -1,3 +1,9 @@ +# Peppa's docker services in one compose project `peppa` (one group in OrbStack): +# postgres — Bugsink's database (Peppa itself is on SQLite since PEP-36) +# bugsink — error tracker of the factory's projects (PEP-58), 127.0.0.1:3180 +# act-runner — Gitea Actions runner of Peppa's projects, label `peppa-trusted` (PEP-57) +# Gitea, Traefik and the projects' deployments (`-`) are not part of it. +# Secrets come from Peppa's .env: scripts/infra-up.sh [service…] name: peppa services: postgres: @@ -12,5 +18,56 @@ services: - "127.0.0.1:5433:5432" volumes: - peppa-pg:/var/lib/postgresql/data + + bugsink: + image: bugsink/bugsink:2.6.3 + container_name: peppa-bugsink + restart: unless-stopped + depends_on: [postgres] + ports: + - "127.0.0.1:3180:8000" + environment: + SECRET_KEY: ${BUGSINK_SECRET_KEY:?BUGSINK_SECRET_KEY in .env} + DATABASE_URL: postgresql://bugsink:${BUGSINK_DB_PASSWORD:?BUGSINK_DB_PASSWORD in .env}@peppa-postgres:5432/bugsink + CREATE_SUPERUSER: ${BUGSINK_ADMIN_EMAIL:-admin@telecom.quest}:${BUGSINK_ADMIN_PASSWORD:?BUGSINK_ADMIN_PASSWORD in .env} + BASE_URL: ${BUGSINK_PUBLIC_URL:-https://bugsink.telecom.quest} + # Cloudflare terminates TLS, Traefik forwards plain HTTP. + BEHIND_HTTPS_PROXY: "true" + USER_REGISTRATION: "closed" + PHONEHOME: "false" + # Alerts go to Peppa on the host (http://host.docker.internal:3100/api/hooks/bugsink/…), a non-global address. + ALERTS_WEBHOOK_DENY_NON_GLOBAL: "false" + TIME_ZONE: Europe/Moscow + extra_hosts: + - "host.docker.internal:host-gateway" + + # Jobs run in containers with the host's docker.sock (image builds, deploys), so the runner is + # registered ONLY on Peppa's project repos: on peppa-bot (its repos) and one per repo of another + # owner (`peppa ci connect`). Never an instance-wide registration. + # scripts/ci-runner-register.sh peppa-bot — registration on peppa-bot's repos + act-runner: + image: gitea/act_runner:0.2.11 + container_name: peppa-act-runner + restart: unless-stopped + entrypoint: ["/sbin/tini", "--", "/peppa/supervise.sh"] + environment: + # Gitea is on Traefik's docker network: the runner reaches it directly, not via Cloudflare. + GITEA_INSTANCE_URL: http://gitea:3000 + volumes: + - ./act-runner/config.yaml:/etc/act_runner/config.yaml:ro + - ./act-runner/supervise.sh:/peppa/supervise.sh:ro + - ./act-runner/register.sh:/usr/local/bin/peppa-runner-register:ro + - peppa-act-runner:/data + - /var/run/docker.sock:/var/run/docker.sock + networks: + - traefik_default + volumes: peppa-pg: + # Registration (.runner) of the runner from the former `peppa-ci` project: kept as is. + peppa-act-runner: + name: peppa-ci_peppa-act-runner + +networks: + traefik_default: + external: true diff --git a/package.json b/package.json index 624b8c79..3b4c9ac9 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,8 @@ "packageManager": "pnpm@12.18.0", "scripts": { "dev:web": "pnpm --filter @peppa/web dev", - "db:up": "docker compose -f infra/docker-compose.yml up -d", - "db:down": "docker compose -f infra/docker-compose.yml down", + "infra:up": "scripts/infra-up.sh", + "infra:down": "docker compose --env-file .env -f infra/docker-compose.yml down", "db:generate": "pnpm --filter @peppa/db generate", "db:migrate": "pnpm --filter @peppa/db migrate", "typecheck": "pnpm -r typecheck", diff --git a/scripts/bugsink-up.sh b/scripts/bugsink-up.sh index c9b7e35f..0bacd847 100755 --- a/scripts/bugsink-up.sh +++ b/scripts/bugsink-up.sh @@ -33,7 +33,7 @@ if [ -z "$($PG -c "select 1 from pg_database where datname='bugsink'")" ]; then echo "created database bugsink" fi -docker compose --env-file "$ENV_FILE" -f "$ROOT/infra/bugsink/docker-compose.yml" up -d +PEPPA_ENV_FILE="$ENV_FILE" "$ROOT/scripts/infra-up.sh" postgres bugsink for i in $(seq 1 60); do curl -sf http://127.0.0.1:3180/health/ready >/dev/null && break sleep 2 diff --git a/scripts/infra-up.sh b/scripts/infra-up.sh new file mode 100755 index 00000000..e9562820 --- /dev/null +++ b/scripts/infra-up.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Peppa's docker services (infra/docker-compose.yml, compose project `peppa`): postgres, bugsink, +# act-runner. Secrets for Bugsink come from Peppa's .env. +# Usage: scripts/infra-up.sh [service…] (default: all) +# PEPPA_ENV_FILE=~/peppa/shared/.env scripts/infra-up.sh +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +ENV_FILE="${PEPPA_ENV_FILE:-$ROOT/.env}" +exec docker compose --env-file "$ENV_FILE" -f "$ROOT/infra/docker-compose.yml" up -d --remove-orphans "$@" -- 2.45.2 From 13ad9cb51e7eb92ff8cc5317af3c9d5190fd450b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 02:24:37 +0500 Subject: [PATCH 039/536] Platform release offers switch: no "deploy to prod?" for Peppa before the launch peppa platform release-offers on|off (setting platform.release_offers, default on). Off closes the open offer and hides the button on the project's releases tab. Turned off now: Peppa runs as next dev from the working copy and has no prod yet. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- apps/web/app/(app)/p/[key]/page.tsx | 4 ++-- packages/cli/src/index.ts | 10 +++++++++- packages/runner/src/deploy.ts | 4 ++-- packages/runner/src/platform-release.ts | 19 +++++++++++++++++-- .../testkit/test/platform-release.test.ts | 19 +++++++++++++++++++ 6 files changed, 50 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ae2959b7..8fc34a47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ - **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем -- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже +- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже - **Прод Пеппы (PEP-18, для будущего официального прода)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh `: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT` - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 51a33231..67c7e3bc 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,6 +1,6 @@ import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket } from "lucide-react"; -import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, type Release } from "@peppa/runner"; +import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, platformReleaseOffers, type Release } from "@peppa/runner"; import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; @@ -73,7 +73,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr currentReleases(db, p.id), ]); // Peppa itself has no staging: its prod candidate is the newest green main (PEP-18). - const prodCandidate = isPlatform(p) ? await platformReleaseCandidate(db, p) : (current.staging?.sha ?? null); + const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null); const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase())); // Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway). const noRepoAccess = (login: string) => diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 15d03db6..bbd52019 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -42,7 +42,7 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb, migrateDb } from "@peppa/db"; -import { answerAndDeliver, connectCi, deployProd, listReleases, recordRelease, type ReleaseStatus, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { loadEnv } from "@peppa/shared"; @@ -73,6 +73,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa session stop peppa session resume [-p ] (new generation, claude --resume) peppa platform allowlist | allow | deny (who may log into Peppa) + peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch) peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist) peppa status (services, outbox, runners, questions, admins) peppa telegram pair | status | unpair (users normally pair in web Settings) @@ -407,6 +408,13 @@ async function main(): Promise { console.log(`${u.login} (#${u.id})`); break; } + case "platform release-offers": { + // PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch. + if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on"); + else if (args[0]) throw new PeppaError("usage: peppa platform release-offers [on|off]"); + console.log(`выкатка Пеппы в прод: ${(await platformReleaseOffers(db)) ? "предлагается" : "выключена"}`); + break; + } case "user egov": { // PEP-65: link (or unlink with "-") the IIN a user logs in with through eGov QR. if (!args[0] || !args[1]) throw new PeppaError("usage: peppa user egov <ИИН|->"); diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 1f7b4ac7..296b7909 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -58,12 +58,12 @@ export async function currentReleases(db: Db, projectId: number): Promise (sha ? sha.slice(0, 7) : "—"); /** Closes earlier unanswered "deploy to prod?" offers of the project: a newer staging is up. */ -export async function expireProdOffers(db: Db, projectId: number) { +export async function expireProdOffers(db: Db, projectId: number, reason = "(неактуально: на staging новый релиз)") { const open = await db .select() .from(questions) .where(and(eq(questions.projectId, projectId), isNull(questions.taskId), isNull(questions.answeredAt), sql`exists (select 1 from json_each(${questions.options}) where value = ${PROD_OPTION})`)); - for (const q of open) await answerQuestion(db, q.id, "(неактуально: на staging новый релиз)", "system").catch(() => {}); + for (const q of open) await answerQuestion(db, q.id, reason, "system").catch(() => {}); } /** Records one step of a deploy and tells the PM what they need to know. */ diff --git a/packages/runner/src/platform-release.ts b/packages/runner/src/platform-release.ts index 83aaf046..86618441 100644 --- a/packages/runner/src/platform-release.ts +++ b/packages/runner/src/platform-release.ts @@ -3,7 +3,7 @@ // `launchctl`), so the PM's button queues a request on this host and the launchd agent // quest.telecom.peppa.release runs scripts/peppa-release.sh, which reports back through // `peppa release report` → recordRelease (same releases table and PM messages as projects). -import { askPmProject, configuredChecks, summarizeChecks, PeppaError, type Project } from "@peppa/core"; +import { askPmProject, configuredChecks, getProject, getSetting, setSetting, summarizeChecks, PeppaError, type Project } from "@peppa/core"; import { checkRuns, releases, type Db } from "@peppa/db"; import { peppaHome } from "@peppa/shared"; import { and, desc, eq } from "drizzle-orm"; @@ -54,9 +54,24 @@ export const platformReleaseCandidate = (db: Db, project: Project) => greenMainS const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—"); +const OFFERS = "platform.release_offers"; + +/** + * Whether Peppa offers "deploy to prod" after a green main (and shows the button). Off before the + * official launch: Peppa then runs as `next dev` from the working copy and there is no prod yet. + */ +export async function platformReleaseOffers(db: Db): Promise { + return (await getSetting(db, OFFERS)) ?? true; +} + +export async function setPlatformReleaseOffers(db: Db, on: boolean): Promise { + await setSetting(db, OFFERS, on); + if (!on) await expireProdOffers(db, (await getProject(db, platformKey())).id, "(выкатка в прод выключена до запуска)"); +} + /** A green report of main: offer the PM to release that commit (once per commit). */ export async function offerPlatformRelease(db: Db, project: Project, sha: string): Promise { - if (!isPlatform(project) || (await greenMainSha(db, project, sha)) !== sha) return false; + if (!isPlatform(project) || !(await platformReleaseOffers(db)) || (await greenMainSha(db, project, sha)) !== sha) return false; const { prod } = await currentReleases(db, project.id); if (prod?.sha === sha) return false; await expireProdOffers(db, project.id); diff --git a/packages/testkit/test/platform-release.test.ts b/packages/testkit/test/platform-release.test.ts index de6a7cbd..88a03f27 100644 --- a/packages/testkit/test/platform-release.test.ts +++ b/packages/testkit/test/platform-release.test.ts @@ -258,4 +258,23 @@ describe("Прод из релизного каталога", () => { symlinkSync(viaCurrent, join(localBin, "probe")); assert.equal(execFileSync("bash", [join(localBin, "probe")], { encoding: "utf8" }).trim(), join(RELEASES, "current")); }); + + test("Scenario: Выключено — после зелёного main вопроса нет, открытый закрыт; включено — снова есть", async () => { + const offers = async () => (await core.pendingQuestions(db, proj.id)).filter((q) => q.options?.includes(runner.PROD_OPTION)); + const first = merge(`${pep.key}-offers-1`); + await greenMain(first); + assert.equal((await offers()).length, 1); + + await runner.setPlatformReleaseOffers(db, false); + assert.equal(await runner.platformReleaseOffers(db), false); + assert.equal((await offers()).length, 0, "the open offer is closed"); + const second = merge(`${pep.key}-offers-2`); + await greenMain(second); + assert.equal((await offers()).length, 0, "no offer while off"); + + await runner.setPlatformReleaseOffers(db, true); + const third = merge(`${pep.key}-offers-3`); + await greenMain(third); + assert.equal((await offers()).length, 1); + }); }); -- 2.45.2 From 414e4500e41e75da7aedeb1f498f21f202998b4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:20:21 +0500 Subject: [PATCH 040/536] =?UTF-8?q?PEP-68:=20local=20users=20without=20Git?= =?UTF-8?q?ea=20=E2=80=94=20password=20login,=20superadmin=20management?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - users.password_hash/password_set_at/disabled_at (migration 0002_local_users) - core/local-users.ts: scrypt, passwordLogin with attempt limits, create/reset/disable - isSuperadmin(db, user) = platform.admins; isUserAllowed honours disabled_at - web: /auth/password + login form, /users for superadmins, Settings → password - Gitea login with a local user's login is refused (giteaLoginRefusal) - local users: projects in peppa-bot namespace, members without Gitea collaboration - CLI: peppa user add|passwd|disable|enable; tests in testkit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- apps/web/app/(app)/actions.ts | 63 +- apps/web/app/(app)/help/page.tsx | 3 +- apps/web/app/(app)/layout.tsx | 4 +- apps/web/app/(app)/projects/new/page.tsx | 52 +- apps/web/app/(app)/settings/page.tsx | 57 +- apps/web/app/(app)/users/page.tsx | 92 + apps/web/app/auth/callback/route.ts | 5 +- apps/web/app/auth/password/route.ts | 25 + apps/web/app/login/page.tsx | 16 +- apps/web/components/Sidebar.tsx | 10 +- openspec/changes/pep-68-local-users/design.md | 60 + .../changes/pep-68-local-users/proposal.md | 43 + .../pep-68-local-users/specs/web-auth/spec.md | 78 + openspec/changes/pep-68-local-users/tasks.md | 10 + packages/cli/src/index.ts | 48 + packages/core/src/access.ts | 26 +- packages/core/src/index.ts | 1 + packages/core/src/local-users.ts | 154 ++ packages/core/src/monitor.ts | 6 + packages/db/migrations/0002_local_users.sql | 3 + .../db/migrations/meta/0002_snapshot.json | 2293 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 5 + packages/mcp/src/manager.ts | 6 +- packages/runner/src/provision.ts | 12 +- packages/runner/src/share.ts | 16 + packages/testkit/test/local-users.test.ts | 171 ++ 28 files changed, 3220 insertions(+), 49 deletions(-) create mode 100644 apps/web/app/(app)/users/page.tsx create mode 100644 apps/web/app/auth/password/route.ts create mode 100644 openspec/changes/pep-68-local-users/design.md create mode 100644 openspec/changes/pep-68-local-users/proposal.md create mode 100644 openspec/changes/pep-68-local-users/specs/web-auth/spec.md create mode 100644 openspec/changes/pep-68-local-users/tasks.md create mode 100644 packages/core/src/local-users.ts create mode 100644 packages/db/migrations/0002_local_users.sql create mode 100644 packages/db/migrations/meta/0002_snapshot.json create mode 100644 packages/testkit/test/local-users.test.ts diff --git a/AGENTS.md b/AGENTS.md index 8fc34a47..b46e9221 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,10 +23,11 @@ - Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3) - `peppa session resume ` → `claude --resume` - агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP) -- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp` +- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные пользователи (PEP-68), кроме отключённых; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp` - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` - **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ``, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` +- **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из stdin или сгенерированный) - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index c99694e0..e1a0e926 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -5,7 +5,6 @@ import { createTask, getQuestion, getSession, - giteaForUser, PeppaError, projectForUser, resolveTask, @@ -18,10 +17,17 @@ import { getProject as getProjectByKey, updateIncidentSettings, type IncidentPolicy, + changeOwnPassword, + createLocalUser, + getUser, + isLocalUser, + isSuperadmin, + setUserDisabled, + setUserPassword, } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; -import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, projectNamespace, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -115,11 +121,8 @@ export async function messageSession(f: FormData) { export async function createProjectAction(f: FormData) { const user = await requireUser(); await attempt(f, async () => { - const owner = str(f, "owner") || user.login; const p = await provisionProject(db, { - gitea: await giteaForUser(db, user), - owner, - ownerIsUser: owner === user.login, + ...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot slug: str(f, "slug").toLowerCase(), key: str(f, "key"), name: str(f, "name"), @@ -288,3 +291,51 @@ export async function resolveIncidentAction(f: FormData) { await resolveIncident(db, i.id, { who: user.login, release: str(f, "release") || null }); }); } + +// ── local users (PEP-68) ──────────────────────────────────────────────────────────── + +/** Superadmin-only actions: everybody else gets "not found", nothing changes. */ +async function requireSuperadmin() { + const user = await requireUser(); + if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено"); + return user; +} + +export async function createLocalUserAction(f: FormData) { + await attempt(f, async () => { + await requireSuperadmin(); + const u = await createLocalUser(db, { login: str(f, "login"), name: str(f, "name"), password: String(f.get("password") ?? "") }); + return `/users?created=${encodeURIComponent(u.login)}`; + }); +} + +export async function resetUserPasswordAction(f: FormData) { + await attempt(f, async () => { + await requireSuperadmin(); + const u = await getUser(db, Number(str(f, "userId"))); + if (!u || !isLocalUser(u)) throw new PeppaError("Пароль задаётся только локальным пользователям"); + await setUserPassword(db, u.id, String(f.get("password") ?? "")); + return `/users?reset=${encodeURIComponent(u.login)}`; + }); +} + +export async function setUserDisabledAction(f: FormData) { + await attempt(f, async () => { + const admin = await requireSuperadmin(); + const u = await getUser(db, Number(str(f, "userId"))); + if (!u) throw new PeppaError("Не найдено"); + if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя"); + await setUserDisabled(db, u.id, str(f, "disabled") === "1"); + }); +} + +export async function changePasswordAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + if (!isLocalUser(user)) throw new PeppaError("Вы входите через Gitea — пароль меняется там"); + const next = String(f.get("newPassword") ?? ""); + if (next !== String(f.get("confirm") ?? "")) throw new PeppaError("Новый пароль и повтор не совпадают"); + await changeOwnPassword(db, user, String(f.get("current") ?? ""), next); + return "/settings?password=changed"; + }); +} diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 2885ebf5..1d0d40c5 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -52,6 +52,7 @@ export default async function Help() {
  • Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
  • Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
  • Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
  • +
  • Локальные пользователи — аккаунты Пеппы без Gitea: входят по логину и паролю на странице входа, создаёт их суперадмин в разделе «Пользователи», пароль меняется в «Настройках». Их добавляют в участники по логину Пеппы; доступа к репозиторию в Gitea у них нет — код только через Пеппу, а их новые проекты создаются в пространстве peppa-bot.
  • Раннер — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, задача, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).
  • Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
  • @@ -61,7 +62,7 @@ export default async function Help() {

    Адрес сервера:

    {mcp}
      -
    • ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через Gitea и нажмите «Разрешить». В чате включите коннектор Peppa.
    • +
    • ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите (Gitea, eGov или логин и пароль) и нажмите «Разрешить». В чате включите коннектор Peppa.
    • Codex, Claude и другие MCP-клиенты: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.
    • Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в Настройках.
    • Чтобы агенты работали на вашей подписке, подключите Claude в Настройках.
    • diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index edb6e78a..e3205fb0 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,4 +1,6 @@ import type { ReactNode } from "react"; +import { isSuperadmin } from "@peppa/core"; +import { db } from "@/lib/db"; import { requireUser } from "@/lib/auth"; import { navCounts } from "@/lib/queries"; import { Sidebar } from "@/components/Sidebar"; @@ -11,7 +13,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) { const counts = await navCounts(user.id); return (
      - +
      {children}
      ); diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx index d216fda7..809f66d6 100644 --- a/apps/web/app/(app)/projects/new/page.tsx +++ b/apps/web/app/(app)/projects/new/page.tsx @@ -1,4 +1,4 @@ -import { giteaForUser, type GiteaOrg } from "@peppa/core"; +import { giteaForUser, isLocalUser, type GiteaOrg } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { Flash, PageHeader } from "@/components/common"; import { Hidden } from "@/components/cards"; @@ -24,10 +24,15 @@ export default async function NewProject({ searchParams }: { searchParams: Promi let orgs: GiteaOrg[] = []; let giteaError: string | undefined; const giteaUrl = loadEnv().GITEA_URL.replace(/^https?:\/\//, ""); - try { - orgs = await (await giteaForUser(db, user)).orgsWithRepoCreate(user.login); - } catch (e) { - giteaError = (e as Error).message; + // PEP-68: a local user has no Gitea account — the repo is created in peppa-bot's namespace. + const local = isLocalUser(user); + const botLogin = process.env.GITEA_BOT_USER ?? "peppa-bot"; + if (!local) { + try { + orgs = await (await giteaForUser(db, user)).orgsWithRepoCreate(user.login); + } catch (e) { + giteaError = (e as Error).message; + } } return ( @@ -50,20 +55,29 @@ export default async function NewProject({ searchParams }: { searchParams: Promi - -

      - Репозиторий будет {giteaUrl}/<пространство>/<slug>. В личном пространстве приватный репозиторий видите - только вы, peppa-bot и участники проекта; в организации — ещё её участники с доступом к репозиториям. - {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."} -

      + {local ? ( +

      + У вас нет аккаунта Gitea — репозиторий будет {giteaUrl}/{botLogin}/<slug>. Доступ к коду — только через + Пеппу (агенты, PR, проверки); соавтором в Gitea вас добавить нельзя. +

      + ) : ( + <> + +

      + Репозиторий будет {giteaUrl}/<пространство>/<slug>. В личном пространстве приватный репозиторий видите + только вы, peppa-bot и участники проекта; в организации — ещё её участники с доступом к репозиториям. + {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."} +

      + + )}
      Видимость Приватный — только те, кому выдан доступ diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index b63272f3..1e1ed210 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,16 +1,16 @@ import { ExternalLink } from "lucide-react"; -import { connectedApps, maskIin } from "@peppa/core"; +import { connectedApps, isLocalUser, isSuperadmin, maskIin, MIN_PASSWORD } from "@peppa/core"; import { pendingClaudeSetup } from "@peppa/runner"; import { Hidden } from "@/components/cards"; import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; -import { Input } from "@/components/ui/input"; +import { Input, Label } from "@/components/ui/input"; import { EgovSign } from "@/components/EgovSign"; import { Workspace } from "@/components/Workspace"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unlinkEgov, unpairTelegramAction } from "../actions"; +import { changePasswordAction, cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unlinkEgov, unpairTelegramAction } from "../actions"; const back = { back: "/settings" }; @@ -27,9 +27,11 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?: ); } -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string; egov?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string; egov?: string; password?: string }> }) { const user = await requireUser(); - const { error, claude, egov } = await searchParams; + const { error, claude, egov, password } = await searchParams; + const local = isLocalUser(user); + const superadmin = await isSuperadmin(db, user); const setup = await pendingClaudeSetup(db, user.id); const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); @@ -38,6 +40,51 @@ export default async function Settings({ searchParams }: { searchParams: Promise
      +
      + {password === "changed" && Пароль изменён} + {local ? ( + +

      + {user.login} — локальный пользователь Пеппы, нет аккаунта Gitea. Доступ к коду проектов — только через Пеппу + (агенты, PR, проверки); соавтором репозитория в Gitea вас добавить нельзя, новые проекты создаются в пространстве{" "} + peppa-bot. +

      +
      + + +
      + + + +
      + + +
      + ) : ( + Вы входите через Gitea{user.egovIin ? " или eGov" : ""}; пароль Пеппы не нужен. + )} + {superadmin && ( + + Пользователи + + } + > + Локальные пользователи без Gitea: создать, сбросить пароль, отключить. + + )} +
      {claude === "connected" && Claude подключён} {setup ? ( diff --git a/apps/web/app/(app)/users/page.tsx b/apps/web/app/(app)/users/page.tsx new file mode 100644 index 00000000..45a80060 --- /dev/null +++ b/apps/web/app/(app)/users/page.tsx @@ -0,0 +1,92 @@ +import { notFound } from "next/navigation"; +import { isLocalUser, isSuperadmin, listUsers, MIN_PASSWORD, platformAdmins } from "@peppa/core"; +import { Hidden } from "@/components/cards"; +import { ago, Flash, Notice, PageHeader, Section } from "@/components/common"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Input, Label } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { createLocalUserAction, resetUserPasswordAction, setUserDisabledAction } from "../actions"; + +const back = { back: "/users" }; + +/** Superadmin only (PEP-68): local users without Gitea — create, reset password, disable. */ +export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string; created?: string; reset?: string }> }) { + const me = await requireUser(); + if (!(await isSuperadmin(db, me))) notFound(); + const { error, created, reset } = await searchParams; + const all = await listUsers(db); + const admins = new Set(await platformAdmins(db)); + return ( + +
      + + {created && Пользователь «{created}» создан — передайте ему логин и временный пароль, сменить его можно в «Настройках».} + {reset && Пароль «{reset}» сброшен — передайте новый временный пароль.} + + Локальные пользователи входят по логину и паролю, без аккаунта Gitea. Отключённый пользователь сразу теряет сессии веба и MCP. + + +
      + +
      + +
      + + + +
      + + +
      +
      + +
      + {all.map((u) => { + const local = isLocalUser(u); + return ( + +
      + {u.login} + {u.name && {u.name}} + {local ? "локальный" : "Gitea"} + {admins.has(u.login.toLowerCase()) && суперадмин} + {u.disabledAt && отключён} + {local && !u.passwordHash && без пароля} + {u.lastLoginAt ? `вход ${ago(u.lastLoginAt)}` : "ещё не входил"} +
      +
      + {local && ( +
      + + + + + )} + {u.id !== me.id && ( +
      + + + + )} +
      +
      + ); + })} +
      +
      +
      + ); +} diff --git a/apps/web/app/auth/callback/route.ts b/apps/web/app/auth/callback/route.ts index 219964c2..2d55a257 100644 --- a/apps/web/app/auth/callback/route.ts +++ b/apps/web/app/auth/callback/route.ts @@ -1,4 +1,4 @@ -import { exchangeOAuthCode, getUserByLogin, GiteaClient, isLoginAllowed, isUserAllowed, upsertUserFromGitea } from "@peppa/core"; +import { exchangeOAuthCode, getUserByLogin, giteaLoginRefusal, GiteaClient, isLoginAllowed, isUserAllowed, upsertUserFromGitea } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { cookies } from "next/headers"; import { NextResponse, type NextRequest } from "next/server"; @@ -17,6 +17,9 @@ export async function GET(req: NextRequest) { try { const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`); const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me(); + // PEP-68: a local user's login is never merged with a Gitea account; disabled users stay out. + const refusal = await giteaLoginRefusal(db, me.login); + if (refusal) return fail(refusal); const existing = await getUserByLogin(db, me.login); if (!(await isLoginAllowed(db, me.login)) && !(existing && (await isUserAllowed(db, existing)))) { return fail("Нет доступа к Пеппе — попросите администратора"); diff --git a/apps/web/app/auth/password/route.ts b/apps/web/app/auth/password/route.ts new file mode 100644 index 00000000..a52b22d0 --- /dev/null +++ b/apps/web/app/auth/password/route.ts @@ -0,0 +1,25 @@ +import { passwordLogin } from "@peppa/core"; +import { headers } from "next/headers"; +import { NextResponse, type NextRequest } from "next/server"; +import { publicOrigin, safeNext, sessionCookie } from "@/lib/auth"; +import { db } from "@/lib/db"; + +/** Login + password form of /login (PEP-68): local users without Gitea. */ +export async function POST(req: NextRequest) { + const origin = await publicOrigin(); + const f = await req.formData(); + const next = safeNext(String(f.get("next") ?? "")); + const login = String(f.get("login") ?? ""); + const h = await headers(); + const ip = h.get("cf-connecting-ip") ?? h.get("x-forwarded-for")?.split(",")[0]?.trim() ?? h.get("x-real-ip") ?? null; + const r = await passwordLogin(db, login, String(f.get("password") ?? ""), ip); + if (!r.ok) { + const q = new URLSearchParams({ error: r.error, login: login.slice(0, 64) }); + if (next !== "/") q.set("next", next); + return NextResponse.redirect(`${origin}/login?${q}`, 303); + } + const res = NextResponse.redirect(`${origin}${next}`, 303); + const c = sessionCookie(r.user.id); + res.cookies.set(c.name, c.value, c.options); + return res; +} diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 2c11bff9..490dde30 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -5,11 +5,12 @@ import { Flash } from "@/components/common"; import { EgovSign } from "@/components/EgovSign"; import { Footer } from "@/components/Footer"; import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; export const dynamic = "force-dynamic"; -export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) { - const { error, next } = await searchParams; +export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string; login?: string }> }) { + const { error, next, login } = await searchParams; if (await currentUser()) redirect(safeNext(next)); return (
      @@ -21,6 +22,17 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ Войти через Gitea +
      + + или по логину Пеппы + +
      +
      + + + + +
      diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 61d3d5ab..2ac0416d 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, type LucideIcon } from "lucide-react"; +import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, Users, type LucideIcon } from "lucide-react"; import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; @@ -14,6 +14,8 @@ interface Item { icon: LucideIcon; match: (p: string) => boolean; count?: "questions" | "waitingRunners"; + /** Superadmin only (PEP-68); desktop panel only — on phones it is linked from Settings. */ + admin?: boolean; } const ITEMS: Item[] = [ @@ -21,12 +23,13 @@ const ITEMS: Item[] = [ { href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, { href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, + { href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true }, { href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") }, ]; const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" }; /** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */ -export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number> }) { +export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number>; superadmin?: boolean }) { const path = usePathname(); return (
      @@ -38,7 +41,7 @@ export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl aria-label="Разделы" className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur md:static md:flex md:flex-col md:gap-0.5 md:border-0 md:bg-transparent md:pb-0 md:backdrop-blur-none" > - {ITEMS.map((i) => { + {ITEMS.filter((i) => !i.admin || superadmin).map((i) => { const active = i.match(path); const n = i.count ? counts[i.count] : 0; return ( @@ -47,6 +50,7 @@ export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl href={i.href} aria-current={active ? "page" : undefined} className={cn( + i.admin && "max-md:hidden", "relative flex flex-col items-center gap-0.5 px-1 pt-2 pb-1.5 text-[10px] text-muted-foreground transition-colors hover:text-foreground hover:no-underline md:flex-row md:gap-2 md:rounded-md md:px-2.5 md:py-1.5 md:text-sm md:hover:bg-accent", active && "font-medium text-foreground md:bg-accent md:before:absolute md:before:inset-y-1.5 md:before:-left-3 md:before:w-0.5 md:before:rounded-full md:before:bg-primary", )} diff --git a/openspec/changes/pep-68-local-users/design.md b/openspec/changes/pep-68-local-users/design.md new file mode 100644 index 00000000..5837d5e6 --- /dev/null +++ b/openspec/changes/pep-68-local-users/design.md @@ -0,0 +1,60 @@ +# Design: PEP-68 + +## Модель + +- `users.password_hash` — `scrypt$N$r$p$$` (N=16384, r=8, p=1, соль 16 + байт, ключ 64 байта); сравнение `timingSafeEqual`. Параметры в строке — можно поднять + стоимость позже без миграции. +- `users.password_set_at`, `users.disabled_at`. +- Локальный пользователь — `gitea_id < 0` (как было для `mock-…`): случайный отрицательный + id, по нему нельзя прийти из OAuth Gitea. Создаёт только суперадмин (веб) или + администратор машины (CLI) — значит, `isUserAllowed` пускает его без allowlist, пока + он не отключён. Отключение (`disabled_at`) действует на любого пользователя, в том + числе вошедшего через Gitea: `currentUser` и `/mcp` проверяют `isUserAllowed` на + каждый запрос, поэтому сессии и токены перестают работать сразу. + +## Суперадмин + +`isSuperadmin(db, user)` = логин в `platform.admins` (`platformAdmins`, по умолчанию — +allowlist). Экспортируется из core; его же использует PEP-67. Суперадмин не может +отключить сам себя. + +## Вход по паролю + +- `POST /auth/password` (форма, работает без JS) → `passwordLogin(db, login, password, ip)`. +- Неизвестный логин, нет пароля, неверный пароль, отключён — одна ошибка «Неверный логин + или пароль»; scrypt считается и для неизвестного логина (по фиктивному хэшу), чтобы + время ответа не выдавало существование логина. +- Попытки: неудачи считаются в `settings` (`auth.fail:login:`, `auth.fail:ip:`), + окно 15 минут; 5 неудач по логину или 20 по IP → пауза 15 минут («Слишком много + попыток…» — одинаково для существующих и несуществующих логинов). Успешный вход + сбрасывает счётчик логина. IP — `cf-connecting-ip`, затем первый `x-forwarded-for`. +- Пароль ≥ 8 символов. + +## Временный пароль + +Суперадмин сам вводит временный пароль при создании / сбросе и передаёт его человеку; +пользователь меняет его в «Настройках». Одноразовую ссылку «задать пароль» не делаем: +пришлось бы показывать её после редиректа (в URL или во flash-cookie), а временный +пароль решает задачу проще. CLI `peppa user add` / `passwd` читает пароль из stdin, если +он не терминал, иначе генерирует и печатает. + +## Логины Gitea и локальные + +Логин локального пользователя при создании проверяется только на уникальность в Пеппе +(в Gitea не ходим: создание не зависит от сети и от того, есть ли в Gitea служебный +`admin`). Защита — в колбэке OAuth: если логин из Gitea занят локальным пользователем +(`gitea_id < 0`), вход отклоняется: «Логин … занят локальным пользователем Пеппы — войдите +по паролю». Привязку Gitea к локальному аккаунту из «Настроек» не делаем: после привязки +пользователь перестал бы быть локальным (`gitea_id > 0`), и его доступ (сейчас — «создан +суперадмином») пришлось бы хранить отдельным флагом, а логин мог бы разойтись с логином +Gitea. Это отдельная стори, если понадобится. + +## Что может локальный пользователь + +- Доска, стори, ответы агентам, участник проектов: `shareProject` сначала ищет локального + пользователя Пеппы с таким логином — его добавляют участником без соавторства в Gitea + (`repoAccess: false`). +- Новый проект: репо создаётся в пространстве `peppa-bot` клиентом бота; выбора + пространства нет. В «Настройках» и на странице нового проекта — «нет аккаунта Gitea: + доступ к коду только через Пеппу». diff --git a/openspec/changes/pep-68-local-users/proposal.md b/openspec/changes/pep-68-local-users/proposal.md new file mode 100644 index 00000000..819dde3f --- /dev/null +++ b/openspec/changes/pep-68-local-users/proposal.md @@ -0,0 +1,43 @@ +# Proposal: PEP-68 — локальные пользователи без Gitea + +Задача Пеппы: **PEP-68**. + +## Why + +Не у всех пользователей Пеппы есть (и должен быть) аккаунт Gitea: первый такой — +суперадмин `admin` (PEP-67). Локальные аккаунты в модели уже есть (`users.gitea_id < 0`), +но войти под ними можно только одноразовой ссылкой из CLI. + +## What Changes + +- Вход по логину и паролю на `/login` рядом с «Войти через Gitea» и eGov. Пароль — scrypt + (`node:crypto`) с солью в `users.password_hash`; одинаковая ошибка «Неверный логин или + пароль»; ограничение попыток по логину и по IP (5 / 20 за 15 минут → пауза 15 минут). +- Суперадмин (`platform.admins`, helper `isSuperadmin(db, user)` в core): раздел + «Пользователи» — создать локального пользователя с временным паролем, сбросить пароль, + отключить / включить. Отключённый (`users.disabled_at`) теряет сессии веба и MCP сразу. +- «Настройки → Пароль»: смена своего пароля (старый + новый). Для локального пользователя + в «Настройках» видно «нет аккаунта Gitea». +- Логины не склеиваются: вход через Gitea с логином локального пользователя — отказ с + понятной ошибкой. +- Локальный пользователь создаёт проект в пространстве `peppa-bot` (клиентом бота) и может + быть участником проектов (добавление по логину Пеппы, без соавторства в Gitea). +- CLI: `peppa user add [--admin] [--name <имя>]`, `peppa user passwd `, + `peppa user disable ` (и `enable`). + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `web-auth`: вход по паролю, локальные пользователи и их управление суперадмином, + отключение пользователя, отказ при совпадении логина Gitea с локальным. + +## Impact + +- Миграция: `users.password_hash`, `users.password_set_at`, `users.disabled_at`. +- core: `local-users.ts` (пароли, попытки, создание/отключение), `isSuperadmin`, + `isUserAllowed` учитывает отключение. +- web: `/auth/password`, форма входа, `/users`, «Настройки → Пароль», меню. +- runner: `shareProject` принимает логин локального пользователя. +- cli: `peppa user add|passwd|disable|enable`. diff --git a/openspec/changes/pep-68-local-users/specs/web-auth/spec.md b/openspec/changes/pep-68-local-users/specs/web-auth/spec.md new file mode 100644 index 00000000..fe5a2b2a --- /dev/null +++ b/openspec/changes/pep-68-local-users/specs/web-auth/spec.md @@ -0,0 +1,78 @@ +## ADDED Requirements + +### Requirement: Вход по логину и паролю +Страница входа SHALL предлагать вход по логину и паролю для локальных пользователей Пеппы +(без аккаунта Gitea). Пароль хранится только как хэш scrypt с солью. Любая причина +отказа (нет логина, нет пароля, неверный пароль, пользователь отключён) SHALL давать одно +и то же сообщение «Неверный логин или пароль». После 5 неудачных попыток по логину или +20 по IP за 15 минут вход по паролю приостанавливается на 15 минут. + +#### Scenario: Вход по паролю +- **GIVEN** суперадмин создал локального пользователя «admin» с паролем +- **WHEN** admin вводит логин и пароль на странице входа +- **THEN** он входит в Пеппу без Gitea + +#### Scenario: Неверный пароль +- **GIVEN** локальный пользователь «kate» +- **WHEN** на странице входа введён логин «kate» и неверный пароль +- **THEN** вход отклонён с сообщением «Неверный логин или пароль» +- **AND** для несуществующего логина сообщение такое же + +#### Scenario: Пауза после 5 попыток +- **GIVEN** для логина «kate» было 5 неудачных попыток за 15 минут +- **WHEN** вводится даже верный пароль +- **THEN** вход отклонён с сообщением о слишком частых попытках + +### Requirement: Управление локальными пользователями +Суперадмин (логин в `platform.admins`) SHALL создавать локальных пользователей (логин, +имя, временный пароль), сбрасывать им пароль и отключать или включать пользователей в +разделе «Пользователи»; остальным раздел недоступен. Администратор машины SHALL делать +то же через CLI `peppa user add|passwd|disable|enable`. Логин локального пользователя +уникален в Пеппе. + +#### Scenario: Создание пользователя +- **GIVEN** суперадмин «admin» +- **WHEN** он создаёт пользователя «kate» с временным паролем +- **THEN** kate может войти по этому паролю + +#### Scenario: Не суперадмин +- **WHEN** пользователь не из `platform.admins` открывает «Пользователи» или отправляет действие раздела +- **THEN** он получает «не найдено», данные не меняются + +#### Scenario: Отключённый пользователь +- **GIVEN** пользователь «kate» вошла в веб и подключила MCP-клиент +- **WHEN** суперадмин отключает её +- **THEN** её следующий запрос к вебу ведёт на страницу входа, запрос MCP-клиента получает 401 +- **AND** войти по паролю она не может + +### Requirement: Смена своего пароля +Локальный пользователь SHALL менять свой пароль в «Настройках», указав текущий и новый +(не короче 8 символов). + +#### Scenario: Смена пароля +- **WHEN** kate вводит текущий пароль и новый +- **THEN** дальше она входит только по новому паролю + +#### Scenario: Неверный текущий пароль +- **WHEN** текущий пароль указан неверно +- **THEN** пароль не меняется и показывается ошибка + +### Requirement: Логины Gitea не склеиваются с локальными +Вход через Gitea SHALL отклоняться, если логин аккаунта Gitea занят локальным +пользователем Пеппы. + +#### Scenario: Логин занят локальным пользователем +- **GIVEN** локальный пользователь «kate» +- **WHEN** аккаунт Gitea «kate» проходит вход через Gitea +- **THEN** сессия не создаётся и показывается, что логин занят локальным пользователем Пеппы + +### Requirement: Возможности локального пользователя +Локальный пользователь SHALL работать с досками, задачами и вопросами своих проектов и +быть участником чужих (добавляется по логину Пеппы, без доступа к репозиторию в Gitea). +Его новые проекты SHALL создаваться в пространстве `peppa-bot`. Веб SHALL показывать ему, +что аккаунта Gitea нет и доступ к коду — только через Пеппу. + +#### Scenario: Участник без Gitea +- **GIVEN** владелец проекта «PAY» и локальный пользователь «kate» +- **WHEN** владелец добавляет «kate» в участники +- **THEN** kate видит проект «PAY», соавтором репозитория в Gitea она не становится diff --git a/openspec/changes/pep-68-local-users/tasks.md b/openspec/changes/pep-68-local-users/tasks.md new file mode 100644 index 00000000..2a94053f --- /dev/null +++ b/openspec/changes/pep-68-local-users/tasks.md @@ -0,0 +1,10 @@ +# Tasks: PEP-68 + +- [x] 1.1 Схема: `users.password_hash`, `password_set_at`, `disabled_at`; миграция `pnpm db:generate` +- [x] 1.2 core: `local-users.ts` — scrypt, `passwordLogin` с ограничением попыток, `createLocalUser`, `setUserPassword`, `changeOwnPassword`, `setUserDisabled`; `isSuperadmin`; `isUserAllowed` учитывает отключение +- [x] 1.3 web: `POST /auth/password`, форма на `/login`; отказ в колбэке Gitea для логина локального пользователя +- [x] 1.4 web: `/users` для суперадмина (создать, сбросить пароль, отключить/включить), пункт меню; «Настройки → Пароль», «нет аккаунта Gitea» +- [x] 1.5 Проект локального пользователя в пространстве `peppa-bot`; `shareProject` для локальных логинов +- [x] 1.6 CLI `peppa user add|passwd|disable|enable` +- [x] 1.7 Тесты testkit: вход по паролю, неверный пароль и пауза, отключение, Gitea-логин занят, суперадмин, шеринг локальному +- [x] 1.8 AGENTS.md, «Помощь», `openspec validate` diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index bbd52019..e0c20672 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -27,6 +27,11 @@ import { getUserByLogin, linkEgovIin, maskIin, + createLocalUser, + generatePassword, + isLocalUser, + setUserDisabled, + setUserPassword, giteaForBot, setProjectOwner, getTaskDetails, @@ -77,6 +82,10 @@ const USAGE = `peppa — Peppa software factory CLI peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist) peppa status (services, outbox, runners, questions, admins) peppa telegram pair | status | unpair (users normally pair in web Settings) + peppa user add [--name <имя>] [--admin] (local user without Gitea, PEP-68; --admin → platform.admins) + peppa user passwd (new password of a local user) + peppa user disable|enable (disabled: no login, web sessions and MCP tokens stop working) + add/passwd read the password from stdin when it is not a terminal, otherwise generate and print one peppa user ensure mock- (local test user) peppa user egov <ИИН|-> (eGov QR login: link the IIN, "-" unlinks; users link it in web Settings) peppa web login-link (one-time admin login, 10 minutes) @@ -104,6 +113,8 @@ const { values: opts, positionals } = parseArgs({ mode: { type: "string" }, provider: { type: "string" }, model: { type: "string" }, + name: { type: "string" }, + admin: { type: "boolean" }, all: { type: "boolean" }, once: { type: "boolean" }, interval: { type: "string", default: "30" }, @@ -415,6 +426,34 @@ async function main(): Promise { console.log(`выкатка Пеппы в прод: ${(await platformReleaseOffers(db)) ? "предлагается" : "выключена"}`); break; } + case "user add": { + // PEP-68: a local user (no Gitea account) who logs in with login + password. + if (!args[0]) throw new PeppaError("usage: peppa user add [--name <имя>] [--admin]"); + const { password, generated } = await readPassword(); + const u = await createLocalUser(db, { login: args[0], name: opts.name, password }); + if (opts.admin) await setPlatformAdmins(db, [...(await platformAdmins(db)), u.login]); + console.log(`${u.login} (#${u.id}) создан${opts.admin ? ", суперадмин" : ""}`); + if (generated) console.log(`пароль: ${password}`); + break; + } + case "user passwd": { + const u = await getUserByLogin(db, args[0] ?? ""); + if (!u) throw new PeppaError("usage: peppa user passwd "); + if (!isLocalUser(u)) throw new PeppaError(`${u.login} входит через Gitea — пароль Пеппы ему не нужен`); + const { password, generated } = await readPassword(); + await setUserPassword(db, u.id, password); + console.log(`${u.login}: пароль изменён`); + if (generated) console.log(`пароль: ${password}`); + break; + } + case "user disable": + case "user enable": { + const u = await getUserByLogin(db, args[0] ?? ""); + if (!u) throw new PeppaError(`usage: peppa user ${cmd} `); + await setUserDisabled(db, u.id, cmd === "disable"); + console.log(`${u.login}: ${cmd === "disable" ? "отключён" : "включён"}`); + break; + } case "user egov": { // PEP-65: link (or unlink with "-") the IIN a user logs in with through eGov QR. if (!args[0] || !args[1]) throw new PeppaError("usage: peppa user egov <ИИН|->"); @@ -447,3 +486,12 @@ try { console.error(e instanceof PeppaError ? `peppa: ${e.message}` : e); process.exit(1); } + +/** Password for `user add|passwd`: the first line of stdin when piped, otherwise a generated one. */ +async function readPassword(): Promise<{ password: string; generated: boolean }> { + if (process.stdin.isTTY) return { password: generatePassword(), generated: true }; + const chunks: Buffer[] = []; + for await (const c of process.stdin) chunks.push(c as Buffer); + const password = Buffer.concat(chunks).toString("utf8").split(/\r?\n/)[0] ?? ""; + return password ? { password, generated: false } : { password: generatePassword(), generated: true }; +} diff --git a/packages/core/src/access.ts b/packages/core/src/access.ts index 18e3e4f6..3e5d0181 100644 --- a/packages/core/src/access.ts +++ b/packages/core/src/access.ts @@ -1,7 +1,7 @@ // Who may log into Peppa at all (web and remote MCP): an allowlist of Gitea logins, plus -// people invited to or members of a project, plus local accounts without Gitea (mock-…). -import { projectInvites, projectMembers, type Db } from "@peppa/db"; -import { eq } from "drizzle-orm"; +// people invited to or members of a project, plus local accounts without Gitea (PEP-68). +import { projectInvites, projectMembers, users, type Db } from "@peppa/db"; +import { eq, sql } from "drizzle-orm"; import { getSetting, setSetting } from "./settings.ts"; import type { User } from "./users.ts"; @@ -24,10 +24,26 @@ export async function isLoginAllowed(db: Db, login: string): Promise { return !!invite; } -/** An existing user keeps access while allowlisted, a project member, or a local account. */ +/** + * An existing user keeps access while not disabled and allowlisted, a project member, or a + * local account (PEP-68: created by a superadmin or the CLI, can't come from Gitea OAuth). + */ export async function isUserAllowed(db: Db, user: User): Promise { - if (user.giteaId < 0) return true; // local account (created by the CLI), can't come from Gitea OAuth + if (user.disabledAt) return false; + if (user.giteaId < 0) return true; if (await isLoginAllowed(db, user.login)) return true; const [m] = await db.select().from(projectMembers).where(eq(projectMembers.userId, user.id)).limit(1); return !!m; } + +/** + * Why a Gitea OAuth login must be refused before the user row is touched, or null (PEP-68): + * a local user's login is never silently merged with a Gitea account; a disabled user stays out. + */ +export async function giteaLoginRefusal(db: Db, login: string): Promise { + const [u] = await db.select().from(users).where(sql`lower(${users.login}) = ${login.toLowerCase()}`); + if (!u) return null; + if (u.giteaId < 0) return `Логин «${login}» занят локальным пользователем Пеппы — войдите по логину и паролю`; + if (u.disabledAt) return "Нет доступа к Пеппе — попросите администратора"; + return null; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a91133a0..002a890e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -18,3 +18,4 @@ export * from "./repo-info.ts"; export * from "./incidents.ts"; export * from "./ci.ts"; export * from "./egov.ts"; +export * from "./local-users.ts"; diff --git a/packages/core/src/local-users.ts b/packages/core/src/local-users.ts new file mode 100644 index 00000000..57fc7a80 --- /dev/null +++ b/packages/core/src/local-users.ts @@ -0,0 +1,154 @@ +// Local Peppa users without a Gitea account (PEP-68): password login with attempt limits, +// created, reset and disabled by a superadmin (web «Пользователи») or the machine CLI. +import { users, type Db } from "@peppa/db"; +import { eq, sql } from "drizzle-orm"; +import { randomBytes, randomInt, scrypt, timingSafeEqual } from "node:crypto"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; +import type { User } from "./users.ts"; + +export const BAD_CREDENTIALS = "Неверный логин или пароль"; +export const TOO_MANY_ATTEMPTS = "Слишком много попыток входа — попробуйте через 15 минут"; +export const MIN_PASSWORD = 8; + +// ── hashing ────────────────────────────────────────────────────────────────────────── + +const N = 16384; +const R = 8; +const P = 1; +const KEYLEN = 64; + +function scryptAsync(password: string, salt: Buffer, n: number, r: number, p: number): Promise { + return new Promise((resolve, reject) => + scrypt(password.normalize("NFKC"), salt, KEYLEN, { N: n, r, p, maxmem: 128 * n * r * 2 }, (e, key) => (e ? reject(e) : resolve(key))), + ); +} + +/** "scrypt$N$r$p$$" — parameters travel with the hash. */ +export async function hashPassword(password: string): Promise { + const salt = randomBytes(16); + const key = await scryptAsync(password, salt, N, R, P); + return `scrypt$${N}$${R}$${P}$${salt.toString("base64")}$${key.toString("base64")}`; +} + +export async function verifyPassword(password: string, stored: string | null | undefined): Promise { + const parts = (stored ?? DUMMY_HASH).split("$"); + if (parts.length !== 6 || parts[0] !== "scrypt") return false; + const [, n, r, p, salt, hash] = parts as [string, string, string, string, string, string]; + const expected = Buffer.from(hash, "base64"); + const key = await scryptAsync(password, Buffer.from(salt, "base64"), Number(n), Number(r), Number(p)); + return key.length === expected.length && timingSafeEqual(key, expected) && !!stored; +} + +// Hash of a random password: unknown logins cost the same scrypt as known ones. +const DUMMY_HASH = `scrypt$${N}$${R}$${P}$${Buffer.alloc(16).toString("base64")}$${Buffer.alloc(KEYLEN).toString("base64")}`; + +export function checkPasswordPolicy(password: string): void { + if (password.length < MIN_PASSWORD) throw new PeppaError(`Пароль — не короче ${MIN_PASSWORD} символов`); + if (password.length > 256) throw new PeppaError("Слишком длинный пароль"); +} + +/** A random temporary password (CLI), 16 characters without look-alikes. */ +export function generatePassword(): string { + const abc = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + return Array.from({ length: 16 }, () => abc[randomInt(abc.length)]).join(""); +} + +// ── attempt limits ─────────────────────────────────────────────────────────────────── + +const WINDOW_MS = 15 * 60_000; +const LOCK_MS = 15 * 60_000; +const MAX_PER_LOGIN = 5; +const MAX_PER_IP = 20; + +interface Failures { + count: number; + firstAt: number; + lockedUntil?: number; +} + +const loginKey = (login: string) => `auth.fail:login:${login.toLowerCase()}`; +const ipKey = (ip: string) => `auth.fail:ip:${ip}`; + +async function isLocked(db: Db, key: string, now: number): Promise { + const f = await getSetting(db, key); + return !!f?.lockedUntil && f.lockedUntil > now; +} + +async function recordFailure(db: Db, key: string, max: number, now: number): Promise { + const prev = await getSetting(db, key); + const fresh = !prev || now - prev.firstAt > WINDOW_MS || (prev.lockedUntil && prev.lockedUntil <= now); + const f: Failures = fresh ? { count: 1, firstAt: now } : { ...prev!, count: prev!.count + 1 }; + if (f.count >= max) f.lockedUntil = now + LOCK_MS; + await setSetting(db, key, f); +} + +export type PasswordLoginResult = { ok: true; user: User } | { ok: false; error: string }; + +/** + * Password login. Every failure reason gives the same message; 5 failures per login or 20 + * per IP within 15 minutes pause password login for 15 minutes (even with the right password). + */ +export async function passwordLogin(db: Db, loginInput: string, password: string, ip: string | null, now = Date.now()): Promise { + const login = loginInput.trim().toLowerCase(); + if (!login || !password) return { ok: false, error: BAD_CREDENTIALS }; + if ((await isLocked(db, loginKey(login), now)) || (ip && (await isLocked(db, ipKey(ip), now)))) { + return { ok: false, error: TOO_MANY_ATTEMPTS }; + } + const user = await userByLoginCi(db, login); + const valid = await verifyPassword(password, user?.passwordHash); + if (!user || !valid || user.disabledAt) { + await recordFailure(db, loginKey(login), MAX_PER_LOGIN, now); + if (ip) await recordFailure(db, ipKey(ip), MAX_PER_IP, now); + return { ok: false, error: BAD_CREDENTIALS }; + } + await deleteSetting(db, loginKey(login)); + await db.update(users).set({ lastLoginAt: new Date(now) }).where(eq(users.id, user.id)); + return { ok: true, user }; +} + +// ── management ─────────────────────────────────────────────────────────────────────── + +async function userByLoginCi(db: Db, login: string): Promise { + const [row] = await db.select().from(users).where(sql`lower(${users.login}) = ${login.toLowerCase()}`); + return row ?? null; +} + +export const isLocalUser = (u: Pick) => u.giteaId < 0; + +const LOGIN_RE = /^[a-z0-9][a-z0-9._-]{1,38}$/; + +/** A local user (negative gitea_id: can never come from Gitea OAuth). */ +export async function createLocalUser(db: Db, o: { login: string; name?: string | null; password: string }): Promise { + const login = o.login.trim().toLowerCase(); + if (!LOGIN_RE.test(login)) throw new PeppaError("Логин: 2–39 символов a–z, 0–9, точка, дефис, подчёркивание; начинается с буквы или цифры"); + checkPasswordPolicy(o.password); + if (await userByLoginCi(db, login)) throw new PeppaError(`Логин «${login}» уже занят`); + const passwordHash = await hashPassword(o.password); + for (let i = 0; i < 5; i++) { + const giteaId = -1 - randomInt(2 ** 47); + const [row] = await db + .insert(users) + .values({ giteaId, login, name: o.name?.trim() || null, passwordHash, passwordSetAt: new Date() }) + .onConflictDoNothing({ target: users.giteaId }) + .returning(); + if (row) return row; + } + throw new PeppaError("Не удалось создать пользователя"); +} + +/** Sets a password (superadmin reset / CLI). */ +export async function setUserPassword(db: Db, userId: number, password: string): Promise { + checkPasswordPolicy(password); + await db.update(users).set({ passwordHash: await hashPassword(password), passwordSetAt: new Date() }).where(eq(users.id, userId)); +} + +/** The user changes their own password: the current one must match. */ +export async function changeOwnPassword(db: Db, user: User, current: string, next: string): Promise { + if (!(await verifyPassword(current, user.passwordHash))) throw new PeppaError("Текущий пароль неверный"); + await setUserPassword(db, user.id, next); +} + +export async function setUserDisabled(db: Db, userId: number, disabled: boolean): Promise { + await db.update(users).set({ disabledAt: disabled ? new Date() : null }).where(eq(users.id, userId)); +} diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts index 33e0b686..ba584c31 100644 --- a/packages/core/src/monitor.ts +++ b/packages/core/src/monitor.ts @@ -107,6 +107,12 @@ export async function platformAdmins(db: Db): Promise { return (await getSetting(db, ADMINS)) ?? (await allowedLogins(db)); } +/** Superadmin of the platform (PEP-68, PEP-67): login in `platform.admins`. */ +export async function isSuperadmin(db: Db, user: Pick | null | undefined): Promise { + if (!user) return false; + return (await platformAdmins(db)).includes(user.login.toLowerCase()); +} + export async function setPlatformAdmins(db: Db, logins: string[] | null): Promise { if (logins === null) return deleteSetting(db, ADMINS); await setSetting(db, ADMINS, [...new Set(logins.map((l) => l.trim().toLowerCase()).filter(Boolean))].sort()); diff --git a/packages/db/migrations/0002_local_users.sql b/packages/db/migrations/0002_local_users.sql new file mode 100644 index 00000000..8552c1a0 --- /dev/null +++ b/packages/db/migrations/0002_local_users.sql @@ -0,0 +1,3 @@ +ALTER TABLE `users` ADD `password_hash` text;--> statement-breakpoint +ALTER TABLE `users` ADD `password_set_at` integer;--> statement-breakpoint +ALTER TABLE `users` ADD `disabled_at` integer; \ No newline at end of file diff --git a/packages/db/migrations/meta/0002_snapshot.json b/packages/db/migrations/meta/0002_snapshot.json new file mode 100644 index 00000000..c2eb386c --- /dev/null +++ b/packages/db/migrations/meta/0002_snapshot.json @@ -0,0 +1,2293 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "8c480919-f0f0-4006-b448-49eff5f43062", + "prevId": "3df631c2-f7e3-47a6-b923-5f85677db9c3", + "tables": { + "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 + } + }, + "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": {} + }, + "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 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "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" + } + }, + "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": {} + }, + "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 + }, + "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" + } + }, + "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 + }, + "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 + }, + "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": {}, + "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 + }, + "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": {} + }, + "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'" + }, + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {} + }, + "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 + }, + "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 + } + }, + "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 + }, + "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 + } + }, + "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" + } + }, + "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": {}, + "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 + }, + "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 + }, + "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 + } + }, + "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 3e1f3981..5d4b60ba 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1794600109462, "tag": "0001_egov_iin", "breakpoints": true + }, + { + "idx": 2, + "version": "6", + "when": 1794608096959, + "tag": "0002_local_users", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index e8ccca7e..d2efad7a 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -34,6 +34,11 @@ export const users = sqliteTable("users", { // eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN. egovIin: text("egov_iin").unique(), egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }), + // Local login (PEP-68): scrypt hash "scrypt$N$r$p$salt$hash" (core/local-users.ts). + passwordHash: text("password_hash"), + passwordSetAt: integer("password_set_at", { mode: "timestamp_ms" }), + // Disabled by a superadmin: no login, sessions and MCP tokens stop working. + disabledAt: integer("disabled_at", { mode: "timestamp_ms" }), createdAt: createdAt(), lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }), }); diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index e3a4424c..a2176106 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -5,7 +5,6 @@ import { createGoal, createTask, getGoal, - giteaForUser, updateGoal, getProject, getQuestion, @@ -32,7 +31,7 @@ import { } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, loadEnv } from "@peppa/shared"; -import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; +import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; import { and, asc, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; @@ -176,8 +175,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ }, false, async ({ name, slug, key, owner, existing, visibility }) => { - const ns = owner || user.login; - const p = await provisionProject(db, { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login, slug: slug.toLowerCase(), key, name, existing, visibility, ownerId: user.id }); + const p = await provisionProject(db, { ...(await projectNamespace(db, user, owner)), slug: slug.toLowerCase(), key, name, existing, visibility, ownerId: user.id }); const repo = await describeRepo(db, p, { fresh: true }); return [ `Created project ${p.key} — ${p.name}. ${webUrl}/p/${p.key}`, diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts index 67a46894..81204ef2 100644 --- a/packages/runner/src/provision.ts +++ b/packages/runner/src/provision.ts @@ -4,7 +4,7 @@ import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { createProject, PeppaError, type GiteaClient, type Project } from "@peppa/core"; +import { createProject, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { eq, or } from "drizzle-orm"; @@ -34,6 +34,16 @@ export interface ProvisionOptions { // Template files that stay in the template repo (RULES.md is loaded live by the runner). const TEMPLATE_SKIP = new Set([".git", "RULES.md", "README.md"]); +/** + * Where a user's new project goes: their namespace (or an org) with their Gitea client; a local + * user without Gitea (PEP-68) always gets peppa-bot's namespace and the bot client. + */ +export async function projectNamespace(db: Db, user: User, owner?: string | null): Promise> { + if (isLocalUser(user)) return { gitea: giteaForBot(), owner: process.env.GITEA_BOT_USER ?? "peppa-bot", ownerIsUser: true }; + const ns = owner || user.login; + return { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login }; +} + export async function provisionProject(db: Db, o: ProvisionOptions): Promise { const env = loadEnv(); const log = o.log ?? (() => {}); diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts index b4e667d1..78f4f16d 100644 --- a/packages/runner/src/share.ts +++ b/packages/runner/src/share.ts @@ -3,7 +3,9 @@ import { addMember, getUser, + getUserByLogin, giteaForBot, + isLocalUser, giteaForUser, PeppaError, removeMember, @@ -43,6 +45,13 @@ export async function shareProject(db: Db, actor: User, project: Project, loginI if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта"); const login = loginInput.trim().replace(/^@/, ""); if (!login) throw new PeppaError("Укажите логин Gitea"); + // PEP-68: a local Peppa user (no Gitea account) becomes a member without repo access. + const local = await localUser(db, login); + if (local) { + const status = await addMember(db, project, local.login, actor.id); + describeCache.delete(project.id); + return { login: local.login, status, repoAccess: false }; + } const clients = await repoAdmins(db, project); if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново"); const account = await clients[0]!.getUserByLogin(login); @@ -68,6 +77,7 @@ export async function unshareProject(db: Db, actor: User, project: Project, logi if (project.ownerId !== actor.id && !self) throw new PeppaError("Участниками управляет только владелец проекта"); if (!(await removeMember(db, project.id, login))) throw new PeppaError(`«${login}» не участник проекта`); describeCache.delete(project.id); + if (await localUser(db, login)) return; // not a Gitea collaborator; the same Gitea login may be someone else for (const c of await repoAdmins(db, project)) { try { await c.removeCollaborator(project.giteaOwner, project.giteaRepo, login); @@ -76,6 +86,11 @@ export async function unshareProject(db: Db, actor: User, project: Project, logi } } +async function localUser(db: Db, login: string): Promise { + const u = (await getUserByLogin(db, login)) ?? (await getUserByLogin(db, login.toLowerCase())); + return u && isLocalUser(u) ? u : null; +} + /** Owner adds every member (not pending invites) as a repo collaborator; returns who failed. */ export async function grantRepoAccess(db: Db, actor: User, project: Project): Promise<{ granted: string[]; failed: string[] }> { if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта"); @@ -84,6 +99,7 @@ export async function grantRepoAccess(db: Db, actor: User, project: Project): Pr const granted: string[] = []; const failed: string[] = []; for (const m of members) { + if (isLocalUser(m)) continue; // PEP-68: no Gitea account to add let ok = false; for (const c of clients) { try { diff --git a/packages/testkit/test/local-users.test.ts b/packages/testkit/test/local-users.test.ts new file mode 100644 index 00000000..969cc3bd --- /dev/null +++ b/packages/testkit/test/local-users.test.ts @@ -0,0 +1,171 @@ +// PEP-68: local users without Gitea — password login, attempt limits, superadmin management. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-local-")), "gitea")); +const OWNER = { id: 61, login: "mock-owner", token: "mock-token-owner" }; +const BOT = { id: 62, login: "peppa-bot", token: "mock-token-bot" }; +const KATE_IN_GITEA = { id: 63, login: "kate", token: "mock-token-kate-gitea" }; // someone else's Gitea account + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + for (const u of [OWNER, BOT, KATE_IN_GITEA]) gitea.addUser(u); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +/** `peppa user …` as the machine admin runs it; the password comes on stdin. */ +function cli(args: string[], input = ""): string { + return execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["user", ...args], { env: process.env, input, encoding: "utf8" }); +} + +const IP = "203.0.113.7"; + +describe("local users", () => { + test("Вход по паролю: суперадмин admin создан CLI и входит без Gitea", async () => { + await core.setPlatformAdmins(db, ["asel"]); + const out = cli(["add", "admin", "--admin", "--name", "Админ"], "mock-admin-password\n"); + assert.match(out, /admin \(#\d+\) создан, суперадмин/); + assert.doesNotMatch(out, /пароль:/, "the piped password is not echoed"); + const admin = (await core.getUserByLogin(db, "admin"))!; + assert.ok(admin.giteaId < 0 && core.isLocalUser(admin)); + assert.equal(admin.name, "Админ"); + assert.ok(admin.passwordHash?.startsWith("scrypt$")); + assert.ok(!admin.passwordHash!.includes("mock-admin-password")); + assert.deepEqual(await core.platformAdmins(db), ["admin", "asel"]); + assert.equal(await core.isSuperadmin(db, admin), true); + assert.equal(await core.isUserAllowed(db, admin), true, "no allowlist needed"); + + const r = await core.passwordLogin(db, "Admin", "mock-admin-password", IP); + assert.ok(r.ok && r.user.id === admin.id, "login is case-insensitive"); + assert.ok((await core.getUserByLogin(db, "admin"))!.lastLoginAt); + }); + + test("CLI generates and prints a password when stdin is empty; passwd changes it", async () => { + const out = cli(["add", "mock-gen"]); + const pw = out.match(/пароль: (\S+)/)?.[1]; + assert.ok(pw && pw.length === 16); + assert.ok((await core.passwordLogin(db, "mock-gen", pw, null)).ok); + cli(["passwd", "mock-gen"], "mock-new-password\n"); + assert.equal((await core.passwordLogin(db, "mock-gen", pw, null)).ok, false); + assert.ok((await core.passwordLogin(db, "mock-gen", "mock-new-password", null)).ok); + assert.throws(() => cli(["add", "mock-gen"], "another-password\n"), /уже занят/); + }); + + test("Неверный пароль: одна ошибка, после 5 попыток — пауза", async () => { + await core.createLocalUser(db, { login: "kate", name: "Kate", password: "mock-kate-password" }); + const t0 = Date.now(); + const wrong = await core.passwordLogin(db, "kate", "nope-nope", IP, t0); + const unknown = await core.passwordLogin(db, "nobody-here", "nope-nope", IP, t0); + assert.deepEqual(wrong, { ok: false, error: "Неверный логин или пароль" }); + assert.deepEqual(unknown, wrong, "same message for an unknown login"); + for (let i = 0; i < 4; i++) await core.passwordLogin(db, "kate", "nope-nope", null, t0 + i); + const paused = await core.passwordLogin(db, "kate", "mock-kate-password", null, t0 + 10); + assert.deepEqual(paused, { ok: false, error: core.TOO_MANY_ATTEMPTS }, "even the right password waits"); + const later = await core.passwordLogin(db, "kate", "mock-kate-password", null, t0 + 16 * 60_000); + assert.ok(later.ok, "after 15 minutes the pause is over"); + // success resets the counter + assert.equal((await core.passwordLogin(db, "kate", "nope-nope", null, t0 + 16 * 60_000 + 1)).ok, false); + assert.ok((await core.passwordLogin(db, "kate", "mock-kate-password", null, t0 + 16 * 60_000 + 2)).ok); + }); + + test("20 failures from one IP pause password login from it, other IPs still work", async () => { + const t0 = Date.now(); + const ip = "198.51.100.9"; + for (let i = 0; i < 20; i++) await core.passwordLogin(db, `mock-spray-${i}`, "nope-nope", ip, t0 + i); + assert.deepEqual(await core.passwordLogin(db, "kate", "mock-kate-password", ip, t0 + 30), { ok: false, error: core.TOO_MANY_ATTEMPTS }); + assert.ok((await core.passwordLogin(db, "kate", "mock-kate-password", "192.0.2.1", t0 + 31)).ok); + }); + + test("Отключённый пользователь: сессии не действуют и войти он не может", async () => { + const kate = (await core.getUserByLogin(db, "kate"))!; + assert.equal(await core.isUserAllowed(db, kate), true); + cli(["disable", "kate"]); + const disabled = (await core.getUserByLogin(db, "kate"))!; + assert.ok(disabled.disabledAt); + assert.equal(await core.isUserAllowed(db, disabled), false, "web session and MCP token stop working"); + assert.deepEqual(await core.passwordLogin(db, "kate", "mock-kate-password", null), { ok: false, error: "Неверный логин или пароль" }); + await core.setUserDisabled(db, kate.id, false); + assert.ok((await core.passwordLogin(db, "kate", "mock-kate-password", null)).ok); + }); + + test("disabling applies to Gitea users too, even allowlisted ones", async () => { + await core.setAllowedLogins(db, ["dana"]); + const dana = await core.upsertUserFromGitea(db, { id: 64, login: "dana" }, { access_token: "x" }); + await core.setUserDisabled(db, dana.id, true); + assert.equal(await core.isUserAllowed(db, (await core.getUser(db, dana.id))!), false); + assert.equal(await core.giteaLoginRefusal(db, "dana"), "Нет доступа к Пеппе — попросите администратора"); + assert.equal((await core.passwordLogin(db, "dana", "anything-at-all", null)).ok, false, "no password → same error"); + }); + + test("Логин занят локальным пользователем: вход через Gitea отклонён", async () => { + assert.match((await core.giteaLoginRefusal(db, "KATE"))!, /занят локальным пользователем Пеппы/); + assert.equal(await core.giteaLoginRefusal(db, "mock-owner"), null); + assert.equal(await core.giteaLoginRefusal(db, "never-seen"), null); + }); + + test("Смена своего пароля", async () => { + const kate = (await core.getUserByLogin(db, "kate"))!; + await assert.rejects(core.changeOwnPassword(db, kate, "wrong-current", "mock-kate-new"), /Текущий пароль неверный/); + await assert.rejects(core.changeOwnPassword(db, kate, "mock-kate-password", "short"), /не короче 8/); + await core.changeOwnPassword(db, kate, "mock-kate-password", "mock-kate-new-password"); + assert.equal((await core.passwordLogin(db, "kate", "mock-kate-password", null)).ok, false); + assert.ok((await core.passwordLogin(db, "kate", "mock-kate-new-password", null)).ok); + }); + + test("validation: login format and password length", async () => { + await assert.rejects(core.createLocalUser(db, { login: "-bad", password: "long-enough" }), /Логин/); + await assert.rejects(core.createLocalUser(db, { login: "ok-login", password: "short" }), /не короче 8/); + await assert.rejects(core.createLocalUser(db, { login: "Dana", password: "long-enough" }), /уже занят/, "a Gitea user's login is taken too"); + }); + + test("Не суперадмин: isSuperadmin только для platform.admins", async () => { + const kate = (await core.getUserByLogin(db, "kate"))!; + assert.equal(await core.isSuperadmin(db, kate), false); + assert.equal(await core.isSuperadmin(db, null), false); + }); + + test("Участник без Gitea: доступ к проекту, но не соавтор репо", async () => { + const owner = await core.upsertUserFromGitea(db, OWNER, { access_token: OWNER.token }); + const p = await project({ turns: [] }); + await core.setProjectOwner(db, (await core.getProject(db, p.key)).id, owner.id); + const proj = await core.getProject(db, p.key); + const repo = gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { admins: [OWNER.login] }); + repo.collaborators.kate = "write"; // the Gitea "kate" (another person) already collaborates + const kate = (await core.getUserByLogin(db, "kate"))!; + + const r = await runner.shareProject(db, owner, proj, "Kate"); + assert.deepEqual(r, { login: "kate", status: "added", repoAccess: false }); + assert.equal((await core.projectForUser(db, kate.id, proj.id)).id, proj.id); + const g = await runner.grantRepoAccess(db, owner, proj); + assert.deepEqual(g, { granted: [], failed: [] }, "local members are skipped"); + + await runner.unshareProject(db, owner, proj, "kate"); + await assert.rejects(core.projectForUser(db, kate.id, proj.id), /Не найдено/); + assert.equal(repo.collaborators.kate, "write", "the Gitea account with the same login is left alone"); + }); + + test("new project of a local user goes to peppa-bot's namespace with the bot client", async () => { + const kate = (await core.getUserByLogin(db, "kate"))!; + const ns = await runner.projectNamespace(db, kate, "some-org"); + assert.equal(ns.owner, "peppa-bot"); + assert.equal(ns.ownerIsUser, true); + assert.equal((await ns.gitea.me()).login, "peppa-bot"); + const owner = (await core.getUserByLogin(db, "mock-owner"))!; + const own = await runner.projectNamespace(db, owner, ""); + assert.deepEqual([own.owner, own.ownerIsUser, (await own.gitea.me()).login], ["mock-owner", true, "mock-owner"]); + }); +}); -- 2.45.2 From 5009975a5af24a58a9935c839ec8558b9da0d417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:22:04 +0500 Subject: [PATCH 041/536] PEP-68: archive OpenSpec change pep-68-local-users Co-Authored-By: Claude Opus 5.5 --- .../2026-11-14-pep-68-local-users}/design.md | 0 .../proposal.md | 0 .../specs/web-auth/spec.md | 0 .../2026-11-14-pep-68-local-users}/tasks.md | 0 openspec/specs/web-auth/spec.md | 77 +++++++++++++++++++ 5 files changed, 77 insertions(+) rename openspec/changes/{pep-68-local-users => archive/2026-11-14-pep-68-local-users}/design.md (100%) rename openspec/changes/{pep-68-local-users => archive/2026-11-14-pep-68-local-users}/proposal.md (100%) rename openspec/changes/{pep-68-local-users => archive/2026-11-14-pep-68-local-users}/specs/web-auth/spec.md (100%) rename openspec/changes/{pep-68-local-users => archive/2026-11-14-pep-68-local-users}/tasks.md (100%) diff --git a/openspec/changes/pep-68-local-users/design.md b/openspec/changes/archive/2026-11-14-pep-68-local-users/design.md similarity index 100% rename from openspec/changes/pep-68-local-users/design.md rename to openspec/changes/archive/2026-11-14-pep-68-local-users/design.md diff --git a/openspec/changes/pep-68-local-users/proposal.md b/openspec/changes/archive/2026-11-14-pep-68-local-users/proposal.md similarity index 100% rename from openspec/changes/pep-68-local-users/proposal.md rename to openspec/changes/archive/2026-11-14-pep-68-local-users/proposal.md diff --git a/openspec/changes/pep-68-local-users/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-14-pep-68-local-users/specs/web-auth/spec.md similarity index 100% rename from openspec/changes/pep-68-local-users/specs/web-auth/spec.md rename to openspec/changes/archive/2026-11-14-pep-68-local-users/specs/web-auth/spec.md diff --git a/openspec/changes/pep-68-local-users/tasks.md b/openspec/changes/archive/2026-11-14-pep-68-local-users/tasks.md similarity index 100% rename from openspec/changes/pep-68-local-users/tasks.md rename to openspec/changes/archive/2026-11-14-pep-68-local-users/tasks.md diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md index 537dd60b..4380dad9 100644 --- a/openspec/specs/web-auth/spec.md +++ b/openspec/specs/web-auth/spec.md @@ -118,3 +118,80 @@ KazEDS, показывает QR и ссылку для eGov Mobile и после #### Scenario: ИИН уже занят - **WHEN** пользователь подписывает QR ИИН, привязанным к другой учётке - **THEN** привязка отклонена + +### Requirement: Вход по логину и паролю +Страница входа SHALL предлагать вход по логину и паролю для локальных пользователей Пеппы +(без аккаунта Gitea). Пароль хранится только как хэш scrypt с солью. Любая причина +отказа (нет логина, нет пароля, неверный пароль, пользователь отключён) SHALL давать одно +и то же сообщение «Неверный логин или пароль». После 5 неудачных попыток по логину или +20 по IP за 15 минут вход по паролю приостанавливается на 15 минут. + +#### Scenario: Вход по паролю +- **GIVEN** суперадмин создал локального пользователя «admin» с паролем +- **WHEN** admin вводит логин и пароль на странице входа +- **THEN** он входит в Пеппу без Gitea + +#### Scenario: Неверный пароль +- **GIVEN** локальный пользователь «kate» +- **WHEN** на странице входа введён логин «kate» и неверный пароль +- **THEN** вход отклонён с сообщением «Неверный логин или пароль» +- **AND** для несуществующего логина сообщение такое же + +#### Scenario: Пауза после 5 попыток +- **GIVEN** для логина «kate» было 5 неудачных попыток за 15 минут +- **WHEN** вводится даже верный пароль +- **THEN** вход отклонён с сообщением о слишком частых попытках + +### Requirement: Управление локальными пользователями +Суперадмин (логин в `platform.admins`) SHALL создавать локальных пользователей (логин, +имя, временный пароль), сбрасывать им пароль и отключать или включать пользователей в +разделе «Пользователи»; остальным раздел недоступен. Администратор машины SHALL делать +то же через CLI `peppa user add|passwd|disable|enable`. Логин локального пользователя +уникален в Пеппе. + +#### Scenario: Создание пользователя +- **GIVEN** суперадмин «admin» +- **WHEN** он создаёт пользователя «kate» с временным паролем +- **THEN** kate может войти по этому паролю + +#### Scenario: Не суперадмин +- **WHEN** пользователь не из `platform.admins` открывает «Пользователи» или отправляет действие раздела +- **THEN** он получает «не найдено», данные не меняются + +#### Scenario: Отключённый пользователь +- **GIVEN** пользователь «kate» вошла в веб и подключила MCP-клиент +- **WHEN** суперадмин отключает её +- **THEN** её следующий запрос к вебу ведёт на страницу входа, запрос MCP-клиента получает 401 +- **AND** войти по паролю она не может + +### Requirement: Смена своего пароля +Локальный пользователь SHALL менять свой пароль в «Настройках», указав текущий и новый +(не короче 8 символов). + +#### Scenario: Смена пароля +- **WHEN** kate вводит текущий пароль и новый +- **THEN** дальше она входит только по новому паролю + +#### Scenario: Неверный текущий пароль +- **WHEN** текущий пароль указан неверно +- **THEN** пароль не меняется и показывается ошибка + +### Requirement: Логины Gitea не склеиваются с локальными +Вход через Gitea SHALL отклоняться, если логин аккаунта Gitea занят локальным +пользователем Пеппы. + +#### Scenario: Логин занят локальным пользователем +- **GIVEN** локальный пользователь «kate» +- **WHEN** аккаунт Gitea «kate» проходит вход через Gitea +- **THEN** сессия не создаётся и показывается, что логин занят локальным пользователем Пеппы + +### Requirement: Возможности локального пользователя +Локальный пользователь SHALL работать с досками, задачами и вопросами своих проектов и +быть участником чужих (добавляется по логину Пеппы, без доступа к репозиторию в Gitea). +Его новые проекты SHALL создаваться в пространстве `peppa-bot`. Веб SHALL показывать ему, +что аккаунта Gitea нет и доступ к коду — только через Пеппу. + +#### Scenario: Участник без Gitea +- **GIVEN** владелец проекта «PAY» и локальный пользователь «kate» +- **WHEN** владелец добавляет «kate» в участники +- **THEN** kate видит проект «PAY», соавтором репозитория в Gitea она не становится -- 2.45.2 From f9bc15632133f7b1f5da43e6ecb7f05ef447d04b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:16:48 +0500 Subject: [PATCH 042/536] PEP-66: OpenSpec change pep-66-github-tabs Co-Authored-By: Claude Opus 5.5 --- openspec/changes/pep-66-github-tabs/design.md | 43 ++++++ .../changes/pep-66-github-tabs/proposal.md | 36 +++++ .../specs/remote-mcp/spec.md | 56 +++++++ .../specs/web-workspace/spec.md | 138 ++++++++++++++++++ openspec/changes/pep-66-github-tabs/tasks.md | 20 +++ 5 files changed, 293 insertions(+) create mode 100644 openspec/changes/pep-66-github-tabs/design.md create mode 100644 openspec/changes/pep-66-github-tabs/proposal.md create mode 100644 openspec/changes/pep-66-github-tabs/specs/remote-mcp/spec.md create mode 100644 openspec/changes/pep-66-github-tabs/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-66-github-tabs/tasks.md diff --git a/openspec/changes/pep-66-github-tabs/design.md b/openspec/changes/pep-66-github-tabs/design.md new file mode 100644 index 00000000..1aad4309 --- /dev/null +++ b/openspec/changes/pep-66-github-tabs/design.md @@ -0,0 +1,43 @@ +# Design: PEP-66 + +## Эпики = таблица `goals` +Таблица `goals` (`title`, `description`, `status` open/done/archived) и `tasks.goal_id` +(необязательная ссылка, `on delete set null`) уже делают всё, что нужно эпику-метке. Миграция +не нужна: в коде core появляются синонимы `createEpic`/`listEpics`/`updateEpic` поверх +функций целей, в интерфейсе слово «цель» заменено на «эпик». Колонку не переименовываем — +переименование таблицы ради слова стоило бы миграции боевой базы без пользы. +«В архив» в «⋯» = `status: archived`: эпик пропадает из фильтра и выбора, стори остаются с +ним (на карточке тега нет, так как архивные эпики не показываются). + +## MCP: алиасы, а не переименование +Удалённые клиенты (claude.ai) кэшируют список инструментов; молча убрать `list_goals` значит +сломать сохранённые сценарии. Поэтому основные — `*_epic(s)` и `epic_id`, старые — алиасы с +описанием «Alias of …». Если переданы и `epic_id`, и `goal_id` — берётся `epic_id`. + +## Вкладки Код и PR — Gitea по требованию +Страница проекта обновляется каждые несколько секунд (`AutoRefresh`), поэтому Gitea +спрашивается только для открытой вкладки и не чаще раза в минуту на проект (кэш как у +`describeRepo`), с таймаутом 5 с; при ошибке — пустое состояние со ссылкой на Gitea, страница +не падает. Клиент — тот же порядок, что у `describeRepo`: клиент владельца, затем peppa-bot. +README рисуется как текст (`
      `, как артефакты OpenSpec на странице стори) — без
      +markdown-зависимости.
      +
      +PR → стори: по ветке `task/-` (`taskForCheck`) или по номеру PR из `tasks.pr_url`.
      +Проверки — `taskCiSummary` (уже есть для карточки стори). PR без стори показывается без
      +проверок.
      +
      +## Спеки из рабочей копии
      +`openspec/specs//spec.md` из `project.workspacePath` (как артефакты change на
      +странице стори). Показываем имя capability, `Purpose` и число требований; текст — в
      +раскрывашке.
      +
      +## Настройки багов в «⋯»
      +`IncidentsSection` делится на две части: настройки (подключение, политика, окружения,
      +вебхук) — в «⋯ Настройки проекта», список инцидентов — во вкладке «Баги». Формы — те же
      +server actions, `back` указывает на текущую вкладку.
      +
      +## Тексты «стори»
      +Меняем только то, что видит человек: веб, сообщения бота и уведомления (outbox),
      +описания MCP-инструментов и `instructions`, «Помощь». Внутренние имена (`tasks`, `taskKey`,
      +`create_task`) не трогаем. Промпты агенту («Работай над задачей …») переводим на «стори»,
      +чтобы агент не путал с пунктами `tasks.md`.
      diff --git a/openspec/changes/pep-66-github-tabs/proposal.md b/openspec/changes/pep-66-github-tabs/proposal.md
      new file mode 100644
      index 00000000..2a636a8e
      --- /dev/null
      +++ b/openspec/changes/pep-66-github-tabs/proposal.md
      @@ -0,0 +1,36 @@
      +# PEP-66: Проект как в GitHub — вкладки Код, Спеки, PR; цели → эпики; задачи → стори
      +
      +## Why
      +PM привык к GitHub: страница репозитория с вкладками Code / Issues / Pull requests / Actions /
      +Settings. Этап 1 (вкладки Доска · Релизы · Баги · Сессии, «+ Стори», «⋯ Настройки проекта»)
      +сделан быстрой полировкой. Не хватает того, что PM видит в GitHub первым делом: код (README,
      +ветки, коммиты), открытые PR с проверками и «что система умеет» (спеки OpenSpec). Цели как
      +отдельный экран не прижились — PM нужна лёгкая группировка, как label/milestone. Слово
      +«задача» путается с пунктами `tasks.md` внутри OpenSpec change.
      +
      +## What Changes
      +- Вкладки страницы проекта: **Доска · Код · Спеки · PR · Релизы · Баги · Сессии** (`?tab=`).
      +  - «Код»: README ветки по умолчанию, ссылка на Gitea, ветки, последние коммиты — через клиент
      +    Gitea в core (`listBranches`, `listCommits`, `readme`), сборка — `repoOverview` в runner.
      +  - «Спеки»: `openspec/specs/*/spec.md` из рабочей копии проекта (`listSpecs`).
      +  - «PR»: открытые PR репозитория, у PR стори — ключ стори и `taskCiSummary`.
      +- **Эпики** вместо целей: необязательный эпик у стори (хранилище — таблица `goals`, без
      +  миграции), тег на карточке доски, фильтр доски по эпику (`?epic=`), выбор эпика в «+ Стори»,
      +  управление эпиками (создать, переименовать, описание, в архив) в «⋯ Настройки проекта».
      +  Описание эпика по-прежнему уходит агенту в `get_task`. Bugsink-цель «Стабильность» — эпик.
      +- MCP PM: `list_epics` / `create_epic` / `update_epic` и `epic_id` в `create_task` /
      +  `update_task`; старые `list_goals` / `create_goal` / `update_goal` и `goal_id` остаются
      +  алиасами. Агентский MCP: `list_epics` (+ алиас `list_goals`).
      +- **Стори**: в интерфейсе (доска, страница стори, Главная, раннеры, бот, описания
      +  MCP-инструментов и `instructions`, «Помощь») задачи Пеппы называются «стори». Имена
      +  MCP-инструментов (`create_task` и т.п.) не меняются. Пункты `tasks.md` остаются «задачами».
      +- Настройки багов (политика, окружения, `IncidentsSection` с формой подключения) — в
      +  «⋯ Настройки проекта»; вкладка «Баги» показывает список инцидентов.
      +
      +## Impact
      +- `apps/web` (страница проекта, доска, «Помощь», тексты), `packages/core` (gitea, epics,
      +  specs), `packages/runner` (repoOverview, openPulls), `packages/mcp` (тексты, алиасы),
      +  `apps/bot` и уведомления в core/runner (тексты), `packages/testkit` (mock-gitea: ветки,
      +  коммиты; тесты).
      +- Без миграций и новых зависимостей. Чтение Gitea на странице — только на открытой вкладке,
      +  с кэшем в минуту.
      diff --git a/openspec/changes/pep-66-github-tabs/specs/remote-mcp/spec.md b/openspec/changes/pep-66-github-tabs/specs/remote-mcp/spec.md
      new file mode 100644
      index 00000000..8c8158c3
      --- /dev/null
      +++ b/openspec/changes/pep-66-github-tabs/specs/remote-mcp/spec.md
      @@ -0,0 +1,56 @@
      +## REMOVED Requirements
      +
      +### Requirement: Цели через MCP
      +**Reason**: цели переименованы в эпики.
      +**Migration**: «Эпики через MCP»; старые инструменты остались алиасами.
      +
      +### Requirement: Цель задачи
      +**Reason**: цели переименованы в эпики.
      +**Migration**: «Эпик стори»; `goal_id` остался алиасом `epic_id`.
      +
      +## MODIFIED Requirements
      +
      +### Requirement: Инструкции сервера
      +MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться
      +инструментами, в терминах проект → эпики → стори → доска.
      +
      +#### Scenario: Подключение
      +- **WHEN** клиент инициализирует соединение
      +- **THEN** получает инструкции сервера с моделью проект → эпики → стори → доска
      +
      +## ADDED Requirements
      +
      +### Requirement: Эпики через MCP
      +MCP SHALL позволять создавать эпики в проекте пользователя (`create_epic`), видеть открытые
      +(`list_epics`) и менять их название, описание и статус (`update_epic`: открыт, завершён, в
      +архиве). `list_goals` / `create_goal` / `update_goal` SHALL работать как алиасы.
      +
      +#### Scenario: Новый эпик и стори в нём
      +- **GIVEN** проект PAY пользователя
      +- **WHEN** клиент вызывает `create_epic` «Оплата картой» и затем `create_task` с его `epic_id`
      +- **THEN** эпик виден в `list_epics`, стори относится к этому эпику
      +
      +#### Scenario: Эпик завершён
      +- **GIVEN** открытый эпик «Оплата картой»
      +- **WHEN** клиент вызывает `update_epic` со статусом `done`
      +- **THEN** эпик пропадает из `list_epics`, его стори не меняются
      +
      +#### Scenario: Алиас цели
      +- **GIVEN** открытый эпик «Оплата картой»
      +- **WHEN** клиент вызывает `list_goals`
      +- **THEN** получает тот же список, что `list_epics`
      +
      +### Requirement: Эпик стори
      +`update_task` SHALL позволять перенести стори в другой эпик своего проекта (`epic_id`, алиас
      +`goal_id`) или отвязать от эпика (`null`), не меняя остальное.
      +
      +#### Scenario: Перенос в другой эпик
      +- **GIVEN** стори PAY-3 в эпике «А» и эпик «Б» того же проекта
      +- **WHEN** клиент вызывает `update_task` с `epic_id` эпика «Б»
      +- **THEN** стори относится к «Б», статус и название прежние, `get_task` показывает «Эпик: #… Б»
      +
      +#### Scenario: Эпик чужого проекта
      +- **GIVEN** эпик принадлежит другому проекту
      +- **WHEN** клиент вызывает `update_task` с его `epic_id`
      +- **THEN** ошибка, стори не меняется
      +
      diff --git a/openspec/changes/pep-66-github-tabs/specs/web-workspace/spec.md b/openspec/changes/pep-66-github-tabs/specs/web-workspace/spec.md
      new file mode 100644
      index 00000000..0d40fa93
      --- /dev/null
      +++ b/openspec/changes/pep-66-github-tabs/specs/web-workspace/spec.md
      @@ -0,0 +1,138 @@
      +## REMOVED Requirements
      +
      +### Requirement: Цели и задачи
      +**Reason**: целей как отдельного экрана нет; их место заняли эпики-метки стори.
      +**Migration**: см. «Стори и эпики»; таблица `goals` хранит эпики, данные не меняются.
      +
      +## MODIFIED Requirements
      +
      +### Requirement: Доска задач
      +Вкладка «Доска» страницы проекта SHALL показывать стори доской с колонками Бэклог, В
      +работе, Ревью, Готово; карточку можно перенести перетаскиванием или кнопкой. Перенос в «В
      +работе» запускает агента по стори, если активной сессии нет; перенос в «Бэклог» или «Готово»
      +останавливает активную сессию. Доску можно отфильтровать по эпику.
      +
      +#### Scenario: Карточку в работу
      +- **GIVEN** стори PAY-3 в «Бэклог» без активной сессии
      +- **WHEN** PM переносит карточку в «В работе»
      +- **THEN** стори получает статус `in_progress` и по ней запускается сессия агента
      +
      +#### Scenario: Карточку в готово
      +- **GIVEN** стори PAY-3 в «Ревью» с активной сессией
      +- **WHEN** PM переносит карточку в «Готово»
      +- **THEN** стори `done`, активная сессия по ней остановлена
      +
      +#### Scenario: Фильтр по эпику
      +- **GIVEN** стори PAY-1 в эпике «Оплата картой» и PAY-2 без эпика
      +- **WHEN** PM выбирает над доской эпик «Оплата картой»
      +- **THEN** на доске только PAY-1, адрес страницы содержит `?epic=`
      +
      +#### Scenario: Чужой эпик в фильтре
      +- **GIVEN** эпик с id 999 принадлежит другому проекту
      +- **WHEN** PM открывает доску PAY с `?epic=999`
      +- **THEN** доска показывает все стори проекта без фильтра
      +
      +## ADDED Requirements
      +
      +### Requirement: Стори и эпики
      +Пользователь SHALL создавать стори (задачи Пеппы) в своём проекте и относить их к
      +необязательному эпику проекта. Номер стори выдаётся так же, как через MCP и CLI. Отдельного
      +экрана целей нет: эпики — метки стори.
      +
      +#### Scenario: Новая стори в эпике
      +- **GIVEN** в проекте PAY есть эпик «Оплата картой»
      +- **WHEN** пользователь в «+ Стори» вводит название «Форма оплаты» и выбирает эпик «Оплата картой»
      +- **THEN** стори получает следующий номер проекта (`PAY-N`), статус `backlog`
      +- **AND** на её карточке на доске виден тег «Оплата картой»
      +
      +#### Scenario: Стори без эпика
      +- **GIVEN** проект PAY
      +- **WHEN** пользователь создаёт стори, оставив эпик «без эпика»
      +- **THEN** стори создана без эпика, на карточке тега нет
      +
      +### Requirement: Вкладки проекта
      +Страница проекта SHALL иметь вкладки Доска · Код · Спеки · PR · Релизы · Баги · Сессии
      +(параметр `?tab=`), кнопку «+ Стори» и «⋯ Настройки проекта» в заголовке. Неизвестная вкладка
      +открывает Доску.
      +
      +#### Scenario: Переход на вкладку
      +- **GIVEN** проект PAY
      +- **WHEN** пользователь открывает `/p/PAY?tab=code`
      +- **THEN** активна вкладка «Код»
      +
      +#### Scenario: Неизвестная вкладка
      +- **WHEN** пользователь открывает `/p/PAY?tab=nope`
      +- **THEN** активна вкладка «Доска»
      +
      +### Requirement: Вкладка «Код»
      +Вкладка «Код» SHALL показывать README ветки по умолчанию, ссылку на репозиторий в Gitea,
      +ветки и последние коммиты (сообщение, автор, время, короткий SHA). Gitea спрашивается не чаще
      +раза в минуту на проект; если Gitea недоступна, вкладка показывает ссылку на репозиторий и
      +сообщение, страница не падает.
      +
      +#### Scenario: Репозиторий с кодом
      +- **GIVEN** в репозитории PAY ветки `main` и `task/PAY-3`, в `main` есть README.md «# Pay»
      +- **WHEN** пользователь открывает вкладку «Код»
      +- **THEN** видны текст README «# Pay», ветки `main` и `task/PAY-3` и последний коммит `main`
      +
      +#### Scenario: Gitea недоступна
      +- **GIVEN** Gitea не отвечает
      +- **WHEN** пользователь открывает вкладку «Код»
      +- **THEN** видна ссылка на репозиторий и «Gitea сейчас не отвечает»
      +
      +### Requirement: Вкладка «Спеки»
      +Вкладка «Спеки» SHALL показывать спецификации `openspec/specs/*/spec.md` из рабочей копии
      +проекта — что система умеет сейчас: имя, назначение, число требований и текст.
      +
      +#### Scenario: Есть спеки
      +- **GIVEN** в рабочей копии есть `openspec/specs/web-auth/spec.md` с двумя требованиями
      +- **WHEN** пользователь открывает вкладку «Спеки»
      +- **THEN** виден пункт «web-auth» с назначением и «2 требования»
      +
      +#### Scenario: Спек нет
      +- **GIVEN** в рабочей копии нет `openspec/specs`
      +- **WHEN** пользователь открывает вкладку «Спеки»
      +- **THEN** видно «Спек ещё нет — они появляются после archive первого change»
      +
      +### Requirement: Вкладка «PR»
      +Вкладка «PR» SHALL показывать открытые PR репозитория со ссылками; у PR стори — ключ стори и
      +сводку проверок (`taskCiSummary`).
      +
      +#### Scenario: PR стори
      +- **GIVEN** открыт PR из ветки `task/PAY-3`, проверки головного коммита: 2 из 2 пройдены
      +- **WHEN** пользователь открывает вкладку «PR»
      +- **THEN** виден PR со ссылкой на стори PAY-3 и «Проверки: 2 из 2 пройдены»
      +
      +#### Scenario: Открытых PR нет
      +- **GIVEN** в репозитории нет открытых PR
      +- **WHEN** пользователь открывает вкладку «PR»
      +- **THEN** видно «Открытых PR нет»
      +
      +### Requirement: Настройки проекта
      +«⋯ Настройки проекта» SHALL содержать репозиторий, участников, эпики (создать,
      +переименовать, описание, в архив) и настройки багов (подключение отслеживания ошибок,
      +политика, окружения). Вкладка «Баги» показывает список инцидентов.
      +
      +#### Scenario: Новый эпик
      +- **GIVEN** проект PAY без эпиков
      +- **WHEN** PM в «⋯» добавляет эпик «Оплата картой»
      +- **THEN** эпик доступен в «+ Стори» и в фильтре доски
      +
      +#### Scenario: Эпик в архив
      +- **GIVEN** эпик «Оплата картой» со стори PAY-1
      +- **WHEN** PM отправляет эпик в архив
      +- **THEN** эпика нет в «+ Стори» и в фильтре, стори PAY-1 не изменилась
      +
      +### Requirement: Слово «стори»
      +Интерфейс (веб, бот Telegram, описания MCP-инструментов и инструкции сервера, «Помощь»)
      +SHALL называть задачи Пеппы «стори», а группы стори — «эпиками»; пункты `tasks.md` OpenSpec
      +change остаются «задачами». Имена MCP-инструментов не меняются.
      +
      +#### Scenario: Сообщение «готово к ревью»
      +- **GIVEN** стори PAY-3 переходит в ревью
      +- **WHEN** бот отправляет PM уведомление
      +- **THEN** в тексте стоит «стори PAY-3», а не «задача PAY-3»
      +
      +#### Scenario: Имя инструмента
      +- **WHEN** клиент MCP запрашивает список инструментов
      +- **THEN** `create_task` есть, а его описание говорит о стори
      diff --git a/openspec/changes/pep-66-github-tabs/tasks.md b/openspec/changes/pep-66-github-tabs/tasks.md
      new file mode 100644
      index 00000000..d4f23553
      --- /dev/null
      +++ b/openspec/changes/pep-66-github-tabs/tasks.md
      @@ -0,0 +1,20 @@
      +# Tasks: PEP-66
      +
      +## 1. Эпики
      +- [ ] 1.1 core: `createEpic`/`listEpics`/`updateEpic` поверх целей; Bugsink-«Стабильность» описана как эпик
      +- [ ] 1.2 MCP PM: `list_epics`/`create_epic`/`update_epic`, `epic_id` в `create_task`/`update_task`, алиасы `*_goal(s)`/`goal_id`; агентский MCP `list_epics` + алиас; `get_task` — «Эпик»
      +- [ ] 1.3 Веб: эпик в «+ Стори», тег на карточке, фильтр `?epic=` на доске, управление эпиками в «⋯»; server actions с проверкой доступа
      +
      +## 2. Вкладки
      +- [ ] 2.1 core Gitea: `listBranches`, `listCommits`, `readme`, `listPulls`; mock-gitea: ветки, коммиты
      +- [ ] 2.2 runner: `repoOverview` (README, ветки, коммиты, кэш, таймаут), `openPulls` (PR → стори + `taskCiSummary`); core `listSpecs`
      +- [ ] 2.3 Веб: вкладки «Код», «Спеки», «PR»; настройки багов в «⋯», вкладка «Баги» — список
      +
      +## 3. Стори
      +- [ ] 3.1 Тексты веба (доска, страница стори, Главная, раннеры, проекты, «Помощь», OAuth-согласие)
      +- [ ] 3.2 Бот и уведомления (core/runner), промпты агенту
      +- [ ] 3.3 Описания MCP-инструментов и `instructions`
      +
      +## 4. Проверка
      +- [ ] 4.1 Тесты: эпики (MCP, алиасы, фильтр), repoOverview/openPulls на mock-gitea, listSpecs
      +- [ ] 4.2 `pnpm typecheck`, e2e, `next build`; UI своим `next dev` на копии базы
      -- 
      2.45.2
      
      
      From 328900e254138c27500f5f9c1d5ce4f671c4b000 Mon Sep 17 00:00:00 2001
      From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= 
      Date: Sat, 14 Nov 2026 03:21:20 +0500
      Subject: [PATCH 043/536] =?UTF-8?q?PEP-66:=20epics=20(goals=20as=20story?=
       =?UTF-8?q?=20labels),=20tabs=20=D0=9A=D0=BE=D0=B4/=D0=A1=D0=BF=D0=B5?=
       =?UTF-8?q?=D0=BA=D0=B8/PR,=20bug=20settings=20in=20=E2=8B=AF?=
      MIME-Version: 1.0
      Content-Type: text/plain; charset=UTF-8
      Content-Transfer-Encoding: 8bit
      
      Co-Authored-By: Claude Opus 5.5 
      ---
       apps/web/app/(app)/actions.ts       |  31 ++++-
       apps/web/app/(app)/p/[key]/page.tsx | 108 +++++++++++----
       apps/web/app/(app)/p/[key]/tabs.tsx | 199 ++++++++++++++++++++++++++++
       apps/web/components/Board.tsx       |  11 +-
       apps/web/components/Incidents.tsx   | 152 +++++++++++----------
       packages/core/src/gitea.ts          |  35 ++++-
       packages/core/src/incidents.ts      |   4 +-
       packages/core/src/index.ts          |   1 +
       packages/core/src/projects.ts       |   9 ++
       packages/core/src/specs.ts          |  27 ++++
       packages/mcp/src/format.ts          |  10 +-
       packages/mcp/src/index.ts           |  57 ++++----
       packages/mcp/src/manager.ts         | 142 ++++++++++----------
       packages/runner/src/code.ts         | 101 ++++++++++++++
       packages/runner/src/index.ts        |   1 +
       packages/testkit/src/mock-gitea.ts  |  26 ++++
       16 files changed, 710 insertions(+), 204 deletions(-)
       create mode 100644 apps/web/app/(app)/p/[key]/tabs.tsx
       create mode 100644 packages/core/src/specs.ts
       create mode 100644 packages/runner/src/code.ts
      
      diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
      index e1a0e926..f8a016a6 100644
      --- a/apps/web/app/(app)/actions.ts
      +++ b/apps/web/app/(app)/actions.ts
      @@ -2,7 +2,9 @@
       
       import {
         linkEgovIin,
      +  createEpic,
         createTask,
      +  updateEpic,
         getQuestion,
         getSession,
         PeppaError,
      @@ -78,12 +80,37 @@ export async function addTask(f: FormData) {
         const user = await requireUser();
         await attempt(f, async () => {
           const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
      -    if (!str(f, "title")) throw new PeppaError("Нужно название задачи");
      -    const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined });
      +    if (!str(f, "title")) throw new PeppaError("Нужно название стори");
      +    const epic = Number(str(f, "epicId")) || undefined;
      +    const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
           return `/t/${ref.key}`;
         });
       }
       
      +/** Epics (PEP-66): labels that group stories; stored in the goals table. */
      +export async function addEpic(f: FormData) {
      +  const user = await requireUser();
      +  await attempt(f, async () => {
      +    const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
      +    if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
      +    await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
      +  });
      +}
      +
      +export async function editEpic(f: FormData) {
      +  const user = await requireUser();
      +  await attempt(f, async () => {
      +    const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
      +    const id = Number(str(f, "epicId"));
      +    if (str(f, "archive")) {
      +      await updateEpic(db, p.id, id, { status: "archived" });
      +      return;
      +    }
      +    if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
      +    await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
      +  });
      +}
      +
       export async function startTaskSession(f: FormData) {
         const user = await requireUser();
         await attempt(f, async () => {
      diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
      index 67c7e3bc..d2c55983 100644
      --- a/apps/web/app/(app)/p/[key]/page.tsx
      +++ b/apps/web/app/(app)/p/[key]/page.tsx
      @@ -1,16 +1,16 @@
       import { notFound } from "next/navigation";
       import { ExternalLink, Plus, Rocket } from "lucide-react";
      -import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, platformReleaseOffers, type Release } from "@peppa/runner";
      -import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
      +import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
      +import { getIncidentSettings, listEpics, listErrorSources, listIncidents, listMembers, listSpecs, repoAudience, repoVisibilityLabel } from "@peppa/core";
       import { AutoRefresh } from "@/components/AutoRefresh";
       import { PanelSection } from "@/components/ActivityAside";
       import { Board, type Card } from "@/components/Board";
       import { Hidden, SessionCard } from "@/components/cards";
       import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
      -import { IncidentsSection } from "@/components/Incidents";
      +import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
       import { Badge } from "@/components/ui/badge";
       import { Button } from "@/components/ui/button";
      -import { Input, Textarea } from "@/components/ui/input";
      +import { Input, NativeSelect, Textarea } from "@/components/ui/input";
       import { SettingsDialog } from "@/components/SettingsDialog";
       import { Workspace } from "@/components/Workspace";
       import { requireUser } from "@/lib/auth";
      @@ -18,6 +18,7 @@ import { cn } from "@/lib/utils";
       import { db } from "@/lib/db";
       import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
       import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
      +import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs";
       
       const RELEASE_STATUS: Record = {
         deploying: { label: "выкатывается", tone: "info" },
      @@ -29,6 +30,9 @@ const RELEASE_STATUS: Record; searchParams: Promise<{ error?: string; created?: string; tab?: string }> }) {
      +export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string }> }) {
         const user = await requireUser();
         const { key } = await params;
      -  const { error, created, tab: tabParam } = await searchParams;
      +  const { error, created, tab: tabParam, epic: epicParam } = await searchParams;
         const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
         const p = await projectForUserByKey(user.id, key).catch(() => null);
         if (!p) notFound();
      -  const [{ tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([
      +  const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([
           board(p.id),
      +    listEpics(db, p.id),
           projectSessions(p.id),
           listMembers(db, p),
           describeRepo(db, p),
      @@ -80,13 +85,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
           repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
         const missingAccess = team.members.some((m) => noRepoAccess(m.login));
         const isOwner = p.ownerId === user.id;
      -  const back = tab === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${tab}`;
      -  const cards: Card[] = tasks.map((t) => ({
      -    key: `${p.key}-${t.number}`,
      -    title: t.title,
      -    status: t.status,
      -    column: columnOf(t.status),
      -  }));
      +  // Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
      +  const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
      +  const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
      +  const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
      +  const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
      +  const cards: Card[] = tasks
      +    .filter((t) => !epicFilter || t.goalId === epicFilter.id)
      +    .map((t) => ({
      +      key: `${p.key}-${t.number}`,
      +      title: t.title,
      +      status: t.status,
      +      column: columnOf(t.status),
      +      epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
      +    }));
      +  // Gitea and the working copy are read only for the open tab.
      +  const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
      +  const specs = tab === "specs" ? listSpecs(p) : [];
       
         const aside = (
           
      @@ -115,6 +130,21 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr + + + + + + + +
      • @@ -173,6 +203,14 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr