From 8dc82859c7396ba728b0b9a2a8acb5b09a1f214b 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 16:51:22 +0500
Subject: [PATCH 001/518] 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
---
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 ` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
- `pnpm typecheck`
-- `tsx packages/mcp/scripts/smoke.ts ` — смоук MCP-сервера
+- `node packages/mcp/scripts/smoke.ts ` — смоук MCP-сервера
- `pnpm dev:web`
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer `
- Логи: `~/.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 `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.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/`): «В работе» запускает агента (`moveTask`),
@@ -82,4 +82,4 @@ PM двигает карточки на доске (веб, `/p/`): «В р
(`template/RULES.md`, MCP `get_rules`): proposal → `request_approval` → одобрение PM →
apply → archive → PR/коммит. Работу вне задачи не делаем; новое — `create_task`.
Вызов MCP-инструмента из shell (для этой сессии без tmux):
-`tsx packages/mcp/scripts/call.ts ''`.
+`node packages/mcp/scripts/call.ts ''`.
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(method: string, params: Record = {}, timeoutMs = 15_000): Promise {
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(method: string, path: string, body?: unknown): Promise {
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 {
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 {
+ 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 {
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 ''
+// Usage: node packages/mcp/scripts/call.ts ''
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
+// Usage: node packages/mcp/scripts/smoke.ts
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 {
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 {
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
WorkingDirectory $workdir
EnvironmentVariables
- PATH $PATH_ENV
+
+ PATH $PATH_ENV
+ PEPPA_NODE $NODE_BIN
+
RunAtLoad
KeepAlive
StandardOutPath $HOME/.peppa/$log
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?=
Date: Fri, 13 Nov 2026 16:44:17 +0500
Subject: [PATCH 002/518] =?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
---
.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/` 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 ` / `peppa q answer `
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
-- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_` (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`, `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//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`)
+- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_` (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`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный 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 `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.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/` (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 `: 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-агент-слушатель, который берёт
+ подписанный запрос «выкатить »; прод Пеппы — по кнопке 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?=
Date: Fri, 13 Nov 2026 16:44:39 +0500
Subject: [PATCH 003/518] PEP-57: archive OpenSpec change pep-57-ci-cd (spec
delivery-pipeline)
Co-Authored-By: Claude Opus 5.5
---
.../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?=
Date: Fri, 13 Nov 2026 16:54:30 +0500
Subject: [PATCH 004/518] 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
---
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?=
Date: Fri, 13 Nov 2026 16:55:17 +0500
Subject: [PATCH 005/518] PEP-57: re-run CI (runner DNS hiccup)
Co-Authored-By: Claude Opus 5.5
--
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?=
Date: Fri, 13 Nov 2026 17:22:47 +0500
Subject: [PATCH 006/518] 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 ` (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
---
.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`), страница рисует центр и правую панель через `` (по умолчанию `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 `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (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 `-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` (`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`
- **Подключить 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`)
@@ -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 ` — одноразовый перенос из Postgres `DATABASE_URL` (только чтение, сверка строк и внешних ключей; старая pg-схема — `packages/cli/legacy-pg-migrations`); `pnpm db:up` — Postgres для Bugsink
- `peppa project create [--existing]` — проект в Gitea (`provisionProject` в runner, тот же код, что у веба); `peppa project owner `
- `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы
- `peppa web login-link ` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
@@ -60,9 +60,9 @@
- `pnpm dev:web`
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer `
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
-- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_` (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`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный 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 `, `peppa-dev tg messages|click <кнопка>|reply <текст>|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//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный 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 `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.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:`), так бот после рестарта дочитывает пропущенное (сейчас 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 `: чтение 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 `: чтение 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- (local test user)
peppa web login-link (one-time admin login, 10 minutes)
peppa watchdog [--once] [--interval ] [--stall ]
+ peppa db migrate (apply schema migrations to PEPPA_DB)
+ peppa db migrate-to-sqlite (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 (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 {
+ 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 {
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`count(*)::int` })
+ .select({ n: sql`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 {
// ── checks ─────────────────────────────────────────────────────────────────────────
-async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise {
+export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise {
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 {
- 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 {
+ const line = `${JSON.stringify(n)}\n`;
+ await Promise.all(
+ SUBSCRIBERS.map(
+ (service) =>
+ new Promise((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> {
+ 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((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(path, resolve);
+ });
+ return () =>
+ new Promise((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 {
- 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(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();
+ 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(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;
+// 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().notNull().default([]),
+ tasks: text("tasks", { mode: "json" }).$type().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(),
+ options: text("options", { mode: "json" }).$type(),
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>().notNull(),
+ params: text("params", { mode: "json" }).$type>().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().notNull(),
+ redirectUris: text("redirect_uris", { mode: "json" }).$type().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: 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().notNull().default(["prod", "production"]),
+ environments: text("environments", { mode: "json" }).$type().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;
+export type Env = z.infer & { 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 settings writes (heartbeat-like)
+// node storage-worker.ts task 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 {
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`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): Promise {
+ 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 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_ or $PEPPA_TEST_DB (dropped at exit), so it can run next
-# to other worktrees' suites. Logs of --pr runs: ~/.peppa/ci/.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/.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() { #
local name=$1; shift
@@ -72,6 +69,6 @@ step() { #
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?=
Date: Fri, 13 Nov 2026 17:58:34 +0500
Subject: [PATCH 007/518] =?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/,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
---
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`), страница рисует центр и правую панель через `` (по умолчанию `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`), страница рисует центр и правую панель через `` (по умолчанию `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 `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (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/:` на 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)
+- **Прод Пеппы (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/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() {
deploy ). После каждого деплоя — проверка /healthz до 2 минут; не
прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
+
+ Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок{" "}
+ main приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с
+ работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат
+ предыдущего релиза.
+
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
- {current.staging && current.staging.sha !== current.prod?.sha && (
+ {prodCandidate && prodCandidate !== current.prod?.sha && (
)}
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 `; не `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// git worktree --detach на коммит; .env → ../../shared/.env
+ current -> releases/
+ shared/.env единственный .env прода
+ logs/-<время>.log
+ .lock/ один релиз за раз (pid внутри; мёртвый pid — замок снимается)
+```
+
+`~/peppa/workspaces` (проекты фабрики) остаётся рядом и не пересекается.
+
+## Порядок шагов и почему не «бэкап → migrate → install → build»
+
+`peppa db migrate` — код релиза, ему нужны зависимости, поэтому install идёт первым. Сборка —
+до бэкапа и миграций: упавшая сборка не меняет ни схему, ни сервисы, а окно, когда старый код
+работает на новой схеме, сокращается до «migrate → kickstart» (секунды). Итог:
+
+1. fetch `repo.git`, коммит существует → `git worktree add --detach releases/`
+2. `pnpm install --frozen-lockfile` · 3. `pnpm --filter @peppa/web build`
+4. `peppa db backup ~/.peppa/backups/release-<время>-.db` (VACUUM INTO + `quick_check` копии;
+ хранятся 5 последних релизных копий, ежедневные — отдельно, 7 штук)
+5. `peppa db migrate` · 6. `ln -sfn releases/ 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/.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//` не перестанет находить
+агент (до `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/` (git worktree на конкретный коммит), симлинк
+ `current`, общий `shared/.env` (симлинк `.env` в каждый релиз), журналы `logs/`.
+- **`scripts/peppa-release.sh `**: 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/`, отдельный от рабочей копии разработки; пути в хуках раннеров и 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 |--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 -s [--previous ] [--reason ]
+ [--log-file ] [--commits-file ] (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] [-d ]
peppa goal list [KEY]
@@ -74,6 +78,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa web login-link (one-time admin login, 10 minutes)
peppa watchdog [--once] [--interval ] [--stall ]
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 (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 {
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 -s ");
+ 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] ");
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 {
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 (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-` 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 {
+export async function deployProd(db: Db, project: Project, by: string, client?: GiteaClient): Promise {
+ 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 {
+ 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 {
+ 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 {
+ 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/ (its plist), unloading/ (`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= 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/ →
+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:.*Label \(.*\) .*:\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();
+const currentSha = () => (existsSync(join(RELEASES, "current")) ? basename(readlinkSync(join(RELEASES, "current"))) : null);
+
+let pep: Awaited>;
+let proj: Awaited>;
+
+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((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 = {}) => ({
+ ...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 = {}) => 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(`PEPPA_ROOT ${ROOT} `));
+ assert.match(plist, /KeepAlive<\/key> /);
+ });
+
+ 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, /QueueDirectories<\/key>.*\/\.peppa\/release-queue<\/string><\/array>/);
+ assert.match(plist, /scripts\/peppa-release\.sh<\/string>\s*--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/ → ~/peppa/current/…: still current, not releases/.
+ 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)/ && rm ~/Library/LaunchAgents/.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=' RunAtLoad
+ KeepAlive '
+
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
PATH $PATH_ENV
PEPPA_NODE $NODE_BIN
+ PEPPA_ROOT $ROOT
- RunAtLoad
- KeepAlive
- StandardOutPath $HOME/.peppa/$log
- StandardErrorPath $HOME/.peppa/$log
+$LIFECYCLE
+ StandardOutPath $PEPPA_HOME/$log
+ StandardErrorPath $PEPPA_HOME/$log
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=" QueueDirectories $PEPPA_HOME/release-queue "
+ install_agent quest.telecom.peppa.release release.log "$HOME" \
+ /bin/bash "$ROOT/scripts/peppa-release.sh" --queue
+ LIFECYCLE=' RunAtLoad
+ KeepAlive ' ;;
*) 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/ 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 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 --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?=
Date: Fri, 13 Nov 2026 18:02:16 +0500
Subject: [PATCH 008/518] PEP-18: archive OpenSpec change pep-18-peppa-prod
Co-Authored-By: Claude Opus 5.5
---
.../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/`, отдельный от рабочей копии разработки; пути в хуках раннеров и 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?=
Date: Fri, 13 Nov 2026 22:52:53 +0500
Subject: [PATCH 009/518] =?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
---
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 (
-
+
{created && !error && (
@@ -174,6 +175,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
)}
{aside}}
crumbs={Проекты }
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 (
-
+
{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
) with page settings rendered on the server. */
+export function SettingsDialog({ title, children }: { title: string; children: ReactNode }) {
+ const ref = useRef(null);
+ return (
+ <>
+ ref.current?.showModal()}>
+
+
+ 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"
+ >
+
+
+
{title}
+ ref.current?.close()}>
+
+
+
+ {children}
+
+
+ >
+ );
+}
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 ? : aside;
return (
-
+
- {children}
+ {children}
{panel && (
--
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?=
Date: Fri, 13 Nov 2026 22:56:02 +0500
Subject: [PATCH 010/518] Pre-launch live mode: PEPPA_WEB_MODE=dev runs next
dev (HMR) from the working copy
Co-Authored-By: Claude Opus 5.5
---
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)/ && rm ~/Library/LaunchAgents/.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?=
Date: Fri, 13 Nov 2026 23:00:11 +0500
Subject: [PATCH 011/518] AGENTS: pre-launch live mode (next dev from the
working copy)
Co-Authored-By: Claude Opus 5.5
---
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`), страница рисует центр и правую панель через `` (по умолчанию `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`), страница рисует центр и правую панель через `` (по умолчанию `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 `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (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/:` на 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 не трогаем
-- **Прод Пеппы (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`
+- **До официального запуска (сейчас)**: всё в деве. `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/` (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
## Внешние зависимости — через моки
--
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?=
Date: Fri, 13 Nov 2026 23:21:32 +0500
Subject: [PATCH 012/518] =?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
---
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
@@ -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 && Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.
}
+
+
+
+ {goals.map((g) => (
+ ◎ {g.title}
+ ))}
+
+
+
);
+ const newTask = (
+
+
+
+
+
+ Без цели
+ {goals.map((g) => (
+ ◎ {g.title}
+ ))}
+
+ Создать стори
+
+ );
+ const tabCount: Partial
> = { board: tasks.length, bugs: incidents.length, sessions: sessions.length };
+
return (
@@ -175,7 +213,14 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
)}
{aside}}
+ actions={
+ <>
+ Стори>}>
+ {newTask}
+
+ {aside}
+ >
+ }
crumbs={Проекты }
title={
<>
@@ -186,109 +231,95 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{repo.fullName} · {repoVisibilityLabel(repo.private)}
-
-
-
+
-
-
-
-
-
- {prodCandidate && prodCandidate !== current.prod?.sha && (
-
-
-
-
- Выкатить в прод {prodCandidate.slice(0, 7)}
-
-
- )}
- {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].label}
- {r.reason && {r.reason} }
-
-
- {r.tasks.map((t) => (
- {t}
- ))}
-
-
- {r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
-
-
- ))}
-
-
+ {tab === "board" &&
}
+
+ {tab === "releases" && (
+
+ {prodCandidate && prodCandidate !== current.prod?.sha && (
+
+
+
+
+ Выкатить в прод {prodCandidate.slice(0, 7)}
+
+
+ )}
+ {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].label}
+ {r.reason && {r.reason} }
+
+
+ {r.tasks.map((t) => (
+ {t}
+ ))}
+
+
+ {r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
+
+
+ ))}
+
+
+
+ )}
+
+ )}
-
[t.id, `${p.key}-${t.number}`]))}
- webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
- />
+ {tab === "bugs" && (
+ [t.id, `${p.key}-${t.number}`]))}
+ webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
+ />
+ )}
-
- {sessions.length === 0 ? Сессий ещё не было. : sessions.map((s) => )}
-
+ {tab === "sessions" && (
+
+ {sessions.length === 0 ? Сессий ещё не было. : sessions.map((s) => )}
+
+ )}
);
}
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 ) with page settings rendered on the server. */
-export function SettingsDialog({ title, children }: { title: string; children: ReactNode }) {
+/**
+ * Button that opens a side dialog (native ) 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(null);
+ const open = () => ref.current?.showModal();
return (
<>
- ref.current?.showModal()}>
-
-
+ {trigger ? (
+
+ {trigger}
+
+ ) : (
+
+
+
+ )}
Date: Fri, 13 Nov 2026 23:36:32 +0500
Subject: [PATCH 013/518] 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
---
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?=
Date: Fri, 13 Nov 2026 23:37:23 +0500
Subject: [PATCH 014/518] CI rerun (toolcache race)
Co-Authored-By: Claude Opus 5.5
--
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?=
Date: Sat, 14 Nov 2026 00:44:55 +0500
Subject: [PATCH 015/518] =?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
---
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 = {
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 && Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.
}
-
-
-
- {goals.map((g) => (
- ◎ {g.title}
- ))}
-
-
-
-
-
- Создать цель
-
-
);
@@ -189,12 +173,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
-
- Без цели
- {goals.map((g) => (
- ◎ {g.title}
- ))}
-
Создать стори
);
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={
<>
{project.name}
- {goal && · ◎ {goal.title} }
>
}
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 }) {
{card.key} {card.title}
- {(card.goal || STATUS[card.status] || NEXT[c.id]) && (
+ {(STATUS[card.status] || NEXT[c.id]) && (
- {card.goal &&
◎ {card.goal} }
{STATUS[card.status] &&
{STATUS[card.status]!.label} }
{NEXT[c.id] && (
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?=
Date: Sat, 14 Nov 2026 00:45:42 +0500
Subject: [PATCH 016/518] CI: install pnpm and openspec into a job-local prefix
(concurrent jobs collided in the toolcache)
Co-Authored-By: Claude Opus 5.5
---
.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?=
Date: Sat, 14 Nov 2026 01:14:10 +0500
Subject: [PATCH 017/518] 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
---
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 `-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`)
@@ -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/:` на 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`. Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `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/` (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)/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
)}
+
+ {egov === "linked" && eGov привязан — теперь можно входить по QR }
+ {user.egovIin ? (
+
+
+ Привязан ИИН {maskIin(user.egovIin)} — на странице входа можно войти через eGov QR.
+
+
+
+ Отвязать
+
+
+ ) : (
+
+ Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. После этого можно входить в Пеппу через eGov.
+
+
+
+
+ )}
+
+
{user.telegramChatId ? (
({}))) 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<{
Войти через Gitea
+
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 = {
+ 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({ 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 (
+
+ {/* eslint-disable-next-line @next/next/no-img-element -- data URL from the server */}
+
+
{STATUS[phase.status] ?? phase.status}
+ {phase.deeplink && (
+
+
+ Открыть в eGov Mobile
+
+
+ )}
+
+ );
+ }
+ return (
+
+ {phase.at === "error" &&
{phase.message}
}
+
void start().catch((e: Error) => fail(e.message))}>
+ {phase.at === "error" ? "Новый QR" : label}
+
+
+ );
+}
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
+
+
+
+```
+
+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(`
+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_SIGNATURE NOT_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 018/518] 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 019/518] 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 020/518] =?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 021/518] 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 022/518] =?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 (
);
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
-
- Пространство в Gitea
-
- {user.login} — личное
- {orgs.map((o) => (
- {o.username} — организация
- ))}
-
-
-
- Репозиторий будет {giteaUrl}/<пространство>/<slug> . В личном пространстве приватный репозиторий видите
- только вы, peppa-bot и участники проекта; в организации — ещё её участники с доступом к репозиториям.
- {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."}
-
+ {local ? (
+
+ У вас нет аккаунта Gitea — репозиторий будет {giteaUrl}/{botLogin}/<slug> . Доступ к коду — только через
+ Пеппу (агенты, PR, проверки); соавтором в Gitea вас добавить нельзя.
+
+ ) : (
+ <>
+
+ Пространство в Gitea
+
+ {user.login} — личное
+ {orgs.map((o) => (
+ {o.username} — организация
+ ))}
+
+
+
+ Репозиторий будет {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
+
{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.
+
+
+
+
+
+
+
+ );
+}
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 023/518] 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 024/518] 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 025/518] =?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
+
+ Без эпика
+ {epics.map((e) => (
+
+ {e.title}
+
+ ))}
+
Создать стори
);
@@ -226,7 +264,35 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
))}
- {tab === "board" && }
+ {tab === "board" && (
+ <>
+ {epics.length > 0 && (
+
+ Эпик:
+ {[{ id: 0, title: "все" }, ...epics].map((e) => {
+ const active = (epicFilter?.id ?? 0) === e.id;
+ return (
+
+ {e.title}
+
+ );
+ })}
+
+ )}
+
+ >
+ )}
+
+ {tab === "code" && code && }
+
+ {tab === "specs" && }
+
+ {tab === "pulls" && pulls && }
{tab === "releases" && (
@@ -280,17 +346,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
)}
{tab === "bugs" && (
- [t.id, `${p.key}-${t.number}`]))}
- webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
- />
+ [t.id, `${p.key}-${t.number}`]))} />
)}
{tab === "sessions" && (
diff --git a/apps/web/app/(app)/p/[key]/tabs.tsx b/apps/web/app/(app)/p/[key]/tabs.tsx
new file mode 100644
index 00000000..6c9f3491
--- /dev/null
+++ b/apps/web/app/(app)/p/[key]/tabs.tsx
@@ -0,0 +1,199 @@
+// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
+import { Archive, ExternalLink, GitBranch, GitPullRequest } from "lucide-react";
+import type { Epic, SpecSummary } from "@peppa/core";
+import type { OpenPull, RepoOverview } from "@peppa/runner";
+import { addEpic, editEpic } from "../../actions";
+import { Hidden } from "@/components/cards";
+import { Disclosure, Empty, Key, Section, StatusBadge } from "@/components/common";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input, Textarea } from "@/components/ui/input";
+
+const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" }) : "—");
+
+function plural(n: number, one: string, few: string, many: string) {
+ const m10 = n % 10;
+ const m100 = n % 100;
+ return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many;
+}
+
+export function CodeTab({ code }: { code: RepoOverview }) {
+ const gitea = (
+
+
+ Открыть в Gitea
+
+
+ );
+ if (code.error) {
+ return (
+
+ );
+ }
+ return (
+
+
README {code.readme && {code.readme.path} }>} actions={gitea}>
+ {code.readme ? (
+ {code.readme.text}
+ ) : (
+ {code.defaultBranch ? `В ветке ${code.defaultBranch} нет README.` : "Репозиторий пуст."}
+ )}
+
+
+
+ {code.branches.length === 0 ? (
+ Веток нет.
+ ) : (
+
+ {code.branches.map((b) => (
+
+
+
+ {b.name}
+
+ {b.name === code.defaultBranch && по умолчанию }
+ {b.sha.slice(0, 7)}
+
+ ))}
+
+ )}
+
+
+ {code.commits.length === 0 ? (
+ Коммитов нет.
+ ) : (
+
+ {code.commits.map((c) => (
+
+ {c.message}
+
+ {c.sha.slice(0, 7)}
+ {c.author} · {when(c.date)}
+
+
+ ))}
+
+ )}
+
+
+
+ );
+}
+
+export function SpecsTab({ specs }: { specs: SpecSummary[] }) {
+ return (
+
+ Что система умеет сейчас: требования OpenSpec из рабочей копии (openspec/specs). Обновляются, когда стори архивирует свой change.
+ {specs.length === 0 ? (
+ Спек ещё нет — они появляются после archive первого change.
+ ) : (
+ specs.map((s) => (
+
+
+ {s.name}
+
+ {s.requirements} {plural(s.requirements, "требование", "требования", "требований")}
+
+
+ {s.purpose && {s.purpose.split("\n")[0]} }
+
+ }
+ >
+ {s.text}
+
+ ))
+ )}
+
+ );
+}
+
+const CI_TONE = { success: "ok", failure: "danger", pending: "info", none: "muted", not_configured: "muted" } as const;
+
+export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error: string | null; repoUrl: string }) {
+ return (
+
+
+ Все PR в Gitea
+
+
+ }
+ >
+ {error ? (
+ {error}.
+ ) : pulls.length === 0 ? (
+ Открытых PR нет.
+ ) : (
+ pulls.map((p) => (
+
+
+
+ {p.branch}
+ {p.task ? (
+ <>
+ · {p.task.key}
+
+ {p.task.ci.label}
+ >
+ ) : (
+ · не стори Пеппы
+ )}
+
+
+ ))
+ )}
+
+ );
+}
+
+/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
+export function EpicsPanel({ projectId, epics, back }: { projectId: number; epics: Epic[]; back: string }) {
+ return (
+
+ {epics.length === 0 &&
Эпиков нет. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори.
}
+ {epics.map((e) => (
+
+
+ ›
+ {e.title}
+ #{e.id}
+
+
+
+
+
+
+ Сохранить
+
+
+
+
+ В архив
+
+
+
+
+ ))}
+
+
+
+
+ Добавить
+
+
+
+ );
+}
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index 7a12bfac..d227775d 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -13,6 +13,8 @@ export interface Card {
title: string;
status: string;
column: Column;
+ /** Epic label (PEP-66), if the story has an open epic. */
+ epic?: string | null;
}
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
@@ -32,7 +34,7 @@ const NEXT: Partial> = {
review: { to: "done", label: "Принять ✓" },
};
-/** Task board: drag a card (or use its button) to move it; the server starts/stops agents. */
+/** Story board: drag a card (or use its button) to move it; the server starts/stops agents. */
export function Board({ cards, back }: { cards: Card[]; back: string }) {
const [pending, start] = useTransition();
const [over, setOver] = useState(null);
@@ -81,8 +83,13 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
{card.key} {card.title}
- {(STATUS[card.status] || NEXT[c.id]) && (
+ {(STATUS[card.status] || NEXT[c.id] || card.epic) && (
+ {card.epic && (
+
+ {card.epic}
+
+ )}
{STATUS[card.status] &&
{STATUS[card.status]!.label} }
{NEXT[c.id] && (
move(card.key, NEXT[c.id]!.to)}>
diff --git a/apps/web/components/Incidents.tsx b/apps/web/components/Incidents.tsx
index 84bb6ae5..c5e9a088 100644
--- a/apps/web/components/Incidents.tsx
+++ b/apps/web/components/Incidents.tsx
@@ -1,4 +1,4 @@
-// Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list.
+// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
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";
@@ -14,22 +14,55 @@ function Code({ children }: { children: React.ReactNode }) {
return {children};
}
+/** Tab «Баги»: the incidents list. Settings live in «⋯ Настройки проекта» (PEP-66). */
export function IncidentsSection(props: {
projectId: number;
- projectKey: string;
+ back: string;
+ settings: IncidentSettings | null;
+ incidents: Incident[];
+ taskKeys: Map;
+}) {
+ const { settings: s } = props;
+ if (!s) {
+ return (
+
+ Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта.
+ Отслеживание ошибок не подключено — подключает владелец в «⋯ Настройки проекта».
+
+ );
+ }
+ const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
+ const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
+ return (
+ политика: {POLICY_RU[s.policy]}}>
+ {active.length === 0 ? Открытых ошибок нет. : active.map((i) => )}
+ {rest.length > 0 && (
+
+
+ {rest.map((i) => (
+
+ ))}
+
+
+ )}
+
+ );
+}
+
+/** «⋯ Настройки проекта» → Баги: connect Bugsink, DSN, webhook, incident policy (PEP-66). */
+export function IncidentSettingsPanel(props: {
+ projectId: number;
back: string;
isOwner: boolean;
settings: IncidentSettings | null;
sources: ErrorSource[];
- incidents: Incident[];
- taskKeys: Map;
webhookUrl: string | null;
}) {
const { projectId, back, settings: s } = props;
if (!s) {
return (
-
- Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.
+
+
Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят во вкладку «Баги» и становятся стори по политике проекта.
{props.isOwner ? (
@@ -41,72 +74,55 @@ export function IncidentsSection(props: {
) : (
Не подключено — подключает владелец проекта.
)}
-
+
);
}
- const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
- const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
- политика: {POLICY_RU[s.policy]}}>
- {active.length === 0 ? Открытых ошибок нет. : active.map((i) => )}
- {rest.length > 0 && (
-
-
- {rest.map((i) => (
-
- ))}
-
-
- )}
-
-
-
- {props.sources.map((src) => (
-
- DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}
- {src.dsn}
-
- ))}
-
- В коде: NEXT_PUBLIC_SENTRY_DSN / SENTRY_DSN из окружения, release = SHA деплоя,{" "}
- environment = prod, sendDefaultPii: false.
-
- {!s.webhookAuto && props.webhookUrl && (
-
- Вебхук не настроен автоматически. В Bugsink: проект → Alerts → Custom webhook:
- {props.webhookUrl}
- Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.
-
- )}
-
-
-
- Политика инцидентов
-
- {incidentPolicies.map((p) => (
-
- {p} — {POLICY_RU[p]}
-
- ))}
-
-
-
-
-
-
-
-
- Сохранить
-
+
+ {props.sources.map((src) => (
+
+ DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}
+ {src.dsn}
-
-
+ ))}
+
+ В коде: NEXT_PUBLIC_SENTRY_DSN / SENTRY_DSN из окружения, release = SHA деплоя,{" "}
+ environment = prod, sendDefaultPii: false.
+
+ {!s.webhookAuto && props.webhookUrl && (
+
+ Вебхук не настроен автоматически. В Bugsink: проект → Alerts → Custom webhook:
+ {props.webhookUrl}
+ Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.
+
+ )}
+
+
+
+ Политика инцидентов
+
+ {incidentPolicies.map((p) => (
+
+ {p} — {POLICY_RU[p]}
+
+ ))}
+
+
+
+
+
+
+
+
+ Сохранить
+
+
);
}
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index 07bab961..ebd6ab71 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -36,6 +36,16 @@ export interface GiteaPull {
head: { ref: string; sha: string; repo?: { full_name: string } | null };
base: { ref: string };
}
+export interface GiteaBranch {
+ name: string;
+ commit: { id: string; message: string; timestamp: string; author?: { name: string } };
+}
+export interface GiteaCommit {
+ sha: string;
+ html_url: string;
+ commit: { message: string; author: { name: string; date: string } };
+ author?: { login: string } | null;
+}
export interface GiteaCommitStatus {
context: string;
status: "pending" | "success" | "error" | "failure" | "warning";
@@ -171,11 +181,34 @@ export class GiteaClient {
return this.request
("GET", `${this.repoPath(owner, repo)}/pulls/${n}`);
}
+ /** Open pull requests, newest first. */
+ listOpenPulls(owner: string, repo: string) {
+ return this.request("GET", `${this.repoPath(owner, repo)}/pulls?state=open&sort=recentupdate&limit=50`);
+ }
+
async openPullForBranch(owner: string, repo: string, branch: string): Promise {
- const pulls = await this.request("GET", `${this.repoPath(owner, repo)}/pulls?state=open&limit=50`);
+ const pulls = await this.listOpenPulls(owner, repo);
return pulls.find((p) => p.head.ref === branch) ?? null;
}
+ listBranches(owner: string, repo: string) {
+ return this.request("GET", `${this.repoPath(owner, repo)}/branches?limit=50`);
+ }
+
+ /** Latest commits of `ref` (no diffs, no stats). */
+ listCommits(owner: string, repo: string, ref: string, limit = 10) {
+ return this.request("GET", `${this.repoPath(owner, repo)}/commits?sha=${encodeURIComponent(ref)}&limit=${limit}&stat=false&verification=false&files=false`);
+ }
+
+ /** README of `ref` (README.md, then other common names); null if there is none. */
+ async readme(owner: string, repo: string, ref: string): Promise<{ path: string; text: string } | null> {
+ for (const path of ["README.md", "readme.md", "README", "README.txt"]) {
+ const text = await this.fileText(owner, repo, path, ref);
+ if (text !== null) return { path, text };
+ }
+ return null;
+ }
+
/** Paths changed by a pull request. */
async pullFiles(owner: string, repo: string, n: number): Promise {
const files = await this.request>("GET", `${this.repoPath(owner, repo)}/pulls/${n}/files?limit=100`);
diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts
index 80c9adf9..b8efb491 100644
--- a/packages/core/src/incidents.ts
+++ b/packages/core/src/incidents.ts
@@ -52,11 +52,11 @@ export async function incidentSettingsBySecret(db: Db, secret: string): Promise<
return row ?? null;
}
-/** Turns error tracking on: webhook secret, default policy and the «Стабильность» goal. */
+/** Turns error tracking on: webhook secret, default policy and the «Стабильность» epic. */
export async function enableIncidents(db: Db, projectId: number, o: { webhookAuto?: boolean } = {}): Promise {
const existing = await getIncidentSettings(db, projectId);
if (existing) return existing;
- const goal = (await listGoals(db, projectId)).find((g) => g.title === STABILITY_GOAL) ?? (await createGoal(db, projectId, STABILITY_GOAL, "Ошибки из работающего продукта (Bugsink): задачи-баги создаются здесь."));
+ const goal = (await listGoals(db, projectId)).find((g) => g.title === STABILITY_GOAL) ?? (await createGoal(db, projectId, STABILITY_GOAL, "Ошибки из работающего продукта (Bugsink): стори-баги создаются в этом эпике."));
const [row] = await db
.insert(incidentSettings)
.values({ projectId, hookSecret: randomBytes(24).toString("base64url"), goalId: goal.id, webhookAuto: o.webhookAuto ?? false })
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 002a890e..5182e36a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -19,3 +19,4 @@ export * from "./incidents.ts";
export * from "./ci.ts";
export * from "./egov.ts";
export * from "./local-users.ts";
+export * from "./specs.ts";
diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts
index 5cd61037..eeb4918a 100644
--- a/packages/core/src/projects.ts
+++ b/packages/core/src/projects.ts
@@ -71,3 +71,12 @@ export async function updateGoal(db: Db, projectId: number, goalId: number, patc
const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning();
return row!;
}
+
+// PEP-66: goals are shown as «эпики» — optional labels that group stories. Same table and
+// rows (no migration); these are the names new code should use.
+export type Epic = Goal;
+export type EpicPatch = GoalPatch;
+export const createEpic = createGoal;
+export const listEpics = listGoals;
+export const getEpic = getGoal;
+export const updateEpic = updateGoal;
diff --git a/packages/core/src/specs.ts b/packages/core/src/specs.ts
new file mode 100644
index 00000000..4eacedd6
--- /dev/null
+++ b/packages/core/src/specs.ts
@@ -0,0 +1,27 @@
+// «Спеки» tab (PEP-66): what the system can do now — openspec/specs/*/spec.md of the
+// project's working copy.
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { Project } from "./projects.ts";
+
+export interface SpecSummary {
+ /** Capability name: the folder under openspec/specs. */
+ name: string;
+ purpose: string;
+ requirements: number;
+ text: string;
+}
+
+export function parseSpec(name: string, text: string): SpecSummary {
+ const purpose = text.match(/^## Purpose\s*\n([\s\S]*?)(?=^## |(?![\s\S]))/m)?.[1]?.trim() ?? "";
+ return { name, purpose: /^TBD\b/.test(purpose) ? "" : purpose, requirements: (text.match(/^### Requirement:/gm) ?? []).length, text };
+}
+
+export function listSpecs(project: Pick): SpecSummary[] {
+ const dir = join(project.workspacePath, "openspec", "specs");
+ if (!existsSync(dir)) return [];
+ return readdirSync(dir, { withFileTypes: true })
+ .filter((d) => d.isDirectory() && existsSync(join(dir, d.name, "spec.md")))
+ .map((d) => parseSpec(d.name, readFileSync(join(dir, d.name, "spec.md"), "utf8")))
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts
index a076ca01..c30e92c7 100644
--- a/packages/mcp/src/format.ts
+++ b/packages/mcp/src/format.ts
@@ -5,9 +5,9 @@ const NEXT_STEP: Record = {
proposing: "Допиши артефакты, `openspec validate`, затем сразу Apply (update_task status: in_progress). request_approval — только для архитектурных стопперов.",
awaiting_approval: "Ты запросил одобрение архитектурного решения. Ничего не реализуй — жди ответа PM, закончи ход.",
in_progress: "Apply: продолжай с первого невыполненного пункта tasks.md (workflow openspec-apply-change), report_progress по ходу. В конце — archive, PR, update_task(status: review).",
- review: "Задача в ревью у PM. Если в вопросах ниже есть замечания — доделай их; иначе ничего не делай.",
- done: "Задача завершена — ничего делать не нужно.",
- blocked: "Задача заблокирована — выясни причину в вопросах ниже или спроси PM через ask_pm.",
+ review: "Стори в ревью у PM. Если в вопросах ниже есть замечания — доделай их; иначе ничего не делай.",
+ done: "Стори завершена — ничего делать не нужно.",
+ blocked: "Стори заблокирована — выясни причину в вопросах ниже или спроси PM через ask_pm.",
};
export function formatTask(d: TaskDetails): string {
@@ -17,14 +17,14 @@ export function formatTask(d: TaskDetails): string {
"",
`- Проект: ${d.project.name} (${d.project.key})`,
`- Статус: **${task.status}**`,
- `- Цель: ${goal ? `#${goal.id} ${goal.title}` : "—"}`,
+ `- Эпик: ${goal ? `#${goal.id} ${goal.title}` : "—"}`,
`- 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 (goal?.description) lines.push("", `## Эпик #${goal.id}: ${goal.title}`, "", goal.description.trim());
if (d.incident) lines.push("", "## Инцидент", "", formatIncident(d.incident));
if (d.questions.length) {
lines.push("", "## Вопросы к PM");
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index e44a540d..ad0e3937 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -1,5 +1,5 @@
-// Peppa MCP server: gives Claude sessions inside a project access to its goals, tasks
-// and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
+// Peppa MCP server: gives Claude sessions inside a project access to its epics, stories
+// (tasks in the tool names) and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
@@ -11,7 +11,7 @@ import {
getTaskDetails,
incidentStatuses,
listIncidents,
- listGoals,
+ listEpics,
listTasks,
loadSharedRules,
PeppaError,
@@ -53,7 +53,7 @@ function tool(
const taskArg = z
.string()
- .describe(`Task key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
+ .describe(`Story key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
const projectArg = z
.string()
.optional()
@@ -67,53 +67,56 @@ async function projectOrDefault(p?: string) {
tool(
"get_rules",
- "Get Peppa's shared agent rules (task workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
+ "Get Peppa's shared agent rules (story workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
{},
async () => (await loadSharedRules()).text,
);
-tool("get_task", "Get a Peppa task: description, goal, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a task number.", { task: taskArg }, async ({ task }) =>
+tool("get_task", "Get a Peppa story (one business story = one OpenSpec change): description, epic, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a story number.", { task: taskArg }, async ({ task }) =>
formatTask(await getTaskDetails(db, await resolveTask(db, task, defaultKey))),
);
tool(
"list_tasks",
- "List tasks in a project, optionally filtered by status or goal.",
- { project: projectArg, status: z.enum(TASK_STATUSES).optional(), goal_id: z.number().int().optional() },
- async ({ project, status, goal_id }) => {
+ "List stories in a project, optionally filtered by status or epic.",
+ { project: projectArg, status: z.enum(TASK_STATUSES).optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id") },
+ async ({ project, status, epic_id, goal_id }) => {
const p = await projectOrDefault(project);
- const rows = await listTasks(db, { projectId: p.id, goalId: goal_id, statuses: status ? [status] : undefined });
- if (!rows.length) return "No tasks.";
- return rows.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`).join("\n");
+ const rows = await listTasks(db, { projectId: p.id, goalId: epic_id ?? goal_id, statuses: status ? [status] : undefined });
+ if (!rows.length) return "No stories.";
+ return rows.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`).join("\n");
},
);
-tool("list_goals", "List the open top-level goals of a project.", { project: projectArg }, async ({ project }) => {
+const listEpicsText = async ({ project }: { project?: string }) => {
const p = await projectOrDefault(project);
- const rows = await listGoals(db, p.id);
- if (!rows.length) return "No open goals.";
+ const rows = await listEpics(db, p.id);
+ if (!rows.length) return "No open epics.";
return rows.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
-});
+};
+tool("list_epics", "List the open epics of a project (labels that group stories).", { project: projectArg }, listEpicsText);
+tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, listEpicsText);
tool(
"create_task",
- "Create a new task (e.g. follow-up work discovered outside the current change's scope). Link it to a goal when possible.",
+ "Create a new story (e.g. follow-up work discovered outside the current change's scope). Label it with an epic when one fits.",
{
title: z.string().min(3),
description: z.string().optional(),
- goal_id: z.number().int().optional(),
+ epic_id: z.number().int().optional(),
+ goal_id: z.number().int().optional().describe("Alias of epic_id"),
project: projectArg,
},
- async ({ title, description, goal_id, project }) => {
+ async ({ title, description, epic_id, goal_id, project }) => {
const p = await projectOrDefault(project);
- const ref = await createTask(db, { projectId: p.id, goalId: goal_id, title, description });
+ const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description });
return `Created ${ref.key}: ${title}`;
},
);
tool(
"update_task",
- "Update a task's status, OpenSpec change name, PR URL, title or description.",
+ "Update a story's status, OpenSpec change name, PR URL, title or description.",
{
task: taskArg,
status: z.enum(TASK_STATUSES).optional(),
@@ -125,7 +128,7 @@ tool(
async ({ task, status, openspec_change, pr_url, title, description }) => {
const ref = await resolveTask(db, task, defaultKey);
// Acceptance stays with the PM: agents can't mark work done or approve themselves.
- if (status === "done") throw new PeppaError("Only the PM marks a task done. Open a PR and set status: review.");
+ if (status === "done") throw new PeppaError("Only the PM marks a story done. Open a PR and set status: review.");
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.");
}
@@ -143,7 +146,7 @@ tool(
tool(
"request_approval",
- "Ask the PM to approve an ARCHITECTURAL decision in a task's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
+ "Ask the PM to approve an ARCHITECTURAL decision in a story's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
{ task: taskArg, summary: z.string().min(10).describe("What, why, risks, open questions — readable on a phone") },
async ({ task, summary }) => {
const ref = await resolveTask(db, task, defaultKey);
@@ -169,7 +172,7 @@ tool(
tool(
"report_progress",
- "Log a short progress note on a task (visible to the PM in the web UI / Telegram digest).",
+ "Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
{ task: taskArg, text: z.string().min(3) },
async ({ task, text }) => {
const ref = await resolveTask(db, task, defaultKey);
@@ -180,19 +183,19 @@ tool(
tool(
"list_incidents",
- "List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked task.",
+ "List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
async ({ project, status }) => {
const p = await projectOrDefault(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return "No incidents.";
- return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · task #${i.taskId}` : ""}`).join("\n");
+ return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · story #${i.taskId}` : ""}`).join("\n");
},
);
tool(
"get_incident",
- "Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug task made from an incident: first write a test reproducing this stack.",
+ "Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug story made from an incident: first write a test reproducing this stack.",
{ id: z.number().int() },
async ({ id }) => {
const i = await getIncident(db, id);
diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts
index a2176106..10b9fa4c 100644
--- a/packages/mcp/src/manager.ts
+++ b/packages/mcp/src/manager.ts
@@ -2,14 +2,14 @@
// user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
- createGoal,
+ createEpic,
createTask,
- getGoal,
- updateGoal,
+ getEpic,
+ updateEpic,
getProject,
getQuestion,
getTaskDetails,
- listGoals,
+ listEpics,
listMembers,
listTasks,
listUserProjects,
@@ -41,16 +41,16 @@ const COLUMNS = ["backlog", "in_progress", "review", "done"] as const;
const COLUMN_NAME: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
/** Sent to clients on initialize: how Peppa is organised and how to use the tools. */
-export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement tasks in Gitea repos, following OpenSpec.
+export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement stories in Gitea repos, following OpenSpec.
-Model: project (a Gitea repo, key like PEP) → goals (top-level objectives) → tasks (PEP-12, one deliverable each) → board columns Backlog / In progress / Review / Done.
-- Moving a task to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the task to review. backlog/done stop the agent.
-- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed task).
+Model: project (a Gitea repo, key like PEP) → epics (optional labels that group stories) → stories (PEP-12: one business story = one OpenSpec change; the tools call them "tasks") → board columns Backlog / In progress / Review / Done. Note: "tasks" inside an OpenSpec change (tasks.md) are the agent's checklist items, not stories.
+- Moving a story to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the story to review. backlog/done stop the agent.
+- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed story).
Good habits:
-- Before creating, look: list_projects, list_goals, list_tasks. Don't duplicate — fix with update_task / update_goal.
-- Put tasks under a goal (goal_id). Write task descriptions with context and a "Definition of done" list; the agent works from them.
-- Only move a task to in_progress when the user asks to start the work.
+- Before creating, look: list_projects, list_epics, list_tasks. Don't duplicate — fix with update_task / update_epic.
+- Label stories with an epic (epic_id) when one fits. Write story descriptions with context and a "Definition of done" list; the agent works from them.
+- Only move a story 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.
@@ -75,10 +75,10 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
await projectForUser(db, user.id, ref.project.id);
return ref;
};
- const taskArg = z.string().describe("Task key, e.g. PEP-3");
+ const taskArg = z.string().describe("Story key, e.g. PEP-3");
const projectArg = z.string().describe("Project key (e.g. PEP) or slug");
- tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo URL, task counts by board column).", {}, true, async () => {
+ tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo URL, story counts by board column).", {}, true, async () => {
const ps = await listUserProjects(db, user.id);
if (!ps.length) return "No projects yet. Create one at " + webUrl + "/projects/new";
const lines = [];
@@ -124,43 +124,35 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
- tool("list_goals", "List open top-level goals of a project.", { project: projectArg }, true, async ({ project }) => {
+ // Epics (PEP-66) live in the goals table; the *_goal(s) tools and goal_id stay as aliases.
+ const listEpicsText = async ({ project }: { project: string }) => {
const p = await ownedProject(project);
- const gs = await listGoals(db, p.id);
- return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals.";
- });
+ const gs = await listEpics(db, p.id);
+ return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open epics.";
+ };
+ const createEpicShape = { project: projectArg, title: z.string().trim().min(3), description: z.string().optional().describe("What the epic is about; agents get it with every story of the epic") };
+ const createEpicText = async ({ project, title, description }: { project: string; title: string; description?: string }) => {
+ const p = await ownedProject(project);
+ const g = await createEpic(db, p.id, title, description);
+ return `Created epic #${g.id} in ${p.key}: ${g.title}`;
+ };
+ const epicPatch = { title: z.string().trim().min(3).optional(), description: z.string().optional(), status: z.enum(["open", "done", "archived"]).optional() };
+ const updateEpicText = async (a: { project: string; epic_id?: number; goal_id?: number; title?: string; description?: string; status?: "open" | "done" | "archived" }) => {
+ const { project, title, description, status } = a;
+ const id = a.epic_id ?? a.goal_id!;
+ if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status");
+ const p = await ownedProject(project);
+ await getEpic(db, p.id, id).catch(() => { throw new PeppaError("Не найдено"); });
+ const g = await updateEpic(db, p.id, id, { title, description, status });
+ return `Epic #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
+ };
- tool(
- "create_goal",
- "Create a top-level goal in a project (an objective that groups tasks).",
- { project: projectArg, title: z.string().trim().min(3), description: z.string().optional() },
- false,
- async ({ project, title, description }) => {
- const p = await ownedProject(project);
- const g = await createGoal(db, p.id, title, description);
- return `Created goal #${g.id} in ${p.key}: ${g.title}`;
- },
- );
-
- tool(
- "update_goal",
- "Edit a goal: title, description and/or status (open, done = achieved, archived). Its tasks are not changed.",
- {
- project: projectArg,
- goal_id: z.number().int(),
- title: z.string().trim().min(3).optional(),
- description: z.string().optional(),
- status: z.enum(["open", "done", "archived"]).optional(),
- },
- false,
- async ({ project, goal_id, title, description, status }) => {
- if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status");
- const p = await ownedProject(project);
- await getGoal(db, p.id, goal_id).catch(() => { throw new PeppaError("Не найдено"); });
- const g = await updateGoal(db, p.id, goal_id, { title, description, status });
- return `Goal #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
- },
- );
+ tool("list_epics", "List open epics of a project: labels that group stories (like GitHub labels/milestones).", { project: projectArg }, true, listEpicsText);
+ tool("create_epic", "Create an epic in a project: a label that groups stories.", createEpicShape, false, createEpicText);
+ tool("update_epic", "Edit an epic: title, description and/or status (open, done, archived — hidden from the board filter). Its stories are not changed.", { project: projectArg, epic_id: z.number().int(), ...epicPatch }, false, updateEpicText);
+ tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, true, listEpicsText);
+ tool("create_goal", "Alias of create_epic (goals were renamed to epics).", createEpicShape, false, createEpicText);
+ tool("update_goal", "Alias of update_epic with goal_id (goals were renamed to epics).", { project: projectArg, goal_id: z.number().int(), ...epicPatch }, false, updateEpicText);
tool(
"create_project",
@@ -168,7 +160,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
{
name: z.string().trim().min(2).describe("Human name, e.g. Payments"),
slug: z.string().describe("Repo name: a-z, 0-9, dashes"),
- key: z.string().describe("Task key prefix, 2–10 letters/digits, e.g. PAY"),
+ key: z.string().describe("Story key prefix, 2–10 letters/digits, e.g. PAY"),
owner: z.string().optional().describe("Gitea namespace: your login (default) or an org"),
existing: z.boolean().optional().describe("Connect an existing repo owner/slug instead of creating one"),
visibility: z.enum(["private", "public"]).optional().describe("New repo visibility (default private: only the namespace owner/org members with access, peppa-bot and project members see it)"),
@@ -187,7 +179,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"list_tasks",
- "List tasks of a project as a board (Backlog / In progress / Review / Done), optionally one column.",
+ "List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column.",
{ project: projectArg, column: z.enum(COLUMNS).optional() },
true,
async ({ project, column }) => {
@@ -196,43 +188,51 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
const out: string[] = [];
for (const c of column ? [column] : COLUMNS) {
const inCol = ts.filter((t) => columnOf(t.status) === c);
- out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`));
+ out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`));
}
return out.join("\n");
},
);
- tool("get_task", "Get a task: description, goal, status, OpenSpec change, PM questions, progress.", { task: taskArg }, true, async ({ task }) => {
+ tool("get_task", "Get a story: description, epic, status, OpenSpec change, PM questions, progress, CI checks.", { task: taskArg }, true, async ({ task }) => {
const ref = await ownedTask(task);
return `${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`;
});
tool(
"create_task",
- "Create a task in a project (lands in Backlog). Link it to a goal when possible.",
- { project: projectArg, title: z.string().min(3), description: z.string().optional(), goal_id: z.number().int().optional() },
+ "Create a story in a project (lands in Backlog). Label it with an epic when one fits.",
+ {
+ project: projectArg,
+ title: z.string().min(3),
+ description: z.string().optional(),
+ epic_id: z.number().int().optional().describe("Epic of the same project (list_epics)"),
+ goal_id: z.number().int().optional().describe("Alias of epic_id"),
+ },
false,
- async ({ project, title, description, goal_id }) => {
+ async ({ project, title, description, epic_id, goal_id }) => {
const p = await ownedProject(project);
- const ref = await createTask(db, { projectId: p.id, title, description, goalId: goal_id });
+ const ref = await createTask(db, { projectId: p.id, title, description, goalId: epic_id ?? goal_id });
return `Created ${ref.key}: ${title} (Backlog). ${webUrl}/t/${ref.key}`;
},
);
tool(
"update_task",
- "Edit a task: title, description and/or goal (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
+ "Edit a story: title, description and/or epic (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
{
task: taskArg,
title: z.string().trim().min(3).optional().describe("New title"),
description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"),
- goal_id: z.number().int().nullable().optional().describe("Move to this goal of the same project; null detaches the task from its goal"),
+ epic_id: z.number().int().nullable().optional().describe("Label with this epic of the same project; null removes the epic"),
+ goal_id: z.number().int().nullable().optional().describe("Alias of epic_id"),
},
false,
- async ({ task, title, description, goal_id }) => {
- if (title === undefined && description === undefined && goal_id === undefined) throw new PeppaError("Nothing to update: pass title, description and/or goal_id");
+ async ({ task, title, description, epic_id, goal_id }) => {
+ const epic = epic_id !== undefined ? epic_id : goal_id;
+ if (title === undefined && description === undefined && epic === undefined) throw new PeppaError("Nothing to update: pass title, description and/or epic_id");
const ref = await ownedTask(task);
- await updateTask(db, ref, { title, description, goalId: goal_id });
+ await updateTask(db, ref, { title, description, goalId: epic });
const updated = await resolveTask(db, ref.key);
return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`;
},
@@ -240,7 +240,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"move_task",
- "Move a task card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.",
+ "Move a story card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.",
{ task: taskArg, to: z.enum(COLUMNS), provider: z.enum(["claude", "codex"]).optional().describe("Agent for in_progress (default claude)") },
false,
async ({ task, to, provider }) => {
@@ -250,7 +250,7 @@ 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 }) => {
+ tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, stories, 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(" · ");
@@ -266,7 +266,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
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.`;
+ return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (stories ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`;
},
);
@@ -291,7 +291,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' 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.",
+ "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 story's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the story, any other text goes back to the agent.",
{ question_id: z.number().int(), answer: z.string().min(1) },
false,
async ({ question_id, answer }) => {
@@ -316,7 +316,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"list_incidents",
- "Production errors of a project (from Bugsink): id, status (pending = waits for the user's decision), title, where, environment, release, events, task.",
+ "Production errors of a project (from Bugsink): id, status (pending = waits for the user's decision), title, where, environment, release, events, story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
true,
async ({ project, status }) => {
@@ -334,7 +334,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"decide_incident",
- "Decide what to do with a production error: backlog (bug task in the backlog), start (bug task + agent starts on it), ignore.",
+ "Decide what to do with a production error: backlog (bug story in the backlog), start (bug story + agent starts on it), ignore.",
{ id: z.number().int(), action: z.enum(["backlog", "start", "ignore"]) },
false,
async ({ id, action }) => {
@@ -346,7 +346,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"resolve_incident",
- "Mark a production error fixed (until CI/CD closes them by release). Also resolves it in Bugsink; if it comes back, the incident reopens and its task returns to the backlog.",
+ "Mark a production error fixed (until CI/CD closes them by release). Also resolves it in Bugsink; if it comes back, the incident reopens and its story returns to the backlog.",
{ id: z.number().int(), release: z.string().optional().describe("Release (commit SHA) with the fix, if known") },
false,
async ({ id, release }) => {
@@ -356,7 +356,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
- tool("get_incident_policy", "A project's incident policy: what happens to a new production error, triage prompt, environments, daily task limit, ignore pattern.", { project: projectArg }, true, async ({ project }) => {
+ tool("get_incident_policy", "A project's incident policy: what happens to a new production error, triage prompt, environments, daily story limit, ignore pattern.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const s = await getIncidentSettings(db, p.id);
if (!s) return "Error tracking is not connected for this project.";
@@ -364,14 +364,14 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
`Policy: ${s.policy} — ${POLICY_RU[s.policy]}`,
`Triage prompt: ${s.triagePrompt ?? "—"}`,
`Environments: ${s.environments.join(", ")}`,
- `Daily task limit: ${s.dailyLimit}`,
+ `Daily story limit: ${s.dailyLimit}`,
`Ignore pattern: ${s.ignorePattern ?? "—"}`,
].join("\n");
});
tool(
"set_incident_policy",
- "Change what happens to new production errors: notify (Telegram only), backlog (bug task, default), start (bug task + agent), ask (Telegram buttons), triage (a triage agent decides by triage_prompt — the user's own words on how to decide; falls back to ask when unsure).",
+ "Change what happens to new production errors: notify (Telegram only), backlog (bug story, default), start (bug story + agent), ask (Telegram buttons), triage (a triage agent decides by triage_prompt — the user's own words on how to decide; falls back to ask when unsure).",
{
project: projectArg,
policy: z.enum(incidentPolicies).optional(),
diff --git a/packages/runner/src/code.ts b/packages/runner/src/code.ts
new file mode 100644
index 00000000..2c856b2a
--- /dev/null
+++ b/packages/runner/src/code.ts
@@ -0,0 +1,101 @@
+// Project page tabs «Код» and «PR» (PEP-66): what the repo holds right now, asked from Gitea
+// with the same clients as describeRepo (owner first, then peppa-bot), cached for a minute,
+// never failing the page.
+import { taskCiSummary, taskForCheck, type CiSummary, type GiteaClient, type Project } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { loadEnv } from "@peppa/shared";
+import { repoAdmins } from "./share.ts";
+
+const TIMEOUT_MS = 5000;
+const CACHE_MS = 60_000;
+const cache = new Map();
+
+export interface RepoOverview {
+ url: string;
+ defaultBranch: string | null;
+ readme: { path: string; text: string } | null;
+ branches: Array<{ name: string; sha: string; message: string; date: string | null }>;
+ commits: Array<{ sha: string; message: string; author: string; date: string; url: string }>;
+ /** Set when Gitea could not be asked: the tab shows the link and this message. */
+ error: string | null;
+}
+
+export interface OpenPull {
+ number: number;
+ title: string;
+ url: string;
+ branch: string;
+ /** Story of the PR (branch `task/-` or the story's pr_url) and its checks. */
+ task: { key: string; title: string; status: string; ci: CiSummary } | null;
+}
+
+/** Asks Gitea with the first client that answers in time; `null` if none did. */
+async function withRepoClient(db: Db, project: Project, ask: (c: GiteaClient) => Promise): Promise {
+ for (const c of await repoAdmins(db, project)) {
+ const timeout = new Promise((r) => setTimeout(() => r(null), TIMEOUT_MS).unref());
+ const v = await Promise.race([ask(c), timeout]).catch(() => null);
+ if (v !== null) return v;
+ }
+ return null;
+}
+
+async function cached(key: string, fresh: boolean | undefined, load: () => Promise): Promise {
+ const hit = cache.get(key);
+ if (!fresh && hit && Date.now() - hit.at < CACHE_MS) return hit.value as T;
+ const value = await load();
+ if (!value.error) cache.set(key, { at: Date.now(), value });
+ return value;
+}
+
+const firstLine = (s: string) => s.split("\n")[0]!.trim();
+
+/** README of the default branch, branches and the latest commits («Код»). */
+export function repoOverview(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise {
+ const url = `${loadEnv().GITEA_URL}/${project.giteaOwner}/${project.giteaRepo}`;
+ return cached(`code:${project.id}`, opts.fresh, async () => {
+ const o = project.giteaOwner;
+ const r = project.giteaRepo;
+ const got = await withRepoClient(db, project, async (c) => {
+ const repo = await c.getRepo(o, r);
+ if (!repo) return { missing: true as const };
+ if (repo.empty) return { missing: false as const, repo, readme: null, branches: [], commits: [] };
+ const ref = repo.default_branch || "main";
+ const [readme, branches, commits] = await Promise.all([c.readme(o, r, ref), c.listBranches(o, r), c.listCommits(o, r, ref, 10)]);
+ return { missing: false as const, repo, readme, branches, commits };
+ });
+ if (!got) return { url, defaultBranch: null, readme: null, branches: [], commits: [], error: "Gitea сейчас не отвечает" };
+ if (got.missing) return { url, defaultBranch: null, readme: null, branches: [], commits: [], error: "Репозиторий не найден в Gitea" };
+ const def = got.repo.default_branch || "main";
+ return {
+ url: got.repo.html_url || url,
+ defaultBranch: def,
+ readme: got.readme,
+ branches: got.branches
+ .map((b) => ({ name: b.name, sha: b.commit.id, message: firstLine(b.commit.message ?? ""), date: b.commit.timestamp ?? null }))
+ .sort((a, b) => (a.name === def ? -1 : b.name === def ? 1 : (b.date ?? "").localeCompare(a.date ?? ""))),
+ commits: got.commits.map((c) => ({ sha: c.sha, message: firstLine(c.commit.message), author: c.author?.login ?? c.commit.author.name, date: c.commit.author.date, url: c.html_url })),
+ error: null,
+ };
+ });
+}
+
+/** Open PRs of the repo; a story's PR carries the story and its checks («PR»). */
+export async function openPulls(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<{ pulls: OpenPull[]; error: string | null }> {
+ const listed = await cached(`pulls:${project.id}`, opts.fresh, async () => {
+ const pulls = await withRepoClient(db, project, (c) => c.listOpenPulls(project.giteaOwner, project.giteaRepo));
+ return pulls ? { pulls, error: null } : { pulls: [], error: "Gitea сейчас не отвечает" };
+ });
+ // Story and checks come from Peppa's own DB on every call: they change faster than a minute.
+ const pulls: OpenPull[] = [];
+ for (const p of listed.pulls) {
+ const ref = await taskForCheck(db, project, p.head.ref, p.number);
+ pulls.push({
+ number: p.number,
+ title: p.title,
+ url: p.html_url,
+ branch: p.head.ref,
+ task: ref ? { key: ref.key, title: ref.task.title, status: ref.task.status, ci: await taskCiSummary(db, ref) } : null,
+ });
+ }
+ return { pulls, error: listed.error };
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index 6efa5781..ec96a83e 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -16,3 +16,4 @@ export * from "./triage.ts";
export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./platform-release.ts";
+export * from "./code.ts";
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index e7091460..9320fa07 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -383,6 +383,32 @@ export class MockGitea {
return { status: 201, body: {} };
}
if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) };
+ if (method === "GET" && sub === "branches") {
+ const out = execFileSync("git", ["--git-dir", r.path, "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(authorname)%09%(committerdate:iso-strict)%09%(contents:subject)", "refs/heads"], { encoding: "utf8" }).trim();
+ return {
+ status: 200,
+ body: out ? out.split("\n").map((l) => {
+ const [name, id, author, timestamp, message] = l.split("\t");
+ return { name, commit: { id, message, timestamp, author: { name: author } } };
+ }) : [],
+ };
+ }
+ if (method === "GET" && sub === "commits") {
+ const ref = q.get("sha") ?? "main";
+ let out = "";
+ try {
+ out = execFileSync("git", ["--git-dir", r.path, "log", `-${Number(q.get("limit") ?? 30)}`, "--format=%H%x09%an%x09%aI%x09%s", ref], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
+ } catch {
+ return { status: 404, body: { message: "ref not found" } };
+ }
+ return {
+ status: 200,
+ body: out ? out.split("\n").map((l) => {
+ const [sha, name, date, message] = l.split("\t");
+ return { sha, html_url: `${this.url}/${r.owner}/${r.name}/commit/${sha}`, commit: { message, author: { name, date } }, author: null };
+ }) : [],
+ };
+ }
if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) {
try {
const text = execFileSync("git", ["--git-dir", r.path, "show", `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
--
2.45.2
From 358fb5c0e96dcfc4d63a8286194abf2eedec40fc 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:26:31 +0500
Subject: [PATCH 026/518] =?UTF-8?q?PEP-66:=20=C2=AB=D1=81=D1=82=D0=BE?=
=?UTF-8?q?=D1=80=D0=B8=C2=BB=20and=20=C2=AB=D1=8D=D0=BF=D0=B8=D0=BA=D0=B8?=
=?UTF-8?q?=C2=BB=20in=20web,=20bot,=20notifications,=20MCP=20texts,=20hel?=
=?UTF-8?q?p;=20tab=20tests?=
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/bot/src/bot.ts | 2 +-
apps/web/app/(app)/help/page.tsx | 38 ++---
apps/web/app/(app)/projects/new/page.tsx | 2 +-
apps/web/app/(app)/projects/page.tsx | 2 +-
apps/web/app/(app)/runners/page.tsx | 6 +-
apps/web/app/(app)/t/[key]/page.tsx | 13 +-
apps/web/app/layout.tsx | 2 +-
apps/web/app/login/page.tsx | 2 +-
apps/web/app/oauth/authorize/page.tsx | 4 +-
apps/web/components/RunnerConsole.tsx | 4 +-
apps/web/components/SettingsDialog.tsx | 2 +-
openspec/changes/pep-66-github-tabs/tasks.md | 22 +--
packages/core/src/incidents.ts | 12 +-
packages/runner/src/ci.ts | 2 +-
packages/runner/src/deploy.ts | 2 +-
packages/runner/src/flow.ts | 2 +-
packages/runner/src/hook.ts | 6 +-
packages/runner/src/incidents.ts | 4 +-
packages/runner/src/provision.ts | 2 +-
packages/runner/src/sessions.ts | 4 +-
packages/runner/src/triage.ts | 6 +-
packages/runner/src/watchdog.ts | 2 +-
packages/testkit/test/incidents.test.ts | 4 +-
packages/testkit/test/oauth.test.ts | 46 +++++-
packages/testkit/test/project-tabs.test.ts | 155 +++++++++++++++++++
26 files changed, 273 insertions(+), 75 deletions(-)
create mode 100644 packages/testkit/test/project-tabs.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index b46e9221..116f9c71 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`), страница рисует центр и правую панель через `` (по умолчанию `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/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`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. 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 `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (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`)
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 5d6b8ed5..930188f3 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -162,7 +162,7 @@ export function createBot(o: BotOptions) {
if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`;
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
scheduleReconcile();
- return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории задачи.";
+ return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори.";
}
const canAccess = (user: User, projectId: number) =>
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 1d0d40c5..3f9c7ada 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -4,12 +4,12 @@ import { Workspace } from "@/components/Workspace";
import { PageHeader, Section } from "@/components/common";
const TOOLS: Array<[string, string]> = [
- ["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько задач в каждой колонке"],
+ ["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке"],
["create_project", "новый проект: репозиторий в Gitea (приватный по умолчанию или публичный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
- ["list_goals / create_goal / update_goal", "цели проекта: завести, переименовать, отметить достигнутой или убрать в архив"],
+ ["list_epics / create_epic / update_epic", "эпики проекта (метки стори): завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"],
- ["get_task", "карточка задачи: описание, цель, статус, OpenSpec, вопросы, прогресс"],
- ["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"],
+ ["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, прогресс"],
+ ["create_task / update_task", "завести стори (в Бэклог, с эпиком epic_id); поправить название, описание, эпик"],
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"],
@@ -21,19 +21,19 @@ const TOOLS: Array<[string, string]> = [
const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Создать проект", say: "Создай проект «Платежи», репо payments, ключ PAY", how: "create_project → проект с доской; агенты будут работать в этом репозитории" },
- { title: "Завести цель", say: "В PAY заведи цель «Приём оплат картой» — зачем и какой результат", how: "create_goal. Цель — верхнеуровневый результат, под ней собираются задачи" },
- { title: "Создать задачу под целью", say: "Под этой целью создай задачу «Форма оплаты» с условиями готовности: …", how: "create_task с goal_id. Пишите контекст и список «Условия готовности» — по ним работает агент" },
- { title: "Поправить задачу", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в цель #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
+ { title: "Завести эпик", say: "В PAY заведи эпик «Оплата картой» — зачем и какой результат", how: "create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори" },
+ { title: "Создать стори в эпике", say: "В этом эпике создай стори «Форма оплаты» с условиями готовности: …", how: "create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент" },
+ { title: "Поправить стори", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
{ title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" },
- { title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит задачу в Ревью" },
+ { title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит стори в Ревью" },
{ title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" },
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
- { title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «Подключить отслеживание ошибок»" },
+ { 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" },
+ { title: "Закрыть эпик", say: "Эпик #5 закончен", how: "update_epic status=done — эпик пропадает из фильтра доски, стори не меняются" },
];
export default async function Help() {
@@ -45,15 +45,15 @@ export default async function Help() {
- Проект — репозиторий в Gitea с ключом задач (например, PEP). Создаётся из веба или через MCP.
+ Проект — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки Доска · Код (README, ветки, коммиты) · Спеки (что система умеет сейчас — openspec/specs ) · PR (открытые PR и их проверки) · Релизы · Баги · Сессии ; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке.
Где репозиторий — в выбранном при создании пространстве Gitea: личном (<ваш логин>/<slug> ) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), peppa-bot и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.
- Цель — верхнеуровневый результат («Мультипользовательская платформа»). Группирует задачи и даёт агенту контекст «зачем».
- Задача (PEP-12) — один результат с описанием и условиями готовности.
+ Стори (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты tasks.md внутри change, не путать.
+ Эпик — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP.
Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
- Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
+ Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
Локальные пользователи — аккаунты Пеппы без Gitea: входят по логину и паролю на странице входа, создаёт их суперадмин в разделе «Пользователи», пароль меняется в «Настройках». Их добавляют в участники по логину Пеппы; доступа к репозиторию в Gitea у них нет — код только через Пеппу, а их новые проекты создаются в пространстве peppa-bot .
- Раннер — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, задача, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).
+ Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).
Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
@@ -98,10 +98,10 @@ export default async function Help() {
Каждый PR агента проверяет Gitea Actions: install , lint ,{" "}
typecheck , test , build . Команды —
- в .peppa/project.json → checks (заполняет агент на первой задаче), workflow приходит из
+ в .peppa/project.json → checks (заполняет агент на первой стори), workflow приходит из
шаблона; в старый проект — командой peppa ci connect KEY (PR от Пеппы). Результат виден в
- карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
- прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без
+ карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
+ прогонов подряд Пеппа спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без
конфликтов. PR, меняющий конвейер (.gitea/ , checks ,{" "}
deploy ), сам не мержится никогда.
@@ -125,7 +125,7 @@ export default async function Help() {
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
- проекта: сообщением, задачей или с кнопками «В бэклог / В работу / Игнорировать».
+ проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать».
diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx
index 809f66d6..8832a812 100644
--- a/apps/web/app/(app)/projects/new/page.tsx
+++ b/apps/web/app/(app)/projects/new/page.tsx
@@ -51,7 +51,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
- Ключ задач
+ Ключ стори
diff --git a/apps/web/app/(app)/projects/page.tsx b/apps/web/app/(app)/projects/page.tsx
index d5cddd57..f6c94222 100644
--- a/apps/web/app/(app)/projects/page.tsx
+++ b/apps/web/app/(app)/projects/page.tsx
@@ -26,7 +26,7 @@ export default async function Projects({ searchParams }: { searchParams: Promise
}
>
- Свои и общие проекты: доска задач, релизы, ошибки из прода, участники.
+ Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.
diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx
index dca587f2..a7be1542 100644
--- a/apps/web/app/(app)/runners/page.tsx
+++ b/apps/web/app/(app)/runners/page.tsx
@@ -59,7 +59,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
- Агенты в tmux по задачам твоих и общих проектов: кто ждёт тебя, кто работает, что готово.
+ Агенты в tmux по стори твоих и общих проектов: кто ждёт тебя, кто работает, что готово.
{FILTERS.map((x) => {
@@ -84,11 +84,11 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
{filter && }
-
+
{shown.length === 0 ? (
- {q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}
+ {q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси стори в «В работе» на доске проекта."}
) : (
{shown.map((s) => (
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index bb27362b..8508aa15 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -1,7 +1,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react";
-import { taskCiSummary } from "@peppa/core";
+import { getEpic, taskCiSummary } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Hidden, QuestionCard, SessionCard } from "@/components/cards";
@@ -16,7 +16,7 @@ import { startTaskSession } from "../../actions";
const CI_ICON = { success: , failure: , pending: };
-export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
+export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key } = await params;
const { error } = await searchParams;
@@ -26,6 +26,7 @@ export default async function TaskPage({ params, searchParams }: { params: Promi
const { questions, sessions, events } = await taskActivity(task.id);
const artifacts = openspecArtifacts(project, task.openspecChange);
const ci = await taskCiSummary(db, ref);
+ const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null;
const back = `/t/${ref.key}`;
const aside = (
@@ -77,6 +78,14 @@ export default async function TaskPage({ params, searchParams }: { params: Promi
crumbs={
<>
{project.name}
+ {epic && (
+ <>
+ /
+
+ эпик «{epic.title}»
+
+ >
+ )}
>
}
title={
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
index aa8316fd..368ed35a 100644
--- a/apps/web/app/layout.tsx
+++ b/apps/web/app/layout.tsx
@@ -6,7 +6,7 @@ import { cn } from "@/lib/utils";
import { THEME_COOKIE } from "@/lib/theme";
import "./app.css";
-export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, задачи и агенты" };
+export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты" };
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.
diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index 490dde30..86e36039 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -16,7 +16,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
-
Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.
+
Софтвейр-фабрика: проекты в Gitea, стори по OpenSpec, агенты Claude Code и Codex.
Войти через Gitea
diff --git a/apps/web/app/oauth/authorize/page.tsx b/apps/web/app/oauth/authorize/page.tsx
index 086ce7fd..3835c96d 100644
--- a/apps/web/app/oauth/authorize/page.tsx
+++ b/apps/web/app/oauth/authorize/page.tsx
@@ -43,8 +43,8 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
{client.name} ({host}) просит доступ к Пеппе от имени {user.login} .
- видеть ваши проекты, цели, задачи и вопросы агентов;
- создавать задачи и двигать карточки — перенос в «В работе» запускает агента;
+ видеть ваши проекты, эпики, стори и вопросы агентов;
+ создавать стори и двигать карточки — перенос в «В работе» запускает агента;
отвечать на вопросы агентов и принимать ревью.
Отозвать доступ можно в «Настройки → Подключённые приложения».
diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx
index 7fd70724..a060b38b 100644
--- a/apps/web/components/RunnerConsole.tsx
+++ b/apps/web/components/RunnerConsole.tsx
@@ -43,7 +43,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
{s.taskKey ?? s.projectKey}
- {s.taskTitle ?? "без задачи"}
+ {s.taskTitle ?? "без стори"}
{limited ? (
<>
@@ -85,7 +85,7 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }:
{s.taskKey && {s.taskKey} }
- {s.taskTitle ?? "без задачи"}
+ {s.taskTitle ?? "без стори"}
{s.status === "rate_limited" && (
diff --git a/apps/web/components/SettingsDialog.tsx b/apps/web/components/SettingsDialog.tsx
index da1fc9c3..ac15038a 100644
--- a/apps/web/components/SettingsDialog.tsx
+++ b/apps/web/components/SettingsDialog.tsx
@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
/**
* Button that opens a side dialog (native ) with content rendered on the server.
- * Default trigger is "⋯" (page settings); pass `trigger` for a labelled button such as "+ Задача".
+ * 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(null);
diff --git a/openspec/changes/pep-66-github-tabs/tasks.md b/openspec/changes/pep-66-github-tabs/tasks.md
index d4f23553..7854d66f 100644
--- a/openspec/changes/pep-66-github-tabs/tasks.md
+++ b/openspec/changes/pep-66-github-tabs/tasks.md
@@ -1,20 +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 с проверкой доступа
+- [x] 1.1 core: `createEpic`/`listEpics`/`updateEpic` поверх целей; Bugsink-«Стабильность» описана как эпик
+- [x] 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` — «Эпик»
+- [x] 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»; настройки багов в «⋯», вкладка «Баги» — список
+- [x] 2.1 core Gitea: `listBranches`, `listCommits`, `readme`, `listPulls`; mock-gitea: ветки, коммиты
+- [x] 2.2 runner: `repoOverview` (README, ветки, коммиты, кэш, таймаут), `openPulls` (PR → стори + `taskCiSummary`); core `listSpecs`
+- [x] 2.3 Веб: вкладки «Код», «Спеки», «PR»; настройки багов в «⋯», вкладка «Баги» — список
## 3. Стори
-- [ ] 3.1 Тексты веба (доска, страница стори, Главная, раннеры, проекты, «Помощь», OAuth-согласие)
-- [ ] 3.2 Бот и уведомления (core/runner), промпты агенту
-- [ ] 3.3 Описания MCP-инструментов и `instructions`
+- [x] 3.1 Тексты веба (доска, страница стори, Главная, раннеры, проекты, «Помощь», OAuth-согласие)
+- [x] 3.2 Бот и уведомления (core/runner), промпты агенту
+- [x] 3.3 Описания MCP-инструментов и `instructions`
## 4. Проверка
-- [ ] 4.1 Тесты: эпики (MCP, алиасы, фильтр), repoOverview/openPulls на mock-gitea, listSpecs
-- [ ] 4.2 `pnpm typecheck`, e2e, `next build`; UI своим `next dev` на копии базы
+- [x] 4.1 Тесты: эпики (MCP, алиасы, фильтр), repoOverview/openPulls на mock-gitea, listSpecs
+- [x] 4.2 `pnpm typecheck`, e2e, `next build`; UI своим `next dev` на копии базы
diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts
index b8efb491..bf7f6eb3 100644
--- a/packages/core/src/incidents.ts
+++ b/packages/core/src/incidents.ts
@@ -21,9 +21,9 @@ export { incidentPolicies, incidentStatuses, type IncidentPolicy };
export const INCIDENT_STATUS_RU: Record = {
new: "новая",
- open: "без задачи",
+ open: "без стори",
pending: "ждёт разбора",
- task: "задача",
+ task: "стори",
ignored: "игнорируется",
resolved: "исправлена",
regressed: "вернулась",
@@ -31,8 +31,8 @@ export const INCIDENT_STATUS_RU: Record = {
export const POLICY_RU: Record = {
notify: "только уведомить",
- backlog: "задача в бэклог",
- start: "задача сразу в работу",
+ backlog: "стори в бэклог",
+ start: "стори сразу в работу",
ask: "спросить в Telegram",
triage: "решает агент-триажёр",
};
@@ -300,13 +300,13 @@ export function renderIncidentMessage(project: Pick, i:
if (i.url) lines.push(`Открыть в Bugsink `);
const taskLink = (t: TaskRef) => `${esc(t.key)} `;
if (m.kind === "task") {
- lines.push("", m.started ? `▶️ Агент взялся: ${taskLink(m.task)}` : `📥 Задача в бэклоге: ${taskLink(m.task)}`);
+ lines.push("", m.started ? `▶️ Агент взялся: ${taskLink(m.task)}` : `📥 Стори в бэклоге: ${taskLink(m.task)}`);
if (m.reason) lines.push(`🤖 Триажёр: ${esc(clip(m.reason, 500))}`);
} else if (m.kind === "ask") {
if (m.note) lines.push("", `${esc(clip(m.note, 500))} `);
lines.push("", "Что делаем?");
} else if (m.kind === "regressed") {
- lines.push("", m.task ? `Задача ${taskLink(m.task)} снова в бэклоге.` : "Задачи нет — реши, что делать.");
+ lines.push("", m.task ? `Стори ${taskLink(m.task)} снова в бэклоге.` : "Стори нет — реши, что делать.");
} else {
lines.push("", `Ошибки проекта `);
}
diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts
index 976dc050..805d1854 100644
--- a/packages/runner/src/ci.ts
+++ b/packages/runner/src/ci.ts
@@ -126,7 +126,7 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str
"- команды проверок — в `.peppa/project.json` → `checks` (`install`, `lint`, `typecheck`, `test`, `build`); пустая команда = шаг пропущен.",
"- деплой (preview на PR, staging на мерж, прод по кнопке PM) — `.peppa/project.json` → `deploy` + `Dockerfile` (заготовки в `deploy/`); без `deploy` шаг пропускается.",
"",
- "Заполнить `checks` — первая задача агента в проекте. Изменение конвейера требует ревью PM.",
+ "Заполнить `checks` — первая стори агента в проекте. Изменение конвейера требует ревью PM.",
].join("\n"),
}));
return { ...setup, prUrl: pr.html_url };
diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts
index 296b7909..b516cf09 100644
--- a/packages/runner/src/deploy.ts
+++ b/packages/runner/src/deploy.ts
@@ -106,7 +106,7 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
}
async function notifyRelease(db: Db, project: Project, rel: Release) {
- const tasks = rel.tasks.length ? ` · задачи: ${rel.tasks.join(", ")}` : "";
+ 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)}` : "";
diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts
index 5858cf4d..3d66c4e6 100644
--- a/packages/runner/src/flow.ts
+++ b/packages/runner/src/flow.ts
@@ -65,7 +65,7 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
*/
export async function acceptTask(db: Db, questionId: number, via: NonNullable): Promise {
const q = await getQuestion(db, questionId);
- if (!q.taskId) throw new PeppaError("Вопрос не привязан к задаче");
+ if (!q.taskId) throw new PeppaError("Вопрос не привязан к стори");
if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${q.answer}`);
const [t] = await db
.select({ key: projects.key, number: tasks.number })
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index db61e007..bcd29c6b 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -163,7 +163,7 @@ async function askQuestion(db: Db, s: SessionView, input: HookInput) {
}
const NUDGE = (key: string) =>
- `Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда задача готова — PR и update_task(status: review).`;
+ `Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда стори готова — PR и update_task(status: review).`;
/**
* The agent finished a turn. Pending question → PM already has it. Task in review →
@@ -180,7 +180,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
}
const [task] = s.taskId ? await db.select().from(tasks).where(eq(tasks.id, s.taskId)) : [];
if (task?.status === "review") {
- await raiseSessionQuestion(db, s, "attention", clip(`✅ ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${text ?? ""}`.trim()));
+ await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${text ?? ""}`.trim()));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
@@ -188,7 +188,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
if (canContinue && working && s.autoNudges < MAX_AUTO_NUDGES) {
await updateSession(db, s.id, { autoNudges: s.autoNudges + 1, status: "running", lastActivityAt: new Date() });
await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 });
- return { decision: "block", reason: NUDGE(s.taskKey ?? "задачей") };
+ return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") };
}
await raiseSessionQuestion(db, s, "attention", clip(text ?? "Сессия закончила ход и ждёт ввода."));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
diff --git a/packages/runner/src/incidents.ts b/packages/runner/src/incidents.ts
index aa537ba9..d47e965d 100644
--- a/packages/runner/src/incidents.ts
+++ b/packages/runner/src/incidents.ts
@@ -117,7 +117,7 @@ async function execute(
}
const today = await autoIncidentTasksToday(db, i.projectId, o.now);
if (today >= s.dailyLimit) {
- const limitNote = `Суточный предел задач из ошибок (${s.dailyLimit}) исчерпан — задача не создана${by === "triage" ? `; триажёр предлагал «${ACTION_RU[action]}»: ${reason}` : ""}.`;
+ const limitNote = `Суточный предел стори из ошибок (${s.dailyLimit}) исчерпан — стори не создана${by === "triage" ? `; триажёр предлагал «${ACTION_RU[action]}»: ${reason}` : ""}.`;
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
return row;
@@ -146,7 +146,7 @@ export async function decideIncident(db: Db, incidentId: number, action: "backlo
const i = await getIncident(db, incidentId);
const already = async () => {
const ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
- return new PeppaError(ref ? `Уже решено: задача ${ref.key}` : `Уже решено: ${INCIDENT_STATUS_RU[i.status]}`);
+ return new PeppaError(ref ? `Уже решено: стори ${ref.key}` : `Уже решено: ${INCIDENT_STATUS_RU[i.status]}`);
};
const open: Incident["status"][] = action === "ignore" ? ["new", "open", "pending", "regressed"] : ["new", "open", "pending", "regressed", "ignored"];
if (i.taskId || !open.includes(i.status)) throw await already();
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index 81204ef2..804a6caa 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -96,7 +96,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise, i: Incident
return [
"Ты — триажёр ошибок софтвейр-фабрики Пеппа. Новая ошибка пришла из работающего продукта.",
"Реши, что с ней делать, строго по правилам PM ниже. Варианты:",
- '- "start" — завести задачу и сразу отдать агенту;',
- '- "backlog" — завести задачу в бэклог;',
- '- "notify" — только сообщить PM, задачу не заводить;',
+ '- "start" — завести стори и сразу отдать агенту;',
+ '- "backlog" — завести стори в бэклог;',
+ '- "notify" — только сообщить PM, стори не заводить;',
'- "ignore" — игнорировать;',
'- "ask" — спросить PM (если правила не дают ясного ответа).',
"",
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index d52787e8..82ab5781 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -156,7 +156,7 @@ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: stri
await expireSessionQuestions(db, s.id, "(лимит сброшен — раннер продолжил сам)");
const alive = (await tmux.hasSession(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
if (alive) {
- await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "задачей"} с того места, где остановился (tasks.md).`);
+ await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "стори"} с того места, где остановился (tasks.md).`);
await updateSession(db, s.id, { ...counters, status: "running", lastActivityAt: now });
} else {
await updateSession(db, s.id, counters);
diff --git a/packages/testkit/test/incidents.test.ts b/packages/testkit/test/incidents.test.ts
index d02e8401..9722da1d 100644
--- a/packages/testkit/test/incidents.test.ts
+++ b/packages/testkit/test/incidents.test.ts
@@ -241,7 +241,7 @@ describe("Политика инцидентов проекта", () => {
assert.ok(t.description!.includes(i.url!));
assert.match(t.description!, /Условия готовности/);
const m = await waitPm("TypeError: amount is undefined", (x) => x.text.includes(t.key));
- assert.match(m.text, /Задача в бэклоге/);
+ assert.match(m.text, /Стори в бэклоге/);
assert.ok(m.text.includes(`http://peppa.test/t/${t.key}`));
});
@@ -371,7 +371,7 @@ describe("Политика инцидентов проекта", () => {
assert.equal(i.taskId, null);
assert.equal((await tasksOf(c)).filter((t) => t.title.startsWith("Ошибка:")).length, 5);
const m = await waitPm("TypeError: limit 6");
- assert.match(m.text, /Суточный предел задач из ошибок \(5\) исчерпан/);
+ assert.match(m.text, /Суточный предел стори из ошибок \(5\) исчерпан/);
assert.equal(buttons(m).length, 3);
// The PM's own decision isn't capped.
const r = await runner.decideIncident(db, i.id, "backlog", "mock-pm");
diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts
index 3da211ab..f339a021 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", "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.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "update_epic", "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);
@@ -154,7 +154,7 @@ describe("update_task over MCP", () => {
const r3 = await call("update_task", { task: ref.key, title: "Оба поля", description: "оба описания" });
assert.match(r3.text, /Оба поля/);
assert.match(r3.text, /оба описания/);
- assert.match(r3.text, /Цель: #\d+ Цель для правки/);
+ assert.match(r3.text, /Эпик: #\d+ Цель для правки/);
assert.deepEqual(await snapshot(), { title: "Оба поля", description: "оба описания", goalId: goal.id, status: "backlog", sessions: 0 });
assert.ok((await call("update_task", { task: ref.key })).isError, "nothing to update");
@@ -171,7 +171,7 @@ describe("update_task over MCP", () => {
describe("goals, task goal and project creation over MCP", () => {
test("server instructions explain the model", async () => {
const { client } = await mcpAs(owner);
- assert.match(client.getInstructions() ?? "", /project .*goals .*tasks/s);
+ assert.match(client.getInstructions() ?? "", /project .*epics .*stories/s);
});
test("create/update goals; move a task between goals and detach; foreign goal refused", async () => {
@@ -179,14 +179,14 @@ describe("goals, task goal and project creation over MCP", () => {
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const { call } = await mcpAs(owner);
- const g1 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
- const g2 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
+ const g1 = Number(/epic #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
+ const g2 = Number(/epic #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
assert.match((await call("list_goals", { project: p.key })).text, /Цель один[\s\S]*Цель два/);
assert.match((await call("update_goal", { project: p.key, goal_id: g1, title: "Цель первая" })).text, /Цель первая \[open\]/);
const t = await call("create_task", { project: p.key, title: "Задача в цели", goal_id: g1 });
const key = /Created (\S+):/.exec(t.text)![1]!;
- assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Цель: #\d+ Цель два/);
+ assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Эпик: #\d+ Цель два/);
const moved = (await core.resolveTask(db, key)).task;
assert.equal(moved.goalId, g2);
assert.equal(moved.title, "Задача в цели");
@@ -203,6 +203,40 @@ describe("goals, task goal and project creation over MCP", () => {
assert.doesNotMatch((await call("list_goals", { project: p.key })).text, /Цель первая/);
});
+ test("Scenario: Новый эпик и стори в нём; Эпик завершён; Алиас цели; Перенос в другой эпик; Эпик чужого проекта", async () => {
+ const p = await project({ turns: [] });
+ const proj = await core.getProject(db, p.key);
+ await core.setProjectOwner(db, proj.id, owner.id);
+ const { call, client } = await mcpAs(owner);
+ const createTask = (await client.listTools()).tools.find((t) => t.name === "create_task");
+ assert.match(createTask?.description ?? "", /story/i, "tool name stays, the text speaks of stories");
+
+ const a = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Оплата картой", description: "Приём оплат" })).text)![1]);
+ const b = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Б" })).text)![1]);
+ const t = await call("create_task", { project: p.key, title: "Форма оплаты", epic_id: a });
+ const key = /Created (\S+):/.exec(t.text)![1]!;
+ assert.equal((await core.resolveTask(db, key)).task.goalId, a);
+ const listed = (await call("list_epics", { project: p.key })).text;
+ assert.match(listed, /Оплата картой — Приём оплат/);
+ assert.equal((await call("list_goals", { project: p.key })).text, listed, "list_goals is an alias");
+ assert.match((await call("list_tasks", { project: p.key })).text, new RegExp(`${key} \\[backlog\\] \\(epic #${a}\\)`));
+
+ const r = await call("update_task", { task: key, epic_id: b });
+ assert.match(r.text, /Эпик: #\d+ Б/);
+ assert.equal((await core.resolveTask(db, key)).task.status, "backlog");
+ assert.match((await call("get_task", { task: key })).text, /Эпик: #\d+ Б/);
+
+ const other = await project({ turns: [] });
+ const foreign = await core.createEpic(db, (await core.getProject(db, other.key)).id, "Чужой эпик");
+ assert.ok((await call("update_task", { task: key, epic_id: foreign.id })).isError);
+ assert.ok((await call("create_task", { project: p.key, title: "С чужим эпиком", epic_id: foreign.id })).isError);
+ assert.equal((await core.resolveTask(db, key)).task.goalId, b);
+
+ assert.match((await call("update_epic", { project: p.key, epic_id: a, status: "done" })).text, /\[done\]/);
+ assert.doesNotMatch((await call("list_epics", { project: p.key })).text, /Оплата картой/);
+ assert.ok((await call("update_epic", { project: p.key, epic_id: a })).isError, "nothing to update");
+ });
+
test("create_project through MCP, owned by the user", async () => {
const { MockGitea } = await import("../src/mock-gitea.ts");
const { mkdtempSync } = await import("node:fs");
diff --git a/packages/testkit/test/project-tabs.test.ts b/packages/testkit/test/project-tabs.test.ts
new file mode 100644
index 00000000..80bc9a0e
--- /dev/null
+++ b/packages/testkit/test/project-tabs.test.ts
@@ -0,0 +1,155 @@
+// PEP-66: project page tabs «Код», «Спеки», «PR» (mock-gitea + real git) and epics in core.
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { core, db, runner, teardown } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+
+const TMP = mkdtempSync(join(tmpdir(), "peppa-tabs-"));
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+
+const gitea = new MockGitea(join(TMP, "gitea"));
+const ALICE = { id: 71, login: "mock-tabs-alice", token: "mock-token-tabs-alice" };
+const BOT = { id: 72, login: "peppa-bot", token: "mock-token-tabs-bot" };
+let alice: Awaited>;
+
+before(async () => {
+ await gitea.start();
+ process.env.GITEA_URL = gitea.url;
+ process.env.GITEA_TOKEN = BOT.token;
+ gitea.addUser(ALICE);
+ gitea.addUser(BOT);
+ alice = await core.upsertUserFromGitea(db, ALICE, { access_token: ALICE.token });
+});
+after(async () => {
+ await gitea.stop();
+ await teardown();
+});
+
+/** A project on a mock repo; the working copy holds .peppa/project.json (checks) and specs. */
+async function tabsProject(key: string, files: Record | null, workspace: Record = {}) {
+ const slug = `mock-tabs-${key.toLowerCase()}`;
+ if (files) gitea.addRepo(ALICE.login, slug, { files, admins: [ALICE.login] });
+ const ws = join(TMP, "ws", slug);
+ for (const [f, text] of Object.entries(workspace)) {
+ mkdirSync(join(ws, f, ".."), { recursive: true });
+ writeFileSync(join(ws, f), text);
+ }
+ mkdirSync(ws, { recursive: true });
+ return core.createProject(db, { slug, key, name: `Mock ${key}`, giteaOwner: ALICE.login, workspacePath: ws, ownerId: alice.id });
+}
+
+describe("Вкладка «Код»", () => {
+ test("Scenario: Репозиторий с кодом — README, ветки main и task/…, последний коммит main", async () => {
+ const p = await tabsProject("MTCODE", { "README.md": "# Pay\n\nПлатежи.", "src/index.ts": "export {};\n" });
+ gitea.commit(ALICE.login, p.giteaRepo, "main", { "src/pay.ts": "export const pay = 1;\n" }, "Оплата картой");
+ gitea.commit(ALICE.login, p.giteaRepo, "task/MTCODE-3", { "src/form.ts": "export {};\n" }, "MTCODE-3: форма");
+ const code = await runner.repoOverview(db, p, { fresh: true });
+ assert.equal(code.error, null);
+ assert.equal(code.defaultBranch, "main");
+ assert.match(code.readme!.text, /^# Pay/);
+ assert.equal(code.readme!.path, "README.md");
+ assert.deepEqual(code.branches.map((b) => b.name), ["main", "task/MTCODE-3"], "default branch first");
+ assert.equal(code.commits[0]!.message, "Оплата картой");
+ assert.equal(code.commits[0]!.sha, gitea.sha(ALICE.login, p.giteaRepo, "main"));
+ assert.equal(code.commits.length, 2);
+ assert.equal(code.url, `${gitea.url}/${ALICE.login}/${p.giteaRepo}`);
+ });
+
+ test("Scenario: Gitea недоступна — ссылка на репозиторий и «Gitea сейчас не отвечает», без исключения", async () => {
+ const p = await tabsProject("MTDOWN", { "README.md": "# Down" });
+ const url = process.env.GITEA_URL;
+ process.env.GITEA_URL = "http://127.0.0.1:9";
+ try {
+ const code = await runner.repoOverview(db, p, { fresh: true });
+ assert.equal(code.error, "Gitea сейчас не отвечает");
+ assert.equal(code.url, `http://127.0.0.1:9/${ALICE.login}/${p.giteaRepo}`);
+ assert.equal(code.readme, null);
+ assert.equal((await runner.openPulls(db, p, { fresh: true })).error, "Gitea сейчас не отвечает");
+ } finally {
+ process.env.GITEA_URL = url;
+ }
+ // A failure is not cached: the next call asks Gitea again.
+ assert.equal((await runner.repoOverview(db, p)).error, null);
+ });
+
+ test("репозиторий без README и пустой репозиторий", async () => {
+ const p = await tabsProject("MTNORD", { "src/a.ts": "1" });
+ const code = await runner.repoOverview(db, p, { fresh: true });
+ assert.equal(code.readme, null);
+ assert.equal(code.error, null);
+ const missing = await tabsProject("MTMISS", null);
+ assert.equal((await runner.repoOverview(db, missing, { fresh: true })).error, "Репозиторий не найден в Gitea");
+ });
+});
+
+describe("Вкладка «PR»", () => {
+ test("Scenario: PR стори — ключ стори и «Проверки: 2 из 2 пройдены»; PR без стори — без проверок", async () => {
+ const p = await tabsProject("MTPR", { "README.md": "# PR" }, { ".peppa/project.json": JSON.stringify({ key: "MTPR", checks: { test: "pnpm test", build: "pnpm build" } }) });
+ const ref = await core.createTask(db, { projectId: p.id, title: "Форма оплаты" });
+ const sha = gitea.commit(ALICE.login, p.giteaRepo, `task/${ref.key}`, { "f.ts": "1" });
+ gitea.openPull(ALICE.login, p.giteaRepo, `task/${ref.key}`, `${ref.key}: форма оплаты`);
+ gitea.commit(ALICE.login, p.giteaRepo, "chore/deps", { "g.ts": "1" });
+ gitea.openPull(ALICE.login, p.giteaRepo, "chore/deps", "Обновить зависимости");
+ for (const check of ["test", "build"]) await core.upsertCheckRun(db, p, ref.task.id, { sha, check, state: "success", branch: `task/${ref.key}` });
+
+ const { pulls, error } = await runner.openPulls(db, p, { fresh: true });
+ assert.equal(error, null);
+ assert.equal(pulls.length, 2);
+ const story = pulls.find((x) => x.branch === `task/${ref.key}`)!;
+ assert.equal(story.task?.key, ref.key);
+ assert.equal(story.task?.ci.label, "Проверки: 2 из 2 пройдены");
+ assert.match(story.url, /\/pulls\/1$/);
+ assert.equal(pulls.find((x) => x.branch === "chore/deps")!.task, null);
+ });
+
+ test("Scenario: Открытых PR нет", async () => {
+ const p = await tabsProject("MTNOPR", { "README.md": "# none" });
+ assert.deepEqual(await runner.openPulls(db, p, { fresh: true }), { pulls: [], error: null });
+ });
+});
+
+describe("Вкладка «Спеки»", () => {
+ const SPEC = "# web-auth Specification\n\n## Purpose\nВход в веб через Gitea.\n\n## Requirements\n\n### Requirement: Вход\nтекст\n\n#### Scenario: a\n- **WHEN** x\n\n### Requirement: Выход\nтекст\n";
+
+ test("Scenario: Есть спеки — имя, назначение и число требований", async () => {
+ const p = await tabsProject("MTSPEC", null, { "openspec/specs/web-auth/spec.md": SPEC, "openspec/specs/billing/spec.md": "# billing\n\n## Purpose\nTBD - created by archiving change x.\n\n## Requirements\n\n### Requirement: Счёт\n" });
+ const specs = core.listSpecs(p);
+ assert.deepEqual(specs.map((s) => [s.name, s.purpose, s.requirements]), [
+ ["billing", "", 1],
+ ["web-auth", "Вход в веб через Gitea.", 2],
+ ]);
+ assert.match(specs[1]!.text, /### Requirement: Выход/);
+ });
+
+ test("Scenario: Спек нет — пустой список", async () => {
+ const p = await tabsProject("MTNOSP", null);
+ assert.deepEqual(core.listSpecs(p), []);
+ });
+});
+
+describe("Эпики (цели как метки стори)", () => {
+ test("Scenario: Новая стори в эпике; Стори без эпика; Эпик в архив — стори не меняется", async () => {
+ const p = await tabsProject("MTEPIC", null);
+ const epic = await core.createEpic(db, p.id, "Оплата картой", "Приём оплат");
+ const withEpic = await core.createTask(db, { projectId: p.id, title: "Форма оплаты", goalId: epic.id });
+ const without = await core.createTask(db, { projectId: p.id, title: "Без эпика" });
+ assert.equal(withEpic.task.goalId, epic.id);
+ assert.equal(without.task.goalId, null);
+ assert.deepEqual((await core.listEpics(db, p.id)).map((e) => e.title), ["Оплата картой"]);
+ assert.match((await import("../../mcp/src/format.ts")).formatTask(await core.getTaskDetails(db, withEpic)), /## Эпик #\d+: Оплата картой\n\nПриём оплат/);
+
+ await core.updateEpic(db, p.id, epic.id, { status: "archived" });
+ assert.deepEqual(await core.listEpics(db, p.id), []);
+ assert.equal((await core.resolveTask(db, withEpic.key)).task.goalId, epic.id, "the story keeps its epic");
+ });
+
+ test("эпик чужого проекта не ставится на стори", async () => {
+ const a = await tabsProject("MTEPA", null);
+ const b = await tabsProject("MTEPB", null);
+ const foreign = await core.createEpic(db, b.id, "Чужой");
+ await assert.rejects(core.createTask(db, { projectId: a.id, title: "x", goalId: foreign.id }));
+ });
+});
--
2.45.2
From 6cceac62b29b17b0955733cde2d3f1c9027977db 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:26:41 +0500
Subject: [PATCH 027/518] PEP-66: archive OpenSpec change
Co-Authored-By: Claude Opus 5.5
---
.../2026-11-14-pep-66-github-tabs}/design.md | 0
.../proposal.md | 0
.../specs/remote-mcp/spec.md | 0
.../specs/web-workspace/spec.md | 0
.../2026-11-14-pep-66-github-tabs}/tasks.md | 0
openspec/specs/remote-mcp/spec.md | 58 ++++---
openspec/specs/web-workspace/spec.md | 141 +++++++++++++++---
7 files changed, 161 insertions(+), 38 deletions(-)
rename openspec/changes/{pep-66-github-tabs => archive/2026-11-14-pep-66-github-tabs}/design.md (100%)
rename openspec/changes/{pep-66-github-tabs => archive/2026-11-14-pep-66-github-tabs}/proposal.md (100%)
rename openspec/changes/{pep-66-github-tabs => archive/2026-11-14-pep-66-github-tabs}/specs/remote-mcp/spec.md (100%)
rename openspec/changes/{pep-66-github-tabs => archive/2026-11-14-pep-66-github-tabs}/specs/web-workspace/spec.md (100%)
rename openspec/changes/{pep-66-github-tabs => archive/2026-11-14-pep-66-github-tabs}/tasks.md (100%)
diff --git a/openspec/changes/pep-66-github-tabs/design.md b/openspec/changes/archive/2026-11-14-pep-66-github-tabs/design.md
similarity index 100%
rename from openspec/changes/pep-66-github-tabs/design.md
rename to openspec/changes/archive/2026-11-14-pep-66-github-tabs/design.md
diff --git a/openspec/changes/pep-66-github-tabs/proposal.md b/openspec/changes/archive/2026-11-14-pep-66-github-tabs/proposal.md
similarity index 100%
rename from openspec/changes/pep-66-github-tabs/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-66-github-tabs/proposal.md
diff --git a/openspec/changes/pep-66-github-tabs/specs/remote-mcp/spec.md b/openspec/changes/archive/2026-11-14-pep-66-github-tabs/specs/remote-mcp/spec.md
similarity index 100%
rename from openspec/changes/pep-66-github-tabs/specs/remote-mcp/spec.md
rename to openspec/changes/archive/2026-11-14-pep-66-github-tabs/specs/remote-mcp/spec.md
diff --git a/openspec/changes/pep-66-github-tabs/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-66-github-tabs/specs/web-workspace/spec.md
similarity index 100%
rename from openspec/changes/pep-66-github-tabs/specs/web-workspace/spec.md
rename to openspec/changes/archive/2026-11-14-pep-66-github-tabs/specs/web-workspace/spec.md
diff --git a/openspec/changes/pep-66-github-tabs/tasks.md b/openspec/changes/archive/2026-11-14-pep-66-github-tabs/tasks.md
similarity index 100%
rename from openspec/changes/pep-66-github-tabs/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-66-github-tabs/tasks.md
diff --git a/openspec/specs/remote-mcp/spec.md b/openspec/specs/remote-mcp/spec.md
index 295033c8..74f625cc 100644
--- a/openspec/specs/remote-mcp/spec.md
+++ b/openspec/specs/remote-mcp/spec.md
@@ -64,25 +64,6 @@ MCP SHALL позволять менять название и описание
- **WHEN** не передано ни `title`, ни `description`, или задача из чужого проекта
- **THEN** ошибка, задача не меняется
-### Requirement: Цели через MCP
-MCP SHALL позволять создавать цели в проекте пользователя и менять их название,
-описание и статус (открыта, достигнута, в архиве).
-
-#### Scenario: Новая цель и задачи под ней
-- **WHEN** клиент создаёт цель и затем задачу с её `goal_id`
-- **THEN** цель видна в списке целей проекта, задача — под этой целью
-
-#### Scenario: Цель достигнута
-- **WHEN** клиент меняет статус цели на «достигнута»
-- **THEN** цель пропадает из списка открытых целей, её задачи не меняются
-
-### Requirement: Цель задачи
-`update_task` SHALL позволять перенести задачу в другую цель своего проекта или отвязать от цели, не меняя остальное.
-
-#### Scenario: Перенос в другую цель
-- **WHEN** клиент вызывает `update_task` с `goal_id` другой цели проекта
-- **THEN** задача относится к этой цели, статус и название прежние
-
### Requirement: Создание проекта через MCP
MCP SHALL создавать проект так же, как веб: новый или существующий репозиторий в
пространстве пользователя или его организации, от имени пользователя.
@@ -92,8 +73,43 @@ MCP SHALL создавать проект так же, как веб: новый
- **THEN** проект создан с пользователем-владельцем и виден в `list_projects`
### Requirement: Инструкции сервера
-MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться инструментами.
+MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться
+инструментами, в терминах проект → эпики → стори → доска.
#### Scenario: Подключение
- **WHEN** клиент инициализирует соединение
-- **THEN** получает инструкции сервера с моделью проект → цели → задачи → доска
+- **THEN** получает инструкции сервера с моделью проект → эпики → стори → доска
+
+### 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/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 1ccc4c4d..b7014a85 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -1,7 +1,7 @@
# web-workspace Specification
## Purpose
-Определяет, что пользователь делает в вебе со своими проектами: ведёт цели и задачи, следит за сессиями агентов и управляет ими, отвечает на вопросы агентов.
+Определяет, что пользователь делает в вебе со своими проектами: ведёт стори и эпики, следит за сессиями агентов и управляет ими, отвечает на вопросы агентов.
## Requirements
@@ -13,14 +13,6 @@
- **WHEN** у пользователя есть неотвеченные вопросы в его проектах
- **THEN** на главной каждый виден с задачей, типом (одобрение, вопрос, разрешение, «ждёт тебя»), текстом и формой ответа
-### Requirement: Цели и задачи
-Пользователь SHALL создавать цели и задачи в своём проекте и видеть задачи
-сгруппированными по целям со статусами. Номер задачи выдаётся так же, как через MCP и CLI.
-
-#### Scenario: Новая задача под целью
-- **WHEN** пользователь создаёт задачу с названием и описанием под целью
-- **THEN** задача получает следующий номер проекта (`KEY-N`), статус `backlog` и видна под этой целью
-
### Requirement: Страница задачи
Страница задачи SHALL показывать описание, цель, статус, PR, артефакты OpenSpec change
(proposal, design, tasks — как текст из рабочей копии), вопросы с ответами, сессии и
@@ -64,18 +56,30 @@
- **THEN** вопрос появляется на странице в течение 10 секунд
### Requirement: Доска задач
-Страница проекта SHALL показывать задачи доской с колонками Бэклог, В работе, Ревью,
-Готово; карточку можно перенести перетаскиванием или кнопкой. Перенос в «В работе»
-запускает агента по задаче, если активной сессии нет; перенос в «Бэклог» или «Готово»
-останавливает активную сессию.
+Вкладка «Доска» страницы проекта SHALL показывать стори доской с колонками Бэклог, В
+работе, Ревью, Готово; карточку можно перенести перетаскиванием или кнопкой. Перенос в «В
+работе» запускает агента по стори, если активной сессии нет; перенос в «Бэклог» или «Готово»
+останавливает активную сессию. Доску можно отфильтровать по эпику.
#### Scenario: Карточку в работу
-- **WHEN** PM переносит карточку из «Бэклог» в «В работе»
-- **THEN** задача получает статус `in_progress` и по ней запускается сессия агента
+- **GIVEN** стори PAY-3 в «Бэклог» без активной сессии
+- **WHEN** PM переносит карточку в «В работе»
+- **THEN** стори получает статус `in_progress` и по ней запускается сессия агента
#### Scenario: Карточку в готово
-- **WHEN** PM переносит карточку из «Ревью» в «Готово»
-- **THEN** задача `done`, активная сессия по ней остановлена
+- **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** доска показывает все стори проекта без фильтра
### Requirement: Помощь
Веб SHALL иметь страницу «Помощь», доступную из меню, с описанием понятий Пеппы,
@@ -178,3 +182,106 @@
- **GIVEN** пользователь переключил тему на светлую
- **WHEN** он закрывает и снова открывает веб
- **THEN** страница в светлой теме без мигания тёмной
+
+### 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` есть, а его описание говорит о стори
--
2.45.2
From 73b82d38a1b7ec9fe1535ba8de13dc925c9cfa51 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:28:15 +0500
Subject: [PATCH 028/518] PEP-66: fix epic MCP test (title min length)
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/oauth.test.ts | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts
index f339a021..7972f51f 100644
--- a/packages/testkit/test/oauth.test.ts
+++ b/packages/testkit/test/oauth.test.ts
@@ -212,7 +212,8 @@ describe("goals, task goal and project creation over MCP", () => {
assert.match(createTask?.description ?? "", /story/i, "tool name stays, the text speaks of stories");
const a = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Оплата картой", description: "Приём оплат" })).text)![1]);
- const b = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Б" })).text)![1]);
+ assert.ok((await call("create_epic", { project: p.key, title: "Б" })).isError, "title of at least 3 chars");
+ const b = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Эпик Б" })).text)![1]);
const t = await call("create_task", { project: p.key, title: "Форма оплаты", epic_id: a });
const key = /Created (\S+):/.exec(t.text)![1]!;
assert.equal((await core.resolveTask(db, key)).task.goalId, a);
@@ -222,9 +223,9 @@ describe("goals, task goal and project creation over MCP", () => {
assert.match((await call("list_tasks", { project: p.key })).text, new RegExp(`${key} \\[backlog\\] \\(epic #${a}\\)`));
const r = await call("update_task", { task: key, epic_id: b });
- assert.match(r.text, /Эпик: #\d+ Б/);
+ assert.match(r.text, /Эпик: #\d+ Эпик Б/);
assert.equal((await core.resolveTask(db, key)).task.status, "backlog");
- assert.match((await call("get_task", { task: key })).text, /Эпик: #\d+ Б/);
+ assert.match((await call("get_task", { task: key })).text, /Эпик: #\d+ Эпик Б/);
const other = await project({ turns: [] });
const foreign = await core.createEpic(db, (await core.getProject(db, other.key)).id, "Чужой эпик");
--
2.45.2
From 818bfe33a97a3f9cde8a2a04c3d4417dcdd09c2f 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:15:09 +0500
Subject: [PATCH 029/518] PEP-64: OpenSpec change pep-64-visibility
Co-Authored-By: Claude Opus 5.5
---
.../changes/pep-64-visibility/.openspec.yaml | 2 +
openspec/changes/pep-64-visibility/design.md | 36 ++++++
.../changes/pep-64-visibility/proposal.md | 42 +++++++
.../specs/project-provisioning/spec.md | 119 ++++++++++++++++++
openspec/changes/pep-64-visibility/tasks.md | 19 +++
5 files changed, 218 insertions(+)
create mode 100644 openspec/changes/pep-64-visibility/.openspec.yaml
create mode 100644 openspec/changes/pep-64-visibility/design.md
create mode 100644 openspec/changes/pep-64-visibility/proposal.md
create mode 100644 openspec/changes/pep-64-visibility/specs/project-provisioning/spec.md
create mode 100644 openspec/changes/pep-64-visibility/tasks.md
diff --git a/openspec/changes/pep-64-visibility/.openspec.yaml b/openspec/changes/pep-64-visibility/.openspec.yaml
new file mode 100644
index 00000000..be831cee
--- /dev/null
+++ b/openspec/changes/pep-64-visibility/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-14
diff --git a/openspec/changes/pep-64-visibility/design.md b/openspec/changes/pep-64-visibility/design.md
new file mode 100644
index 00000000..eb02ce44
--- /dev/null
+++ b/openspec/changes/pep-64-visibility/design.md
@@ -0,0 +1,36 @@
+# Design: PEP-64
+
+## Кто может менять видимость
+
+- Веб и MCP — только владелец проекта (как управление участниками): видимость решает,
+ кто видит код, это уровень владельца. Участник получает понятную ошибку.
+- CLI — админ машины Пеппы, без проверки владельца: нужен для разового массового
+ перевода (`--all`) и отката, включая проекты без владельца (созданные ботом).
+
+## Чем менять
+
+`repoAdmins(db, project)` — уже есть (PEP-12/15): клиент владельца, затем `peppa-bot`.
+Пробуем по очереди `PATCH /repos/{owner}/{repo}` с `{ private }`; первая удача — готово.
+Все упали — `PeppaError` с последней причиной (нет прав администратора в Gitea).
+После смены кэш `describeRepo` удаляется и возвращается свежий `RepoInfo`, поэтому
+блок «Репозиторий», шапка страницы и ответ MCP показывают новую видимость сразу.
+
+Уже совпадающая видимость — не ошибка: PATCH идемпотентен, отвечаем текущим состоянием.
+
+## `--all`
+
+Перебирает все проекты (`listProjects`), по одному; ошибка одного не останавливает
+остальные, итог — строка на проект и ненулевой код выхода, если что-то не вышло.
+
+## Умолчание
+
+`provisionProject`: `visibility` по умолчанию `"public"` (`createRepo(..., o.visibility
+=== "private")`). `GiteaClient.createRepo` оставляем с явным параметром. Подключение
+существующего репозитория по-прежнему не меняет его видимость.
+
+## UI
+
+В «⋯ Настройки проекта», раздел «Репозиторий», под «Видимость» — форма с кнопкой
+«Сделать публичным» / «Сделать приватным» (только владельцу и только когда видимость
+известна). Подтверждение — `confirm()` не используем (серверный компонент); действие
+обратимо той же кнопкой.
diff --git a/openspec/changes/pep-64-visibility/proposal.md b/openspec/changes/pep-64-visibility/proposal.md
new file mode 100644
index 00000000..ee782af3
--- /dev/null
+++ b/openspec/changes/pep-64-visibility/proposal.md
@@ -0,0 +1,42 @@
+# Proposal: PEP-64 — видимость проектов: публичные по умолчанию, смена видимости
+
+Задача Пеппы: **PEP-64**. Решение PM от 2026-11-13.
+
+## Why
+
+Репозитории проектов создаются приватными (PEP-15), и коллеги в Gitea их не видят. PM
+решил: все существующие репозитории — публичные, новые — публичные по умолчанию,
+«Приватный» — по выбору. Сейчас сменить видимость существующего проекта можно только
+руками в Gitea, а вернуть массово — нечем.
+
+## What Changes
+
+- Умолчание «Публичный» при создании нового репозитория: веб-форма «Новый проект»,
+ MCP `create_project`, `provisionProject`; CLI `peppa project create … --private`
+ вместо `--public`.
+- Смена видимости существующего проекта: `setProjectVisibility` в runner (PATCH repo
+ `private` клиентом владельца, иначе `peppa-bot`; кэш `describeRepo` сбрасывается,
+ карточка сразу показывает новую видимость).
+ - Веб: «⋯ Настройки проекта» → «Репозиторий» → кнопка «Сделать публичным/приватным»
+ (только владелец).
+ - MCP: `set_project_visibility` (только владелец), описан в `/help`.
+ - CLI: `peppa project visibility public|private` — админская команда
+ машины Пеппы (без проверки владельца), для разового перевода всех репозиториев и
+ отката.
+- `mock-gitea` принимает `PATCH /repos/{owner}/{repo}` (`private`, только админ репо).
+- Сами репозитории существующих проектов в Gitea этот change не переключает: это
+ делает координатор после мержа командой `peppa project visibility --all public`.
+
+## Capabilities
+
+### Modified Capabilities
+- `project-provisioning`: умолчание видимости — публичный; смена видимости
+ существующего проекта (веб, MCP, CLI).
+
+## Impact
+
+- `packages/core/src/gitea.ts` — `setRepoPrivate`.
+- `packages/runner/src/share.ts`, `provision.ts`.
+- `apps/web`: форма нового проекта, страница проекта, `actions.ts`, `/help`.
+- `packages/mcp/src/manager.ts`, `packages/cli/src/index.ts`.
+- `packages/testkit`: `mock-gitea`, `repo-visibility.test.ts`.
diff --git a/openspec/changes/pep-64-visibility/specs/project-provisioning/spec.md b/openspec/changes/pep-64-visibility/specs/project-provisioning/spec.md
new file mode 100644
index 00000000..bf433c09
--- /dev/null
+++ b/openspec/changes/pep-64-visibility/specs/project-provisioning/spec.md
@@ -0,0 +1,119 @@
+## MODIFIED Requirements
+
+### Requirement: Новый проект с новым репозиторием
+Пеппа SHALL создавать проект по имени, slug и ключу задач: репозиторий в выбранном
+пространстве (пользователь или организация, где он может создавать репозитории) с
+выбранной видимостью (публичный по умолчанию или приватный), заполненный из шаблона и
+инициализированный OpenSpec.
+
+#### Scenario: Успешное создание
+- **GIVEN** пользователь `alice` вошёл в Пеппу
+- **WHEN** он создаёт проект «Demo», slug `demo`, ключ `DEMO` в своём пространстве, не меняя видимость
+- **THEN** в Gitea появляется публичный `alice/demo` с первым коммитом от Peppa, содержащим `AGENTS.md`, `CLAUDE.md`, `.mcp.json`, `.peppa/project.json` (slug, ключ, URL Пеппы) и `openspec/`, но не `RULES.md`
+- **AND** в Пеппе появляется проект DEMO с владельцем `alice`
+- **AND** рабочая копия лежит в `$PEPPA_WORKSPACES/demo`
+
+#### Scenario: Публичный репозиторий в организации
+- **GIVEN** `alice` может создавать репозитории в организации `team`
+- **WHEN** она создаёт проект со slug `site` в пространстве `team` с видимостью «Публичный»
+- **THEN** в Gitea появляется публичный `team/site`
+
+#### Scenario: Приватный репозиторий по выбору
+- **GIVEN** `alice` может создавать репозитории в организации `team`
+- **WHEN** она создаёт проект со slug `app` в пространстве `team` с видимостью «Приватный»
+- **THEN** в Gitea появляется приватный `team/app`
+
+#### Scenario: Конфликты
+- **WHEN** slug или ключ уже заняты в Пеппе, или репозиторий с таким именем уже есть в выбранном пространстве
+- **THEN** проект не создаётся, пользователь видит причину, частично созданное не остаётся в Пеппе
+
+### Requirement: Создание проекта из CLI
+Тот же сценарий SHALL быть доступен из CLI на машине Пеппы от имени `peppa-bot`
+(репозиторий в пространстве бота, без владельца-пользователя); репозиторий публичный,
+`--private` создаёт приватный.
+
+#### Scenario: CLI
+- **WHEN** админ выполняет `peppa project create demo DEMO "Demo"`
+- **THEN** результат совпадает с созданием из веба, кроме пространства (`peppa-bot`) и отсутствия владельца
+
+#### Scenario: CLI, приватный
+- **WHEN** админ выполняет `peppa project create demo DEMO "Demo" --private`
+- **THEN** репозиторий `peppa-bot/demo` приватный
+
+### Requirement: Где репозиторий и кто его видит
+Пеппа SHALL показывать, где лежит репозиторий проекта и кто его видит: в форме нового
+проекта — до создания, после создания — сразу, на странице проекта и через MCP — всегда.
+Видимость и соавторы читаются из Gitea при показе.
+
+#### Scenario: Форма нового проекта
+- **GIVEN** `alice` открывает «Новый проект»
+- **THEN** она видит выбор пространства (`alice` — личное, и организации, где может создавать репозитории) и видимости (публичный по умолчанию, приватный)
+- **AND** подсказку, кто увидит репозиторий в каждом случае
+
+#### Scenario: Сразу после создания
+- **WHEN** `alice` создала проект DEMO в вебе
+- **THEN** открывается страница проекта с сообщением «Репозиторий создан» и ссылкой «Открыть в Gitea» на `alice/demo`
+
+#### Scenario Outline: Кто видит репозиторий
+- **GIVEN** репозиторий проекта <видимость> в пространстве <пространство> с соавторами `peppa-bot` и `bob`
+- **WHEN** участник открывает страницу проекта
+- **THEN** блок «Репозиторий» показывает путь, ссылку, видимость и текст «<кто видит>»
+
+| видимость | пространство | кто видит |
+|---|---|---|
+| приватный | пользователя `alice` | `alice` и соавторы: peppa-bot, bob |
+| приватный | организации `team` | участники организации `team` с доступом к репозиторию и соавторы: peppa-bot, bob |
+| публичный | пользователя `alice` | все, у кого есть доступ к Gitea |
+
+#### Scenario: Участник без доступа к репозиторию
+- **GIVEN** `bob` — участник проекта, но не соавтор репозитория (его добавили, когда у Пеппы не было прав)
+- **WHEN** владелец открывает страницу проекта
+- **THEN** у `bob` отмечено «нет доступа к репозиторию»
+- **WHEN** владелец нажимает «Выдать доступ участникам»
+- **THEN** `bob` — соавтор репозитория с правом write
+
+#### Scenario: MCP
+- **WHEN** клиент вызывает `create_project` без `visibility`
+- **THEN** репозиторий публичный, ответ содержит URL репозитория в Gitea, его видимость и кто его видит
+- **AND** `list_projects` показывает URL репозитория у каждого проекта
+
+#### Scenario: Gitea недоступен
+- **GIVEN** Gitea не отвечает
+- **WHEN** пользователь открывает страницу проекта
+- **THEN** путь и ссылка на репозиторий видны, вместо видимости — «не удалось узнать у Gitea»
+
+## ADDED Requirements
+
+### Requirement: Смена видимости существующего проекта
+Владелец проекта SHALL менять видимость его репозитория в Gitea из «⋯ Настройки
+проекта» в вебе и MCP-инструментом `set_project_visibility`; Пеппа меняет её клиентом
+владельца, иначе `peppa-bot`, и сразу показывает новую. Админ машины Пеппы SHALL
+менять видимость одного или всех проектов командой
+`peppa project visibility public|private`.
+
+#### Scenario: Владелец делает репозиторий приватным
+- **GIVEN** проект DEMO владельца `alice` с публичным репозиторием `alice/demo`
+- **WHEN** `alice` нажимает «Сделать приватным» в «⋯ Настройки проекта» → «Репозиторий»
+- **THEN** `alice/demo` в Gitea приватный
+- **AND** блок «Репозиторий» показывает видимость «приватный» и «alice и соавторы: peppa-bot»
+
+#### Scenario: Через MCP
+- **GIVEN** проект DEMO владельца `alice` с приватным репозиторием
+- **WHEN** клиент `alice` вызывает `set_project_visibility` с `project: "DEMO"`, `visibility: "public"`
+- **THEN** репозиторий публичный, ответ — «DEMO: репозиторий alice/demo теперь публичный» и кто его видит
+
+#### Scenario: Не владелец
+- **GIVEN** `bob` — участник проекта DEMO, но не владелец
+- **WHEN** `bob` пытается сменить видимость
+- **THEN** он получает ошибку «Видимость репозитория меняет только владелец проекта», видимость в Gitea не меняется
+
+#### Scenario: Нет прав в Gitea
+- **GIVEN** ни у владельца, ни у `peppa-bot` нет прав администратора на репозиторий
+- **WHEN** владелец меняет видимость
+- **THEN** он видит ошибку «Не удалось сменить видимость …: нет прав администратора в Gitea», видимость не меняется
+
+#### Scenario: Все проекты из CLI
+- **GIVEN** проекты HWT и PEP с приватными репозиториями
+- **WHEN** админ выполняет `peppa project visibility --all public`
+- **THEN** оба репозитория публичные, по строке на проект
+- **AND** `peppa project visibility --all private` возвращает их обратно
diff --git a/openspec/changes/pep-64-visibility/tasks.md b/openspec/changes/pep-64-visibility/tasks.md
new file mode 100644
index 00000000..aa172c03
--- /dev/null
+++ b/openspec/changes/pep-64-visibility/tasks.md
@@ -0,0 +1,19 @@
+# Tasks: PEP-64
+
+## 1. Умолчание «Публичный»
+- [ ] 1.1 `provisionProject`: по умолчанию публичный
+- [ ] 1.2 Веб «Новый проект»: «Публичный» выбран по умолчанию
+- [ ] 1.3 MCP `create_project`: описание и умолчание
+- [ ] 1.4 CLI `peppa project create … --private` вместо `--public`
+
+## 2. Смена видимости
+- [ ] 2.1 `GiteaClient.setRepoPrivate` + `mock-gitea` PATCH repo
+- [ ] 2.2 `setProjectVisibility` в runner (владелец/бот, сброс кэша)
+- [ ] 2.3 Веб: кнопка в «⋯ Настройки проекта» → «Репозиторий», server action
+- [ ] 2.4 MCP `set_project_visibility` + `/help` + instructions
+- [ ] 2.5 CLI `peppa project visibility public|private`
+
+## 3. Проверка
+- [ ] 3.1 Тесты в `repo-visibility.test.ts` по сценариям
+- [ ] 3.2 typecheck, e2e
+- [ ] 3.3 AGENTS.md: строка про видимость
--
2.45.2
From efeac4500bfe3c2541b8a05c5612231daacb9a7d 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:18:59 +0500
Subject: [PATCH 030/518] PEP-64: public by default, change visibility (runner,
web, MCP, CLI), tests
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 12 +-
apps/web/app/(app)/help/page.tsx | 6 +-
apps/web/app/(app)/p/[key]/page.tsx | 25 ++++-
apps/web/app/(app)/projects/new/page.tsx | 4 +-
openspec/changes/pep-64-visibility/tasks.md | 24 ++--
packages/cli/src/index.ts | 33 +++++-
packages/core/src/gitea.ts | 5 +
packages/mcp/src/manager.ts | 20 +++-
packages/runner/src/provision.ts | 4 +-
packages/runner/src/share.ts | 32 ++++++
packages/testkit/src/mock-gitea.ts | 6 +
packages/testkit/test/repo-visibility.test.ts | 104 +++++++++++++++++-
13 files changed, 236 insertions(+), 40 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 116f9c71..f6459652 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,6 +25,7 @@
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в 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-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility public|private` — админ, без проверки владельца
- **Ошибки из прода (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 или сгенерированный)
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index f8a016a6..0609abb7 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -29,7 +29,7 @@ import {
} 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, projectNamespace, 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, setProjectVisibility, 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";
@@ -154,7 +154,7 @@ export async function createProjectAction(f: FormData) {
key: str(f, "key"),
name: str(f, "name"),
existing: str(f, "mode") === "existing",
- visibility: str(f, "visibility") === "public" ? "public" : "private",
+ visibility: str(f, "visibility") === "private" ? "private" : "public",
ownerId: user.id,
});
return `/p/${p.key}?created=1`;
@@ -241,6 +241,14 @@ export async function grantRepoAccessToMembers(f: FormData) {
});
}
+export async function setProjectVisibilityAction(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await setProjectVisibility(db, p, str(f, "visibility") === "private" ? "private" : "public", { actor: user });
+ });
+}
+
export async function removeProjectMember(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 3f9c7ada..b13be4d2 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -5,12 +5,13 @@ import { PageHeader, Section } from "@/components/common";
const TOOLS: Array<[string, string]> = [
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке"],
- ["create_project", "новый проект: репозиторий в Gitea (приватный по умолчанию или публичный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
+ ["create_project", "новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
["list_epics / create_epic / update_epic", "эпики проекта (метки стори): завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"],
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, прогресс"],
["create_task / update_task", "завести стори (в Бэклог, с эпиком epic_id); поправить название, описание, эпик"],
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
+ ["set_project_visibility", "сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий"],
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"],
["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"],
@@ -30,6 +31,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
+ { title: "Видимость репозитория", say: "Сделай репозиторий PAY приватным", how: "set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»" },
{ 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; не поднялся — Пеппа сама откатит и напишет" },
@@ -46,7 +48,7 @@ export default async function Help() {
Проект — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки Доска · Код (README, ветки, коммиты) · Спеки (что система умеет сейчас — openspec/specs ) · PR (открытые PR и их проверки) · Релизы · Баги · Сессии ; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке.
- Где репозиторий — в выбранном при создании пространстве Gitea: личном (<ваш логин>/<slug> ) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), peppa-bot и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.
+ Где репозиторий — в выбранном при создании пространстве Gitea: личном (<ваш логин>/<slug> ) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), peppa-bot и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий».
Стори (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты tasks.md внутри change, не путать.
Эпик — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP.
Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index d2c55983..82187214 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -17,7 +17,7 @@ import { requireUser } from "@/lib/auth";
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 { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, setProjectVisibilityAction } from "../../actions";
import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs";
const RELEASE_STATUS: Record = {
@@ -123,11 +123,24 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Рабочая копия
{p.workspacePath}
-
-
- Открыть в Gitea
-
-
+
+
+
+ Открыть в Gitea
+
+
+ {isOwner && repo.private !== null && (
+
+
+ {repo.private ? "Сделать публичным" : "Сделать приватным"}
+
+ )}
+
+ {isOwner && repo.private !== null && (
+
+ {repo.private ? "Публичный репозиторий видят все, у кого есть доступ к Gitea." : "Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot."} Видимость меняется в Gitea сразу.
+
+ )}
diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx
index 8832a812..40e4b445 100644
--- a/apps/web/app/(app)/projects/new/page.tsx
+++ b/apps/web/app/(app)/projects/new/page.tsx
@@ -80,8 +80,8 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
)}
Видимость
- Приватный — только те, кому выдан доступ
- Публичный — все, у кого есть доступ к Gitea
+ Публичный — все, у кого есть доступ к Gitea
+ Приватный — только те, кому выдан доступ
Репозиторий
diff --git a/openspec/changes/pep-64-visibility/tasks.md b/openspec/changes/pep-64-visibility/tasks.md
index aa172c03..f423f9cd 100644
--- a/openspec/changes/pep-64-visibility/tasks.md
+++ b/openspec/changes/pep-64-visibility/tasks.md
@@ -1,19 +1,19 @@
# Tasks: PEP-64
## 1. Умолчание «Публичный»
-- [ ] 1.1 `provisionProject`: по умолчанию публичный
-- [ ] 1.2 Веб «Новый проект»: «Публичный» выбран по умолчанию
-- [ ] 1.3 MCP `create_project`: описание и умолчание
-- [ ] 1.4 CLI `peppa project create … --private` вместо `--public`
+- [x] 1.1 `provisionProject`: по умолчанию публичный
+- [x] 1.2 Веб «Новый проект»: «Публичный» выбран по умолчанию
+- [x] 1.3 MCP `create_project`: описание и умолчание
+- [x] 1.4 CLI `peppa project create … --private` вместо `--public`
## 2. Смена видимости
-- [ ] 2.1 `GiteaClient.setRepoPrivate` + `mock-gitea` PATCH repo
-- [ ] 2.2 `setProjectVisibility` в runner (владелец/бот, сброс кэша)
-- [ ] 2.3 Веб: кнопка в «⋯ Настройки проекта» → «Репозиторий», server action
-- [ ] 2.4 MCP `set_project_visibility` + `/help` + instructions
-- [ ] 2.5 CLI `peppa project visibility public|private`
+- [x] 2.1 `GiteaClient.setRepoPrivate` + `mock-gitea` PATCH repo
+- [x] 2.2 `setProjectVisibility` в runner (владелец/бот, сброс кэша)
+- [x] 2.3 Веб: кнопка в «⋯ Настройки проекта» → «Репозиторий», server action
+- [x] 2.4 MCP `set_project_visibility` + `/help` + instructions
+- [x] 2.5 CLI `peppa project visibility public|private`
## 3. Проверка
-- [ ] 3.1 Тесты в `repo-visibility.test.ts` по сценариям
-- [ ] 3.2 typecheck, e2e
-- [ ] 3.3 AGENTS.md: строка про видимость
+- [x] 3.1 Тесты в `repo-visibility.test.ts` по сценариям
+- [x] 3.2 typecheck, e2e
+- [x] 3.3 AGENTS.md: строка про видимость
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index e0c20672..660d5184 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -8,6 +8,7 @@ import {
createTask,
findProjectFile,
getProject,
+ repoVisibilityLabel,
createLoginLink,
createPairingCode,
listUsers,
@@ -47,16 +48,17 @@ import {
type TaskStatus,
} from "@peppa/core";
import { createDb, migrateDb } from "@peppa/db";
-import { answerAndDeliver, connectCi, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, 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, setProjectVisibility, 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
- peppa project create [--existing] [--public] (repo in peppa-bot's Gitea namespace)
+ peppa project create [--existing] [--private] (repo in peppa-bot's Gitea namespace)
peppa project add [--owner peppa] [--repo ] [--path ] (register only)
peppa project owner
+ peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot)
peppa project list
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
peppa release list [KEY]
@@ -102,7 +104,7 @@ const { values: opts, positionals } = parseArgs({
options: {
owner: { type: "string", default: "peppa-bot" },
existing: { type: "boolean" },
- public: { type: "boolean" },
+ private: { type: "boolean" },
repo: { type: "string" },
path: { type: "string" },
description: { type: "string", short: "d" },
@@ -199,7 +201,7 @@ async function main(): Promise {
}
case "project create": {
const [slug, key, name] = args;
- if (!slug || !key || !name) throw new PeppaError("usage: peppa project create [--existing] [--public]");
+ if (!slug || !key || !name) throw new PeppaError("usage: peppa project create [--existing] [--private]");
const bot = giteaForBot();
const p = await provisionProject(db, {
gitea: bot,
@@ -209,7 +211,7 @@ async function main(): Promise {
key,
name,
existing: opts.existing,
- visibility: opts.public ? "public" : "private",
+ visibility: opts.private ? "private" : "public",
log: (step) => console.log(`… ${step}`),
});
console.log(`Project ${p.key} → ${p.workspacePath} (${env.GITEA_URL}/${p.giteaOwner}/${p.giteaRepo})`);
@@ -225,6 +227,25 @@ async function main(): Promise {
console.log(`${p.key} owner → ${u?.login ?? "none"}`);
break;
}
+ case "project visibility": {
+ const [first, second] = args;
+ const keys = opts.all ? (await listProjects(db)).map((p) => p.key) : first ? [first] : [];
+ const vis = opts.all ? first : second;
+ if (!keys.length || (vis !== "public" && vis !== "private")) throw new PeppaError("usage: peppa project visibility public|private");
+ let failed = 0;
+ for (const key of keys) {
+ const p = await getProject(db, key);
+ try {
+ const repo = await setProjectVisibility(db, p, vis);
+ console.log(`${p.key.padEnd(8)} ${repo.fullName} → ${repoVisibilityLabel(repo.private)}`);
+ } catch (e) {
+ failed++;
+ console.log(`${p.key.padEnd(8)} ${p.giteaOwner}/${p.giteaRepo} ✗ ${(e as Error).message}`);
+ }
+ }
+ if (failed) process.exitCode = 1;
+ break;
+ }
case "project list":
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`);
break;
@@ -481,7 +502,7 @@ async function main(): Promise {
try {
if (opts.help) console.log(USAGE);
else await main();
- process.exit(0);
+ process.exit(process.exitCode ?? 0);
} catch (e) {
console.error(e instanceof PeppaError ? `peppa: ${e.message}` : e);
process.exit(1);
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index ebd6ab71..e5a77367 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -136,6 +136,11 @@ export class GiteaClient {
return this.request("POST", asUser ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, body);
}
+ /** Changes repo visibility (needs admin rights on the repo). */
+ setRepoPrivate(owner: string, name: string, isPrivate: boolean) {
+ return this.request("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate });
+ }
+
/** True if `name` is an organization (false for a user account). */
async isOrg(name: string): Promise {
try {
diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts
index 10b9fa4c..aa32f29a 100644
--- a/packages/mcp/src/manager.ts
+++ b/packages/mcp/src/manager.ts
@@ -31,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, projectNamespace, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
+import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, 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";
@@ -52,7 +52,7 @@ Good habits:
- Label stories with an epic (epic_id) when one fits. Write story descriptions with context and a "Definition of done" list; the agent works from them.
- Only move a story 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.
+- Projects can be shared: add_member / remove_member (owner only); members can do everything else. Repos are public by default; set_project_visibility (owner only) makes one private or public again.
- 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.`;
@@ -156,14 +156,14 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"create_project",
- "Create a Peppa project: a new Gitea repo (private by default, or public) or connect an existing one you admin (its visibility is kept), in your namespace or an org you can create repos in, filled from the Peppa template with OpenSpec. Returns the repo URL, its visibility and who can see it. Takes ~15 s.",
+ "Create a Peppa project: a new Gitea repo (public by default, or private) or connect an existing one you admin (its visibility is kept), in your namespace or an org you can create repos in, filled from the Peppa template with OpenSpec. Returns the repo URL, its visibility and who can see it. Takes ~15 s.",
{
name: z.string().trim().min(2).describe("Human name, e.g. Payments"),
slug: z.string().describe("Repo name: a-z, 0-9, dashes"),
key: z.string().describe("Story key prefix, 2–10 letters/digits, e.g. PAY"),
owner: z.string().optional().describe("Gitea namespace: your login (default) or an org"),
existing: z.boolean().optional().describe("Connect an existing repo owner/slug instead of creating one"),
- visibility: z.enum(["private", "public"]).optional().describe("New repo visibility (default private: only the namespace owner/org members with access, peppa-bot and project members see it)"),
+ visibility: z.enum(["private", "public"]).optional().describe("New repo visibility (default public: everyone with Gitea access sees it; private: only the namespace owner/org members with access, peppa-bot and project members)"),
},
false,
async ({ name, slug, key, owner, existing, visibility }) => {
@@ -177,6 +177,18 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
+ tool(
+ "set_project_visibility",
+ "Make the project's Gitea repo public (everyone with Gitea access sees it) or private (only the namespace owner/org members with access, collaborators and peppa-bot). Owner only. Returns the new visibility and who can see the repo.",
+ { project: projectArg, visibility: z.enum(["public", "private"]) },
+ false,
+ async ({ project, visibility }) => {
+ const p = await ownedProject(project);
+ const repo = await setProjectVisibility(db, p, visibility, { actor: user });
+ return [`${p.key}: репозиторий ${repo.fullName} теперь ${repoVisibilityLabel(repo.private)}`, `Who can see it: ${repoAudience(repo)}`].join("\n");
+ },
+ );
+
tool(
"list_tasks",
"List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column.",
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index 804a6caa..741e3d48 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -20,7 +20,7 @@ export interface ProvisionOptions {
slug: string;
key: string;
name: string;
- /** For a new repo; an existing one keeps its visibility. Default private. */
+ /** For a new repo; an existing one keeps its visibility. Default public (PEP-64). */
visibility?: "private" | "public";
/** Connect an existing repo `owner/slug` instead of creating one. */
existing?: boolean;
@@ -64,7 +64,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise {
+ if (visibility !== "public" && visibility !== "private") throw new PeppaError(`Видимость: public или private, не «${visibility}»`);
+ if (opts.actor && project.ownerId !== opts.actor.id) throw new PeppaError("Видимость репозитория меняет только владелец проекта");
+ const fullName = `${project.giteaOwner}/${project.giteaRepo}`;
+ const clients = await repoAdmins(db, project);
+ if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново");
+ let last: unknown = null;
+ let done = false;
+ for (const c of clients) {
+ try {
+ await c.setRepoPrivate(project.giteaOwner, project.giteaRepo, visibility === "private");
+ done = true;
+ break;
+ } catch (e) {
+ last = e;
+ }
+ }
+ describeCache.delete(project.id);
+ if (!done) {
+ const status = (last as { status?: number } | null)?.status;
+ const why = status === 403 || status === 401 ? "нет прав администратора в Gitea" : status === 404 ? "репозиторий не найден в Gitea" : ((last as Error | null)?.message ?? "Gitea не ответил");
+ throw new PeppaError(`Не удалось сменить видимость ${fullName}: ${why}`);
+ }
+ return describeRepo(db, project, { fresh: true });
+}
+
const DESCRIBE_TIMEOUT_MS = 5000;
const DESCRIBE_CACHE_MS = 60_000;
// The project page refreshes every few seconds; Gitea is asked at most once a minute per project.
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index 9320fa07..eb9e85a6 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -302,6 +302,12 @@ export class MockGitea {
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
if (!r) return { status: 404, body: { message: "not found" } };
if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 };
+ if (method === "PATCH") {
+ // Gitea: only repo admins (owner, org owners, admin collaborators) may edit settings.
+ if (!r.admins.has(me.login)) return { status: 403, body: { message: "token does not have at least one of required scope(s): [write:repository]" } };
+ if (typeof body.private === "boolean") r.private = body.private;
+ return { status: 200, body: this.json(r, me) };
+ }
return { status: 200, body: this.json(r, me) };
}
if (method === "POST" && (path === "/api/v1/user/repos" || (m = path.match(/^\/api\/v1\/orgs\/([^/]+)\/repos$/)))) {
diff --git a/packages/testkit/test/repo-visibility.test.ts b/packages/testkit/test/repo-visibility.test.ts
index cdfb7a3d..0f2eefb7 100644
--- a/packages/testkit/test/repo-visibility.test.ts
+++ b/packages/testkit/test/repo-visibility.test.ts
@@ -1,6 +1,8 @@
// PEP-15: where the project's Gitea repo is, its visibility and who can see it.
+// PEP-64: public by default, private by choice; the owner (or the CLI) changes it later.
import assert from "node:assert/strict";
-import { execFileSync } from "node:child_process";
+import { execFile, execFileSync } from "node:child_process";
+import { promisify } from "node:util";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
@@ -64,8 +66,16 @@ async function mcpAs(user: U) {
}
describe("repo visibility and namespace", () => {
- test("default: private repo in the personal namespace, seen by the owner and collaborators", async () => {
- const p = await provision({ slug: "mock-vis-demo", key: "MVDEMO" });
+ test("new project by default is public", async () => {
+ const p = await provision({ slug: "mock-vis-default", key: "MVDEF" });
+ assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
+ const repo = await runner.describeRepo(db, p);
+ assert.equal(core.repoVisibilityLabel(repo.private), "публичный");
+ assert.equal(core.repoAudience(repo), "все, у кого есть доступ к Gitea");
+ });
+
+ test("private by choice: private repo in the personal namespace, seen by the owner and collaborators", async () => {
+ const p = await provision({ slug: "mock-vis-demo", key: "MVDEMO", visibility: "private" });
assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-demo`)!.private, true);
const repo = await runner.describeRepo(db, p);
assert.equal(repo.fullName, `${ALICE.login}/mock-vis-demo`);
@@ -105,7 +115,7 @@ describe("repo visibility and namespace", () => {
});
test("member without repo access is visible; owner grants access to all members", async () => {
- const p = await provision({ slug: "mock-vis-team-app", key: "MVTEAM" });
+ const p = await provision({ slug: "mock-vis-team-app", key: "MVTEAM", visibility: "private" });
await core.addMember(db, p, BOB.login, alice.id); // Peppa membership only, no Gitea collaborator
let repo = await runner.describeRepo(db, p, { fresh: true });
assert.ok(!repo.collaborators!.includes(BOB.login));
@@ -147,4 +157,90 @@ describe("repo visibility and namespace", () => {
const list = await call("list_projects");
assert.match(list.text, new RegExp(`MVMCP — Mock MCP \\(${gitea.url}/${ALICE.login}/mock-vis-mcp\\)`));
});
+
+ test("MCP: create_project without visibility makes a public repo", async () => {
+ const call = await mcpAs(alice);
+ process.env.PEPPA_TEMPLATE_URL = templateUrl;
+ try {
+ const r = await call("create_project", { name: "Mock MCP default", slug: "mock-vis-mcp-def", key: "MVMCPD" });
+ assert.equal(r.isError, false, r.text);
+ assert.match(r.text, /\(публичный, personal namespace\)/);
+ assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-mcp-def`)!.private, false);
+ } finally {
+ delete process.env.PEPPA_TEMPLATE_URL;
+ }
+ });
+});
+
+describe("changing visibility of an existing project (PEP-64)", () => {
+ test("owner makes the repo private: Gitea and the project card show it at once", async () => {
+ const p = await core.getProject(db, "MVDEF");
+ assert.equal((await runner.describeRepo(db, p)).private, false); // cached as public
+ const repo = await runner.setProjectVisibility(db, p, "private", { actor: alice });
+ assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, true);
+ assert.equal(repo.private, true);
+ const card = await runner.describeRepo(db, p); // no stale cache
+ assert.equal(core.repoVisibilityLabel(card.private), "приватный");
+ assert.equal(core.repoAudience(card), `${ALICE.login} и соавторы: peppa-bot`);
+ });
+
+ test("MCP: set_project_visibility makes it public and says who sees it", async () => {
+ const call = await mcpAs(alice);
+ const r = await call("set_project_visibility", { project: "MVDEF", visibility: "public" });
+ assert.equal(r.isError, false, r.text);
+ assert.match(r.text, new RegExp(`MVDEF: репозиторий ${ALICE.login}/mock-vis-default теперь публичный`));
+ assert.match(r.text, /Who can see it: все, у кого есть доступ к Gitea/);
+ assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
+ });
+
+ test("not the owner: refused, visibility unchanged", async () => {
+ const p = await core.getProject(db, "MVDEF");
+ await core.addMember(db, p, BOB.login, alice.id);
+ await assert.rejects(runner.setProjectVisibility(db, p, "private", { actor: bob }), /меняет только владелец проекта/);
+ const call = await mcpAs(bob);
+ const r = await call("set_project_visibility", { project: "MVDEF", visibility: "private" });
+ assert.equal(r.isError, true);
+ assert.match(r.text, /меняет только владелец проекта/);
+ assert.equal(gitea.repos.get(`${ALICE.login}/mock-vis-default`)!.private, false);
+ });
+
+ test("no admin rights in Gitea: clear error, visibility unchanged", async () => {
+ // A repo in bob's namespace that alice's project points to: neither alice nor peppa-bot administers it.
+ gitea.addRepo(BOB.login, "mock-vis-foreign", { admins: [BOB.login], private: false });
+ const p = await core.createProject(db, { slug: "mock-vis-foreign", key: "MVFOR", name: "Foreign", giteaOwner: BOB.login, giteaRepo: "mock-vis-foreign", workspacePath: join(TMP, "foreign") });
+ await core.setProjectOwner(db, p.id, alice.id);
+ const owned = await core.getProject(db, "MVFOR");
+ await assert.rejects(runner.setProjectVisibility(db, owned, "private", { actor: alice }), /Не удалось сменить видимость mock-vis-bob\/mock-vis-foreign: нет прав администратора в Gitea/);
+ assert.equal(gitea.repos.get(`${BOB.login}/mock-vis-foreign`)!.private, false);
+ });
+
+ test("CLI: peppa project visibility --all public|private, one line per project", async () => {
+ // Async: mock-gitea answers from this process.
+ const cli = async (...a: string[]) => {
+ try {
+ const r = await promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "visibility", ...a], { encoding: "utf8", env: process.env });
+ return { out: r.stdout + r.stderr, code: 0 };
+ } catch (e) {
+ const x = e as { stdout: string; stderr: string; code: number };
+ return { out: x.stdout + x.stderr, code: x.code };
+ }
+ };
+ const mine = [...gitea.repos.values()].filter((r) => r.owner === ALICE.login || r.owner === "mock-vis-team");
+ const one = await cli("MVDEMO", "public");
+ assert.equal(one.code, 0, one.out);
+ assert.match(one.out, new RegExp(`MVDEMO\\s+${ALICE.login}/mock-vis-demo → публичный`));
+ const all = await cli("--all", "private");
+ assert.equal(all.code, 1, all.out); // MVFOR: no admin rights → reported, the rest still switched
+ assert.match(all.out, /MVFOR .*✗ Не удалось сменить видимость/);
+ assert.match(all.out, /MVMCP\s+.*→ приватный/);
+ const projects = ["mock-vis-demo", "mock-vis-pub", "mock-vis-mcp", "mock-vis-default"];
+ for (const name of projects) {
+ const r = mine.find((x) => x.name === name)!;
+ assert.equal(r.private, true, `${name} private`);
+ }
+ const back = await cli("--all", "public");
+ for (const name of projects) assert.equal(mine.find((x) => x.name === name)!.private, false, `${name} public again`);
+ assert.match(back.out, /MVPUB\s+mock-vis-team\/mock-vis-pub → публичный/);
+ assert.match((await cli("MVDEMO")).out, /usage: peppa project visibility/);
+ });
});
--
2.45.2
From 90bb5daabe1e8017bfcda01e03d178982fed56cd 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:19:31 +0500
Subject: [PATCH 031/518] PEP-64: archive OpenSpec change pep-64-visibility
Co-Authored-By: Claude Opus 5.5
---
.../.openspec.yaml | 0
.../2026-11-14-pep-64-visibility}/design.md | 0
.../2026-11-14-pep-64-visibility}/proposal.md | 0
.../specs/project-provisioning/spec.md | 0
.../2026-11-14-pep-64-visibility}/tasks.md | 0
openspec/specs/project-provisioning/spec.md | 61 ++++++++++++++++---
6 files changed, 52 insertions(+), 9 deletions(-)
rename openspec/changes/{pep-64-visibility => archive/2026-11-14-pep-64-visibility}/.openspec.yaml (100%)
rename openspec/changes/{pep-64-visibility => archive/2026-11-14-pep-64-visibility}/design.md (100%)
rename openspec/changes/{pep-64-visibility => archive/2026-11-14-pep-64-visibility}/proposal.md (100%)
rename openspec/changes/{pep-64-visibility => archive/2026-11-14-pep-64-visibility}/specs/project-provisioning/spec.md (100%)
rename openspec/changes/{pep-64-visibility => archive/2026-11-14-pep-64-visibility}/tasks.md (100%)
diff --git a/openspec/changes/pep-64-visibility/.openspec.yaml b/openspec/changes/archive/2026-11-14-pep-64-visibility/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-64-visibility/.openspec.yaml
rename to openspec/changes/archive/2026-11-14-pep-64-visibility/.openspec.yaml
diff --git a/openspec/changes/pep-64-visibility/design.md b/openspec/changes/archive/2026-11-14-pep-64-visibility/design.md
similarity index 100%
rename from openspec/changes/pep-64-visibility/design.md
rename to openspec/changes/archive/2026-11-14-pep-64-visibility/design.md
diff --git a/openspec/changes/pep-64-visibility/proposal.md b/openspec/changes/archive/2026-11-14-pep-64-visibility/proposal.md
similarity index 100%
rename from openspec/changes/pep-64-visibility/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-64-visibility/proposal.md
diff --git a/openspec/changes/pep-64-visibility/specs/project-provisioning/spec.md b/openspec/changes/archive/2026-11-14-pep-64-visibility/specs/project-provisioning/spec.md
similarity index 100%
rename from openspec/changes/pep-64-visibility/specs/project-provisioning/spec.md
rename to openspec/changes/archive/2026-11-14-pep-64-visibility/specs/project-provisioning/spec.md
diff --git a/openspec/changes/pep-64-visibility/tasks.md b/openspec/changes/archive/2026-11-14-pep-64-visibility/tasks.md
similarity index 100%
rename from openspec/changes/pep-64-visibility/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-64-visibility/tasks.md
diff --git a/openspec/specs/project-provisioning/spec.md b/openspec/specs/project-provisioning/spec.md
index 37c4642d..20cba60b 100644
--- a/openspec/specs/project-provisioning/spec.md
+++ b/openspec/specs/project-provisioning/spec.md
@@ -8,20 +8,25 @@
### Requirement: Новый проект с новым репозиторием
Пеппа SHALL создавать проект по имени, slug и ключу задач: репозиторий в выбранном
пространстве (пользователь или организация, где он может создавать репозитории) с
-выбранной видимостью (приватный по умолчанию или публичный), заполненный из шаблона и
+выбранной видимостью (публичный по умолчанию или приватный), заполненный из шаблона и
инициализированный OpenSpec.
#### Scenario: Успешное создание
- **GIVEN** пользователь `alice` вошёл в Пеппу
- **WHEN** он создаёт проект «Demo», slug `demo`, ключ `DEMO` в своём пространстве, не меняя видимость
-- **THEN** в Gitea появляется приватный `alice/demo` с первым коммитом от Peppa, содержащим `AGENTS.md`, `CLAUDE.md`, `.mcp.json`, `.peppa/project.json` (slug, ключ, URL Пеппы) и `openspec/`, но не `RULES.md`
+- **THEN** в Gitea появляется публичный `alice/demo` с первым коммитом от Peppa, содержащим `AGENTS.md`, `CLAUDE.md`, `.mcp.json`, `.peppa/project.json` (slug, ключ, URL Пеппы) и `openspec/`, но не `RULES.md`
- **AND** в Пеппе появляется проект DEMO с владельцем `alice`
- **AND** рабочая копия лежит в `$PEPPA_WORKSPACES/demo`
#### Scenario: Публичный репозиторий в организации
- **GIVEN** `alice` может создавать репозитории в организации `team`
-- **WHEN** она создаёт проект со slug `app` в пространстве `team` с видимостью «публичный»
-- **THEN** в Gitea появляется публичный `team/app`
+- **WHEN** она создаёт проект со slug `site` в пространстве `team` с видимостью «Публичный»
+- **THEN** в Gitea появляется публичный `team/site`
+
+#### Scenario: Приватный репозиторий по выбору
+- **GIVEN** `alice` может создавать репозитории в организации `team`
+- **WHEN** она создаёт проект со slug `app` в пространстве `team` с видимостью «Приватный»
+- **THEN** в Gitea появляется приватный `team/app`
#### Scenario: Конфликты
- **WHEN** slug или ключ уже заняты в Пеппе, или репозиторий с таким именем уже есть в выбранном пространстве
@@ -54,13 +59,17 @@
### Requirement: Создание проекта из CLI
Тот же сценарий SHALL быть доступен из CLI на машине Пеппы от имени `peppa-bot`
-(репозиторий в пространстве бота, без владельца-пользователя); `--public` создаёт
-публичный репозиторий.
+(репозиторий в пространстве бота, без владельца-пользователя); репозиторий публичный,
+`--private` создаёт приватный.
#### Scenario: CLI
- **WHEN** админ выполняет `peppa project create demo DEMO "Demo"`
- **THEN** результат совпадает с созданием из веба, кроме пространства (`peppa-bot`) и отсутствия владельца
+#### Scenario: CLI, приватный
+- **WHEN** админ выполняет `peppa project create demo DEMO "Demo" --private`
+- **THEN** репозиторий `peppa-bot/demo` приватный
+
### Requirement: Где репозиторий и кто его видит
Пеппа SHALL показывать, где лежит репозиторий проекта и кто его видит: в форме нового
проекта — до создания, после создания — сразу, на странице проекта и через MCP — всегда.
@@ -68,7 +77,7 @@
#### Scenario: Форма нового проекта
- **GIVEN** `alice` открывает «Новый проект»
-- **THEN** она видит выбор пространства (`alice` — личное, и организации, где может создавать репозитории) и видимости (приватный по умолчанию, публичный)
+- **THEN** она видит выбор пространства (`alice` — личное, и организации, где может создавать репозитории) и видимости (публичный по умолчанию, приватный)
- **AND** подсказку, кто увидит репозиторий в каждом случае
#### Scenario: Сразу после создания
@@ -94,11 +103,45 @@
- **THEN** `bob` — соавтор репозитория с правом write
#### Scenario: MCP
-- **WHEN** клиент вызывает `create_project` с `visibility: "public"`
-- **THEN** ответ содержит URL репозитория в Gitea, его видимость и кто его видит
+- **WHEN** клиент вызывает `create_project` без `visibility`
+- **THEN** репозиторий публичный, ответ содержит URL репозитория в Gitea, его видимость и кто его видит
- **AND** `list_projects` показывает URL репозитория у каждого проекта
#### Scenario: Gitea недоступен
- **GIVEN** Gitea не отвечает
- **WHEN** пользователь открывает страницу проекта
- **THEN** путь и ссылка на репозиторий видны, вместо видимости — «не удалось узнать у Gitea»
+
+### Requirement: Смена видимости существующего проекта
+Владелец проекта SHALL менять видимость его репозитория в Gitea из «⋯ Настройки
+проекта» в вебе и MCP-инструментом `set_project_visibility`; Пеппа меняет её клиентом
+владельца, иначе `peppa-bot`, и сразу показывает новую. Админ машины Пеппы SHALL
+менять видимость одного или всех проектов командой
+`peppa project visibility public|private`.
+
+#### Scenario: Владелец делает репозиторий приватным
+- **GIVEN** проект DEMO владельца `alice` с публичным репозиторием `alice/demo`
+- **WHEN** `alice` нажимает «Сделать приватным» в «⋯ Настройки проекта» → «Репозиторий»
+- **THEN** `alice/demo` в Gitea приватный
+- **AND** блок «Репозиторий» показывает видимость «приватный» и «alice и соавторы: peppa-bot»
+
+#### Scenario: Через MCP
+- **GIVEN** проект DEMO владельца `alice` с приватным репозиторием
+- **WHEN** клиент `alice` вызывает `set_project_visibility` с `project: "DEMO"`, `visibility: "public"`
+- **THEN** репозиторий публичный, ответ — «DEMO: репозиторий alice/demo теперь публичный» и кто его видит
+
+#### Scenario: Не владелец
+- **GIVEN** `bob` — участник проекта DEMO, но не владелец
+- **WHEN** `bob` пытается сменить видимость
+- **THEN** он получает ошибку «Видимость репозитория меняет только владелец проекта», видимость в Gitea не меняется
+
+#### Scenario: Нет прав в Gitea
+- **GIVEN** ни у владельца, ни у `peppa-bot` нет прав администратора на репозиторий
+- **WHEN** владелец меняет видимость
+- **THEN** он видит ошибку «Не удалось сменить видимость …: нет прав администратора в Gitea», видимость не меняется
+
+#### Scenario: Все проекты из CLI
+- **GIVEN** проекты HWT и PEP с приватными репозиториями
+- **WHEN** админ выполняет `peppa project visibility --all public`
+- **THEN** оба репозитория публичные, по строке на проект
+- **AND** `peppa project visibility --all private` возвращает их обратно
--
2.45.2
From 9720bb7d53f003f42bea8b4fc881a3d128809d5a 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:23:06 +0500
Subject: [PATCH 032/518] PEP-64: oauth test knows set_project_visibility
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/oauth.test.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts
index 7972f51f..938844f5 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_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "update_epic", "update_goal", "update_task"]);
+ assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "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 11778d98bde6e9b7140fedec189c2376cf833862 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:17:12 +0500
Subject: [PATCH 033/518] PEP-67: OpenSpec change pep-67-subscriptions
Co-Authored-By: Claude Opus 5.5
---
.../changes/pep-67-subscriptions/design.md | 113 ++++++++++++++++++
.../changes/pep-67-subscriptions/proposal.md | 50 ++++++++
.../specs/agent-credentials/spec.md | 110 +++++++++++++++++
.../specs/web-workspace/spec.md | 18 +++
.../changes/pep-67-subscriptions/tasks.md | 26 ++++
5 files changed, 317 insertions(+)
create mode 100644 openspec/changes/pep-67-subscriptions/design.md
create mode 100644 openspec/changes/pep-67-subscriptions/proposal.md
create mode 100644 openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md
create mode 100644 openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md
create mode 100644 openspec/changes/pep-67-subscriptions/tasks.md
diff --git a/openspec/changes/pep-67-subscriptions/design.md b/openspec/changes/pep-67-subscriptions/design.md
new file mode 100644
index 00000000..824bce3c
--- /dev/null
+++ b/openspec/changes/pep-67-subscriptions/design.md
@@ -0,0 +1,113 @@
+# Design: PEP-67 — подписки
+
+## Суперадмин
+`isSuperadmin(db, user)` (core/access.ts) = логин в `platformAdmins(db)` (`platform.admins`,
+по умолчанию allowlist). Отдельную настройку `platform.superadmins` пока не заводим: сейчас
+это одни и те же люди (asel, admin), а получатели алертов и права — одна роль «админ
+платформы». Отделить можно позже, поменяв только тело helper'а. Тот же helper делает PEP-68 —
+при слиянии остаётся один.
+
+Доступ: страница `/subscriptions` вызывает `notFound()` для не-суперадмина; все server
+actions подписок проверяют `requireSuperadmin()` (иначе ошибка «Не найдено»).
+
+## Модель данных
+- `subscriptions`: `provider` (claude|codex|opencode), `name`, `auth_kind`
+ (oauth|api_key|device), `secret_enc` (токен Claude / ключ OpenCode, AES-GCM `encrypt`),
+ `opencode_provider` (anthropic|openai|openrouter — какой env-ключ отдать), `status`
+ (pending|active|limited|auth_error), `limited_until`, `last_error`, `checked_at`,
+ `created_by` → users, `created_at`.
+- `subscription_pools` (`name` уникальное, `created_by`), `subscription_pool_members`
+ (pool_id, subscription_id — PK, каскад).
+- `projects.subscription_pool_id` → пулы (`set null`), `sessions.subscription_id` →
+ подписки (`set null`), `sessions.provider` += `opencode` (enum только в TS).
+- Колонки `users.claude_token_enc/_set_at` остаются в схеме (дроп колонки в SQLite —
+ пересоздание таблицы, рискованно рядом с параллельными миграциями), но миграция их
+ обнуляет после переноса и код их больше не читает.
+
+### Миграция данных
+Для каждого пользователя с `claude_token_enc`: подписка Claude «Claude — »
+(`auth_kind=oauth`, тот же шифротекст — ключ тот же), пул «Claude — » с ней, и этот
+пул — по умолчанию у проектов, где пользователь владелец. Так сессии его проектов после
+миграции работают на той же подписке, что и раньше. Затем токен у пользователя обнуляется.
+
+## Где хранится вход Codex / OpenCode
+Codex держит вход (ChatGPT OAuth с обновлением токена или ключ) в `$CODEX_HOME/auth.json`
+и сам его обновляет, поэтому зашифрованная копия в БД быстро устареет. Решение: у каждой
+подписки Codex свой каталог `$PEPPA_HOME/subscriptions/s/codex` (права 0700), так же
+как сам Codex хранит `~/.codex`. API-ключ Codex тоже уходит туда через
+`codex login --with-api-key` (ключ на stdin, в argv и логи не попадает), в БД ключ не
+храним. Удаление подписки удаляет каталог.
+
+OpenCode — подписка только по API-ключу провайдера модели: ключ зашифрован в БД и при
+запуске отдаётся как `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` / `OPENROUTER_API_KEY`.
+Интерактивный `opencode auth login` (выбор провайдера в TUI) из веба не ведём — это следующий
+шаг, если понадобится подписка, а не ключ.
+
+## Вход
+Общий механизм `runner/subscriptions.ts` поверх tmux (`peppa-auth-sub`), состояние
+входа — `settings` `subscription.login:` (10 мин):
+- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` переписан на подписку):
+ ссылка → код в форму → токен из вывода → `secret_enc`, статус `active`, tmux убивается
+ (стирает токен из буфера). Либо вставить готовый токен `sk-ant-oat…` руками.
+- Codex device auth: `codex login --device-auth` с `CODEX_HOME` подписки → со страницы
+ парсим ссылку и одноразовый код, показываем; страница опрашивает (`AutoRefresh`), раннер
+ смотрит: процесс завершился с успехом и есть `auth.json` → `active`; умер с ошибкой →
+ `auth_error`.
+- Новая подписка создаётся в статусе `pending`; отмена входа удаляет её, если она ни разу не
+ была активной.
+
+## «Проверить»
+Короткий запуск CLI без tmux (`execFile`, таймаут 60 с) в пустом каталоге:
+claude `-p "Ответь одним словом: ok" --max-turns 1`, codex `exec --skip-git-repo-check …`,
+opencode `run …` — с окружением подписки. Код 0 → `active`; в выводе лимит
+(`usage limit`, `rate limit`, `limit reached`, `resets …`) → `limited` (+ `limited_until`, если
+время сброса распознано, иначе +1 ч); иначе `auth_error` с хвостом вывода (секреты маскируются).
+
+## Выбор подписки раннером
+`startSession(…, { subscriptionIds?, poolId?, provider? })`:
+1. кандидаты = `subscriptionIds`, иначе подписки `poolId`, иначе пула проекта;
+2. если задан `provider` — только его подписки;
+3. пусто и ничего не выбрано явно → как раньше, без подписки (вход машины);
+ набор задан явно (или пул проекта есть), но подходящих нет → ошибка с объяснением;
+4. из `active` (и `limited`, у которых `limited_until` прошёл) — первая без активных сессий
+ (порядок: id); если все заняты — с наименьшим числом активных сессий (раннер не
+ блокируется, а PEP-39 решит справедливость);
+5. нет активных → ошибка «Нет активных подписок…».
+Провайдер сессии = провайдер подписки. `resumeSession` берёт подписку сессии (если её удалили —
+без подписки). Триаж инцидентов (`claudeTokenForProject`) берёт первую активную подписку
+Claude из пула проекта.
+
+Ротации и учёта лимита по подписке нет: при лимите сессия ведёт себя как раньше (PEP-56).
+Отметку `limited` у подписки ставит только «Проверить» — автоматику делает PEP-39.
+
+## OpenCode как провайдер раннера
+`opencode [cwd] --prompt [--model m] [--session ]` в tmux. Правила и MCP —
+через сгенерированный `opencode.json` в каталоге запуска (`OPENCODE_CONFIG`):
+`instructions: [rules.md]`, `mcp.peppa = { type: "local", command: [peppa-mcp] }`.
+Хуков, совместимых с Claude, у OpenCode нет (есть JS-плагины с событиями, контракт для нас не
+снят), поэтому этап минимальный, как у Codex без notify: статус сессии по процессу/экрану —
+вачдог (живой pane, смерть, зависание). Вопросы-разрешения в Telegram не ходят. Хуки через
+плагин OpenCode — отдельная задача.
+
+## Веб
+- Меню: «Подписки» (иконка KeyRound) только при `isSuperadmin`.
+- `/subscriptions`: список подписок (провайдер, название, кто добавил, статус, сессии сейчас,
+ «Проверить», «Удалить», «Переподключить» для Claude), блоки «+ Claude Code», «+ Codex»,
+ «+ OpenCode»; пулы — создать (название + отметки подписок), изменить состав, удалить.
+- «⋯ Настройки проекта» → «Подписки»: пул по умолчанию (select для суперадмина, текст для
+ остальных).
+- Страница стори → «Запустить агента»: суперадмин выбирает пул или отмечает подписки
+ (checkbox, multiple choice); остальные — провайдер, как раньше, и пул проекта.
+- «Раннеры»: строка и детали показывают подписку сессии.
+- «Настройки → Claude» убрано, вместо него — подсказка, что подписки ведёт суперадмин.
+
+## Моки
+- `mock-claude setup-token` (было), `mock-claude -p` (пробный запуск: токен с `bad` →
+ ошибка входа, с `limit` → баннер лимита);
+- `mock-codex login --device-auth` (печатает ссылку и код, ждёт файл
+ `$CODEX_HOME/mock-device-approved` или `…-denied`, пишет `auth.json`),
+ `mock-codex login --with-api-key` (ключ со stdin, `mock-bad…` → ошибка), `mock-codex exec`;
+- `mock-opencode` (TUI-сессия по сценарию через `mock-agent.ts opencode`, `run` для проверки).
+
+Для реальной интеграции нужны: настоящие подписки (вход суперадмина), проверка вывода
+настоящего `codex login --device-auth` (регэкспы ссылки и кода) и `opencode` на машине.
diff --git a/openspec/changes/pep-67-subscriptions/proposal.md b/openspec/changes/pep-67-subscriptions/proposal.md
new file mode 100644
index 00000000..41b8776b
--- /dev/null
+++ b/openspec/changes/pep-67-subscriptions/proposal.md
@@ -0,0 +1,50 @@
+# Proposal: PEP-67 — подписки и пулы для ротации
+
+Задача Пеппы: **PEP-67** (первый этап PEP-39).
+
+## Why
+
+Агенты сейчас работают либо на входе машины, либо на токене Claude владельца проекта
+(«Настройки → Claude», PEP-13). Подписок у фабрики несколько (Claude Max, ChatGPT/Codex,
+ключи для OpenCode), и чтобы раннеры не упирались в лимит одной подписки, нужно вести их
+в одном месте и раздавать раннерам из пулов. Это база для ротации при лимите (PEP-39).
+
+## What Changes
+
+- Новый раздел веба **«Подписки»** (`/subscriptions`) — только для суперадмина: пункта меню
+ у остальных нет, прямой URL отвечает 404. Суперадмин = `platform.admins` (helper
+ `isSuperadmin(db, user)` в core).
+- **Подписка**: провайдер (Claude Code / Codex / OpenCode), название, кто добавил, статус
+ (ожидает входа / активна / лимит до … / ошибка входа), сколько сессий на ней сейчас,
+ кнопка «Проверить» (короткий пробный запуск CLI).
+ - Claude Code — `claude setup-token` в tmux: ссылка → код → токен (как PEP-13), либо
+ вставить готовый токен.
+ - Codex — `codex login --device-auth` (подписка ChatGPT: ссылка + одноразовый код) или
+ API-ключ (`codex login --with-api-key`); у каждой подписки свой `CODEX_HOME`.
+ - OpenCode — новый провайдер раннера, подписка по API-ключу провайдера модели.
+ - Секреты — только зашифрованно (`PEPPA_SECRET`), не в логах.
+- **Пулы** — именованные наборы подписок (подписка может быть в нескольких пулах).
+ У проекта — пул по умолчанию («⋯ Настройки проекта», меняет только суперадмин).
+- **Раннер**: при старте берёт первую свободную активную подписку из выбранного набора
+ (подписки/пул из формы запуска, иначе пул проекта), провайдер сессии = провайдер
+ подписки; сессия запоминает подписку (видно в «Раннерах»), resume идёт на ней же.
+ Ротации при лимите нет — это PEP-39.
+- «Настройки → Claude» убирается; миграция переносит токены `users.claude_token_enc` в
+ подписки Claude и делает пул владельца пулом его проектов (поведение сессий не меняется).
+- Моки: `mock-claude setup-token` / `-p`, `mock-codex login` / `exec`, новый `mock-opencode`.
+
+## Capabilities
+
+### Modified Capabilities
+- `agent-credentials` — вместо токена Claude у пользователя: подписки, пулы, выбор
+ подписки раннером, раздел суперадмина.
+- `web-workspace` — запуск агента с выбором пула/подписок, подписка в «Раннерах».
+
+## Impact
+
+- БД: таблицы `subscriptions`, `subscription_pools`, `subscription_pool_members`; колонки
+ `projects.subscription_pool_id`, `sessions.subscription_id`, провайдер `opencode`.
+ Миграция данных токенов Claude. **На живой базе нужна `peppa db backup && peppa db migrate`.**
+- runner: `subscriptions.ts` (вход, проверка, выбор), `providers.ts` (OpenCode),
+ `sessions.ts`; `claude-auth.ts` теперь работает на подписку, а не на пользователя.
+- web: `/subscriptions`, меню, настройки проекта, форма запуска, «Раннеры», «Настройки».
diff --git a/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md b/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md
new file mode 100644
index 00000000..96a3d017
--- /dev/null
+++ b/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md
@@ -0,0 +1,110 @@
+# Spec Delta: agent-credentials
+
+## ADDED Requirements
+
+### Requirement: Раздел «Подписки» только для суперадмина
+Раздел «Подписки» SHALL быть виден и доступен только суперадмину (логин из
+`platform.admins`): у остальных пункта меню нет, `/subscriptions` отвечает 404, действия
+раздела отклоняются.
+
+#### Scenario: Пользователь без прав суперадмина
+- **GIVEN** пользователь «dana» не входит в `platform.admins`
+- **WHEN** он открывает Пеппу и затем `/subscriptions`
+- **THEN** пункта «Подписки» в меню нет, а `/subscriptions` отвечает 404
+
+#### Scenario: Суперадмин
+- **GIVEN** `platform.admins` = asel, admin
+- **WHEN** «asel» открывает Пеппу
+- **THEN** в меню есть «Подписки», страница показывает подписки и пулы
+
+### Requirement: Подписка агента
+Суперадмин SHALL добавлять подписки Claude Code, Codex и OpenCode. Подписка хранит
+провайдера, название, кто добавил, статус (ожидает входа / активна / лимит до … / ошибка
+входа) и показывает число сессий на ней сейчас. Секреты SHALL храниться только
+зашифрованно (или в закрытом каталоге входа CLI) и не показываться.
+
+#### Scenario: Суперадмин добавляет подписку Claude
+- **GIVEN** суперадмин открыл «Подписки»
+- **WHEN** он выбирает «+ Claude Code» с названием «Claude Max — asel», входит по ссылке и вставляет код
+- **THEN** подписка «Claude Max — asel» появляется в списке со статусом «активна», токен хранится зашифрованным
+
+#### Scenario: Неверный код Claude
+- **GIVEN** суперадмин начал вход новой подписки Claude
+- **WHEN** Claude не принимает вставленный код
+- **THEN** суперадмин видит ошибку, подписка не становится активной
+
+#### Scenario: Codex через ChatGPT
+- **GIVEN** суперадмин выбрал «+ Codex» и вход через ChatGPT
+- **WHEN** он открывает показанную ссылку и вводит показанный одноразовый код на своём устройстве
+- **THEN** подписка Codex становится активной, вход хранится в её собственном `CODEX_HOME`
+
+#### Scenario: OpenCode по ключу
+- **WHEN** суперадмин добавляет подписку OpenCode с ключом провайдера «anthropic»
+- **THEN** подписка активна, ключ хранится зашифрованным
+
+### Requirement: Проверка подписки
+Кнопка «Проверить» SHALL делать короткий пробный запуск CLI с этой подпиской и обновлять
+её статус.
+
+#### Scenario: Подписка упёрлась в лимит
+- **GIVEN** у подписки Claude исчерпан лимит
+- **WHEN** суперадмин нажимает «Проверить»
+- **THEN** статус подписки — «лимит до …»
+
+#### Scenario: Отозванный вход
+- **WHEN** пробный запуск завершился ошибкой авторизации
+- **THEN** статус подписки — «ошибка входа» с текстом ошибки без секретов
+
+### Requirement: Пулы подписок
+Суперадмин SHALL создавать пулы — именованные наборы подписок (подписка может быть в
+нескольких пулах) — и назначать проекту пул по умолчанию. Пул проекта меняет только
+суперадмин.
+
+#### Scenario: Пул для ротации
+- **GIVEN** есть две активные подписки Claude и одна Codex
+- **WHEN** суперадмин создаёт пул «Основной» из этих трёх подписок и назначает его проекту по умолчанию
+- **THEN** новые раннеры проекта стартуют на свободной подписке из этого пула
+
+#### Scenario: Не суперадмин меняет пул проекта
+- **GIVEN** «dana» — участник проекта, но не суперадмин
+- **WHEN** она пытается сменить пул проекта
+- **THEN** изменение отклонено
+
+### Requirement: Подписка сессии
+Раннер SHALL при старте брать первую свободную активную подписку из выбранного набора
+(отмеченные подписки или пул из формы запуска, иначе пул проекта) и запоминать её у сессии;
+провайдер сессии — провайдер подписки, процесс агента получает вход этой подписки. Resume
+SHALL идти на той же подписке. Без пула и выбора сессия запускается на входе машины.
+
+#### Scenario: Свободная подписка
+- **GIVEN** в пуле проекта подписки «A» и «B», на «A» уже работает сессия
+- **WHEN** запускается новый раннер проекта
+- **THEN** он стартует на подписке «B»
+
+#### Scenario: Нет активных подписок
+- **GIVEN** у всех подписок пула проекта статус «ошибка входа»
+- **WHEN** запускается новый раннер
+- **THEN** запуск отклонён с сообщением «Нет активных подписок»
+
+### Requirement: Перенос токена Claude из настроек
+Миграция SHALL переносить подключённые токены Claude пользователей (PEP-13) в подписки
+Claude и делать пул с этой подпиской пулом по умолчанию проектов владельца.
+
+#### Scenario: Был подключён Claude
+- **GIVEN** у «asel» в настройках был подключён Claude и он владелец проекта PEP
+- **WHEN** применяется миграция
+- **THEN** есть активная подписка «Claude — asel» с тем же токеном, у PEP пул «Claude — asel», а у пользователя токена больше нет
+
+## REMOVED Requirements
+
+### Requirement: Подключение Claude из веба
+**Reason**: вход Claude переехал в подписки суперадмина.
+**Migration**: токен переносится в подписку миграцией; новые — «Подписки → + Claude Code».
+
+### Requirement: Хранение и отключение
+**Reason**: заменено требованием «Подписка агента» (удаление подписки).
+**Migration**: удалить подписку в «Подписках».
+
+### Requirement: Токен в сессиях
+**Reason**: заменено требованием «Подписка сессии».
+**Migration**: миграция назначает проектам владельца пул с его подпиской.
diff --git a/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md b/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md
new file mode 100644
index 00000000..3cec17da
--- /dev/null
+++ b/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md
@@ -0,0 +1,18 @@
+# Spec Delta: web-workspace
+
+## ADDED Requirements
+
+### Requirement: Выбор подписок при запуске агента
+Форма «Запустить агента» SHALL давать суперадмину выбрать пул или отметить несколько
+подписок (по умолчанию — пул проекта); остальные запускают на пуле проекта. «Раннеры»
+SHALL показывать, на какой подписке работает сессия.
+
+#### Scenario: Выбор при запуске
+- **GIVEN** суперадмин на странице стори, есть подписки «Claude A», «Claude B», «Codex C»
+- **WHEN** он отмечает «Claude B» и «Codex C» и запускает агента
+- **THEN** раннер стартует на одной из них, и в «Раннерах» видно, на какой
+
+#### Scenario: Отмеченная подписка неактивна
+- **GIVEN** у отмеченной подписки статус «ошибка входа», других не отмечено
+- **WHEN** суперадмин запускает агента
+- **THEN** запуск отклонён с сообщением «Нет активных подписок»
diff --git a/openspec/changes/pep-67-subscriptions/tasks.md b/openspec/changes/pep-67-subscriptions/tasks.md
new file mode 100644
index 00000000..ead0113c
--- /dev/null
+++ b/openspec/changes/pep-67-subscriptions/tasks.md
@@ -0,0 +1,26 @@
+# Tasks: PEP-67
+
+## 1. Данные
+- [ ] 1.1 Схема: subscriptions, subscription_pools, subscription_pool_members, projects.subscription_pool_id, sessions.subscription_id, provider opencode
+- [ ] 1.2 Миграция (drizzle-kit generate) + перенос users.claude_token_enc в подписки и пулы
+- [ ] 1.3 core: isSuperadmin, CRUD подписок и пулов, пул проекта, выбор подписки, claudeTokenForProject из пула
+
+## 2. Раннер
+- [ ] 2.1 Вход: Claude setup-token на подписку, ручной токен; Codex device auth и API-ключ (CODEX_HOME); OpenCode ключ
+- [ ] 2.2 «Проверить» (пробный запуск) и статусы
+- [ ] 2.3 Провайдер OpenCode (providers.ts, opencode.json, env)
+- [ ] 2.4 startSession/resumeSession: выбор подписки, env подписки, sessions.subscription_id
+
+## 3. Моки
+- [ ] 3.1 mock-claude -p, mock-codex login/exec, mock-opencode
+
+## 4. Веб
+- [ ] 4.1 Меню «Подписки» только суперадмину, /subscriptions (404 остальным)
+- [ ] 4.2 Страница подписок: список, добавление трёх провайдеров, проверка, удаление, пулы
+- [ ] 4.3 Настройки проекта: пул по умолчанию; форма запуска: пул/подписки; «Раннеры»: подписка
+- [ ] 4.4 Убрать «Настройки → Claude», обновить Помощь
+
+## 5. Тесты и документация
+- [ ] 5.1 testkit: subscriptions.test.ts (сценарии спеки), перенос claude-auth.test.ts, миграция токенов
+- [ ] 5.2 AGENTS.md
+- [ ] 5.3 pnpm run ci зелёный
--
2.45.2
From 9054774f96372618d714d8ff26fedf3d386bc65c 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:23:46 +0500
Subject: [PATCH 034/518] PEP-67: subscriptions and pools in core/db, sign-in
and checks in runner, OpenCode provider, mocks, tests
Co-Authored-By: Claude Opus 5.5
---
.../changes/pep-67-subscriptions/design.md | 2 +-
.../changes/pep-67-subscriptions/proposal.md | 2 +-
packages/cli/src/index.ts | 2 +-
packages/core/src/index.ts | 1 +
packages/core/src/sessions.ts | 16 +-
packages/core/src/subscriptions.ts | 270 ++
packages/core/src/users.ts | 14 -
packages/db/migrations/0003_subscriptions.sql | 54 +
.../db/migrations/meta/0003_snapshot.json | 2570 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 57 +-
packages/runner/src/claude-auth.ts | 90 -
packages/runner/src/index.ts | 3 +-
packages/runner/src/providers.ts | 43 +-
packages/runner/src/sessions.ts | 26 +-
packages/runner/src/subscription-login.ts | 242 ++
packages/runner/src/subscriptions.ts | 128 +
packages/runner/src/triage.ts | 2 +-
packages/testkit/bin/mock-opencode | 4 +
packages/testkit/src/mock-agent.ts | 96 +-
packages/testkit/test/claude-auth.test.ts | 54 -
packages/testkit/test/helpers.ts | 5 +-
packages/testkit/test/subscriptions.test.ts | 253 ++
23 files changed, 3748 insertions(+), 193 deletions(-)
create mode 100644 packages/core/src/subscriptions.ts
create mode 100644 packages/db/migrations/0003_subscriptions.sql
create mode 100644 packages/db/migrations/meta/0003_snapshot.json
delete mode 100644 packages/runner/src/claude-auth.ts
create mode 100644 packages/runner/src/subscription-login.ts
create mode 100644 packages/runner/src/subscriptions.ts
create mode 100755 packages/testkit/bin/mock-opencode
delete mode 100644 packages/testkit/test/claude-auth.test.ts
create mode 100644 packages/testkit/test/subscriptions.test.ts
diff --git a/openspec/changes/pep-67-subscriptions/design.md b/openspec/changes/pep-67-subscriptions/design.md
index 824bce3c..df14cddb 100644
--- a/openspec/changes/pep-67-subscriptions/design.md
+++ b/openspec/changes/pep-67-subscriptions/design.md
@@ -46,7 +46,7 @@ OpenCode — подписка только по API-ключу провайде
## Вход
Общий механизм `runner/subscriptions.ts` поверх tmux (`peppa-auth-sub`), состояние
входа — `settings` `subscription.login:` (10 мин):
-- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` переписан на подписку):
+- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` → `subscription-login.ts`, на подписку):
ссылка → код в форму → токен из вывода → `secret_enc`, статус `active`, tmux убивается
(стирает токен из буфера). Либо вставить готовый токен `sk-ant-oat…` руками.
- Codex device auth: `codex login --device-auth` с `CODEX_HOME` подписки → со страницы
diff --git a/openspec/changes/pep-67-subscriptions/proposal.md b/openspec/changes/pep-67-subscriptions/proposal.md
index 41b8776b..2fe8d503 100644
--- a/openspec/changes/pep-67-subscriptions/proposal.md
+++ b/openspec/changes/pep-67-subscriptions/proposal.md
@@ -46,5 +46,5 @@
`projects.subscription_pool_id`, `sessions.subscription_id`, провайдер `opencode`.
Миграция данных токенов Claude. **На живой базе нужна `peppa db backup && peppa db migrate`.**
- runner: `subscriptions.ts` (вход, проверка, выбор), `providers.ts` (OpenCode),
- `sessions.ts`; `claude-auth.ts` теперь работает на подписку, а не на пользователя.
+ `sessions.ts`; `claude-auth.ts` → `subscription-login.ts`: вход на подписку, а не на пользователя.
- web: `/subscriptions`, меню, настройки проекта, форма запуска, «Раннеры», «Настройки».
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 660d5184..a79cf379 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -73,7 +73,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa task set -s
peppa q list [KEY]
peppa q answer (delivered into the session's terminal)
- peppa session start [--provider claude|codex] [-p ] [--mode ] [--model ]
+ peppa session start [--provider claude|codex|opencode] [-p ] [--mode ] [--model ]
peppa session list [--all]
peppa session send
peppa session attach
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5182e36a..840698bf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -20,3 +20,4 @@ export * from "./ci.ts";
export * from "./egov.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
+export * from "./subscriptions.ts";
diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts
index ad19e314..6be52088 100644
--- a/packages/core/src/sessions.ts
+++ b/packages/core/src/sessions.ts
@@ -1,4 +1,4 @@
-import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
+import { events, projects, questions, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
@@ -14,11 +14,13 @@ export interface SessionView extends Session {
projectKey: string;
taskKey: string | null;
taskTitle: string | null;
+ /** PEP-67: name of the subscription the session runs on. */
+ subscriptionName: string | null;
}
export async function createSession(
db: Db,
- s: { projectId: number; taskId?: number; provider?: Session["provider"] },
+ s: { projectId: number; taskId?: number; provider?: Session["provider"]; subscriptionId?: number | null },
): Promise {
// tmux name needs the id, so insert with a unique placeholder first.
const [row] = await db
@@ -69,7 +71,7 @@ export async function listUserSessions(db: Db, userId: number, opts: { filter?:
export async function updateSession(
db: Db,
id: number,
- patch: Partial>,
+ patch: Partial>,
): Promise {
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
if (!row) throw new PeppaError(`Session #${id} not found`);
@@ -160,18 +162,20 @@ export async function raiseSessionQuestion(
function sessionQuery(db: Db) {
return db
- .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title })
+ .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, subscriptionName: subscriptions.name })
.from(sessions)
.innerJoin(projects, eq(sessions.projectId, projects.id))
- .leftJoin(tasks, eq(sessions.taskId, tasks.id));
+ .leftJoin(tasks, eq(sessions.taskId, tasks.id))
+ .leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id));
}
-function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView {
+function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; subscriptionName: string | null }): SessionView {
return {
...r.session,
projectKey: r.projectKey,
taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null,
taskTitle: r.taskTitle,
+ subscriptionName: r.subscriptionName,
};
}
diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts
new file mode 100644
index 00000000..5b8d8e45
--- /dev/null
+++ b/packages/core/src/subscriptions.ts
@@ -0,0 +1,270 @@
+// Agent subscriptions and pools (PEP-67): superadmins keep the accounts agents run on
+// (Claude Code, Codex, OpenCode) and group them into pools; a runner takes the first free
+// active subscription of the chosen set. Rotation on limits and fairness — PEP-39.
+import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
+import { and, asc, count, eq, inArray, notInArray } from "drizzle-orm";
+import { decrypt, encrypt } from "./crypto.ts";
+import { PeppaError } from "./errors.ts";
+import { isSuperadmin } from "./monitor.ts";
+import type { Project } from "./projects.ts";
+import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
+import type { User } from "./users.ts";
+
+export type Subscription = typeof subscriptions.$inferSelect;
+export type SubscriptionProvider = Subscription["provider"];
+export type SubscriptionStatus = Subscription["status"];
+export type SubscriptionPool = typeof subscriptionPools.$inferSelect;
+
+export const PROVIDER_NAMES: Record = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" };
+/** OpenCode model providers a key can belong to, and the env variable it goes into. */
+export const OPENCODE_KEY_ENV: Record = {
+ anthropic: "ANTHROPIC_API_KEY",
+ openai: "OPENAI_API_KEY",
+ openrouter: "OPENROUTER_API_KEY",
+};
+
+export interface SubscriptionView extends Subscription {
+ createdByLogin: string | null;
+ activeSessions: number;
+ poolIds: number[];
+}
+
+export interface PoolView extends SubscriptionPool {
+ subscriptionIds: number[];
+ projectKeys: string[];
+}
+
+/** Throws "not found" unless the user is a superadmin: the section doesn't exist for others. */
+export async function requireSuperadmin(db: Db, user: Pick | null | undefined): Promise {
+ if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
+}
+
+// ── subscriptions ────────────────────────────────────────────────────────────────
+
+async function activeSessionCounts(db: Db): Promise> {
+ const rows = await db
+ .select({ id: sessions.subscriptionId, n: count() })
+ .from(sessions)
+ .where(notInArray(sessions.status, FINISHED_SESSION_STATUSES))
+ .groupBy(sessions.subscriptionId);
+ return new Map(rows.filter((r) => r.id != null).map((r) => [r.id!, r.n]));
+}
+
+export async function listSubscriptions(db: Db): Promise {
+ const rows = await db
+ .select({ s: subscriptions, login: users.login })
+ .from(subscriptions)
+ .leftJoin(users, eq(subscriptions.createdBy, users.id))
+ .orderBy(asc(subscriptions.id));
+ const counts = await activeSessionCounts(db);
+ const members = await db.select().from(subscriptionPoolMembers);
+ return rows.map((r) => ({
+ ...r.s,
+ createdByLogin: r.login,
+ activeSessions: counts.get(r.s.id) ?? 0,
+ poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId),
+ }));
+}
+
+export async function getSubscription(db: Db, id: number): Promise {
+ const [row] = await db.select().from(subscriptions).where(eq(subscriptions.id, id));
+ if (!row) throw new PeppaError(`Подписка #${id} не найдена`);
+ return row;
+}
+
+export async function createSubscription(
+ db: Db,
+ s: { provider: SubscriptionProvider; name: string; authKind: Subscription["authKind"]; secret?: string | null; keyProvider?: string | null; createdBy?: number | null },
+): Promise {
+ const name = s.name.trim();
+ if (!name) throw new PeppaError("Нужно название подписки");
+ if (s.provider === "opencode" && !(s.keyProvider && s.keyProvider in OPENCODE_KEY_ENV)) throw new PeppaError("Выберите провайдера ключа OpenCode");
+ const [row] = await db
+ .insert(subscriptions)
+ .values({
+ provider: s.provider,
+ name,
+ authKind: s.authKind,
+ secretEnc: s.secret ? encrypt(s.secret) : null,
+ keyProvider: s.keyProvider ?? null,
+ createdBy: s.createdBy ?? null,
+ })
+ .returning();
+ return row!;
+}
+
+export async function updateSubscription(
+ db: Db,
+ id: number,
+ patch: Partial> & { secret?: string | null },
+): Promise {
+ const { secret, ...rest } = patch;
+ const set: Partial = { ...rest };
+ if (secret !== undefined) set.secretEnc = secret ? encrypt(secret) : null;
+ if (patch.status === "active") {
+ set.limitedUntil = null;
+ set.lastError = null;
+ const cur = await getSubscription(db, id);
+ if (!cur.activatedAt) set.activatedAt = new Date();
+ }
+ const [row] = await db.update(subscriptions).set(set).where(eq(subscriptions.id, id)).returning();
+ if (!row) throw new PeppaError(`Подписка #${id} не найдена`);
+ return row;
+}
+
+/** Removes a subscription; its sessions keep running but forget it. The runner wipes its login dir. */
+export async function deleteSubscription(db: Db, id: number): Promise {
+ db.transaction((tx) => {
+ tx.update(sessions).set({ subscriptionId: null }).where(eq(sessions.subscriptionId, id)).run();
+ tx.delete(subscriptions).where(eq(subscriptions.id, id)).run();
+ });
+}
+
+/** The decrypted secret (Claude token / OpenCode key); null if the subscription has none. */
+export function subscriptionSecret(s: Pick): string | null {
+ return s.secretEnc ? decrypt(s.secretEnc) : null;
+}
+
+/** Active now: `active`, or `limited` whose reset time has passed. */
+export function isUsable(s: Pick, now = new Date()): boolean {
+ return s.status === "active" || (s.status === "limited" && !!s.limitedUntil && s.limitedUntil <= now);
+}
+
+// ── pools ────────────────────────────────────────────────────────────────────────
+
+export async function listPools(db: Db): Promise {
+ const pools = await db.select().from(subscriptionPools).orderBy(asc(subscriptionPools.name));
+ const members = await db.select().from(subscriptionPoolMembers);
+ const used = await db.select({ key: projects.key, poolId: projects.subscriptionPoolId }).from(projects);
+ return pools.map((p) => ({
+ ...p,
+ subscriptionIds: members.filter((m) => m.poolId === p.id).map((m) => m.subscriptionId).sort((a, b) => a - b),
+ projectKeys: used.filter((u) => u.poolId === p.id).map((u) => u.key),
+ }));
+}
+
+export async function getPool(db: Db, id: number): Promise {
+ const [row] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id));
+ if (!row) throw new PeppaError(`Пул #${id} не найден`);
+ return row;
+}
+
+async function checkSubscriptionIds(db: Db, ids: number[]): Promise {
+ const uniq = [...new Set(ids.filter((n) => Number.isInteger(n) && n > 0))];
+ if (!uniq.length) return [];
+ const found = await db.select({ id: subscriptions.id }).from(subscriptions).where(inArray(subscriptions.id, uniq));
+ if (found.length !== uniq.length) throw new PeppaError("Некоторых подписок уже нет");
+ return uniq;
+}
+
+export async function createPool(db: Db, p: { name: string; subscriptionIds: number[]; createdBy?: number | null }): Promise {
+ const name = p.name.trim();
+ if (!name) throw new PeppaError("Нужно название пула");
+ const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
+ if (dup) throw new PeppaError(`Пул «${name}» уже есть`);
+ const ids = await checkSubscriptionIds(db, p.subscriptionIds);
+ return db.transaction((tx) => {
+ const row = tx.insert(subscriptionPools).values({ name, createdBy: p.createdBy ?? null }).returning().get();
+ for (const id of ids) tx.insert(subscriptionPoolMembers).values({ poolId: row.id, subscriptionId: id }).run();
+ return row;
+ });
+}
+
+export async function updatePool(db: Db, id: number, p: { name?: string; subscriptionIds?: number[] }): Promise {
+ await getPool(db, id);
+ const ids = p.subscriptionIds ? await checkSubscriptionIds(db, p.subscriptionIds) : null;
+ const name = p.name?.trim();
+ if (name) {
+ const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
+ if (dup && dup.id !== id) throw new PeppaError(`Пул «${name}» уже есть`);
+ }
+ db.transaction((tx) => {
+ if (name) tx.update(subscriptionPools).set({ name }).where(eq(subscriptionPools.id, id)).run();
+ if (ids) {
+ tx.delete(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.poolId, id)).run();
+ for (const sid of ids) tx.insert(subscriptionPoolMembers).values({ poolId: id, subscriptionId: sid }).run();
+ }
+ });
+}
+
+/** Deletes a pool; projects that used it as default go back to "no pool". */
+export async function deletePool(db: Db, id: number): Promise {
+ db.transaction((tx) => {
+ tx.update(projects).set({ subscriptionPoolId: null }).where(eq(projects.subscriptionPoolId, id)).run();
+ tx.delete(subscriptionPools).where(eq(subscriptionPools.id, id)).run();
+ });
+}
+
+export async function setProjectPool(db: Db, projectId: number, poolId: number | null): Promise {
+ if (poolId != null) await getPool(db, poolId);
+ await db.update(projects).set({ subscriptionPoolId: poolId }).where(eq(projects.id, projectId));
+}
+
+async function poolSubscriptions(db: Db, poolId: number): Promise {
+ const rows = await db
+ .select({ s: subscriptions })
+ .from(subscriptionPoolMembers)
+ .innerJoin(subscriptions, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
+ .where(eq(subscriptionPoolMembers.poolId, poolId))
+ .orderBy(asc(subscriptions.id));
+ return rows.map((r) => r.s);
+}
+
+// ── choosing a subscription for a runner ─────────────────────────────────────────
+
+export interface PickOptions {
+ projectId: number;
+ /** Subscriptions ticked in the launch form (multiple choice). */
+ subscriptionIds?: number[];
+ /** A pool chosen in the launch form instead of the project's default. */
+ poolId?: number | null;
+ provider?: SubscriptionProvider;
+ now?: Date;
+}
+
+/**
+ * The subscription a new runner starts on: the first free usable one of the chosen set
+ * (ticked subscriptions, else the chosen pool, else the project's pool), by id; if all are
+ * busy — the least busy one (the runner never waits; fairness is PEP-39). Null when nothing
+ * is chosen and the project has no pool: the agent runs on this machine's own login.
+ */
+export async function pickSubscription(db: Db, o: PickOptions): Promise {
+ let candidates: Subscription[];
+ let source: string;
+ if (o.subscriptionIds?.length) {
+ candidates = await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)).orderBy(asc(subscriptions.id));
+ source = "отмеченных";
+ } else {
+ const poolId = o.poolId ?? (await db.select({ id: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, o.projectId)))[0]?.id;
+ if (poolId == null) return null;
+ const pool = await getPool(db, poolId);
+ candidates = await poolSubscriptions(db, poolId);
+ source = `пула «${pool.name}»`;
+ }
+ if (o.provider) {
+ candidates = candidates.filter((s) => s.provider === o.provider);
+ if (!candidates.length) throw new PeppaError(`Среди ${source} подписок нет подписок ${PROVIDER_NAMES[o.provider]}`);
+ }
+ const usable = candidates.filter((s) => isUsable(s, o.now));
+ if (!usable.length) throw new PeppaError(`Нет активных подписок среди ${source}${candidates.length ? "" : " (пул пуст)"} — проверьте их в «Подписках»`);
+ const counts = await activeSessionCounts(db);
+ return usable.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best));
+}
+
+/** Claude token for one-off calls on behalf of a project (incident triage): the project's pool. */
+export async function claudeTokenForProject(db: Db, project: Pick): Promise {
+ const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, project.id));
+ if (p?.poolId == null) return null;
+ const s = (await poolSubscriptions(db, p.poolId)).find((x) => x.provider === "claude" && isUsable(x) && x.secretEnc);
+ return s ? subscriptionSecret(s) : null;
+}
+
+/** Pool name of a project (for the project settings), or null. */
+export async function projectPool(db: Db, projectId: number): Promise {
+ const [row] = await db
+ .select({ pool: subscriptionPools })
+ .from(projects)
+ .innerJoin(subscriptionPools, eq(projects.subscriptionPoolId, subscriptionPools.id))
+ .where(and(eq(projects.id, projectId)));
+ return row?.pool ?? null;
+}
diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts
index 3eb7cb18..f23b25a6 100644
--- a/packages/core/src/users.ts
+++ b/packages/core/src/users.ts
@@ -179,20 +179,6 @@ export async function consumeLoginLink(db: Db, code: string): Promise {
- await db
- .update(users)
- .set({ claudeTokenEnc: token ? encrypt(token) : null, claudeTokenSetAt: token ? new Date() : null })
- .where(eq(users.id, userId));
-}
-
-/** The decrypted Claude token of a project's owner, if they connected Claude. */
-export async function claudeTokenForProject(db: Db, project: Pick): Promise {
- if (!project.ownerId) return null;
- const u = await getUser(db, project.ownerId);
- return u?.claudeTokenEnc ? decrypt(u.claudeTokenEnc) : null;
-}
-
export async function listUsers(db: Db): Promise {
return db.select().from(users).orderBy(asc(users.login));
}
diff --git a/packages/db/migrations/0003_subscriptions.sql b/packages/db/migrations/0003_subscriptions.sql
new file mode 100644
index 00000000..246d1b12
--- /dev/null
+++ b/packages/db/migrations/0003_subscriptions.sql
@@ -0,0 +1,54 @@
+CREATE TABLE `subscription_pool_members` (
+ `pool_id` integer NOT NULL,
+ `subscription_id` integer NOT NULL,
+ PRIMARY KEY(`pool_id`, `subscription_id`),
+ FOREIGN KEY (`pool_id`) REFERENCES `subscription_pools`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `subscription_pools` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `name` text NOT NULL,
+ `created_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `subscription_pools_name_unique` ON `subscription_pools` (`name`);--> statement-breakpoint
+CREATE TABLE `subscriptions` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `provider` text NOT NULL,
+ `name` text NOT NULL,
+ `auth_kind` text NOT NULL,
+ `secret_enc` text,
+ `key_provider` text,
+ `status` text DEFAULT 'pending' NOT NULL,
+ `limited_until` integer,
+ `last_error` text,
+ `checked_at` integer,
+ `activated_at` integer,
+ `created_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+ALTER TABLE `projects` ADD `subscription_pool_id` integer REFERENCES subscription_pools(id) ON DELETE set null;--> statement-breakpoint
+ALTER TABLE `sessions` ADD `subscription_id` integer REFERENCES subscriptions(id) ON DELETE set null;--> statement-breakpoint
+-- PEP-67 data: the PEP-13 Claude token of every user becomes a subscription «Claude — »
+-- (same ciphertext: same PEPPA_SECRET key), a pool of the same name, and the default pool of the
+-- projects that user owns — sessions keep running on the same account. Then the token is cleared.
+INSERT INTO `subscriptions` (`provider`, `name`, `auth_kind`, `secret_enc`, `status`, `activated_at`, `created_by`)
+SELECT 'claude', 'Claude — ' || `login`, 'oauth', `claude_token_enc`, 'active', coalesce(`claude_token_set_at`, cast(unixepoch('subsec') * 1000 as integer)), `id`
+FROM `users` WHERE `claude_token_enc` IS NOT NULL;--> statement-breakpoint
+INSERT OR IGNORE INTO `subscription_pools` (`name`, `created_by`)
+SELECT 'Claude — ' || `login`, `id` FROM `users` WHERE `claude_token_enc` IS NOT NULL;--> statement-breakpoint
+INSERT OR IGNORE INTO `subscription_pool_members` (`pool_id`, `subscription_id`)
+SELECT p.`id`, s.`id` FROM `users` u
+JOIN `subscription_pools` p ON p.`name` = 'Claude — ' || u.`login`
+JOIN `subscriptions` s ON s.`name` = 'Claude — ' || u.`login` AND s.`created_by` = u.`id` AND s.`provider` = 'claude'
+WHERE u.`claude_token_enc` IS NOT NULL;--> statement-breakpoint
+UPDATE `projects` SET `subscription_pool_id` = (
+ SELECT p.`id` FROM `users` u JOIN `subscription_pools` p ON p.`name` = 'Claude — ' || u.`login`
+ WHERE u.`id` = `projects`.`owner_id` AND u.`claude_token_enc` IS NOT NULL
+) WHERE `subscription_pool_id` IS NULL AND `owner_id` IN (SELECT `id` FROM `users` WHERE `claude_token_enc` IS NOT NULL);--> statement-breakpoint
+UPDATE `users` SET `claude_token_enc` = NULL, `claude_token_set_at` = NULL WHERE `claude_token_enc` IS NOT NULL;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json
new file mode 100644
index 00000000..ac8894f5
--- /dev/null
+++ b/packages/db/migrations/meta/0003_snapshot.json
@@ -0,0 +1,2570 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "922324fb-4f7c-4dd7-9cb7-7cb03780a882",
+ "prevId": "8c480919-f0f0-4006-b448-49eff5f43062",
+ "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
+ },
+ "subscription_pool_id": {
+ "name": "subscription_pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "projects_subscription_pool_id_subscription_pools_id_fk": {
+ "name": "projects_subscription_pool_id_subscription_pools_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "subscription_pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "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'"
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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"
+ },
+ "sessions_subscription_id_subscriptions_id_fk": {
+ "name": "sessions_subscription_id_subscriptions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pool_members": {
+ "name": "subscription_pool_members",
+ "columns": {
+ "pool_id": {
+ "name": "pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscription_pool_members_pool_id_subscription_pools_id_fk": {
+ "name": "subscription_pool_members_pool_id_subscription_pools_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subscription_pool_members_subscription_id_subscriptions_id_fk": {
+ "name": "subscription_pool_members_subscription_id_subscriptions_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subscription_pool_members_pool_id_subscription_id_pk": {
+ "columns": [
+ "pool_id",
+ "subscription_id"
+ ],
+ "name": "subscription_pool_members_pool_id_subscription_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pools": {
+ "name": "subscription_pools",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "subscription_pools_name_unique": {
+ "name": "subscription_pools_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "subscription_pools_created_by_users_id_fk": {
+ "name": "subscription_pools_created_by_users_id_fk",
+ "tableFrom": "subscription_pools",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth_kind": {
+ "name": "auth_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret_enc": {
+ "name": "secret_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "key_provider": {
+ "name": "key_provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "limited_until": {
+ "name": "limited_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "activated_at": {
+ "name": "activated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscriptions_created_by_users_id_fk": {
+ "name": "subscriptions_created_by_users_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "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 5d4b60ba..bee3921a 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -22,6 +22,13 @@
"when": 1794608096959,
"tag": "0002_local_users",
"breakpoints": true
+ },
+ {
+ "idx": 3,
+ "version": "6",
+ "when": 1794608984819,
+ "tag": "0003_subscriptions",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index d2efad7a..a7e88503 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -1,6 +1,6 @@
import { relations } from "drizzle-orm";
import { sql } from "drizzle-orm";
-import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+import { integer, primaryKey, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
// 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.
@@ -22,8 +22,8 @@ export const users = sqliteTable("users", {
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.
+ // Deprecated (PEP-67): the PEP-13 Claude token moved to `subscriptions`; the migration
+ // copies it there and clears these columns. Not read by the code any more.
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.
@@ -58,6 +58,8 @@ export const projects = sqliteTable("projects", {
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),
+ // PEP-67: default subscription pool for the project's runners (set by a superadmin).
+ subscriptionPoolId: integer("subscription_pool_id").references((): AnySQLiteColumn => subscriptionPools.id, { onDelete: "set null" }),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
@@ -187,13 +189,58 @@ export const sessionStatus = { enumValues: [
"failed",
] as const };
-/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
+export const agentProviders = { enumValues: ["claude", "codex", "opencode"] as const };
+
+/**
+ * PEP-67: an agent subscription (Claude Code / Codex / OpenCode) managed by superadmins.
+ * Claude: OAuth token from `claude setup-token` in `secret_enc`; Codex: the login lives in
+ * its own CODEX_HOME ($PEPPA_HOME/subscriptions/s/codex); OpenCode: a model provider
+ * API key in `secret_enc`. Secrets are AES-256-GCM encrypted with PEPPA_SECRET.
+ */
+export const subscriptions = sqliteTable("subscriptions", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ provider: text("provider", { enum: agentProviders.enumValues }).notNull(),
+ name: text("name").notNull(),
+ authKind: text("auth_kind", { enum: ["oauth", "api_key", "device"] }).notNull(),
+ secretEnc: text("secret_enc"),
+ // OpenCode: which model provider the key belongs to (anthropic | openai | openrouter).
+ keyProvider: text("key_provider"),
+ status: text("status", { enum: ["pending", "active", "limited", "auth_error"] }).notNull().default("pending"),
+ limitedUntil: integer("limited_until", { mode: "timestamp_ms" }),
+ lastError: text("last_error"),
+ checkedAt: integer("checked_at", { mode: "timestamp_ms" }),
+ // Became active at least once (a cancelled first login deletes the row).
+ activatedAt: integer("activated_at", { mode: "timestamp_ms" }),
+ createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
+ createdAt: createdAt(),
+});
+
+/** PEP-67: a named set of subscriptions runners take from (rotation within it — PEP-39). */
+export const subscriptionPools = sqliteTable("subscription_pools", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ name: text("name").notNull().unique(),
+ createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
+ createdAt: createdAt(),
+});
+
+export const subscriptionPoolMembers = sqliteTable(
+ "subscription_pool_members",
+ {
+ poolId: integer("pool_id").notNull().references(() => subscriptionPools.id, { onDelete: "cascade" }),
+ subscriptionId: integer("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }),
+ },
+ (t) => [primaryKey({ columns: [t.poolId, t.subscriptionId] })],
+);
+
+/** An agent CLI session (Claude Code, Codex or OpenCode) 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"),
+ provider: text("provider", { enum: agentProviders.enumValues }).notNull().default("claude"),
+ // PEP-67: the subscription the session runs on (null = this machine's own login).
+ subscriptionId: integer("subscription_id").references(() => subscriptions.id, { onDelete: "set null" }),
// 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.
diff --git a/packages/runner/src/claude-auth.ts b/packages/runner/src/claude-auth.ts
deleted file mode 100644
index 8221df0e..00000000
--- a/packages/runner/src/claude-auth.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-// "Connect Claude" from the web: runs `claude setup-token` on this machine in a tmux
-// session, hands the sign-in URL to the user, types back the code they paste into the
-// web form, and stores the resulting long-lived token (encrypted) on the user.
-import { homedir } from "node:os";
-import { deleteSetting, getSetting, PeppaError, setClaudeToken, setSetting } from "@peppa/core";
-import type { Db } from "@peppa/db";
-import * as tmux from "./tmux.ts";
-
-const SETUP_TTL_MS = 10 * 60_000;
-const URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/;
-const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/;
-const ERROR_RE = /(error|invalid|failed|expired)/i;
-
-const sessionName = (userId: number) => `peppa-auth-u${userId}`;
-const settingKey = (userId: number) => `claude.setup.u${userId}`;
-const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
-
-export interface ClaudeSetup {
- url: string;
- startedAt: number;
-}
-
-/** Pending setup of this user (null if none or expired). */
-export async function pendingClaudeSetup(db: Db, userId: number): Promise {
- const s = await getSetting(db, settingKey(userId));
- if (!s) return null;
- if (Date.now() - s.startedAt > SETUP_TTL_MS || !(await tmux.hasSession(sessionName(userId)))) {
- await cancelClaudeSetup(db, userId);
- return null;
- }
- return s;
-}
-
-export async function cancelClaudeSetup(db: Db, userId: number): Promise {
- await deleteSetting(db, settingKey(userId));
- if (await tmux.hasSession(sessionName(userId))) await tmux.killSession(sessionName(userId)).catch(() => {});
-}
-
-/** Starts `claude setup-token` and returns the sign-in URL to show the user. */
-export async function startClaudeSetup(db: Db, userId: number): Promise {
- await cancelClaudeSetup(db, userId);
- await tmux.newSession({
- name: sessionName(userId),
- cwd: homedir(),
- command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`,
- env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine
- width: 1000,
- });
- for (let i = 0; i < 60; i++) {
- await sleep(500);
- const url = URL_RE.exec(await tmux.capturePane(sessionName(userId)))?.[0];
- if (url) {
- const setup = { url, startedAt: Date.now() };
- await setSetting(db, settingKey(userId), setup);
- return setup;
- }
- }
- const tail = await tmux.capturePane(sessionName(userId)).catch(() => "");
- await cancelClaudeSetup(db, userId);
- throw new PeppaError(`claude setup-token не показал ссылку входа${tail.trim() ? `: ${tail.trim().split("\n").slice(-3).join(" ")}` : ""}`);
-}
-
-/** Types the user's code into setup-token and stores the token it prints. */
-export async function finishClaudeSetup(db: Db, userId: number, code: string): Promise {
- const c = code.trim();
- if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов");
- if (!(await pendingClaudeSetup(db, userId))) throw new PeppaError("Подключение не начато или истекло — нажмите «Подключить Claude» ещё раз");
- const name = sessionName(userId);
- const before = await tmux.capturePane(name);
- await tmux.sendText(name, c);
- for (let i = 0; i < 60; i++) {
- await sleep(500);
- const screen = await tmux.capturePane(name, 200);
- const token = TOKEN_RE.exec(screen)?.[0];
- if (token) {
- await setClaudeToken(db, userId, token);
- await cancelClaudeSetup(db, userId); // also wipes the token from the tmux scrollback
- return;
- }
- const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length);
- const dead = (await tmux.paneState(name)).dead;
- if (dead || ERROR_RE.test(after)) {
- const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" ");
- await cancelClaudeSetup(db, userId);
- throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`);
- }
- }
- await cancelClaudeSetup(db, userId);
- throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново.");
-}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index ec96a83e..3112ece5 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -6,7 +6,8 @@ export * from "./run-settings.ts";
export * from "./providers.ts";
export * from "./provision.ts";
export * from "./flow.ts";
-export * from "./claude-auth.ts";
+export * from "./subscription-login.ts";
+export * from "./subscriptions.ts";
export * from "./share.ts";
export * from "./limits.ts";
export * from "./monitor.ts";
diff --git a/packages/runner/src/providers.ts b/packages/runner/src/providers.ts
index 35ce0cce..1219278c 100644
--- a/packages/runner/src/providers.ts
+++ b/packages/runner/src/providers.ts
@@ -1,11 +1,12 @@
-import { dirname, resolve } from "node:path";
+import { writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { Session } from "@peppa/core";
import { peppaRoot } from "@peppa/shared";
-import { writeRunRules, writeRunSettings } from "./run-settings.ts";
+import { runDir, writeRunRules, writeRunSettings } from "./run-settings.ts";
export type Provider = Session["provider"];
-export const PROVIDERS: Provider[] = ["claude", "codex"];
+export const PROVIDERS: Provider[] = ["claude", "codex", "opencode"];
// PEPPA_ROOT first: inside a Next.js build import.meta.url points into .next/.
const ROOT = () => peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."));
@@ -25,7 +26,12 @@ export interface LaunchContext {
/** argv for one run of the agent CLI (executable first). */
export function buildCommand(provider: Provider, c: LaunchContext): string[] {
- return provider === "codex" ? codexCommand(c) : claudeCommand(c);
+ return provider === "codex" ? codexCommand(c) : provider === "opencode" ? opencodeCommand(c) : claudeCommand(c);
+}
+
+/** Extra environment the provider's CLI needs for this run (OpenCode reads its config from a file). */
+export function providerEnv(provider: Provider, c: Pick): Record {
+ return provider === "opencode" ? { OPENCODE_CONFIG: join(runDir(c.sessionId, c.generation), "opencode.json") } : {};
}
function claudeCommand(c: LaunchContext): string[] {
@@ -69,3 +75,32 @@ function codexCommand(c: LaunchContext): string[] {
c.prompt,
];
}
+
+/**
+ * OpenCode (PEP-67): TUI in tmux; rules and the peppa MCP server come from a generated
+ * opencode.json (OPENCODE_CONFIG, see providerEnv). It has no Claude-style hooks — the
+ * watchdog follows the process (alive, dead, stalled); hooks via an OpenCode plugin later.
+ */
+function opencodeCommand(c: LaunchContext): string[] {
+ const dir = runDir(c.sessionId, c.generation);
+ writeFileSync(
+ join(dir, "opencode.json"),
+ JSON.stringify(
+ {
+ $schema: "https://opencode.ai/config.json",
+ instructions: [writeRunRules(c.sessionId, c.generation, c.rules)],
+ mcp: { peppa: { type: "local", command: [MCP_BIN()], enabled: true } },
+ },
+ null,
+ 2,
+ ),
+ );
+ return [
+ process.env.PEPPA_OPENCODE_BIN ?? "opencode",
+ c.cwd,
+ ...(c.model ? ["--model", c.model] : []),
+ ...(c.resume ? ["--session", c.resume] : []),
+ "--prompt",
+ c.prompt,
+ ];
+}
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 8e999444..7668e4df 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -2,7 +2,8 @@ import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
answerQuestion,
- claudeTokenForProject,
+ getSubscription,
+ pickSubscription,
createSession,
expireSessionQuestions,
getSession,
@@ -20,7 +21,8 @@ import { projects, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { loadEnv } from "@peppa/shared";
import { trustWorkspace } from "./claude-config.ts";
-import { buildCommand, type Provider } from "./providers.ts";
+import { buildCommand, providerEnv, type Provider } from "./providers.ts";
+import { subscriptionEnv } from "./subscriptions.ts";
import { runDir } from "./run-settings.ts";
import * as tmux from "./tmux.ts";
import { onReleaseAnswer } from "./deploy.ts";
@@ -33,6 +35,9 @@ export interface StartOptions {
/** Project for a bare task number ("42"). */
defaultProjectKey?: string;
provider?: Provider;
+ /** PEP-67: subscriptions ticked at launch (multiple choice); else `poolId`; else the project's pool. */
+ subscriptionIds?: number[];
+ poolId?: number | null;
}
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
@@ -44,9 +49,11 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
const cwd = realpathSync(dir);
- const provider = opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
+ // PEP-67: the first free active subscription of the chosen set decides the provider.
+ const sub = await pickSubscription(db, { projectId: ref.project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider: opts.provider });
+ const provider = sub?.provider ?? opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
if (provider === "claude") trustWorkspace(cwd);
- const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider });
+ const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider, subscriptionId: sub?.id ?? null });
const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n");
@@ -84,8 +91,8 @@ async function launch(
): Promise {
const generation = s.generation + 1;
const rules = await loadSharedRules();
- const [owner] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, s.projectId));
- const claudeToken = s.provider === "claude" && owner ? await claudeTokenForProject(db, owner) : null;
+ // The session's subscription (no rotation on resume — PEP-39); none = this machine's login.
+ const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
const argv = buildCommand(s.provider, {
sessionId: s.id,
generation,
@@ -98,6 +105,7 @@ async function launch(
});
// tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux
// command line, and leaves a record of exactly what was started.
+ const ctx = { sessionId: s.id, generation };
const launchScript = join(runDir(s.id, generation), "launch.sh");
writeFileSync(launchScript, `#!/bin/bash\nexec ${argv.map(shq).join(" ")}\n`);
chmodSync(launchScript, 0o700);
@@ -114,8 +122,9 @@ async function launch(
// Hooks and the MCP server must talk to the same DB / state dir as the runner.
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 } : {}),
+ ...providerEnv(s.provider, ctx),
+ // The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
+ ...(sub ? subscriptionEnv(sub) : {}),
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
},
});
@@ -129,6 +138,7 @@ async function launch(
tmuxName: s.tmuxName,
prompt: opts.prompt,
provider: s.provider,
+ subscriptionId: sub?.id ?? null,
rulesSource: rules.source,
});
return getSession(db, s.id);
diff --git a/packages/runner/src/subscription-login.ts b/packages/runner/src/subscription-login.ts
new file mode 100644
index 00000000..1ff6a4c6
--- /dev/null
+++ b/packages/runner/src/subscription-login.ts
@@ -0,0 +1,242 @@
+// Sign-in of agent subscriptions from the web (PEP-13 → PEP-67): the agent CLI's own login
+// runs on this machine in a tmux session (`peppa-auth-sub`); the superadmin opens the
+// link on their device and, for Claude, pastes the code back into the web form.
+// Claude — `claude setup-token`: URL → code → long-lived token, stored encrypted.
+// Codex — `codex login --device-auth` with the subscription's own CODEX_HOME: URL + one-time
+// code; Codex itself writes auth.json there when the user confirms on their device.
+import { execFile } from "node:child_process";
+import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import {
+ deleteSetting,
+ deleteSubscription,
+ getSetting,
+ getSubscription,
+ PeppaError,
+ setSetting,
+ updateSubscription,
+ type Subscription,
+} from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { peppaHome } from "@peppa/shared";
+import * as tmux from "./tmux.ts";
+
+const LOGIN_TTL_MS = 10 * 60_000;
+const CLAUDE_URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/;
+const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/;
+const ERROR_RE = /(error|invalid|failed|expired)/i;
+const CODEX_URL_RE = /https:\/\/\S+/;
+const CODEX_CODE_RE = /\b[A-Z0-9]{4,5}-[A-Z0-9]{4,5}\b/;
+
+const sessionName = (id: number) => `peppa-auth-sub${id}`;
+const settingKey = (id: number) => `subscription.login:${id}`;
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** Login dir of a subscription (Codex: CODEX_HOME). Private: the CLI keeps credentials there. */
+export function subscriptionDir(id: number): string {
+ return join(peppaHome(), "subscriptions", `s${id}`);
+}
+export function codexHome(id: number): string {
+ const dir = join(subscriptionDir(id), "codex");
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ return dir;
+}
+
+export interface PendingLogin {
+ kind: "claude" | "codex";
+ url: string;
+ /** Codex device auth: the one-time code to enter on the device. */
+ code?: string;
+ startedAt: number;
+}
+
+/** Pending sign-in of a subscription (null if none or expired). */
+export async function pendingLogin(db: Db, id: number): Promise {
+ const s = await getSetting(db, settingKey(id));
+ if (!s) return null;
+ if (Date.now() - s.startedAt > LOGIN_TTL_MS || !(await tmux.hasSession(sessionName(id)))) {
+ await endLogin(db, id);
+ return null;
+ }
+ return s;
+}
+
+async function endLogin(db: Db, id: number): Promise {
+ await deleteSetting(db, settingKey(id));
+ if (await tmux.hasSession(sessionName(id))) await tmux.killSession(sessionName(id)).catch(() => {});
+}
+
+/** Cancels a sign-in; a subscription that was never active disappears with it. */
+export async function cancelLogin(db: Db, id: number): Promise {
+ await endLogin(db, id);
+ const s = await getSubscription(db, id).catch(() => null);
+ if (s && !s.activatedAt) await removeSubscription(db, id);
+}
+
+/** Deletes a subscription with its login dir (and any sign-in in progress). */
+export async function removeSubscription(db: Db, id: number): Promise {
+ await endLogin(db, id);
+ await deleteSubscription(db, id);
+ rmSync(subscriptionDir(id), { recursive: true, force: true });
+}
+
+async function waitForScreen(id: number, re: RegExp, what: string): Promise {
+ for (let i = 0; i < 60; i++) {
+ await sleep(500);
+ const screen = await tmux.capturePane(sessionName(id), 200).catch(() => "");
+ if (re.test(screen)) return screen;
+ if ((await tmux.paneState(sessionName(id)).catch(() => ({ dead: true }))).dead) break;
+ }
+ const tail = (await tmux.capturePane(sessionName(id)).catch(() => "")).trim();
+ throw new PeppaError(`${what} не показал ссылку входа${tail ? `: ${tail.split("\n").slice(-3).join(" ").slice(0, 200)}` : ""}`);
+}
+
+// ── Claude ───────────────────────────────────────────────────────────────────────
+
+/** Starts `claude setup-token` for a Claude subscription and returns the sign-in URL. */
+export async function startClaudeLogin(db: Db, id: number): Promise {
+ const sub = await getSubscription(db, id);
+ if (sub.provider !== "claude") throw new PeppaError("Это не подписка Claude");
+ await endLogin(db, id);
+ await tmux.newSession({
+ name: sessionName(id),
+ cwd: homedir(),
+ command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`,
+ env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine
+ width: 1000,
+ });
+ try {
+ const url = CLAUDE_URL_RE.exec(await waitForScreen(id, CLAUDE_URL_RE, "claude setup-token"))![0];
+ const login: PendingLogin = { kind: "claude", url, startedAt: Date.now() };
+ await setSetting(db, settingKey(id), login);
+ return login;
+ } catch (e) {
+ await endLogin(db, id);
+ throw e;
+ }
+}
+
+/** Types the code into setup-token and stores the token it prints on the subscription. */
+export async function finishClaudeLogin(db: Db, id: number, code: string): Promise {
+ const c = code.trim();
+ if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов");
+ const login = await pendingLogin(db, id);
+ if (login?.kind !== "claude") throw new PeppaError("Вход не начат или истёк — начните заново");
+ const name = sessionName(id);
+ const before = await tmux.capturePane(name);
+ await tmux.sendText(name, c);
+ for (let i = 0; i < 60; i++) {
+ await sleep(500);
+ const screen = await tmux.capturePane(name, 200);
+ const token = TOKEN_RE.exec(screen)?.[0];
+ if (token) {
+ await updateSubscription(db, id, { secret: token, authKind: "oauth", status: "active", checkedAt: new Date() });
+ await endLogin(db, id); // also wipes the token from the tmux scrollback
+ return;
+ }
+ const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length);
+ const dead = (await tmux.paneState(name)).dead;
+ if (dead || ERROR_RE.test(after)) {
+ const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" ");
+ await endLogin(db, id);
+ throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`);
+ }
+ }
+ await endLogin(db, id);
+ throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново.");
+}
+
+/** A ready token pasted by hand (from `claude setup-token` run elsewhere). */
+export async function setClaudeSubscriptionToken(db: Db, id: number, token: string): Promise {
+ const t = token.trim();
+ if (!TOKEN_RE.test(t) || TOKEN_RE.exec(t)![0] !== t) throw new PeppaError("Это не похоже на токен Claude (sk-ant-oat…)");
+ await endLogin(db, id);
+ await updateSubscription(db, id, { secret: t, authKind: "oauth", status: "active", checkedAt: new Date() });
+}
+
+// ── Codex ────────────────────────────────────────────────────────────────────────
+
+/** Starts `codex login --device-auth` with the subscription's CODEX_HOME: URL + one-time code. */
+export async function startCodexLogin(db: Db, id: number): Promise {
+ const sub = await getSubscription(db, id);
+ if (sub.provider !== "codex") throw new PeppaError("Это не подписка Codex");
+ await endLogin(db, id);
+ await tmux.newSession({
+ name: sessionName(id),
+ cwd: homedir(),
+ command: `${process.env.PEPPA_CODEX_BIN ?? "codex"} login --device-auth`,
+ env: { CODEX_HOME: codexHome(id), BROWSER: "/usr/bin/true" },
+ width: 300,
+ });
+ try {
+ const screen = await waitForScreen(id, CODEX_CODE_RE, "codex login");
+ const url = CODEX_URL_RE.exec(screen)?.[0];
+ if (!url) throw new PeppaError("codex login не показал ссылку входа");
+ const login: PendingLogin = { kind: "codex", url, code: CODEX_CODE_RE.exec(screen)![0], startedAt: Date.now() };
+ await setSetting(db, settingKey(id), login);
+ await updateSubscription(db, id, { authKind: "device" });
+ return login;
+ } catch (e) {
+ await endLogin(db, id);
+ throw e;
+ }
+}
+
+/**
+ * Where a Codex device sign-in stands: still waiting for the user, done (auth.json written,
+ * subscription active) or failed. Called by the page while it shows the code.
+ */
+export async function pollCodexLogin(db: Db, id: number): Promise<"pending" | "active" | "failed" | "none"> {
+ const login = await getSetting(db, settingKey(id));
+ if (login?.kind !== "codex") return "none";
+ const name = sessionName(id);
+ const state = (await tmux.hasSession(name)) ? await tmux.paneState(name) : { dead: true, exitStatus: null };
+ if (!state.dead) {
+ if (Date.now() - login.startedAt > LOGIN_TTL_MS) {
+ await endLogin(db, id);
+ await updateSubscription(db, id, { status: "auth_error", lastError: "вход не подтверждён за 10 минут" });
+ return "failed";
+ }
+ return "pending";
+ }
+ const screen = await tmux.capturePane(name, 200).catch(() => "");
+ await endLogin(db, id);
+ if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) {
+ await updateSubscription(db, id, { status: "active", checkedAt: new Date() });
+ return "active";
+ }
+ const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200);
+ await updateSubscription(db, id, { status: "auth_error", lastError: msg || `codex login завершился с кодом ${state.exitStatus}` });
+ return "failed";
+}
+
+/** API key for Codex: `codex login --with-api-key` (key on stdin, never in argv or logs). */
+export async function setCodexApiKey(db: Db, id: number, key: string): Promise {
+ const k = key.trim();
+ if (!k || /\s/.test(k)) throw new PeppaError("Вставьте ключ целиком, без пробелов");
+ await endLogin(db, id);
+ const out = await new Promise<{ code: number | null; text: string }>((resolve) => {
+ const child = execFile(
+ process.env.PEPPA_CODEX_BIN ?? "codex",
+ ["login", "--with-api-key"],
+ { env: { ...process.env, CODEX_HOME: codexHome(id) }, timeout: 60_000 },
+ (err, stdout, stderr) => resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, text: `${stdout}${stderr}` }),
+ );
+ child.stdin?.end(`${k}\n`);
+ });
+ if (out.code !== 0) {
+ await updateSubscription(db, id, { status: "auth_error", authKind: "api_key", lastError: mask(out.text, [k]).trim().slice(-200) });
+ throw new PeppaError(`Codex не принял ключ: ${mask(out.text, [k]).trim().split("\n").slice(-1)[0]?.slice(0, 200) ?? ""}`);
+ }
+ await updateSubscription(db, id, { status: "active", authKind: "api_key", checkedAt: new Date() });
+}
+
+/** Removes secrets from CLI output before it is stored or shown. */
+export function mask(text: string, secrets: Array