Merge pull request 'PEP-36 этап 2: SQLite (node:sqlite, WAL) вместо Postgres — мержить вместе с переключением прода' (#29) from task/PEP-36-sqlite into main
This commit is contained in:
commit
75019fdf1c
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
14
AGENTS.md
14
AGENTS.md
@ -8,9 +8,9 @@
|
||||
## Структура
|
||||
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web`
|
||||
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
|
||||
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
|
||||
- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36)
|
||||
- `packages/shared` — env, ключи задач (`PEP-42`)
|
||||
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё
|
||||
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM); живые обновления — `notify()` будит подписчика (бота) через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот вдобавок раз в секунду смотрит `PRAGMA data_version`; ежедневная копия базы (`backupDb`, `VACUUM INTO`, `~/.peppa/backups`, 7 штук) из вачдога; всё ходит через неё
|
||||
- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов
|
||||
- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, create_project, list_goals, create_goal, update_goal, list_tasks, get_task, create_task, update_task (название/описание/цель, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question; `instructions` сервера объясняют модель клиенту. Пользовательская документация — `/help` в вебе (держать в актуальном состоянии при изменении инструментов)
|
||||
- `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM
|
||||
@ -25,7 +25,7 @@
|
||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
|
||||
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
|
||||
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres Пеппы, `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
|
||||
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
|
||||
- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u<id>` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины
|
||||
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:<service>`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon:<service>:…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]`
|
||||
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect <KEY>` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)
|
||||
@ -51,7 +51,7 @@
|
||||
интеграции (какой доступ, у кого).
|
||||
|
||||
## Команды
|
||||
- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
|
||||
- `pnpm db:generate` (новая миграция из схемы) / `pnpm db:migrate` (= `peppa db migrate`); `peppa db migrate-to-sqlite <file>` — одноразовый перенос из Postgres `DATABASE_URL` (только чтение, сверка строк и внешних ключей; старая pg-схема — `packages/cli/legacy-pg-migrations`); `pnpm db:up` — Postgres для Bugsink
|
||||
- `peppa project create <slug> <KEY> <name> [--existing]` — проект в Gitea (`provisionProject` в runner, тот же код, что у веба); `peppa project owner <KEY> <login>`
|
||||
- `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы
|
||||
- `peppa web login-link <login>` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
|
||||
@ -60,9 +60,9 @@
|
||||
- `pnpm dev:web`
|
||||
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>`
|
||||
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
|
||||
- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_<pid>` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста, БД `peppa_test_ci_r<run_id>`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`)
|
||||
- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`)
|
||||
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
|
||||
- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`)
|
||||
- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (у каждого файла свой временный SQLite-файл, свой tmux `-L`, свой `PEPPA_HOME` — параллельные worktree не мешают друг другу)
|
||||
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
|
||||
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
|
||||
|
||||
TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`.
|
||||
|
||||
@ -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"
|
||||
```
|
||||
|
||||
@ -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() {
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -227,14 +227,17 @@ FIFO-очередь записи без хвостов — нужен тольк
|
||||
- запись — `BEGIN IMMEDIATE`, транзакции короткие и синхронные, до 3 повторов на BUSY;
|
||||
- база только на локальном диске (WAL не работает на сетевых ФС).
|
||||
|
||||
### 3. LISTEN/NOTIFY → журнал событий + сигнал + страховочный опрос
|
||||
### 3. LISTEN/NOTIFY → сигнал по сокету + `PRAGMA data_version`
|
||||
|
||||
Источник правды — таблица `events` и курсор подписчика (`settings`, ключ
|
||||
`cursor:<service>`), так бот после рестарта дочитывает пропущенное (сейчас NOTIFY,
|
||||
пришедший во время рестарта, теряется, спасает только reconcile раз в 10 с). Записавший
|
||||
процесс шлёт датаграмму «есть новое» в unix-сокет `~/.peppa/events.sock` каждого
|
||||
подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в
|
||||
секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала.
|
||||
Сделано в этапе 2 проще, чем планировалось: бот и сейчас не читает содержимое NOTIFY,
|
||||
а по любому сигналу сверяет очередь с базой (reconcile), поэтому курсор по `events` не
|
||||
нужен. `notify()` после записи подключается к unix-сокету `$PEPPA_HOME/bot.events.sock`
|
||||
и пишет строку JSON (сокета нет — сразу возвращается). Бот, кроме того, раз в секунду
|
||||
читает `PRAGMA data_version` — он меняется при каждом коммите **другого** соединения, —
|
||||
и при изменении делает reconcile; плюс прежний reconcile раз в 10 с и при старте. Итог:
|
||||
~1 мс в норме, ≤ 1 с при пропущенном сигнале, после рестарта бот находит всё сам.
|
||||
(UDP-датаграммы по unix-сокету в Node нет — поэтому короткое stream-соединение.) Веб
|
||||
живых обновлений не имел и не получает; SSE — отдельной задачей.
|
||||
|
||||
### 4. Поэтапно: Node без tsx → SQLite → Docker
|
||||
|
||||
|
||||
@ -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 без изменений и печатать, в какой таблице расхождение.
|
||||
|
||||
@ -21,16 +21,16 @@
|
||||
|
||||
## 2. Этап 2 — SQLite вместо Postgres
|
||||
|
||||
- [ ] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`)
|
||||
- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
|
||||
- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции
|
||||
- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async`
|
||||
- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть
|
||||
- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме
|
||||
- [ ] 2.6 `peppa db migrate-to-sqlite <file>`: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении
|
||||
- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл
|
||||
- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude)
|
||||
- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63)
|
||||
- [x] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`) — смержен (#24–#26)
|
||||
- [x] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
|
||||
- [x] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции
|
||||
- [x] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) переписан; async-колбэк драйвер отклоняет с ошибкой (вместо lint-проверки)
|
||||
- [x] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть
|
||||
- [x] 2.5 Живые обновления: `notify()` будит бота через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот раз в секунду смотрит `PRAGMA data_version` (запись другого процесса) + прежний reconcile раз в 10 с; веб без живых обновлений, как и раньше (SSE — отдельной задачей)
|
||||
- [x] 2.6 `peppa db migrate-to-sqlite <file>`: чтение Postgres в read-only снапшоте, порядок таблиц по внешним ключам из схемы, сверка строк и `foreign_key_check`, файл появляется только после проверок; проверено на копии боевой БД (20 таблиц, 64 мс, расхождений нет)
|
||||
- [x] 2.7 Ежедневная копия (`backupDb`, `VACUUM INTO`) из вачдога, 7 копий, алерт админам при ошибке; health проверяет таблицы базы
|
||||
- [x] 2.8 testkit: временный файл базы на каждый файл тестов вместо `peppa_test`; `storage.test.ts` (20 процессов, нумерация задач из разных процессов, сокет/`data_version`, перенос из Postgres, копии)
|
||||
- [ ] 2.9 Переключение прода (деплой — PM, шаги в PR): остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63)
|
||||
|
||||
## 3. Этап 3 — запуск одной командой
|
||||
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"@peppa/runner": "workspace:*"
|
||||
"@peppa/runner": "workspace:*",
|
||||
"postgres": "4.1.1"
|
||||
}
|
||||
}
|
||||
|
||||
@ -38,7 +38,7 @@ import {
|
||||
updateTask,
|
||||
type TaskStatus,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { createDb, migrateDb } from "@peppa/db";
|
||||
import { answerAndDeliver, connectCi, deployProd, listReleases, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
@ -73,6 +73,8 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa user ensure mock-<name> (local test user)
|
||||
peppa web login-link <gitea-login> (one-time admin login, 10 minutes)
|
||||
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
||||
peppa db migrate (apply schema migrations to PEPPA_DB)
|
||||
peppa db migrate-to-sqlite <file> (one-time copy from Postgres DATABASE_URL, read-only)
|
||||
|
||||
KEY defaults to the project of the current directory (.peppa/project.json).
|
||||
Statuses: ${TASK_STATUSES.join(", ")}`;
|
||||
@ -101,7 +103,31 @@ const { values: opts, positionals } = parseArgs({
|
||||
});
|
||||
|
||||
const env = loadEnv();
|
||||
const db = createDb(env.DATABASE_URL);
|
||||
|
||||
// `db` commands run before the database is opened: they create or replace the file.
|
||||
if (positionals[0] === "db") {
|
||||
try {
|
||||
if (positionals[1] === "migrate") {
|
||||
migrateDb(createDb(env.PEPPA_DB));
|
||||
console.log(`migrated ${env.PEPPA_DB}`);
|
||||
} else if (positionals[1] === "migrate-to-sqlite" && positionals[2]) {
|
||||
if (!env.DATABASE_URL) throw new PeppaError("DATABASE_URL (the Postgres source) is not set");
|
||||
const { migrateToSqlite } = await import("./migrate-to-sqlite.ts");
|
||||
const r = await migrateToSqlite(env.DATABASE_URL, resolve(positionals[2]));
|
||||
for (const t of r.tables) console.log(`${t.name.padEnd(20)} ${t.copied}`);
|
||||
console.log(`перенесено, расхождений нет: ${r.file} (${r.ms} мс)`);
|
||||
} else {
|
||||
console.error(USAGE);
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
} catch (e) {
|
||||
console.error(`peppa: ${(e as Error).message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
const here = findProjectFile(process.cwd())?.data.key;
|
||||
const [group, cmd, ...args] = positionals;
|
||||
|
||||
|
||||
69
packages/cli/src/migrate-to-sqlite.ts
Normal file
69
packages/cli/src/migrate-to-sqlite.ts
Normal file
@ -0,0 +1,69 @@
|
||||
// One-time move of Peppa's data from Postgres to SQLite (PEP-36):
|
||||
// peppa db migrate-to-sqlite <file> (source: DATABASE_URL)
|
||||
// The Postgres session is read-only, so the source cannot change. The new file is built
|
||||
// next to the target and renamed into place only after row counts and foreign keys check
|
||||
// out; on any mismatch it is deleted and nothing else is touched.
|
||||
import { createDb, migrateDb, tablesInFkOrder } from "@peppa/db";
|
||||
import { existsSync, renameSync, rmSync } from "node:fs";
|
||||
import postgres from "postgres";
|
||||
|
||||
const toSqlite = (v: unknown, c: { json: boolean; ms: boolean; bool: boolean }) => {
|
||||
if (v === null || v === undefined) return null;
|
||||
if (c.ms) return v instanceof Date ? v.getTime() : new Date(String(v)).getTime();
|
||||
if (c.bool) return v ? 1 : 0;
|
||||
if (c.json) return JSON.stringify(v);
|
||||
if (typeof v === "bigint") return Number(v);
|
||||
if (v instanceof Date) return v.getTime();
|
||||
return v as string | number;
|
||||
};
|
||||
|
||||
export interface MigrationReport {
|
||||
file: string;
|
||||
tables: { name: string; source: number; copied: number }[];
|
||||
ms: number;
|
||||
}
|
||||
|
||||
export async function migrateToSqlite(sourceUrl: string, file: string): Promise<MigrationReport> {
|
||||
if (existsSync(file)) throw new Error(`${file} уже существует — переложите его`);
|
||||
const tmp = `${file}.migrating`;
|
||||
for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true });
|
||||
const pg = postgres(sourceUrl, { max: 1, onnotice: () => {}, connection: { default_transaction_read_only: "on" } as never });
|
||||
const t0 = Date.now();
|
||||
const db = createDb(tmp);
|
||||
try {
|
||||
migrateDb(db);
|
||||
// Copy first, then check: foreign_key_check names the table with a dangling reference.
|
||||
db.$client.db.exec("PRAGMA foreign_keys = OFF");
|
||||
const report: MigrationReport["tables"] = [];
|
||||
// One read-only snapshot of Postgres for all tables.
|
||||
await pg.begin("isolation level repeatable read read only", async (tx) => {
|
||||
for (const t of tablesInFkOrder()) {
|
||||
const rows = await tx.unsafe(`select * from "${t.name}"`);
|
||||
const cols = t.columns.filter((c) => rows.length === 0 || c.name in rows[0]!);
|
||||
if (rows.length) {
|
||||
const stmt = db.$client.db.prepare(`insert into "${t.name}" (${cols.map((c) => `"${c.name}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`);
|
||||
db.$client.transaction(() => {
|
||||
for (const r of rows) stmt.run(...cols.map((c) => toSqlite(r[c.name], c)));
|
||||
}).immediate();
|
||||
}
|
||||
const [{ n }] = db.$client.db.prepare(`select count(*) n from "${t.name}"`).all() as { n: number }[];
|
||||
report.push({ name: t.name, source: rows.length, copied: Number(n) });
|
||||
}
|
||||
});
|
||||
const bad = report.filter((t) => t.source !== t.copied);
|
||||
if (bad.length) throw new Error(`расходится число строк: ${bad.map((t) => `${t.name} ${t.source}→${t.copied}`).join(", ")}`);
|
||||
const fk = db.$client.db.prepare("PRAGMA foreign_key_check").all() as { table: string }[];
|
||||
if (fk.length) throw new Error(`${[...new Set(fk.map((r) => r.table))].join(", ")}: нарушение внешнего ключа`);
|
||||
db.$client.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
||||
db.$client.close();
|
||||
renameSync(tmp, file);
|
||||
for (const s of ["-wal", "-shm"]) rmSync(tmp + s, { force: true });
|
||||
return { file, tables: report, ms: Date.now() - t0 };
|
||||
} catch (e) {
|
||||
db.$client.close();
|
||||
for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true });
|
||||
throw e;
|
||||
} finally {
|
||||
await pg.end({ timeout: 1 });
|
||||
}
|
||||
}
|
||||
52
packages/core/src/backup.ts
Normal file
52
packages/core/src/backup.ts
Normal file
@ -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 };
|
||||
}
|
||||
@ -202,12 +202,12 @@ export async function updateIncident(db: Db, id: number, patch: Partial<Omit<Inc
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Takes incidents nobody has applied the policy to yet; each one is returned once. */
|
||||
/** Takes incidents nobody has applied the policy to yet; each one is returned once (one statement: SQLite runs writers one at a time). */
|
||||
export async function claimNewIncidents(db: Db, limit = 20): Promise<Incident[]> {
|
||||
return db
|
||||
.update(incidents)
|
||||
.set({ status: "pending" })
|
||||
.where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit} for update skip locked)`))
|
||||
.where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit})`))
|
||||
.returning();
|
||||
}
|
||||
|
||||
@ -216,7 +216,7 @@ export async function autoIncidentTasksToday(db: Db, projectId: number, now = ne
|
||||
const midnight = new Date(now);
|
||||
midnight.setHours(0, 0, 0, 0);
|
||||
const [r] = await db
|
||||
.select({ n: sql<number>`count(*)::int` })
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(incidents)
|
||||
.where(and(eq(incidents.projectId, projectId), gte(incidents.taskCreatedAt, midnight), inArray(incidents.decidedBy, ["policy", "triage"])));
|
||||
return r?.n ?? 0;
|
||||
|
||||
@ -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";
|
||||
|
||||
@ -121,7 +121,7 @@ export async function adminRecipients(db: Db): Promise<User[]> {
|
||||
|
||||
// ── checks ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise<number> {
|
||||
export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise<number> {
|
||||
const to = await adminRecipients(db);
|
||||
if (!to.length) {
|
||||
log(`monitor: ${text} (нет админа с Telegram)`);
|
||||
@ -203,7 +203,7 @@ export async function healthReport(db: Db, o: { now?: Date; version?: string; co
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
db.execute(sql`select 1`),
|
||||
(async () => db.get(sql`select 1 from settings limit 1`))(),
|
||||
new Promise((_, rej) => (timer = setTimeout(() => rej(new Error("database timeout")), o.timeoutMs ?? 3000))),
|
||||
]);
|
||||
} catch (e) {
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import type { Db } from "@peppa/db";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
export const EVENTS_CHANNEL = "peppa_events";
|
||||
import { peppaHome } from "@peppa/shared";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { connect, createServer } from "node:net";
|
||||
import { join } from "node:path";
|
||||
|
||||
export type PeppaNotification =
|
||||
| { type: "question"; questionId: number }
|
||||
@ -11,7 +12,61 @@ export type PeppaNotification =
|
||||
| { type: "session_updated"; sessionId: number }
|
||||
| { type: "incident"; incidentId: number };
|
||||
|
||||
/** Broadcasts via Postgres NOTIFY; the bot and web listen on EVENTS_CHANNEL. */
|
||||
export async function notify(db: Db, n: PeppaNotification): Promise<void> {
|
||||
await db.execute(sql`select pg_notify(${EVENTS_CHANNEL}, ${JSON.stringify(n)})`);
|
||||
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME. */
|
||||
export const SUBSCRIBERS = ["bot"] as const;
|
||||
export type Subscriber = (typeof SUBSCRIBERS)[number];
|
||||
|
||||
export const eventsSocket = (service: Subscriber) => join(peppaHome(), `${service}.events.sock`);
|
||||
|
||||
/**
|
||||
* Wakes the subscribers after a write (replaces Postgres NOTIFY, PEP-36). Fire and forget:
|
||||
* the data is already in the database, and a subscriber that misses the poke finds the
|
||||
* change by its own polling (PRAGMA data_version) within a second.
|
||||
*/
|
||||
export async function notify(_db: Db, n: PeppaNotification): Promise<void> {
|
||||
const line = `${JSON.stringify(n)}\n`;
|
||||
await Promise.all(
|
||||
SUBSCRIBERS.map(
|
||||
(service) =>
|
||||
new Promise<void>((resolve) => {
|
||||
const path = eventsSocket(service);
|
||||
if (!existsSync(path)) return resolve();
|
||||
const sock = connect(path);
|
||||
const done = () => (sock.destroy(), resolve());
|
||||
sock.setTimeout(200, done);
|
||||
sock.on("error", done);
|
||||
sock.end(line, done);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Listens for notify() pokes; returns a function that stops listening. */
|
||||
export async function listenEvents(service: Subscriber, onEvent: (n: PeppaNotification) => void): Promise<() => Promise<void>> {
|
||||
const path = eventsSocket(service);
|
||||
rmSync(path, { force: true }); // left over from a crashed run
|
||||
const server = createServer((sock) => {
|
||||
let buf = "";
|
||||
sock.setEncoding("utf8");
|
||||
sock.on("data", (c) => {
|
||||
buf += c;
|
||||
for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
|
||||
const line = buf.slice(0, i);
|
||||
buf = buf.slice(i + 1);
|
||||
try {
|
||||
onEvent(JSON.parse(line));
|
||||
} catch {}
|
||||
}
|
||||
});
|
||||
sock.on("error", () => {});
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(path, resolve);
|
||||
});
|
||||
return () =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
rmSync(path, { force: true });
|
||||
});
|
||||
}
|
||||
|
||||
@ -46,21 +46,27 @@ export interface NewTask {
|
||||
}
|
||||
|
||||
export async function createTask(db: Db, t: NewTask): Promise<TaskRef> {
|
||||
return db.transaction(async (tx) => {
|
||||
// Hand out the per-project number atomically.
|
||||
const [project] = await tx
|
||||
.update(projects)
|
||||
.set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` })
|
||||
.where(eq(projects.id, t.projectId))
|
||||
.returning();
|
||||
if (!project) throw new PeppaError(`Project #${t.projectId} not found`);
|
||||
if (t.goalId != null) await getGoal(tx as unknown as Db, t.projectId, t.goalId);
|
||||
const [task] = await tx
|
||||
.insert(tasks)
|
||||
.values({ ...t, number: project.nextTaskNumber - 1 })
|
||||
.returning();
|
||||
return { project, task: task!, key: formatTaskKey(project.key, task!.number) };
|
||||
});
|
||||
if (t.goalId != null) await getGoal(db, t.projectId, t.goalId);
|
||||
// Hand out the per-project number atomically. SQLite transactions are synchronous: no
|
||||
// await inside (the driver refuses an async callback).
|
||||
return db.transaction(
|
||||
(tx) => {
|
||||
const [project] = tx
|
||||
.update(projects)
|
||||
.set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` })
|
||||
.where(eq(projects.id, t.projectId))
|
||||
.returning()
|
||||
.all();
|
||||
if (!project) throw new PeppaError(`Project #${t.projectId} not found`);
|
||||
const task = tx
|
||||
.insert(tasks)
|
||||
.values({ ...t, number: project.nextTaskNumber - 1 })
|
||||
.returning()
|
||||
.get();
|
||||
return { project, task, key: formatTaskKey(project.key, task.number) };
|
||||
},
|
||||
{ behavior: "immediate" },
|
||||
);
|
||||
}
|
||||
|
||||
export interface TaskFilter {
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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" },
|
||||
});
|
||||
|
||||
313
packages/db/migrations/0000_baseline.sql
Normal file
313
packages/db/migrations/0000_baseline.sql
Normal file
@ -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`);
|
||||
File diff suppressed because it is too large
Load Diff
@ -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": {}
|
||||
}
|
||||
}
|
||||
@ -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": {}
|
||||
}
|
||||
}
|
||||
@ -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": {}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -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
|
||||
}
|
||||
]
|
||||
|
||||
@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
121
packages/db/src/client.ts
Normal file
121
packages/db/src/client.ts
Normal file
@ -0,0 +1,121 @@
|
||||
// drizzle on Node's built-in node:sqlite (PEP-36). drizzle-orm 0.45 has no node:sqlite
|
||||
// driver (only 1.0 beta/rc does), but node:sqlite's API is close to better-sqlite3's, so a
|
||||
// thin client lets drizzle's better-sqlite3 *session* run on it. drizzle-orm/better-sqlite3
|
||||
// itself is not imported: its driver.js loads the native better-sqlite3 package.
|
||||
// Every Peppa process (web, bot, watchdog, each hook and MCP server) opens the file itself;
|
||||
// WAL lets readers run next to the single writer, busy_timeout makes writers queue.
|
||||
import { DatabaseSync, type StatementSync } from "node:sqlite";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
export const BUSY_TIMEOUT_MS = 5000;
|
||||
const BUSY_RETRIES = 3;
|
||||
|
||||
const isBusy = (e: unknown) => /SQLITE_BUSY|database is locked/i.test(String((e as Error)?.message ?? e));
|
||||
|
||||
/** SQLITE_BUSY after busy_timeout already waited: try a few more times before giving up. */
|
||||
function retryBusy<T>(fn: () => T): T {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
return fn();
|
||||
} catch (e) {
|
||||
if (!isBusy(e) || attempt >= BUSY_RETRIES) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Params = unknown[];
|
||||
|
||||
class Statement {
|
||||
private stmt: StatementSync;
|
||||
private rawStmt: StatementSync | null = null;
|
||||
private db: DatabaseSync;
|
||||
private sql: string;
|
||||
constructor(db: DatabaseSync, sql: string) {
|
||||
this.db = db;
|
||||
this.sql = sql;
|
||||
this.stmt = db.prepare(sql);
|
||||
}
|
||||
run(...p: Params) {
|
||||
return retryBusy(() => this.stmt.run(...(p as never[])));
|
||||
}
|
||||
all(...p: Params) {
|
||||
return retryBusy(() => this.stmt.all(...(p as never[])));
|
||||
}
|
||||
get(...p: Params) {
|
||||
return retryBusy(() => this.stmt.get(...(p as never[])));
|
||||
}
|
||||
/** The same statement returning rows as arrays (drizzle maps columns by position). */
|
||||
raw() {
|
||||
if (!this.rawStmt) {
|
||||
this.rawStmt = this.db.prepare(this.sql);
|
||||
this.rawStmt.setReturnArrays(true);
|
||||
}
|
||||
const s = this.rawStmt;
|
||||
return { all: (...p: Params) => retryBusy(() => s.all(...(p as never[]))), get: (...p: Params) => retryBusy(() => s.get(...(p as never[]))) };
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteClient {
|
||||
readonly path: string;
|
||||
private readOnly: boolean;
|
||||
private conn: DatabaseSync | null = null;
|
||||
private cache = new Map<string, Statement>();
|
||||
constructor(path: string, opts: { readOnly?: boolean } = {}) {
|
||||
this.path = path;
|
||||
this.readOnly = opts.readOnly ?? false;
|
||||
}
|
||||
/**
|
||||
* The connection, opened on first use: importing a module that creates the client (the
|
||||
* web's lib/db.ts during `next build`) must not create the database file.
|
||||
*/
|
||||
get db(): DatabaseSync {
|
||||
if (this.conn) return this.conn;
|
||||
if (this.path !== ":memory:" && !this.readOnly) mkdirSync(dirname(this.path), { recursive: true });
|
||||
const db = new DatabaseSync(this.path, { readOnly: this.readOnly });
|
||||
// busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY
|
||||
// when many processes open the file together (bench/sqlite/README.md).
|
||||
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
||||
if (!this.readOnly) retryBusy(() => db.exec("PRAGMA journal_mode = WAL"));
|
||||
db.exec("PRAGMA synchronous = NORMAL");
|
||||
db.exec("PRAGMA foreign_keys = ON");
|
||||
return (this.conn = db);
|
||||
}
|
||||
prepare(sql: string) {
|
||||
let s = this.cache.get(sql);
|
||||
if (!s) this.cache.set(sql, (s = new Statement(this.db, sql)));
|
||||
return s;
|
||||
}
|
||||
exec(sql: string) {
|
||||
retryBusy(() => this.db.exec(sql));
|
||||
}
|
||||
/** better-sqlite3's transaction API; the callback must be synchronous. */
|
||||
transaction<T>(fn: (...a: never[]) => T) {
|
||||
const run =
|
||||
(begin: string) =>
|
||||
(...a: never[]): T => {
|
||||
retryBusy(() => this.db.exec(begin));
|
||||
try {
|
||||
const r = fn(...a);
|
||||
if (r && typeof (r as { then?: unknown }).then === "function") {
|
||||
throw new Error("SQLite transactions must be synchronous: no async callback, no await inside db.transaction()");
|
||||
}
|
||||
this.db.exec("COMMIT");
|
||||
return r;
|
||||
} catch (e) {
|
||||
if (this.db.isTransaction) this.db.exec("ROLLBACK");
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
|
||||
}
|
||||
/** Changes committed by other connections since the last call (PRAGMA data_version). */
|
||||
dataVersion(): number {
|
||||
return Number((this.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version);
|
||||
}
|
||||
close() {
|
||||
if (this.conn?.isOpen) this.conn.close();
|
||||
this.conn = null;
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@ -1,14 +1,72 @@
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session";
|
||||
import { migrate as drizzleMigrate } from "drizzle-orm/better-sqlite3/migrator";
|
||||
import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations";
|
||||
import { is } from "drizzle-orm";
|
||||
import { getTableConfig, SQLiteTable } from "drizzle-orm/sqlite-core";
|
||||
import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db";
|
||||
import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect";
|
||||
import type { StatementResultingChanges } from "node:sqlite";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { SqliteClient } from "./client.ts";
|
||||
import * as schema from "./schema.ts";
|
||||
|
||||
export * from "./schema.ts";
|
||||
export { schema };
|
||||
export { schema, SqliteClient };
|
||||
|
||||
export function createDb(url = loadEnv().DATABASE_URL) {
|
||||
const client = postgres(url, { max: 5 });
|
||||
return drizzle(client, { schema });
|
||||
export type Db = BaseSQLiteDatabase<"sync", StatementResultingChanges, typeof schema> & { $client: SqliteClient };
|
||||
|
||||
/** Opens Peppa's SQLite database (PEPPA_DB, default ~/.peppa/peppa.db). */
|
||||
export function createDb(path = loadEnv().PEPPA_DB, opts: { readOnly?: boolean } = {}): Db {
|
||||
const client = new SqliteClient(path, opts);
|
||||
const dialect = new SQLiteSyncDialect();
|
||||
const tables = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
|
||||
const relational = { fullSchema: schema, schema: tables.tables, tableNamesMap: tables.tableNamesMap };
|
||||
const session = new BetterSQLiteSession(client as never, dialect, relational as never);
|
||||
const db = new BaseSQLiteDatabase("sync", dialect, session as never, relational as never) as Db;
|
||||
db.$client = client;
|
||||
return db;
|
||||
}
|
||||
|
||||
export type Db = ReturnType<typeof createDb>;
|
||||
// Not `new URL(…, import.meta.url)`: Next's bundler would try to resolve it as an asset.
|
||||
export const migrationsFolder = join(dirname(fileURLToPath(import.meta.url)), "..", "migrations");
|
||||
|
||||
/** Applies pending migrations (idempotent; safe to run from several processes). */
|
||||
export function migrateDb(db: Db) {
|
||||
drizzleMigrate(db as never, { migrationsFolder });
|
||||
}
|
||||
|
||||
export interface TableInfo {
|
||||
name: string;
|
||||
columns: { name: string; json: boolean; ms: boolean; bool: boolean }[];
|
||||
}
|
||||
|
||||
/** Peppa's tables, parents before children by foreign keys (for copying data in). */
|
||||
export function tablesInFkOrder(): TableInfo[] {
|
||||
const configs = new Map(
|
||||
Object.values(schema)
|
||||
.filter((t) => is(t, SQLiteTable))
|
||||
.map((t) => getTableConfig(t as SQLiteTable))
|
||||
.map((c) => [c.name, c]),
|
||||
);
|
||||
const ordered: string[] = [];
|
||||
const visit = (name: string, path: string[]) => {
|
||||
if (ordered.includes(name) || path.includes(name)) return;
|
||||
for (const fk of configs.get(name)!.foreignKeys) {
|
||||
const parent = getTableConfig(fk.reference().foreignTable).name;
|
||||
if (parent !== name) visit(parent, [...path, name]);
|
||||
}
|
||||
ordered.push(name);
|
||||
};
|
||||
for (const name of [...configs.keys()].sort()) visit(name, []);
|
||||
return ordered.map((name) => ({
|
||||
name,
|
||||
columns: configs.get(name)!.columns.map((c) => ({
|
||||
name: c.name,
|
||||
json: c.columnType === "SQLiteTextJson",
|
||||
ms: c.columnType === "SQLiteTimestamp",
|
||||
bool: c.columnType === "SQLiteBoolean",
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
@ -1,13 +1,18 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { bigint, boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
||||
|
||||
const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
|
||||
// SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is
|
||||
// text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only.
|
||||
const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
|
||||
|
||||
const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs);
|
||||
const updatedAt = () =>
|
||||
timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date());
|
||||
integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date());
|
||||
|
||||
/** People who log into the web, one per Gitea account. */
|
||||
export const users = pgTable("users", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const users = sqliteTable("users", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
giteaId: integer("gitea_id").notNull().unique(),
|
||||
login: text("login").notNull().unique(),
|
||||
name: text("name"),
|
||||
@ -16,22 +21,22 @@ export const users = pgTable("users", {
|
||||
// OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts).
|
||||
accessTokenEnc: text("access_token_enc"),
|
||||
refreshTokenEnc: text("refresh_token_enc"),
|
||||
tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }),
|
||||
tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
|
||||
// Long-lived Claude Code token from `claude setup-token` (encrypted); used for the
|
||||
// Claude sessions of this user's projects.
|
||||
claudeTokenEnc: text("claude_token_enc"),
|
||||
claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }),
|
||||
claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }),
|
||||
// Telegram chat paired from Settings; agent questions of this user's projects go there.
|
||||
telegramChatId: bigint("telegram_chat_id", { mode: "number" }).unique(),
|
||||
telegramUserId: bigint("telegram_user_id", { mode: "number" }),
|
||||
telegramChatId: integer("telegram_chat_id").unique(),
|
||||
telegramUserId: integer("telegram_user_id"),
|
||||
telegramUsername: text("telegram_username"),
|
||||
telegramPairedAt: timestamp("telegram_paired_at", { withTimezone: true }),
|
||||
telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
|
||||
createdAt: createdAt(),
|
||||
lastLoginAt: timestamp("last_login_at", { withTimezone: true }),
|
||||
lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
export const projects = pgTable("projects", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const projects = sqliteTable("projects", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
slug: text("slug").notNull().unique(),
|
||||
// Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2…
|
||||
key: text("key").notNull().unique(),
|
||||
@ -50,7 +55,7 @@ export const projects = pgTable("projects", {
|
||||
});
|
||||
|
||||
/** People who work on a project besides its owner (projects.owner_id). */
|
||||
export const projectMembers = pgTable(
|
||||
export const projectMembers = sqliteTable(
|
||||
"project_members",
|
||||
{
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
@ -62,7 +67,7 @@ export const projectMembers = pgTable(
|
||||
);
|
||||
|
||||
/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */
|
||||
export const projectInvites = pgTable(
|
||||
export const projectInvites = sqliteTable(
|
||||
"project_invites",
|
||||
{
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
@ -73,20 +78,20 @@ export const projectInvites = pgTable(
|
||||
(t) => [primaryKey({ columns: [t.projectId, t.login] })],
|
||||
);
|
||||
|
||||
export const goalStatus = pgEnum("goal_status", ["open", "done", "archived"]);
|
||||
export const goalStatus = { enumValues: ["open", "done", "archived"] as const };
|
||||
|
||||
/** Top-level objectives set by the PM; tasks are broken out of them. */
|
||||
export const goals = pgTable("goals", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const goals = sqliteTable("goals", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
title: text("title").notNull(),
|
||||
description: text("description"),
|
||||
status: goalStatus("status").notNull().default("open"),
|
||||
status: text("status", { enum: goalStatus.enumValues }).notNull().default("open"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
export const taskStatus = pgEnum("task_status", [
|
||||
export const taskStatus = { enumValues: [
|
||||
"backlog", // created, nobody working on it
|
||||
"proposing", // agent is writing the OpenSpec change
|
||||
"awaiting_approval", // proposal ready, PM must approve
|
||||
@ -94,18 +99,18 @@ export const taskStatus = pgEnum("task_status", [
|
||||
"review", // PR open in Gitea
|
||||
"done", // change archived, merged
|
||||
"blocked",
|
||||
]);
|
||||
] as const };
|
||||
|
||||
export const tasks = pgTable(
|
||||
export const tasks = sqliteTable(
|
||||
"tasks",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
|
||||
number: integer("number").notNull(),
|
||||
title: text("title").notNull(),
|
||||
description: text("description"),
|
||||
status: taskStatus("status").notNull().default("backlog"),
|
||||
status: text("status", { enum: taskStatus.enumValues }).notNull().default("backlog"),
|
||||
// OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth"
|
||||
openspecChange: text("openspec_change"),
|
||||
prUrl: text("pr_url"),
|
||||
@ -119,8 +124,8 @@ export const tasks = pgTable(
|
||||
);
|
||||
|
||||
/** PEP-57: one deployment of a project to an environment (and its outcome). */
|
||||
export const releases = pgTable("releases", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const releases = sqliteTable("releases", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
env: text("env", { enum: ["preview", "staging", "prod"] }).notNull(),
|
||||
sha: text("sha").notNull(),
|
||||
@ -129,7 +134,7 @@ export const releases = pgTable("releases", {
|
||||
host: text("host"),
|
||||
prNumber: integer("pr_number"),
|
||||
// Task keys in the release ("PAY-7"), from the merged commits.
|
||||
tasks: jsonb("tasks").$type<string[]>().notNull().default([]),
|
||||
tasks: text("tasks", { mode: "json" }).$type<string[]>().notNull().default([]),
|
||||
status: text("status", { enum: ["deploying", "healthy", "rolled_back", "failed", "removed"] }).notNull().default("deploying"),
|
||||
// "ci" for automatic deploys, the PM's login for prod by the button.
|
||||
deployedBy: text("deployed_by").notNull().default("ci"),
|
||||
@ -141,10 +146,10 @@ export const releases = pgTable("releases", {
|
||||
});
|
||||
|
||||
/** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */
|
||||
export const checkRuns = pgTable(
|
||||
export const checkRuns = sqliteTable(
|
||||
"check_runs",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
||||
sha: text("sha").notNull(),
|
||||
@ -163,7 +168,7 @@ export const checkRuns = pgTable(
|
||||
(t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)],
|
||||
);
|
||||
|
||||
export const sessionStatus = pgEnum("session_status", [
|
||||
export const sessionStatus = { enumValues: [
|
||||
"starting",
|
||||
"running",
|
||||
"waiting_input", // Claude asked something / needs permission
|
||||
@ -172,11 +177,11 @@ export const sessionStatus = pgEnum("session_status", [
|
||||
"rate_limited", // StopFailure with error=rate_limit, or limit banner on screen
|
||||
"done",
|
||||
"failed",
|
||||
]);
|
||||
] as const };
|
||||
|
||||
/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
|
||||
export const sessions = pgTable("sessions", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const sessions = sqliteTable("sessions", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
||||
tmuxName: text("tmux_name").notNull().unique(),
|
||||
@ -189,53 +194,53 @@ export const sessions = pgTable("sessions", {
|
||||
autoNudges: integer("auto_nudges").notNull().default(0),
|
||||
// Usage limit recovery (PEP-56): when to continue, current probe interval if the reset
|
||||
// time is unknown, auto-resumes today (cap), and when the last auto-resume happened.
|
||||
resumeAt: timestamp("resume_at", { withTimezone: true }),
|
||||
resumeAt: integer("resume_at", { mode: "timestamp_ms" }),
|
||||
limitProbeMin: integer("limit_probe_min"),
|
||||
limitResumes: integer("limit_resumes").notNull().default(0),
|
||||
limitResumesDay: text("limit_resumes_day"),
|
||||
limitResumedAt: timestamp("limit_resumed_at", { withTimezone: true }),
|
||||
status: sessionStatus("status").notNull().default("starting"),
|
||||
lastActivityAt: timestamp("last_activity_at", { withTimezone: true }),
|
||||
limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }),
|
||||
status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"),
|
||||
lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }),
|
||||
startedAt: createdAt(),
|
||||
endedAt: timestamp("ended_at", { withTimezone: true }),
|
||||
endedAt: integer("ended_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
/** Questions routed to the PM (Telegram / web) and their answers. */
|
||||
export const questions = pgTable("questions", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const questions = sqliteTable("questions", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
||||
// Null when asked from a session Peppa did not start (manual `claude`).
|
||||
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
||||
kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
|
||||
text: text("text").notNull(),
|
||||
options: jsonb("options").$type<string[]>(),
|
||||
options: text("options", { mode: "json" }).$type<string[]>(),
|
||||
answer: text("answer"),
|
||||
// "system": closed by Peppa itself (session stopped/resumed), not by a person.
|
||||
answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }),
|
||||
telegramMessageId: integer("telegram_message_id"),
|
||||
// A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer,
|
||||
// so it must not also be typed into the terminal.
|
||||
awaitingHook: boolean("awaiting_hook").notNull().default(false),
|
||||
awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false),
|
||||
createdAt: createdAt(),
|
||||
answeredAt: timestamp("answered_at", { withTimezone: true }),
|
||||
answeredAt: integer("answered_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
/** Event log: hook / watchdog events, progress reports, status changes. */
|
||||
export const events = pgTable("events", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const events = sqliteTable("events", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
||||
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
||||
type: text("type").notNull(),
|
||||
payload: jsonb("payload"),
|
||||
payload: text("payload", { mode: "json" }),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/** Small key/value store for service state (Telegram offset, pairing, binding). */
|
||||
export const settings = pgTable("settings", {
|
||||
export const settings = sqliteTable("settings", {
|
||||
key: text("key").primaryKey(),
|
||||
value: jsonb("value").notNull(),
|
||||
value: text("value", { mode: "json" }).notNull(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
@ -243,87 +248,87 @@ export const settings = pgTable("settings", {
|
||||
* Durable Telegram outbox: every message/edit is queued here first, then delivered with
|
||||
* retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message).
|
||||
*/
|
||||
export const telegramOutbox = pgTable("telegram_outbox", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const telegramOutbox = sqliteTable("telegram_outbox", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
dedupeKey: text("dedupe_key").notNull().unique(),
|
||||
method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(),
|
||||
params: jsonb("params").$type<Record<string, unknown>>().notNull(),
|
||||
params: text("params", { mode: "json" }).$type<Record<string, unknown>>().notNull(),
|
||||
questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
|
||||
status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"),
|
||||
attempts: integer("attempts").notNull().default(0),
|
||||
nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs),
|
||||
telegramMessageId: integer("telegram_message_id"),
|
||||
error: text("error"),
|
||||
createdAt: createdAt(),
|
||||
sentAt: timestamp("sent_at", { withTimezone: true }),
|
||||
sentAt: integer("sent_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
/** Telegram updates already taken: recorded before acting, so a restart never replays one. */
|
||||
export const telegramUpdates = pgTable("telegram_updates", {
|
||||
export const telegramUpdates = sqliteTable("telegram_updates", {
|
||||
updateId: integer("update_id").primaryKey(),
|
||||
status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */
|
||||
export const oauthClients = pgTable("oauth_clients", {
|
||||
export const oauthClients = sqliteTable("oauth_clients", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
redirectUris: jsonb("redirect_uris").$type<string[]>().notNull(),
|
||||
redirectUris: text("redirect_uris", { mode: "json" }).$type<string[]>().notNull(),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */
|
||||
export const oauthCodes = pgTable("oauth_codes", {
|
||||
export const oauthCodes = sqliteTable("oauth_codes", {
|
||||
codeHash: text("code_hash").primaryKey(),
|
||||
clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }),
|
||||
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||
redirectUri: text("redirect_uri").notNull(),
|
||||
codeChallenge: text("code_challenge").notNull(),
|
||||
scope: text("scope"),
|
||||
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
||||
usedAt: timestamp("used_at", { withTimezone: true }),
|
||||
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
|
||||
usedAt: integer("used_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */
|
||||
export const oauthTokens = pgTable("oauth_tokens", {
|
||||
export const oauthTokens = sqliteTable("oauth_tokens", {
|
||||
tokenHash: text("token_hash").primaryKey(),
|
||||
kind: text("kind", { enum: ["access", "refresh"] }).notNull(),
|
||||
clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }),
|
||||
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||
scope: text("scope"),
|
||||
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
||||
revokedAt: timestamp("revoked_at", { withTimezone: true }),
|
||||
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
|
||||
revokedAt: integer("revoked_at", { mode: "timestamp_ms" }),
|
||||
createdAt: createdAt(),
|
||||
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
|
||||
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const;
|
||||
export type IncidentPolicy = (typeof incidentPolicies)[number];
|
||||
|
||||
/** Error tracking of a project (PEP-58): webhook secret and how new errors are handled. */
|
||||
export const incidentSettings = pgTable("incident_settings", {
|
||||
export const incidentSettings = sqliteTable("incident_settings", {
|
||||
projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),
|
||||
// Part of the webhook URL Bugsink posts alerts to: /api/hooks/bugsink/<hookSecret>.
|
||||
hookSecret: text("hook_secret").notNull().unique(),
|
||||
policy: text("policy", { enum: incidentPolicies }).notNull().default("backlog"),
|
||||
// The PM's mini-prompt for the triage agent ("how to decide").
|
||||
triagePrompt: text("triage_prompt"),
|
||||
environments: jsonb("environments").$type<string[]>().notNull().default(["prod", "production"]),
|
||||
environments: text("environments", { mode: "json" }).$type<string[]>().notNull().default(["prod", "production"]),
|
||||
dailyLimit: integer("daily_limit").notNull().default(5),
|
||||
ignorePattern: text("ignore_pattern"),
|
||||
goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
|
||||
// False: the alert webhook still has to be added in Bugsink by hand (polling covers it).
|
||||
webhookAuto: boolean("webhook_auto").notNull().default(false),
|
||||
webhookAuto: integer("webhook_auto", { mode: "boolean" }).notNull().default(false),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
/** Bugsink projects feeding a Peppa project: one for the frontend, one for the backend. */
|
||||
export const errorSources = pgTable(
|
||||
export const errorSources = sqliteTable(
|
||||
"error_sources",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
kind: text("kind", { enum: ["web", "api"] }).notNull(),
|
||||
bugsinkProjectId: integer("bugsink_project_id").notNull().unique(),
|
||||
@ -336,8 +341,8 @@ export const errorSources = pgTable(
|
||||
export const incidentStatuses = ["new", "open", "pending", "task", "ignored", "resolved", "regressed"] as const;
|
||||
|
||||
/** A Bugsink issue seen in Peppa. Repeated events update the same row. */
|
||||
export const incidents = pgTable("incidents", {
|
||||
id: serial("id").primaryKey(),
|
||||
export const incidents = sqliteTable("incidents", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
source: text("source", { enum: ["web", "api"] }).notNull(),
|
||||
bugsinkIssueId: text("bugsink_issue_id").notNull().unique(),
|
||||
@ -349,8 +354,8 @@ export const incidents = pgTable("incidents", {
|
||||
firstRelease: text("first_release"),
|
||||
lastRelease: text("last_release"),
|
||||
events: integer("events").notNull().default(1),
|
||||
firstSeen: timestamp("first_seen", { withTimezone: true }).notNull(),
|
||||
lastSeen: timestamp("last_seen", { withTimezone: true }).notNull(),
|
||||
firstSeen: integer("first_seen", { mode: "timestamp_ms" }).notNull(),
|
||||
lastSeen: integer("last_seen", { mode: "timestamp_ms" }).notNull(),
|
||||
url: text("url"),
|
||||
stack: text("stack"),
|
||||
// new → open | pending | task | ignored; task → resolved → regressed (see design.md)
|
||||
@ -359,9 +364,9 @@ export const incidents = pgTable("incidents", {
|
||||
decidedBy: text("decided_by", { enum: ["policy", "triage", "pm"] }),
|
||||
decisionReason: text("decision_reason"),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
||||
taskCreatedAt: timestamp("task_created_at", { withTimezone: true }),
|
||||
taskCreatedAt: integer("task_created_at", { mode: "timestamp_ms" }),
|
||||
resolvedRelease: text("resolved_release"),
|
||||
resolvedAt: timestamp("resolved_at", { withTimezone: true }),
|
||||
resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }),
|
||||
regressions: integer("regressions").notNull().default(0),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
|
||||
@ -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(() => {});
|
||||
}
|
||||
|
||||
|
||||
@ -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 } : {}),
|
||||
|
||||
@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,10 @@ import { homedir } from "node:os";
|
||||
import { z } from "zod";
|
||||
|
||||
const schema = z.object({
|
||||
DATABASE_URL: z.string().default("postgres://peppa:peppa@127.0.0.1:5433/peppa"),
|
||||
// Peppa's SQLite database file (PEP-36); default ~/.peppa/peppa.db.
|
||||
PEPPA_DB: z.string().optional(),
|
||||
// The old Postgres database: only the source of `peppa db migrate-to-sqlite`.
|
||||
DATABASE_URL: z.string().optional(),
|
||||
GITEA_URL: z.string().url().default("https://git.telecom.quest"),
|
||||
GITEA_TOKEN: z.string().optional(),
|
||||
GITEA_TEMPLATE_REPO: z.string().default("peppa-bot/template"),
|
||||
@ -15,12 +18,13 @@ const schema = z.object({
|
||||
GITEA_OAUTH_CLIENT_SECRET: z.string().optional(),
|
||||
});
|
||||
|
||||
export type Env = z.infer<typeof schema>;
|
||||
export type Env = z.infer<typeof schema> & { PEPPA_DB: string };
|
||||
|
||||
export function loadEnv(source: NodeJS.ProcessEnv = process.env): Env {
|
||||
const env = schema.parse(source);
|
||||
env.PEPPA_WORKSPACES = env.PEPPA_WORKSPACES.replace(/^~(?=$|\/)/, homedir());
|
||||
return env;
|
||||
const db = (env.PEPPA_DB ?? `${source.PEPPA_HOME ?? `${homedir()}/.peppa`}/peppa.db`).replace(/^~(?=$|\/)/, homedir());
|
||||
return { ...env, PEPPA_DB: db };
|
||||
}
|
||||
|
||||
/** The Peppa checkout; bins, hooks and the template are resolved from it. */
|
||||
|
||||
@ -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
|
||||
|
||||
18
packages/testkit/src/storage-worker.ts
Normal file
18
packages/testkit/src/storage-worker.ts
Normal file
@ -0,0 +1,18 @@
|
||||
// A separate Peppa process for storage tests (PEP-36): opens PEPPA_DB itself, like a hook
|
||||
// or an MCP server does, and writes.
|
||||
// node storage-worker.ts settings <n> <tag> n settings writes (heartbeat-like)
|
||||
// node storage-worker.ts task <projectId> one createTask (per-project numbering)
|
||||
import { createDb } from "@peppa/db";
|
||||
import { createTask, setSetting } from "@peppa/core";
|
||||
|
||||
const [mode, a, b] = process.argv.slice(2);
|
||||
const db = createDb();
|
||||
if (mode === "settings") {
|
||||
for (let i = 0; i < Number(a); i++) await setSetting(db, `storage:${b}:${i}`, { i, pid: process.pid });
|
||||
} else if (mode === "task") {
|
||||
const t = await createTask(db, { projectId: Number(a), title: `from ${process.pid}` });
|
||||
process.stdout.write(String(t.task.number));
|
||||
} else {
|
||||
throw new Error(`unknown mode ${mode}`);
|
||||
}
|
||||
db.$client.close();
|
||||
@ -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 {}
|
||||
|
||||
@ -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/);
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
// (controlled clock, mock-telegram, the real bot), `peppa status`.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, before, beforeEach, describe, test } from "node:test";
|
||||
@ -38,7 +40,7 @@ async function queued(chatId: number): Promise<string[]> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(telegramOutbox)
|
||||
.where(sql`${telegramOutbox.dedupeKey} like 'mon:%' and ${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`)
|
||||
.where(sql`${telegramOutbox.dedupeKey} like 'mon:%' and cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`)
|
||||
.orderBy(telegramOutbox.id);
|
||||
return rows.map((r) => String(r.params.text));
|
||||
}
|
||||
@ -53,7 +55,7 @@ before(async () => {
|
||||
await core.setAllowedLogins(db, [ADMIN.login, OTHER.login]);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.execute(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`);
|
||||
db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`);
|
||||
await db.delete(telegramOutbox);
|
||||
await core.setPlatformAdmins(db, [ADMIN.login]);
|
||||
await pair(ADMIN.login, ADMIN.chatId, 9001);
|
||||
@ -103,14 +105,15 @@ describe("Health-эндпоинт", () => {
|
||||
});
|
||||
|
||||
test("БД недоступна", async () => {
|
||||
const dead = createDb("postgres://peppa:peppa@127.0.0.1:9/nothing");
|
||||
// A database file without Peppa's tables (deleted and recreated, or the wrong file).
|
||||
const dead = createDb(join(mkdtempSync(join(tmpdir(), "peppa-dead-")), "peppa.db"));
|
||||
const t0 = Date.now();
|
||||
const r = await core.healthReport(dead, { version: "0.15.0" });
|
||||
assert.ok(Date.now() - t0 < 3500);
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.db.ok, false);
|
||||
assert.ok(r.db.error);
|
||||
await dead.$client.end({ timeout: 0 }).catch(() => {});
|
||||
dead.$client.close();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
197
packages/testkit/test/storage.test.ts
Normal file
197
packages/testkit/test/storage.test.ts
Normal file
@ -0,0 +1,197 @@
|
||||
// PEP-36: one SQLite file for every Peppa process — concurrent writers, live updates
|
||||
// without Postgres NOTIFY, and the one-time move of the data from Postgres.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, teardown } from "./helpers.ts";
|
||||
import { createDb, events, projects, settings } from "@peppa/db";
|
||||
import type { PeppaNotification } from "@peppa/core";
|
||||
import { like, sql } from "drizzle-orm";
|
||||
import postgres from "postgres";
|
||||
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
const WORKER = join(ROOT, "packages/testkit/src/storage-worker.ts");
|
||||
const run = promisify(execFile);
|
||||
const worker = (...args: string[]) => run(process.execPath, [WORKER, ...args], { env: process.env, encoding: "utf8" });
|
||||
|
||||
after(teardown);
|
||||
|
||||
describe("Одна база SQLite для всех процессов", () => {
|
||||
test("Scenario: 20 процессов открывают базу одновременно и пишут — ни одной ошибки, ни одной потерянной записи", async () => {
|
||||
const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => worker("settings", "25", `p${i}`)));
|
||||
const failed = results.filter((r) => r.status === "rejected");
|
||||
assert.equal(failed.length, 0, failed.map((r) => String((r as PromiseRejectedResult).reason)).join("\n"));
|
||||
const [{ n }] = await db.select({ n: sql<number>`count(*)` }).from(settings).where(like(settings.key, "storage:%"));
|
||||
assert.equal(n, 20 * 25);
|
||||
});
|
||||
|
||||
test("Scenario: задачи из разных процессов получают разные номера подряд", async () => {
|
||||
const [p] = await db
|
||||
.insert(projects)
|
||||
.values({ slug: "storage", key: "STO", name: "STO", giteaOwner: "o", giteaRepo: "storage", workspacePath: "/tmp/storage" })
|
||||
.returning();
|
||||
const numbers = (await Promise.all(Array.from({ length: 10 }, () => worker("task", String(p!.id))))).map((r) => Number(r.stdout));
|
||||
assert.deepEqual([...numbers].sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
||||
});
|
||||
|
||||
// drizzle's SQLite transactions are synchronous: with an async callback everything after the
|
||||
// first await would silently run outside the transaction. The driver makes it a loud error.
|
||||
test("транзакция с async-колбэком отклоняется с понятной ошибкой", async () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
db.transaction(async (tx) => {
|
||||
await tx.insert(projects).values({ slug: "async", key: "ASY", name: "ASY", giteaOwner: "o", giteaRepo: "async", workspacePath: "/tmp/a" });
|
||||
}),
|
||||
/must be synchronous/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Живые обновления без Postgres", () => {
|
||||
test("notify() будит подписчика по сокету", async () => {
|
||||
const got: PeppaNotification[] = [];
|
||||
const stop = await core.listenEvents("bot", (n) => got.push(n));
|
||||
try {
|
||||
await core.notify(db, { type: "question", questionId: 42 });
|
||||
for (let i = 0; i < 40 && got.length === 0; i++) await new Promise((r) => setTimeout(r, 25));
|
||||
assert.deepEqual(got, [{ type: "question", questionId: 42 }]);
|
||||
} finally {
|
||||
await stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("Scenario: сокет подписки недоступен — запись другого процесса видна по data_version", async () => {
|
||||
assert.ok(!existsSync(core.eventsSocket("bot")));
|
||||
const t0 = Date.now();
|
||||
await core.notify(db, { type: "progress", eventId: 1 }); // nobody listens: returns at once
|
||||
assert.ok(Date.now() - t0 < 100);
|
||||
const v = db.$client.dataVersion();
|
||||
await worker("settings", "1", "dv");
|
||||
assert.notEqual(db.$client.dataVersion(), v);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Резервная копия базы", () => {
|
||||
test("Scenario: ночная копия открывается сама по себе, копий не больше 7", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "peppa-backups-"));
|
||||
for (let d = 1; d <= 8; d++) writeFileSync(join(dir, `peppa-2026-10-0${d}.db`), "old");
|
||||
const r = await core.backupDb(db, { dir, now: new Date("2026-11-13T03:00:00Z") });
|
||||
assert.ok(r.file?.endsWith("peppa-2026-11-13.db"));
|
||||
const copy = createDb(r.file!, { readOnly: true });
|
||||
assert.equal((await copy.select().from(projects)).length, (await db.select().from(projects)).length);
|
||||
copy.$client.close();
|
||||
const left = readdirSync(dir).sort();
|
||||
assert.equal(left.length, 7);
|
||||
assert.equal(left.at(-1), "peppa-2026-11-13.db");
|
||||
assert.deepEqual(await core.backupDb(db, { dir, now: new Date("2026-11-13T12:00:00Z") }), { skipped: true });
|
||||
});
|
||||
|
||||
test("Scenario: копия не удалась — неполного файла нет, база работает", async () => {
|
||||
const base = mkdtempSync(join(tmpdir(), "peppa-backups-"));
|
||||
const dir = join(base, "not-a-dir");
|
||||
writeFileSync(dir, "a file where the backup dir should be");
|
||||
const logs: string[] = [];
|
||||
const r = await core.backupDb(db, { dir, force: true, log: (m) => logs.push(m) });
|
||||
assert.ok(r.error);
|
||||
assert.match(logs.join("\n"), /Резервная копия базы Пеппы не сделана/);
|
||||
assert.equal(readdirSync(base).length, 1);
|
||||
await core.setSetting(db, "storage:after-backup", 1);
|
||||
});
|
||||
});
|
||||
|
||||
// The move needs a Postgres server to read from (Peppa's own on the dev machine, the host's in CI).
|
||||
const PG = process.env.PEPPA_TEST_PG ?? "postgres://peppa:peppa@127.0.0.1:5433";
|
||||
const pgReachable = await (async () => {
|
||||
const c = postgres(`${PG}/postgres`, { max: 1, connect_timeout: 3, onnotice: () => {} });
|
||||
try {
|
||||
await c`select 1`;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
await c.end({ timeout: 1 });
|
||||
}
|
||||
})();
|
||||
|
||||
describe("Перенос данных из Postgres", { skip: pgReachable ? false : `no Postgres at ${PG}` }, () => {
|
||||
const name = `peppa_test_m2s_${process.pid}`;
|
||||
const admin = () => postgres(`${PG}/postgres`, { max: 1, onnotice: () => {} });
|
||||
const legacy = join(ROOT, "packages/cli/legacy-pg-migrations");
|
||||
|
||||
/** A Postgres database with the last Postgres schema of Peppa and some data. */
|
||||
async function source(seed: (pg: postgres.Sql) => Promise<void>): Promise<string> {
|
||||
const a = admin();
|
||||
await a.unsafe(`drop database if exists ${name}`);
|
||||
await a.unsafe(`create database ${name}`);
|
||||
await a.end();
|
||||
const pg = postgres(`${PG}/${name}`, { max: 1, onnotice: () => {} });
|
||||
for (const f of readdirSync(legacy).filter((f) => f.endsWith(".sql")).sort())
|
||||
for (const stmt of readFileSync(join(legacy, f), "utf8").split("--> statement-breakpoint")) if (stmt.trim()) await pg.unsafe(stmt);
|
||||
await seed(pg);
|
||||
await pg.end();
|
||||
return `${PG}/${name}`;
|
||||
}
|
||||
after(async () => {
|
||||
const a = admin();
|
||||
await a.unsafe(`drop database if exists ${name}`);
|
||||
await a.end();
|
||||
});
|
||||
|
||||
test("Scenario: успешный перенос — строки, даты, JSON, boolean и id чата на месте", async () => {
|
||||
const url = await source(async (pg) => {
|
||||
await pg`insert into users (gitea_id, login, telegram_chat_id) values (1, 'mock-pm', 9007199254740991)`;
|
||||
await pg`insert into projects (slug, key, name, gitea_owner, gitea_repo, workspace_path, owner_id, next_task_number) values ('pay', 'PAY', 'Pay', 'o', 'pay', '/tmp/pay', 1, 2)`;
|
||||
await pg`insert into tasks (project_id, number, title, status) values (1, 1, 'Первая', 'in_progress')`;
|
||||
await pg`insert into sessions (project_id, task_id, tmux_name, status) values (1, 1, 'peppa-PAY-1-s1', 'running')`;
|
||||
await pg`insert into questions (project_id, task_id, session_id, kind, text, options, awaiting_hook) values (1, 1, 1, 'permission', 'Удалить build?', '["Да","Нет"]', true)`;
|
||||
for (let i = 0; i < 107; i++) await pg`insert into events (project_id, task_id, type, payload) values (1, 1, 'progress', ${pg.json({ i })})`;
|
||||
await pg`insert into telegram_outbox (dedupe_key, method, params, question_id, status, telegram_message_id) values ('q:1', 'sendMessage', ${pg.json({ chat_id: 4242, text: "?" })}, 1, 'sent', 77)`;
|
||||
});
|
||||
const file = join(mkdtempSync(join(tmpdir(), "peppa-m2s-")), "peppa.db");
|
||||
const out = execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["db", "migrate-to-sqlite", file], {
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, DATABASE_URL: url },
|
||||
});
|
||||
assert.match(out, /перенесено, расхождений нет/);
|
||||
assert.match(out, /events\s+107/);
|
||||
const m = createDb(file);
|
||||
const q = await m.query.questions.findFirst({ with: { session: true } });
|
||||
assert.deepEqual(q!.options, ["Да", "Нет"]);
|
||||
assert.equal(q!.awaitingHook, true);
|
||||
assert.ok(q!.createdAt instanceof Date && Math.abs(q!.createdAt.getTime() - Date.now()) < 60_000);
|
||||
assert.equal(q!.session!.tmuxName, "peppa-PAY-1-s1");
|
||||
assert.equal((await m.query.users.findFirst())!.telegramChatId, 9007199254740991);
|
||||
assert.equal((await m.select().from(events)).length, 107);
|
||||
assert.equal((await core.questionByTelegramMessage(m, 4242, 77))?.id, q!.id); // json filter over migrated params
|
||||
// The new file is a working Peppa database: numbering continues.
|
||||
const t = await core.createTask(m, { projectId: 1, title: "Вторая" });
|
||||
assert.equal(t.key, "PAY-2");
|
||||
m.$client.close();
|
||||
});
|
||||
|
||||
test("Scenario: расхождение — нарушение внешнего ключа, файла нет, Postgres не тронут", async () => {
|
||||
const url = await source(async (pg) => {
|
||||
await pg`insert into projects (slug, key, name, gitea_owner, gitea_repo, workspace_path) values ('pay', 'PAY', 'Pay', 'o', 'pay', '/tmp/pay')`;
|
||||
await pg`alter table questions drop constraint questions_session_id_sessions_id_fk`;
|
||||
await pg`insert into questions (project_id, session_id, kind, text) values (1, 999, 'question', 'Висящая ссылка')`;
|
||||
});
|
||||
const file = join(mkdtempSync(join(tmpdir(), "peppa-m2s-")), "peppa.db");
|
||||
let err = "";
|
||||
try {
|
||||
execFileSync(join(ROOT, "packages/cli/bin/peppa"), ["db", "migrate-to-sqlite", file], { encoding: "utf8", stdio: "pipe", env: { ...process.env, DATABASE_URL: url } });
|
||||
} catch (e) {
|
||||
err = String((e as { stderr: string }).stderr);
|
||||
assert.equal((e as { status: number }).status, 1);
|
||||
}
|
||||
assert.match(err, /questions: нарушение внешнего ключа/);
|
||||
assert.ok(!existsSync(file) && !existsSync(`${file}.migrating`));
|
||||
const pg = postgres(url, { max: 1, onnotice: () => {} });
|
||||
assert.equal((await pg`select count(*)::int n from questions`)[0]!.n, 1);
|
||||
await pg.end();
|
||||
});
|
||||
});
|
||||
6
pnpm-lock.yaml
generated
6
pnpm-lock.yaml
generated
@ -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
|
||||
|
||||
@ -7,8 +7,9 @@
|
||||
# scripts/ci.sh --repeat <N> run the e2e suite N times in a row (flake hunting)
|
||||
# scripts/ci.sh --skip-build skip `next build`
|
||||
#
|
||||
# Every run uses its own database peppa_test_ci_<pid> or $PEPPA_TEST_DB (dropped at exit), so it can run next
|
||||
# to other worktrees' suites. Logs of --pr runs: ~/.peppa/ci/<sha>.log.
|
||||
# Every e2e test file uses its own SQLite file in a temp dir, so runs never share state; the
|
||||
# Postgres → SQLite migration test makes (and drops) its own database on $PEPPA_TEST_PG.
|
||||
# Logs of --pr runs: ~/.peppa/ci/<sha>.log.
|
||||
set -uo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PR="" REPEAT=1 BUILD=1
|
||||
@ -57,10 +58,6 @@ if [ -n "$PR" ]; then
|
||||
fi
|
||||
|
||||
cd "$ROOT"
|
||||
# The Actions job passes PEPPA_TEST_DB per run: pids inside job containers repeat.
|
||||
DB="${PEPPA_TEST_DB:-peppa_test_ci_$$}"
|
||||
cleanup() { docker exec peppa-postgres dropdb -U peppa --if-exists "$DB" >/dev/null 2>&1; }
|
||||
trap cleanup EXIT
|
||||
|
||||
step() { # <name> <command...>
|
||||
local name=$1; shift
|
||||
@ -72,6 +69,6 @@ step() { # <name> <command...>
|
||||
step typecheck pnpm -r typecheck
|
||||
[ "$BUILD" = 1 ] && step "web build" pnpm --filter @peppa/web build
|
||||
for i in $(seq 1 "$REPEAT"); do
|
||||
step "e2e $i/$REPEAT" env PEPPA_TEST_DB="$DB" pnpm --filter @peppa/testkit test
|
||||
step "e2e $i/$REPEAT" pnpm --filter @peppa/testkit test
|
||||
done
|
||||
echo "ci: all green"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user