+
+
+
{TOOLS.map(([name, what]) => (
-
- {name}
- {what}
+
+ {name}
+ {what}
))}
+
+
- CI/CD
-
- Каждый PR агента проверяет Gitea Actions: install , lint ,{" "}
- typecheck , test , build . Команды —
- в .peppa/project.json → checks (заполняет агент на первой задаче), workflow приходит из
- шаблона; в старый проект — командой peppa ci connect KEY (PR от Пеппы). Результат виден в
+
+
+ Каждый PR агента проверяет Gitea Actions: install , lint ,{" "}
+ typecheck , test , build . Команды —
+ в .peppa/project.json → checks (заполняет агент на первой задаче), workflow приходит из
+ шаблона; в старый проект — командой peppa ci connect KEY (PR от Пеппы). Результат виден в
карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без
- конфликтов. PR, меняющий конвейер (.gitea/ , checks ,{" "}
- deploy ), сам не мержится никогда.
+ конфликтов. PR, меняющий конвейер (.gitea/ , checks ,{" "}
+ deploy ), сам не мержится никогда.
-
- Деплой — deploy в project.json и Dockerfile (заготовки в{" "}
- deploy/ ): PR получает preview slug-prN.telecom.quest (удаляется при
- закрытии), мерж выкатывает staging slug-staging.telecom.quest , прод{" "}
- slug-prod.telecom.quest — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
- deploy ). После каждого деплоя — проверка /healthz до 2 минут; не
+
+ Деплой — deploy в project.json и Dockerfile (заготовки в{" "}
+ deploy/ ): PR получает preview slug-prN.telecom.quest (удаляется при
+ закрытии), мерж выкатывает staging slug-staging.telecom.quest , прод{" "}
+ slug-prod.telecom.quest — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
+ deploy ). После каждого деплоя — проверка /healthz до 2 минут; не
прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
+
-
Telegram
-
+
+
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
проекта: сообщением, задачей или с кнопками «В бэклог / В работу / Игнорировать».
-
+
+
);
}
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index f77a7464..1ff408b1 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -1,25 +1,50 @@
import { notFound } from "next/navigation";
-import { AutoRefresh } from "@/components/AutoRefresh";
-import { Flash, Notice, SessionCard } from "@/components/ui";
-import { Board, type Card } from "@/components/Board";
-import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner";
-import { requireUser } from "@/lib/auth";
-import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
+import { ExternalLink, Plus, Rocket, Target } from "lucide-react";
+import { columnOf, currentReleases, describeRepo, listReleases, bugsinkWebhookBase, type Release } from "@peppa/runner";
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
-import { bugsinkWebhookBase } from "@peppa/runner";
+import { AutoRefresh } from "@/components/AutoRefresh";
+import { PanelSection } from "@/components/ActivityAside";
+import { Board, type Card } from "@/components/Board";
+import { Hidden, SessionCard } from "@/components/cards";
+import { Disclosure, Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentsSection } from "@/components/Incidents";
-import { db } from "@/lib/db";
-import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
+import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
-const RELEASE_STATUS: Record = {
- deploying: "⏳ выкатывается",
- healthy: "✅ работает",
- rolled_back: "↩️ откат",
- failed: "❌ не поднялся",
- removed: "🗑 удалён",
+const RELEASE_STATUS: Record = {
+ deploying: { label: "выкатывается", tone: "info" },
+ healthy: { label: "работает", tone: "ok" },
+ rolled_back: { label: "откат", tone: "warn" },
+ failed: { label: "не поднялся", tone: "danger" },
+ removed: { label: "удалён", tone: "muted" },
};
+function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
+ return (
+
+
{name}
+ {r ? (
+
+ {r.sha.slice(0, 7)}
+ {r.host && (
+
+ {r.host}
+
+ )}
+
+ ) : (
+
нет
+ )}
+
+ );
+}
+
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) {
const user = await requireUser();
const { key } = await params;
@@ -53,83 +78,197 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
column: columnOf(t.status),
goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null,
}));
+
+ const aside = (
+
+
+
+ Где
+
+ {repo.fullName}
+
+ Пространство
+
+ {p.giteaOwner}
+ {repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
+
+ Видимость
+ {repoVisibilityLabel(repo.private)}
+ Кто видит
+ {repoAudience(repo)}
+ Рабочая копия
+ {p.workspacePath}
+
+
+
+ Открыть в Gitea
+
+
+
+
+
+
+
+ {team.owner?.login ?? "—"}
+ владелец · агенты работают на его подписке Claude
+
+ {team.members.map((m) => (
+
+
+ {m.login}
+ участник{noRepoAccess(m.login) && " · нет доступа к репозиторию"}
+
+ {(isOwner || m.id === user.id) && (
+
+ )}
+
+ ))}
+ {team.invites.map((login) => (
+
+
+ {login}
+ приглашён · появится после первого входа в Пеппу
+
+ {isOwner && (
+
+ )}
+
+ ))}
+
+ {isOwner && (
+
+ )}
+ {isOwner && missingAccess && (
+
+ )}
+ {isOwner && Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.
}
+
+
+ );
+
return (
-
+
{created && !error && (
- Репозиторий создан: {repo.fullName} ({repoVisibilityLabel(repo.private)}).{" "}
- Открыть в Gitea
+ Репозиторий создан: {repo.fullName} ({repoVisibilityLabel(repo.private)}).
+
+ Открыть в Gitea
+
)}
-
- {p.key} {p.name}
-
-
- {repo.fullName} · {repoVisibilityLabel(repo.private)}
-
+ Проекты}
+ title={
+ <>
+ {p.key} {p.name}
+ >
+ }
+ >
+ {repo.fullName} · {repoVisibilityLabel(repo.private)}
+
- {groups.map(({ goal }) => (
-
- + Задача{goal ? ` · 🎯 ${goal.title}` : " без цели"}
-
);
}
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 46337a96..4a9d6330 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -1,12 +1,12 @@
-import Link from "next/link";
import { listUserProjects } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
-import { Flash, ProjectList, QuestionCard, SessionCard } from "@/components/ui";
+import { ActivityAside } from "@/components/ActivityAside";
+import { ProjectList, QuestionCard, SessionCard } from "@/components/cards";
+import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common";
+import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { activeSessions, inbox } from "@/lib/queries";
-import { Workspace } from "@/components/Workspace";
-import { ActivityAside } from "@/components/ActivityAside";
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@@ -16,23 +16,16 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
}>
- Главная
-
- Вопросы агентов {items.length > 0 && {items.length} }
- {items.length === 0 ? Агентам от тебя ничего не нужно.
: items.map((q) => )}
-
-
-
- Активные раннеры все раннеры →
-
- {sessions.length === 0 ? Сейчас ничего не запущено.
: sessions.map((s) => )}
-
-
-
- Мои проекты все проекты →
-
+ {items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}
+
+ {items.length === 0 ? Агентам от тебя ничего не нужно. : items.map((q) => )}
+
+ все раннеры}>
+ {sessions.length === 0 ? Сейчас ничего не запущено. : sessions.map((s) => )}
+
+
+
);
}
diff --git a/apps/web/app/(app)/projects/new/page.tsx b/apps/web/app/(app)/projects/new/page.tsx
index 520a6fa6..d216fda7 100644
--- a/apps/web/app/(app)/projects/new/page.tsx
+++ b/apps/web/app/(app)/projects/new/page.tsx
@@ -1,10 +1,22 @@
import { giteaForUser, type GiteaOrg } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
-import { Flash } from "@/components/ui";
+import { Flash, PageHeader } from "@/components/common";
+import { Hidden } from "@/components/cards";
+import { Button } from "@/components/ui/button";
+import { Input, Label, NativeSelect } from "@/components/ui/input";
+import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { createProjectAction } from "../../actions";
-import { Workspace } from "@/components/Workspace";
+
+function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
+ return (
+
+
+ {children}
+
+ );
+}
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@@ -19,64 +31,56 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
}
return (
-
+
);
}
diff --git a/apps/web/app/(app)/projects/page.tsx b/apps/web/app/(app)/projects/page.tsx
index 4fc5d361..d5cddd57 100644
--- a/apps/web/app/(app)/projects/page.tsx
+++ b/apps/web/app/(app)/projects/page.tsx
@@ -1,9 +1,12 @@
import Link from "next/link";
+import { Plus } from "lucide-react";
import { listUserProjects } from "@peppa/core";
-import { Flash, ProjectList } from "@/components/ui";
+import { ProjectList } from "@/components/cards";
+import { Flash, PageHeader } from "@/components/common";
+import { Button } from "@/components/ui/button";
+import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { Workspace } from "@/components/Workspace";
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@@ -12,12 +15,19 @@ export default async function Projects({ searchParams }: { searchParams: Promise
return (
-
- Проекты{" "}
-
- Новый проект
-
-
+
+
+
+ Новый проект
+
+
+ }
+ >
+ Свои и общие проекты: доска задач, релизы, ошибки из прода, участники.
+
);
diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx
index 7f90ce4b..9644c1b3 100644
--- a/apps/web/app/(app)/runners/page.tsx
+++ b/apps/web/app/(app)/runners/page.tsx
@@ -1,10 +1,12 @@
import Link from "next/link";
import { listUserSessions, RUNNER_FILTERS, type RunnerFilter } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
-import { Flash, SessionCard } from "@/components/ui";
+import { SessionCard } from "@/components/cards";
+import { Empty, Flash, PageHeader } from "@/components/common";
+import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { Workspace } from "@/components/Workspace";
+import { cn } from "@/lib/utils";
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
{ key: undefined, label: "Все" },
@@ -26,16 +28,22 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
- Раннеры
- Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.
-
+ Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.
+
{FILTERS.map((x) => (
-
- {x.label} {count(x.key)}
+
+ {x.label} {count(x.key)}
))}
- {shown.length === 0 ? {filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}
: shown.map((s) => )}
+
+ {shown.length === 0 ? {filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."} : shown.map((s) => )}
+
);
}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 13c3717c..7cf42ad8 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -1,10 +1,30 @@
+import { ExternalLink } from "lucide-react";
import { connectedApps } from "@peppa/core";
-import { ago, Flash } from "@/components/ui";
+import { pendingClaudeSetup } from "@peppa/runner";
+import { Hidden } from "@/components/cards";
+import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
-import { pendingClaudeSetup } from "@peppa/runner";
import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions";
-import { Workspace } from "@/components/Workspace";
+
+const back = { back: "/settings" };
+
+/** A connected thing: title + details on the left, actions on the right. */
+function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
+ return (
+
+
+
{title}
+ {children &&
{children}
}
+
+ {actions && {actions}
}
+
+ );
+}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) {
const user = await requireUser();
@@ -14,106 +34,118 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const origin = await publicOrigin();
return (
-
-
- Настройки
- Claude
- {claude === "connected" && Claude подключён ✅
}
- {setup ? (
-
-
- 1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):
-
-
Войти в Claude ↗
-
2. Claude покажет код — вставьте его сюда:
-
-
-
- Подключить
-
-
-
- Отменить
-
-
- ) : user.claudeTokenEnc ? (
-
-
-
Claude подключён
-
-
-
- Переподключить
-
-
-
- Отключить
-
-
- ) : (
-
-
- Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой
- токен через claude setup-token , вход делаете вы сами по ссылке.
+
+ ) : (
+
+
+ Подключить Claude
+
+ }
+ >
+ Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой токен через{" "}
+ claude setup-token , вход делаете вы сами по ссылке.
+
+ )}
+
+
+ {user.telegramChatId ? (
+
+
+ Отвязать
+
+ }
+ >
+ Вопросы агентов из ваших и общих проектов приходят в этот чат.
+
+ ) : (
+
+
+ Привязать Telegram
+
+ }
+ >
+ Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
+
+ )}
+
+
+ Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.
+ {origin}/mcp
+
+ Как подключить и что спрашивать — в Помощи .
-
-
- Подключить Claude
-
-
- )}
-
Telegram
- {user.telegramChatId ? (
-
-
-
Telegram привязан{user.telegramUsername ? ` (@${user.telegramUsername})` : ""}
-
Вопросы агентов из ваших и общих проектов приходят в этот чат.
-
-
-
- Отвязать
-
-
- ) : (
-
-
- Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
-
-
-
- Привязать Telegram
-
-
- )}
-
MCP для ChatGPT и других клиентов
-
- Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент
- зарегистрируется сам, вы подтвердите доступ на экране Пеппы.
-
-
{origin}/mcp
-
Как подключить и что спрашивать — в Помощи .
-
Подключённые приложения
- {apps.length === 0 ? (
-
Нет подключённых приложений.
- ) : (
- apps.map((a) => (
-
-
-
{a.name}
-
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
-
-
-
-
- Отозвать
-
-
- ))
- )}
-
+
+
+ {apps.length === 0 ? (
+ Нет подключённых приложений.
+ ) : (
+ apps.map((a) => (
+
+
+ Отозвать
+
+ }
+ >
+ с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
+
+ ))
+ )}
+
+
);
}
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index 93f4e933..c95764ca 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -1,15 +1,22 @@
import Link from "next/link";
import { notFound } from "next/navigation";
-import { AutoRefresh } from "@/components/AutoRefresh";
-import { ago, Badge, Flash, QuestionCard, SessionCard } from "@/components/ui";
-import { requireUser } from "@/lib/auth";
-import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
-import { db } from "@/lib/db";
+import { eq } from "drizzle-orm";
+import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react";
import { goals } from "@peppa/db";
import { taskCiSummary } from "@peppa/core";
-import { eq } from "drizzle-orm";
-import { startTaskSession } from "../../actions";
+import { AutoRefresh } from "@/components/AutoRefresh";
+import { PanelSection } from "@/components/ActivityAside";
+import { Hidden, QuestionCard, SessionCard } from "@/components/cards";
+import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
+import { Button } from "@/components/ui/button";
+import { Input, NativeSelect } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
+import { startTaskSession } from "../../actions";
+
+const CI_ICON = { success: , failure: , pending: };
export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@@ -23,82 +30,108 @@ export default async function TaskPage({ params, searchParams }: { params: Promi
const artifacts = openspecArtifacts(project, task.openspecChange);
const ci = await taskCiSummary(db, ref);
const back = `/t/${ref.key}`;
+
+ const aside = (
+
+
+
+ {CI_ICON[ci.state as keyof typeof CI_ICON]}
+ {ci.runUrl ?
{ci.label} : ci.label}
+ {ci.sha &&
{ci.sha.slice(0, 7)} }
+
+ {task.ciAttempts > 0 && красных подряд: {task.ciAttempts}
}
+ {ci.failed.map((f) => (
+
+
+ {f.check}
+ {f.runUrl && лог }
+
+ }
+ >
+ {f.logTail && {f.logTail.split("\n").slice(-60).join("\n")} }
+
+ ))}
+
+
+ {events.length === 0 ? (
+ Событий нет.
+ ) : (
+
+ {events.map((e) => (
+
+ {ago(e.createdAt)} {e.type} {" "}
+ {e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
+
+ ))}
+
+ )}
+
+
+ );
+
return (
-
+
-
- {project.name}
- {goal && <> · 🎯 {goal.title}>}
-
-
- {ref.key} {task.title}
-
- {task.prUrl && PR
}
-
- Проверки
-
- {ci.state === "success" ? "✅ " : ci.state === "failure" ? "❌ " : ci.state === "pending" ? "⏳ " : ""}
- {ci.runUrl ? {ci.label} : ci.label}
- {ci.sha && · {ci.sha.slice(0, 7)} }
- {task.ciAttempts > 0 && · красных подряд: {task.ciAttempts} }
-
- {ci.failed.map((f) => (
-
-
- ❌ {f.check} {f.runUrl && лог }
-
- {f.logTail && {f.logTail.split("\n").slice(-60).join("\n")} }
-
- ))}
-
- {task.description || Без описания }
+
+ {project.name}
+ {goal && · ◎ {goal.title} }
+ >
+ }
+ title={
+ <>
+ {ref.key} {task.title}
+ >
+ }
+ actions={
+ task.prUrl && (
+
+
+
+ PR
+
+
+ )
+ }
+ />
+ {task.description || Без описания }
-
+
-
- Вопросы
- {questions.length === 0 ? Вопросов не было.
: questions.map((q) => )}
-
+
+ {questions.length === 0 ? Вопросов не было. : questions.map((q) => )}
+
-
- OpenSpec {task.openspecChange && {task.openspecChange} }
+ OpenSpec {task.openspecChange && {task.openspecChange} }>}>
{artifacts?.length ? (
artifacts.map((a) => (
-
- {a.name}
- {a.text}
-
+ {a.name}}>
+ {a.text}
+
))
) : (
- Change ещё не создан.
+ Change ещё не создан.
)}
-
-
-
- События
-
- {events.map((e) => (
-
- {ago(e.createdAt)} {e.type} {" "}
- {e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
-
- ))}
-
-
+
);
}
diff --git a/apps/web/app/app.css b/apps/web/app/app.css
index bc13d895..f150bd47 100644
--- a/apps/web/app/app.css
+++ b/apps/web/app/app.css
@@ -1,5 +1,4 @@
@import "tailwindcss";
-@import "./legacy.css" layer(base);
/* Theme tokens (shadcn/ui naming): light in :root, dark — the default — in .dark (PEP-38). */
@custom-variant dark (&:where(.dark, .dark *));
diff --git a/apps/web/app/legacy.css b/apps/web/app/legacy.css
deleted file mode 100644
index 3cfee729..00000000
--- a/apps/web/app/legacy.css
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Pre-PEP-38 page styles, imported into the `base` layer so Tailwind utilities win. Removed page by page in stage 2. */
-
-a { color: var(--primary); text-decoration: none; }
-a:hover { text-decoration: underline; }
-h1 { font-size: 1.5rem; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
-h2 { font-size: 1.1rem; margin: 28px 0 10px; }
-.mono, code, pre { font-family: var(--font-mono); font-size: 0.9em; }
-.muted { color: var(--muted-foreground); }
-.empty { color: var(--muted-foreground); padding: 12px 0; }
-
-h2 .more { font-size: 0.85rem; font-weight: 400; margin-left: 8px; }
-.filters { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0 4px; }
-.filters a { padding: 4px 12px; border: 1px solid var(--border); border-radius: 999px; color: var(--foreground); background: var(--card); }
-.filters a:hover { text-decoration: none; border-color: var(--muted-foreground); }
-.filters a.active { border-color: var(--primary); box-shadow: inset 0 0 0 1px var(--primary); }
-.session header.row { flex-wrap: wrap; row-gap: 2px; }
-.session header .mono { white-space: nowrap; }
-.session .title { flex: 1 1 12em; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.narrow { max-width: 560px; }
-.crumbs { margin: 0 0 4px; color: var(--muted-foreground); }
-.desc { white-space: pre-wrap; }
-
-.card {
- background: var(--card); border: 1px solid var(--border); border-radius: var(--radius);
- padding: 14px 16px; margin: 10px 0;
-}
-.q { border-left: 4px solid var(--info); }
-.q-approval { border-left-color: var(--primary); }
-.q-permission { border-left-color: var(--warn); }
-.q-attention { border-left-color: var(--ok); }
-.q.answered { opacity: 0.7; border-left-color: var(--border); }
-.kind { font-weight: 600; }
-.qtext { white-space: pre-wrap; margin: 8px 0; max-height: 18em; overflow: auto; }
-.attach { display: block; color: var(--muted-foreground); margin: 6px 0; overflow-x: auto; }
-.count { background: var(--primary); color: var(--primary-foreground); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; }
-
-.row { display: flex; gap: 8px; align-items: center; }
-.row.wrap { flex-wrap: wrap; }
-.grow { flex: 1; min-width: 0; }
-.row > input[type=text] { flex: 1; min-width: 0; }
-.stack { display: flex; flex-direction: column; gap: 12px; margin: 10px 0; }
-label { display: flex; flex-direction: column; gap: 4px; font-weight: 500; }
-label.inline { flex-direction: row; align-items: center; font-weight: 400; }
-fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 8px 12px; }
-.answer { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
-
-input[type=text], textarea, select {
- font: inherit; color: var(--foreground); background: var(--background);
- border: 1px solid var(--border); border-radius: 8px; padding: 7px 10px; width: 100%;
-}
-input.short { width: 8em; }
-textarea { resize: vertical; }
-input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--primary); outline-offset: 1px; }
-
-button, .button {
- font: inherit; cursor: pointer; border-radius: 8px; padding: 7px 14px;
- border: 1px solid var(--border); background: var(--card); color: var(--foreground); white-space: nowrap;
- display: inline-block;
-}
-button:hover, .button:hover { border-color: var(--muted-foreground); text-decoration: none; }
-.primary { background: var(--primary); color: var(--primary-foreground); border-color: var(--primary); }
-.danger { color: var(--danger); }
-button.link { border: 0; background: none; padding: 0; color: var(--muted-foreground); }
-
-.badge {
- font-size: 0.75rem; font-weight: 600; border-radius: 999px; padding: 2px 9px;
- background: var(--muted); color: var(--muted-foreground); white-space: nowrap;
-}
-.s-in_progress, .s-running { color: var(--info); }
-.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--primary); }
-.s-review, .s-done { color: var(--ok); }
-.s-blocked, .s-failed, .s-stalled, .s-rate_limited { color: var(--danger); }
-
-.notice { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
-.flash { background: color-mix(in srgb, var(--danger) 12%, var(--card)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; }
-
-ul.tasks, ul.projects, ul.events { list-style: none; padding: 0; margin: 0; }
-ul.tasks li, ul.projects li {
- display: flex; gap: 10px; align-items: center; justify-content: space-between;
- padding: 8px 12px; background: var(--card); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0;
-}
-ul.tasks li a, ul.projects li a { color: var(--foreground); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
-ul.events li { padding: 3px 0; border-bottom: 1px dashed var(--border); overflow-wrap: anywhere; }
-details { margin: 8px 0; }
-summary { cursor: pointer; color: var(--primary); }
-pre.md {
- white-space: pre-wrap; background: var(--muted); border-radius: 8px; padding: 12px;
- max-height: 32em; overflow: auto;
-}
-
-.board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin: 16px 0; }
-.board.busy { opacity: 0.6; pointer-events: none; }
-.col { background: color-mix(in srgb, var(--border) 35%, var(--background)); border-radius: var(--radius); padding: 8px; min-height: 120px; }
-.col.over { outline: 2px dashed var(--primary); }
-.col h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; margin: 4px 4px 8px; color: var(--muted-foreground); }
-.hint { font-size: 0.75rem; margin: -4px 4px 8px; }
-.tcard { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 6px 0; cursor: grab; display: flex; flex-direction: column; gap: 6px; }
-.tcard a { color: var(--foreground); }
-.tcard .goal { font-size: 0.75rem; flex-basis: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.small { font-size: 0.78rem; padding: 3px 8px; }
-details.add { margin: 4px 0; }
-.login { max-width: 420px; margin: 18vh auto; text-align: center; display: flex; flex-direction: column; gap: 14px; align-items: center; }
-.login h1 { font-size: 2rem; justify-content: center; }
-
-@media (max-width: 640px) {
- .session form.grow { flex-basis: 100%; }
- ul.tasks li { flex-direction: column; align-items: flex-start; }
- .board { grid-template-columns: 1fr; }
-}
-
-.consent { text-align: left; align-items: stretch; }
-.consent h1 { justify-content: flex-start; }
-.scopes { margin: 0; padding-left: 20px; }
-.mcp-url { display: block; padding: 10px 12px; background: var(--muted); border-radius: 8px; overflow-x: auto; }
-
-.ok { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
-
-.help ul { padding-left: 20px; }
-.help li { margin: 4px 0; }
-.say { margin: 6px 0; font-style: italic; }
-table.tools { width: 100%; border-collapse: collapse; }
-table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; }
-table.tools td.mono { white-space: nowrap; }
-@media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } }
-
-ul.members { list-style: none; padding: 0; margin: 0 0 10px; }
-ul.members li { display: flex; gap: 10px; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed var(--border); }
-
-
-dl.repo { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0 0 10px; }
-dl.repo dt { color: var(--muted-foreground); }
-dl.repo dd { margin: 0; }
diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index 667e146d..cceff97a 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -1,7 +1,9 @@
import { redirect } from "next/navigation";
import { currentUser, safeNext } from "@/lib/auth";
-import { Flash } from "@/components/ui";
+import { Brand } from "@/components/Brand";
+import { Flash } from "@/components/common";
import { Footer } from "@/components/Footer";
+import { Button } from "@/components/ui/button";
export const dynamic = "force-dynamic";
@@ -9,12 +11,16 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
return (
-
- 🐷 Peppa
- Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.
-
- Войти через Gitea
-
+
+
+
+
Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.
+
+
+ Войти через Gitea
+
+
+
);
}
diff --git a/apps/web/app/oauth/authorize/page.tsx b/apps/web/app/oauth/authorize/page.tsx
index ce003176..086ce7fd 100644
--- a/apps/web/app/oauth/authorize/page.tsx
+++ b/apps/web/app/oauth/authorize/page.tsx
@@ -3,6 +3,9 @@ import { redirect } from "next/navigation";
import { currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { approve, deny } from "./actions";
+import { Brand } from "@/components/Brand";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
export const dynamic = "force-dynamic";
@@ -29,33 +32,35 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
}
const host = p.redirect_uri ? new URL(p.redirect_uri).host : "";
return (
-
- 🐷 Peppa
- {error || !client ? (
- Запрос авторизации некорректен: {error}
- ) : (
- <>
-
- {client.name} ({host}) просит доступ к Пеппе от имени {user.login} .
-
-
- видеть ваши проекты, цели, задачи и вопросы агентов;
- создавать задачи и двигать карточки — перенос в «В работе» запускает агента;
- отвечать на вопросы агентов и принимать ревью.
-
- Отозвать доступ можно в «Настройки → Подключённые приложения».
-
-
-
- Разрешить
-
-
-
- Отклонить
-
-
- >
- )}
+
+
+
+ {error || !client ? (
+ Запрос авторизации некорректен: {error}
+ ) : (
+ <>
+
+ {client.name} ({host}) просит доступ к Пеппе от имени {user.login} .
+
+
+ видеть ваши проекты, цели, задачи и вопросы агентов;
+ создавать задачи и двигать карточки — перенос в «В работе» запускает агента;
+ отвечать на вопросы агентов и принимать ревью.
+
+ Отозвать доступ можно в «Настройки → Подключённые приложения».
+
+
+
+ Разрешить
+
+
+
+ Отклонить
+
+
+ >
+ )}
+
);
}
diff --git a/apps/web/components/ActivityAside.tsx b/apps/web/components/ActivityAside.tsx
index f078ea1e..d7a274b5 100644
--- a/apps/web/components/ActivityAside.tsx
+++ b/apps/web/components/ActivityAside.tsx
@@ -1,5 +1,5 @@
import Link from "next/link";
-import { ago } from "@/components/ui";
+import { ago } from "@/components/common";
import { requireUser } from "@/lib/auth";
import { activeSessions, inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG } from "@/lib/status";
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index cdd94f94..32b17faa 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -3,6 +3,9 @@
import Link from "next/link";
import { useState, useTransition } from "react";
import { moveTaskCard } from "@/app/(app)/actions";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { cn } from "@/lib/utils";
export type Column = "backlog" | "in_progress" | "review" | "done";
export interface Card {
@@ -13,13 +16,18 @@ export interface Card {
goal: string | null;
}
-const COLUMNS: Array<{ id: Column; title: string; hint: string }> = [
- { id: "backlog", title: "Бэклог", hint: "" },
- { id: "in_progress", title: "В работе", hint: "сюда — запустить агента" },
- { id: "review", title: "Ревью", hint: "" },
- { id: "done", title: "Готово", hint: "" },
+const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
+ { id: "backlog", title: "Бэклог", hint: "", dot: "bg-muted-foreground" },
+ { id: "in_progress", title: "В работе", hint: "сюда — запустить агента", dot: "bg-info" },
+ { id: "review", title: "Ревью", hint: "", dot: "bg-ok" },
+ { id: "done", title: "Готово", hint: "", dot: "bg-ok" },
];
-const STATUS: Record = { proposing: "proposal", awaiting_approval: "ждёт PM", blocked: "блок", in_progress: "агент" };
+const STATUS: Record = {
+ proposing: { label: "proposal", tone: "primary" },
+ awaiting_approval: { label: "ждёт PM", tone: "primary" },
+ blocked: { label: "блок", tone: "danger" },
+ in_progress: { label: "агент", tone: "info" },
+};
const NEXT: Partial> = {
backlog: { to: "in_progress", label: "В работу →" },
review: { to: "done", label: "Принять ✓" },
@@ -37,48 +45,59 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
start(() => moveTaskCard(f));
};
return (
-
- {COLUMNS.map((c) => (
-
{
- e.preventDefault();
- setOver(c.id);
- }}
- onDragLeave={() => setOver(null)}
- onDrop={(e) => {
- e.preventDefault();
- setOver(null);
- const key = e.dataTransfer.getData("text/plain");
- const card = cards.find((x) => x.key === key);
- if (card && card.column !== c.id) move(key, c.id);
- }}
- >
-
- {c.title} {cards.filter((x) => x.column === c.id).length}
-
- {c.hint && {c.hint}
}
- {cards
- .filter((x) => x.column === c.id)
- .map((card) => (
- e.dataTransfer.setData("text/plain", card.key)}>
-
- {card.key} {card.title}
+
+ {COLUMNS.map((c) => {
+ const list = cards.filter((x) => x.column === c.id);
+ return (
+
{
+ e.preventDefault();
+ setOver(c.id);
+ }}
+ onDragLeave={() => setOver(null)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(null);
+ const key = e.dataTransfer.getData("text/plain");
+ const card = cards.find((x) => x.key === key);
+ if (card && card.column !== c.id) move(key, c.id);
+ }}
+ >
+
+
+ {c.title}
+ {list.length}
+
+ {c.hint && {c.hint}
}
+ {list.map((card) => (
+ e.dataTransfer.setData("text/plain", card.key)}
+ className="flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
+ >
+
+ {card.key} {card.title}
-
- {card.goal && 🎯 {card.goal} }
- {STATUS[card.status] && {STATUS[card.status]} }
- {NEXT[c.id] && (
- move(card.key, NEXT[c.id]!.to)}>
- {NEXT[c.id]!.label}
-
- )}
-
+ {(card.goal || STATUS[card.status] || NEXT[c.id]) && (
+
+ {card.goal && ◎ {card.goal} }
+ {STATUS[card.status] && {STATUS[card.status]!.label} }
+ {NEXT[c.id] && (
+ move(card.key, NEXT[c.id]!.to)}>
+ {NEXT[c.id]!.label}
+
+ )}
+
+ )}
))}
-
- ))}
+
+ );
+ })}
);
}
diff --git a/apps/web/components/Brand.tsx b/apps/web/components/Brand.tsx
new file mode 100644
index 00000000..f32319b5
--- /dev/null
+++ b/apps/web/components/Brand.tsx
@@ -0,0 +1,11 @@
+/** Peppa mark: pink tile with a glow + mono word. */
+export function Brand({ large = false }: { large?: boolean }) {
+ return (
+
+
+ P
+
+ peppa
+
+ );
+}
diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx
index eab5f3be..5be0d18b 100644
--- a/apps/web/components/Footer.tsx
+++ b/apps/web/components/Footer.tsx
@@ -13,7 +13,7 @@ export function Footer() {
{commit && (
<>
{" · "}
-
+
{commit}
{dirty && +изменения }
diff --git a/apps/web/components/Incidents.tsx b/apps/web/components/Incidents.tsx
index 061bb3ba..84bb6ae5 100644
--- a/apps/web/components/Incidents.tsx
+++ b/apps/web/components/Incidents.tsx
@@ -1,14 +1,18 @@
// Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list.
+import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
-import { ago } from "./ui";
+import { Hidden } from "@/components/cards";
+import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input, Label, NativeSelect, Textarea } from "@/components/ui/input";
-const Hidden = ({ projectId, back }: { projectId: number; back: string }) => (
- <>
-
-
- >
-);
+const STATUS_TONE: Record = { new: "danger", open: "warn", pending: "warn", task: "info", ignored: "muted", resolved: "ok", regressed: "danger" };
+
+function Code({ children }: { children: React.ReactNode }) {
+ return {children};
+}
export function IncidentsSection(props: {
projectId: number;
@@ -24,138 +28,143 @@ export function IncidentsSection(props: {
const { projectId, back, settings: s } = props;
if (!s) {
return (
-
- Ошибки
- Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.
+
+ Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.
{props.isOwner ? (
-
- Подключить отслеживание ошибок
+
+
+
+ Подключить отслеживание ошибок
+
) : (
- Не подключено — подключает владелец проекта.
+ Не подключено — подключает владелец проекта.
)}
-
+
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
-
-
- Ошибки политика: {POLICY_RU[s.policy]}
-
- {active.length === 0 ? Открытых ошибок нет.
: active.map((i) => )}
+ политика: {POLICY_RU[s.policy]}}>
+ {active.length === 0 ? Открытых ошибок нет. : active.map((i) => )}
{rest.length > 0 && (
-
- Исправленные и игнорируемые ({rest.length})
- {rest.map((i) => (
-
- ))}
-
+
+
+ {rest.map((i) => (
+
+ ))}
+
+
)}
-
- Настройки ошибок
-
+
+
{props.sources.map((src) => (
-
-
DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}
-
{src.dsn}
+
+ DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}
+ {src.dsn}
))}
-
- В коде: {"NEXT_PUBLIC_SENTRY_DSN"} / SENTRY_DSN из окружения, release = SHA деплоя, environment = prod, sendDefaultPii: false.
+
+ В коде: NEXT_PUBLIC_SENTRY_DSN / SENTRY_DSN из окружения, release = SHA деплоя,{" "}
+ environment = prod, sendDefaultPii: false.
{!s.webhookAuto && props.webhookUrl && (
-
-
Вебхук не настроен автоматически. В Bugsink: проект → Alerts → Custom webhook:
-
{props.webhookUrl}
-
Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.
+
+ Вебхук не настроен автоматически. В Bugsink: проект → Alerts → Custom webhook:
+ {props.webhookUrl}
+ Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.
)}
-
-
-
- Политика инцидентов{" "}
-
+
+
+
+ Политика инцидентов
+
{incidentPolicies.map((p) => (
{p} — {POLICY_RU[p]}
))}
-
-
-
+
+
-
-
-
+
+
);
}
function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map }) {
const taskKey = i.taskId ? taskKeys.get(i.taskId) : null;
- const decide = (action: string, label: string) => (
+ const decide = (action: string, label: string, icon: React.ReactNode) => (
-
-
-
- {label}
+
+
+ {icon}
+ {label}
+
);
return (
-
-
-
{INCIDENT_STATUS_RU[i.status]}
-
{i.title}
-
{ago(i.lastSeen)}
+
+
+ {INCIDENT_STATUS_RU[i.status]}
+ {i.title}
+ {ago(i.lastSeen)}
-
+
{i.source} · {i.environment ?? "—"} · релиз {i.lastRelease ?? "—"} · событий {i.events}
- {i.culprit && <> · 📍 {i.culprit}>}
+ {i.culprit && (
+
+ · {i.culprit}
+
+ )}
{i.url && (
<>
- {" · "}
-
Bugsink
+ ·
Bugsink
>
)}
{taskKey && (
<>
- {" · "}
-
{taskKey}
+ ·
{taskKey}
>
)}
- {i.decisionReason &&
{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}
}
-
+ {i.decisionReason &&
{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}
}
+
{!i.taskId && i.status !== "resolved" && (
<>
- {decide("backlog", "📥 В бэклог")}
- {decide("start", "▶️ В работу")}
- {i.status !== "ignored" && decide("ignore", "🙈 Игнорировать")}
+ {decide("backlog", "В бэклог",
)}
+ {decide("start", "В работу",
)}
+ {i.status !== "ignored" && decide("ignore", "Игнорировать",
)}
>
)}
{i.status !== "resolved" && i.status !== "ignored" && (
-
-
-
- ✅ Исправлено
+
+
+
+
+ Исправлено
+
)}
-
+
);
}
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index a6b9c43e..61d3d5ab 100644
--- a/apps/web/components/Sidebar.tsx
+++ b/apps/web/components/Sidebar.tsx
@@ -3,6 +3,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, type LucideIcon } from "lucide-react";
+import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
@@ -30,8 +31,7 @@ export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl
return (
- P
- peppa
+
фабрика
}) {
+ return (
+ <>
+ {Object.entries(fields).map(([k, v]) => (v == null ? null : ))}
+ >
+ );
+}
+
+export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean }) {
+ const review = q.kind === "attention" && taskStatus === "review";
+ const answered = !!q.answeredAt;
+ const k = KIND[q.kind];
+ const Icon = review ? CircleCheck : k.icon;
+ return (
+
+
+
+ {review ? "Готово к ревью" : k.label}
+ {taskKey && {taskKey} }
+
+ #{q.id} · {ago(q.createdAt)}
+
+
+ {q.text}
+ {answered ? (
+
+ {q.answeredVia === "system" ? : }
+ {q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
+
+ ) : (
+
+
+
+ {q.kind === "approval" && Одобрить }
+ {q.kind === "permission" && (
+ <>
+ Разрешить
+ Всегда
+ Запретить
+ >
+ )}
+ {review && Принять }
+ {q.kind === "attention" && !review && Продолжай }
+ {(q.options ?? []).map((o) => (
+ {o}
+ ))}
+
+ {q.kind !== "permission" && (
+
+
+ Ответить
+
+ )}
+
+ )}
+
+ );
+}
+
+/** Message / stop / resume controls of one runner. */
+export function SessionActions({ s, back }: { s: SessionView; back: string }) {
+ const alive = !["done", "failed"].includes(s.status);
+ return (
+
+ {alive && (
+
+
+
+
+
+ Отправить
+
+
+ )}
+ {alive && (
+
+
+
+
+ Остановить
+
+
+ )}
+ {(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
+
+
+
+ {alive ? : }
+ Resume
+
+
+ )}
+
+ );
+}
+
+export function AttachCommand({ name }: { name: string }) {
+ return tmux attach -t {name};
+}
+
+export function SessionCard({ s, back, showTitle = false }: { s: SessionView; back: string; showTitle?: boolean }) {
+ return (
+
+
+
+ {s.taskKey ? {s.taskKey} : {s.projectKey} }
+ {showTitle && s.taskTitle && {s.taskTitle} }
+
+ #{s.id} · {s.provider} · пок. {s.generation} · {ago(s.lastActivityAt)}
+
+
+
+
+
+ );
+}
+
+export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) {
+ if (!projects.length)
+ return (
+
+ Проектов пока нет. Создать первый
+
+ );
+ return (
+
+ {projects.map((p) => (
+
+
+
+ {p.key}
+ {p.name}
+ {p.ownerId !== userId && общий }
+
+
+ {p.giteaOwner}/{p.giteaRepo}
+
+
+
+ ))}
+
+ );
+}
diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx
new file mode 100644
index 00000000..ace2ab0a
--- /dev/null
+++ b/apps/web/components/common.tsx
@@ -0,0 +1,101 @@
+// Page building blocks of the console (PEP-38): header, sections, empty states, status badges, alerts.
+import Link from "next/link";
+import type { ReactNode } from "react";
+import { CircleAlert, CircleCheck } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status";
+import { cn } from "@/lib/utils";
+
+export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
+ return (
+
+ {crumbs && {crumbs}
}
+
+
{title}
+ {actions &&
{actions}
}
+
+ {children && {children}
}
+
+ );
+}
+
+export function Section({ title, count, actions, children, className, id }: { title: ReactNode; count?: number; actions?: ReactNode; children: ReactNode; className?: string; id?: string }) {
+ return (
+
+
+
{title}
+ {count != null && count > 0 &&
{count} }
+ {actions &&
{actions}
}
+
+ {children}
+
+ );
+}
+
+export function MoreLink({ href, children }: { href: string; children: ReactNode }) {
+ return (
+
+ {children} →
+
+ );
+}
+
+export function Empty({ children }: { children: ReactNode }) {
+ return {children}
;
+}
+
+/** Monospace task/project key, optionally a link. */
+export function Key({ children, href, className }: { children: ReactNode; href?: string; className?: string }) {
+ const cls = cn("font-mono text-[0.9em] whitespace-nowrap", href ? "text-primary hover:underline" : "text-muted-foreground", className);
+ return href ? {children} : {children} ;
+}
+
+export function StatusBadge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
+ const s = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? { label: status, tone: "muted" as const };
+ return (
+
+ {kind === "session" && }
+ {s.label}
+
+ );
+}
+
+export function Flash({ error }: { error?: string }) {
+ return error ? (
+
+
+ {error}
+
+ ) : null;
+}
+
+export function Notice({ children }: { children: ReactNode }) {
+ return (
+
+
+ {children}
+
+ );
+}
+
+/** Collapsible block styled as a card (native : no client JS). */
+export function Disclosure({ summary, children, open, className }: { summary: ReactNode; children: ReactNode; open?: boolean; className?: string }) {
+ return (
+
+
+ ›
+ {summary}
+
+ {children}
+
+ );
+}
+
+export function ago(d: Date | null | undefined): string {
+ if (!d) return "—";
+ const s = Math.round((Date.now() - d.getTime()) / 1000);
+ if (s < 60) return `${s} с назад`;
+ if (s < 3600) return `${Math.round(s / 60)} мин назад`;
+ if (s < 86400) return `${Math.round(s / 3600)} ч назад`;
+ return d.toLocaleDateString("ru-RU");
+}
diff --git a/apps/web/components/ui.tsx b/apps/web/components/ui.tsx
deleted file mode 100644
index 6dcc24be..00000000
--- a/apps/web/components/ui.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import Link from "next/link";
-import type { ReactNode } from "react";
-import type { Project, Question, SessionView } from "@peppa/core";
-import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
-
-const TASK_STATUS: Record = {
- backlog: "Бэклог",
- proposing: "Proposal",
- awaiting_approval: "Ждёт одобрения",
- in_progress: "В работе",
- review: "Ревью",
- done: "Готово",
- blocked: "Блок",
-};
-const SESSION_STATUS: Record = {
- starting: "запуск",
- running: "работает",
- waiting_input: "ждёт тебя",
- idle: "простаивает",
- stalled: "зависла?",
- rate_limited: "лимит",
- done: "завершена",
- failed: "упала",
-};
-const KIND: Record = { approval: "Одобрение proposal", question: "Вопрос", permission: "Разрешение", attention: "Сессия ждёт тебя" };
-
-export function Badge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
- const label = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? status;
- return {label} ;
-}
-
-export function Flash({ error }: { error?: string }) {
- return error ? {error}
: null;
-}
-
-export function Notice({ children }: { children: ReactNode }) {
- return {children}
;
-}
-
-export function ago(d: Date | null | undefined): string {
- if (!d) return "—";
- const s = Math.round((Date.now() - d.getTime()) / 1000);
- if (s < 60) return `${s} с назад`;
- if (s < 3600) return `${Math.round(s / 60)} мин назад`;
- if (s < 86400) return `${Math.round(s / 3600)} ч назад`;
- return d.toLocaleDateString("ru-RU");
-}
-
-export function QuestionCard({ q, taskKey, taskStatus, back }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string }) {
- const review = q.kind === "attention" && taskStatus === "review";
- const answered = !!q.answeredAt;
- return (
-
-
- {review ? "Готово к ревью" : KIND[q.kind]}
- {taskKey && (
-
- {taskKey}
-
- )}
- #{q.id} · {ago(q.createdAt)}
-
- {q.text}
- {answered ? (
-
- {q.answeredVia === "system" ? "⌛ " : "✅ "}
- {q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
-
- ) : (
-
-
-
-
- {q.kind === "approval" && Одобрить }
- {q.kind === "permission" && (
- <>
- Разрешить
- Всегда
- Запретить
- >
- )}
- {review && Принять }
- {q.kind === "attention" && !review && Продолжай }
- {(q.options ?? []).map((o) => (
- {o}
- ))}
-
- {q.kind !== "permission" && (
-
-
- Ответить
-
- )}
-
- )}
-
- );
-}
-
-export function SessionCard({ s, back, showTitle = false }: { s: SessionView; back: string; showTitle?: boolean }) {
- const alive = !["done", "failed"].includes(s.status);
- return (
-
-
-
- {s.taskKey ? {s.taskKey} : {s.projectKey}}
- {showTitle && s.taskTitle && {s.taskTitle} }
- #{s.id} · {s.provider} · поколение {s.generation} · {ago(s.lastActivityAt)}
-
- tmux attach -t {s.tmuxName}
-
- {alive && (
-
-
-
-
- Отправить
-
- )}
- {alive ? (
-
-
-
- Остановить
-
- ) : null}
- {(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
-
-
-
- Resume
-
- )}
-
-
- );
-}
-
-export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) {
- if (!projects.length)
- return (
-
- Проектов пока нет. Создать первый
-
- );
- return (
-
- {projects.map((p) => (
-
-
- {p.key} {p.name}
-
-
- {p.ownerId !== userId && общий } {p.giteaOwner}/{p.giteaRepo}
-
-
- ))}
-
- );
-}
diff --git a/apps/web/scripts/mock-ui-seed.ts b/apps/web/scripts/mock-ui-seed.ts
index a5e81e4c..fa281db0 100644
--- a/apps/web/scripts/mock-ui-seed.ts
+++ b/apps/web/scripts/mock-ui-seed.ts
@@ -2,10 +2,10 @@
// column, runners in every status (one hit the usage limit and resumes later), open questions, releases.
// Only for a throwaway database — refuses the production one:
// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login]
-import { mkdirSync } from "node:fs";
+import { mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { createDb, events, goals, projects, questions, releases, sessions, tasks, users } from "@peppa/db";
+import { checkRuns, createDb, errorSources, events, goals, incidents, incidentSettings, projects, questions, releases, sessions, tasks, users } from "@peppa/db";
import { eq } from "drizzle-orm";
const url = process.env.DATABASE_URL ?? "";
@@ -19,7 +19,9 @@ const ws = join(tmpdir(), "peppa-mock-ui");
const [user] = await db.insert(users).values({ giteaId: -900001, login }).onConflictDoUpdate({ target: users.login, set: { login } }).returning();
async function project(key: string, name: string, slug: string) {
- mkdirSync(join(ws, slug), { recursive: true });
+ mkdirSync(join(ws, slug, ".peppa"), { recursive: true });
+ const checks = { typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" };
+ writeFileSync(join(ws, slug, ".peppa", "project.json"), JSON.stringify({ key, slug, checks }));
const [p] = await db
.insert(projects)
.values({ key, name, slug, giteaOwner: login, giteaRepo: slug, workspacePath: join(ws, slug), ownerId: user!.id })
@@ -108,5 +110,22 @@ await db.insert(releases).values([
{ projectId: pay.id, env: "staging", sha: "a1b2c3d4e5f6", status: "healthy", host: "mock-payments-staging.telecom.quest", tasks: ["PAY-6"], deployedBy: "ci" },
{ projectId: pay.id, env: "prod", sha: "9f8e7d6c5b4a", status: "healthy", host: "mock-payments-prod.telecom.quest", tasks: ["PAY-5"], deployedBy: login },
]);
+// CI of PAY-1 (one red check with a log tail) and PAY-4 (green), PEP-57.
+await db.insert(checkRuns).values([
+ ...["typecheck", "build"].map((check) => ({ projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check, state: "success" as const })),
+ { projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check: "test", state: "failure" as const, logTail: "FAIL src/webhook.test.ts\n ✕ marks the payment paid (12 ms)\n expected 'paid', got 'pending'" },
+ ...["typecheck", "test", "build"].map((check) => ({ projectId: pay.id, taskId: pt[3]!.id, sha: "beef5678", check, state: "success" as const })),
+]);
+// Error tracking (PEP-58): settings, DSNs, an open incident, one with a task, one ignored.
+await db.insert(incidentSettings).values({ projectId: pay.id, hookSecret: "mock-hook-secret", policy: "ask", webhookAuto: false });
+await db.insert(errorSources).values([
+ { projectId: pay.id, kind: "web", bugsinkProjectId: 9001, dsn: "https://mock-key@bugsink.example/9001" },
+ { projectId: pay.id, kind: "api", bugsinkProjectId: 9002, dsn: "https://mock-key@bugsink.example/9002" },
+]);
+await db.insert(incidents).values([
+ { projectId: pay.id, source: "web", bugsinkIssueId: "mock-1", title: "TypeError: Cannot read properties of undefined (reading 'amount')", culprit: "PaymentForm.tsx in submit", environment: "prod", lastRelease: "9f8e7d6", events: 14, firstSeen: ago(300), lastSeen: ago(6), status: "pending", decidedBy: "triage", decisionReason: "Падает оплата у части пользователей — нужен PM" },
+ { projectId: pay.id, source: "api", bugsinkIssueId: "mock-2", title: "TimeoutError: YooKassa did not answer in 10s", environment: "prod", events: 3, firstSeen: ago(900), lastSeen: ago(90), status: "task", taskId: pt[4]!.id },
+ { projectId: pay.id, source: "web", bugsinkIssueId: "mock-3", title: "ResizeObserver loop limit exceeded", environment: "prod", events: 120, firstSeen: ago(5000), lastSeen: ago(30), status: "ignored" },
+]);
console.log(`seeded: user ${login}, projects PAY and SHOP, ${made.length} runners`);
process.exit(0);
diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/pep-38-factory-console/tasks.md
index cf8e8886..82c64687 100644
--- a/openspec/changes/pep-38-factory-console/tasks.md
+++ b/openspec/changes/pep-38-factory-console/tasks.md
@@ -8,12 +8,12 @@
- [x] 1.5 Старый CSS в слое `base`, все маршруты открываются; проверка в браузере (desktop + 390 px)
## 2. Перенос страниц (PR 2)
-- [ ] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer
-- [ ] 2.2 Главная, Проекты, Новый проект
-- [ ] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий
-- [ ] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события
-- [ ] 2.5 Настройки, Помощь, вход, согласие OAuth
-- [ ] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере
+- [x] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer
+- [x] 2.2 Главная, Проекты, Новый проект
+- [x] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий
+- [x] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события
+- [x] 2.5 Настройки, Помощь, вход, согласие OAuth
+- [x] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере
## 3. Пульт раннеров (PR 3)
- [ ] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой
--
2.45.2
From 50b1d1afecd39807a50d0f7ca5684c39d19a23c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:03:43 +0500
Subject: [PATCH 011/532] PEP-36: benchmark SQLite vs Postgres and propose Bun
+ SQLite stack
bench/sqlite (outside the workspace): Peppa-like load with 10/20 runners,
a hook process per event, MCP, bot, web and watchdog; bun:sqlite,
node:sqlite, better-sqlite3, a single-writer service and Postgres; notify
replacements (cursor polling, fs.watch on WAL, unix-socket push); a
ceiling test; a schema port to sqlite with a data copy from Postgres and
a check of drizzle transactions.
openspec/changes/pep-36-lightweight-stack: proposal, design with the
numbers, specs (platform-storage, service-monitoring), phased tasks.
No product code changes; the move waits for the PM's decision.
Co-Authored-By: Claude Opus 5.5
---
bench/sqlite/.gitignore | 2 +
bench/sqlite/README.md | 62 +
bench/sqlite/RESULTS.md | 70 +
bench/sqlite/contention.ts | 76 +
bench/sqlite/lib/db.ts | 172 ++
bench/sqlite/lib/notify.ts | 49 +
bench/sqlite/lib/schema.ts | 34 +
bench/sqlite/matrix.sh | 32 +
bench/sqlite/package.json | 15 +
bench/sqlite/pnpm-lock.yaml | 40 +
bench/sqlite/report.ts | 48 +
bench/sqlite/roles.ts | 336 +++
bench/sqlite/run.ts | 128 ++
bench/sqlite/schema-port/copy-from-pg.ts | 53 +
bench/sqlite/schema-port/drizzle.config.ts | 2 +
.../schema-port/migrations/0000_baseline.sql | 271 +++
.../migrations/meta/0000_snapshot.json | 1947 +++++++++++++++++
.../schema-port/migrations/meta/_journal.json | 13 +
bench/sqlite/schema-port/schema.ts | 357 +++
bench/sqlite/schema-port/tx-check.ts | 35 +
.../pep-36-lightweight-stack/design.md | 215 ++
.../pep-36-lightweight-stack/proposal.md | 67 +
.../specs/platform-storage/spec.md | 95 +
.../specs/service-monitoring/spec.md | 16 +
.../changes/pep-36-lightweight-stack/tasks.md | 41 +
25 files changed, 4176 insertions(+)
create mode 100644 bench/sqlite/.gitignore
create mode 100644 bench/sqlite/README.md
create mode 100644 bench/sqlite/RESULTS.md
create mode 100644 bench/sqlite/contention.ts
create mode 100644 bench/sqlite/lib/db.ts
create mode 100644 bench/sqlite/lib/notify.ts
create mode 100644 bench/sqlite/lib/schema.ts
create mode 100755 bench/sqlite/matrix.sh
create mode 100644 bench/sqlite/package.json
create mode 100644 bench/sqlite/pnpm-lock.yaml
create mode 100644 bench/sqlite/report.ts
create mode 100644 bench/sqlite/roles.ts
create mode 100644 bench/sqlite/run.ts
create mode 100644 bench/sqlite/schema-port/copy-from-pg.ts
create mode 100644 bench/sqlite/schema-port/drizzle.config.ts
create mode 100644 bench/sqlite/schema-port/migrations/0000_baseline.sql
create mode 100644 bench/sqlite/schema-port/migrations/meta/0000_snapshot.json
create mode 100644 bench/sqlite/schema-port/migrations/meta/_journal.json
create mode 100644 bench/sqlite/schema-port/schema.ts
create mode 100644 bench/sqlite/schema-port/tx-check.ts
create mode 100644 openspec/changes/pep-36-lightweight-stack/design.md
create mode 100644 openspec/changes/pep-36-lightweight-stack/proposal.md
create mode 100644 openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
create mode 100644 openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md
create mode 100644 openspec/changes/pep-36-lightweight-stack/tasks.md
diff --git a/bench/sqlite/.gitignore b/bench/sqlite/.gitignore
new file mode 100644
index 00000000..2be94185
--- /dev/null
+++ b/bench/sqlite/.gitignore
@@ -0,0 +1,2 @@
+node_modules
+results/
diff --git a/bench/sqlite/README.md b/bench/sqlite/README.md
new file mode 100644
index 00000000..db7c344a
--- /dev/null
+++ b/bench/sqlite/README.md
@@ -0,0 +1,62 @@
+# PEP-36: замер SQLite vs Postgres под нагрузкой Пеппы
+
+Не часть продукта: отдельный `package.json` вне pnpm-воркспейса, свои зависимости.
+Результаты и выводы — в `openspec/changes/pep-36-lightweight-stack/design.md`.
+
+```bash
+cd bench/sqlite
+pnpm install --ignore-workspace # better-sqlite3 под Node 26 собирается из исходников (node-gyp)
+# один прогон
+node run.ts --backend bun --runners 10 --load 1 --duration 90 --notify poll:1000
+# вся матрица (~35 мин); Postgres — только одноразовая БД peppa_bench
+BENCH_PG_URL=postgres://peppa:…@127.0.0.1:5433/peppa_bench ./matrix.sh
+```
+
+`results/<прогон>/summary.json` — перцентили по каждой операции (в git не кладутся).
+
+## Модель нагрузки
+
+Частоты сняты с боевой БД `peppa` (только чтение, 2026-11-13): за сутки 107 событий,
+медианный промежуток между событиями одной сессии 16 с, пик 6 событий в минуту на сессию.
+Хуки Claude у Пеппы срабатывают на prompt / notification / stop / permission, не на каждый
+вызов инструмента. Модель с запасом:
+
+| Процесс | Что делает | Частота (×1) |
+|---|---|---|
+| хук (`peppa-hook`) | **новый процесс на каждое событие**: открыть БД, прочитать сессию, транзакция «update sessions + insert events» | экспоненциально, в среднем раз в 10 с на раннер |
+| хук-вопрос | 10 % хуков: insert questions + update sessions + insert events, затем опрос ответа раз в 1,5 с (как PermissionRequest) и снятие `awaiting_hook` | — |
+| MCP (`peppa-mcp`) | долгоживущий на раннер: `report_progress` (insert events + update tasks), `get_task` (2 чтения) | 30 с / 15 с |
+| бот | outbox раз в 1 с, reconcile раз в 2 с, ответ «PM» через 2–8 с (insert telegram_updates → update questions), heartbeat 30 с; потребитель событий | — |
+| веб | 3 открытые доски, 4 запроса раз в 5 с; потребитель событий | — |
+| вачдог | tick раз в 30 с: список сессий, 10 % — stalled (update + insert), heartbeat | — |
+
+`--load 10` умножает частоты хуков и MCP в 10 раз (стресс). `--runners` — 10 или 20.
+
+## Варианты (`--backend`)
+
+- `bun` — `bun:sqlite`, каждый процесс открывает файл сам; WAL, `busy_timeout=5000`,
+ `synchronous=NORMAL`, транзакции записи `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`.
+- `node` — то же на `node:sqlite` (Node 26).
+- `better` — то же на `better-sqlite3` 13 (Node).
+- `writer` — один процесс-писатель (Bun) владеет записью, остальные шлют транзакции по
+ HTTP через unix-сокет; чтения идут прямо в файл (читатели WAL не блокируются).
+- `pg` — текущий стек: Postgres 17 (docker), postgres.js, Node; хук открывает соединение.
+
+## Доставка событий (`--notify`)
+
+Потребитель (бот, веб) будится и читает `events where id > cursor`. Задержка — от момента
+перед записью события до момента, когда потребитель его прочитал.
+
+- `pg` — LISTEN/NOTIFY (как сейчас в боте)
+- `poll:N` — опрос с курсором каждые N мс
+- `fswatch` — `fs.watch` на `-wal` файле (+ страховочный опрос раз в 5 с)
+- `push` — писатель (или маленький хаб) рассылает id новых событий подписчикам по unix-сокету
+
+## Найденные ловушки
+
+- `PRAGMA busy_timeout` должен идти **первым** после открытия. Если раньше выполнить хоть
+ что-то (даже `journal_mode`), при одновременном открытии файла многими процессами
+ прилетает `SQLITE_BUSY_RECOVERY` сразу, без ожидания. `journal_mode=WAL` постоянный —
+ ставится один раз при создании файла.
+- Путь unix-сокета на macOS ограничен 104 байтами — сокеты держать в коротком каталоге.
+- На Bun `fetch(..., { unix })` заметно быстрее `node:http` для одноразовых процессов.
diff --git a/bench/sqlite/RESULTS.md b/bench/sqlite/RESULTS.md
new file mode 100644
index 00000000..72e9576a
--- /dev/null
+++ b/bench/sqlite/RESULTS.md
@@ -0,0 +1,70 @@
+# PEP-36: результаты замера (2026-11-13, Mac Пеппы, Bun 1.4.4, Node 26.8.1, Postgres 17.11)
+
+Сгенерировано `node report.ts` после `./matrix.sh`; потолок — `contention.ts`.
+
+## Записи и доставка
+
+| раннеры | нагрузка | вариант | записей | p50 мс | p95 | p99 | max | BUSY-повторы | ошибки | хук целиком p50/p95 | старт хука p50 | доставка боту p50/p95/p99 |
+|---|---|---|---|---|---|---|---|---|---|---|---|---|
+| 10 | ×1 | bun:sqlite | 126 | 0.32 | 1.61 | 2.34 | 2.68 | 0 | 0 | 35.77 / 38.68 | 31.94 | 459 / 974 / 993 (poll:1000) |
+| 10 | ×1 | node:sqlite | 192 | 0.20 | 0.70 | 1.18 | 1.27 | 0 | 0 | 98.08 / 9112 | 96.21 | 421 / 906 / 950 (poll:1000) |
+| 10 | ×1 | better-sqlite3 | 169 | 0.19 | 0.95 | 2.02 | 2.21 | 0 | 0 | 103 / 6117 | 97.01 | 556 / 981 / 987 (poll:1000) |
+| 10 | ×1 | один писатель (Bun) | 140 | 1.21 | 2.35 | 3.89 | 8.19 | 0 | 0 | 31.10 / 6036 | 22.56 | 0.97 / 3.20 / 1547 (push) |
+| 10 | ×1 | Postgres (Node) | 177 | 9.60 | 18.11 | 36.05 | 38.15 | 0 | 0 | 132 / 6156 | 92.00 | 13.32 / 23.25 / 39.90 (pg) |
+| 10 | ×10 | bun:sqlite | 728 | 0.24 | 0.78 | 1.22 | 5.96 | 0 | 0 | 30.37 / 7535 | 24.86 | 478 / 937 / 992 (poll:1000) |
+| 10 | ×10 | node:sqlite | 696 | 0.14 | 0.38 | 0.94 | 1.76 | 0 | 0 | 77.71 / 7573 | 74.67 | 519 / 960 / 996 (poll:1000) |
+| 10 | ×10 | better-sqlite3 | 698 | 0.17 | 0.49 | 1.41 | 2.51 | 0 | 0 | 81.82 / 6091 | 73.97 | 508 / 951 / 987 (poll:1000) |
+| 10 | ×10 | один писатель (Bun) | 719 | 1.16 | 2.12 | 2.60 | 6.55 | 0 | 0 | 30.22 / 7530 | 23.42 | 0.81 / 2.05 / 3.50 (push) |
+| 10 | ×10 | Postgres (Node) | 691 | 8.03 | 12.61 | 16.25 | 24.60 | 0 | 0 | 114 / 7628 | 74.03 | 11.21 / 16.51 / 19.12 (pg) |
+| 20 | ×1 | bun:sqlite | 327 | 0.29 | 1.34 | 2.21 | 3.06 | 0 | 0 | 33.67 / 6035 | 28.45 | 454 / 925 / 991 (poll:1000) |
+| 20 | ×1 | node:sqlite | 324 | 0.16 | 0.71 | 1.33 | 2.00 | 0 | 0 | 73.96 / 7562 | 71.88 | 553 / 982 / 1013 (poll:1000) |
+| 20 | ×1 | better-sqlite3 | 314 | 0.19 | 0.82 | 1.53 | 2.20 | 0 | 0 | 96.47 / 9084 | 87.91 | 497 / 944 / 985 (poll:1000) |
+| 20 | ×1 | один писатель (Bun) | 305 | 1.34 | 2.38 | 4.16 | 7.41 | 0 | 0 | 31.33 / 6050 | 25.39 | 1.11 / 2.94 / 5.29 (push) |
+| 20 | ×1 | Postgres (Node) | 306 | 8.06 | 17.16 | 29.14 | 36.39 | 0 | 0 | 121 / 7621 | 85.12 | 11.42 / 20.32 / 32.03 (pg) |
+| 20 | ×10 | bun:sqlite | 1510 | 0.20 | 0.46 | 1.75 | 6.17 | 0 | 0 | 23.34 / 6035 | 19.45 | 503 / 945 / 991 (poll:1000) |
+| 20 | ×10 | node:sqlite | 1424 | 0.13 | 0.24 | 1.32 | 2.29 | 0 | 0 | 70.15 / 6074 | 68.68 | 480 / 941 / 993 (poll:1000) |
+| 20 | ×10 | better-sqlite3 | 1471 | 0.16 | 0.27 | 1.17 | 7.86 | 0 | 0 | 75.04 / 6085 | 68.83 | 509 / 946 / 993 (poll:1000) |
+| 20 | ×10 | один писатель (Bun) | 1438 | 1.07 | 2.02 | 2.63 | 8.42 | 0 | 0 | 24.81 / 6033 | 19.62 | 0.71 / 1.30 / 2.35 (push) |
+| 20 | ×10 | Postgres (Node) | 1345 | 6.98 | 11.89 | 17.85 | 43.83 | 0 | 0 | 102 / 6120 | 67.98 | 9.76 / 15.06 / 17.73 (pg) |
+| 20 | ×50 | bun:sqlite | 3172 | 0.15 | 0.35 | 1.83 | 7.48 | 0 | 0 | 18.78 / 6029 | 15.53 | 515 / 949 / 994 (poll:1000) |
+| 20 | ×50 | один писатель (Bun) | 3093 | 0.30 | 1.58 | 2.23 | 9.16 | 0 | 0 | 19.89 / 6032 | 15.64 | 0.39 / 0.85 / 1.48 (push) |
+| 20 | ×50 | Postgres (Node) | 2910 | 4.58 | 9.19 | 12.13 | 29.31 | 0 | 0 | 96.66 / 6116 | 68.14 | 6.17 / 11.37 / 14.30 (pg) |
+
+## Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10)
+
+| способ | доставка боту p50 | p95 | p99 | max | веб p50 | p95 |
+|---|---|---|---|---|---|---|
+| fswatch | 26.29 | 192 | 300 | 508 | 26.29 | 193 |
+| poll:1000 | 503 | 945 | 991 | 1002 | 509 | 947 |
+| poll:200 | 100 | 192 | 200 | 204 | 103 | 192 |
+| push | 0.80 | 1.42 | 2.48 | 46.85 | 0.83 | 1.47 |
+| Postgres LISTEN/NOTIFY (для сравнения) | 9.76 | 15.06 | 17.73 | 28.17 | 9.72 | 14.71 |
+
+## Самые медленные операции записи (p99, мс) при 20 раннерах ×10
+
+| операция | bun:sqlite | node:sqlite | better-sqlite3 | один писатель (Bun) | Postgres (Node) |
+|---|---|---|---|---|---|
+| bot.answer | 0.50 | 0.49 | 0.14 | 5.32 | 9.32 |
+| bot.enqueue | 5.15 | 1.32 | 0.13 | 0.93 | 9.33 |
+| bot.heartbeat | 2.93 | 0.15 | 0.71 | 7.01 | 43.83 |
+| bot.sent | 0.18 | 0.91 | 0.08 | 1.10 | 10.21 |
+| bot.update | 0.45 | 0.48 | 0.52 | 1.56 | 9.55 |
+| hook.answered | 6.17 | 2.29 | 7.86 | 4.07 | 30.26 |
+| hook.event | 0.64 | 0.30 | 1.47 | 2.47 | 14.20 |
+| hook.question | 5.43 | 0.33 | 1.06 | 2.40 | 14.27 |
+| mcp.progress | 1.71 | 0.81 | 0.60 | 2.75 | 19.55 |
+| wd.heartbeat | 0.15 | 0.07 | 0.06 | 0.92 | 5.60 |
+| wd.stalled | 5.48 | 0.66 | 0.20 | 8.42 | 17.87 |
+
+## Потолок (contention.ts, 10 с, без пауз)
+
+```
+{"backend":"bun","procs":20,"seconds":10,"txPerSec":33537,"p50":"0.02","p95":"0.08","p99":"4.24","max":"2710.8","busyRetries":0,"errors":0}
+{"backend":"bun","procs":40,"seconds":10,"txPerSec":27223,"p50":"0.03","p95":"0.31","p99":"21.96","max":"2930.6","busyRetries":0,"errors":0}
+{"backend":"node","procs":20,"seconds":10,"txPerSec":48578,"p50":"0.02","p95":"0.03","p99":"0.05","max":"5405.9","busyRetries":1,"errors":0}
+{"backend":"node","procs":40,"seconds":10,"txPerSec":47694,"p50":"0.02","p95":"0.03","p99":"0.06","max":"6413.2","busyRetries":3,"errors":0}
+{"backend":"better","procs":20,"seconds":10,"txPerSec":47456,"p50":"0.02","p95":"0.03","p99":"0.05","max":"5359.5","busyRetries":1,"errors":0}
+{"backend":"better","procs":40,"seconds":10,"txPerSec":45076,"p50":"0.02","p95":"0.03","p99":"0.06","max":"5937.5","busyRetries":2,"errors":0}
+{"backend":"pg","procs":20,"seconds":10,"txPerSec":4890,"p50":"3.88","p95":"6.82","p99":"9.01","max":"97.1","busyRetries":0,"errors":0}
+{"backend":"pg","procs":40,"seconds":10,"txPerSec":7555,"p50":"5.47","p95":"6.95","p99":"8.33","max":"210.2","busyRetries":0,"errors":0}
+```
diff --git a/bench/sqlite/contention.ts b/bench/sqlite/contention.ts
new file mode 100644
index 00000000..9b4129a3
--- /dev/null
+++ b/bench/sqlite/contention.ts
@@ -0,0 +1,76 @@
+// Ceiling test: P processes write hook-like transactions back to back, no pauses.
+// Far beyond Peppa's real load; shows where each backend starts to bend.
+// node contention.ts --backend bun --procs 20 --seconds 10
+import { spawn } from "node:child_process";
+import { homedir } from "node:os";
+import { parseArgs } from "node:util";
+import { openDb, openPg, openSqlite, type Backend } from "./lib/db.ts";
+import { pgSchema, seedStmts, sqliteSchema } from "./lib/schema.ts";
+
+const { values: a } = parseArgs({ options: { backend: { type: "string", default: "bun" }, procs: { type: "string", default: "20" }, seconds: { type: "string", default: "10" }, worker: { type: "boolean" } } });
+const backend = a.backend as Backend;
+const now = () => performance.timeOrigin + performance.now();
+
+if (a.worker) {
+ const db = await openDb(backend);
+ const sid = Number(process.env.BENCH_SESSION);
+ const end = Number(process.env.BENCH_END);
+ const ms: number[] = [];
+ let busy = 0;
+ let errors = 0;
+ while (Date.now() < end) {
+ const t = now();
+ try {
+ await db.tx([
+ ["update sessions set status = 'running', last_activity_at = ? where id = ?", [Date.now(), sid]],
+ ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'turn_end', ?, ?) returning id", [sid, sid, JSON.stringify({ t0: t }), Date.now()]],
+ ]);
+ } catch {
+ errors++;
+ }
+ busy += db.lastBusy;
+ ms.push(now() - t);
+ }
+ await db.close();
+ // A file, not stdout: process.exit() can cut a large pipe write short.
+ (await import("node:fs")).writeFileSync(`${process.env.BENCH_DB}.${sid}.json`, JSON.stringify({ ms, busy, errors }));
+ process.exit(0);
+}
+
+const procs = Number(a.procs);
+const runtime = backend === "pg" || backend === "node" || backend === "better" ? process.execPath : `${homedir()}/.bun/bin/bun`;
+const work = `${process.env.BENCH_TMP ?? "/tmp"}/peppa-contention-${process.pid}`;
+const env = { ...process.env, BENCH_BACKEND: backend, BENCH_DB: `${work}.db` } as Record;
+if (backend === "pg") {
+ if (!/\/peppa_bench(\?|$)/.test(env.BENCH_PG_URL ?? "")) throw new Error("BENCH_PG_URL must point at peppa_bench");
+ const db = await openPg(env.BENCH_PG_URL);
+ await db.all("drop schema public cascade");
+ await db.all("create schema public");
+ for (const s of pgSchema) await db.all(s);
+ await db.tx(seedStmts(procs));
+ await db.close();
+} else {
+ const db = await openSqlite("node", env.BENCH_DB);
+ await db.all("PRAGMA journal_mode = WAL");
+ for (const s of sqliteSchema) await db.all(s);
+ await db.tx(seedStmts(procs));
+ await db.close();
+}
+const end = Date.now() + 1000 + Number(a.seconds) * 1000;
+const results = await Promise.all(
+ Array.from({ length: procs }, (_, i) =>
+ new Promise<{ ms: number[]; busy: number; errors: number }>((resolve) => {
+ const p = spawn(runtime, [new URL(import.meta.url).pathname, "--worker", "--backend", backend], { env: { ...env, BENCH_SESSION: String(i + 1), BENCH_END: String(end) }, stdio: ["ignore", "inherit", "inherit"] });
+ p.on("exit", async () => {
+ const fs = await import("node:fs");
+ const f = `${env.BENCH_DB}.${i + 1}.json`;
+ resolve(fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, "utf8")) : { ms: [], busy: 0, errors: 1 });
+ fs.rmSync(f, { force: true });
+ });
+ }),
+ ),
+);
+const ms = results.flatMap((r) => r.ms).sort((x, y) => x - y);
+const pct = (p: number) => ms[Math.min(ms.length - 1, Math.floor((p / 100) * ms.length))].toFixed(2);
+console.log(JSON.stringify({ backend, procs, seconds: Number(a.seconds), txPerSec: Math.round(ms.length / Number(a.seconds)), p50: pct(50), p95: pct(95), p99: pct(99), max: ms.at(-1)!.toFixed(1), busyRetries: results.reduce((s, r) => s + r.busy, 0), errors: results.reduce((s, r) => s + r.errors, 0) }));
+for (const s of ["", "-wal", "-shm"]) (await import("node:fs")).rmSync(env.BENCH_DB + s, { force: true });
diff --git a/bench/sqlite/lib/db.ts b/bench/sqlite/lib/db.ts
new file mode 100644
index 00000000..b731a46b
--- /dev/null
+++ b/bench/sqlite/lib/db.ts
@@ -0,0 +1,172 @@
+// Uniform async DB access for the benchmark: bun:sqlite, node:sqlite, better-sqlite3,
+// Postgres (postgres.js) and a "writer" client that sends writes to one writer process.
+// SQL is written in SQLite dialect with `?` params; the Postgres adapter renumbers them.
+import { request } from "node:http";
+
+export type Stmt = [sql: string, params?: unknown[]];
+export type Row = Record;
+
+export interface Db {
+ all(sql: string, params?: unknown[]): Promise;
+ /** Runs statements in one write transaction; returns each statement's rows. */
+ tx(stmts: Stmt[]): Promise;
+ /** SQLITE_BUSY retries made by the last tx (0 for Postgres/writer). */
+ lastBusy: number;
+ close(): Promise;
+ /** Postgres only: raw client for LISTEN/NOTIFY. */
+ pg?: any;
+}
+
+export type Backend = "bun" | "node" | "better" | "pg" | "writer";
+
+export const BUSY_TIMEOUT_MS = Number(process.env.BENCH_BUSY_TIMEOUT_MS ?? 5000);
+
+// busy_timeout must come first: with 20 hook processes opening the file at once, any
+// statement before it (even journal_mode) can fail at once with SQLITE_BUSY_RECOVERY.
+// journal_mode=WAL is persistent, so it is set once when the file is created (run.ts).
+const PRAGMAS = [
+ `PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`,
+ "PRAGMA synchronous = NORMAL",
+ "PRAGMA foreign_keys = ON",
+];
+
+function isBusy(e: unknown) {
+ const s = String((e as any)?.code ?? "") + " " + String((e as any)?.message ?? e);
+ return /SQLITE_BUSY|database is locked/i.test(s);
+}
+
+/** Wraps a synchronous SQLite driver: BEGIN IMMEDIATE + retry on SQLITE_BUSY. */
+function syncSqlite(exec: (sql: string) => void, all: (sql: string, p: unknown[]) => Row[], close: () => void): Db {
+ const db: Db = {
+ lastBusy: 0,
+ async all(sql, params = []) {
+ return all(sql, params);
+ },
+ async tx(stmts) {
+ db.lastBusy = 0;
+ for (;;) {
+ try {
+ exec("BEGIN IMMEDIATE");
+ try {
+ const out = stmts.map(([s, p]) => all(s, p ?? []));
+ exec("COMMIT");
+ return out;
+ } catch (e) {
+ try { exec("ROLLBACK"); } catch {}
+ throw e;
+ }
+ } catch (e) {
+ // busy_timeout already waited BUSY_TIMEOUT_MS; count it and give up after 3.
+ if (!isBusy(e) || ++db.lastBusy >= 3) throw e;
+ }
+ }
+ },
+ async close() {
+ close();
+ },
+ };
+ return db;
+}
+
+export async function openSqlite(kind: "bun" | "node" | "better", path: string, readonly = false): Promise {
+ if (kind === "bun") {
+ const { Database } = await import("bun:sqlite" as string);
+ const d = new Database(path, readonly ? { readonly: true } : { create: true });
+ for (const p of PRAGMAS) d.exec(p);
+ return syncSqlite((s) => d.exec(s), (s, p) => d.query(s).all(...p), () => d.close());
+ }
+ if (kind === "node") {
+ const { DatabaseSync } = await import("node:sqlite");
+ const d = new DatabaseSync(path, { readOnly: readonly });
+ for (const p of PRAGMAS) d.exec(p);
+ const cache = new Map();
+ const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s));
+ return syncSqlite((s) => d.exec(s), (s, p) => prep(s).all(...(p as any[])) as Row[], () => d.close());
+ }
+ const { default: Better } = await import("better-sqlite3");
+ const d = new Better(path, { readonly });
+ for (const p of PRAGMAS) d.exec(p);
+ const cache = new Map();
+ const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s));
+ return syncSqlite(
+ (s) => d.exec(s),
+ (s, p) => {
+ const st = prep(s);
+ return st.reader ? st.all(...p) : (st.run(...p), []);
+ },
+ () => d.close(),
+ );
+}
+
+const toPg = (s: string) => {
+ let i = 0;
+ return s.replace(/\?/g, () => `$${++i}`);
+};
+
+export async function openPg(url: string, max = 1): Promise {
+ const { default: postgres } = await import("postgres");
+ const sql = postgres(url, { max, onnotice: () => {} });
+ return {
+ lastBusy: 0,
+ pg: sql,
+ async all(s, p = []) {
+ return (await sql.unsafe(toPg(s), p as any[])) as unknown as Row[];
+ },
+ async tx(stmts) {
+ return (await sql.begin(async (t: any) => {
+ const out: Row[][] = [];
+ for (const [s, p] of stmts) out.push(await t.unsafe(toPg(s), p ?? []));
+ return out;
+ })) as Row[][];
+ },
+ async close() {
+ await sql.end({ timeout: 1 });
+ },
+ };
+}
+
+export async function httpUnix(socketPath: string, path: string, body: unknown): Promise {
+ // Bun's fetch speaks unix sockets natively and starts much faster than node:http there.
+ if (typeof (globalThis as any).Bun !== "undefined") {
+ const r = await fetch(`http://writer${path}`, { method: "POST", body: JSON.stringify(body), unix: socketPath } as RequestInit);
+ const j = await r.json();
+ if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`);
+ return j;
+ }
+ return new Promise((resolve, reject) => {
+ const data = JSON.stringify(body);
+ const req = request(
+ { socketPath, path, method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data) } },
+ (res) => {
+ let buf = "";
+ res.setEncoding("utf8");
+ res.on("data", (c) => (buf += c));
+ res.on("end", () => {
+ const j = buf ? JSON.parse(buf) : null;
+ res.statusCode === 200 ? resolve(j) : reject(new Error(j?.error ?? `HTTP ${res.statusCode}`));
+ });
+ },
+ );
+ req.on("error", reject);
+ req.end(data);
+ });
+}
+
+/** Writes go to the writer process over a unix socket; reads go straight to the file (WAL readers never block). */
+export async function openWriterClient(socketPath: string, dbPath: string, readKind: "bun" | "node"): Promise {
+ const reader = await openSqlite(readKind, dbPath, true);
+ return {
+ lastBusy: 0,
+ all: (s, p) => reader.all(s, p),
+ async tx(stmts) {
+ return (await httpUnix(socketPath, "/tx", { stmts })).rows;
+ },
+ close: () => reader.close(),
+ };
+}
+
+export async function openDb(backend: Backend, env = process.env): Promise {
+ if (backend === "pg") return openPg(env.BENCH_PG_URL!);
+ if (backend === "writer") return openWriterClient(env.BENCH_WRITER_SOCK!, env.BENCH_DB!, (env.BENCH_READ_KIND as any) ?? "bun");
+ return openSqlite(backend, env.BENCH_DB!);
+}
diff --git a/bench/sqlite/lib/notify.ts b/bench/sqlite/lib/notify.ts
new file mode 100644
index 00000000..13fafb66
--- /dev/null
+++ b/bench/sqlite/lib/notify.ts
@@ -0,0 +1,49 @@
+// Replacements for Postgres LISTEN/NOTIFY, all measured the same way: the consumer is
+// woken up somehow, then reads new events after its cursor from the database.
+// pg — LISTEN/NOTIFY (today's Peppa)
+// poll:N — select events where id > cursor every N ms
+// fswatch — fs.watch on the -wal file (+5 s safety poll)
+// push — the writer (or a tiny hub) pushes event ids over a unix socket
+import { watch } from "node:fs";
+import { request } from "node:http";
+import type { Db } from "./db.ts";
+import { httpUnix } from "./db.ts";
+
+export const CHANNEL = "peppa_events";
+
+/** Called by event producers after commit. */
+export async function publish(db: Db, mode: string, eventId: number, env = process.env) {
+ if (mode === "pg") await db.pg.unsafe(`select pg_notify('${CHANNEL}', $1)`, [JSON.stringify({ type: "progress", eventId })]);
+ else if (mode === "push" && env.BENCH_BACKEND !== "writer") await httpUnix(env.BENCH_HUB_SOCK!, "/publish", { ids: [eventId] }).catch(() => {});
+ // writer backend publishes itself after commit; poll/fswatch need nothing.
+}
+
+/** Subscribes `wake` to new events; returns a stop function. */
+export function subscribe(db: Db, mode: string, wake: () => void, env = process.env): () => void {
+ if (mode === "pg") {
+ let l: any;
+ db.pg.listen(CHANNEL, () => wake()).then((x: any) => (l = x));
+ return () => l?.unlisten();
+ }
+ if (mode.startsWith("poll:")) {
+ const t = setInterval(wake, Number(mode.slice(5)));
+ return () => clearInterval(t);
+ }
+ if (mode === "fswatch") {
+ const w = watch(env.BENCH_DB! + "-wal", () => wake());
+ const t = setInterval(wake, 5000);
+ return () => (w.close(), clearInterval(t));
+ }
+ if (mode === "push") {
+ const sock = env.BENCH_BACKEND === "writer" ? env.BENCH_WRITER_SOCK! : env.BENCH_HUB_SOCK!;
+ const req = request({ socketPath: sock, path: "/subscribe", method: "GET" }, (res) => {
+ res.setEncoding("utf8");
+ res.on("data", () => wake());
+ });
+ req.on("error", () => {});
+ req.end();
+ const t = setInterval(wake, 5000);
+ return () => (req.destroy(), clearInterval(t));
+ }
+ throw new Error(`unknown notify mode ${mode}`);
+}
diff --git a/bench/sqlite/lib/schema.ts b/bench/sqlite/lib/schema.ts
new file mode 100644
index 00000000..a75dcac2
--- /dev/null
+++ b/bench/sqlite/lib/schema.ts
@@ -0,0 +1,34 @@
+// The hot part of Peppa's schema (packages/db/src/schema.ts), in both dialects.
+// Timestamps are epoch milliseconds passed as params so the same SQL runs on both.
+
+const tables = (pg: boolean) => {
+ const id = pg ? "serial primary key" : "integer primary key autoincrement";
+ const json = pg ? "jsonb" : "text";
+ const ts = pg ? "bigint" : "integer";
+ return [
+ `create table projects (id ${id}, key text not null unique, name text not null, next_task_number integer not null default 1, updated_at ${ts})`,
+ `create table tasks (id ${id}, project_id integer not null references projects(id) on delete cascade, number integer not null, title text not null, status text not null default 'backlog', updated_at ${ts}, unique(project_id, number))`,
+ `create table sessions (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete set null, tmux_name text not null unique, generation integer not null default 0, auto_nudges integer not null default 0, status text not null default 'starting', last_activity_at ${ts}, started_at ${ts})`,
+ `create table questions (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete cascade, session_id integer references sessions(id) on delete set null, kind text not null, text text not null, options ${json}, answer text, answered_via text, telegram_message_id integer, awaiting_hook boolean not null default false, created_at ${ts}, answered_at ${ts})`,
+ `create table events (id ${id}, project_id integer not null references projects(id) on delete cascade, task_id integer references tasks(id) on delete cascade, session_id integer references sessions(id) on delete set null, type text not null, payload ${json}, created_at ${ts})`,
+ `create index events_task on events(task_id, id)`,
+ `create table settings (key text primary key, value ${json} not null, updated_at ${ts})`,
+ `create table telegram_outbox (id ${id}, dedupe_key text not null unique, method text not null, params ${json} not null, question_id integer references questions(id) on delete set null, status text not null default 'pending', attempts integer not null default 0, next_attempt_at ${ts} not null, telegram_message_id integer, created_at ${ts}, sent_at ${ts})`,
+ `create index outbox_pending on telegram_outbox(status, next_attempt_at)`,
+ `create table telegram_updates (update_id integer primary key, status text not null, created_at ${ts})`,
+ ];
+};
+
+export const sqliteSchema = tables(false);
+export const pgSchema = tables(true);
+
+/** One project, `runners` tasks in progress, one live session per task. */
+export function seedStmts(runners: number): [string, unknown[]][] {
+ const now = Date.now();
+ const out: [string, unknown[]][] = [["insert into projects (key, name, next_task_number, updated_at) values ('PEP', 'Peppa', ?, ?)", [runners + 1, now]]];
+ for (let i = 1; i <= runners; i++) {
+ out.push(["insert into tasks (project_id, number, title, status, updated_at) values (1, ?, ?, 'in_progress', ?)", [i, `Task ${i}`, now]]);
+ out.push(["insert into sessions (project_id, task_id, tmux_name, generation, status, last_activity_at, started_at) values (1, ?, ?, 1, 'running', ?, ?)", [i, `peppa-PEP-${i}-s${i}`, now, now]]);
+ }
+ return out;
+}
diff --git a/bench/sqlite/matrix.sh b/bench/sqlite/matrix.sh
new file mode 100755
index 00000000..efad8770
--- /dev/null
+++ b/bench/sqlite/matrix.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Full PEP-36 matrix. BENCH_PG_URL must point at the throwaway peppa_bench database.
+# BENCH_PG_URL=postgres://…/peppa_bench ./matrix.sh [smoke]
+set -u
+cd "$(dirname "$0")"
+DUR1=${DUR1:-90}; DUR10=${DUR10:-60}
+run() { node run.ts "$@" 2>&1 | grep -vE "^\[bench\]"; }
+if [ "${1:-}" = smoke ]; then
+ for b in "--backend bun --notify push" "--backend writer --notify push" "--backend node --notify fswatch" "--backend pg"; do
+ run $b --runners 3 --load 5 --duration 12 --name smoke | grep -E "==|write ALL|deliver|rror"
+ done
+ exit
+fi
+# 1. Write contention: every backend at 10/20 runners, real load (x1) and x10.
+for r in 10 20; do
+ for x in 1 10; do
+ d=$([ $x = 1 ] && echo $DUR1 || echo $DUR10)
+ run --backend bun --runners $r --load $x --duration $d --notify poll:1000
+ run --backend node --runners $r --load $x --duration $d --notify poll:1000
+ run --backend better --runners $r --load $x --duration $d --notify poll:1000
+ run --backend writer --runners $r --load $x --duration $d --notify push
+ run --backend pg --runners $r --load $x --duration $d --notify pg
+ done
+done
+# 2. LISTEN/NOTIFY replacements on bun:sqlite, 20 runners x10.
+for n in poll:200 poll:1000 fswatch push; do
+ run --backend bun --runners 20 --load 10 --duration $DUR10 --notify $n
+done
+# 3. Saturation: 20 runners at x50 (≈ 100 hook processes/s) — where does each one bend?
+for b in "--backend bun --notify poll:1000" "--backend writer --notify push" "--backend pg --notify pg"; do
+ run $b --runners 20 --load 50 --duration 45
+done
diff --git a/bench/sqlite/package.json b/bench/sqlite/package.json
new file mode 100644
index 00000000..dd910a75
--- /dev/null
+++ b/bench/sqlite/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "peppa-bench-sqlite",
+ "private": true,
+ "type": "module",
+ "description": "PEP-36: SQLite vs Postgres write/notify benchmark under Peppa-like load. Not part of the product.",
+ "dependencies": {
+ "better-sqlite3": "13.1.1",
+ "postgres": "4.1.1"
+ },
+ "pnpm": {
+ "onlyBuiltDependencies": [
+ "better-sqlite3"
+ ]
+ }
+}
diff --git a/bench/sqlite/pnpm-lock.yaml b/bench/sqlite/pnpm-lock.yaml
new file mode 100644
index 00000000..b12da76e
--- /dev/null
+++ b/bench/sqlite/pnpm-lock.yaml
@@ -0,0 +1,40 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ dependencies:
+ better-sqlite3:
+ specifier: 13.1.1
+ version: 13.1.1
+ postgres:
+ specifier: 4.1.1
+ version: 4.1.1
+
+packages:
+
+ better-sqlite3@13.1.1:
+ resolution: {integrity: sha512-JjyLCATp+VLxZVFyWkicyzKYwpEFLCrV4MmshW97xv3JXdhw5jBDcsbEWRGm2L/96E+k7rtjON8q9nml05h3Pw==}
+ engines: {node: '>=22'}
+
+ node-addon-api@8.9.2:
+ resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==}
+ engines: {node: ^18 || ^20 || >= 21}
+
+ postgres@4.1.1:
+ resolution: {integrity: sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug==}
+ engines: {node: '>=18'}
+
+snapshots:
+
+ better-sqlite3@13.1.1:
+ dependencies:
+ node-addon-api: 8.9.2
+
+ node-addon-api@8.9.2: {}
+
+ postgres@4.1.1: {}
diff --git a/bench/sqlite/report.ts b/bench/sqlite/report.ts
new file mode 100644
index 00000000..8328b37f
--- /dev/null
+++ b/bench/sqlite/report.ts
@@ -0,0 +1,48 @@
+// Markdown tables from results/*/summary.json: `node report.ts > results/report.md`.
+import { readdirSync, readFileSync, existsSync } from "node:fs";
+
+const dir = new URL("results/", import.meta.url).pathname;
+const runs = readdirSync(dir)
+ .filter((d) => existsSync(`${dir}${d}/summary.json`))
+ .map((d) => JSON.parse(readFileSync(`${dir}${d}/summary.json`, "utf8")));
+
+const order = ["bun", "node", "better", "writer", "pg"];
+const label: Record = { bun: "bun:sqlite", node: "node:sqlite", better: "better-sqlite3", writer: "один писатель (Bun)", pg: "Postgres (Node)" };
+const f = (v: number) => (Number.isFinite(v) ? (v >= 100 ? v.toFixed(0) : v.toFixed(2)) : "—");
+const row = (r: any, k: string) => r.rows[k] ?? { n: 0, p50: NaN, p95: NaN, p99: NaN, max: NaN, busy: 0, errors: 0 };
+
+console.log("## Записи и доставка\n");
+console.log("| раннеры | нагрузка | вариант | записей | p50 мс | p95 | p99 | max | BUSY-повторы | ошибки | хук целиком p50/p95 | старт хука p50 | доставка боту p50/p95/p99 |");
+console.log("|---|---|---|---|---|---|---|---|---|---|---|---|---|");
+for (const r of runs.filter((r) => r.notify === "pg" || r.notify === "poll:1000" || (r.backend === "writer" && r.notify === "push")).sort((a, b) => a.runners - b.runners || a.load - b.load || order.indexOf(a.backend) - order.indexOf(b.backend))) {
+ if (r.backend === "bun" && r.notify !== "poll:1000") continue;
+ const w = { ...row(r, "write ALL") };
+ // Runs before the fix counted hooks killed by the end-of-run SIGTERM as crashes.
+ if (r.errors.every((e: string) => e === "hook exited with null")) w.errors -= row(r, "write hook.crashed").errors;
+ const h = row(r, "total hook");
+ const s = row(r, "startup hook");
+ const d = row(r, "deliver bot");
+ console.log(`| ${r.runners} | ×${r.load} | ${label[r.backend]} | ${w.n} | ${f(w.p50)} | ${f(w.p95)} | ${f(w.p99)} | ${f(w.max)} | ${w.busy} | ${w.errors} | ${f(h.p50)} / ${f(h.p95)} | ${f(s.p50)} | ${f(d.p50)} / ${f(d.p95)} / ${f(d.p99)} (${r.notify}) |`);
+}
+
+console.log("\n## Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10)\n");
+console.log("| способ | доставка боту p50 | p95 | p99 | max | веб p50 | p95 |");
+console.log("|---|---|---|---|---|---|---|");
+for (const r of runs.filter((r) => r.backend === "bun" && r.runners === 20 && r.load === 10)) {
+ const b = row(r, "deliver bot");
+ const w = row(r, "deliver web");
+ console.log(`| ${r.notify} | ${f(b.p50)} | ${f(b.p95)} | ${f(b.p99)} | ${f(b.max)} | ${f(w.p50)} | ${f(w.p95)} |`);
+}
+const pg = runs.find((r) => r.backend === "pg" && r.runners === 20 && r.load === 10);
+if (pg) {
+ const b = row(pg, "deliver bot");
+ console.log(`| Postgres LISTEN/NOTIFY (для сравнения) | ${f(b.p50)} | ${f(b.p95)} | ${f(b.p99)} | ${f(b.max)} | ${f(row(pg, "deliver web").p50)} | ${f(row(pg, "deliver web").p95)} |`);
+}
+
+console.log("\n## Самые медленные операции записи (p99, мс) при 20 раннерах ×10\n");
+console.log("| операция | " + order.map((b) => label[b]).join(" | ") + " |");
+console.log("|---|" + order.map(() => "---|").join(""));
+const at = (b: string) => runs.find((r) => r.backend === b && r.runners === 20 && r.load === 10 && (b !== "bun" || r.notify === "poll:1000"));
+const ops = new Set();
+for (const b of order) for (const k of Object.keys(at(b)?.rows ?? {})) if (k.startsWith("write ") && k !== "write ALL" && k !== "write hook.crashed") ops.add(k);
+for (const k of [...ops].sort()) console.log(`| ${k.slice(6)} | ` + order.map((b) => f(at(b)?.rows[k]?.p99 ?? NaN)).join(" | ") + " |");
diff --git a/bench/sqlite/roles.ts b/bench/sqlite/roles.ts
new file mode 100644
index 00000000..18dc0d67
--- /dev/null
+++ b/bench/sqlite/roles.ts
@@ -0,0 +1,336 @@
+// One process of the simulated Peppa: ` roles.ts `; run.ts starts them.
+// Load per runner is taken from the live peppa DB (see README.md): a hook every ~10 s
+// (a new process each time, like Claude's command hooks), 10 % of them a blocking
+// question polled every 1.5 s, MCP progress every ~30 s and get_task every ~15 s.
+// BENCH_LOAD multiplies these rates for the stress runs.
+import { spawn } from "node:child_process";
+import { appendFileSync, rmSync } from "node:fs";
+import { createServer, type ServerResponse } from "node:http";
+import { openDb, openSqlite, type Backend, type Db, type Row } from "./lib/db.ts";
+import { publish, subscribe } from "./lib/notify.ts";
+
+const env = process.env;
+const role = process.argv[2];
+const backend = env.BENCH_BACKEND as Backend;
+const mode = env.BENCH_NOTIFY ?? "poll:1000";
+const load = Number(env.BENCH_LOAD ?? 1);
+const now = () => performance.timeOrigin + performance.now();
+// Sleeps end early on SIGTERM so every process stops right after the run.
+const wakers = new Set<() => void>();
+const sleep = (ms: number) =>
+ new Promise((r) => {
+ const done = () => (clearTimeout(t), wakers.delete(done), r());
+ const t = setTimeout(done, ms);
+ wakers.add(done);
+ });
+const expo = (mean: number) => -Math.log(1 - Math.random()) * mean;
+
+const samples: unknown[] = [];
+const rec = (kind: string, op: string, ms: number, extra: object = {}) => samples.push({ kind, op, ms: +ms.toFixed(3), ...extra });
+function flush() {
+ if (samples.length) appendFileSync(`${env.BENCH_OUT}/${role}-${process.pid}.jsonl`, samples.map((s) => JSON.stringify(s)).join("\n") + "\n");
+ samples.length = 0;
+}
+
+let stopping = false;
+const stops: (() => void)[] = [];
+process.on("SIGTERM", () => {
+ stopping = true;
+ stops.forEach((f) => f());
+ wakers.forEach((f) => f());
+});
+
+/** A write transaction with latency, busy retries and errors recorded. */
+async function write(db: Db, op: string, stmts: [string, unknown[]][]): Promise {
+ const t = now();
+ try {
+ const r = await db.tx(stmts);
+ rec("write", op, now() - t, db.lastBusy ? { busy: db.lastBusy } : {});
+ return r;
+ } catch (e) {
+ rec("write", op, now() - t, { busy: db.lastBusy, error: String((e as Error).message).slice(0, 80) });
+ return null;
+ }
+}
+async function read(db: Db, op: string, sql: string, params: unknown[] = []) {
+ const t = now();
+ const r = await db.all(sql, params);
+ rec("read", op, now() - t);
+ return r;
+}
+
+/** Reads events after the cursor whenever woken; records event→consumer latency. */
+function consume(db: Db, who: string) {
+ let cursor = 0;
+ let busy = false;
+ let again = false;
+ const check = async () => {
+ if (busy) return void (again = true);
+ busy = true;
+ try {
+ do {
+ again = false;
+ const rows = await db.all("select id, payload from events where id > ? order by id limit 500", [cursor]);
+ for (const r of rows) {
+ cursor = Number(r.id);
+ const p = typeof r.payload === "string" ? JSON.parse(r.payload) : r.payload;
+ if (p?.t0) rec("deliver", who, now() - p.t0);
+ }
+ } while (again);
+ } finally {
+ busy = false;
+ }
+ };
+ db.all("select coalesce(max(id), 0) m from events").then((r) => (cursor = Number(r[0].m)));
+ stops.push(subscribe(db, mode, () => void check().catch(() => {})));
+}
+
+async function hook() {
+ const t0 = Number(env.BENCH_SPAWN_T);
+ rec("startup", "hook", now() - t0);
+ process.on("exit", flush);
+ const sid = Number(env.BENCH_SESSION);
+ const tOpen = now();
+ const db = await openDb(backend);
+ rec("open", "hook", now() - tOpen);
+ const [s] = await read(db, "hook.session", "select id, task_id, generation from sessions where id = ?", [sid]);
+ const ts = Date.now();
+ if (Math.random() < 0.1) {
+ const r = await write(db, "hook.question", [
+ ["insert into questions (project_id, task_id, session_id, kind, text, options, awaiting_hook, created_at) values (1, ?, ?, 'permission', 'Allow Bash(rm -rf build)', ?, true, ?) returning id", [s.task_id, sid, JSON.stringify(["Да", "Нет"]), ts]],
+ ["update sessions set status = 'waiting_input', last_activity_at = ? where id = ?", [ts, sid]],
+ ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'question', ?, ?) returning id", [s.task_id, sid, JSON.stringify({ t0: now() }), ts]],
+ ]);
+ if (r) {
+ await publish(db, mode, Number(r[2][0].id));
+ const qid = Number(r[0][0].id);
+ const tAsk = now();
+ // Blocking PermissionRequest hook: poll for the PM's answer (hook.ts, every 1.5 s).
+ for (let i = 0; i < 40 && !stopping; i++) {
+ const [q] = await read(db, "hook.poll", "select answer from questions where id = ?", [qid]);
+ if (q?.answer) break;
+ await sleep(1500);
+ }
+ rec("roundtrip", "question", now() - tAsk);
+ await write(db, "hook.answered", [
+ ["update questions set awaiting_hook = false where id = ?", [qid]],
+ ["update sessions set status = 'running', auto_nudges = 0, last_activity_at = ? where id = ?", [Date.now(), sid]],
+ ]);
+ }
+ } else {
+ const r = await write(db, "hook.event", [
+ ["update sessions set status = 'running', last_activity_at = ? where id = ? and generation = ?", [ts, sid, s.generation]],
+ ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'turn_end', ?, ?) returning id", [s.task_id, sid, JSON.stringify({ t0: now(), hook: "Stop" }), ts]],
+ ]);
+ if (r) await publish(db, mode, Number(r[1][0].id));
+ }
+ await db.close();
+ rec("total", "hook", now() - t0);
+ flush();
+}
+
+/** Plays Claude for one session: fires hooks one after another, each a new process. */
+async function runner() {
+ const sid = env.BENCH_SESSION!;
+ while (!stopping) {
+ await sleep(expo(10_000 / load));
+ if (stopping) break;
+ const child = spawn(process.execPath, [new URL(import.meta.url).pathname, "hook"], {
+ env: { ...env, BENCH_SPAWN_T: String(now()), BENCH_SESSION: sid },
+ stdio: ["ignore", "ignore", "inherit"],
+ });
+ const kill = () => child.kill("SIGTERM");
+ stops.push(kill);
+ const code = await new Promise((r) => child.on("exit", r));
+ stops.splice(stops.indexOf(kill), 1);
+ // A hook killed by our own SIGTERM at the end of the run is not a failure.
+ if (code !== 0 && !(code === null && stopping)) rec("write", "hook.crashed", 0, { error: `hook exited with ${code}` });
+ }
+ flush();
+}
+
+async function mcp() {
+ const sid = Number(env.BENCH_SESSION);
+ const db = await openDb(backend);
+ const progress = async () => {
+ while (!stopping) {
+ await sleep(expo(30_000 / load));
+ if (stopping) break;
+ const ts = Date.now();
+ const r = await write(db, "mcp.progress", [
+ ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'progress', ?, ?) returning id", [sid, sid, JSON.stringify({ t0: now(), text: "Сделал шаг 3 из 7" }), ts]],
+ ["update tasks set updated_at = ? where id = ?", [ts, sid]],
+ ]);
+ if (r) await publish(db, mode, Number(r[0][0].id));
+ }
+ };
+ const getTask = async () => {
+ while (!stopping) {
+ await sleep(expo(15_000 / load));
+ if (stopping) break;
+ await read(db, "mcp.get_task", "select * from tasks where id = ?", [sid]);
+ await read(db, "mcp.get_task", "select * from events where task_id = ? order by id desc limit 20", [sid]);
+ }
+ };
+ await Promise.all([progress(), getTask()]);
+ await db.close();
+ flush();
+}
+
+/** Telegram bot: outbox loop (1 s), reconcile (10 s + on events), heartbeat, PM answers. */
+async function bot() {
+ const db = await openDb(backend);
+ consume(db, "bot");
+ let updateId = 1;
+ const answering = new Set();
+ const reconcile = async () => {
+ const qs = await read(db, "bot.reconcile", "select id from questions where answer is null and telegram_message_id is null");
+ for (const q of qs) {
+ const id = Number(q.id);
+ await write(db, "bot.enqueue", [
+ ["insert into telegram_outbox (dedupe_key, method, params, question_id, next_attempt_at, created_at) values (?, 'sendMessage', ?, ?, ?, ?) on conflict (dedupe_key) do nothing", [`q:${id}`, JSON.stringify({ chat_id: 1, text: "?" }), id, Date.now(), Date.now()]],
+ ]);
+ if (answering.has(id)) continue;
+ answering.add(id);
+ // The PM taps a button 2–8 s later: record the update first, then answer (bot.ts).
+ setTimeout(async () => {
+ const u = updateId++;
+ await write(db, "bot.update", [["insert into telegram_updates (update_id, status, created_at) values (?, 'dispatching', ?)", [u, Date.now()]]]);
+ const r = await write(db, "bot.answer", [
+ ["update questions set answer = 'Да', answered_via = 'telegram', answered_at = ? where id = ? and answer is null", [Date.now(), id]],
+ ["update telegram_updates set status = 'done' where update_id = ?", [u]],
+ ["insert into events (project_id, type, payload, created_at) values (1, 'question_answered', ?, ?) returning id", [JSON.stringify({ t0: now() }), Date.now()]],
+ ]);
+ if (r) await publish(db, mode, Number(r[2][0].id));
+ }, 2000 + Math.random() * 6000);
+ }
+ };
+ const loops = [
+ (async () => {
+ while (!stopping) {
+ const rows = await read(db, "bot.outbox", "select id, question_id from telegram_outbox where status = 'pending' and next_attempt_at <= ? order by id limit 20", [Date.now()]);
+ for (const o of rows)
+ await write(db, "bot.sent", [
+ ["update telegram_outbox set status = 'sent', attempts = attempts + 1, telegram_message_id = ?, sent_at = ? where id = ?", [Number(o.id) + 1000, Date.now(), o.id]],
+ ["update questions set telegram_message_id = ? where id = ?", [Number(o.id) + 1000, o.question_id]],
+ ]);
+ await sleep(1000);
+ }
+ })(),
+ (async () => {
+ while (!stopping) {
+ await reconcile();
+ await sleep(2000);
+ }
+ })(),
+ (async () => {
+ while (!stopping) {
+ await write(db, "bot.heartbeat", [["insert into settings (key, value, updated_at) values ('heartbeat:bot', ?, ?) on conflict (key) do update set value = excluded.value, updated_at = excluded.updated_at", [JSON.stringify({ at: Date.now() }), Date.now()]]]);
+ await sleep(30_000);
+ }
+ })(),
+ ];
+ await new Promise((r) => stops.push(r));
+ await Promise.race([Promise.all(loops), sleep(3000)]);
+ flush();
+ await db.close();
+}
+
+/** Web: 3 open boards refreshing every 5 s + a live-update consumer. */
+async function web() {
+ const db = await openDb(backend);
+ consume(db, "web");
+ const viewer = async () => {
+ await sleep(Math.random() * 5000);
+ while (!stopping) {
+ const t = now();
+ await db.all("select id, number, title, status, updated_at from tasks where project_id = 1 order by number");
+ await db.all("select id, task_id, status, last_activity_at from sessions where status in ('starting','running','waiting_input','idle','stalled','rate_limited')");
+ await db.all("select count(*) c from questions where answer is null");
+ await db.all("select id, type, created_at from events where project_id = 1 order by id desc limit 30");
+ rec("read", "web.board", now() - t);
+ await sleep(5000);
+ }
+ };
+ await Promise.all([viewer(), viewer(), viewer()]);
+ flush();
+ await db.close();
+}
+
+/** Watchdog tick every 30 s: list sessions, touch some, heartbeat. */
+async function watchdog() {
+ const db = await openDb(backend);
+ while (!stopping) {
+ const ss = await read(db, "wd.sessions", "select id, task_id, status, last_activity_at from sessions where status not in ('done','failed')");
+ for (const s of ss) {
+ if (Math.random() >= 0.1) continue;
+ const r = await write(db, "wd.stalled", [
+ ["update sessions set status = 'stalled' where id = ? and status = 'running'", [s.id]],
+ ["insert into events (project_id, task_id, session_id, type, payload, created_at) values (1, ?, ?, 'stalled', ?, ?) returning id", [s.task_id, s.id, JSON.stringify({ t0: now() }), Date.now()]],
+ ]);
+ if (r) await publish(db, mode, Number(r[1][0].id));
+ }
+ await write(db, "wd.heartbeat", [["insert into settings (key, value, updated_at) values ('heartbeat:watchdog', ?, ?) on conflict (key) do update set value = excluded.value, updated_at = excluded.updated_at", [JSON.stringify({ at: Date.now() }), Date.now()]]]);
+ for (let i = 0; i < 30 && !stopping; i++) await sleep(1000);
+ }
+ flush();
+ await db.close();
+}
+
+/**
+ * The only process that opens the SQLite file for writing (backend=writer), or just a
+ * notify hub (notify=push with direct SQLite). Pushes new event ids to /subscribe.
+ */
+async function writer() {
+ const sock = env.BENCH_SOCK!;
+ rmSync(sock, { force: true });
+ const db = env.BENCH_HUB_ONLY ? null : await openSqlite((env.BENCH_WRITER_KIND as any) ?? "bun", env.BENCH_DB!);
+ const subs = new Set();
+ const push = (ids: unknown[]) => {
+ const line = JSON.stringify(ids) + "\n";
+ for (const s of subs) s.write(line);
+ };
+ const server = createServer((req, res) => {
+ if (req.url === "/subscribe") {
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.flushHeaders();
+ subs.add(res);
+ req.on("close", () => subs.delete(res));
+ return;
+ }
+ let body = "";
+ req.setEncoding("utf8");
+ req.on("data", (c) => (body += c));
+ req.on("end", async () => {
+ const j = JSON.parse(body);
+ try {
+ if (req.url === "/publish") {
+ push(j.ids);
+ return void res.end("null");
+ }
+ const rows = await db!.tx(j.stmts);
+ const ids = j.stmts.flatMap(([s]: [string], i: number) => (s.startsWith("insert into events") ? rows[i].map((r) => r.id) : []));
+ res.end(JSON.stringify({ rows }));
+ if (ids.length) push(ids);
+ } catch (e) {
+ res.statusCode = 500;
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+ });
+ });
+ server.listen(sock);
+ await new Promise((r) => stops.push(r));
+ server.close();
+ for (const s of subs) s.end();
+ await db?.close();
+}
+
+const roles: Record Promise> = { hook, runner, mcp, bot, web, watchdog, writer };
+roles[role]().then(
+ () => process.exit(0),
+ (e) => {
+ console.error(`[${role}]`, e);
+ flush();
+ process.exit(1);
+ },
+);
diff --git a/bench/sqlite/run.ts b/bench/sqlite/run.ts
new file mode 100644
index 00000000..b63360ad
--- /dev/null
+++ b/bench/sqlite/run.ts
@@ -0,0 +1,128 @@
+// Orchestrator: fresh database, then N runners (+ their hook processes) and N MCP
+// servers, bot, web, watchdog (and the writer/hub when needed) for --duration seconds.
+// node run.ts --backend bun --runtime bun --runners 10 --load 1 --duration 90 --notify poll:1000
+// Prints and saves (results//summary.json) latency percentiles per operation.
+import { spawn, type ChildProcess } from "node:child_process";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { parseArgs } from "node:util";
+import { openPg, openSqlite } from "./lib/db.ts";
+import { pgSchema, seedStmts, sqliteSchema } from "./lib/schema.ts";
+
+const here = new URL(".", import.meta.url).pathname;
+const { values: a } = parseArgs({
+ options: {
+ backend: { type: "string", default: "bun" },
+ runtime: { type: "string" },
+ runners: { type: "string", default: "10" },
+ load: { type: "string", default: "1" },
+ duration: { type: "string", default: "90" },
+ notify: { type: "string" },
+ name: { type: "string" },
+ },
+});
+const backend = a.backend!;
+const runtime = a.runtime ?? (backend === "node" || backend === "better" || backend === "pg" ? "node" : "bun");
+const notify = a.notify ?? (backend === "pg" ? "pg" : "poll:1000");
+const runners = Number(a.runners);
+const name = a.name ?? `${backend}-${runtime}-r${runners}-x${a.load}-${notify.replace(":", "")}`;
+const bin = runtime === "bun" ? `${homedir()}/.bun/bin/bun` : process.execPath;
+
+const work = `${process.env.BENCH_TMP ?? "/tmp"}/peppa-bench-${process.pid}`;
+const out = `${here}results/${name}`;
+rmSync(out, { recursive: true, force: true });
+mkdirSync(out, { recursive: true });
+mkdirSync(work, { recursive: true });
+const sockDir = `/tmp/pb-${process.pid}`;
+mkdirSync(sockDir, { recursive: true });
+
+const env: Record = {
+ ...(process.env as Record),
+ BENCH_BACKEND: backend,
+ BENCH_NOTIFY: notify,
+ BENCH_LOAD: a.load!,
+ BENCH_OUT: out,
+ BENCH_DB: `${work}/peppa.db`,
+ // macOS caps unix socket paths at 104 bytes, so sockets live in a short /tmp dir.
+ BENCH_WRITER_SOCK: `${sockDir}/writer.sock`,
+ BENCH_HUB_SOCK: `${sockDir}/hub.sock`,
+ BENCH_READ_KIND: runtime === "bun" ? "bun" : "node",
+ BENCH_WRITER_KIND: runtime === "bun" ? "bun" : "node",
+};
+
+// Fresh database with the seed.
+if (backend === "pg") {
+ if (!env.BENCH_PG_URL) throw new Error("BENCH_PG_URL (…/peppa_bench) is required");
+ if (!/\/peppa_bench(\?|$)/.test(env.BENCH_PG_URL)) throw new Error("refusing to use a database other than peppa_bench");
+ const db = await openPg(env.BENCH_PG_URL);
+ await db.all("drop schema public cascade");
+ await db.all("create schema public");
+ for (const s of pgSchema) await db.all(s);
+ await db.tx(seedStmts(runners));
+ await db.close();
+} else {
+ const db = await openSqlite("node", env.BENCH_DB);
+ await db.all("PRAGMA journal_mode = WAL");
+ for (const s of sqliteSchema) await db.all(s);
+ await db.tx(seedStmts(runners));
+ await db.close();
+}
+
+const procs: ChildProcess[] = [];
+const start = (role: string, extra: Record = {}) => {
+ const p = spawn(bin, [`${here}roles.ts`, role], { env: { ...env, ...extra }, stdio: ["ignore", "inherit", "inherit"] });
+ procs.push(p);
+ return p;
+};
+const waitSock = async (s: string) => {
+ for (let i = 0; i < 100 && !existsSync(s); i++) await new Promise((r) => setTimeout(r, 50));
+};
+
+const servers: ChildProcess[] = [];
+if (backend === "writer") {
+ servers.push(start("writer", { BENCH_SOCK: env.BENCH_WRITER_SOCK }));
+ await waitSock(env.BENCH_WRITER_SOCK);
+} else if (notify === "push") {
+ servers.push(start("writer", { BENCH_SOCK: env.BENCH_HUB_SOCK, BENCH_HUB_ONLY: "1" }));
+ await waitSock(env.BENCH_HUB_SOCK);
+}
+procs.length = 0;
+const clients = [start("bot"), start("web"), start("watchdog")];
+for (let i = 1; i <= runners; i++) clients.push(start("mcp", { BENCH_SESSION: String(i) }), start("runner", { BENCH_SESSION: String(i) }));
+
+console.error(`[bench] ${name}: ${clients.length} processes for ${a.duration}s`);
+await new Promise((r) => setTimeout(r, Number(a.duration) * 1000));
+const exited = (ps: ChildProcess[]) => Promise.all(ps.map((p) => (p.exitCode !== null ? null : new Promise((r) => p.on("exit", r)))));
+for (const p of clients) p.kill("SIGTERM");
+await Promise.race([exited(clients), new Promise((r) => setTimeout(r, 90_000).unref())]);
+for (const p of servers) p.kill("SIGTERM");
+await exited(servers);
+
+// Aggregate.
+type S = { kind: string; op: string; ms: number; busy?: number; error?: string };
+const all: S[] = readdirSync(out)
+ .filter((f) => f.endsWith(".jsonl"))
+ .flatMap((f) => readFileSync(`${out}/${f}`, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)));
+const pct = (xs: number[], p: number) => (xs.length ? xs[Math.min(xs.length - 1, Math.floor((p / 100) * xs.length))] : NaN);
+const summarize = (xs: S[]) => {
+ const ms = xs.map((x) => x.ms).sort((x, y) => x - y);
+ const r = (v: number) => +v.toFixed(2);
+ return { n: ms.length, p50: r(pct(ms, 50)), p95: r(pct(ms, 95)), p99: r(pct(ms, 99)), max: r(ms.at(-1) ?? NaN), busy: xs.reduce((s, x) => s + (x.busy ?? 0), 0), errors: xs.filter((x) => x.error).length };
+};
+const groups = new Map();
+for (const s of all) {
+ const k = `${s.kind} ${s.op}`;
+ groups.set(k, [...(groups.get(k) ?? []), s]);
+}
+const rows: Record> = {};
+rows["write ALL"] = summarize(all.filter((s) => s.kind === "write"));
+for (const k of [...groups.keys()].sort()) rows[k] = summarize(groups.get(k)!);
+const errors = [...new Set(all.filter((s) => s.error).map((s) => s.error))];
+const summary = { name, backend, runtime, notify, runners, load: Number(a.load), duration: Number(a.duration), rows, errors, at: new Date().toISOString() };
+writeFileSync(`${out}/summary.json`, JSON.stringify(summary, null, 2));
+for (const f of readdirSync(out)) if (f.endsWith(".jsonl")) rmSync(`${out}/${f}`);
+console.log(`\n== ${name}`);
+console.table(rows);
+if (errors.length) console.log("errors:", errors);
+rmSync(work, { recursive: true, force: true });
+rmSync(sockDir, { recursive: true, force: true });
diff --git a/bench/sqlite/schema-port/copy-from-pg.ts b/bench/sqlite/schema-port/copy-from-pg.ts
new file mode 100644
index 00000000..60bf8a77
--- /dev/null
+++ b/bench/sqlite/schema-port/copy-from-pg.ts
@@ -0,0 +1,53 @@
+// PEP-36 prototype: copy a Peppa Postgres database into a fresh SQLite file using the
+// ported schema, then read it back through drizzle and compare row counts.
+// bun copy-from-pg.ts
+// The Postgres session is read-only (default_transaction_read_only), so pointing it at
+// the live database cannot change anything there.
+import { Database } from "bun:sqlite";
+import { drizzle } from "drizzle-orm/bun-sqlite";
+import { migrate } from "drizzle-orm/bun-sqlite/migrator";
+import postgres from "postgres";
+import * as schema from "./schema.ts";
+
+const [url, out] = process.argv.slice(2);
+if (!url || !out) throw new Error("usage: bun copy-from-pg.ts ");
+
+const pg = postgres(url, { max: 1, connection: { default_transaction_read_only: "on" } as any });
+const file = new Database(out, { create: true });
+file.exec("PRAGMA busy_timeout = 5000");
+file.exec("PRAGMA journal_mode = WAL");
+const db = drizzle(file, { schema });
+migrate(db, { migrationsFolder: new URL("migrations", import.meta.url).pathname });
+
+// Parents before children (foreign keys are enforced).
+const order = [
+ "users", "projects", "project_members", "project_invites", "goals", "tasks", "sessions", "questions", "events",
+ "settings", "telegram_outbox", "telegram_updates", "oauth_clients", "oauth_codes", "oauth_tokens",
+ "incident_settings", "error_sources", "incidents",
+];
+const toSqlite = (v: unknown) =>
+ v instanceof Date ? v.getTime() : typeof v === "boolean" ? (v ? 1 : 0) : v !== null && typeof v === "object" ? JSON.stringify(v) : typeof v === "bigint" ? Number(v) : v;
+
+file.exec("PRAGMA foreign_keys = ON");
+const t0 = performance.now();
+const counts: Record = {};
+for (const t of order) {
+ const rows = await pg.unsafe(`select * from ${t}`);
+ if (rows.length) {
+ const cols = Object.keys(rows[0]);
+ const ins = file.prepare(`insert into ${t} (${cols.map((c) => `"${c}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`);
+ file.transaction(() => {
+ for (const r of rows) ins.run(...(cols.map((c) => toSqlite(r[c])) as any[]));
+ })();
+ }
+ const [{ n }] = file.query(`select count(*) n from ${t}`).all() as { n: number }[];
+ counts[t] = [rows.length, n];
+}
+const ms = performance.now() - t0;
+await pg.end();
+
+// Read back through drizzle: relations, timestamps as Date, json as objects, enums as text.
+const tasks = await db.query.tasks.findMany({ with: { project: true, sessions: true }, limit: 3 });
+const q = await db.query.questions.findFirst({ where: (q, { isNotNull }) => isNotNull(q.options) });
+const fk = file.query("PRAGMA foreign_key_check").all();
+console.log(JSON.stringify({ ms: Math.round(ms), counts, mismatched: Object.entries(counts).filter(([, [a, b]]) => a !== b), fkViolations: fk.length, sample: { task: tasks[0] && { key: `${tasks[0].project.key}-${tasks[0].number}`, createdAt: tasks[0].createdAt, isDate: tasks[0].createdAt instanceof Date, sessions: tasks[0].sessions.length }, questionOptions: q?.options, optionsIsArray: Array.isArray(q?.options) } }, null, 2));
diff --git a/bench/sqlite/schema-port/drizzle.config.ts b/bench/sqlite/schema-port/drizzle.config.ts
new file mode 100644
index 00000000..308c2681
--- /dev/null
+++ b/bench/sqlite/schema-port/drizzle.config.ts
@@ -0,0 +1,2 @@
+import { defineConfig } from "drizzle-kit";
+export default defineConfig({ dialect: "sqlite", schema: "./schema.ts", out: "./migrations" });
diff --git a/bench/sqlite/schema-port/migrations/0000_baseline.sql b/bench/sqlite/schema-port/migrations/0000_baseline.sql
new file mode 100644
index 00000000..ab29ddb1
--- /dev/null
+++ b/bench/sqlite/schema-port/migrations/0000_baseline.sql
@@ -0,0 +1,271 @@
+CREATE TABLE `error_sources` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `kind` text NOT NULL,
+ `bugsink_project_id` integer NOT NULL,
+ `dsn` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `error_sources_bugsink_project_id_unique` ON `error_sources` (`bugsink_project_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `error_sources_project_kind` ON `error_sources` (`project_id`,`kind`);--> statement-breakpoint
+CREATE TABLE `events` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `session_id` integer,
+ `type` text NOT NULL,
+ `payload` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `goals` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `title` text NOT NULL,
+ `description` text,
+ `status` text DEFAULT 'open' NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `incident_settings` (
+ `project_id` integer PRIMARY KEY NOT NULL,
+ `hook_secret` text NOT NULL,
+ `policy` text DEFAULT 'backlog' NOT NULL,
+ `triage_prompt` text,
+ `environments` text DEFAULT '["prod","production"]' NOT NULL,
+ `daily_limit` integer DEFAULT 5 NOT NULL,
+ `ignore_pattern` text,
+ `goal_id` integer,
+ `webhook_auto` integer DEFAULT false NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `incident_settings_hook_secret_unique` ON `incident_settings` (`hook_secret`);--> statement-breakpoint
+CREATE TABLE `incidents` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `source` text NOT NULL,
+ `bugsink_issue_id` text NOT NULL,
+ `friendly_id` text,
+ `title` text NOT NULL,
+ `culprit` text,
+ `level` text,
+ `environment` text,
+ `first_release` text,
+ `last_release` text,
+ `events` integer DEFAULT 1 NOT NULL,
+ `first_seen` integer NOT NULL,
+ `last_seen` integer NOT NULL,
+ `url` text,
+ `stack` text,
+ `status` text DEFAULT 'new' NOT NULL,
+ `decision` text,
+ `decided_by` text,
+ `decision_reason` text,
+ `task_id` integer,
+ `task_created_at` integer,
+ `resolved_release` text,
+ `resolved_at` integer,
+ `regressions` integer DEFAULT 0 NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `incidents_bugsink_issue_id_unique` ON `incidents` (`bugsink_issue_id`);--> statement-breakpoint
+CREATE TABLE `oauth_clients` (
+ `id` text PRIMARY KEY NOT NULL,
+ `name` text NOT NULL,
+ `redirect_uris` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `oauth_codes` (
+ `code_hash` text PRIMARY KEY NOT NULL,
+ `client_id` text NOT NULL,
+ `user_id` integer NOT NULL,
+ `redirect_uri` text NOT NULL,
+ `code_challenge` text NOT NULL,
+ `scope` text,
+ `expires_at` integer NOT NULL,
+ `used_at` integer,
+ FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `oauth_tokens` (
+ `token_hash` text PRIMARY KEY NOT NULL,
+ `kind` text NOT NULL,
+ `client_id` text NOT NULL,
+ `user_id` integer NOT NULL,
+ `scope` text,
+ `expires_at` integer NOT NULL,
+ `revoked_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `last_used_at` integer,
+ FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `project_invites` (
+ `project_id` integer NOT NULL,
+ `login` text NOT NULL,
+ `invited_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ PRIMARY KEY(`project_id`, `login`),
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`invited_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `project_members` (
+ `project_id` integer NOT NULL,
+ `user_id` integer NOT NULL,
+ `added_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ PRIMARY KEY(`project_id`, `user_id`),
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`added_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `projects` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `slug` text NOT NULL,
+ `key` text NOT NULL,
+ `name` text NOT NULL,
+ `description` text,
+ `gitea_owner` text NOT NULL,
+ `gitea_repo` text NOT NULL,
+ `default_branch` text DEFAULT 'main' NOT NULL,
+ `workspace_path` text NOT NULL,
+ `owner_id` integer,
+ `next_task_number` integer DEFAULT 1 NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `projects_slug_unique` ON `projects` (`slug`);--> statement-breakpoint
+CREATE UNIQUE INDEX `projects_key_unique` ON `projects` (`key`);--> statement-breakpoint
+CREATE TABLE `questions` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `session_id` integer,
+ `kind` text NOT NULL,
+ `text` text NOT NULL,
+ `options` text,
+ `answer` text,
+ `answered_via` text,
+ `telegram_message_id` integer,
+ `awaiting_hook` integer DEFAULT false NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `answered_at` integer,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `sessions` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `tmux_name` text NOT NULL,
+ `provider` text DEFAULT 'claude' NOT NULL,
+ `claude_session_id` text,
+ `generation` integer DEFAULT 0 NOT NULL,
+ `auto_nudges` integer DEFAULT 0 NOT NULL,
+ `resume_at` integer,
+ `limit_probe_min` integer,
+ `limit_resumes` integer DEFAULT 0 NOT NULL,
+ `limit_resumes_day` text,
+ `limit_resumed_at` integer,
+ `status` text DEFAULT 'starting' NOT NULL,
+ `last_activity_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `ended_at` integer,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `sessions_tmux_name_unique` ON `sessions` (`tmux_name`);--> statement-breakpoint
+CREATE TABLE `settings` (
+ `key` text PRIMARY KEY NOT NULL,
+ `value` text NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `tasks` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `goal_id` integer,
+ `number` integer NOT NULL,
+ `title` text NOT NULL,
+ `description` text,
+ `status` text DEFAULT 'backlog' NOT NULL,
+ `openspec_change` text,
+ `pr_url` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `tasks_project_number` ON `tasks` (`project_id`,`number`);--> statement-breakpoint
+CREATE TABLE `telegram_outbox` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `dedupe_key` text NOT NULL,
+ `method` text NOT NULL,
+ `params` text NOT NULL,
+ `question_id` integer,
+ `status` text DEFAULT 'pending' NOT NULL,
+ `attempts` integer DEFAULT 0 NOT NULL,
+ `next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `telegram_message_id` integer,
+ `error` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `sent_at` integer,
+ FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `telegram_outbox_dedupe_key_unique` ON `telegram_outbox` (`dedupe_key`);--> statement-breakpoint
+CREATE TABLE `telegram_updates` (
+ `update_id` integer PRIMARY KEY NOT NULL,
+ `status` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `users` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `gitea_id` integer NOT NULL,
+ `login` text NOT NULL,
+ `name` text,
+ `email` text,
+ `avatar_url` text,
+ `access_token_enc` text,
+ `refresh_token_enc` text,
+ `token_expires_at` integer,
+ `claude_token_enc` text,
+ `claude_token_set_at` integer,
+ `telegram_chat_id` integer,
+ `telegram_user_id` integer,
+ `telegram_username` text,
+ `telegram_paired_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `last_login_at` integer
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `users_gitea_id_unique` ON `users` (`gitea_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `users_login_unique` ON `users` (`login`);--> statement-breakpoint
+CREATE UNIQUE INDEX `users_telegram_chat_id_unique` ON `users` (`telegram_chat_id`);
\ No newline at end of file
diff --git a/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json b/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json
new file mode 100644
index 00000000..01d02036
--- /dev/null
+++ b/bench/sqlite/schema-port/migrations/meta/0000_snapshot.json
@@ -0,0 +1,1947 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "d623ae37-1edf-4383-bd4f-443a1954867e",
+ "prevId": "00000000-0000-0000-0000-000000000000",
+ "tables": {
+ "error_sources": {
+ "name": "error_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "columns": [
+ "bugsink_project_id"
+ ],
+ "isUnique": true
+ },
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ "project_id",
+ "kind"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "error_sources_project_id_projects_id_fk": {
+ "name": "error_sources_project_id_projects_id_fk",
+ "tableFrom": "error_sources",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "events": {
+ "name": "events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "goals": {
+ "name": "goals",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incident_settings": {
+ "name": "incident_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[\"prod\",\"production\"]'"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "columns": [
+ "hook_secret"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_settings_project_id_projects_id_fk": {
+ "name": "incident_settings_project_id_projects_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incident_settings_goal_id_goals_id_fk": {
+ "name": "incident_settings_goal_id_goals_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incidents": {
+ "name": "incidents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "columns": [
+ "bugsink_issue_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incidents_project_id_projects_id_fk": {
+ "name": "incidents_project_id_projects_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_task_id_tasks_id_fk": {
+ "name": "incidents_task_id_tasks_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_clients": {
+ "name": "oauth_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_codes": {
+ "name": "oauth_codes",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_tokens": {
+ "name": "oauth_tokens",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_invites": {
+ "name": "project_invites",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "columns": [
+ "project_id",
+ "login"
+ ],
+ "name": "project_invites_project_id_login_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_members": {
+ "name": "project_members",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "columns": [
+ "project_id",
+ "user_id"
+ ],
+ "name": "project_members_project_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "questions": {
+ "name": "questions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude'"
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "columns": [
+ "tmux_name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tasks": {
+ "name": "tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ "project_id",
+ "number"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_outbox": {
+ "name": "telegram_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "params": {
+ "name": "params",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_updates": {
+ "name": "telegram_updates",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "columns": [
+ "gitea_id"
+ ],
+ "isUnique": true
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "columns": [
+ "login"
+ ],
+ "isUnique": true
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "columns": [
+ "telegram_chat_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/bench/sqlite/schema-port/migrations/meta/_journal.json b/bench/sqlite/schema-port/migrations/meta/_journal.json
new file mode 100644
index 00000000..82b04f9e
--- /dev/null
+++ b/bench/sqlite/schema-port/migrations/meta/_journal.json
@@ -0,0 +1,13 @@
+{
+ "version": "7",
+ "dialect": "sqlite",
+ "entries": [
+ {
+ "idx": 0,
+ "version": "6",
+ "when": 1794565466624,
+ "tag": "0000_baseline",
+ "breakpoints": true
+ }
+ ]
+}
\ No newline at end of file
diff --git a/bench/sqlite/schema-port/schema.ts b/bench/sqlite/schema-port/schema.ts
new file mode 100644
index 00000000..4b36f55e
--- /dev/null
+++ b/bench/sqlite/schema-port/schema.ts
@@ -0,0 +1,357 @@
+import { relations } from "drizzle-orm";
+import { sql } from "drizzle-orm";
+import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+
+// PEP-36 prototype: the Peppa schema mechanically ported to SQLite (not used by the product).
+const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
+
+const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs);
+const updatedAt = () =>
+ integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date());
+
+/** People who log into the web, one per Gitea account. */
+export const users = sqliteTable("users", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ giteaId: integer("gitea_id").notNull().unique(),
+ login: text("login").notNull().unique(),
+ name: text("name"),
+ email: text("email"),
+ avatarUrl: text("avatar_url"),
+ // OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts).
+ accessTokenEnc: text("access_token_enc"),
+ refreshTokenEnc: text("refresh_token_enc"),
+ tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
+ // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the
+ // Claude sessions of this user's projects.
+ claudeTokenEnc: text("claude_token_enc"),
+ claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }),
+ // Telegram chat paired from Settings; agent questions of this user's projects go there.
+ telegramChatId: integer("telegram_chat_id").unique(),
+ telegramUserId: integer("telegram_user_id"),
+ telegramUsername: text("telegram_username"),
+ telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
+ createdAt: createdAt(),
+ lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }),
+});
+
+export const projects = sqliteTable("projects", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ slug: text("slug").notNull().unique(),
+ // Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2…
+ key: text("key").notNull().unique(),
+ name: text("name").notNull(),
+ description: text("description"),
+ giteaOwner: text("gitea_owner").notNull(),
+ giteaRepo: text("gitea_repo").notNull(),
+ defaultBranch: text("default_branch").notNull().default("main"),
+ workspacePath: text("workspace_path").notNull(),
+ // Null for projects created by the bot/CLI; only the owner sees a project in the web.
+ ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }),
+ // Next task number to hand out; bumped atomically on task creation.
+ nextTaskNumber: integer("next_task_number").notNull().default(1),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
+/** People who work on a project besides its owner (projects.owner_id). */
+export const projectMembers = sqliteTable(
+ "project_members",
+ {
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
+ addedBy: integer("added_by").references(() => users.id, { onDelete: "set null" }),
+ createdAt: createdAt(),
+ },
+ (t) => [primaryKey({ columns: [t.projectId, t.userId] })],
+);
+
+/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */
+export const projectInvites = sqliteTable(
+ "project_invites",
+ {
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ login: text("login").notNull(), // lower-cased Gitea login
+ invitedBy: integer("invited_by").references(() => users.id, { onDelete: "set null" }),
+ createdAt: createdAt(),
+ },
+ (t) => [primaryKey({ columns: [t.projectId, t.login] })],
+);
+
+export const goalStatusValues = ["open", "done", "archived"] as const;
+
+/** Top-level objectives set by the PM; tasks are broken out of them. */
+export const goals = sqliteTable("goals", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ title: text("title").notNull(),
+ description: text("description"),
+ status: text("status", { enum: goalStatusValues }).notNull().default("open"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
+export const taskStatusValues = [
+ "backlog", // created, nobody working on it
+ "proposing", // agent is writing the OpenSpec change
+ "awaiting_approval", // proposal ready, PM must approve
+ "in_progress", // agent applying the change
+ "review", // PR open in Gitea
+ "done", // change archived, merged
+ "blocked",
+] as const;
+
+export const tasks = sqliteTable(
+ "tasks",
+ {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
+ number: integer("number").notNull(),
+ title: text("title").notNull(),
+ description: text("description"),
+ status: text("status", { enum: taskStatusValues }).notNull().default("backlog"),
+ // OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth"
+ openspecChange: text("openspec_change"),
+ prUrl: text("pr_url"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)],
+);
+
+export const sessionStatusValues = [
+ "starting",
+ "running",
+ "waiting_input", // Claude asked something / needs permission
+ "idle", // turn finished, nothing pending
+ "stalled", // watchdog saw no activity
+ "rate_limited", // StopFailure with error=rate_limit, or limit banner on screen
+ "done",
+ "failed",
+] as const;
+
+/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
+export const sessions = sqliteTable("sessions", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
+ tmuxName: text("tmux_name").notNull().unique(),
+ provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"),
+ // Claude session id or Codex thread id — the resume target.
+ conversationId: text("claude_session_id"),
+ // Bumped on every launch/resume; hooks from an older generation are ignored.
+ generation: integer("generation").notNull().default(0),
+ // Consecutive "keep going" nudges from the Stop hook; reset when a human answers.
+ autoNudges: integer("auto_nudges").notNull().default(0),
+ // Usage limit recovery (PEP-56): when to continue, current probe interval if the reset
+ // time is unknown, auto-resumes today (cap), and when the last auto-resume happened.
+ resumeAt: integer("resume_at", { mode: "timestamp_ms" }),
+ limitProbeMin: integer("limit_probe_min"),
+ limitResumes: integer("limit_resumes").notNull().default(0),
+ limitResumesDay: text("limit_resumes_day"),
+ limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }),
+ status: text("status", { enum: sessionStatusValues }).notNull().default("starting"),
+ lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }),
+ startedAt: createdAt(),
+ endedAt: integer("ended_at", { mode: "timestamp_ms" }),
+});
+
+/** Questions routed to the PM (Telegram / web) and their answers. */
+export const questions = sqliteTable("questions", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
+ // Null when asked from a session Peppa did not start (manual `claude`).
+ sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
+ kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
+ text: text("text").notNull(),
+ options: text("options", { mode: "json" }).$type(),
+ answer: text("answer"),
+ // "system": closed by Peppa itself (session stopped/resumed), not by a person.
+ answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }),
+ telegramMessageId: integer("telegram_message_id"),
+ // A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer,
+ // so it must not also be typed into the terminal.
+ awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false),
+ createdAt: createdAt(),
+ answeredAt: integer("answered_at", { mode: "timestamp_ms" }),
+});
+
+/** Event log: hook / watchdog events, progress reports, status changes. */
+export const events = sqliteTable("events", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
+ sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
+ type: text("type").notNull(),
+ payload: text("payload", { mode: "json" }),
+ createdAt: createdAt(),
+});
+
+/** Small key/value store for service state (Telegram offset, pairing, binding). */
+export const settings = sqliteTable("settings", {
+ key: text("key").primaryKey(),
+ value: text("value", { mode: "json" }).notNull(),
+ updatedAt: updatedAt(),
+});
+
+/**
+ * Durable Telegram outbox: every message/edit is queued here first, then delivered with
+ * retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message).
+ */
+export const telegramOutbox = sqliteTable("telegram_outbox", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ dedupeKey: text("dedupe_key").notNull().unique(),
+ method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(),
+ params: text("params", { mode: "json" }).$type>().notNull(),
+ questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
+ status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"),
+ attempts: integer("attempts").notNull().default(0),
+ nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs),
+ telegramMessageId: integer("telegram_message_id"),
+ error: text("error"),
+ createdAt: createdAt(),
+ sentAt: integer("sent_at", { mode: "timestamp_ms" }),
+});
+
+/** Telegram updates already taken: recorded before acting, so a restart never replays one. */
+export const telegramUpdates = sqliteTable("telegram_updates", {
+ updateId: integer("update_id").primaryKey(),
+ status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(),
+ createdAt: createdAt(),
+});
+
+/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */
+export const oauthClients = sqliteTable("oauth_clients", {
+ id: text("id").primaryKey(),
+ name: text("name").notNull(),
+ redirectUris: text("redirect_uris", { mode: "json" }).$type().notNull(),
+ createdAt: createdAt(),
+});
+
+/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */
+export const oauthCodes = sqliteTable("oauth_codes", {
+ codeHash: text("code_hash").primaryKey(),
+ clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }),
+ userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
+ redirectUri: text("redirect_uri").notNull(),
+ codeChallenge: text("code_challenge").notNull(),
+ scope: text("scope"),
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
+ usedAt: integer("used_at", { mode: "timestamp_ms" }),
+});
+
+/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */
+export const oauthTokens = sqliteTable("oauth_tokens", {
+ tokenHash: text("token_hash").primaryKey(),
+ kind: text("kind", { enum: ["access", "refresh"] }).notNull(),
+ clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }),
+ userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
+ scope: text("scope"),
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
+ revokedAt: integer("revoked_at", { mode: "timestamp_ms" }),
+ createdAt: createdAt(),
+ lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
+});
+
+export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const;
+export type IncidentPolicy = (typeof incidentPolicies)[number];
+
+/** Error tracking of a project (PEP-58): webhook secret and how new errors are handled. */
+export const incidentSettings = sqliteTable("incident_settings", {
+ projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),
+ // Part of the webhook URL Bugsink posts alerts to: /api/hooks/bugsink/.
+ hookSecret: text("hook_secret").notNull().unique(),
+ policy: text("policy", { enum: incidentPolicies }).notNull().default("backlog"),
+ // The PM's mini-prompt for the triage agent ("how to decide").
+ triagePrompt: text("triage_prompt"),
+ environments: text("environments", { mode: "json" }).$type().notNull().default(["prod", "production"]),
+ dailyLimit: integer("daily_limit").notNull().default(5),
+ ignorePattern: text("ignore_pattern"),
+ goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
+ // False: the alert webhook still has to be added in Bugsink by hand (polling covers it).
+ webhookAuto: integer("webhook_auto", { mode: "boolean" }).notNull().default(false),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
+/** Bugsink projects feeding a Peppa project: one for the frontend, one for the backend. */
+export const errorSources = sqliteTable(
+ "error_sources",
+ {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ kind: text("kind", { enum: ["web", "api"] }).notNull(),
+ bugsinkProjectId: integer("bugsink_project_id").notNull().unique(),
+ dsn: text("dsn").notNull(),
+ createdAt: createdAt(),
+ },
+ (t) => [uniqueIndex("error_sources_project_kind").on(t.projectId, t.kind)],
+);
+
+export const incidentStatuses = ["new", "open", "pending", "task", "ignored", "resolved", "regressed"] as const;
+
+/** A Bugsink issue seen in Peppa. Repeated events update the same row. */
+export const incidents = sqliteTable("incidents", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ source: text("source", { enum: ["web", "api"] }).notNull(),
+ bugsinkIssueId: text("bugsink_issue_id").notNull().unique(),
+ friendlyId: text("friendly_id"),
+ title: text("title").notNull(),
+ culprit: text("culprit"),
+ level: text("level"),
+ environment: text("environment"),
+ firstRelease: text("first_release"),
+ lastRelease: text("last_release"),
+ events: integer("events").notNull().default(1),
+ firstSeen: integer("first_seen", { mode: "timestamp_ms" }).notNull(),
+ lastSeen: integer("last_seen", { mode: "timestamp_ms" }).notNull(),
+ url: text("url"),
+ stack: text("stack"),
+ // new → open | pending | task | ignored; task → resolved → regressed (see design.md)
+ status: text("status", { enum: incidentStatuses }).notNull().default("new"),
+ decision: text("decision", { enum: ["notify", "backlog", "start", "ask", "ignore"] }),
+ decidedBy: text("decided_by", { enum: ["policy", "triage", "pm"] }),
+ decisionReason: text("decision_reason"),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
+ taskCreatedAt: integer("task_created_at", { mode: "timestamp_ms" }),
+ resolvedRelease: text("resolved_release"),
+ resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }),
+ regressions: integer("regressions").notNull().default(0),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
+export const projectsRelations = relations(projects, ({ many }) => ({
+ goals: many(goals),
+ tasks: many(tasks),
+ sessions: many(sessions),
+}));
+export const goalsRelations = relations(goals, ({ one, many }) => ({
+ project: one(projects, { fields: [goals.projectId], references: [projects.id] }),
+ tasks: many(tasks),
+}));
+export const tasksRelations = relations(tasks, ({ one, many }) => ({
+ project: one(projects, { fields: [tasks.projectId], references: [projects.id] }),
+ goal: one(goals, { fields: [tasks.goalId], references: [goals.id] }),
+ sessions: many(sessions),
+ questions: many(questions),
+ events: many(events),
+}));
+export const sessionsRelations = relations(sessions, ({ one, many }) => ({
+ project: one(projects, { fields: [sessions.projectId], references: [projects.id] }),
+ task: one(tasks, { fields: [sessions.taskId], references: [tasks.id] }),
+ questions: many(questions),
+ events: many(events),
+}));
+export const questionsRelations = relations(questions, ({ one }) => ({
+ project: one(projects, { fields: [questions.projectId], references: [projects.id] }),
+ task: one(tasks, { fields: [questions.taskId], references: [tasks.id] }),
+ session: one(sessions, { fields: [questions.sessionId], references: [sessions.id] }),
+}));
+export const eventsRelations = relations(events, ({ one }) => ({
+ project: one(projects, { fields: [events.projectId], references: [projects.id] }),
+ task: one(tasks, { fields: [events.taskId], references: [tasks.id] }),
+ session: one(sessions, { fields: [events.sessionId], references: [sessions.id] }),
+}));
diff --git a/bench/sqlite/schema-port/tx-check.ts b/bench/sqlite/schema-port/tx-check.ts
new file mode 100644
index 00000000..2182f226
--- /dev/null
+++ b/bench/sqlite/schema-port/tx-check.ts
@@ -0,0 +1,35 @@
+// PEP-36 prototype: does drizzle's bun:sqlite driver keep `await` inside db.transaction()?
+// core/tasks.ts (createTask) is written that way for postgres-js.
+import { Database } from "bun:sqlite";
+import { eq, sql } from "drizzle-orm";
+import { drizzle } from "drizzle-orm/bun-sqlite";
+import { migrate } from "drizzle-orm/bun-sqlite/migrator";
+import * as schema from "./schema.ts";
+
+const db = drizzle(new Database(":memory:"), { schema });
+migrate(db, { migrationsFolder: new URL("migrations", import.meta.url).pathname });
+await db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp" });
+
+// 1. Async callback, as in core/tasks.ts.
+try {
+ await db.transaction(async (tx) => {
+ const [p] = await tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning();
+ await tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title: "t" });
+ throw new Error("rollback please");
+ });
+} catch (e) {
+ console.log("async tx threw:", (e as Error).message);
+}
+const [p1] = await db.select().from(schema.projects);
+const t1 = await db.select().from(schema.tasks);
+console.log("after async tx + throw: next_task_number =", p1.nextTaskNumber, "tasks =", t1.length, t1.length || p1.nextTaskNumber !== 1 ? "→ NOT rolled back" : "→ rolled back");
+
+// 2. Sync callback (what the sqlite drivers expect).
+try {
+ db.transaction((tx) => {
+ tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run();
+ throw new Error("rollback please");
+ });
+} catch {}
+const [p2] = await db.select().from(schema.projects);
+console.log("after sync tx + throw: next_task_number =", p2.nextTaskNumber, p2.nextTaskNumber === 100 ? "→ NOT rolled back" : "→ rolled back");
diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md
new file mode 100644
index 00000000..955ed09c
--- /dev/null
+++ b/openspec/changes/pep-36-lightweight-stack/design.md
@@ -0,0 +1,215 @@
+# Design: PEP-36 — Bun + SQLite
+
+## Контекст
+
+В базу Пеппы пишут одновременно: веб (server actions, OAuth, health), бот (outbox,
+telegram_updates, ответы), вачдог (tick раз в 30 с, heartbeat, лимиты, Bugsink), **хук
+каждого события Claude — отдельный короткий процесс**, MCP-сервер каждого раннера и CLI.
+Бот узнаёт о новых событиях через Postgres LISTEN/NOTIFY (`core/notify.ts`,
+`apps/bot/src/bot.ts`). Вопрос этапа: тянет ли это SQLite, чем заменить NOTIFY и что
+сломается под Bun.
+
+Всё ниже измерено на Mac Пеппы (Apple Silicon, Node 26.8, Bun 1.4.4, Postgres 17.11 в
+docker) бенчмарком `bench/sqlite` (методика — `bench/sqlite/README.md`).
+
+## Реальная нагрузка (боевая БД, только чтение)
+
+- 107 событий за сутки на 5 сессиях; медианный промежуток между событиями одной сессии
+ 16 с, пик — 6 событий в минуту на сессию.
+- Хуки срабатывают на prompt / notification / stop / permission, не на каждый tool use.
+- База — 9 МБ. Самые «горячие» таблицы по числу изменений: sessions, oauth_tokens, tasks,
+ events, settings, telegram_outbox.
+
+Модель бенчмарка берёт это с запасом (хук раз в 10 с на раннер, 10 % — блокирующий вопрос
+с опросом раз в 1,5 с, MCP progress раз в 30 с, get_task раз в 15 с, бот, 3 доски веба
+раз в 5 с, вачдог), плюс стресс ×10 и ×50.
+
+## Результаты
+
+### Запись при параллельной работе раннеров
+
+p50/p95/p99/max — время транзакции записи в мс (включая ожидание блокировки); «хук» —
+время старта процесса хука до первой строки кода (без tsx, см. ниже).
+
+| раннеры | нагрузка | вариант | записей | p50 | p95 | p99 | max | SQLITE_BUSY | ошибки | старт хука p50 |
+|---|---|---|---|---|---|---|---|---|---|---|
+| 10 | ×1 | bun:sqlite | 126 | 0.32 | 1.61 | 2.34 | 2.68 | 0 | 0 | 32 мс |
+| 10 | ×1 | node:sqlite | 192 | 0.20 | 0.70 | 1.18 | 1.27 | 0 | 0 | 96 мс |
+| 10 | ×1 | better-sqlite3 | 169 | 0.19 | 0.95 | 2.02 | 2.21 | 0 | 0 | 97 мс |
+| 10 | ×1 | один писатель | 140 | 1.21 | 2.35 | 3.89 | 8.19 | 0 | 0 | 23 мс |
+| 10 | ×1 | **Postgres (сейчас)** | 177 | 9.60 | 18.11 | 36.05 | 38.15 | — | 0 | 92 мс |
+| 20 | ×1 | bun:sqlite | 327 | 0.29 | 1.34 | 2.21 | 3.06 | 0 | 0 | 28 мс |
+| 20 | ×1 | node:sqlite | 324 | 0.16 | 0.71 | 1.33 | 2.00 | 0 | 0 | 72 мс |
+| 20 | ×1 | better-sqlite3 | 314 | 0.19 | 0.82 | 1.53 | 2.20 | 0 | 0 | 88 мс |
+| 20 | ×1 | один писатель | 305 | 1.34 | 2.38 | 4.16 | 7.41 | 0 | 0 | 25 мс |
+| 20 | ×1 | **Postgres (сейчас)** | 306 | 8.06 | 17.16 | 29.14 | 36.39 | — | 0 | 85 мс |
+| 20 | ×10 | bun:sqlite | 1510 | 0.20 | 0.46 | 1.75 | 6.17 | 0 | 0 | 19 мс |
+| 20 | ×10 | node:sqlite | 1424 | 0.13 | 0.24 | 1.32 | 2.29 | 0 | 0 | 69 мс |
+| 20 | ×10 | better-sqlite3 | 1471 | 0.16 | 0.27 | 1.17 | 7.86 | 0 | 0 | 69 мс |
+| 20 | ×10 | один писатель | 1438 | 1.07 | 2.02 | 2.63 | 8.42 | 0 | 0 | 20 мс |
+| 20 | ×10 | **Postgres (сейчас)** | 1345 | 6.98 | 11.89 | 17.85 | 43.83 | — | 0 | 68 мс |
+| 20 | ×50 | bun:sqlite | 3172 | 0.15 | 0.35 | 1.83 | 7.48 | 0 | 0 | 16 мс |
+| 20 | ×50 | один писатель | 3093 | 0.30 | 1.58 | 2.23 | 9.16 | 0 | 0 | 16 мс |
+| 20 | ×50 | **Postgres (сейчас)** | 2910 | 4.58 | 9.19 | 12.13 | 29.31 | — | 0 | 68 мс |
+
+Полные таблицы по каждой операции — `node bench/sqlite/report.ts` после прогона.
+Чтения: доска веба (4 запроса) p99 0,2 мс на SQLite против 5,8 мс на Postgres; опрос
+ответа хуком p99 0,2 мс против 2,2 мс.
+
+**Вывод:** при реальной нагрузке и даже при ×50 (≈ 70 записей/с — больше упирается в
+запуск процессов хука, чем в базу) SQLite в WAL не дал ни одного SQLITE_BUSY и ни одной
+ошибки; запись в 25–50 раз быстрее Postgres по медиане и в 6–15 раз по p99. Причина —
+нет сетевого хопа и соединения: процесс хука открывает файл за 2 мс против 8 мс на
+соединение с Postgres.
+
+### Потолок: все процессы пишут без пауз
+
+`bench/sqlite/contention.ts`: N процессов пишут транзакцию хука (update + insert) подряд,
+10 секунд. Это в ~1000 раз выше реальной нагрузки.
+
+| вариант | процессов | транзакций/с | p50 | p95 | p99 | max | BUSY-повторы | ошибки |
+|---|---|---|---|---|---|---|---|---|
+| bun:sqlite | 20 | 33 537 | 0.02 | 0.08 | 4.24 | 2711 | 0 | 0 |
+| bun:sqlite | 40 | 27 223 | 0.03 | 0.31 | 21.96 | 2931 | 0 | 0 |
+| node:sqlite | 20 | 48 578 | 0.02 | 0.03 | 0.05 | 5406 | 1 | 0 |
+| node:sqlite | 40 | 47 694 | 0.02 | 0.03 | 0.06 | 6413 | 3 | 0 |
+| better-sqlite3 | 20 | 47 456 | 0.02 | 0.03 | 0.05 | 5360 | 1 | 0 |
+| better-sqlite3 | 40 | 45 076 | 0.02 | 0.03 | 0.06 | 5938 | 2 | 0 |
+| Postgres | 20 | 4 890 | 3.88 | 6.82 | 9.01 | 97 | — | 0 |
+| Postgres | 40 | 7 555 | 5.47 | 6.95 | 8.33 | 210 | — | 0 |
+
+**Вывод:** запас по пропускной способности — три-четыре порядка. Слабое место SQLite —
+**хвост при насыщении**: блокировка записи не очередь FIFO, а повторные попытки с паузами,
+поэтому единичные транзакции ждут секунды (max 3–6 с), а при `busy_timeout=5000` бывают
+единичные SQLITE_BUSY (повтор спасает, ошибок 0). Postgres в насыщении предсказуемее
+(max 0,1–0,2 с). Для Пеппы это не актуально, пока запись — короткие транзакции раз в
+секунды; это и есть граница, где Postgres «как дополнение» имеет смысл (см. ниже).
+
+Наблюдение: `bun:sqlite` на macOS использует системную SQLite 3.43 (Node 26 — встроенную
+3.53, better-sqlite3 — 3.54), отсюда хуже p99 в насыщении. В Docker на Linux Bun несёт
+свою свежую SQLite; на Mac можно подключить свежую через `Database.setCustomSQLite`.
+
+### Замена LISTEN/NOTIFY (bun:sqlite, 20 раннеров, ×10)
+
+Задержка от момента записи события до момента, когда бот/веб его прочитали.
+
+| способ | бот p50 | p95 | p99 | max |
+|---|---|---|---|---|
+| **push** (сигнал по unix-сокету) | 0.80 | 1.42 | 2.48 | 47 |
+| fs.watch на `-wal` | 26 | 192 | 300 | 508 |
+| опрос с курсором 200 мс | 100 | 192 | 200 | 204 |
+| опрос с курсором 1000 мс | 503 | 945 | 991 | 1002 |
+| Postgres LISTEN/NOTIFY (сейчас) | 9.76 | 15.06 | 17.73 | 28 |
+
+- **push** быстрее NOTIFY в 10 раз; при недоступном сокете подписчик не узнаёт о событии
+ до страховочного опроса.
+- **fs.watch** на macOS склеивает и теряет уведомления (в смоуке единичные события
+ доходили только страховочным опросом через 3 с), в Docker с bind-mount с хоста Mac не
+ работает совсем (inotify не проходит через VM). Отвергнут.
+- **опрос** надёжен и прост, 200 мс — дешёвый запрос по индексу (0,1 мс), но всегда
+ добавляет задержку.
+
+### Bun на текущем коде (без изменений кода)
+
+| что | результат |
+|---|---|
+| `peppa` CLI (`help`, `project add`, `goal add`, `task add/list`) | работает; старт 0,04 с против 0,47 с у tsx |
+| `peppa-hook` | работает (запись события + `pg_notify`); старт **0,04 с против 0,44 с у tsx** |
+| `peppa-mcp` (stdio, SDK MCP) | работает: `tools/list`, `list_goals`, `list_tasks`, `get_task` |
+| drizzle + postgres.js, мигратор | работает: все 12 миграций применены под Bun |
+| бот (`bot.test.ts`, LISTEN, mock-telegram) | 13/13 тестов под `bun test` |
+| весь e2e под `bun test` (13 файлов, по одному) | **134 прошли, 0 упали** (1 пропущен, как и под tsx); бинари внутри тестов (mock-claude, peppa-mcp, peppa-hook) пока через tsx |
+| `bun --bun next dev` (Next 16.4, Turbopack) | работает: готов за 0,2 с, `/api/health` 200, вход по login-link, доска `/p/BUN`, задача `/t/BUN-1`, раннеры, настройки, помощь — 200; `node_modules/.bin/next` — shell-шим pnpm, запускать `next/dist/bin/next` |
+| node:test | `bun test` понимает `node:test` (`describe/it/before`); прямой запуск файла `bun x.test.ts` — нет, нужен `bun test` |
+| tsx-специфика | не нужна: Bun исполняет `.ts` с импортами `.ts` как есть |
+
+Хук — главный выигрыш: Claude ждёт хук на каждом событии, а PermissionRequest/
+AskUserQuestion — ещё и человека; 0,4 с на старт tsx сейчас — это 90 % времени хука.
+
+### Схема и данные на SQLite (`bench/sqlite/schema-port`)
+
+- Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`,
+ `serial` → `integer primaryKey autoIncrement`, `timestamp withTimezone` →
+ `integer mode timestamp_ms` (drizzle отдаёт `Date`, как сейчас), `jsonb` → `text mode
+ json` (отдаёт объекты), `pgEnum` → `text enum` (типы в TS те же), `boolean` →
+ `integer mode boolean`, `bigint` → `integer` (64 бита), `defaultNow()` →
+ `unixepoch('subsec')*1000`. drizzle-kit генерирует одну базовую миграцию (18 таблиц,
+ 270 строк) вместо 12 миграций Postgres — историю миграций Postgres не переносим.
+- **Перенос боевых данных** (Postgres только на чтение → новый файл): 57 мс, все 18 таблиц
+ совпали по числу строк, 0 нарушений внешних ключей; drizzle читает `Date`, массивы JSON,
+ связи (`db.query.tasks.findMany({ with: … })`).
+- **Ловушка: асинхронные транзакции.** sqlite-драйверы drizzle (`bun-sqlite`,
+ `better-sqlite3`) синхронные: `db.transaction(async tx => { await …; await … })`
+ коммитит после первого `await`, остальное идёт вне транзакции, и **откат не работает**
+ (проверено: `tx-check.ts`, `next_task_number` и задача остались после исключения).
+ В коде такой одна — `createTask` (core/tasks.ts); переписать на синхронную и запретить
+ `transaction(async` проверкой.
+- Прочая Postgres-специфика: `pg_notify` (core/notify.ts), `$client.listen` (бот),
+ `for update skip locked` (core/incidents.ts — не нужно, `BEGIN IMMEDIATE` и так
+ сериализует писателей), `count(*)::int` (monitor/incidents). `->>`, `lower()`, `like`,
+ `returning`, `on conflict` в SQLite есть.
+
+## Решения
+
+### 1. Переезжать целиком, Postgres не держать
+
+Замер не нашёл места, где Postgres нужен Пеппе: по задержке SQLite лучше на всех
+режимах, ошибок блокировки нет, запас по пропускной способности — тысячи раз. Гибрид
+(SQLite + Postgres для части таблиц) добавил бы два драйвера, два способа уведомлений и
+распределённые транзакции между базами ради нагрузки, которой нет. Чаты PM решил долго не
+хранить — их объём тоже не повод. Postgres «как дополнение» возвращаем точечно, если
+появится поток записей на сотни в секунду длинными транзакциями (там, где у SQLite
+хвост блокировок) — например, хранение логов терминалов раннеров (PEP-9).
+
+Отвергнуто: «не переезжать» — Postgres медленнее на нашей нагрузке и требует отдельного
+контейнера; «гибрид сейчас» — сложность без измеренной причины.
+
+### 2. Каждый процесс пишет сам, без сервиса-писателя
+
+Вариант «один писатель» (все записи по HTTP через unix-сокет) медленнее прямой записи в
+4–6 раз по медиане (1,1–1,3 мс против 0,2–0,3), добавляет точку отказа (упал писатель —
+встали хуки всех раннеров) и процесс, который нужно поднимать раньше всех. Его плюс —
+FIFO-очередь записи без хвостов — нужен только при насыщении, которого нет.
+
+Правила для всех процессов (обёртка в `packages/db`):
+- `PRAGMA busy_timeout = 5000` **первой** командой — иначе при одновременном открытии
+ файла многими процессами бывает `SQLITE_BUSY_RECOVERY` без ожидания (поймано в смоуке);
+- `journal_mode=WAL` один раз при создании файла; `synchronous=NORMAL`, `foreign_keys=ON`;
+- запись — `BEGIN IMMEDIATE`, транзакции короткие и синхронные, до 3 повторов на BUSY;
+- база только на локальном диске (WAL не работает на сетевых ФС).
+
+### 3. LISTEN/NOTIFY → журнал событий + сигнал + страховочный опрос
+
+Источник правды — таблица `events` и курсор подписчика (`settings`, ключ
+`cursor:`), так бот после рестарта дочитывает пропущенное (сейчас NOTIFY,
+пришедший во время рестарта, теряется, спасает только reconcile раз в 10 с). Записавший
+процесс шлёт датаграмму «есть новое» в unix-сокет `~/.peppa/events.sock` каждого
+подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в
+секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала.
+
+### 4. Поэтапно: Bun → SQLite → Docker
+
+Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; даёт ускорение хука в
+10 раз сразу. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме
+только чтения как откатом. Этап 3 зависит от PEP-17/PEP-18: раннеры (tmux + claude +
+рабочие копии) должны видеть тот же файл базы на локальном диске; самый простой вариант —
+сервисы и раннеры в одном контейнере с томами хоста.
+
+## Риски
+
+- **Хвост блокировок при насыщении** (max секунды) — не проявился на нагрузке ×50; следим
+ метрикой «время записи p99» в heartbeat, порог алерта 1 с.
+- **Повреждение/потеря файла** — WAL устойчив к падению процесса; ежедневная копия
+ `VACUUM INTO` (7 штук) и копия перед переносом.
+- **Next.js под Bun** — dev-режим работает (проверено), но `bun --bun` для Next официально
+ экспериментальный; запасной вариант — веб на Node, остальное на Bun: SQLite это не мешает
+ (`node:sqlite` в Node 26 работает с тем же файлом, замерено).
+- **Bugsink** держит свою базу в контейнере `peppa-postgres` — контейнер нельзя удалить,
+ пока Bugsink не переведён (отдельная задача; Bugsink умеет SQLite).
+- `better-sqlite3` под Node 26 нет готовых бинарников (сборка node-gyp из исходников,
+ версия 12.x не собирается вовсе) — в Docker на Node это лишняя сборка; `bun:sqlite` и
+ `node:sqlite` встроены.
+
+## Открытые вопросы
+
+См. «Решения PM» в proposal.md.
diff --git a/openspec/changes/pep-36-lightweight-stack/proposal.md b/openspec/changes/pep-36-lightweight-stack/proposal.md
new file mode 100644
index 00000000..1e084be8
--- /dev/null
+++ b/openspec/changes/pep-36-lightweight-stack/proposal.md
@@ -0,0 +1,67 @@
+# Proposal: PEP-36 — легковесный стек: Bun + SQLite, запуск одной командой
+
+Задача Пеппы: **PEP-36** · Цель «Безопасность и эксплуатация».
+
+## Why
+
+Пеппу сейчас поднимают Node + tsx + pnpm + Postgres в docker + `next build`. Для одной
+машины это тяжело: отдельный контейнер БД, сборка веба после каждой правки, медленный
+старт процессов (хук Claude — это новый процесс tsx на каждое событие, ~0,44 с только на
+старт). PM решил (2026-11-13): вся Пеппа на Bun + SQLite (WAL), Postgres — только как
+дополнение там, где SQLite не тянет параллельные записи; переписку чатов долго не храним.
+
+Перед переездом нужно было ответить на вопрос: выдержит ли один файл SQLite записи из
+многих процессов (веб, бот, вачдог, хуки и MCP каждого раннера), чем заменить
+LISTEN/NOTIFY и что сломается под Bun. Замер сделан (`bench/sqlite`, цифры в design.md).
+
+## What Changes
+
+Рекомендация по замеру — **переезжать целиком, поэтапно**; Postgres для Пеппы не нужен.
+
+- **Этап 1 — Bun вместо tsx** (без смены БД): обёртки бинарей, launchd, тесты на
+ `bun test`. Текущий код уже работает под Bun без правок (CLI, хук, MCP, бот, e2e бота).
+ Хук стартует за 0,04 с вместо 0,44 с.
+- **Этап 2 — SQLite вместо Postgres**: схема на `sqlite-core` (одна базовая миграция
+ вместо 12), каждый процесс открывает файл сам (WAL + `busy_timeout`), без отдельного
+ сервиса-писателя; LISTEN/NOTIFY → журнал `events` с курсором + сигнал по unix-сокету +
+ опрос раз в секунду как страховка; перенос данных командой со сверкой; ежедневная копия.
+- **Этап 3 — `docker compose up`**: один образ на Bun для веба, бота и вачдога; база и
+ рабочие копии в томах хоста. Связан с PEP-17 (песочница) и PEP-18 (деплой).
+
+Вне scope: переезд Bugsink (у него своя база в контейнере Postgres, см. «Решения PM»),
+хранение чатов (PM: долго не храним).
+
+## Capabilities
+
+### New Capabilities
+- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Bun, запуск одной командой.
+
+### Modified Capabilities
+- `service-monitoring`: health-эндпоинт проверяет файл SQLite вместо Postgres.
+
+## Impact
+
+- `packages/db` (схема, клиент, миграции), `packages/core/src/notify.ts`, `core/tasks.ts`
+ (транзакция), `core/incidents.ts` (`for update skip locked`), `apps/bot` (подписка),
+ `apps/web` (живые обновления, health), `packages/testkit` (БД тестов), bin-обёртки,
+ `scripts/install-launchd.sh`, `infra/`.
+- Зависимости: −`postgres`, −`tsx` (после этапа 1), +Bun ≥ 1.4 на машине или в образе.
+- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос занимает доли секунды).
+
+## Решения PM
+
+1. **Переезд целиком или гибрид?** Рекомендация: целиком. Замер не нашёл места, где
+ Postgres нужен: при 20 раннерах и нагрузке до ×50 запись в SQLite в 25–50 раз (по медиане)
+ быстрее, без единой блокировки. Postgres можно вернуть точечно, если появится
+ нагрузка другого порядка (например, хранение чатов в больших объёмах).
+2. **Как развести записи многих процессов?** Рекомендация: каждый процесс пишет сам
+ (WAL + `busy_timeout` + `BEGIN IMMEDIATE`), без сервиса-писателя. Писатель по сокету
+ медленнее (лишний переход), добавляет точку отказа и не нужен при наших частотах.
+3. **Замена LISTEN/NOTIFY**: журнал `events` с курсором + сигнал по unix-сокету от
+ записавшего процесса + опрос раз в секунду. fs.watch отвергнут: на macOS теряет события.
+4. **Bugsink**: его база `bugsink` живёт в том же контейнере `peppa-postgres`. Оставить
+ контейнер только под Bugsink или перевести Bugsink на его встроенный SQLite (отдельная
+ задача)? Рекомендация: отдельная задача, контейнер пока остаётся для Bugsink.
+5. **Порядок**: этап 1 (Bun) можно делать сразу — он обратим и не трогает данные. Этап 2
+ — после этапа 1, с неделей отката на Postgres в режиме только чтения. Этап 3 — после
+ решений PEP-17/PEP-18 о том, где живут раннеры.
diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
new file mode 100644
index 00000000..1a43aad8
--- /dev/null
+++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
@@ -0,0 +1,95 @@
+# Spec Delta: platform-storage
+
+## Purpose
+
+Описывает, где Пеппа хранит свои данные после переезда на Bun + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой.
+
+## ADDED Requirements
+
+### Requirement: Одна база SQLite для всех процессов
+Все процессы Пеппы (веб, бот, вачдог, `peppa-hook`, `peppa-mcp`, CLI) SHALL хранить данные в одном файле SQLite в режиме WAL. Каждый процесс SHALL открывать файл сам, первой командой выставлять ожидание блокировки не меньше 5 секунд и писать короткими транзакциями с немедленным захватом записи. Запись, которая не получила блокировку за время ожидания, SHALL повторяться до 3 раз и только потом считаться ошибкой; ошибка SHALL попадать в лог процесса с именем операции.
+
+#### Scenario: 20 раннеров пишут одновременно
+- **GIVEN** 20 раннеров в работе, у каждого свои процессы хуков и MCP, бот, веб и вачдог запущены
+- **WHEN** за 10 минут хуки, MCP, бот и вачдог записывают 6000 событий, вопросов и обновлений сессий
+- **THEN** в базе ровно 6000 новых записей, ни одна запись не завершилась ошибкой «database is locked», 99 % записей заняли меньше 20 мс
+
+#### Scenario: Много процессов открывают базу одновременно
+- **GIVEN** файл базы существует и в нём идут записи
+- **WHEN** 20 процессов хука стартуют в одну и ту же секунду
+- **THEN** все 20 открывают базу и записывают свои события, ни один не завершается с кодом `SQLITE_BUSY_RECOVERY`
+
+#### Scenario: Блокировка держится дольше ожидания
+- **GIVEN** посторонний процесс держит транзакцию записи 20 секунд
+- **WHEN** хук раннера «PEP-42» пытается записать событие `turn_end`
+- **THEN** хук делает 3 попытки, затем пишет в `~/.peppa/hook.log` строку с `hook.event` и `SQLITE_BUSY` и завершается без зависания Claude дольше 30 секунд
+
+### Requirement: Живые обновления без Postgres
+Бот и веб SHALL узнавать о новых событиях, вопросах и изменениях задач, читая журнал `events` по курсору (id последнего прочитанного события). Процесс, записавший событие, SHALL будить подписчиков коротким сигналом по локальному сокету; если сигнал не дошёл, подписчик SHALL всё равно найти событие опросом не реже раза в секунду.
+
+#### Scenario: Вопрос агента доходит до PM
+- **GIVEN** бот запущен, PM привязал Telegram
+- **WHEN** агент раннера «PEP-42» задаёт вопрос «Удалить build?»
+- **THEN** бот видит вопрос и ставит сообщение PM в очередь в среднем быстрее 50 мс и в 99 % случаев быстрее 1 секунды
+
+#### Scenario: Сокет подписки недоступен
+- **GIVEN** бот запущен, сокет сигналов не создан или упал
+- **WHEN** MCP раннера «PEP-42» пишет `report_progress` «Сделал шаг 3 из 7»
+- **THEN** бот читает это событие не позже чем через 1 секунду после записи
+
+#### Scenario: Бот перезапустился
+- **GIVEN** бот остановлен, курсор бота — событие 120, за время простоя записаны события 121–125
+- **WHEN** бот запускается
+- **THEN** бот обрабатывает события 121–125 по одному разу и сохраняет курсор 125
+
+### Requirement: Перенос данных из Postgres
+Переезд SHALL выполняться командой, которая читает боевую базу Postgres только на чтение, создаёт новый файл SQLite по актуальной схеме, переносит все таблицы и сверяет число строк и внешние ключи. При любом расхождении команда SHALL удалять новый файл, оставлять Postgres без изменений и печатать, в какой таблице расхождение.
+
+#### Scenario: Успешный перенос
+- **GIVEN** в Postgres 18 таблиц Пеппы, среди них 107 событий, 18 вопросов и 47 сообщений outbox
+- **WHEN** администратор запускает `peppa db migrate-to-sqlite ~/.peppa/peppa.db`
+- **THEN** создан файл `~/.peppa/peppa.db`, в нём 107 событий, 18 вопросов и 47 сообщений outbox, проверка внешних ключей без нарушений, команда печатает «перенесено, расхождений нет»
+
+#### Scenario: Расхождение при переносе
+- **GIVEN** в таблице `questions` есть строка, ссылающаяся на несуществующую сессию
+- **WHEN** администратор запускает перенос
+- **THEN** файл SQLite не создан, Postgres не изменён, команда печатает «questions: нарушение внешнего ключа» и завершается с кодом 1
+
+### Requirement: Резервная копия базы
+Вачдог SHALL раз в сутки делать согласованную копию файла базы без остановки сервисов и хранить последние 7 копий; копия SHALL открываться как самостоятельная база.
+
+#### Scenario: Ночная копия
+- **GIVEN** сервисы работают, раннеры пишут события
+- **WHEN** наступает время ежедневной копии
+- **THEN** в `~/.peppa/backups/` появляется файл с датой, он открывается и содержит все задачи на момент копии, копий не больше 7
+
+#### Scenario: Нет места на диске
+- **GIVEN** на диске меньше места, чем размер базы
+- **WHEN** вачдог делает копию
+- **THEN** неполная копия удалена, админы платформы получают сообщение «резервная копия не сделана: нет места», сервисы продолжают работать
+
+### Requirement: Сервисы Пеппы на Bun
+Веб (режим разработки Next.js без сборки), бот, вачдог, `peppa-hook`, `peppa-mcp` и CLI SHALL запускаться под Bun без tsx и pnpm. Хук SHALL стартовать и закончить запись события быстрее 150 мс.
+
+#### Scenario: Хук на каждое событие
+- **GIVEN** раннер «PEP-42» работает, Claude вызывает хук Stop
+- **WHEN** `peppa-hook stop` получает событие
+- **THEN** событие `turn_end` записано, хук завершился быстрее 150 мс
+
+#### Scenario: Нет Bun на машине
+- **GIVEN** на машине не установлен Bun
+- **WHEN** администратор запускает `peppa status`
+- **THEN** команда печатает «нужен Bun ≥ 1.4: https://bun.sh» и завершается с кодом 1
+
+### Requirement: Запуск одной командой
+Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Bun: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске.
+
+#### Scenario: Первый запуск
+- **GIVEN** чистая машина с Docker, заполненный `.env`
+- **WHEN** администратор выполняет `docker compose up -d`
+- **THEN** через минуту `GET /api/health` отвечает 200, `db.ok: true`, бот и вачдог в сводке «работает»
+
+#### Scenario: База на сетевом диске
+- **GIVEN** том с базой смонтирован как сетевая папка (NFS/SMB)
+- **WHEN** сервис Пеппы стартует
+- **THEN** сервис не запускается и пишет «файл базы на сетевом диске: SQLite WAL требует локальный диск»
diff --git a/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md
new file mode 100644
index 00000000..6b7dd9d8
--- /dev/null
+++ b/openspec/changes/pep-36-lightweight-stack/specs/service-monitoring/spec.md
@@ -0,0 +1,16 @@
+# Spec Delta: service-monitoring
+
+## MODIFIED Requirements
+
+### Requirement: Health-эндпоинт
+Веб SHALL отвечать на `GET /api/health` JSON-сводкой: доступность БД, версия и коммит, состояние сервисов; код ответа 200, если БД доступна, иначе 503. Сводка не содержит логинов и чатов пользователей.
+
+#### Scenario: Всё работает
+- **GIVEN** БД доступна, версия Пеппы 0.15.0
+- **WHEN** запрошен `/api/health`
+- **THEN** ответ 200 с `ok: true`, `db.ok: true`, `version: "0.15.0"` и списком сервисов web, bot, watchdog
+
+#### Scenario: БД недоступна
+- **GIVEN** файл базы SQLite не открывается (удалён, нет прав или повреждён)
+- **WHEN** запрошен `/api/health`
+- **THEN** ответ 503 с `ok: false`, `db.ok: false` и текстом ошибки, не дольше чем за 3 секунды
diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md
new file mode 100644
index 00000000..18d162fe
--- /dev/null
+++ b/openspec/changes/pep-36-lightweight-stack/tasks.md
@@ -0,0 +1,41 @@
+# Tasks: PEP-36
+
+## 0. Замер и решение (этот этап)
+
+- [x] 0.1 Частоты записи из боевой БД (только чтение): события, вопросы, сессии, outbox
+- [x] 0.2 Бенчмарк `bench/sqlite`: 10 и 20 раннеров, ×1 и ×10; bun:sqlite, node:sqlite, better-sqlite3, один писатель, Postgres
+- [x] 0.3 Прототипы замены LISTEN/NOTIFY: опрос с курсором, fs.watch WAL, push по unix-сокету
+- [x] 0.4 Текущий код под Bun: CLI, `peppa-hook`, `peppa-mcp`, бот, e2e (`bun test`), `next dev`
+- [x] 0.5 Прототип схемы на sqlite (`bench/sqlite/schema-port`): базовая миграция, перенос боевых данных, проверка транзакций drizzle
+- [ ] 0.6 Решение PM по «Решениям PM» в proposal.md (request_approval)
+
+## 1. Этап 1 — Bun вместо tsx (без смены БД)
+
+- [ ] 1.1 Обёртки `packages/*/bin/*` и `apps/bot/bin/*`: `bun` вместо `tsx`, проверка версии Bun (≥ 1.4) с понятной ошибкой
+- [ ] 1.2 Тесты: `bun test` вместо `tsx --test` (node:test работает в Bun); прогнать весь e2e, починить расхождения
+- [ ] 1.3 launchd-агенты бота и вачдога на Bun; веб — `bun --bun next dev`/`next start` по итогам проверки 0.4
+- [ ] 1.4 Замер хука на живой машине: старт и запись события (цель < 150 мс)
+
+## 2. Этап 2 — SQLite вместо Postgres
+
+- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `bun:sqlite`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
+- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции
+- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async`
+- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` и `lower()` работают как есть
+- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме
+- [ ] 2.6 `peppa db migrate-to-sqlite `: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении
+- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл
+- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude)
+- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (Bugsink остаётся на своём Postgres или переезжает отдельно)
+
+## 3. Этап 3 — запуск одной командой
+
+- [ ] 3.1 Образ на `oven/bun` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста
+- [ ] 3.2 Согласовать с PEP-17 (песочница) и PEP-18 (деплой): где живут раннеры, как контейнер видит рабочие копии и токены
+- [ ] 3.3 `docker compose up` на чистой машине → health 200 за минуту; документация в README и `/help`
+- [ ] 3.4 Отказ запуска, если база на сетевом диске
+
+## 4. Завершение
+
+- [ ] 4.1 AGENTS.md, docs/HANDOFF.md, `/help` — новый стек и команды
+- [ ] 4.2 Архив change, PR
--
2.45.2
From eeb326cc4fb4e6e5af39008be6cd5a0779e3bcf9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:28:59 +0500
Subject: [PATCH 012/532] =?UTF-8?q?PEP-36:=20PM=20decision=20=E2=80=94=20N?=
=?UTF-8?q?ode=2026=20+=20node:sqlite;=20drizzle=20shim=20and=20check?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
bench/sqlite/README.md | 4 +-
bench/sqlite/RESULTS.md | 9 ++
bench/sqlite/schema-port/drizzle-check.ts | 96 +++++++++++++++++++
.../sqlite/schema-port/node-sqlite-driver.ts | 93 ++++++++++++++++++
.../pep-36-lightweight-stack/design.md | 64 ++++++++++---
.../pep-36-lightweight-stack/proposal.md | 77 +++++++--------
.../specs/platform-storage/spec.md | 21 ++--
.../changes/pep-36-lightweight-stack/tasks.md | 24 +++--
8 files changed, 312 insertions(+), 76 deletions(-)
create mode 100644 bench/sqlite/schema-port/drizzle-check.ts
create mode 100644 bench/sqlite/schema-port/node-sqlite-driver.ts
diff --git a/bench/sqlite/README.md b/bench/sqlite/README.md
index db7c344a..ac8249e3 100644
--- a/bench/sqlite/README.md
+++ b/bench/sqlite/README.md
@@ -1,7 +1,9 @@
# PEP-36: замер SQLite vs Postgres под нагрузкой Пеппы
Не часть продукта: отдельный `package.json` вне pnpm-воркспейса, свои зависимости.
-Результаты и выводы — в `openspec/changes/pep-36-lightweight-stack/design.md`.
+Результаты — `RESULTS.md`, выводы — `openspec/changes/pep-36-lightweight-stack/design.md`.
+Решение PM: Node 26 + `node:sqlite` (Bun замерен для сравнения). Прототип драйвера drizzle
+на `node:sqlite` — `schema-port/node-sqlite-driver.ts`, проверки — `node schema-port/drizzle-check.ts`.
```bash
cd bench/sqlite
diff --git a/bench/sqlite/RESULTS.md b/bench/sqlite/RESULTS.md
index 72e9576a..c12b7993 100644
--- a/bench/sqlite/RESULTS.md
+++ b/bench/sqlite/RESULTS.md
@@ -68,3 +68,12 @@
{"backend":"pg","procs":20,"seconds":10,"txPerSec":4890,"p50":"3.88","p95":"6.82","p99":"9.01","max":"97.1","busyRetries":0,"errors":0}
{"backend":"pg","procs":40,"seconds":10,"txPerSec":7555,"p50":"5.47","p95":"6.95","p99":"8.33","max":"210.2","busyRetries":0,"errors":0}
```
+
+## drizzle на node:sqlite и bun:sqlite (`schema-port/drizzle-check.ts`)
+
+Транзакция хука (update sessions + insert events) через drizzle, 20 000 подряд в одном процессе:
+
+| драйвер | мкс на транзакцию |
+|---|---|
+| node:sqlite (Node 26.8, прослойка `node-sqlite-driver.ts`) | 53.0 |
+| bun:sqlite (Bun 1.4.4, `drizzle-orm/bun-sqlite`) | 62.9 |
diff --git a/bench/sqlite/schema-port/drizzle-check.ts b/bench/sqlite/schema-port/drizzle-check.ts
new file mode 100644
index 00000000..00ba80fb
--- /dev/null
+++ b/bench/sqlite/schema-port/drizzle-check.ts
@@ -0,0 +1,96 @@
+// PEP-36 prototype: Peppa's ported schema through drizzle on node:sqlite (Node 26) or
+// bun:sqlite (Bun) — migrations, typed round trips, transactions, and the cost of a
+// hook-like write through the ORM.
+// node drizzle-check.ts bun drizzle-check.ts
+import { eq, sql } from "drizzle-orm";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import * as schema from "./schema.ts";
+
+const isBun = typeof (globalThis as any).Bun !== "undefined";
+const dir = mkdtempSync(join(tmpdir(), "pep36-"));
+const file = join(dir, "peppa.db");
+const migrationsFolder = new URL("migrations", import.meta.url).pathname;
+
+let db: any;
+if (isBun) {
+ const { Database } = await import("bun:sqlite" as string);
+ const { drizzle } = await import("drizzle-orm/bun-sqlite");
+ const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
+ const d = new Database(file, { create: true });
+ for (const p of ["PRAGMA busy_timeout = 5000", "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA foreign_keys = ON"]) d.exec(p);
+ db = drizzle(d, { schema });
+ migrate(db, { migrationsFolder });
+} else {
+ const { drizzleNodeSqlite } = await import("./node-sqlite-driver.ts");
+ const { migrate } = await import("drizzle-orm/better-sqlite3/migrator");
+ db = drizzleNodeSqlite(file, schema);
+ migrate(db, { migrationsFolder });
+}
+const ok = (name: string, cond: boolean, extra = "") => console.log(`${cond ? "ok " : "FAIL"} ${name}${extra ? ` — ${extra}` : ""}`);
+
+const [user] = db.insert(schema.users).values({ giteaId: 1, login: "mock-pm", telegramChatId: 9007199254740991 }).returning().all();
+const [project] = db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp", ownerId: user.id }).returning().all();
+ok("insert … returning", project.id === 1 && project.createdAt instanceof Date, `createdAt ${project.createdAt.toISOString()}`);
+ok("bigint chat id round trip", db.select().from(schema.users).get().telegramChatId === 9007199254740991);
+
+// createTask as it has to look on SQLite: synchronous transaction, BEGIN IMMEDIATE.
+const createTask = (title: string) =>
+ db.transaction(
+ (tx: any) => {
+ const [p] = tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning().all();
+ return tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title }).returning().get();
+ },
+ { behavior: "immediate" },
+ );
+const t1 = createTask("Первая");
+const t2 = createTask("Вторая");
+ok("sync transaction", t1.number === 1 && t2.number === 2 && t2.status === "backlog");
+
+try {
+ db.transaction((tx: any) => {
+ tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run();
+ throw new Error("boom");
+ });
+} catch {}
+ok("rollback on throw", db.select().from(schema.projects).get().nextTaskNumber === 3);
+
+let asyncRefused = false;
+try {
+ await db.transaction(async (tx: any) => {
+ await tx.update(schema.projects).set({ nextTaskNumber: 200 }).where(eq(schema.projects.id, 1));
+ });
+} catch (e) {
+ asyncRefused = /synchronous/.test((e as Error).message);
+}
+ok("async transaction", isBun ? true : asyncRefused, isBun ? "bun-sqlite: commits after the first await (not refused) — see tx-check.ts" : "refused with a clear error");
+
+const [sess] = db.insert(schema.sessions).values({ projectId: 1, taskId: t1.id, tmuxName: "peppa-P-1-s1" }).returning().all();
+db.insert(schema.questions).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, kind: "permission", text: "Удалить build?", options: ["Да", "Нет"], awaitingHook: true }).run();
+const q = db.query.questions.findFirst({ with: { session: true, task: true } }).sync();
+ok("json + boolean + relations", Array.isArray(q.options) && q.options[1] === "Нет" && q.awaitingHook === true && q.session.tmuxName === "peppa-P-1-s1" && q.task.title === "Первая");
+db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 1 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 2 } } }).run();
+db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 3 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 3 } } }).run();
+ok("upsert json", db.select().from(schema.settings).get().value.at === 3);
+db.insert(schema.telegramOutbox).values({ dedupeKey: "q:1", method: "sendMessage", params: { chat_id: 42, text: "?" } }).run();
+// core/telegram.ts compares params->>'chat_id' with a string. Postgres ->> returns text;
+// SQLite ->> returns the JSON number as a number, so the same SQL finds nothing.
+const asText = db.select().from(schema.telegramOutbox).where(sql`${schema.telegramOutbox.params}->>'chat_id' = ${"42"}`).all();
+const asCast = db.select().from(schema.telegramOutbox).where(sql`cast(${schema.telegramOutbox.params}->>'chat_id' as text) = ${"42"}`).all();
+ok("json ->> as in core/telegram.ts differs from Postgres", asText.length === 0 && asCast.length === 1, "needs cast(… as text) on SQLite");
+
+// Cost of the hook's write through the ORM (update session + insert event), one process.
+const n = 20000;
+const t0 = performance.now();
+for (let i = 0; i < n; i++)
+ db.transaction(
+ (tx: any) => {
+ tx.update(schema.sessions).set({ status: "running", lastActivityAt: new Date() }).where(eq(schema.sessions.id, sess.id)).run();
+ tx.insert(schema.events).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, type: "turn_end", payload: { i } }).run();
+ },
+ { behavior: "immediate" },
+ );
+const us = ((performance.now() - t0) / n) * 1000;
+console.log(`${isBun ? "bun:sqlite" : "node:sqlite"} via drizzle: ${us.toFixed(1)} µs per hook transaction (${n} in one process)`);
+rmSync(dir, { recursive: true, force: true });
diff --git a/bench/sqlite/schema-port/node-sqlite-driver.ts b/bench/sqlite/schema-port/node-sqlite-driver.ts
new file mode 100644
index 00000000..94a35c7e
--- /dev/null
+++ b/bench/sqlite/schema-port/node-sqlite-driver.ts
@@ -0,0 +1,93 @@
+// PEP-36 prototype: drizzle on Node's built-in node:sqlite. drizzle-orm 0.45 has no
+// node:sqlite driver (it exists only in 1.0 beta/rc), but node:sqlite's API is close to
+// better-sqlite3's, so a thin client shim lets drizzle's better-sqlite3 *session* run on it:
+// prepare() → run/all/get/raw(), transaction(fn) → .deferred/.immediate/.exclusive.
+// drizzle-orm/better-sqlite3 itself is not imported: its driver.js imports the native
+// better-sqlite3 package at load time. construct() below mirrors that driver.
+import { DatabaseSync, type StatementSync } from "node:sqlite";
+import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session";
+import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations";
+import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db";
+import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect";
+
+type Params = unknown[];
+
+class Statement {
+ stmt: StatementSync;
+ rawStmt: StatementSync | null = null;
+ db: DatabaseSync;
+ sql: string;
+ constructor(db: DatabaseSync, sql: string) {
+ this.db = db;
+ this.sql = sql;
+ this.stmt = db.prepare(sql);
+ }
+ run(...p: Params) {
+ return this.stmt.run(...(p as any[]));
+ }
+ all(...p: Params) {
+ return this.stmt.all(...(p as any[]));
+ }
+ get(...p: Params) {
+ return this.stmt.get(...(p as any[]));
+ }
+ /** Rows as arrays (drizzle maps columns by position). */
+ raw() {
+ if (!this.rawStmt) {
+ this.rawStmt = this.db.prepare(this.sql);
+ this.rawStmt.setReturnArrays(true);
+ }
+ return this.rawStmt;
+ }
+}
+
+export class NodeSqliteClient {
+ db: DatabaseSync;
+ cache = new Map();
+ constructor(path: string, opts: { busyTimeoutMs?: number } = {}) {
+ this.db = new DatabaseSync(path);
+ // busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY
+ // when many processes open the file together (see bench/sqlite/README.md).
+ this.db.exec(`PRAGMA busy_timeout = ${opts.busyTimeoutMs ?? 5000}`);
+ this.db.exec("PRAGMA journal_mode = WAL");
+ this.db.exec("PRAGMA synchronous = NORMAL");
+ this.db.exec("PRAGMA foreign_keys = ON");
+ }
+ prepare(sql: string) {
+ let s = this.cache.get(sql);
+ if (!s) this.cache.set(sql, (s = new Statement(this.db, sql)));
+ return s;
+ }
+ exec(sql: string) {
+ this.db.exec(sql);
+ }
+ transaction(fn: (...a: any[]) => T) {
+ const run = (begin: string) => (...a: any[]) => {
+ this.db.exec(begin);
+ try {
+ const r = fn(...a);
+ if (r && typeof (r as any).then === "function") throw new Error("SQLite transactions must be synchronous (no async callback)");
+ this.db.exec("COMMIT");
+ return r;
+ } catch (e) {
+ if (this.db.isTransaction) this.db.exec("ROLLBACK");
+ throw e;
+ }
+ };
+ return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
+ }
+ close() {
+ this.db.close();
+ }
+}
+
+export function drizzleNodeSqlite>(path: string, fullSchema: S) {
+ const client = new NodeSqliteClient(path);
+ const dialect = new SQLiteSyncDialect();
+ const tables = extractTablesRelationalConfig(fullSchema, createTableRelationsHelpers);
+ const schema = { fullSchema, schema: tables.tables, tableNamesMap: tables.tableNamesMap };
+ const session = new BetterSQLiteSession(client as any, dialect, schema as any);
+ const db = new BaseSQLiteDatabase("sync", dialect, session as any, schema as any) as any;
+ db.$client = client;
+ return db as BaseSQLiteDatabase<"sync", unknown, S>;
+}
diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md
index 955ed09c..b889c006 100644
--- a/openspec/changes/pep-36-lightweight-stack/design.md
+++ b/openspec/changes/pep-36-lightweight-stack/design.md
@@ -1,4 +1,4 @@
-# Design: PEP-36 — Bun + SQLite
+# Design: PEP-36 — Node 26 без сборки + SQLite
## Контекст
@@ -7,7 +7,7 @@ telegram_updates, ответы), вачдог (tick раз в 30 с, heartbeat,
каждого события Claude — отдельный короткий процесс**, MCP-сервер каждого раннера и CLI.
Бот узнаёт о новых событиях через Postgres LISTEN/NOTIFY (`core/notify.ts`,
`apps/bot/src/bot.ts`). Вопрос этапа: тянет ли это SQLite, чем заменить NOTIFY и что
-сломается под Bun.
+сломается без tsx (замер делался для Bun и Node; PM выбрал Node 26, см. «Решение PM»).
Всё ниже измерено на Mac Пеппы (Apple Silicon, Node 26.8, Bun 1.4.4, Postgres 17.11 в
docker) бенчмарком `bench/sqlite` (методика — `bench/sqlite/README.md`).
@@ -109,7 +109,7 @@ p50/p95/p99/max — время транзакции записи в мс (вкл
- **опрос** надёжен и прост, 200 мс — дешёвый запрос по индексу (0,1 мс), но всегда
добавляет задержку.
-### Bun на текущем коде (без изменений кода)
+### Bun на текущем коде (проверено до решения PM; Node без tsx — этап 1)
| что | результат |
|---|---|
@@ -126,6 +126,37 @@ p50/p95/p99/max — время транзакции записи в мс (вкл
Хук — главный выигрыш: Claude ждёт хук на каждом событии, а PermissionRequest/
AskUserQuestion — ещё и человека; 0,4 с на старт tsx сейчас — это 90 % времени хука.
+### Node 26 вместо Bun (решение PM)
+
+PM выбрал Node 26 со встроенным снятием типов и `node:sqlite`. По замеру это не хуже Bun
+там, где важно:
+
+- **Запись** на той же нагрузке (таблица выше, строки `node:sqlite`): p50 0,13–0,20 мс,
+ p99 0,9–1,3 мс — не хуже `bun:sqlite` (0,20–0,32 / 1,2–2,3); в потолке — 48 тыс.
+ транзакций/с против 27–34 тыс. и p99 0,05 мс против 4–22 мс (у Node 26 встроенная
+ SQLite 3.53, у Bun на macOS — системная 3.43).
+- **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert,
+ 20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс.
+- **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против
+ 16–32 мс; но против tsx (0,44 с) это всё равно в 4–6 раз быстрее. Реальный старт
+ `peppa-hook` на Node без tsx замеряется в этапе 1.
+- `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего
+ лишнего.
+
+**Драйвер drizzle.** В стабильном drizzle 0.45 драйвера `node:sqlite` нет (только в
+1.0 beta/rc — мажорное обновление ради одного драйвера не берём). `sqlite-proxy` не
+подходит: он асинхронный, транзакции через него не атомарны для нескольких процессов.
+better-sqlite3 под Node 26 собирается из исходников (готовых бинарников нет, 12.x не
+собирается вовсе). Решение — **тонкая прослойка** (`schema-port/node-sqlite-driver.ts`,
+~80 строк): клиент `node:sqlite` с API better-sqlite3 (`prepare → run/all/get/raw`,
+`transaction(fn).immediate`) под сессию drizzle `better-sqlite3/session`; сам
+`drizzle-orm/better-sqlite3` не импортируется (его driver.js тянет нативный пакет).
+Проверено: мигратор drizzle, `returning`, `Date`, JSON, boolean, bigint (id чата
+9007199254740991), связи `db.query…with`, upsert, синхронная транзакция с откатом;
+**async-колбэк транзакции прослойка отклоняет с понятной ошибкой** (вместо тихой потери
+атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется
+штатным `drizzle-orm/node-sqlite`.
+
### Схема и данные на SQLite (`bench/sqlite/schema-port`)
- Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`,
@@ -148,6 +179,10 @@ AskUserQuestion — ещё и человека; 0,4 с на старт tsx се
`for update skip locked` (core/incidents.ts — не нужно, `BEGIN IMMEDIATE` и так
сериализует писателей), `count(*)::int` (monitor/incidents). `->>`, `lower()`, `like`,
`returning`, `on conflict` в SQLite есть.
+- **Ловушка: `->>` возвращает число.** В Postgres `params->>'chat_id'` — текст, в SQLite —
+ значение JSON-типа (число). `core/telegram.ts` сравнивает его со строкой — на SQLite
+ такой фильтр ничего не найдёт; нужен `cast(… as text)` или сравнение с числом
+ (проверено в `drizzle-check.ts`).
## Решения
@@ -187,10 +222,11 @@ FIFO-очередь записи без хвостов — нужен тольк
подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в
секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала.
-### 4. Поэтапно: Bun → SQLite → Docker
+### 4. Поэтапно: Node без tsx → SQLite → Docker
-Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; даёт ускорение хука в
-10 раз сразу. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме
+Этап 1 не трогает данные и обратим одной строкой в bin-обёртках; ускоряет старт каждого
+процесса (хук — в разы). Код должен проходить `erasableSyntaxOnly`: Node снимает только
+типы, parameter properties, `enum`, `namespace` с кодом не поддерживаются. Этап 2 — с переносом данных командой со сверкой и неделей Postgres в режиме
только чтения как откатом. Этап 3 зависит от PEP-17/PEP-18: раннеры (tmux + claude +
рабочие копии) должны видеть тот же файл базы на локальном диске; самый простой вариант —
сервисы и раннеры в одном контейнере с томами хоста.
@@ -201,15 +237,17 @@ FIFO-очередь записи без хвостов — нужен тольк
метрикой «время записи p99» в heartbeat, порог алерта 1 с.
- **Повреждение/потеря файла** — WAL устойчив к падению процесса; ежедневная копия
`VACUUM INTO` (7 штук) и копия перед переносом.
-- **Next.js под Bun** — dev-режим работает (проверено), но `bun --bun` для Next официально
- экспериментальный; запасной вариант — веб на Node, остальное на Bun: SQLite это не мешает
- (`node:sqlite` в Node 26 работает с тем же файлом, замерено).
+- **Next.js** остаётся как есть (свой компилятор TS); `node:sqlite` работает в серверном
+ коде Next на Node 26 так же, как в остальных процессах.
+- **Прослойка drizzle ↔ node:sqlite** — своя, хоть и маленькая; покрыта проверками
+ `drizzle-check.ts`, при переходе на drizzle 1.0 заменяется штатным драйвером.
- **Bugsink** держит свою базу в контейнере `peppa-postgres` — контейнер нельзя удалить,
пока Bugsink не переведён (отдельная задача; Bugsink умеет SQLite).
- `better-sqlite3` под Node 26 нет готовых бинарников (сборка node-gyp из исходников,
- версия 12.x не собирается вовсе) — в Docker на Node это лишняя сборка; `bun:sqlite` и
- `node:sqlite` встроены.
+ версия 12.x не собирается вовсе) — поэтому `node:sqlite`, он встроен.
-## Открытые вопросы
+## Решение PM
-См. «Решения PM» в proposal.md.
+Одобрено 2026-11-13 (approval #41) с изменением рантайма: Node 26 + `node:sqlite` вместо
+Bun; каждый процесс пишет сам; Postgres остаётся только для Bugsink (перевод — отдельная
+задача). Этап 2 начинается после мержа PEP-38 (переделка `apps/web`).
diff --git a/openspec/changes/pep-36-lightweight-stack/proposal.md b/openspec/changes/pep-36-lightweight-stack/proposal.md
index 1e084be8..a4a91726 100644
--- a/openspec/changes/pep-36-lightweight-stack/proposal.md
+++ b/openspec/changes/pep-36-lightweight-stack/proposal.md
@@ -1,67 +1,56 @@
-# Proposal: PEP-36 — легковесный стек: Bun + SQLite, запуск одной командой
+# Proposal: PEP-36 — легковесный стек: Node 26 без сборки + SQLite, запуск одной командой
Задача Пеппы: **PEP-36** · Цель «Безопасность и эксплуатация».
## Why
Пеппу сейчас поднимают Node + tsx + pnpm + Postgres в docker + `next build`. Для одной
-машины это тяжело: отдельный контейнер БД, сборка веба после каждой правки, медленный
-старт процессов (хук Claude — это новый процесс tsx на каждое событие, ~0,44 с только на
-старт). PM решил (2026-11-13): вся Пеппа на Bun + SQLite (WAL), Postgres — только как
-дополнение там, где SQLite не тянет параллельные записи; переписку чатов долго не храним.
+машины это тяжело: отдельный контейнер БД, медленный старт процессов (хук Claude — новый
+процесс tsx на каждое событие, ~0,44 с только на старт). Перед переездом нужно было
+ответить: выдержит ли один файл SQLite записи из многих процессов (веб, бот, вачдог, хуки
+и MCP каждого раннера), чем заменить LISTEN/NOTIFY и что сломается без tsx. Замер сделан
+(`bench/sqlite`, цифры в design.md).
-Перед переездом нужно было ответить на вопрос: выдержит ли один файл SQLite записи из
-многих процессов (веб, бот, вачдог, хуки и MCP каждого раннера), чем заменить
-LISTEN/NOTIFY и что сломается под Bun. Замер сделан (`bench/sqlite`, цифры в design.md).
+## Решение PM (2026-11-13, approval #41)
+
+- Вся Пеппа на **SQLite (WAL)**; **каждый процесс пишет сам** (WAL + `busy_timeout`), без
+ сервиса-писателя.
+- Рантайм — **Node 26 со встроенным TypeScript** (снятие типов) и **`node:sqlite`**, не Bun.
+ От tsx уходим. Next.js остаётся как есть.
+- Postgres остаётся **только для Bugsink**; перевод Bugsink — отдельная задача.
## What Changes
-Рекомендация по замеру — **переезжать целиком, поэтапно**; Postgres для Пеппы не нужен.
-
-- **Этап 1 — Bun вместо tsx** (без смены БД): обёртки бинарей, launchd, тесты на
- `bun test`. Текущий код уже работает под Bun без правок (CLI, хук, MCP, бот, e2e бота).
- Хук стартует за 0,04 с вместо 0,44 с.
+- **Этап 1 — Node без tsx** (без смены БД): `erasableSyntaxOnly` в tsconfig и правка кода,
+ который Node не может просто очистить от типов (parameter properties и т. п.); bin-обёртки,
+ скрипты, CI и `install-launchd.sh` — `node` вместо `tsx`; тесты — `node --test`.
- **Этап 2 — SQLite вместо Postgres**: схема на `sqlite-core` (одна базовая миграция
- вместо 12), каждый процесс открывает файл сам (WAL + `busy_timeout`), без отдельного
- сервиса-писателя; LISTEN/NOTIFY → журнал `events` с курсором + сигнал по unix-сокету +
- опрос раз в секунду как страховка; перенос данных командой со сверкой; ежедневная копия.
-- **Этап 3 — `docker compose up`**: один образ на Bun для веба, бота и вачдога; база и
+ вместо 12), драйвер `node:sqlite` через тонкую прослойку под сессию drizzle (готового
+ драйвера в стабильном drizzle 0.45 нет, better-sqlite3 под Node 26 собирается из
+ исходников — не берём); каждый процесс открывает файл сам; LISTEN/NOTIFY → журнал
+ `events` с курсором + сигнал по unix-сокету + опрос раз в секунду; перенос данных
+ командой со сверкой; ежедневная копия. Начинается после мержа PEP-38 (переделка `apps/web`).
+- **Этап 3 — `docker compose up`**: один образ `node:26` для веба, бота и вачдога; база и
рабочие копии в томах хоста. Связан с PEP-17 (песочница) и PEP-18 (деплой).
-Вне scope: переезд Bugsink (у него своя база в контейнере Postgres, см. «Решения PM»),
-хранение чатов (PM: долго не храним).
+Вне scope: перевод Bugsink с Postgres (PEP-63), хранение чатов (PM: долго не храним).
## Capabilities
### New Capabilities
-- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Bun, запуск одной командой.
+- `platform-storage`: одна база SQLite для всех процессов, живые обновления без Postgres, перенос данных, резервные копии, сервисы на Node без сборки, запуск одной командой.
### Modified Capabilities
- `service-monitoring`: health-эндпоинт проверяет файл SQLite вместо Postgres.
## Impact
-- `packages/db` (схема, клиент, миграции), `packages/core/src/notify.ts`, `core/tasks.ts`
- (транзакция), `core/incidents.ts` (`for update skip locked`), `apps/bot` (подписка),
- `apps/web` (живые обновления, health), `packages/testkit` (БД тестов), bin-обёртки,
- `scripts/install-launchd.sh`, `infra/`.
-- Зависимости: −`postgres`, −`tsx` (после этапа 1), +Bun ≥ 1.4 на машине или в образе.
-- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос занимает доли секунды).
-
-## Решения PM
-
-1. **Переезд целиком или гибрид?** Рекомендация: целиком. Замер не нашёл места, где
- Postgres нужен: при 20 раннерах и нагрузке до ×50 запись в SQLite в 25–50 раз (по медиане)
- быстрее, без единой блокировки. Postgres можно вернуть точечно, если появится
- нагрузка другого порядка (например, хранение чатов в больших объёмах).
-2. **Как развести записи многих процессов?** Рекомендация: каждый процесс пишет сам
- (WAL + `busy_timeout` + `BEGIN IMMEDIATE`), без сервиса-писателя. Писатель по сокету
- медленнее (лишний переход), добавляет точку отказа и не нужен при наших частотах.
-3. **Замена LISTEN/NOTIFY**: журнал `events` с курсором + сигнал по unix-сокету от
- записавшего процесса + опрос раз в секунду. fs.watch отвергнут: на macOS теряет события.
-4. **Bugsink**: его база `bugsink` живёт в том же контейнере `peppa-postgres`. Оставить
- контейнер только под Bugsink или перевести Bugsink на его встроенный SQLite (отдельная
- задача)? Рекомендация: отдельная задача, контейнер пока остаётся для Bugsink.
-5. **Порядок**: этап 1 (Bun) можно делать сразу — он обратим и не трогает данные. Этап 2
- — после этапа 1, с неделей отката на Postgres в режиме только чтения. Этап 3 — после
- решений PEP-17/PEP-18 о том, где живут раннеры.
+- Этап 1: `tsconfig.base.json`, классы с parameter properties, `packages/*/bin/*`,
+ `apps/bot/bin/*`, `package.json` (скрипты), `.gitea/workflows/ci.yml`, `scripts/ci.sh`,
+ `scripts/install-launchd.sh`. Перевыкатка launchd-агентов — PM.
+- Этап 2: `packages/db` (схема, клиент, миграции), `core/notify.ts`, `core/tasks.ts`
+ (транзакция), `core/incidents.ts` (`for update skip locked`), `core/telegram.ts`
+ (`->>` возвращает число), `apps/bot` (подписка), `apps/web` (живые обновления, health),
+ `packages/testkit` (БД тестов).
+- Зависимости: −`tsx` (этап 1), −`postgres` (этап 2); нужен Node ≥ 26.
+- Данные: одноразовый перенос боевой БД (сейчас 9 МБ, перенос — доли секунды).
diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
index 1a43aad8..14bf7044 100644
--- a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
+++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
@@ -2,7 +2,7 @@
## Purpose
-Описывает, где Пеппа хранит свои данные после переезда на Bun + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой.
+Описывает, где Пеппа хранит свои данные после переезда на Node 26 + SQLite: один файл БД, в который одновременно пишут веб, бот, вачдог, хуки и MCP всех раннеров; как сервисы узнают о новых событиях без LISTEN/NOTIFY; как переносятся данные из Postgres и как Пеппа запускается одной командой.
## ADDED Requirements
@@ -68,21 +68,26 @@
- **WHEN** вачдог делает копию
- **THEN** неполная копия удалена, админы платформы получают сообщение «резервная копия не сделана: нет места», сервисы продолжают работать
-### Requirement: Сервисы Пеппы на Bun
-Веб (режим разработки Next.js без сборки), бот, вачдог, `peppa-hook`, `peppa-mcp` и CLI SHALL запускаться под Bun без tsx и pnpm. Хук SHALL стартовать и закончить запись события быстрее 150 мс.
+### Requirement: Сервисы Пеппы на Node без сборки
+Бот, вачдог, `peppa-hook`, `peppa-mcp`, CLI и тесты SHALL запускаться командой `node` (Node ≥ 26) прямо из исходников на TypeScript, без tsx и без шага сборки; веб SHALL работать на Next.js как раньше. Код SHALL проходить проверку типов с `erasableSyntaxOnly`. Хук SHALL стартовать и закончить запись события быстрее 300 мс.
#### Scenario: Хук на каждое событие
- **GIVEN** раннер «PEP-42» работает, Claude вызывает хук Stop
- **WHEN** `peppa-hook stop` получает событие
-- **THEN** событие `turn_end` записано, хук завершился быстрее 150 мс
+- **THEN** событие `turn_end` записано, хук завершился быстрее 300 мс, в stderr хука нет предупреждений Node
-#### Scenario: Нет Bun на машине
-- **GIVEN** на машине не установлен Bun
+#### Scenario: Старый Node на машине
+- **GIVEN** на машине Node 22
- **WHEN** администратор запускает `peppa status`
-- **THEN** команда печатает «нужен Bun ≥ 1.4: https://bun.sh» и завершается с кодом 1
+- **THEN** команда печатает «нужен Node ≥ 26» и завершается с кодом 1
+
+#### Scenario: Синтаксис, который Node не умеет снять
+- **GIVEN** в `packages/core` добавлен класс с parameter property `constructor(private db: Db)`
+- **WHEN** запускается проверка типов
+- **THEN** проверка падает с ошибкой `erasableSyntaxOnly` на этой строке
### Requirement: Запуск одной командой
-Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Bun: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске.
+Пеппа SHALL подниматься одной командой `docker compose up` из одного образа на Node 26: веб, бот и вачдог в одном контейнере, файл базы и рабочие копии проектов — в томах хоста. Раннеры (tmux, Claude) SHALL работать там, где лежат рабочие копии; база SHALL быть доступна раннерам и сервисам как один и тот же файл на локальном диске.
#### Scenario: Первый запуск
- **GIVEN** чистая машина с Docker, заполненный `.env`
diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md
index 18d162fe..50e05236 100644
--- a/openspec/changes/pep-36-lightweight-stack/tasks.md
+++ b/openspec/changes/pep-36-lightweight-stack/tasks.md
@@ -7,30 +7,34 @@
- [x] 0.3 Прототипы замены LISTEN/NOTIFY: опрос с курсором, fs.watch WAL, push по unix-сокету
- [x] 0.4 Текущий код под Bun: CLI, `peppa-hook`, `peppa-mcp`, бот, e2e (`bun test`), `next dev`
- [x] 0.5 Прототип схемы на sqlite (`bench/sqlite/schema-port`): базовая миграция, перенос боевых данных, проверка транзакций drizzle
-- [ ] 0.6 Решение PM по «Решениям PM» в proposal.md (request_approval)
+- [x] 0.6 Решение PM (approval #41): SQLite, каждый процесс пишет сам; рантайм Node 26 + `node:sqlite` вместо Bun; Postgres только для Bugsink
+- [x] 0.7 Драйвер drizzle ↔ `node:sqlite`: прослойка `schema-port/node-sqlite-driver.ts` + `drizzle-check.ts`; замер node:sqlite против bun:sqlite через drizzle
+- [x] 0.8 Отдельная задача: перевод Bugsink с Postgres — PEP-63
-## 1. Этап 1 — Bun вместо tsx (без смены БД)
+## 1. Этап 1 — Node 26 без tsx (без смены БД)
-- [ ] 1.1 Обёртки `packages/*/bin/*` и `apps/bot/bin/*`: `bun` вместо `tsx`, проверка версии Bun (≥ 1.4) с понятной ошибкой
-- [ ] 1.2 Тесты: `bun test` вместо `tsx --test` (node:test работает в Bun); прогнать весь e2e, починить расхождения
-- [ ] 1.3 launchd-агенты бота и вачдога на Bun; веб — `bun --bun next dev`/`next start` по итогам проверки 0.4
-- [ ] 1.4 Замер хука на живой машине: старт и запись события (цель < 150 мс)
+- [ ] 1.1 `erasableSyntaxOnly` в `tsconfig.base.json`; переписать parameter properties, `enum` и прочее, что Node не может очистить от типов; `typecheck` зелёный
+- [ ] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx`; проверка версии Node (≥ 26) с понятной ошибкой
+- [ ] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`.gitea/workflows/ci.yml`, `scripts/ci.sh`); `tsx` убрать из зависимостей
+- [ ] 1.4 `scripts/install-launchd.sh` — без tsx; на машине не перевыкатывать (деплой — PM), в PR перечислить, что перевыкатить
+- [ ] 1.5 Весь e2e на своей `PEPPA_TEST_DB`; замер старта `peppa-hook` (цель < 300 мс)
## 2. Этап 2 — SQLite вместо Postgres
-- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `bun:sqlite`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
+- [ ] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`)
+- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции
- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async`
-- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` и `lower()` работают как есть
+- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть
- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме
- [ ] 2.6 `peppa db migrate-to-sqlite `: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении
- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл
- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude)
-- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (Bugsink остаётся на своём Postgres или переезжает отдельно)
+- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63)
## 3. Этап 3 — запуск одной командой
-- [ ] 3.1 Образ на `oven/bun` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста
+- [ ] 3.1 Образ на `node:26` с tmux, git, Claude CLI; веб, бот и вачдог в одном контейнере; база и рабочие копии в томах хоста
- [ ] 3.2 Согласовать с PEP-17 (песочница) и PEP-18 (деплой): где живут раннеры, как контейнер видит рабочие копии и токены
- [ ] 3.3 `docker compose up` на чистой машине → health 200 за минуту; документация в README и `/help`
- [ ] 3.4 Отказ запуска, если база на сетевом диске
--
2.45.2
From d3a54fc8458b465eaf1c1849c6d12d542cde3c8a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:25:05 +0500
Subject: [PATCH 013/532] =?UTF-8?q?PEP-38:=20runners=20console=20=E2=80=94?=
=?UTF-8?q?=20filter=20counters,=20search,=20limit=20resume=20time,=20deta?=
=?UTF-8?q?ils=20panel?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/web/app/(app)/help/page.tsx | 2 +-
apps/web/app/(app)/runners/page.tsx | 110 +++++++++----
apps/web/components/LocalTime.tsx | 24 +++
apps/web/components/RunnerConsole.tsx | 146 ++++++++++++++++++
apps/web/components/Workspace.tsx | 7 +-
apps/web/lib/queries.ts | 5 +
.../changes/pep-38-factory-console/tasks.md | 8 +-
7 files changed, 265 insertions(+), 37 deletions(-)
create mode 100644 apps/web/components/LocalTime.tsx
create mode 100644 apps/web/components/RunnerConsole.tsx
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 6c792523..d1375129 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -52,7 +52,7 @@ export default async function Help() {
Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
- Раннер — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, задача, команда tmux attach, сообщение, остановка и resume; фильтры «ждут тебя / работают / остановлены (упали) / завершены».
+ Раннер — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, задача, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).
Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx
index 9644c1b3..dca587f2 100644
--- a/apps/web/app/(app)/runners/page.tsx
+++ b/apps/web/app/(app)/runners/page.tsx
@@ -1,49 +1,101 @@
import Link from "next/link";
-import { listUserSessions, RUNNER_FILTERS, type RunnerFilter } from "@peppa/core";
+import { Search } from "lucide-react";
+import { listUserSessions, RUNNER_FILTERS, type RunnerFilter, type SessionView } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
-import { SessionCard } from "@/components/cards";
import { Empty, Flash, PageHeader } from "@/components/common";
+import { RunnerDetails, RunnerRow } from "@/components/RunnerConsole";
+import { Input } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
+import { inbox, sessionEvents } from "@/lib/queries";
import { cn } from "@/lib/utils";
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
- { key: undefined, label: "Все" },
- { key: "waiting", label: "Ждут тебя" },
- { key: "working", label: "Работают" },
- { key: "stopped", label: "Остановлены" },
- { key: "finished", label: "Завершены" },
+ { key: undefined, label: "все" },
+ { key: "waiting", label: "ждут тебя" },
+ { key: "working", label: "работают" },
+ { key: "stopped", label: "упали" },
+ { key: "finished", label: "готово" },
];
+const inFilter = (s: SessionView, f: RunnerFilter) => (RUNNER_FILTERS[f] as string[]).includes(s.status);
+const matches = (s: SessionView, q: string) =>
+ [s.taskKey, s.taskTitle, s.projectKey, s.tmuxName, `#${s.id}`].some((v) => v?.toLowerCase().includes(q));
-export default async function Runners({ searchParams }: { searchParams: Promise<{ error?: string; f?: string }> }) {
+type Params = { error?: string; f?: string; q?: string; id?: string };
+
+export default async function Runners({ searchParams }: { searchParams: Promise }) {
const user = await requireUser();
- const { error, f } = await searchParams;
+ const { error, f, q: rawQ, id } = await searchParams;
const filter = f && f in RUNNER_FILTERS ? (f as RunnerFilter) : undefined;
- const all = await listUserSessions(db, user.id);
- const count = (k: RunnerFilter | undefined) => (k ? all.filter((s) => (RUNNER_FILTERS[k] as string[]).includes(s.status)).length : all.length);
- const shown = filter ? all.filter((s) => (RUNNER_FILTERS[filter] as string[]).includes(s.status)) : all;
- const back = filter ? `/runners?f=${filter}` : "/runners";
+ const q = rawQ?.trim().toLowerCase() ?? "";
+ const [all, open] = await Promise.all([listUserSessions(db, user.id), inbox(user.id)]);
+ const asking = new Map();
+ for (const x of open) if (x.sessionId) asking.set(x.sessionId, [...(asking.get(x.sessionId) ?? []), x]);
+ const needsPm = (s: SessionView) => s.status === "waiting_input" || asking.has(s.id);
+
+ const found = q ? all.filter((s) => matches(s, q)) : all;
+ const count = (k: RunnerFilter | undefined) => (k ? found.filter((s) => inFilter(s, k)).length : found.length);
+ // Who needs the PM first, then live runners, then finished ones; newest first inside each group.
+ const rank = (s: SessionView) => (needsPm(s) ? 0 : ["done", "failed"].includes(s.status) ? 2 : 1);
+ const shown = (filter ? found.filter((s) => inFilter(s, filter)) : found).sort((a, b) => rank(a) - rank(b) || b.id - a.id);
+
+ const url = (p: { f?: string; q?: string; id?: number | string }) => {
+ const sp = new URLSearchParams();
+ if (p.f) sp.set("f", p.f);
+ if (p.q) sp.set("q", p.q);
+ if (p.id) sp.set("id", String(p.id));
+ const s = sp.toString();
+ return s ? `/runners?${s}` : "/runners";
+ };
+ const base = { f: filter, q: rawQ?.trim() || undefined };
+ const selected = (id && all.find((s) => s.id === Number(id))) || shown[0];
+ const back = url({ ...base, id: selected?.id });
+ const aside = selected ? (
+
+ ) : null;
+
return (
-
+
- Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.
-
- {FILTERS.map((x) => (
-
- {x.label} {count(x.key)}
-
- ))}
-
-
- {shown.length === 0 ?
{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."} : shown.map((s) =>
)}
+
Агенты в tmux по задачам твоих и общих проектов: кто ждёт тебя, кто работает, что готово.
+
+
+ {FILTERS.map((x) => {
+ const n = count(x.key);
+ const active = x.key === filter;
+ return (
+
+ 0 ? "text-primary" : "text-foreground")}>{n}
+ {x.label}
+
+ );
+ })}
+
+
+ {filter && }
+
+
+
+ {shown.length === 0 ? (
+
{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}
+ ) : (
+
+ {shown.map((s) => (
+
+ ))}
+
+ )}
);
}
diff --git a/apps/web/components/LocalTime.tsx b/apps/web/components/LocalTime.tsx
new file mode 100644
index 00000000..9bd49e62
--- /dev/null
+++ b/apps/web/components/LocalTime.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+
+/** HH:MM (with the date when not today) in the viewer's time zone; the server renders its own zone first. */
+export function LocalTime({ iso }: { iso: string }) {
+ const d = new Date(iso);
+ const today = new Date().toDateString() === d.toDateString();
+ const time = d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
+ return (
+
+ {today ? time : `${d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" })} ${time}`}
+
+ );
+}
+
+/** On narrow screens the side panel sits under the list: bring the chosen runner into view. */
+export function ScrollIntoViewOnNarrow({ id }: { id: string | number }) {
+ const ref = useRef
(null);
+ useEffect(() => {
+ if (window.matchMedia("(max-width: 1279px)").matches) ref.current?.scrollIntoView({ block: "start" });
+ }, [id]);
+ return ;
+}
diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx
new file mode 100644
index 00000000..7fd70724
--- /dev/null
+++ b/apps/web/components/RunnerConsole.tsx
@@ -0,0 +1,146 @@
+// Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner.
+import Link from "next/link";
+import { SquareTerminal, X } from "lucide-react";
+import type { SessionView } from "@peppa/core";
+import { MAX_LIMIT_RESUMES_PER_DAY } from "@peppa/runner";
+import { PanelSection } from "@/components/ActivityAside";
+import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards";
+import { ago, Key, StatusBadge } from "@/components/common";
+import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime";
+import type { InboxItem } from "@/lib/queries";
+import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
+import { cn } from "@/lib/utils";
+
+/** «остановлена · продолжит в 03:10» for a runner that hit the usage limit (PEP-56). */
+export function LimitNote({ s }: { s: SessionView }) {
+ if (s.status !== "rate_limited") return null;
+ if (!s.resumeAt) return <>остановлена · лимит>;
+ if (s.resumeAt.getTime() <= Date.now()) return <>остановлена · продолжит сейчас>;
+ return (
+ <>
+ остановлена · продолжит в
+ >
+ );
+}
+
+/** `selected`: "wide" — picked by default, highlighted only where the side panel is visible. */
+export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) {
+ const limited = s.status === "rate_limited";
+ const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const };
+ return (
+
+
+
+
+ {s.taskKey ?? s.projectKey}
+ {s.taskTitle ?? "без задачи"}
+
+ {limited ? (
+ <>
+ {st.label}
+
+
+
+ >
+ ) : (
+ st.label
+ )}
+
+
+ {s.projectKey} · {s.provider} · #{s.id} · {s.tmuxName}
+
+ {ago(s.lastActivityAt)}
+ {limited && (
+
+
+
+ )}
+
+
+ );
+}
+
+export function RunnerDetails({ s, questions, events, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; back: string; closeHref: string; chosen: boolean }) {
+ return (
+
+ {/* Picked from the list: on narrow screens the panel is under it, scroll there. */}
+ {chosen &&
}
+
+
+
+ Проект
+
+ {s.projectKey}
+
+ Агент
+ {s.provider === "codex" ? "Codex" : "Claude Code"} · поколение {s.generation}
+ Запущен
+ {ago(s.startedAt)}
+ Активность
+ {ago(s.lastActivityAt)}
+
+
+
+
+
+ {questions.length > 0 && (
+
+ {questions.map((q) => (
+
+ ))}
+
+ )}
+
+
+
+
+ Живой терминал раннера появится здесь (PEP-9).
+ Пока — команда tmux attach выше, на машине Пеппы.
+
+
+
+ {events.length > 0 && (
+
+
+ {events.map((e) => (
+
+ {ago(e.createdAt)} {e.type} {" "}
+ {e.type === "progress" ? (e.payload as { text: string }).text : ""}
+
+ ))}
+
+
+ )}
+
+ );
+}
diff --git a/apps/web/components/Workspace.tsx b/apps/web/components/Workspace.tsx
index 2ea900f4..30bb2a48 100644
--- a/apps/web/components/Workspace.tsx
+++ b/apps/web/components/Workspace.tsx
@@ -1,13 +1,14 @@
import type { ReactNode } from "react";
import { ActivityAside } from "@/components/ActivityAside";
import { Footer } from "@/components/Footer";
+import { cn } from "@/lib/utils";
/**
* Centre + right panel of the console (PEP-38). The page decides what the right panel shows;
* without `aside` it gets the default activity panel, `aside={null}` hides it.
- * Below xl the panel goes under the page content, the footer is always last.
+ * Below xl the panel goes under the page content (`asideWideOnly`: shown on xl only), the footer is always last.
*/
-export function Workspace({ children, aside }: { children: ReactNode; aside?: ReactNode }) {
+export function Workspace({ children, aside, asideWideOnly = false }: { children: ReactNode; aside?: ReactNode; asideWideOnly?: boolean }) {
const panel = aside === undefined ? : aside;
return (
@@ -15,7 +16,7 @@ export function Workspace({ children, aside }: { children: ReactNode; aside?: Re
{children}
{panel && (
-
+
)}
diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts
index 8c72f872..cac7be72 100644
--- a/apps/web/lib/queries.ts
+++ b/apps/web/lib/queries.ts
@@ -85,3 +85,8 @@ export async function navCounts(userId: number): Promise<{ questions: number; wa
const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input")));
return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0 };
}
+
+/** Latest events of one runner, newest first (runner details panel, PEP-38). */
+export async function sessionEvents(sessionId: number, limit = 12) {
+ return db.select().from(events).where(eq(events.sessionId, sessionId)).orderBy(desc(events.id)).limit(limit);
+}
diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/pep-38-factory-console/tasks.md
index 82c64687..f769d0ec 100644
--- a/openspec/changes/pep-38-factory-console/tasks.md
+++ b/openspec/changes/pep-38-factory-console/tasks.md
@@ -16,10 +16,10 @@
- [x] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере
## 3. Пульт раннеров (PR 3)
-- [ ] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой
-- [ ] 3.2 «остановлена · продолжит в HH:MM» по `resume_at`
-- [ ] 3.3 Правая панель: детали выбранного раннера, вопросы, действия, заглушка терминала
-- [ ] 3.4 Помощь обновлена; проверка в браузере
+- [x] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой
+- [x] 3.2 «остановлена · продолжит в HH:MM» по `resume_at`
+- [x] 3.3 Правая панель: детали выбранного раннера, вопросы, действия, заглушка терминала
+- [x] 3.4 Помощь обновлена; проверка в браузере
## 4. Завершение
- [ ] 4.1 `openspec archive`, задача в review с pr_url
--
2.45.2
From 4c4b3a482fbce417ffbffce41c302a9a6ba65276 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:44:58 +0500
Subject: [PATCH 014/532] PEP-38: archive OpenSpec change
pep-38-factory-console
Co-Authored-By: Claude Opus 5.5
---
.../design.md | 0
.../proposal.md | 0
.../specs/web-workspace/spec.md | 0
.../tasks.md | 2 +-
openspec/specs/web-workspace/spec.md | 65 ++++++++++++++++++-
5 files changed, 63 insertions(+), 4 deletions(-)
rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/design.md (100%)
rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/proposal.md (100%)
rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/specs/web-workspace/spec.md (100%)
rename openspec/changes/{pep-38-factory-console => archive/2026-11-13-pep-38-factory-console}/tasks.md (96%)
diff --git a/openspec/changes/pep-38-factory-console/design.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/design.md
similarity index 100%
rename from openspec/changes/pep-38-factory-console/design.md
rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/design.md
diff --git a/openspec/changes/pep-38-factory-console/proposal.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/proposal.md
similarity index 100%
rename from openspec/changes/pep-38-factory-console/proposal.md
rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/proposal.md
diff --git a/openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/specs/web-workspace/spec.md
similarity index 100%
rename from openspec/changes/pep-38-factory-console/specs/web-workspace/spec.md
rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/specs/web-workspace/spec.md
diff --git a/openspec/changes/pep-38-factory-console/tasks.md b/openspec/changes/archive/2026-11-13-pep-38-factory-console/tasks.md
similarity index 96%
rename from openspec/changes/pep-38-factory-console/tasks.md
rename to openspec/changes/archive/2026-11-13-pep-38-factory-console/tasks.md
index f769d0ec..1c00b4f6 100644
--- a/openspec/changes/pep-38-factory-console/tasks.md
+++ b/openspec/changes/archive/2026-11-13-pep-38-factory-console/tasks.md
@@ -22,4 +22,4 @@
- [x] 3.4 Помощь обновлена; проверка в браузере
## 4. Завершение
-- [ ] 4.1 `openspec archive`, задача в review с pr_url
+- [x] 4.1 `openspec archive`, задача в review с pr_url
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 548e579e..1ccc4c4d 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -100,22 +100,81 @@
- **THEN** рядом с хэшем видна пометка «+изменения»
### Requirement: Верхнее меню
-Веб SHALL показывать верхнее меню с пунктами «Главная», «Проекты», «Раннеры», «Помощь» и подсвечивать текущий раздел.
+Веб SHALL показывать меню навигации с пунктами «Главная», «Проекты», «Раннеры», «Помощь», «Настройки» и подсвечивать текущий раздел; на десктопе меню — левая панель, на узком экране — панель вкладок снизу.
#### Scenario: Главная
- **GIVEN** вошедший пользователь
- **WHEN** он открывает корень сайта
- **THEN** в меню подсвечен пункт «Главная», пункта «Входящие» нет
+#### Scenario: Задача проекта
+- **GIVEN** вошедший пользователь
+- **WHEN** он открывает страницу задачи «PAY-3»
+- **THEN** в меню подсвечен пункт «Проекты»
+
### Requirement: Список раннеров
-Страница «Раннеры» SHALL показывать раннеры всех проектов пользователя (своих и общих) со статусом, проектом и задачей, агентом, временем последней активности и действиями, с фильтрами по состоянию.
+Страница «Раннеры» SHALL показывать в центре раннеры всех проектов пользователя (своих и общих) со статусом, проектом и задачей, агентом и временем последней активности, с фильтрами-счётчиками по состоянию и поиском, а справа — детали выбранного раннера с действиями.
#### Scenario: Раннер ждёт ответа
- **GIVEN** у пользователя раннер по задаче PAY-3 в статусе «ждёт тебя» и раннер по PAY-4 «работает»
- **WHEN** он открывает «Раннеры» и выбирает фильтр «ждут тебя»
-- **THEN** в списке только раннер PAY-3 со ссылкой на задачу и кнопкой ответа
+- **THEN** в списке только раннер PAY-3, строка подсвечена, у фильтра счётчик 1
#### Scenario: Чужие раннеры
- **GIVEN** раннер в проекте, где пользователь не владелец и не участник
- **WHEN** пользователь открывает «Раннеры»
- **THEN** этого раннера в списке нет
+
+#### Scenario: Поиск
+- **GIVEN** раннеры по задачам PAY-3 «Оплата картой» и PAY-4 «Возвраты»
+- **WHEN** пользователь ищет «возвр»
+- **THEN** в списке только раннер PAY-4
+
+#### Scenario: Лимит
+- **GIVEN** раннер в статусе «лимит» с временем продолжения 03:10
+- **WHEN** пользователь открывает «Раннеры»
+- **THEN** в строке раннера написано «остановлена · продолжит в 03:10»
+
+#### Scenario: Детали раннера
+- **GIVEN** раннер по задаче PAY-3 ждёт ответа на вопрос
+- **WHEN** пользователь выбирает его в списке
+- **THEN** справа видны статус, задача, агент, команда tmux attach, вопрос с формой ответа, кнопки «Остановить» и сообщение в сессию, и место под терминал
+
+### Requirement: Раскладка пульта
+Веб SHALL показывать вошедшему пользователю раскладку в три панели: слева навигация, в центре страница, справа контекстная панель; на узком экране разделы — панель вкладок снизу, а правая панель уходит под центр.
+
+#### Scenario: Десктоп
+- **GIVEN** вошедший пользователь на экране шириной 1440 px
+- **WHEN** он открывает любую страницу за входом
+- **THEN** слева видна навигация «Главная», «Проекты», «Раннеры», «Помощь», «Настройки», в центре — страница, справа — контекстная панель
+
+#### Scenario: Телефон
+- **GIVEN** вошедший пользователь на экране шириной 390 px
+- **WHEN** он открывает Главную
+- **THEN** разделы — панель вкладок внизу экрана, страница не прокручивается по горизонтали, правая панель — под содержимым
+
+### Requirement: Счётчик «ждут тебя»
+Навигация SHALL показывать у пункта «Главная» число открытых вопросов агентов по проектам пользователя, а у пункта «Раннеры» — число раннеров, ждущих PM.
+
+#### Scenario: Есть вопросы
+- **GIVEN** в проектах пользователя 3 неотвеченных вопроса и 1 раннер в статусе «ждёт тебя»
+- **WHEN** он открывает любую страницу
+- **THEN** у «Главная» стоит счётчик 3, у «Раннеры» — 1
+
+#### Scenario: Ничего не ждёт
+- **GIVEN** открытых вопросов и ждущих раннеров нет
+- **WHEN** пользователь открывает любую страницу
+- **THEN** счётчиков в навигации нет
+
+### Requirement: Тема оформления
+Веб SHALL открываться в тёмной теме по умолчанию и позволять переключиться на светлую; выбор SHALL сохраняться между визитами.
+
+#### Scenario: Первый визит
+- **GIVEN** пользователь ни разу не переключал тему
+- **WHEN** он открывает веб
+- **THEN** страница в тёмной теме
+
+#### Scenario: Светлая тема сохраняется
+- **GIVEN** пользователь переключил тему на светлую
+- **WHEN** он закрывает и снова открывает веб
+- **THEN** страница в светлой теме без мигания тёмной
--
2.45.2
From 8dc82859c7396ba728b0b9a2a8acb5b09a1f214b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:51:22 +0500
Subject: [PATCH 015/532] PEP-36 stage 1: run Peppa with Node 26 type stripping
instead of tsx
- tsconfig: erasableSyntaxOnly + verbatimModuleSyntax; parameter properties
rewritten (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError,
TelegramApi, MockGitea)
- bin wrappers (peppa, peppa-mcp, peppa-hook, peppa-bot, testkit mocks,
peppa-dev): `node --import scripts/lib/require-node.mjs` (clear error on
Node < 26, PEPPA_NODE overrides the binary); package scripts and tests on
`node` / `node --test`; tsx removed
- install-launchd.sh pins PEPPA_NODE (checked absolute path) in the plists
- fix a race the faster hooks exposed: the prompt hook answered every pending
question, including a PM question raised after Peppa itself pasted text
into the terminal; sendToSession now logs `input_sent` and the hook only
answers questions older than that input
- change pep-36-lightweight-stack: stage 1 done, hook start numbers
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 6 ++---
apps/bot/bin/peppa-bot | 2 +-
apps/bot/package.json | 2 +-
apps/bot/src/telegram.ts | 25 +++++++++++--------
apps/web/scripts/mock-ui-seed.ts | 2 +-
.../pep-36-lightweight-stack/design.md | 18 +++++++++++--
.../changes/pep-36-lightweight-stack/tasks.md | 10 ++++----
package.json | 1 -
packages/bugsink/src/index.ts | 7 +++---
packages/cli/bin/peppa | 2 +-
packages/cli/package.json | 2 +-
packages/core/src/gitea.ts | 17 +++++++------
packages/core/src/oauth.ts | 9 ++++---
packages/core/src/sessions.ts | 22 ++++++++++++++--
packages/mcp/bin/peppa-mcp | 2 +-
packages/mcp/package.json | 2 +-
packages/mcp/scripts/call.ts | 2 +-
packages/mcp/scripts/smoke.ts | 2 +-
packages/runner/bin/peppa-hook | 2 +-
packages/runner/src/hook.ts | 8 ++++--
packages/runner/src/sessions.ts | 2 ++
packages/testkit/bin/mock-claude | 2 +-
packages/testkit/bin/mock-codex | 2 +-
packages/testkit/bin/mock-telegram | 2 +-
packages/testkit/bin/mock-triage | 2 +-
packages/testkit/bin/peppa-dev | 2 +-
packages/testkit/package.json | 2 +-
packages/testkit/src/mock-gitea.ts | 4 ++-
packages/testkit/test/monitor.test.ts | 2 +-
pnpm-lock.yaml | 3 ---
scripts/install-launchd.sh | 10 +++++++-
scripts/lib/require-node.mjs | 9 +++++++
tsconfig.base.json | 2 ++
33 files changed, 124 insertions(+), 63 deletions(-)
create mode 100644 scripts/lib/require-node.mjs
diff --git a/AGENTS.md b/AGENTS.md
index 267cec7b..8ce96f26 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -56,7 +56,7 @@
- `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы
- `peppa web login-link ` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
- `pnpm typecheck`
-- `tsx packages/mcp/scripts/smoke.ts ` — смоук MCP-сервера
+- `node packages/mcp/scripts/smoke.ts ` — смоук MCP-сервера
- `pnpm dev:web`
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer `
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
@@ -65,7 +65,7 @@
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
-TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`.
+TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`.
## Автономный режим (PEP-7)
PM двигает карточки на доске (веб, `/p/`): «В работе» запускает агента (`moveTask`),
@@ -82,4 +82,4 @@ PM двигает карточки на доске (веб, `/p/`): «В р
(`template/RULES.md`, MCP `get_rules`): proposal → `request_approval` → одобрение PM →
apply → archive → PR/коммит. Работу вне задачи не делаем; новое — `create_task`.
Вызов MCP-инструмента из shell (для этой сессии без tmux):
-`tsx packages/mcp/scripts/call.ts ''`.
+`node packages/mcp/scripts/call.ts ''`.
diff --git a/apps/bot/bin/peppa-bot b/apps/bot/bin/peppa-bot
index 1f7067b7..5a96f3c4 100755
--- a/apps/bot/bin/peppa-bot
+++ b/apps/bot/bin/peppa-bot
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
-exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"
+exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"
diff --git a/apps/bot/package.json b/apps/bot/package.json
index 1dca122c..5e87285a 100644
--- a/apps/bot/package.json
+++ b/apps/bot/package.json
@@ -5,7 +5,7 @@
"type": "module",
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
"bin": { "peppa-bot": "./bin/peppa-bot" },
- "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
+ "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
"dependencies": {
"@peppa/core": "workspace:*",
"@peppa/db": "workspace:*",
diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts
index bea22d50..fad604cc 100644
--- a/apps/bot/src/telegram.ts
+++ b/apps/bot/src/telegram.ts
@@ -31,21 +31,26 @@ export interface InlineButton {
}
export class TelegramError extends Error {
- constructor(
- readonly method: string,
- readonly code: number,
- readonly description: string,
- readonly retryAfter?: number,
- ) {
+ readonly method: string;
+ readonly code: number;
+ readonly description: string;
+ readonly retryAfter?: number;
+ constructor(method: string, code: number, description: string, retryAfter?: number) {
super(`${method}: ${code} ${description}`);
+ this.method = method;
+ this.code = code;
+ this.description = description;
+ this.retryAfter = retryAfter;
}
}
export class TelegramApi {
- constructor(
- private readonly token: string,
- private readonly baseUrl = "https://api.telegram.org",
- ) {}
+ private readonly token: string;
+ private readonly baseUrl: string;
+ constructor(token: string, baseUrl = "https://api.telegram.org") {
+ this.token = token;
+ this.baseUrl = baseUrl;
+ }
async call(method: string, params: Record = {}, timeoutMs = 15_000): Promise {
let res: Response;
diff --git a/apps/web/scripts/mock-ui-seed.ts b/apps/web/scripts/mock-ui-seed.ts
index fa281db0..68a2246e 100644
--- a/apps/web/scripts/mock-ui-seed.ts
+++ b/apps/web/scripts/mock-ui-seed.ts
@@ -1,7 +1,7 @@
// Demo data for checking the web UI by eye (PEP-38): a user, two projects, goals, tasks on every board
// column, runners in every status (one hit the usage limit and resumes later), open questions, releases.
// Only for a throwaway database — refuses the production one:
-// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login]
+// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui node apps/web/scripts/mock-ui-seed.ts [login]
import { mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md
index b889c006..c2b3968c 100644
--- a/openspec/changes/pep-36-lightweight-stack/design.md
+++ b/openspec/changes/pep-36-lightweight-stack/design.md
@@ -138,8 +138,12 @@ PM выбрал Node 26 со встроенным снятием типов и `
- **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert,
20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс.
- **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против
- 16–32 мс; но против tsx (0,44 с) это всё равно в 4–6 раз быстрее. Реальный старт
- `peppa-hook` на Node без tsx замеряется в этапе 1.
+ 16–32 мс. Реальный `peppa-hook` на Node 26 без tsx (этап 1): **0,31 с против 0,44 с у
+ tsx** (Bun — 0,04 с). Почти всё время — загрузка drizzle-orm: `drizzle-orm` ~105 мс +
+ `pg-core` ~90 мс (сотни мелких ESM-файлов; `NODE_COMPILE_CACHE` даёт лишь ~0,03 с),
+ `postgres` — 10 мс, свой код — ~40 мс. С `sqlite-core` вместо `pg-core` картина та же
+ (~75 мс). Если 0,3 с на хук окажется заметным, в этапе 2 хук пишет через `node:sqlite`
+ напрямую (две-три команды SQL, без drizzle) — оценка ~0,1 с.
- `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего
лишнего.
@@ -157,6 +161,16 @@ better-sqlite3 под Node 26 собирается из исходников (г
атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется
штатным `drizzle-orm/node-sqlite`.
+### Этап 1: найденная гонка «промпт закрывает чужой вопрос»
+
+С быстрым стартом хука на Node e2e `ci-feedback` («Три неудачи подряд») стал падать в
+3 из 5 прогонов (на tsx — 0 из 5). Причина в коде, не в тесте: хук `UserPromptSubmit`
+закрывал **все** открытые вопросы сессии ответом «из терминала», в том числе вопрос PM,
+созданный уже после того, как Пеппа сама вставила текст (отчёт о красном CI) в терминал.
+Исправлено: `sendToSession` пишет событие `input_sent` с текстом до ввода, хук, узнав
+этот текст в промпте, закрывает только вопросы, созданные раньше ввода; текст,
+набранный человеком, закрывает всё, как раньше. После правки — 6 из 6.
+
### Схема и данные на SQLite (`bench/sqlite/schema-port`)
- Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`,
diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md
index 50e05236..ab312704 100644
--- a/openspec/changes/pep-36-lightweight-stack/tasks.md
+++ b/openspec/changes/pep-36-lightweight-stack/tasks.md
@@ -13,11 +13,11 @@
## 1. Этап 1 — Node 26 без tsx (без смены БД)
-- [ ] 1.1 `erasableSyntaxOnly` в `tsconfig.base.json`; переписать parameter properties, `enum` и прочее, что Node не может очистить от типов; `typecheck` зелёный
-- [ ] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx`; проверка версии Node (≥ 26) с понятной ошибкой
-- [ ] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`.gitea/workflows/ci.yml`, `scripts/ci.sh`); `tsx` убрать из зависимостей
-- [ ] 1.4 `scripts/install-launchd.sh` — без tsx; на машине не перевыкатывать (деплой — PM), в PR перечислить, что перевыкатить
-- [ ] 1.5 Весь e2e на своей `PEPPA_TEST_DB`; замер старта `peppa-hook` (цель < 300 мс)
+- [x] 1.1 `erasableSyntaxOnly` + `verbatimModuleSyntax` в `tsconfig.base.json`; parameter properties переписаны (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError, TelegramApi, MockGitea); `typecheck` зелёный
+- [x] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx` (`PEPPA_NODE` переопределяет); проверка версии Node ≥ 26 — `scripts/lib/require-node.mjs` через `node --import`
+- [x] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`ci.yml` уже ставит Node 26, `ci.sh` вызывает скрипт пакета — правок не потребовали); `tsx` убран из зависимостей
+- [x] 1.4 `scripts/install-launchd.sh`: плисты и так вызывают bin-обёртки; добавлен закреплённый `PEPPA_NODE` (абсолютный путь, проверка версии при установке); на машине не перевыкатывал — список в PR
+- [x] 1.5 Весь e2e на своей `PEPPA_TEST_DB` (`node --test`); старт `peppa-hook` 0,31 с (tsx 0,44 с) — см. design; гонка «промпт закрывает чужой вопрос» найдена и исправлена (`input_sent`)
## 2. Этап 2 — SQLite вместо Postgres
diff --git a/package.json b/package.json
index af1109a4..624b8c79 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,6 @@
},
"devDependencies": {
"@types/node": "26.6.6",
- "tsx": "4.23.15",
"typescript": "6.0.3"
}
}
diff --git a/packages/bugsink/src/index.ts b/packages/bugsink/src/index.ts
index 3295ead8..3bf91640 100644
--- a/packages/bugsink/src/index.ts
+++ b/packages/bugsink/src/index.ts
@@ -129,11 +129,10 @@ export function parseWebhook(body: unknown): BugsinkIssueJson | null {
}
export class BugsinkError extends Error {
- constructor(
- message: string,
- readonly status?: number,
- ) {
+ readonly status?: number;
+ constructor(message: string, status?: number) {
super(message);
+ this.status = status;
}
}
diff --git a/packages/cli/bin/peppa b/packages/cli/bin/peppa
index 9ee84182..442bd3ae 100755
--- a/packages/cli/bin/peppa
+++ b/packages/cli/bin/peppa
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
-exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@"
+exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@"
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 09fa8af9..abaa8675 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -7,7 +7,7 @@
"peppa": "./bin/peppa"
},
"scripts": {
- "start": "tsx src/index.ts",
+ "start": "node src/index.ts",
"typecheck": "tsc -p ."
},
"dependencies": {
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index 8ea94ac3..07bab961 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -62,19 +62,20 @@ export interface OAuthTokens {
}
export class GiteaError extends PeppaError {
- constructor(
- readonly status: number,
- message: string,
- ) {
+ readonly status: number;
+ constructor(status: number, message: string) {
super(message);
+ this.status = status;
}
}
export class GiteaClient {
- constructor(
- readonly baseUrl: string,
- private readonly token: string,
- ) {}
+ readonly baseUrl: string;
+ private readonly token: string;
+ constructor(baseUrl: string, token: string) {
+ this.baseUrl = baseUrl;
+ this.token = token;
+ }
async request(method: string, path: string, body?: unknown): Promise {
const res = await fetch(`${this.baseUrl}/api/v1${path}`, {
diff --git a/packages/core/src/oauth.ts b/packages/core/src/oauth.ts
index 942e7154..4396e2bf 100644
--- a/packages/core/src/oauth.ts
+++ b/packages/core/src/oauth.ts
@@ -12,12 +12,13 @@ export const ACCESS_TTL_SEC = 3600;
const REFRESH_TTL_SEC = 30 * 86400;
const CODE_TTL_MS = 10 * 60_000;
+type OAuthErrorCode = "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied";
+
export class OAuthError extends PeppaError {
- constructor(
- readonly error: "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied",
- description: string,
- ) {
+ readonly error: OAuthErrorCode;
+ constructor(error: OAuthErrorCode, description: string) {
super(description);
+ this.error = error;
}
}
diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts
index 6cf865d7..ad19e314 100644
--- a/packages/core/src/sessions.ts
+++ b/packages/core/src/sessions.ts
@@ -1,6 +1,6 @@
import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
-import { and, desc, eq, inArray, isNull, notInArray } from "drizzle-orm";
+import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import type { Question, QuestionKind } from "./tasks.ts";
@@ -89,7 +89,7 @@ export async function logSessionEvent(db: Db, s: Session, type: string, payload?
export async function pendingSessionQuestions(
db: Db,
sessionId: number,
- opts: { excludeHook?: boolean } = {},
+ opts: { excludeHook?: boolean; createdBefore?: Date } = {},
): Promise {
return db
.select()
@@ -99,10 +99,28 @@ export async function pendingSessionQuestions(
eq(questions.sessionId, sessionId),
isNull(questions.answeredAt),
opts.excludeHook ? eq(questions.awaitingHook, false) : undefined,
+ opts.createdBefore ? lte(questions.createdAt, opts.createdBefore) : undefined,
),
);
}
+const sameText = (a: string, b: string) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim();
+
+/**
+ * When Peppa itself typed `prompt` into the session's terminal (an `input_sent` event),
+ * the time it did so; null if the prompt came from a person.
+ */
+export async function peppaInputSentAt(db: Db, sessionId: number, prompt: string): Promise {
+ const sent = await db
+ .select()
+ .from(events)
+ .where(and(eq(events.sessionId, sessionId), eq(events.type, "input_sent")))
+ .orderBy(desc(events.id))
+ .limit(10);
+ const hit = sent.find((e) => sameText(String((e.payload as { text?: string } | null)?.text ?? ""), prompt));
+ return hit?.createdAt ?? null;
+}
+
export async function getQuestion(db: Db, id: number): Promise {
const [row] = await db.select().from(questions).where(eq(questions.id, id));
if (!row) throw new PeppaError(`Question #${id} not found`);
diff --git a/packages/mcp/bin/peppa-mcp b/packages/mcp/bin/peppa-mcp
index bb1ffdb6..837073f1 100755
--- a/packages/mcp/bin/peppa-mcp
+++ b/packages/mcp/bin/peppa-mcp
@@ -2,4 +2,4 @@
# Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves.
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
-exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@"
+exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@"
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index f38906c2..4c6995bd 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -7,7 +7,7 @@
"peppa-mcp": "./bin/peppa-mcp"
},
"scripts": {
- "start": "tsx src/index.ts",
+ "start": "node src/index.ts",
"typecheck": "tsc -p ."
},
"dependencies": {
diff --git a/packages/mcp/scripts/call.ts b/packages/mcp/scripts/call.ts
index 97ba10a3..05301615 100644
--- a/packages/mcp/scripts/call.ts
+++ b/packages/mcp/scripts/call.ts
@@ -1,5 +1,5 @@
// Calls one peppa MCP tool from the current directory, as an agent would.
-// Usage: tsx packages/mcp/scripts/call.ts ''
+// Usage: node packages/mcp/scripts/call.ts ''
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { fileURLToPath } from "node:url";
diff --git a/packages/mcp/scripts/smoke.ts b/packages/mcp/scripts/smoke.ts
index 7d8b5e2a..4d31af3c 100644
--- a/packages/mcp/scripts/smoke.ts
+++ b/packages/mcp/scripts/smoke.ts
@@ -1,5 +1,5 @@
// Smoke test: spawns peppa-mcp in the given project dir and calls a few tools.
-// Usage: tsx packages/mcp/scripts/smoke.ts
+// Usage: node packages/mcp/scripts/smoke.ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { fileURLToPath } from "node:url";
diff --git a/packages/runner/bin/peppa-hook b/packages/runner/bin/peppa-hook
index 3bda0f3d..38dc361f 100755
--- a/packages/runner/bin/peppa-hook
+++ b/packages/runner/bin/peppa-hook
@@ -4,4 +4,4 @@ PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
[ -z "${PEPPA_SESSION_ID:-}" ] && { [ "${1:-}" = codex-notify ] || cat >/dev/null; exit 0; }
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
mkdir -p "${PEPPA_HOME:-$HOME/.peppa}"
-exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@"
+exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@"
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index fa558deb..db61e007 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -10,6 +10,7 @@ import {
getQuestion,
getSession,
logSessionEvent,
+ peppaInputSentAt,
pendingSessionQuestions,
raiseSessionQuestion,
releaseHookQuestion,
@@ -214,8 +215,11 @@ async function handle(event: string, input: HookInput): Promise {
case "prompt":
// Someone typed into the terminal (or Peppa pasted an answer): anything still
- // pending for this session is now answered — except hook-held questions.
- for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true })) {
+ // pending for this session is now answered — except hook-held questions, and,
+ // when Peppa typed this text itself, questions raised after it did (e.g. a CI
+ // failure pasted while the PM is being asked about the next one).
+ const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null;
+ for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) {
await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {});
}
await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now });
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 86601e24..669a48dd 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -136,6 +136,8 @@ async function launch(
export async function sendToSession(db: Db, sessionId: number, text: string): Promise {
const s = await getSession(db, sessionId);
if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`);
+ // Recorded before typing: the prompt hook answers only questions older than this input.
+ await logSessionEvent(db, s, "input_sent", { text });
await tmux.sendText(s.tmuxName, text);
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
}
diff --git a/packages/testkit/bin/mock-claude b/packages/testkit/bin/mock-claude
index c24821f4..d6d407a7 100755
--- a/packages/testkit/bin/mock-claude
+++ b/packages/testkit/bin/mock-claude
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
# Mock claude CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts).
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
-exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@"
+exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@"
diff --git a/packages/testkit/bin/mock-codex b/packages/testkit/bin/mock-codex
index 3616fe4f..c26c43a9 100755
--- a/packages/testkit/bin/mock-codex
+++ b/packages/testkit/bin/mock-codex
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
# Mock codex CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts).
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
-exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@"
+exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@"
diff --git a/packages/testkit/bin/mock-telegram b/packages/testkit/bin/mock-telegram
index 19b2bf9f..e7875044 100755
--- a/packages/testkit/bin/mock-telegram
+++ b/packages/testkit/bin/mock-telegram
@@ -1,3 +1,3 @@
#!/usr/bin/env bash
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
-exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-telegram-server.ts" "$@"
+exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-telegram-server.ts" "$@"
diff --git a/packages/testkit/bin/mock-triage b/packages/testkit/bin/mock-triage
index 22cfbdb3..4f3bc6fc 100755
--- a/packages/testkit/bin/mock-triage
+++ b/packages/testkit/bin/mock-triage
@@ -1,3 +1,3 @@
#!/usr/bin/env bash
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
-exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-triage.ts" "$@"
+exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-triage.ts" "$@"
diff --git a/packages/testkit/bin/peppa-dev b/packages/testkit/bin/peppa-dev
index 5cd5c5b4..6ce87b5f 100755
--- a/packages/testkit/bin/peppa-dev
+++ b/packages/testkit/bin/peppa-dev
@@ -53,6 +53,6 @@ case "${1:-}" in
down) "${TM[@]}" kill-server 2>/dev/null || true; echo "stand is down" ;;
status) status ;;
peppa) shift; exec "$PEPPA" "$@" ;;
- tg) shift; exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/peppa-dev-tg.ts" "$@" ;;
+ tg) shift; exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/peppa-dev-tg.ts" "$@" ;;
*) sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac
diff --git a/packages/testkit/package.json b/packages/testkit/package.json
index cc45f2b5..48887c51 100644
--- a/packages/testkit/package.json
+++ b/packages/testkit/package.json
@@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"typecheck": "tsc -p .",
- "test": "tsx --test --test-concurrency=1 test/*.test.ts"
+ "test": "node --test --test-concurrency=1 test/*.test.ts"
},
"dependencies": {
"@modelcontextprotocol/sdk": "1.32.2",
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index 1fa3591f..e7091460 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -50,8 +50,10 @@ export class MockGitea {
private seq = 1;
private server: Server | null = null;
url = "";
+ private readonly dir: string;
- constructor(private readonly dir: string) {
+ constructor(dir: string) {
+ this.dir = dir;
mkdirSync(dir, { recursive: true });
}
diff --git a/packages/testkit/test/monitor.test.ts b/packages/testkit/test/monitor.test.ts
index 0c586174..b1bb5ba9 100644
--- a/packages/testkit/test/monitor.test.ts
+++ b/packages/testkit/test/monitor.test.ts
@@ -219,7 +219,7 @@ describe("Без спама", () => {
describe("Сводка в CLI", () => {
const cli = (...args: string[]) =>
- execFileSync(join(ROOT, "node_modules/.bin/tsx"), [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env });
+ execFileSync(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env });
test("Сводка", async () => {
const now = Date.now();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1bbe1444..768ee51a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -169,9 +169,6 @@ importers:
'@types/node':
specifier: 26.6.6
version: 26.6.6
- tsx:
- specifier: 4.23.15
- version: 4.23.15
typescript:
specifier: 6.0.3
version: 6.0.3
diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh
index ce102372..d729363e 100755
--- a/scripts/install-launchd.sh
+++ b/scripts/install-launchd.sh
@@ -9,6 +9,11 @@ set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa"
PATH_ENV="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
+# Bot and watchdog run TypeScript straight from source with Node's type stripping (PEP-36):
+# pin the Node that was checked here, so launchd does not depend on what PATH finds later.
+NODE_BIN="${PEPPA_NODE:-$(PATH="$PATH_ENV" command -v node || true)}"
+[ -x "$NODE_BIN" ] || { echo "node not found (set PEPPA_NODE)" >&2; exit 1; }
+"$NODE_BIN" --import "$ROOT/scripts/lib/require-node.mjs" -e 0 || exit 1
install_agent() { # label log workdir args...
local label=$1 log=$2 workdir=$3; shift 3
@@ -25,7 +30,10 @@ install_agent() { # label log workdir args...
$args
WorkingDirectory $workdir
EnvironmentVariables
- PATH $PATH_ENV
+
+ PATH $PATH_ENV
+ PEPPA_NODE $NODE_BIN
+
RunAtLoad
KeepAlive
StandardOutPath $HOME/.peppa/$log
diff --git a/scripts/lib/require-node.mjs b/scripts/lib/require-node.mjs
new file mode 100644
index 00000000..0245f378
--- /dev/null
+++ b/scripts/lib/require-node.mjs
@@ -0,0 +1,9 @@
+// Preloaded by Peppa's bin wrappers (`node --import`): Peppa runs its TypeScript straight
+// from source with Node's built-in type stripping, which older Node versions lack — say so
+// before the first .ts file fails to load with a cryptic error.
+const MIN_MAJOR = 26;
+const major = Number(process.versions.node.split(".")[0]);
+if (major < MIN_MAJOR) {
+ process.stderr.write(`peppa: нужен Node ≥ ${MIN_MAJOR} (сейчас ${process.versions.node}): https://nodejs.org\n`);
+ process.exit(1);
+}
diff --git a/tsconfig.base.json b/tsconfig.base.json
index cf45cb83..d7025976 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -8,6 +8,8 @@
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true,
+ "erasableSyntaxOnly": true,
+ "verbatimModuleSyntax": true,
"noEmit": true,
"types": ["node"]
}
--
2.45.2
From 5120b97a0be45d5047c4180d50d46ae0026fa02d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:44:17 +0500
Subject: [PATCH 016/532] =?UTF-8?q?PEP-57:=20Peppa=20on=20its=20own=20pipe?=
=?UTF-8?q?line=20=E2=80=94=20CI=20via=20project=20checks=20and=20peppa-ch?=
=?UTF-8?q?eck.sh;=204.2=20moved=20to=20PEP-18?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.gitea/peppa-check.sh | 1 +
.gitea/workflows/ci.yml | 38 +++++++++++++++++++------
.peppa/project.json | 13 ++++++++-
AGENTS.md | 2 +-
openspec/changes/pep-57-ci-cd/design.md | 26 +++++++++++++++++
openspec/changes/pep-57-ci-cd/tasks.md | 4 +--
6 files changed, 72 insertions(+), 12 deletions(-)
create mode 120000 .gitea/peppa-check.sh
diff --git a/.gitea/peppa-check.sh b/.gitea/peppa-check.sh
new file mode 120000
index 00000000..b87cf46a
--- /dev/null
+++ b/.gitea/peppa-check.sh
@@ -0,0 +1 @@
+../template/.gitea/peppa-check.sh
\ No newline at end of file
diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml
index e97b18e6..5f6574a9 100644
--- a/.gitea/workflows/ci.yml
+++ b/.gitea/workflows/ci.yml
@@ -1,11 +1,20 @@
-# CI for Peppa itself (PEP-22): typecheck, web build and the e2e suite on mocks — the same
-# scripts/ci.sh that runs locally. Runs on Peppa's act_runner (`peppa-trusted`, registered for
-# peppa-bot's repos, PEP-57); tmux and the openspec CLI are installed in the job.
+# CI for Peppa itself (PEP-22): typecheck, web build and the e2e suite on mocks. Runs on Peppa's
+# act_runner (`peppa-trusted`, registered for peppa-bot's repos, PEP-57); tmux and the openspec
+# CLI are installed in the job. Each check is a step of the factory's own pipeline (PEP-57):
+# the commands are `checks` in .peppa/project.json, .gitea/peppa-check.sh (the template's) sets
+# the `peppa/` commit status and reports to Peppa, so PEP tasks get the same card, review
+# gate and red-check feedback as any factory project. `scripts/ci.sh` runs the same locally.
name: peppa-ci
on:
pull_request:
push:
branches: [main]
+env:
+ PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
+ PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }}
+ PEPPA_PR: ${{ github.event.pull_request.number }}
+ PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }}
+ GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
jobs:
ci:
# The runner has the host's docker.sock: only branches of this repository, never forks.
@@ -13,12 +22,14 @@ jobs:
runs-on: peppa-trusted
timeout-minutes: 30
env:
- # Peppa's Postgres on the host, a database per run (dropped by ci.sh). A service container
+ # Peppa's Postgres on the host, a database per run (dropped in the last step). A service container
# doesn't isolate here: every job shares the traefik_default network and its `postgres` alias.
PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433
PEPPA_TEST_DB: peppa_test_ci_r${{ github.run_id }}
steps:
- uses: actions/checkout@v4
+ with:
+ ref: ${{ env.PEPPA_SHA }}
- uses: actions/setup-node@v4
with:
node-version: "26"
@@ -26,7 +37,18 @@ jobs:
run: |
apt-get update -qq && apt-get install -y -qq tmux >/dev/null
npm install -g pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
- - name: install
- run: pnpm install --frozen-lockfile
- - name: ci
- run: bash scripts/ci.sh
+ - id: install
+ name: install
+ run: bash .gitea/peppa-check.sh install
+ - name: typecheck
+ if: (success() || failure()) && steps.install.outcome == 'success'
+ run: bash .gitea/peppa-check.sh typecheck
+ - name: build
+ if: (success() || failure()) && steps.install.outcome == 'success'
+ run: bash .gitea/peppa-check.sh build
+ - name: test
+ if: (success() || failure()) && steps.install.outcome == 'success'
+ run: bash .gitea/peppa-check.sh test
+ - name: drop test database
+ if: always()
+ run: docker exec peppa-postgres dropdb -U peppa --if-exists "$PEPPA_TEST_DB" || true
diff --git a/.peppa/project.json b/.peppa/project.json
index 830a0620..77a81fb8 100644
--- a/.peppa/project.json
+++ b/.peppa/project.json
@@ -1 +1,12 @@
-{ "slug": "peppa", "key": "PEP", "name": "Peppa", "peppaUrl": "https://peppa.telecom.quest" }
+{
+ "slug": "peppa",
+ "key": "PEP",
+ "name": "Peppa",
+ "peppaUrl": "https://peppa.telecom.quest",
+ "checks": {
+ "install": "pnpm install --frozen-lockfile",
+ "typecheck": "pnpm -r typecheck",
+ "build": "pnpm --filter @peppa/web build",
+ "test": "pnpm --filter @peppa/testkit test"
+ }
+}
diff --git a/AGENTS.md b/AGENTS.md
index 8ce96f26..79255c61 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -60,7 +60,7 @@
- `pnpm dev:web`
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer `
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
-- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: `.gitea/workflows/ci.yml` гоняет `scripts/ci.sh` на каждый PR и push в main на раннере PEP-57 (`peppa-trusted`, Postgres хоста, БД `peppa_test_ci_r`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`); статус `peppa-ci / ci (pull_request)` в PR, мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`)
+- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста, БД `peppa_test_ci_r`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`)
- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`)
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md
index 03d79ade..8a0094e8 100644
--- a/openspec/changes/pep-57-ci-cd/design.md
+++ b/openspec/changes/pep-57-ci-cd/design.md
@@ -90,3 +90,29 @@ Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не н
присылает их); для прода по кнопке — задачи staging-релизов с прошлого прода.
- **Сообщения PM** — вопросы без задачи (`askPmProject`): «staging обновлён» с кнопкой
«🚀 Выкатить в прод» (прежние такие предложения закрываются), откат/провал, прод выкачен.
+- **Откат при смене health-пути** — откат проверяется тем же `deploy.health`, что и новый релиз.
+ Если релиз сам меняет путь проверки на неработающий, старый образ поднимается, но отчёт —
+ `failed` («откат тоже не поднялся»). Проверено вживую на SBX; редкий случай, оставлено так.
+
+## Этап 4
+
+- **4.1 (сделано)** — workflow Пеппы из PEP-22 гоняет `checks` из `.peppa/project.json` через
+ шаблонный `peppa-check.sh` (симлинк `.gitea/peppa-check.sh`): статусы `peppa/<проверка>` и
+ отчёты в Пеппу, гейт ревью и обратная связь для PEP-задач как у любого проекта. Секрет и вебхук
+ на `peppa-bot/peppa` — `setupCi` (раннер peppa-bot уже есть). `scripts/ci.sh` — то же локально.
+- **4.2 (перенесено в PEP-18, нужно решение PM)** — деплой Пеппы её же конвейером меняет
+ launchd и рабочую копию `/Users/telecom/Dev/Peppa`. План:
+ 1. Релизный каталог `~/peppa/releases/` (git worktree от `peppa-bot/peppa`) + симлинк
+ `~/peppa/current`; `.env` — один файл вне релизов (симлинк в каждый релиз).
+ 2. launchd web/bot/watchdog и `~/.local/bin` смотрят в `~/peppa/current`, не в рабочую копию
+ разработки (разработка остаётся в `/Users/telecom/Dev/Peppa`, сессии в worktree).
+ 3. `scripts/peppa-release.sh `: checkout → `pnpm install --frozen-lockfile` → бэкап БД
+ (`pg_dump`) → `pnpm db:migrate` → `next build` → переключить симлинк → `launchctl kickstart`
+ трёх сервисов → health `https://peppa.telecom.quest/healthz` (+ вачдог жив) → при провале
+ симлинк назад и kickstart (миграции только аддитивные, отката схемы нет — восстановление из
+ бэкапа вручную).
+ 4. Запуск: push в main → job `deploy` на `peppa-trusted`, но релиз выполняется на хосте (job в
+ контейнере не может делать `launchctl`) — через launchd-агент-слушатель, который берёт
+ подписанный запрос «выкатить »; прод Пеппы — по кнопке PM, как у проектов
+ (`releases` с project PEP).
+ 5. Ежедневный бэкап Postgres и проверка восстановления (остальное из PEP-18).
diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md
index 3638fdc1..c11b3726 100644
--- a/openspec/changes/pep-57-ci-cd/tasks.md
+++ b/openspec/changes/pep-57-ci-cd/tasks.md
@@ -28,8 +28,8 @@
## 4. Пеппа на собственном конвейере
-- [ ] 4.1 CI Пеппы: typecheck, build, e2e (закрывает PEP-22)
-- [ ] 4.2 CD Пеппы: релизный checkout вместо рабочей копии, миграции, перезапуск сервисов, health, откат (закрывает PEP-18)
+- [x] 4.1 CI Пеппы: typecheck, build, e2e (закрывает PEP-22) — workflow PEP-22 переведён на `checks` + `peppa-check.sh`, секрет и вебхук `setupCi` на peppa-bot/peppa
+- [ ] 4.2 CD Пеппы: релизный checkout вместо рабочей копии, миграции, перезапуск сервисов, health, откат (закрывает PEP-18) — **перенесено в PEP-18**: меняет launchd и рабочую копию `/Users/telecom/Dev/Peppa`, нужно решение PM (план — в design.md, «Этап 4.2»)
## 5. Завершение
--
2.45.2
From ae37ba90d529e5c31f9fbed6d8076adc7e9c39c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:44:39 +0500
Subject: [PATCH 017/532] PEP-57: archive OpenSpec change pep-57-ci-cd (spec
delivery-pipeline)
Co-Authored-By: Claude Opus 5.5
---
.../2026-11-13-pep-57-ci-cd}/.openspec.yaml | 0
.../2026-11-13-pep-57-ci-cd}/design.md | 0
.../2026-11-13-pep-57-ci-cd}/proposal.md | 0
.../specs/delivery-pipeline/spec.md | 0
.../2026-11-13-pep-57-ci-cd}/tasks.md | 2 +-
openspec/specs/delivery-pipeline/spec.md | 83 +++++++++++++++++++
6 files changed, 84 insertions(+), 1 deletion(-)
rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/.openspec.yaml (100%)
rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/design.md (100%)
rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/proposal.md (100%)
rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/specs/delivery-pipeline/spec.md (100%)
rename openspec/changes/{pep-57-ci-cd => archive/2026-11-13-pep-57-ci-cd}/tasks.md (98%)
create mode 100644 openspec/specs/delivery-pipeline/spec.md
diff --git a/openspec/changes/pep-57-ci-cd/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-57-ci-cd/.openspec.yaml
rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/.openspec.yaml
diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/design.md
similarity index 100%
rename from openspec/changes/pep-57-ci-cd/design.md
rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/design.md
diff --git a/openspec/changes/pep-57-ci-cd/proposal.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/proposal.md
similarity index 100%
rename from openspec/changes/pep-57-ci-cd/proposal.md
rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/proposal.md
diff --git a/openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/specs/delivery-pipeline/spec.md
similarity index 100%
rename from openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md
rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/specs/delivery-pipeline/spec.md
diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/tasks.md
similarity index 98%
rename from openspec/changes/pep-57-ci-cd/tasks.md
rename to openspec/changes/archive/2026-11-13-pep-57-ci-cd/tasks.md
index c11b3726..1fffd27a 100644
--- a/openspec/changes/pep-57-ci-cd/tasks.md
+++ b/openspec/changes/archive/2026-11-13-pep-57-ci-cd/tasks.md
@@ -33,4 +33,4 @@
## 5. Завершение
-- [ ] 5.1 Помощь в вебе: раздел «CI/CD»; AGENTS.md; `openspec validate pep-57-ci-cd`; весь e2e-набор зелёный
+- [x] 5.1 Помощь в вебе: раздел «CI/CD»; AGENTS.md; `openspec validate pep-57-ci-cd`; весь e2e-набор зелёный
diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md
new file mode 100644
index 00000000..b143d246
--- /dev/null
+++ b/openspec/specs/delivery-pipeline/spec.md
@@ -0,0 +1,83 @@
+# delivery-pipeline Specification
+
+## Purpose
+Описывает путь изменения от PR агента до работающего продукта: автоматические проверки, условия ревью и мержа, деплой по окружениям, проверку здоровья и откат.
+
+## Requirements
+
+### Requirement: Проверки на каждый PR
+Для каждого PR проекта с настроенными проверками SHALL автоматически выполняться lint, typecheck, test и build, а их результат — отображаться в карточке задачи.
+
+#### Scenario: Зелёные проверки
+- **GIVEN** проект «PAY» с настроенными командами проверок и задача PAY-7 в работе
+- **WHEN** раннер открывает PR по задаче PAY-7 и все проверки проходят
+- **THEN** в карточке PAY-7 видно «Проверки: 4 из 4 пройдены» со ссылкой на прогон
+
+#### Scenario: Проверки не настроены
+- **GIVEN** проект без команд проверок
+- **WHEN** раннер открывает PR
+- **THEN** в карточке задачи видно «проверки не настроены», а переход в «Ревью» не блокируется
+
+### Requirement: Красные проверки возвращаются агенту
+Проваленная проверка SHALL возвращать задачу раннеру с названием шага и фрагментом лога; после 3 неудачных попыток подряд Пеппа SHALL спросить PM.
+
+#### Scenario: Агент чинит сам
+- **GIVEN** PR задачи PAY-7 с проваленным шагом «test» и работающим раннером
+- **WHEN** Пеппа получает результат проверки
+- **THEN** раннер получает сообщение с шагом «test» и последними строками лога
+- **AND** задача остаётся в «В работе», PM ничего не получает
+
+#### Scenario: Три неудачи подряд
+- **GIVEN** проверки PR задачи PAY-7 провалились 3 раза подряд после исправлений агента
+- **WHEN** приходит третий красный результат
+- **THEN** PM получает вопрос по задаче PAY-7 со ссылкой на лог
+- **AND** раннер ждёт ответа
+
+### Requirement: Гейт ревью и мержа
+Задача SHALL попадать в «Ревью», а её PR — мержиться (вручную или автоматически) только при зелёных проверках последнего коммита и отсутствии конфликтов.
+
+#### Scenario: Мерж при красных проверках
+- **GIVEN** PR задачи PAY-7 с проваленной проверкой последнего коммита
+- **WHEN** PM нажимает «Принять»
+- **THEN** мерж не выполняется
+- **AND** PM видит причину «проверки не пройдены»
+
+#### Scenario: Приёмка
+- **GIVEN** PR задачи PAY-7 с зелёными проверками и без конфликтов
+- **WHEN** PM нажимает «Принять»
+- **THEN** PR смержен в основную ветку
+- **AND** задача PAY-7 в «Готово»
+
+### Requirement: Деплой по окружениям
+Мерж в основную ветку SHALL выкатывать проект на staging; прод SHALL выкатываться по действию PM или автоматически, если это включено в настройках проекта; для открытого PR SHALL быть доступен preview-стенд.
+
+#### Scenario: Staging после мержа
+- **GIVEN** проект «PAY» с настроенным деплоем
+- **WHEN** PR задачи PAY-7 смержен
+- **THEN** собран образ с тегом коммита и выкачен на staging
+- **AND** в Пеппе появился релиз staging со списком задач «PAY-7»
+
+#### Scenario: Прод по кнопке
+- **GIVEN** здоровый релиз на staging и ручной режим прода
+- **WHEN** PM нажимает «Выкатить в прод»
+- **THEN** тот же образ выкачен в прод
+- **AND** релиз прода записан с автором «PM»
+
+### Requirement: Проверка здоровья и откат
+После каждого деплоя SHALL выполняться проверка здоровья; при провале окружение SHALL возвращаться к предыдущему релизу, а PM — получать сообщение.
+
+#### Scenario: Неудачный релиз
+- **GIVEN** в проде работает релиз «a1b2c3»
+- **WHEN** выкачен релиз «d4e5f6» и проверка `/healthz` не проходит за 2 минуты
+- **THEN** прод возвращён на «a1b2c3»
+- **AND** релиз «d4e5f6» помечен «откат»
+- **AND** PM получает сообщение с причиной и ссылкой на лог
+
+### Requirement: Изменение конвейера требует ревью
+Изменения файлов конвейера и команд проверок в PR агента SHALL явно показываться PM и не мержиться автоматически.
+
+#### Scenario: Агент отключил тесты
+- **GIVEN** проект в автоматическом режиме мержа
+- **WHEN** PR агента меняет команду «test» в настройках проверок
+- **THEN** PR не мержится автоматически
+- **AND** PM получает вопрос с описанием изменения конвейера
--
2.45.2
From 07e2caa3933762040fa5d2b36c5e3b40439ad3aa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:54:30 +0500
Subject: [PATCH 018/532] PEP-57: PM question on red CI is not closed by the
agent's prompts
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
After three red runs Peppa asked the PM with the session attached, then pasted
"wait for the PM" into that session — its prompt hook closed the question as
answered in the terminal. The question is now task-only; answers to task
questions without a session go to the task's active session.
Co-Authored-By: Claude Opus 5.5
---
packages/runner/src/ci-feedback.ts | 3 ++-
packages/runner/src/sessions.ts | 8 ++++++--
packages/testkit/test/ci-feedback.test.ts | 6 ++++++
3 files changed, 14 insertions(+), 3 deletions(-)
diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts
index 030cc42f..09ac608a 100644
--- a/packages/runner/src/ci-feedback.ts
+++ b/packages/runner/src/ci-feedback.ts
@@ -68,9 +68,10 @@ export async function recordCheck(db: Db, project: Project, r: CheckReport): Pro
if (attempts >= MAX_CI_ATTEMPTS) {
if (!newRun) return { task: ref.key, action: "none" }; // the PM already has this commit
+ // Not tied to the session: the "wait for the PM" paste below (and any prompt of the agent)
+ // would close it as answered in the terminal. The answer still reaches the task's agent.
await askPm(db, ref, {
kind: "question",
- sessionId: sessionId ?? undefined,
text: `❌ ${ref.key}: проверки PR красные ${attempts} раза подряд — агент не справился сам. Упала «${r.check}» (коммит ${r.sha.slice(0, 7)}).${link ? `\nЛог: ${link}` : ""}\n\nЧто делать? Ответ уйдёт агенту.`,
});
if (sessionId) {
diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts
index 669a48dd..95ba8b51 100644
--- a/packages/runner/src/sessions.ts
+++ b/packages/runner/src/sessions.ts
@@ -6,6 +6,7 @@ import {
createSession,
expireSessionQuestions,
getSession,
+ listSessions,
loadSharedRules,
PeppaError,
resolveTask,
@@ -184,8 +185,11 @@ export async function answerAndDeliver(
// "Deploy to prod" on a "staging updated" message (PEP-57).
if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q };
- if (!q.sessionId) return { delivered: false, question: q };
- const s = await getSession(db, q.sessionId);
+ // A task question asked outside a session (red CI, a manual session) goes to the agent
+ // working on the task now, if any.
+ const sessionId = q.sessionId ?? (q.taskId ? (await listSessions(db, { active: true, taskId: q.taskId }))[0]?.id : undefined);
+ if (!sessionId) return { delivered: false, question: q };
+ const s = await getSession(db, sessionId);
if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q };
if (q.kind === "permission") {
diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts
index bdea79c1..398e189f 100644
--- a/packages/testkit/test/ci-feedback.test.ts
+++ b/packages/testkit/test/ci-feedback.test.ts
@@ -133,6 +133,12 @@ describe("Красные проверки возвращаются агенту"
assert.equal(q.taskId, (await t.ref()).task.id);
assert.match(q.text, new RegExp(`красные 3 раза подряд[\\s\\S]*Лог: ${gitea.url}/`));
await t.p.waitLog("runner told to wait", (e) => e.ev === "prompt" && String(e.prompt).includes("жди ответа PM"));
+ // The agent's prompts (the "wait" paste included) don't close the PM's question…
+ await new Promise((r) => setTimeout(r, 1500));
+ assert.ok((await core.pendingQuestions(db, t.proj.id)).some((x) => x.id === q.id), "question still open after the agent's prompt");
+ // …and the answer reaches the agent of the task.
+ assert.equal((await runner.answerAndDeliver(db, q.id, "откати последний коммит", "web")).delivered, true);
+ await t.p.waitLog("answer delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("откати последний коммит"));
// Green again → the counter starts over.
const sha = t.push();
for (const c of Object.keys(CHECKS)) await t.report(sha, c, "success");
--
2.45.2
From 048006fd32a71d48ce24902942a422be7fd5eee2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 16:55:17 +0500
Subject: [PATCH 019/532] PEP-57: re-run CI (runner DNS hiccup)
Co-Authored-By: Claude Opus 5.5
--
2.45.2
From 3a282b8054b3d66a483d8e1de270cb7f9bb8a038 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 17:22:47 +0500
Subject: [PATCH 020/532] PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of
Postgres
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text,
booleans 0/1), one baseline migration; node:sqlite client under drizzle's
better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on
SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB
(default ~/.peppa/peppa.db)
- live updates: notify() pokes the bot over a unix socket; the bot also watches
PRAGMA data_version every second (writes by other processes)
- Postgres specifics ported: createTask transaction is synchronous, no
`for update skip locked`, `count(*)`, json_extract instead of ->>, json_each
instead of @>
- `peppa db migrate` and `peppa db migrate-to-sqlite ` (read-only
snapshot of Postgres, FK order from the schema, row count + foreign key
checks, file appears only when they pass); old Postgres schema kept in
packages/cli/legacy-pg-migrations for the migration and its test
- daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure)
- tests: a temp SQLite file per test file; storage.test.ts (20 processes,
per-project numbering across processes, socket/data_version, migration from
Postgres incl. a dangling foreign key, backups); two test races fixed
- CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test
Co-Authored-By: Claude Opus 5.5
---
.env.example | 6 +-
.gitea/workflows/ci.yml | 8 +-
AGENTS.md | 14 +-
README.md | 2 +-
apps/bot/src/bot.ts | 23 +-
apps/bot/src/index.ts | 2 +-
.../pep-36-lightweight-stack/design.md | 17 +-
.../specs/platform-storage/spec.md | 14 +-
.../changes/pep-36-lightweight-stack/tasks.md | 20 +-
.../0000_safe_shiver_man.sql | 0
.../0001_chunky_dreadnoughts.sql | 0
.../0002_happy_preak.sql | 0
.../0003_material_wild_child.sql | 0
.../0004_loving_wasp.sql | 0
.../0005_sloppy_blue_marvel.sql | 0
.../0006_crazy_stellaris.sql | 0
.../0007_empty_crystal.sql | 0
.../0008_wandering_jetstream.sql | 0
.../0009_steady_preak.sql | 0
.../0010_glamorous_ego.sql | 0
.../0011_pep58_incidents.sql | 0
.../0012_faithful_matthew_murdock.sql | 0
.../0013_pep57_releases.sql | 0
packages/cli/package.json | 3 +-
packages/cli/src/index.ts | 30 +-
packages/cli/src/migrate-to-sqlite.ts | 69 +
packages/core/src/backup.ts | 52 +
packages/core/src/incidents.ts | 6 +-
packages/core/src/index.ts | 1 +
packages/core/src/monitor.ts | 4 +-
packages/core/src/notify.ts | 67 +-
packages/core/src/tasks.ts | 36 +-
packages/core/src/telegram.ts | 3 +-
packages/db/drizzle.config.ts | 4 +-
packages/db/migrations/0000_baseline.sql | 313 +++
.../db/migrations/meta/0000_snapshot.json | 1948 +++++++++++++--
.../db/migrations/meta/0001_snapshot.json | 706 ------
.../db/migrations/meta/0002_snapshot.json | 713 ------
.../db/migrations/meta/0003_snapshot.json | 888 -------
.../db/migrations/meta/0004_snapshot.json | 1003 --------
.../db/migrations/meta/0005_snapshot.json | 1010 --------
.../db/migrations/meta/0006_snapshot.json | 1231 ---------
.../db/migrations/meta/0007_snapshot.json | 1243 ----------
.../db/migrations/meta/0008_snapshot.json | 1402 -----------
.../db/migrations/meta/0009_snapshot.json | 1433 -----------
.../db/migrations/meta/0010_snapshot.json | 1464 -----------
.../db/migrations/meta/0011_snapshot.json | 1893 --------------
.../db/migrations/meta/0012_snapshot.json | 2061 ----------------
.../db/migrations/meta/0013_snapshot.json | 2189 -----------------
packages/db/migrations/meta/_journal.json | 99 +-
packages/db/package.json | 15 +-
packages/db/src/client.ts | 121 +
packages/db/src/index.ts | 72 +-
packages/db/src/schema.ts | 153 +-
packages/runner/src/deploy.ts | 2 +-
packages/runner/src/sessions.ts | 2 +-
packages/runner/src/watchdog.ts | 3 +
packages/shared/src/env.ts | 10 +-
packages/testkit/bin/peppa-dev | 8 +-
packages/testkit/src/storage-worker.ts | 18 +
packages/testkit/test/helpers.ts | 26 +-
packages/testkit/test/incidents.test.ts | 5 +-
packages/testkit/test/monitor.test.ts | 11 +-
packages/testkit/test/storage.test.ts | 197 ++
pnpm-lock.yaml | 6 +-
scripts/ci.sh | 11 +-
66 files changed, 2902 insertions(+), 17735 deletions(-)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0000_safe_shiver_man.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0001_chunky_dreadnoughts.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0002_happy_preak.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0003_material_wild_child.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0004_loving_wasp.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0005_sloppy_blue_marvel.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0006_crazy_stellaris.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0007_empty_crystal.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0008_wandering_jetstream.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0009_steady_preak.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0010_glamorous_ego.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0011_pep58_incidents.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0012_faithful_matthew_murdock.sql (100%)
rename packages/{db/migrations => cli/legacy-pg-migrations}/0013_pep57_releases.sql (100%)
create mode 100644 packages/cli/src/migrate-to-sqlite.ts
create mode 100644 packages/core/src/backup.ts
create mode 100644 packages/db/migrations/0000_baseline.sql
delete mode 100644 packages/db/migrations/meta/0001_snapshot.json
delete mode 100644 packages/db/migrations/meta/0002_snapshot.json
delete mode 100644 packages/db/migrations/meta/0003_snapshot.json
delete mode 100644 packages/db/migrations/meta/0004_snapshot.json
delete mode 100644 packages/db/migrations/meta/0005_snapshot.json
delete mode 100644 packages/db/migrations/meta/0006_snapshot.json
delete mode 100644 packages/db/migrations/meta/0007_snapshot.json
delete mode 100644 packages/db/migrations/meta/0008_snapshot.json
delete mode 100644 packages/db/migrations/meta/0009_snapshot.json
delete mode 100644 packages/db/migrations/meta/0010_snapshot.json
delete mode 100644 packages/db/migrations/meta/0011_snapshot.json
delete mode 100644 packages/db/migrations/meta/0012_snapshot.json
delete mode 100644 packages/db/migrations/meta/0013_snapshot.json
create mode 100644 packages/db/src/client.ts
create mode 100644 packages/testkit/src/storage-worker.ts
create mode 100644 packages/testkit/test/storage.test.ts
diff --git a/.env.example b/.env.example
index 690070bb..ee5cfd5e 100644
--- a/.env.example
+++ b/.env.example
@@ -1,5 +1,7 @@
-# Postgres (infra/docker-compose.yml)
-DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
+# SQLite database file (default ~/.peppa/peppa.db)
+# PEPPA_DB=/Users/me/.peppa/peppa.db
+# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
+# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
# Gitea (git.telecom.quest) — token with repo + org scope
GITEA_URL=https://git.telecom.quest
diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml
index 5f6574a9..a523b9f9 100644
--- a/.gitea/workflows/ci.yml
+++ b/.gitea/workflows/ci.yml
@@ -22,10 +22,9 @@ jobs:
runs-on: peppa-trusted
timeout-minutes: 30
env:
- # Peppa's Postgres on the host, a database per run (dropped in the last step). A service container
- # doesn't isolate here: every job shares the traefik_default network and its `postgres` alias.
+ # Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
+ # for the Postgres → SQLite migration test, which makes and drops its own database.
PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433
- PEPPA_TEST_DB: peppa_test_ci_r${{ github.run_id }}
steps:
- uses: actions/checkout@v4
with:
@@ -49,6 +48,3 @@ jobs:
- name: test
if: (success() || failure()) && steps.install.outcome == 'success'
run: bash .gitea/peppa-check.sh test
- - name: drop test database
- if: always()
- run: docker exec peppa-postgres dropdb -U peppa --if-exists "$PEPPA_TEST_DB" || true
diff --git a/AGENTS.md b/AGENTS.md
index 79255c61..671748aa 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,9 +8,9 @@
## Структура
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web`
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
-- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
+- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36)
- `packages/shared` — env, ключи задач (`PEP-42`)
-- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё
+- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM); живые обновления — `notify()` будит подписчика (бота) через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот вдобавок раз в секунду смотрит `PRAGMA data_version`; ежедневная копия базы (`backupDb`, `VACUUM INTO`, `~/.peppa/backups`, 7 штук) из вачдога; всё ходит через неё
- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов
- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, create_project, list_goals, create_goal, update_goal, list_tasks, get_task, create_task, update_task (название/описание/цель, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question; `instructions` сервера объясняют модель клиенту. Пользовательская документация — `/help` в вебе (держать в актуальном состоянии при изменении инструментов)
- `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM
@@ -25,7 +25,7 @@
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
-- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres Пеппы, `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
+- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (`infra/bugsink/`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]`
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)
@@ -51,7 +51,7 @@
интеграции (какой доступ, у кого).
## Команды
-- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
+- `pnpm db:generate` (новая миграция из схемы) / `pnpm db:migrate` (= `peppa db migrate`); `peppa db migrate-to-sqlite ` — одноразовый перенос из Postgres `DATABASE_URL` (только чтение, сверка строк и внешних ключей; старая pg-схема — `packages/cli/legacy-pg-migrations`); `pnpm db:up` — Postgres для Bugsink
- `peppa project create [--existing]` — проект в Gitea (`provisionProject` в runner, тот же код, что у веба); `peppa project owner `
- `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы
- `peppa web login-link ` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
@@ -60,9 +60,9 @@
- `pnpm dev:web`
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer `
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
-- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e в своей БД `peppa_test_ci_` (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста, БД `peppa_test_ci_r`, `PEPPA_TEST_PG`/`PEPPA_TEST_DB`, удаляется последним шагом); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`)
-- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (БД `$PEPPA_TEST_DB`, по умолчанию `peppa_test`; при параллельных worktree — своя, свой tmux `-L`, свой `PEPPA_HOME`)
-- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
+- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa//.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr ` (временный worktree, статус `peppa/ci`)
+- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (у каждого файла свой временный SQLite-файл, свой tmux `-L`, свой `PEPPA_HOME` — параллельные worktree не мешают друг другу)
+- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa `, `peppa-dev tg messages|click <кнопка>|reply <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`.
diff --git a/README.md b/README.md
index db2ad338..75041df9 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
```bash
pnpm install
cp .env.example .env # GITEA_TOKEN и т.д.
-pnpm db:up && pnpm db:migrate
+pnpm db:migrate # SQLite в ~/.peppa/peppa.db (PEPPA_DB)
scripts/push-template.sh # залить template/ в Gitea
peppa project create demo DEMO "Demo project"
```
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 3bebe1c8..5d6b8ed5 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -9,8 +9,8 @@ import {
claimUpdate,
dueOutbox,
enqueueTelegram,
- EVENTS_CHANNEL,
finishUpdate,
+ listenEvents,
answeredQuestionMessages,
projectForUser,
questionRecipients,
@@ -50,6 +50,8 @@ export interface BotOptions {
reconcileIntervalMs?: number;
/** Heartbeat + check on the watchdog and the web (PEP-20). */
heartbeatIntervalMs?: number;
+ // How often to check PRAGMA data_version for writes the notify() poke missed.
+ changesIntervalMs?: number;
log?: (msg: string) => void;
}
@@ -320,6 +322,20 @@ export function createBot(o: BotOptions) {
}
}
+ // Writes by other processes the poke missed (PRAGMA data_version moves on every commit
+ // from another connection): at most a second late instead of waiting for reconcileLoop.
+ async function changesLoop() {
+ let seen = db.$client.dataVersion();
+ while (!abort.signal.aborted) {
+ await sleep(o.changesIntervalMs ?? 1000);
+ const v = db.$client.dataVersion();
+ if (v !== seen) {
+ seen = v;
+ scheduleReconcile();
+ }
+ }
+ }
+
async function monitorLoop() {
while (!abort.signal.aborted) {
try {
@@ -343,9 +359,8 @@ export function createBot(o: BotOptions) {
const me = await api.getMe();
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
log(`bot @${me.username} started`);
- const l = await db.$client.listen(EVENTS_CHANNEL, () => scheduleReconcile());
- unlisten = () => l.unlisten();
- loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), monitorLoop()]);
+ unlisten = await listenEvents("bot", () => scheduleReconcile());
+ loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]);
return me;
},
async stop() {
diff --git a/apps/bot/src/index.ts b/apps/bot/src/index.ts
index 2fc21e3a..270725ed 100644
--- a/apps/bot/src/index.ts
+++ b/apps/bot/src/index.ts
@@ -10,7 +10,7 @@ if (!env.TELEGRAM_BOT_TOKEN) {
process.exit(1);
}
const bot = createBot({
- db: createDb(env.DATABASE_URL),
+ db: createDb(env.PEPPA_DB),
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
secret: env.TELEGRAM_BOT_TOKEN,
webUrl: env.PEPPA_WEB_URL,
diff --git a/openspec/changes/pep-36-lightweight-stack/design.md b/openspec/changes/pep-36-lightweight-stack/design.md
index c2b3968c..076b8060 100644
--- a/openspec/changes/pep-36-lightweight-stack/design.md
+++ b/openspec/changes/pep-36-lightweight-stack/design.md
@@ -227,14 +227,17 @@ FIFO-очередь записи без хвостов — нужен тольк
- запись — `BEGIN IMMEDIATE`, транзакции короткие и синхронные, до 3 повторов на BUSY;
- база только на локальном диске (WAL не работает на сетевых ФС).
-### 3. LISTEN/NOTIFY → журнал событий + сигнал + страховочный опрос
+### 3. LISTEN/NOTIFY → сигнал по сокету + `PRAGMA data_version`
-Источник правды — таблица `events` и курсор подписчика (`settings`, ключ
-`cursor:`), так бот после рестарта дочитывает пропущенное (сейчас NOTIFY,
-пришедший во время рестарта, теряется, спасает только reconcile раз в 10 с). Записавший
-процесс шлёт датаграмму «есть новое» в unix-сокет `~/.peppa/events.sock` каждого
-подписчика (бот, веб; веб отдаёт браузеру SSE); подписчик без сигнала опрашивает раз в
-секунду. Итог: задержка ~1 мс в норме, ≤ 1 с при сбое сигнала.
+Сделано в этапе 2 проще, чем планировалось: бот и сейчас не читает содержимое NOTIFY,
+а по любому сигналу сверяет очередь с базой (reconcile), поэтому курсор по `events` не
+нужен. `notify()` после записи подключается к unix-сокету `$PEPPA_HOME/bot.events.sock`
+и пишет строку JSON (сокета нет — сразу возвращается). Бот, кроме того, раз в секунду
+читает `PRAGMA data_version` — он меняется при каждом коммите **другого** соединения, —
+и при изменении делает reconcile; плюс прежний reconcile раз в 10 с и при старте. Итог:
+~1 мс в норме, ≤ 1 с при пропущенном сигнале, после рестарта бот находит всё сам.
+(UDP-датаграммы по unix-сокету в Node нет — поэтому короткое stream-соединение.) Веб
+живых обновлений не имел и не получает; SSE — отдельной задачей.
### 4. Поэтапно: Node без tsx → SQLite → Docker
diff --git a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
index 14bf7044..a1a35875 100644
--- a/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
+++ b/openspec/changes/pep-36-lightweight-stack/specs/platform-storage/spec.md
@@ -25,22 +25,22 @@
- **THEN** хук делает 3 попытки, затем пишет в `~/.peppa/hook.log` строку с `hook.event` и `SQLITE_BUSY` и завершается без зависания Claude дольше 30 секунд
### Requirement: Живые обновления без Postgres
-Бот и веб SHALL узнавать о новых событиях, вопросах и изменениях задач, читая журнал `events` по курсору (id последнего прочитанного события). Процесс, записавший событие, SHALL будить подписчиков коротким сигналом по локальному сокету; если сигнал не дошёл, подписчик SHALL всё равно найти событие опросом не реже раза в секунду.
+Процесс, записавший вопрос, ответ, событие или изменение задачи, SHALL будить бота коротким сигналом по локальному unix-сокету; бот по сигналу SHALL сверять очередь сообщений с базой. Если сигнал не дошёл (сокета нет, бот перезапускался), бот SHALL замечать запись другого процесса по счётчику изменений базы не позже чем через секунду.
#### Scenario: Вопрос агента доходит до PM
- **GIVEN** бот запущен, PM привязал Telegram
- **WHEN** агент раннера «PEP-42» задаёт вопрос «Удалить build?»
-- **THEN** бот видит вопрос и ставит сообщение PM в очередь в среднем быстрее 50 мс и в 99 % случаев быстрее 1 секунды
+- **THEN** бот ставит сообщение PM в очередь в 99 % случаев быстрее 1 секунды
#### Scenario: Сокет подписки недоступен
-- **GIVEN** бот запущен, сокет сигналов не создан или упал
-- **WHEN** MCP раннера «PEP-42» пишет `report_progress` «Сделал шаг 3 из 7»
-- **THEN** бот читает это событие не позже чем через 1 секунду после записи
+- **GIVEN** бот запущен, сокет сигналов удалён
+- **WHEN** MCP раннера «PEP-42» в другом процессе пишет `report_progress` «Сделал шаг 3 из 7»
+- **THEN** бот замечает изменение базы не позже чем через 1 секунду после записи
#### Scenario: Бот перезапустился
-- **GIVEN** бот остановлен, курсор бота — событие 120, за время простоя записаны события 121–125
+- **GIVEN** бот остановлен, за время простоя агенты задали 3 вопроса
- **WHEN** бот запускается
-- **THEN** бот обрабатывает события 121–125 по одному разу и сохраняет курсор 125
+- **THEN** PM получает 3 сообщения, по одному на вопрос
### Requirement: Перенос данных из Postgres
Переезд SHALL выполняться командой, которая читает боевую базу Postgres только на чтение, создаёт новый файл SQLite по актуальной схеме, переносит все таблицы и сверяет число строк и внешние ключи. При любом расхождении команда SHALL удалять новый файл, оставлять Postgres без изменений и печатать, в какой таблице расхождение.
diff --git a/openspec/changes/pep-36-lightweight-stack/tasks.md b/openspec/changes/pep-36-lightweight-stack/tasks.md
index ab312704..89b73913 100644
--- a/openspec/changes/pep-36-lightweight-stack/tasks.md
+++ b/openspec/changes/pep-36-lightweight-stack/tasks.md
@@ -21,16 +21,16 @@
## 2. Этап 2 — SQLite вместо Postgres
-- [ ] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`)
-- [ ] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
-- [ ] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции
-- [ ] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) и все будущие `db.transaction` — без `await` внутри; lint-проверка на `transaction(async`
-- [ ] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть
-- [ ] 2.5 Живые обновления: курсор подписчика в `settings`, сигнал по unix-сокету (`~/.peppa/events.sock`) от записавшего процесса, опрос раз в секунду как страховка; бот и веб (SSE) на этом механизме
-- [ ] 2.6 `peppa db migrate-to-sqlite `: чтение Postgres только на чтение, перенос по порядку FK, сверка строк и `foreign_key_check`, откат при расхождении
-- [ ] 2.7 Ежедневная резервная копия (`VACUUM INTO`) из вачдога, 7 копий, алерт при ошибке; health-эндпоинт проверяет файл
-- [ ] 2.8 testkit: временный файл базы на тест вместо `peppa_test`; повторить бенчмарк на настоящем коде (10/20 раннеров на mock-claude)
-- [ ] 2.9 Переключение прода: остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63)
+- [x] 2.0 Начинать после мержа PEP-38 (переделка `apps/web`) — смержен (#24–#26)
+- [x] 2.1 `packages/db`: схема на `sqlite-core` (перенос из `bench/sqlite/schema-port`), одна базовая миграция вместо 0000–0011, драйвер `node:sqlite` через прослойку `node-sqlite-driver.ts`, открытие с `busy_timeout` первой командой, WAL, `synchronous=NORMAL`, `foreign_keys=ON`
+- [x] 2.2 Обёртка записи: `BEGIN IMMEDIATE`, до 3 повторов на `SQLITE_BUSY`, лог с именем операции
+- [x] 2.3 Транзакции только синхронные: `createTask` (core/tasks.ts) переписан; async-колбэк драйвер отклоняет с ошибкой (вместо lint-проверки)
+- [x] 2.4 Postgres-специфика: `pg_notify` → журнал событий + сигнал; `for update skip locked` (core/incidents.ts) → обычная транзакция; `count(*)::int` → `count(*)`; `->>` в core/telegram.ts возвращает число — `cast(… as text)`; `lower()` работает как есть
+- [x] 2.5 Живые обновления: `notify()` будит бота через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот раз в секунду смотрит `PRAGMA data_version` (запись другого процесса) + прежний reconcile раз в 10 с; веб без живых обновлений, как и раньше (SSE — отдельной задачей)
+- [x] 2.6 `peppa db migrate-to-sqlite `: чтение Postgres в read-only снапшоте, порядок таблиц по внешним ключам из схемы, сверка строк и `foreign_key_check`, файл появляется только после проверок; проверено на копии боевой БД (20 таблиц, 64 мс, расхождений нет)
+- [x] 2.7 Ежедневная копия (`backupDb`, `VACUUM INTO`) из вачдога, 7 копий, алерт админам при ошибке; health проверяет таблицы базы
+- [x] 2.8 testkit: временный файл базы на каждый файл тестов вместо `peppa_test`; `storage.test.ts` (20 процессов, нумерация задач из разных процессов, сокет/`data_version`, перенос из Postgres, копии)
+- [ ] 2.9 Переключение прода (деплой — PM, шаги в PR): остановить сервисы → перенос → запуск на SQLite → неделя с Postgres в режиме только чтения как откат → удалить контейнер `peppa-postgres` (контейнер остаётся под Bugsink до PEP-63)
## 3. Этап 3 — запуск одной командой
diff --git a/packages/db/migrations/0000_safe_shiver_man.sql b/packages/cli/legacy-pg-migrations/0000_safe_shiver_man.sql
similarity index 100%
rename from packages/db/migrations/0000_safe_shiver_man.sql
rename to packages/cli/legacy-pg-migrations/0000_safe_shiver_man.sql
diff --git a/packages/db/migrations/0001_chunky_dreadnoughts.sql b/packages/cli/legacy-pg-migrations/0001_chunky_dreadnoughts.sql
similarity index 100%
rename from packages/db/migrations/0001_chunky_dreadnoughts.sql
rename to packages/cli/legacy-pg-migrations/0001_chunky_dreadnoughts.sql
diff --git a/packages/db/migrations/0002_happy_preak.sql b/packages/cli/legacy-pg-migrations/0002_happy_preak.sql
similarity index 100%
rename from packages/db/migrations/0002_happy_preak.sql
rename to packages/cli/legacy-pg-migrations/0002_happy_preak.sql
diff --git a/packages/db/migrations/0003_material_wild_child.sql b/packages/cli/legacy-pg-migrations/0003_material_wild_child.sql
similarity index 100%
rename from packages/db/migrations/0003_material_wild_child.sql
rename to packages/cli/legacy-pg-migrations/0003_material_wild_child.sql
diff --git a/packages/db/migrations/0004_loving_wasp.sql b/packages/cli/legacy-pg-migrations/0004_loving_wasp.sql
similarity index 100%
rename from packages/db/migrations/0004_loving_wasp.sql
rename to packages/cli/legacy-pg-migrations/0004_loving_wasp.sql
diff --git a/packages/db/migrations/0005_sloppy_blue_marvel.sql b/packages/cli/legacy-pg-migrations/0005_sloppy_blue_marvel.sql
similarity index 100%
rename from packages/db/migrations/0005_sloppy_blue_marvel.sql
rename to packages/cli/legacy-pg-migrations/0005_sloppy_blue_marvel.sql
diff --git a/packages/db/migrations/0006_crazy_stellaris.sql b/packages/cli/legacy-pg-migrations/0006_crazy_stellaris.sql
similarity index 100%
rename from packages/db/migrations/0006_crazy_stellaris.sql
rename to packages/cli/legacy-pg-migrations/0006_crazy_stellaris.sql
diff --git a/packages/db/migrations/0007_empty_crystal.sql b/packages/cli/legacy-pg-migrations/0007_empty_crystal.sql
similarity index 100%
rename from packages/db/migrations/0007_empty_crystal.sql
rename to packages/cli/legacy-pg-migrations/0007_empty_crystal.sql
diff --git a/packages/db/migrations/0008_wandering_jetstream.sql b/packages/cli/legacy-pg-migrations/0008_wandering_jetstream.sql
similarity index 100%
rename from packages/db/migrations/0008_wandering_jetstream.sql
rename to packages/cli/legacy-pg-migrations/0008_wandering_jetstream.sql
diff --git a/packages/db/migrations/0009_steady_preak.sql b/packages/cli/legacy-pg-migrations/0009_steady_preak.sql
similarity index 100%
rename from packages/db/migrations/0009_steady_preak.sql
rename to packages/cli/legacy-pg-migrations/0009_steady_preak.sql
diff --git a/packages/db/migrations/0010_glamorous_ego.sql b/packages/cli/legacy-pg-migrations/0010_glamorous_ego.sql
similarity index 100%
rename from packages/db/migrations/0010_glamorous_ego.sql
rename to packages/cli/legacy-pg-migrations/0010_glamorous_ego.sql
diff --git a/packages/db/migrations/0011_pep58_incidents.sql b/packages/cli/legacy-pg-migrations/0011_pep58_incidents.sql
similarity index 100%
rename from packages/db/migrations/0011_pep58_incidents.sql
rename to packages/cli/legacy-pg-migrations/0011_pep58_incidents.sql
diff --git a/packages/db/migrations/0012_faithful_matthew_murdock.sql b/packages/cli/legacy-pg-migrations/0012_faithful_matthew_murdock.sql
similarity index 100%
rename from packages/db/migrations/0012_faithful_matthew_murdock.sql
rename to packages/cli/legacy-pg-migrations/0012_faithful_matthew_murdock.sql
diff --git a/packages/db/migrations/0013_pep57_releases.sql b/packages/cli/legacy-pg-migrations/0013_pep57_releases.sql
similarity index 100%
rename from packages/db/migrations/0013_pep57_releases.sql
rename to packages/cli/legacy-pg-migrations/0013_pep57_releases.sql
diff --git a/packages/cli/package.json b/packages/cli/package.json
index abaa8675..e5cf0316 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -14,6 +14,7 @@
"@peppa/core": "workspace:*",
"@peppa/db": "workspace:*",
"@peppa/shared": "workspace:*",
- "@peppa/runner": "workspace:*"
+ "@peppa/runner": "workspace:*",
+ "postgres": "4.1.1"
}
}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 4635b0ef..a1db5dba 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -38,7 +38,7 @@ import {
updateTask,
type TaskStatus,
} from "@peppa/core";
-import { createDb } from "@peppa/db";
+import { createDb, migrateDb } from "@peppa/db";
import { answerAndDeliver, connectCi, deployProd, listReleases, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
import { loadEnv } from "@peppa/shared";
@@ -73,6 +73,8 @@ const USAGE = `peppa — Peppa software factory CLI
peppa user ensure mock- (local test user)
peppa web login-link (one-time admin login, 10 minutes)
peppa watchdog [--once] [--interval ] [--stall ]
+ peppa db migrate (apply schema migrations to PEPPA_DB)
+ peppa db migrate-to-sqlite (one-time copy from Postgres DATABASE_URL, read-only)
KEY defaults to the project of the current directory (.peppa/project.json).
Statuses: ${TASK_STATUSES.join(", ")}`;
@@ -101,7 +103,31 @@ const { values: opts, positionals } = parseArgs({
});
const env = loadEnv();
-const db = createDb(env.DATABASE_URL);
+
+// `db` commands run before the database is opened: they create or replace the file.
+if (positionals[0] === "db") {
+ try {
+ if (positionals[1] === "migrate") {
+ migrateDb(createDb(env.PEPPA_DB));
+ console.log(`migrated ${env.PEPPA_DB}`);
+ } else if (positionals[1] === "migrate-to-sqlite" && positionals[2]) {
+ if (!env.DATABASE_URL) throw new PeppaError("DATABASE_URL (the Postgres source) is not set");
+ const { migrateToSqlite } = await import("./migrate-to-sqlite.ts");
+ const r = await migrateToSqlite(env.DATABASE_URL, resolve(positionals[2]));
+ for (const t of r.tables) console.log(`${t.name.padEnd(20)} ${t.copied}`);
+ console.log(`перенесено, расхождений нет: ${r.file} (${r.ms} мс)`);
+ } else {
+ console.error(USAGE);
+ process.exit(1);
+ }
+ process.exit(0);
+ } catch (e) {
+ console.error(`peppa: ${(e as Error).message}`);
+ process.exit(1);
+ }
+}
+
+const db = createDb(env.PEPPA_DB);
const here = findProjectFile(process.cwd())?.data.key;
const [group, cmd, ...args] = positionals;
diff --git a/packages/cli/src/migrate-to-sqlite.ts b/packages/cli/src/migrate-to-sqlite.ts
new file mode 100644
index 00000000..d02ee5cc
--- /dev/null
+++ b/packages/cli/src/migrate-to-sqlite.ts
@@ -0,0 +1,69 @@
+// One-time move of Peppa's data from Postgres to SQLite (PEP-36):
+// peppa db migrate-to-sqlite (source: DATABASE_URL)
+// The Postgres session is read-only, so the source cannot change. The new file is built
+// next to the target and renamed into place only after row counts and foreign keys check
+// out; on any mismatch it is deleted and nothing else is touched.
+import { createDb, migrateDb, tablesInFkOrder } from "@peppa/db";
+import { existsSync, renameSync, rmSync } from "node:fs";
+import postgres from "postgres";
+
+const toSqlite = (v: unknown, c: { json: boolean; ms: boolean; bool: boolean }) => {
+ if (v === null || v === undefined) return null;
+ if (c.ms) return v instanceof Date ? v.getTime() : new Date(String(v)).getTime();
+ if (c.bool) return v ? 1 : 0;
+ if (c.json) return JSON.stringify(v);
+ if (typeof v === "bigint") return Number(v);
+ if (v instanceof Date) return v.getTime();
+ return v as string | number;
+};
+
+export interface MigrationReport {
+ file: string;
+ tables: { name: string; source: number; copied: number }[];
+ ms: number;
+}
+
+export async function migrateToSqlite(sourceUrl: string, file: string): Promise {
+ if (existsSync(file)) throw new Error(`${file} уже существует — переложите его`);
+ const tmp = `${file}.migrating`;
+ for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true });
+ const pg = postgres(sourceUrl, { max: 1, onnotice: () => {}, connection: { default_transaction_read_only: "on" } as never });
+ const t0 = Date.now();
+ const db = createDb(tmp);
+ try {
+ migrateDb(db);
+ // Copy first, then check: foreign_key_check names the table with a dangling reference.
+ db.$client.db.exec("PRAGMA foreign_keys = OFF");
+ const report: MigrationReport["tables"] = [];
+ // One read-only snapshot of Postgres for all tables.
+ await pg.begin("isolation level repeatable read read only", async (tx) => {
+ for (const t of tablesInFkOrder()) {
+ const rows = await tx.unsafe(`select * from "${t.name}"`);
+ const cols = t.columns.filter((c) => rows.length === 0 || c.name in rows[0]!);
+ if (rows.length) {
+ const stmt = db.$client.db.prepare(`insert into "${t.name}" (${cols.map((c) => `"${c.name}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`);
+ db.$client.transaction(() => {
+ for (const r of rows) stmt.run(...cols.map((c) => toSqlite(r[c.name], c)));
+ }).immediate();
+ }
+ const [{ n }] = db.$client.db.prepare(`select count(*) n from "${t.name}"`).all() as { n: number }[];
+ report.push({ name: t.name, source: rows.length, copied: Number(n) });
+ }
+ });
+ const bad = report.filter((t) => t.source !== t.copied);
+ if (bad.length) throw new Error(`расходится число строк: ${bad.map((t) => `${t.name} ${t.source}→${t.copied}`).join(", ")}`);
+ const fk = db.$client.db.prepare("PRAGMA foreign_key_check").all() as { table: string }[];
+ if (fk.length) throw new Error(`${[...new Set(fk.map((r) => r.table))].join(", ")}: нарушение внешнего ключа`);
+ db.$client.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
+ db.$client.close();
+ renameSync(tmp, file);
+ for (const s of ["-wal", "-shm"]) rmSync(tmp + s, { force: true });
+ return { file, tables: report, ms: Date.now() - t0 };
+ } catch (e) {
+ db.$client.close();
+ for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true });
+ throw e;
+ } finally {
+ await pg.end({ timeout: 1 });
+ }
+}
diff --git a/packages/core/src/backup.ts b/packages/core/src/backup.ts
new file mode 100644
index 00000000..5660459d
--- /dev/null
+++ b/packages/core/src/backup.ts
@@ -0,0 +1,52 @@
+import type { Db } from "@peppa/db";
+import { peppaHome } from "@peppa/shared";
+import { mkdirSync, readdirSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { alertAdmins } from "./monitor.ts";
+import { getSetting, setSetting } from "./settings.ts";
+
+const DAY_MS = 24 * 3600_000;
+const KEY = "backup:last";
+
+export interface BackupOptions {
+ now?: Date;
+ dir?: string;
+ keep?: number;
+ /** Back up even if the last copy is younger than a day. */
+ force?: boolean;
+ log?: (m: string) => void;
+}
+
+/**
+ * Daily consistent copy of the database (`VACUUM INTO`, no need to stop anything) into
+ * ~/.peppa/backups/peppa-YYYY-MM-DD.db, keeping the newest `keep` (7). A failed copy is
+ * removed and the platform admins are told; the services keep running either way.
+ */
+export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: string; error?: string; skipped?: boolean }> {
+ const now = o.now ?? new Date();
+ const log = o.log ?? (() => {});
+ const last = await getSetting<{ at: number }>(db, KEY);
+ if (!o.force && last && now.getTime() - last.at < DAY_MS) return { skipped: true };
+ const dir = o.dir ?? join(peppaHome(), "backups");
+ const day = now.toLocaleDateString("sv-SE");
+ const file = join(dir, `peppa-${day}.db`);
+ try {
+ mkdirSync(dir, { recursive: true });
+ rmSync(file, { force: true }); // VACUUM INTO refuses to overwrite
+ db.$client.db.prepare("VACUUM INTO ?").run(file);
+ } catch (e) {
+ try {
+ rmSync(file, { force: true });
+ } catch {}
+ const msg = (e as Error).message;
+ const reason = /SQLITE_FULL|ENOSPC|disk is full/i.test(msg) ? "нет места на диске" : msg;
+ await alertAdmins(db, `backup:fail:${day}`, `⚠️ Резервная копия базы Пеппы не сделана: ${reason}`, log);
+ return { error: reason };
+ }
+ const keep = o.keep ?? 7;
+ const copies = readdirSync(dir).filter((f) => /^peppa-\d{4}-\d{2}-\d{2}\.db$/.test(f)).sort();
+ for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true });
+ await setSetting(db, KEY, { at: now.getTime(), file });
+ log(`backup: ${file}`);
+ return { file };
+}
diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts
index 107b7d4f..80c9adf9 100644
--- a/packages/core/src/incidents.ts
+++ b/packages/core/src/incidents.ts
@@ -202,12 +202,12 @@ export async function updateIncident(db: Db, id: number, patch: Partial {
return db
.update(incidents)
.set({ status: "pending" })
- .where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit} for update skip locked)`))
+ .where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit})`))
.returning();
}
@@ -216,7 +216,7 @@ export async function autoIncidentTasksToday(db: Db, projectId: number, now = ne
const midnight = new Date(now);
midnight.setHours(0, 0, 0, 0);
const [r] = await db
- .select({ n: sql`count(*)::int` })
+ .select({ n: sql`count(*)` })
.from(incidents)
.where(and(eq(incidents.projectId, projectId), gte(incidents.taskCreatedAt, midnight), inArray(incidents.decidedBy, ["policy", "triage"])));
return r?.n ?? 0;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c224e041..651f1cd7 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -13,6 +13,7 @@ export * from "./users.ts";
export * from "./oauth.ts";
export * from "./access.ts";
export * from "./monitor.ts";
+export * from "./backup.ts";
export * from "./repo-info.ts";
export * from "./incidents.ts";
export * from "./ci.ts";
diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts
index 9c274dfc..33e0b686 100644
--- a/packages/core/src/monitor.ts
+++ b/packages/core/src/monitor.ts
@@ -121,7 +121,7 @@ export async function adminRecipients(db: Db): Promise {
// ── checks ─────────────────────────────────────────────────────────────────────────
-async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise {
+export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise {
const to = await adminRecipients(db);
if (!to.length) {
log(`monitor: ${text} (нет админа с Telegram)`);
@@ -203,7 +203,7 @@ export async function healthReport(db: Db, o: { now?: Date; version?: string; co
let timer: NodeJS.Timeout | undefined;
try {
await Promise.race([
- db.execute(sql`select 1`),
+ (async () => db.get(sql`select 1 from settings limit 1`))(),
new Promise((_, rej) => (timer = setTimeout(() => rej(new Error("database timeout")), o.timeoutMs ?? 3000))),
]);
} catch (e) {
diff --git a/packages/core/src/notify.ts b/packages/core/src/notify.ts
index a3a4d7bc..96b272b3 100644
--- a/packages/core/src/notify.ts
+++ b/packages/core/src/notify.ts
@@ -1,7 +1,8 @@
import type { Db } from "@peppa/db";
-import { sql } from "drizzle-orm";
-
-export const EVENTS_CHANNEL = "peppa_events";
+import { peppaHome } from "@peppa/shared";
+import { existsSync, rmSync } from "node:fs";
+import { connect, createServer } from "node:net";
+import { join } from "node:path";
export type PeppaNotification =
| { type: "question"; questionId: number }
@@ -11,7 +12,61 @@ export type PeppaNotification =
| { type: "session_updated"; sessionId: number }
| { type: "incident"; incidentId: number };
-/** Broadcasts via Postgres NOTIFY; the bot and web listen on EVENTS_CHANNEL. */
-export async function notify(db: Db, n: PeppaNotification): Promise {
- await db.execute(sql`select pg_notify(${EVENTS_CHANNEL}, ${JSON.stringify(n)})`);
+/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME. */
+export const SUBSCRIBERS = ["bot"] as const;
+export type Subscriber = (typeof SUBSCRIBERS)[number];
+
+export const eventsSocket = (service: Subscriber) => join(peppaHome(), `${service}.events.sock`);
+
+/**
+ * Wakes the subscribers after a write (replaces Postgres NOTIFY, PEP-36). Fire and forget:
+ * the data is already in the database, and a subscriber that misses the poke finds the
+ * change by its own polling (PRAGMA data_version) within a second.
+ */
+export async function notify(_db: Db, n: PeppaNotification): Promise {
+ const line = `${JSON.stringify(n)}\n`;
+ await Promise.all(
+ SUBSCRIBERS.map(
+ (service) =>
+ new Promise((resolve) => {
+ const path = eventsSocket(service);
+ if (!existsSync(path)) return resolve();
+ const sock = connect(path);
+ const done = () => (sock.destroy(), resolve());
+ sock.setTimeout(200, done);
+ sock.on("error", done);
+ sock.end(line, done);
+ }),
+ ),
+ );
+}
+
+/** Listens for notify() pokes; returns a function that stops listening. */
+export async function listenEvents(service: Subscriber, onEvent: (n: PeppaNotification) => void): Promise<() => Promise> {
+ const path = eventsSocket(service);
+ rmSync(path, { force: true }); // left over from a crashed run
+ const server = createServer((sock) => {
+ let buf = "";
+ sock.setEncoding("utf8");
+ sock.on("data", (c) => {
+ buf += c;
+ for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
+ const line = buf.slice(0, i);
+ buf = buf.slice(i + 1);
+ try {
+ onEvent(JSON.parse(line));
+ } catch {}
+ }
+ });
+ sock.on("error", () => {});
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(path, resolve);
+ });
+ return () =>
+ new Promise((resolve) => {
+ server.close(() => resolve());
+ rmSync(path, { force: true });
+ });
}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index f392e3e1..40f1b93d 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -46,21 +46,27 @@ export interface NewTask {
}
export async function createTask(db: Db, t: NewTask): Promise {
- return db.transaction(async (tx) => {
- // Hand out the per-project number atomically.
- const [project] = await tx
- .update(projects)
- .set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` })
- .where(eq(projects.id, t.projectId))
- .returning();
- if (!project) throw new PeppaError(`Project #${t.projectId} not found`);
- if (t.goalId != null) await getGoal(tx as unknown as Db, t.projectId, t.goalId);
- const [task] = await tx
- .insert(tasks)
- .values({ ...t, number: project.nextTaskNumber - 1 })
- .returning();
- return { project, task: task!, key: formatTaskKey(project.key, task!.number) };
- });
+ if (t.goalId != null) await getGoal(db, t.projectId, t.goalId);
+ // Hand out the per-project number atomically. SQLite transactions are synchronous: no
+ // await inside (the driver refuses an async callback).
+ return db.transaction(
+ (tx) => {
+ const [project] = tx
+ .update(projects)
+ .set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` })
+ .where(eq(projects.id, t.projectId))
+ .returning()
+ .all();
+ if (!project) throw new PeppaError(`Project #${t.projectId} not found`);
+ const task = tx
+ .insert(tasks)
+ .values({ ...t, number: project.nextTaskNumber - 1 })
+ .returning()
+ .get();
+ return { project, task, key: formatTaskKey(project.key, task.number) };
+ },
+ { behavior: "immediate" },
+ );
}
export interface TaskFilter {
diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts
index 60b7c251..05e1e8fe 100644
--- a/packages/core/src/telegram.ts
+++ b/packages/core/src/telegram.ts
@@ -142,7 +142,8 @@ export async function questionByTelegramMessage(db: Db, chatId: number, messageI
and(
eq(telegramOutbox.method, "sendMessage"),
eq(telegramOutbox.telegramMessageId, messageId),
- sql`${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`,
+ // json_extract, not ->>: chat_id may be stored as a number or a string.
+ sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`,
),
);
return row?.q ?? null;
diff --git a/packages/db/drizzle.config.ts b/packages/db/drizzle.config.ts
index 8ccff936..0c5e92f3 100644
--- a/packages/db/drizzle.config.ts
+++ b/packages/db/drizzle.config.ts
@@ -1,8 +1,8 @@
import { defineConfig } from "drizzle-kit";
+// `drizzle-kit generate` only; migrations are applied by `peppa db migrate` (node:sqlite).
export default defineConfig({
- dialect: "postgresql",
+ dialect: "sqlite",
schema: "./src/schema.ts",
out: "./migrations",
- dbCredentials: { url: process.env.DATABASE_URL ?? "postgres://peppa:peppa@127.0.0.1:5433/peppa" },
});
diff --git a/packages/db/migrations/0000_baseline.sql b/packages/db/migrations/0000_baseline.sql
new file mode 100644
index 00000000..3e9a1aec
--- /dev/null
+++ b/packages/db/migrations/0000_baseline.sql
@@ -0,0 +1,313 @@
+CREATE TABLE `check_runs` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `sha` text NOT NULL,
+ `branch` text,
+ `pr_number` integer,
+ `check` text NOT NULL,
+ `state` text NOT NULL,
+ `run_url` text,
+ `log_tail` text,
+ `duration_sec` integer,
+ `source` text DEFAULT 'report' NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `check_runs_project_sha_check` ON `check_runs` (`project_id`,`sha`,`check`);--> statement-breakpoint
+CREATE TABLE `error_sources` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `kind` text NOT NULL,
+ `bugsink_project_id` integer NOT NULL,
+ `dsn` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `error_sources_bugsink_project_id_unique` ON `error_sources` (`bugsink_project_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `error_sources_project_kind` ON `error_sources` (`project_id`,`kind`);--> statement-breakpoint
+CREATE TABLE `events` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `session_id` integer,
+ `type` text NOT NULL,
+ `payload` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `goals` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `title` text NOT NULL,
+ `description` text,
+ `status` text DEFAULT 'open' NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `incident_settings` (
+ `project_id` integer PRIMARY KEY NOT NULL,
+ `hook_secret` text NOT NULL,
+ `policy` text DEFAULT 'backlog' NOT NULL,
+ `triage_prompt` text,
+ `environments` text DEFAULT '["prod","production"]' NOT NULL,
+ `daily_limit` integer DEFAULT 5 NOT NULL,
+ `ignore_pattern` text,
+ `goal_id` integer,
+ `webhook_auto` integer DEFAULT false NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `incident_settings_hook_secret_unique` ON `incident_settings` (`hook_secret`);--> statement-breakpoint
+CREATE TABLE `incidents` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `source` text NOT NULL,
+ `bugsink_issue_id` text NOT NULL,
+ `friendly_id` text,
+ `title` text NOT NULL,
+ `culprit` text,
+ `level` text,
+ `environment` text,
+ `first_release` text,
+ `last_release` text,
+ `events` integer DEFAULT 1 NOT NULL,
+ `first_seen` integer NOT NULL,
+ `last_seen` integer NOT NULL,
+ `url` text,
+ `stack` text,
+ `status` text DEFAULT 'new' NOT NULL,
+ `decision` text,
+ `decided_by` text,
+ `decision_reason` text,
+ `task_id` integer,
+ `task_created_at` integer,
+ `resolved_release` text,
+ `resolved_at` integer,
+ `regressions` integer DEFAULT 0 NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `incidents_bugsink_issue_id_unique` ON `incidents` (`bugsink_issue_id`);--> statement-breakpoint
+CREATE TABLE `oauth_clients` (
+ `id` text PRIMARY KEY NOT NULL,
+ `name` text NOT NULL,
+ `redirect_uris` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `oauth_codes` (
+ `code_hash` text PRIMARY KEY NOT NULL,
+ `client_id` text NOT NULL,
+ `user_id` integer NOT NULL,
+ `redirect_uri` text NOT NULL,
+ `code_challenge` text NOT NULL,
+ `scope` text,
+ `expires_at` integer NOT NULL,
+ `used_at` integer,
+ FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `oauth_tokens` (
+ `token_hash` text PRIMARY KEY NOT NULL,
+ `kind` text NOT NULL,
+ `client_id` text NOT NULL,
+ `user_id` integer NOT NULL,
+ `scope` text,
+ `expires_at` integer NOT NULL,
+ `revoked_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `last_used_at` integer,
+ FOREIGN KEY (`client_id`) REFERENCES `oauth_clients`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `project_invites` (
+ `project_id` integer NOT NULL,
+ `login` text NOT NULL,
+ `invited_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ PRIMARY KEY(`project_id`, `login`),
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`invited_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `project_members` (
+ `project_id` integer NOT NULL,
+ `user_id` integer NOT NULL,
+ `added_by` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ PRIMARY KEY(`project_id`, `user_id`),
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`added_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `projects` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `slug` text NOT NULL,
+ `key` text NOT NULL,
+ `name` text NOT NULL,
+ `description` text,
+ `gitea_owner` text NOT NULL,
+ `gitea_repo` text NOT NULL,
+ `default_branch` text DEFAULT 'main' NOT NULL,
+ `workspace_path` text NOT NULL,
+ `owner_id` integer,
+ `next_task_number` integer DEFAULT 1 NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `projects_slug_unique` ON `projects` (`slug`);--> statement-breakpoint
+CREATE UNIQUE INDEX `projects_key_unique` ON `projects` (`key`);--> statement-breakpoint
+CREATE TABLE `questions` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `session_id` integer,
+ `kind` text NOT NULL,
+ `text` text NOT NULL,
+ `options` text,
+ `answer` text,
+ `answered_via` text,
+ `telegram_message_id` integer,
+ `awaiting_hook` integer DEFAULT false NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `answered_at` integer,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE TABLE `releases` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `env` text NOT NULL,
+ `sha` text NOT NULL,
+ `previous_sha` text,
+ `image` text,
+ `host` text,
+ `pr_number` integer,
+ `tasks` text DEFAULT '[]' NOT NULL,
+ `status` text DEFAULT 'deploying' NOT NULL,
+ `deployed_by` text DEFAULT 'ci' NOT NULL,
+ `reason` text,
+ `run_url` text,
+ `log_tail` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `sessions` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer,
+ `tmux_name` text NOT NULL,
+ `provider` text DEFAULT 'claude' NOT NULL,
+ `claude_session_id` text,
+ `generation` integer DEFAULT 0 NOT NULL,
+ `auto_nudges` integer DEFAULT 0 NOT NULL,
+ `resume_at` integer,
+ `limit_probe_min` integer,
+ `limit_resumes` integer DEFAULT 0 NOT NULL,
+ `limit_resumes_day` text,
+ `limit_resumed_at` integer,
+ `status` text DEFAULT 'starting' NOT NULL,
+ `last_activity_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `ended_at` integer,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `sessions_tmux_name_unique` ON `sessions` (`tmux_name`);--> statement-breakpoint
+CREATE TABLE `settings` (
+ `key` text PRIMARY KEY NOT NULL,
+ `value` text NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `tasks` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `goal_id` integer,
+ `number` integer NOT NULL,
+ `title` text NOT NULL,
+ `description` text,
+ `status` text DEFAULT 'backlog' NOT NULL,
+ `openspec_change` text,
+ `pr_url` text,
+ `ci_attempts` integer DEFAULT 0 NOT NULL,
+ `ci_failed_sha` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`goal_id`) REFERENCES `goals`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `tasks_project_number` ON `tasks` (`project_id`,`number`);--> statement-breakpoint
+CREATE TABLE `telegram_outbox` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `dedupe_key` text NOT NULL,
+ `method` text NOT NULL,
+ `params` text NOT NULL,
+ `question_id` integer,
+ `status` text DEFAULT 'pending' NOT NULL,
+ `attempts` integer DEFAULT 0 NOT NULL,
+ `next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `telegram_message_id` integer,
+ `error` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `sent_at` integer,
+ FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `telegram_outbox_dedupe_key_unique` ON `telegram_outbox` (`dedupe_key`);--> statement-breakpoint
+CREATE TABLE `telegram_updates` (
+ `update_id` integer PRIMARY KEY NOT NULL,
+ `status` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `users` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `gitea_id` integer NOT NULL,
+ `login` text NOT NULL,
+ `name` text,
+ `email` text,
+ `avatar_url` text,
+ `access_token_enc` text,
+ `refresh_token_enc` text,
+ `token_expires_at` integer,
+ `claude_token_enc` text,
+ `claude_token_set_at` integer,
+ `telegram_chat_id` integer,
+ `telegram_user_id` integer,
+ `telegram_username` text,
+ `telegram_paired_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `last_login_at` integer
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `users_gitea_id_unique` ON `users` (`gitea_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `users_login_unique` ON `users` (`login`);--> statement-breakpoint
+CREATE UNIQUE INDEX `users_telegram_chat_id_unique` ON `users` (`telegram_chat_id`);
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0000_snapshot.json b/packages/db/migrations/meta/0000_snapshot.json
index a2548dc1..14467986 100644
--- a/packages/db/migrations/meta/0000_snapshot.json
+++ b/packages/db/migrations/meta/0000_snapshot.json
@@ -1,55 +1,292 @@
{
- "id": "2281ab22-b150-4664-9ffc-a0bb54103d9c",
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "7fd81ecb-0ba2-4d0d-9ee9-d1239d6d9725",
"prevId": "00000000-0000-0000-0000-000000000000",
- "version": "7",
- "dialect": "postgresql",
"tables": {
- "public.events": {
- "name": "events",
- "schema": "",
+ "check_runs": {
+ "name": "check_runs",
"columns": {
"id": {
"name": "id",
- "type": "serial",
+ "type": "integer",
"primaryKey": true,
- "notNull": true
+ "notNull": true,
+ "autoincrement": true
},
"project_id": {
"name": "project_id",
"type": "integer",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"task_id": {
"name": "task_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check": {
+ "name": "check",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_sec": {
+ "name": "duration_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'report'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "check_runs_project_sha_check": {
+ "name": "check_runs_project_sha_check",
+ "columns": [
+ "project_id",
+ "sha",
+ "check"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "check_runs_project_id_projects_id_fk": {
+ "name": "check_runs_project_id_projects_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "check_runs_task_id_tasks_id_fk": {
+ "name": "check_runs_task_id_tasks_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "error_sources": {
+ "name": "error_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "columns": [
+ "bugsink_project_id"
+ ],
+ "isUnique": true
+ },
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ "project_id",
+ "kind"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "error_sources_project_id_projects_id_fk": {
+ "name": "error_sources_project_id_projects_id_fk",
+ "tableFrom": "error_sources",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "events": {
+ "name": "events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
},
"session_id": {
"name": "session_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"payload": {
"name": "payload",
- "type": "jsonb",
+ "type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"created_at": {
"name": "created_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
}
},
"indexes": {},
@@ -96,59 +333,62 @@
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
+ "checkConstraints": {}
},
- "public.goals": {
+ "goals": {
"name": "goals",
- "schema": "",
"columns": {
"id": {
"name": "id",
- "type": "serial",
+ "type": "integer",
"primaryKey": true,
- "notNull": true
+ "notNull": true,
+ "autoincrement": true
},
"project_id": {
"name": "project_id",
"type": "integer",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"status": {
"name": "status",
- "type": "goal_status",
- "typeSchema": "public",
+ "type": "text",
"primaryKey": false,
"notNull": true,
+ "autoincrement": false,
"default": "'open'"
},
"created_at": {
"name": "created_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
}
},
"indexes": {},
@@ -169,190 +409,998 @@
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
+ "checkConstraints": {}
},
- "public.projects": {
- "name": "projects",
- "schema": "",
+ "incident_settings": {
+ "name": "incident_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[\"prod\",\"production\"]'"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "columns": [
+ "hook_secret"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_settings_project_id_projects_id_fk": {
+ "name": "incident_settings_project_id_projects_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incident_settings_goal_id_goals_id_fk": {
+ "name": "incident_settings_goal_id_goals_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incidents": {
+ "name": "incidents",
"columns": {
"id": {
"name": "id",
- "type": "serial",
+ "type": "integer",
"primaryKey": true,
- "notNull": true
+ "notNull": true,
+ "autoincrement": true
},
- "slug": {
- "name": "slug",
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
- "key": {
- "name": "key",
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "columns": [
+ "bugsink_issue_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incidents_project_id_projects_id_fk": {
+ "name": "incidents_project_id_projects_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_task_id_tasks_id_fk": {
+ "name": "incidents_task_id_tasks_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_clients": {
+ "name": "oauth_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_codes": {
+ "name": "oauth_codes",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_tokens": {
+ "name": "oauth_tokens",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_invites": {
+ "name": "project_invites",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "columns": [
+ "project_id",
+ "login"
+ ],
+ "name": "project_invites_project_id_login_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_members": {
+ "name": "project_members",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "columns": [
+ "project_id",
+ "user_id"
+ ],
+ "name": "project_members_project_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"gitea_owner": {
"name": "gitea_owner",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"gitea_repo": {
"name": "gitea_repo",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"default_branch": {
"name": "default_branch",
"type": "text",
"primaryKey": false,
"notNull": true,
+ "autoincrement": false,
"default": "'main'"
},
"workspace_path": {
"name": "workspace_path",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
},
"next_task_number": {
"name": "next_task_number",
"type": "integer",
"primaryKey": false,
"notNull": true,
+ "autoincrement": false,
"default": 1
},
"created_at": {
"name": "created_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
}
},
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
+ "indexes": {
"projects_slug_unique": {
"name": "projects_slug_unique",
- "nullsNotDistinct": false,
"columns": [
"slug"
- ]
+ ],
+ "isUnique": true
},
"projects_key_unique": {
"name": "projects_key_unique",
- "nullsNotDistinct": false,
"columns": [
"key"
- ]
+ ],
+ "isUnique": true
}
},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
},
- "public.questions": {
+ "questions": {
"name": "questions",
- "schema": "",
"columns": {
"id": {
"name": "id",
- "type": "serial",
+ "type": "integer",
"primaryKey": true,
- "notNull": true
+ "notNull": true,
+ "autoincrement": true
},
"project_id": {
"name": "project_id",
"type": "integer",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"task_id": {
"name": "task_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"session_id": {
"name": "session_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"text": {
"name": "text",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"options": {
"name": "options",
- "type": "jsonb",
+ "type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"answer": {
"name": "answer",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"answered_via": {
"name": "answered_via",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"telegram_message_id": {
"name": "telegram_message_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
},
"created_at": {
"name": "created_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
},
"answered_at": {
"name": "answered_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
}
},
"indexes": {},
@@ -399,73 +1447,287 @@
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
+ "checkConstraints": {}
},
- "public.sessions": {
- "name": "sessions",
- "schema": "",
+ "releases": {
+ "name": "releases",
"columns": {
"id": {
"name": "id",
- "type": "serial",
+ "type": "integer",
"primaryKey": true,
- "notNull": true
+ "notNull": true,
+ "autoincrement": true
},
"project_id": {
"name": "project_id",
"type": "integer",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "previous_sha": {
+ "name": "previous_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tasks": {
+ "name": "tasks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'deploying'"
+ },
+ "deployed_by": {
+ "name": "deployed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ci'"
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "releases_project_id_projects_id_fk": {
+ "name": "releases_project_id_projects_id_fk",
+ "tableFrom": "releases",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
},
"task_id": {
"name": "task_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"tmux_name": {
"name": "tmux_name",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude'"
},
"claude_session_id": {
"name": "claude_session_id",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
},
"status": {
"name": "status",
- "type": "session_status",
- "typeSchema": "public",
+ "type": "text",
"primaryKey": false,
"notNull": true,
+ "autoincrement": false,
"default": "'starting'"
},
"last_activity_at": {
"name": "last_activity_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"created_at": {
"name": "created_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
},
"ended_at": {
"name": "ended_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "columns": [
+ "tmux_name"
+ ],
+ "isUnique": true
}
},
- "indexes": {},
"foreignKeys": {
"sessions_project_id_projects_id_fk": {
"name": "sessions_project_id_projects_id_fk",
@@ -495,115 +1757,148 @@
}
},
"compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
}
},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
},
- "public.tasks": {
+ "tasks": {
"name": "tasks",
- "schema": "",
"columns": {
"id": {
"name": "id",
- "type": "serial",
+ "type": "integer",
"primaryKey": true,
- "notNull": true
+ "notNull": true,
+ "autoincrement": true
},
"project_id": {
"name": "project_id",
"type": "integer",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"goal_id": {
"name": "goal_id",
"type": "integer",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"number": {
"name": "number",
"type": "integer",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"status": {
"name": "status",
- "type": "task_status",
- "typeSchema": "public",
+ "type": "text",
"primaryKey": false,
"notNull": true,
+ "autoincrement": false,
"default": "'backlog'"
},
"openspec_change": {
"name": "openspec_change",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
},
"pr_url": {
"name": "pr_url",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ci_attempts": {
+ "name": "ci_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "ci_failed_sha": {
+ "name": "ci_failed_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
},
"created_at": {
"name": "created_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
},
"updated_at": {
"name": "updated_at",
- "type": "timestamp with time zone",
+ "type": "integer",
"primaryKey": false,
"notNull": true,
- "default": "now()"
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
}
},
"indexes": {
"tasks_project_number": {
"name": "tasks_project_number",
"columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
+ "project_id",
+ "number"
],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
+ "isUnique": true
}
},
"foreignKeys": {
@@ -636,56 +1931,321 @@
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
+ "checkConstraints": {}
+ },
+ "telegram_outbox": {
+ "name": "telegram_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "params": {
+ "name": "params",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_updates": {
+ "name": "telegram_updates",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "columns": [
+ "gitea_id"
+ ],
+ "isUnique": true
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "columns": [
+ "login"
+ ],
+ "isUnique": true
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "columns": [
+ "telegram_chat_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
}
},
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
"views": {},
+ "enums": {},
"_meta": {
- "columns": {},
"schemas": {},
- "tables": {}
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
}
}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0001_snapshot.json b/packages/db/migrations/meta/0001_snapshot.json
deleted file mode 100644
index bcd77562..00000000
--- a/packages/db/migrations/meta/0001_snapshot.json
+++ /dev/null
@@ -1,706 +0,0 @@
-{
- "id": "7e63ed2b-721c-4506-a2ab-21922112a126",
- "prevId": "2281ab22-b150-4664-9ffc-a0bb54103d9c",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0002_snapshot.json b/packages/db/migrations/meta/0002_snapshot.json
deleted file mode 100644
index 2a1ec5e3..00000000
--- a/packages/db/migrations/meta/0002_snapshot.json
+++ /dev/null
@@ -1,713 +0,0 @@
-{
- "id": "93b4fb9b-40f7-4af5-9ff7-b89be76777ed",
- "prevId": "7e63ed2b-721c-4506-a2ab-21922112a126",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json
deleted file mode 100644
index 2abf1302..00000000
--- a/packages/db/migrations/meta/0003_snapshot.json
+++ /dev/null
@@ -1,888 +0,0 @@
-{
- "id": "6c02c03e-025e-4f66-83bc-fbb2ac391ed4",
- "prevId": "93b4fb9b-40f7-4af5-9ff7-b89be76777ed",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0004_snapshot.json b/packages/db/migrations/meta/0004_snapshot.json
deleted file mode 100644
index 9d06fd40..00000000
--- a/packages/db/migrations/meta/0004_snapshot.json
+++ /dev/null
@@ -1,1003 +0,0 @@
-{
- "id": "1e918b46-e483-457b-8af7-6234a462627c",
- "prevId": "6c02c03e-025e-4f66-83bc-fbb2ac391ed4",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0005_snapshot.json b/packages/db/migrations/meta/0005_snapshot.json
deleted file mode 100644
index 4bf59ff2..00000000
--- a/packages/db/migrations/meta/0005_snapshot.json
+++ /dev/null
@@ -1,1010 +0,0 @@
-{
- "id": "62fecad8-73cc-4298-a603-a38021323859",
- "prevId": "1e918b46-e483-457b-8af7-6234a462627c",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0006_snapshot.json b/packages/db/migrations/meta/0006_snapshot.json
deleted file mode 100644
index c656e4b6..00000000
--- a/packages/db/migrations/meta/0006_snapshot.json
+++ /dev/null
@@ -1,1231 +0,0 @@
-{
- "id": "141bce5b-54a3-438f-b6c9-edf22525ab7b",
- "prevId": "62fecad8-73cc-4298-a603-a38021323859",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0007_snapshot.json b/packages/db/migrations/meta/0007_snapshot.json
deleted file mode 100644
index 3d6d1c5d..00000000
--- a/packages/db/migrations/meta/0007_snapshot.json
+++ /dev/null
@@ -1,1243 +0,0 @@
-{
- "id": "d7d79655-c98d-4cc6-b49b-b8db3ce22738",
- "prevId": "141bce5b-54a3-438f-b6c9-edf22525ab7b",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0008_snapshot.json b/packages/db/migrations/meta/0008_snapshot.json
deleted file mode 100644
index 4c6b99ff..00000000
--- a/packages/db/migrations/meta/0008_snapshot.json
+++ /dev/null
@@ -1,1402 +0,0 @@
-{
- "id": "69625371-6b59-41c2-8555-4582c3e311fa",
- "prevId": "d7d79655-c98d-4cc6-b49b-b8db3ce22738",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_invites": {
- "name": "project_invites",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "invited_by": {
- "name": "invited_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_invites_project_id_projects_id_fk": {
- "name": "project_invites_project_id_projects_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_invites_invited_by_users_id_fk": {
- "name": "project_invites_invited_by_users_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "users",
- "columnsFrom": [
- "invited_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_invites_project_id_login_pk": {
- "name": "project_invites_project_id_login_pk",
- "columns": [
- "project_id",
- "login"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_members": {
- "name": "project_members",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "added_by": {
- "name": "added_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_members_project_id_projects_id_fk": {
- "name": "project_members_project_id_projects_id_fk",
- "tableFrom": "project_members",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_user_id_users_id_fk": {
- "name": "project_members_user_id_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_added_by_users_id_fk": {
- "name": "project_members_added_by_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "added_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_members_project_id_user_id_pk": {
- "name": "project_members_project_id_user_id_pk",
- "columns": [
- "project_id",
- "user_id"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0009_snapshot.json b/packages/db/migrations/meta/0009_snapshot.json
deleted file mode 100644
index c55b0666..00000000
--- a/packages/db/migrations/meta/0009_snapshot.json
+++ /dev/null
@@ -1,1433 +0,0 @@
-{
- "id": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4",
- "prevId": "69625371-6b59-41c2-8555-4582c3e311fa",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_invites": {
- "name": "project_invites",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "invited_by": {
- "name": "invited_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_invites_project_id_projects_id_fk": {
- "name": "project_invites_project_id_projects_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_invites_invited_by_users_id_fk": {
- "name": "project_invites_invited_by_users_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "users",
- "columnsFrom": [
- "invited_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_invites_project_id_login_pk": {
- "name": "project_invites_project_id_login_pk",
- "columns": [
- "project_id",
- "login"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_members": {
- "name": "project_members",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "added_by": {
- "name": "added_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_members_project_id_projects_id_fk": {
- "name": "project_members_project_id_projects_id_fk",
- "tableFrom": "project_members",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_user_id_users_id_fk": {
- "name": "project_members_user_id_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_added_by_users_id_fk": {
- "name": "project_members_added_by_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "added_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_members_project_id_user_id_pk": {
- "name": "project_members_project_id_user_id_pk",
- "columns": [
- "project_id",
- "user_id"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_chat_id": {
- "name": "telegram_chat_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_user_id": {
- "name": "telegram_user_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_username": {
- "name": "telegram_username",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_paired_at": {
- "name": "telegram_paired_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- },
- "users_telegram_chat_id_unique": {
- "name": "users_telegram_chat_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "telegram_chat_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0010_snapshot.json b/packages/db/migrations/meta/0010_snapshot.json
deleted file mode 100644
index 38b990ca..00000000
--- a/packages/db/migrations/meta/0010_snapshot.json
+++ /dev/null
@@ -1,1464 +0,0 @@
-{
- "id": "d5839a22-0118-42d7-9632-545e36e36848",
- "prevId": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_invites": {
- "name": "project_invites",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "invited_by": {
- "name": "invited_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_invites_project_id_projects_id_fk": {
- "name": "project_invites_project_id_projects_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_invites_invited_by_users_id_fk": {
- "name": "project_invites_invited_by_users_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "users",
- "columnsFrom": [
- "invited_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_invites_project_id_login_pk": {
- "name": "project_invites_project_id_login_pk",
- "columns": [
- "project_id",
- "login"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_members": {
- "name": "project_members",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "added_by": {
- "name": "added_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_members_project_id_projects_id_fk": {
- "name": "project_members_project_id_projects_id_fk",
- "tableFrom": "project_members",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_user_id_users_id_fk": {
- "name": "project_members_user_id_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_added_by_users_id_fk": {
- "name": "project_members_added_by_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "added_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_members_project_id_user_id_pk": {
- "name": "project_members_project_id_user_id_pk",
- "columns": [
- "project_id",
- "user_id"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "resume_at": {
- "name": "resume_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "limit_probe_min": {
- "name": "limit_probe_min",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumes": {
- "name": "limit_resumes",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "limit_resumes_day": {
- "name": "limit_resumes_day",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumed_at": {
- "name": "limit_resumed_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_chat_id": {
- "name": "telegram_chat_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_user_id": {
- "name": "telegram_user_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_username": {
- "name": "telegram_username",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_paired_at": {
- "name": "telegram_paired_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- },
- "users_telegram_chat_id_unique": {
- "name": "users_telegram_chat_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "telegram_chat_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0011_snapshot.json b/packages/db/migrations/meta/0011_snapshot.json
deleted file mode 100644
index 3823a4fc..00000000
--- a/packages/db/migrations/meta/0011_snapshot.json
+++ /dev/null
@@ -1,1893 +0,0 @@
-{
- "id": "47a9fc06-6fdb-42ad-8a5f-d80e76193258",
- "prevId": "d5839a22-0118-42d7-9632-545e36e36848",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.error_sources": {
- "name": "error_sources",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "bugsink_project_id": {
- "name": "bugsink_project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "dsn": {
- "name": "dsn",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "error_sources_project_kind": {
- "name": "error_sources_project_kind",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "kind",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "error_sources_project_id_projects_id_fk": {
- "name": "error_sources_project_id_projects_id_fk",
- "tableFrom": "error_sources",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "error_sources_bugsink_project_id_unique": {
- "name": "error_sources_bugsink_project_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "bugsink_project_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.incident_settings": {
- "name": "incident_settings",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "hook_secret": {
- "name": "hook_secret",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "policy": {
- "name": "policy",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "triage_prompt": {
- "name": "triage_prompt",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "environments": {
- "name": "environments",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true,
- "default": "'[\"prod\",\"production\"]'::jsonb"
- },
- "daily_limit": {
- "name": "daily_limit",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 5
- },
- "ignore_pattern": {
- "name": "ignore_pattern",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "webhook_auto": {
- "name": "webhook_auto",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "incident_settings_project_id_projects_id_fk": {
- "name": "incident_settings_project_id_projects_id_fk",
- "tableFrom": "incident_settings",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "incident_settings_goal_id_goals_id_fk": {
- "name": "incident_settings_goal_id_goals_id_fk",
- "tableFrom": "incident_settings",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "incident_settings_hook_secret_unique": {
- "name": "incident_settings_hook_secret_unique",
- "nullsNotDistinct": false,
- "columns": [
- "hook_secret"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.incidents": {
- "name": "incidents",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "source": {
- "name": "source",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "bugsink_issue_id": {
- "name": "bugsink_issue_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "friendly_id": {
- "name": "friendly_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "culprit": {
- "name": "culprit",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "level": {
- "name": "level",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "environment": {
- "name": "environment",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "first_release": {
- "name": "first_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "last_release": {
- "name": "last_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "events": {
- "name": "events",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "first_seen": {
- "name": "first_seen",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "last_seen": {
- "name": "last_seen",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "url": {
- "name": "url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "stack": {
- "name": "stack",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'new'"
- },
- "decision": {
- "name": "decision",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "decided_by": {
- "name": "decided_by",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "decision_reason": {
- "name": "decision_reason",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "task_created_at": {
- "name": "task_created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "resolved_release": {
- "name": "resolved_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "resolved_at": {
- "name": "resolved_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "regressions": {
- "name": "regressions",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "incidents_project_id_projects_id_fk": {
- "name": "incidents_project_id_projects_id_fk",
- "tableFrom": "incidents",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "incidents_task_id_tasks_id_fk": {
- "name": "incidents_task_id_tasks_id_fk",
- "tableFrom": "incidents",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "incidents_bugsink_issue_id_unique": {
- "name": "incidents_bugsink_issue_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "bugsink_issue_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_invites": {
- "name": "project_invites",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "invited_by": {
- "name": "invited_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_invites_project_id_projects_id_fk": {
- "name": "project_invites_project_id_projects_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_invites_invited_by_users_id_fk": {
- "name": "project_invites_invited_by_users_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "users",
- "columnsFrom": [
- "invited_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_invites_project_id_login_pk": {
- "name": "project_invites_project_id_login_pk",
- "columns": [
- "project_id",
- "login"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_members": {
- "name": "project_members",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "added_by": {
- "name": "added_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_members_project_id_projects_id_fk": {
- "name": "project_members_project_id_projects_id_fk",
- "tableFrom": "project_members",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_user_id_users_id_fk": {
- "name": "project_members_user_id_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_added_by_users_id_fk": {
- "name": "project_members_added_by_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "added_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_members_project_id_user_id_pk": {
- "name": "project_members_project_id_user_id_pk",
- "columns": [
- "project_id",
- "user_id"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "resume_at": {
- "name": "resume_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "limit_probe_min": {
- "name": "limit_probe_min",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumes": {
- "name": "limit_resumes",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "limit_resumes_day": {
- "name": "limit_resumes_day",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumed_at": {
- "name": "limit_resumed_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_chat_id": {
- "name": "telegram_chat_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_user_id": {
- "name": "telegram_user_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_username": {
- "name": "telegram_username",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_paired_at": {
- "name": "telegram_paired_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- },
- "users_telegram_chat_id_unique": {
- "name": "users_telegram_chat_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "telegram_chat_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0012_snapshot.json b/packages/db/migrations/meta/0012_snapshot.json
deleted file mode 100644
index c30f3501..00000000
--- a/packages/db/migrations/meta/0012_snapshot.json
+++ /dev/null
@@ -1,2061 +0,0 @@
-{
- "id": "ca89d235-ea51-4284-95fe-50b24621c88a",
- "prevId": "47a9fc06-6fdb-42ad-8a5f-d80e76193258",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.check_runs": {
- "name": "check_runs",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "sha": {
- "name": "sha",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "branch": {
- "name": "branch",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_number": {
- "name": "pr_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "check": {
- "name": "check",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "state": {
- "name": "state",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "run_url": {
- "name": "run_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "log_tail": {
- "name": "log_tail",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "duration_sec": {
- "name": "duration_sec",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "source": {
- "name": "source",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'report'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "check_runs_project_sha_check": {
- "name": "check_runs_project_sha_check",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "sha",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "check",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "check_runs_project_id_projects_id_fk": {
- "name": "check_runs_project_id_projects_id_fk",
- "tableFrom": "check_runs",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "check_runs_task_id_tasks_id_fk": {
- "name": "check_runs_task_id_tasks_id_fk",
- "tableFrom": "check_runs",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.error_sources": {
- "name": "error_sources",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "bugsink_project_id": {
- "name": "bugsink_project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "dsn": {
- "name": "dsn",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "error_sources_project_kind": {
- "name": "error_sources_project_kind",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "kind",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "error_sources_project_id_projects_id_fk": {
- "name": "error_sources_project_id_projects_id_fk",
- "tableFrom": "error_sources",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "error_sources_bugsink_project_id_unique": {
- "name": "error_sources_bugsink_project_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "bugsink_project_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.incident_settings": {
- "name": "incident_settings",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "hook_secret": {
- "name": "hook_secret",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "policy": {
- "name": "policy",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "triage_prompt": {
- "name": "triage_prompt",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "environments": {
- "name": "environments",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true,
- "default": "'[\"prod\",\"production\"]'::jsonb"
- },
- "daily_limit": {
- "name": "daily_limit",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 5
- },
- "ignore_pattern": {
- "name": "ignore_pattern",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "webhook_auto": {
- "name": "webhook_auto",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "incident_settings_project_id_projects_id_fk": {
- "name": "incident_settings_project_id_projects_id_fk",
- "tableFrom": "incident_settings",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "incident_settings_goal_id_goals_id_fk": {
- "name": "incident_settings_goal_id_goals_id_fk",
- "tableFrom": "incident_settings",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "incident_settings_hook_secret_unique": {
- "name": "incident_settings_hook_secret_unique",
- "nullsNotDistinct": false,
- "columns": [
- "hook_secret"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.incidents": {
- "name": "incidents",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "source": {
- "name": "source",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "bugsink_issue_id": {
- "name": "bugsink_issue_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "friendly_id": {
- "name": "friendly_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "culprit": {
- "name": "culprit",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "level": {
- "name": "level",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "environment": {
- "name": "environment",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "first_release": {
- "name": "first_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "last_release": {
- "name": "last_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "events": {
- "name": "events",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "first_seen": {
- "name": "first_seen",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "last_seen": {
- "name": "last_seen",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "url": {
- "name": "url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "stack": {
- "name": "stack",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'new'"
- },
- "decision": {
- "name": "decision",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "decided_by": {
- "name": "decided_by",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "decision_reason": {
- "name": "decision_reason",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "task_created_at": {
- "name": "task_created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "resolved_release": {
- "name": "resolved_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "resolved_at": {
- "name": "resolved_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "regressions": {
- "name": "regressions",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "incidents_project_id_projects_id_fk": {
- "name": "incidents_project_id_projects_id_fk",
- "tableFrom": "incidents",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "incidents_task_id_tasks_id_fk": {
- "name": "incidents_task_id_tasks_id_fk",
- "tableFrom": "incidents",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "incidents_bugsink_issue_id_unique": {
- "name": "incidents_bugsink_issue_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "bugsink_issue_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_invites": {
- "name": "project_invites",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "invited_by": {
- "name": "invited_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_invites_project_id_projects_id_fk": {
- "name": "project_invites_project_id_projects_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_invites_invited_by_users_id_fk": {
- "name": "project_invites_invited_by_users_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "users",
- "columnsFrom": [
- "invited_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_invites_project_id_login_pk": {
- "name": "project_invites_project_id_login_pk",
- "columns": [
- "project_id",
- "login"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_members": {
- "name": "project_members",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "added_by": {
- "name": "added_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_members_project_id_projects_id_fk": {
- "name": "project_members_project_id_projects_id_fk",
- "tableFrom": "project_members",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_user_id_users_id_fk": {
- "name": "project_members_user_id_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_added_by_users_id_fk": {
- "name": "project_members_added_by_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "added_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_members_project_id_user_id_pk": {
- "name": "project_members_project_id_user_id_pk",
- "columns": [
- "project_id",
- "user_id"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "resume_at": {
- "name": "resume_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "limit_probe_min": {
- "name": "limit_probe_min",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumes": {
- "name": "limit_resumes",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "limit_resumes_day": {
- "name": "limit_resumes_day",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumed_at": {
- "name": "limit_resumed_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "ci_attempts": {
- "name": "ci_attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "ci_failed_sha": {
- "name": "ci_failed_sha",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_chat_id": {
- "name": "telegram_chat_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_user_id": {
- "name": "telegram_user_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_username": {
- "name": "telegram_username",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_paired_at": {
- "name": "telegram_paired_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- },
- "users_telegram_chat_id_unique": {
- "name": "users_telegram_chat_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "telegram_chat_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0013_snapshot.json b/packages/db/migrations/meta/0013_snapshot.json
deleted file mode 100644
index 56cb70cd..00000000
--- a/packages/db/migrations/meta/0013_snapshot.json
+++ /dev/null
@@ -1,2189 +0,0 @@
-{
- "id": "82ed94db-27de-4e8f-81c1-5440cb5f4011",
- "prevId": "ca89d235-ea51-4284-95fe-50b24621c88a",
- "version": "7",
- "dialect": "postgresql",
- "tables": {
- "public.check_runs": {
- "name": "check_runs",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "sha": {
- "name": "sha",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "branch": {
- "name": "branch",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_number": {
- "name": "pr_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "check": {
- "name": "check",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "state": {
- "name": "state",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "run_url": {
- "name": "run_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "log_tail": {
- "name": "log_tail",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "duration_sec": {
- "name": "duration_sec",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "source": {
- "name": "source",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'report'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "check_runs_project_sha_check": {
- "name": "check_runs_project_sha_check",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "sha",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "check",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "check_runs_project_id_projects_id_fk": {
- "name": "check_runs_project_id_projects_id_fk",
- "tableFrom": "check_runs",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "check_runs_task_id_tasks_id_fk": {
- "name": "check_runs_task_id_tasks_id_fk",
- "tableFrom": "check_runs",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.error_sources": {
- "name": "error_sources",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "bugsink_project_id": {
- "name": "bugsink_project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "dsn": {
- "name": "dsn",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "error_sources_project_kind": {
- "name": "error_sources_project_kind",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "kind",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "error_sources_project_id_projects_id_fk": {
- "name": "error_sources_project_id_projects_id_fk",
- "tableFrom": "error_sources",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "error_sources_bugsink_project_id_unique": {
- "name": "error_sources_bugsink_project_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "bugsink_project_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.events": {
- "name": "events",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "events_project_id_projects_id_fk": {
- "name": "events_project_id_projects_id_fk",
- "tableFrom": "events",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_task_id_tasks_id_fk": {
- "name": "events_task_id_tasks_id_fk",
- "tableFrom": "events",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "events_session_id_sessions_id_fk": {
- "name": "events_session_id_sessions_id_fk",
- "tableFrom": "events",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.goals": {
- "name": "goals",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "goal_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'open'"
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "goals_project_id_projects_id_fk": {
- "name": "goals_project_id_projects_id_fk",
- "tableFrom": "goals",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.incident_settings": {
- "name": "incident_settings",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "hook_secret": {
- "name": "hook_secret",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "policy": {
- "name": "policy",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "triage_prompt": {
- "name": "triage_prompt",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "environments": {
- "name": "environments",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true,
- "default": "'[\"prod\",\"production\"]'::jsonb"
- },
- "daily_limit": {
- "name": "daily_limit",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 5
- },
- "ignore_pattern": {
- "name": "ignore_pattern",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "webhook_auto": {
- "name": "webhook_auto",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "incident_settings_project_id_projects_id_fk": {
- "name": "incident_settings_project_id_projects_id_fk",
- "tableFrom": "incident_settings",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "incident_settings_goal_id_goals_id_fk": {
- "name": "incident_settings_goal_id_goals_id_fk",
- "tableFrom": "incident_settings",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "incident_settings_hook_secret_unique": {
- "name": "incident_settings_hook_secret_unique",
- "nullsNotDistinct": false,
- "columns": [
- "hook_secret"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.incidents": {
- "name": "incidents",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "source": {
- "name": "source",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "bugsink_issue_id": {
- "name": "bugsink_issue_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "friendly_id": {
- "name": "friendly_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "culprit": {
- "name": "culprit",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "level": {
- "name": "level",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "environment": {
- "name": "environment",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "first_release": {
- "name": "first_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "last_release": {
- "name": "last_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "events": {
- "name": "events",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "first_seen": {
- "name": "first_seen",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "last_seen": {
- "name": "last_seen",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "url": {
- "name": "url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "stack": {
- "name": "stack",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'new'"
- },
- "decision": {
- "name": "decision",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "decided_by": {
- "name": "decided_by",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "decision_reason": {
- "name": "decision_reason",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "task_created_at": {
- "name": "task_created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "resolved_release": {
- "name": "resolved_release",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "resolved_at": {
- "name": "resolved_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "regressions": {
- "name": "regressions",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "incidents_project_id_projects_id_fk": {
- "name": "incidents_project_id_projects_id_fk",
- "tableFrom": "incidents",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "incidents_task_id_tasks_id_fk": {
- "name": "incidents_task_id_tasks_id_fk",
- "tableFrom": "incidents",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "incidents_bugsink_issue_id_unique": {
- "name": "incidents_bugsink_issue_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "bugsink_issue_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_clients": {
- "name": "oauth_clients",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uris": {
- "name": "redirect_uris",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_codes": {
- "name": "oauth_codes",
- "schema": "",
- "columns": {
- "code_hash": {
- "name": "code_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "redirect_uri": {
- "name": "redirect_uri",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "code_challenge": {
- "name": "code_challenge",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "used_at": {
- "name": "used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_codes_client_id_oauth_clients_id_fk": {
- "name": "oauth_codes_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_codes_user_id_users_id_fk": {
- "name": "oauth_codes_user_id_users_id_fk",
- "tableFrom": "oauth_codes",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.oauth_tokens": {
- "name": "oauth_tokens",
- "schema": "",
- "columns": {
- "token_hash": {
- "name": "token_hash",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "client_id": {
- "name": "client_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "scope": {
- "name": "scope",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "expires_at": {
- "name": "expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true
- },
- "revoked_at": {
- "name": "revoked_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_used_at": {
- "name": "last_used_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "oauth_tokens_client_id_oauth_clients_id_fk": {
- "name": "oauth_tokens_client_id_oauth_clients_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "oauth_clients",
- "columnsFrom": [
- "client_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "oauth_tokens_user_id_users_id_fk": {
- "name": "oauth_tokens_user_id_users_id_fk",
- "tableFrom": "oauth_tokens",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_invites": {
- "name": "project_invites",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "invited_by": {
- "name": "invited_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_invites_project_id_projects_id_fk": {
- "name": "project_invites_project_id_projects_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_invites_invited_by_users_id_fk": {
- "name": "project_invites_invited_by_users_id_fk",
- "tableFrom": "project_invites",
- "tableTo": "users",
- "columnsFrom": [
- "invited_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_invites_project_id_login_pk": {
- "name": "project_invites_project_id_login_pk",
- "columns": [
- "project_id",
- "login"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.project_members": {
- "name": "project_members",
- "schema": "",
- "columns": {
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "user_id": {
- "name": "user_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "added_by": {
- "name": "added_by",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "project_members_project_id_projects_id_fk": {
- "name": "project_members_project_id_projects_id_fk",
- "tableFrom": "project_members",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_user_id_users_id_fk": {
- "name": "project_members_user_id_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "user_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "project_members_added_by_users_id_fk": {
- "name": "project_members_added_by_users_id_fk",
- "tableFrom": "project_members",
- "tableTo": "users",
- "columnsFrom": [
- "added_by"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {
- "project_members_project_id_user_id_pk": {
- "name": "project_members_project_id_user_id_pk",
- "columns": [
- "project_id",
- "user_id"
- ]
- }
- },
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.projects": {
- "name": "projects",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "slug": {
- "name": "slug",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "gitea_owner": {
- "name": "gitea_owner",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "gitea_repo": {
- "name": "gitea_repo",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "default_branch": {
- "name": "default_branch",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'main'"
- },
- "workspace_path": {
- "name": "workspace_path",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "owner_id": {
- "name": "owner_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "next_task_number": {
- "name": "next_task_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "projects_owner_id_users_id_fk": {
- "name": "projects_owner_id_users_id_fk",
- "tableFrom": "projects",
- "tableTo": "users",
- "columnsFrom": [
- "owner_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "projects_slug_unique": {
- "name": "projects_slug_unique",
- "nullsNotDistinct": false,
- "columns": [
- "slug"
- ]
- },
- "projects_key_unique": {
- "name": "projects_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.questions": {
- "name": "questions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "session_id": {
- "name": "session_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "kind": {
- "name": "kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "text": {
- "name": "text",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "options": {
- "name": "options",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "answer": {
- "name": "answer",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "answered_via": {
- "name": "answered_via",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "awaiting_hook": {
- "name": "awaiting_hook",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "answered_at": {
- "name": "answered_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "questions_project_id_projects_id_fk": {
- "name": "questions_project_id_projects_id_fk",
- "tableFrom": "questions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_task_id_tasks_id_fk": {
- "name": "questions_task_id_tasks_id_fk",
- "tableFrom": "questions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "questions_session_id_sessions_id_fk": {
- "name": "questions_session_id_sessions_id_fk",
- "tableFrom": "questions",
- "tableTo": "sessions",
- "columnsFrom": [
- "session_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.releases": {
- "name": "releases",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "env": {
- "name": "env",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "sha": {
- "name": "sha",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "previous_sha": {
- "name": "previous_sha",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "image": {
- "name": "image",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "host": {
- "name": "host",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_number": {
- "name": "pr_number",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tasks": {
- "name": "tasks",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true,
- "default": "'[]'::jsonb"
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'deploying'"
- },
- "deployed_by": {
- "name": "deployed_by",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'ci'"
- },
- "reason": {
- "name": "reason",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "run_url": {
- "name": "run_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "log_tail": {
- "name": "log_tail",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {
- "releases_project_id_projects_id_fk": {
- "name": "releases_project_id_projects_id_fk",
- "tableFrom": "releases",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.sessions": {
- "name": "sessions",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "task_id": {
- "name": "task_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "tmux_name": {
- "name": "tmux_name",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'claude'"
- },
- "claude_session_id": {
- "name": "claude_session_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "generation": {
- "name": "generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "auto_nudges": {
- "name": "auto_nudges",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "resume_at": {
- "name": "resume_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "limit_probe_min": {
- "name": "limit_probe_min",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumes": {
- "name": "limit_resumes",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "limit_resumes_day": {
- "name": "limit_resumes_day",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "limit_resumed_at": {
- "name": "limit_resumed_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "session_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'starting'"
- },
- "last_activity_at": {
- "name": "last_activity_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "ended_at": {
- "name": "ended_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "sessions_project_id_projects_id_fk": {
- "name": "sessions_project_id_projects_id_fk",
- "tableFrom": "sessions",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "sessions_task_id_tasks_id_fk": {
- "name": "sessions_task_id_tasks_id_fk",
- "tableFrom": "sessions",
- "tableTo": "tasks",
- "columnsFrom": [
- "task_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "sessions_tmux_name_unique": {
- "name": "sessions_tmux_name_unique",
- "nullsNotDistinct": false,
- "columns": [
- "tmux_name"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.settings": {
- "name": "settings",
- "schema": "",
- "columns": {
- "key": {
- "name": "key",
- "type": "text",
- "primaryKey": true,
- "notNull": true
- },
- "value": {
- "name": "value",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.tasks": {
- "name": "tasks",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "project_id": {
- "name": "project_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "goal_id": {
- "name": "goal_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "number": {
- "name": "number",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "task_status",
- "typeSchema": "public",
- "primaryKey": false,
- "notNull": true,
- "default": "'backlog'"
- },
- "openspec_change": {
- "name": "openspec_change",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "pr_url": {
- "name": "pr_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "ci_attempts": {
- "name": "ci_attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "ci_failed_sha": {
- "name": "ci_failed_sha",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "updated_at": {
- "name": "updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {
- "tasks_project_number": {
- "name": "tasks_project_number",
- "columns": [
- {
- "expression": "project_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "number",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- }
- },
- "foreignKeys": {
- "tasks_project_id_projects_id_fk": {
- "name": "tasks_project_id_projects_id_fk",
- "tableFrom": "tasks",
- "tableTo": "projects",
- "columnsFrom": [
- "project_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "tasks_goal_id_goals_id_fk": {
- "name": "tasks_goal_id_goals_id_fk",
- "tableFrom": "tasks",
- "tableTo": "goals",
- "columnsFrom": [
- "goal_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_outbox": {
- "name": "telegram_outbox",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "dedupe_key": {
- "name": "dedupe_key",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "method": {
- "name": "method",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "params": {
- "name": "params",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
- },
- "question_id": {
- "name": "question_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'pending'"
- },
- "attempts": {
- "name": "attempts",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 0
- },
- "next_attempt_at": {
- "name": "next_attempt_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "telegram_message_id": {
- "name": "telegram_message_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
- "error": {
- "name": "error",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "sent_at": {
- "name": "sent_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {
- "telegram_outbox_question_id_questions_id_fk": {
- "name": "telegram_outbox_question_id_questions_id_fk",
- "tableFrom": "telegram_outbox",
- "tableTo": "questions",
- "columnsFrom": [
- "question_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "set null",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "telegram_outbox_dedupe_key_unique": {
- "name": "telegram_outbox_dedupe_key_unique",
- "nullsNotDistinct": false,
- "columns": [
- "dedupe_key"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.telegram_updates": {
- "name": "telegram_updates",
- "schema": "",
- "columns": {
- "update_id": {
- "name": "update_id",
- "type": "integer",
- "primaryKey": true,
- "notNull": true
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- },
- "public.users": {
- "name": "users",
- "schema": "",
- "columns": {
- "id": {
- "name": "id",
- "type": "serial",
- "primaryKey": true,
- "notNull": true
- },
- "gitea_id": {
- "name": "gitea_id",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "login": {
- "name": "login",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "avatar_url": {
- "name": "avatar_url",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "access_token_enc": {
- "name": "access_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "refresh_token_enc": {
- "name": "refresh_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "token_expires_at": {
- "name": "token_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_enc": {
- "name": "claude_token_enc",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "claude_token_set_at": {
- "name": "claude_token_set_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_chat_id": {
- "name": "telegram_chat_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_user_id": {
- "name": "telegram_user_id",
- "type": "bigint",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_username": {
- "name": "telegram_username",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "telegram_paired_at": {
- "name": "telegram_paired_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
- },
- "last_login_at": {
- "name": "last_login_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {
- "users_gitea_id_unique": {
- "name": "users_gitea_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "gitea_id"
- ]
- },
- "users_login_unique": {
- "name": "users_login_unique",
- "nullsNotDistinct": false,
- "columns": [
- "login"
- ]
- },
- "users_telegram_chat_id_unique": {
- "name": "users_telegram_chat_id_unique",
- "nullsNotDistinct": false,
- "columns": [
- "telegram_chat_id"
- ]
- }
- },
- "policies": {},
- "checkConstraints": {},
- "isRLSEnabled": false
- }
- },
- "enums": {
- "public.goal_status": {
- "name": "goal_status",
- "schema": "public",
- "values": [
- "open",
- "done",
- "archived"
- ]
- },
- "public.session_status": {
- "name": "session_status",
- "schema": "public",
- "values": [
- "starting",
- "running",
- "waiting_input",
- "idle",
- "stalled",
- "rate_limited",
- "done",
- "failed"
- ]
- },
- "public.task_status": {
- "name": "task_status",
- "schema": "public",
- "values": [
- "backlog",
- "proposing",
- "awaiting_approval",
- "in_progress",
- "review",
- "done",
- "blocked"
- ]
- }
- },
- "schemas": {},
- "sequences": {},
- "roles": {},
- "policies": {},
- "views": {},
- "_meta": {
- "columns": {},
- "schemas": {},
- "tables": {}
- }
-}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json
index 108d9a85..48cddda1 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -1,103 +1,12 @@
{
"version": "7",
- "dialect": "postgresql",
+ "dialect": "sqlite",
"entries": [
{
"idx": 0,
- "version": "7",
- "when": 1794492884912,
- "tag": "0000_safe_shiver_man",
- "breakpoints": true
- },
- {
- "idx": 1,
- "version": "7",
- "when": 1794493804069,
- "tag": "0001_chunky_dreadnoughts",
- "breakpoints": true
- },
- {
- "idx": 2,
- "version": "7",
- "when": 1794495121487,
- "tag": "0002_happy_preak",
- "breakpoints": true
- },
- {
- "idx": 3,
- "version": "7",
- "when": 1794496377868,
- "tag": "0003_material_wild_child",
- "breakpoints": true
- },
- {
- "idx": 4,
- "version": "7",
- "when": 1794498071152,
- "tag": "0004_loving_wasp",
- "breakpoints": true
- },
- {
- "idx": 5,
- "version": "7",
- "when": 1794499927803,
- "tag": "0005_sloppy_blue_marvel",
- "breakpoints": true
- },
- {
- "idx": 6,
- "version": "7",
- "when": 1794500991061,
- "tag": "0006_crazy_stellaris",
- "breakpoints": true
- },
- {
- "idx": 7,
- "version": "7",
- "when": 1794502693680,
- "tag": "0007_empty_crystal",
- "breakpoints": true
- },
- {
- "idx": 8,
- "version": "7",
- "when": 1794504595170,
- "tag": "0008_wandering_jetstream",
- "breakpoints": true
- },
- {
- "idx": 9,
- "version": "7",
- "when": 1794505063021,
- "tag": "0009_steady_preak",
- "breakpoints": true
- },
- {
- "idx": 10,
- "version": "7",
- "when": 1794523548954,
- "tag": "0010_glamorous_ego",
- "breakpoints": true
- },
- {
- "idx": 11,
- "version": "7",
- "when": 1794561166402,
- "tag": "0011_pep58_incidents",
- "breakpoints": true
- },
- {
- "idx": 12,
- "version": "7",
- "when": 1794562626634,
- "tag": "0012_faithful_matthew_murdock",
- "breakpoints": true
- },
- {
- "idx": 13,
- "version": "7",
- "when": 1794562970727,
- "tag": "0013_pep57_releases",
+ "version": "6",
+ "when": 1794571062983,
+ "tag": "0000_baseline",
"breakpoints": true
}
]
diff --git a/packages/db/package.json b/packages/db/package.json
index c614d06c..a79173d2 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -3,17 +3,20 @@
"version": "0.0.0",
"private": true,
"type": "module",
- "exports": { ".": "./src/index.ts", "./schema": "./src/schema.ts" },
+ "exports": {
+ ".": "./src/index.ts",
+ "./schema": "./src/schema.ts"
+ },
"scripts": {
"typecheck": "tsc -p .",
"generate": "drizzle-kit generate",
- "migrate": "drizzle-kit migrate",
- "studio": "drizzle-kit studio"
+ "migrate": "node ../cli/src/index.ts db migrate"
},
"dependencies": {
"@peppa/shared": "workspace:*",
- "drizzle-orm": "0.45.4",
- "postgres": "4.1.1"
+ "drizzle-orm": "0.45.4"
},
- "devDependencies": { "drizzle-kit": "0.31.11" }
+ "devDependencies": {
+ "drizzle-kit": "0.31.11"
+ }
}
diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts
new file mode 100644
index 00000000..9f2f8082
--- /dev/null
+++ b/packages/db/src/client.ts
@@ -0,0 +1,121 @@
+// drizzle on Node's built-in node:sqlite (PEP-36). drizzle-orm 0.45 has no node:sqlite
+// driver (only 1.0 beta/rc does), but node:sqlite's API is close to better-sqlite3's, so a
+// thin client lets drizzle's better-sqlite3 *session* run on it. drizzle-orm/better-sqlite3
+// itself is not imported: its driver.js loads the native better-sqlite3 package.
+// Every Peppa process (web, bot, watchdog, each hook and MCP server) opens the file itself;
+// WAL lets readers run next to the single writer, busy_timeout makes writers queue.
+import { DatabaseSync, type StatementSync } from "node:sqlite";
+import { mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+export const BUSY_TIMEOUT_MS = 5000;
+const BUSY_RETRIES = 3;
+
+const isBusy = (e: unknown) => /SQLITE_BUSY|database is locked/i.test(String((e as Error)?.message ?? e));
+
+/** SQLITE_BUSY after busy_timeout already waited: try a few more times before giving up. */
+function retryBusy(fn: () => T): T {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return fn();
+ } catch (e) {
+ if (!isBusy(e) || attempt >= BUSY_RETRIES) throw e;
+ }
+ }
+}
+
+type Params = unknown[];
+
+class Statement {
+ private stmt: StatementSync;
+ private rawStmt: StatementSync | null = null;
+ private db: DatabaseSync;
+ private sql: string;
+ constructor(db: DatabaseSync, sql: string) {
+ this.db = db;
+ this.sql = sql;
+ this.stmt = db.prepare(sql);
+ }
+ run(...p: Params) {
+ return retryBusy(() => this.stmt.run(...(p as never[])));
+ }
+ all(...p: Params) {
+ return retryBusy(() => this.stmt.all(...(p as never[])));
+ }
+ get(...p: Params) {
+ return retryBusy(() => this.stmt.get(...(p as never[])));
+ }
+ /** The same statement returning rows as arrays (drizzle maps columns by position). */
+ raw() {
+ if (!this.rawStmt) {
+ this.rawStmt = this.db.prepare(this.sql);
+ this.rawStmt.setReturnArrays(true);
+ }
+ const s = this.rawStmt;
+ return { all: (...p: Params) => retryBusy(() => s.all(...(p as never[]))), get: (...p: Params) => retryBusy(() => s.get(...(p as never[]))) };
+ }
+}
+
+export class SqliteClient {
+ readonly path: string;
+ private readOnly: boolean;
+ private conn: DatabaseSync | null = null;
+ private cache = new Map();
+ constructor(path: string, opts: { readOnly?: boolean } = {}) {
+ this.path = path;
+ this.readOnly = opts.readOnly ?? false;
+ }
+ /**
+ * The connection, opened on first use: importing a module that creates the client (the
+ * web's lib/db.ts during `next build`) must not create the database file.
+ */
+ get db(): DatabaseSync {
+ if (this.conn) return this.conn;
+ if (this.path !== ":memory:" && !this.readOnly) mkdirSync(dirname(this.path), { recursive: true });
+ const db = new DatabaseSync(this.path, { readOnly: this.readOnly });
+ // busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY
+ // when many processes open the file together (bench/sqlite/README.md).
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
+ if (!this.readOnly) retryBusy(() => db.exec("PRAGMA journal_mode = WAL"));
+ db.exec("PRAGMA synchronous = NORMAL");
+ db.exec("PRAGMA foreign_keys = ON");
+ return (this.conn = db);
+ }
+ prepare(sql: string) {
+ let s = this.cache.get(sql);
+ if (!s) this.cache.set(sql, (s = new Statement(this.db, sql)));
+ return s;
+ }
+ exec(sql: string) {
+ retryBusy(() => this.db.exec(sql));
+ }
+ /** better-sqlite3's transaction API; the callback must be synchronous. */
+ transaction(fn: (...a: never[]) => T) {
+ const run =
+ (begin: string) =>
+ (...a: never[]): T => {
+ retryBusy(() => this.db.exec(begin));
+ try {
+ const r = fn(...a);
+ if (r && typeof (r as { then?: unknown }).then === "function") {
+ throw new Error("SQLite transactions must be synchronous: no async callback, no await inside db.transaction()");
+ }
+ this.db.exec("COMMIT");
+ return r;
+ } catch (e) {
+ if (this.db.isTransaction) this.db.exec("ROLLBACK");
+ throw e;
+ }
+ };
+ return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
+ }
+ /** Changes committed by other connections since the last call (PRAGMA data_version). */
+ dataVersion(): number {
+ return Number((this.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version);
+ }
+ close() {
+ if (this.conn?.isOpen) this.conn.close();
+ this.conn = null;
+ this.cache.clear();
+ }
+}
diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts
index 8c7aab96..050427fc 100644
--- a/packages/db/src/index.ts
+++ b/packages/db/src/index.ts
@@ -1,14 +1,72 @@
import { loadEnv } from "@peppa/shared";
-import { drizzle } from "drizzle-orm/postgres-js";
-import postgres from "postgres";
+import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session";
+import { migrate as drizzleMigrate } from "drizzle-orm/better-sqlite3/migrator";
+import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations";
+import { is } from "drizzle-orm";
+import { getTableConfig, SQLiteTable } from "drizzle-orm/sqlite-core";
+import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db";
+import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect";
+import type { StatementResultingChanges } from "node:sqlite";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { SqliteClient } from "./client.ts";
import * as schema from "./schema.ts";
export * from "./schema.ts";
-export { schema };
+export { schema, SqliteClient };
-export function createDb(url = loadEnv().DATABASE_URL) {
- const client = postgres(url, { max: 5 });
- return drizzle(client, { schema });
+export type Db = BaseSQLiteDatabase<"sync", StatementResultingChanges, typeof schema> & { $client: SqliteClient };
+
+/** Opens Peppa's SQLite database (PEPPA_DB, default ~/.peppa/peppa.db). */
+export function createDb(path = loadEnv().PEPPA_DB, opts: { readOnly?: boolean } = {}): Db {
+ const client = new SqliteClient(path, opts);
+ const dialect = new SQLiteSyncDialect();
+ const tables = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
+ const relational = { fullSchema: schema, schema: tables.tables, tableNamesMap: tables.tableNamesMap };
+ const session = new BetterSQLiteSession(client as never, dialect, relational as never);
+ const db = new BaseSQLiteDatabase("sync", dialect, session as never, relational as never) as Db;
+ db.$client = client;
+ return db;
}
-export type Db = ReturnType;
+// Not `new URL(…, import.meta.url)`: Next's bundler would try to resolve it as an asset.
+export const migrationsFolder = join(dirname(fileURLToPath(import.meta.url)), "..", "migrations");
+
+/** Applies pending migrations (idempotent; safe to run from several processes). */
+export function migrateDb(db: Db) {
+ drizzleMigrate(db as never, { migrationsFolder });
+}
+
+export interface TableInfo {
+ name: string;
+ columns: { name: string; json: boolean; ms: boolean; bool: boolean }[];
+}
+
+/** Peppa's tables, parents before children by foreign keys (for copying data in). */
+export function tablesInFkOrder(): TableInfo[] {
+ const configs = new Map(
+ Object.values(schema)
+ .filter((t) => is(t, SQLiteTable))
+ .map((t) => getTableConfig(t as SQLiteTable))
+ .map((c) => [c.name, c]),
+ );
+ const ordered: string[] = [];
+ const visit = (name: string, path: string[]) => {
+ if (ordered.includes(name) || path.includes(name)) return;
+ for (const fk of configs.get(name)!.foreignKeys) {
+ const parent = getTableConfig(fk.reference().foreignTable).name;
+ if (parent !== name) visit(parent, [...path, name]);
+ }
+ ordered.push(name);
+ };
+ for (const name of [...configs.keys()].sort()) visit(name, []);
+ return ordered.map((name) => ({
+ name,
+ columns: configs.get(name)!.columns.map((c) => ({
+ name: c.name,
+ json: c.columnType === "SQLiteTextJson",
+ ms: c.columnType === "SQLiteTimestamp",
+ bool: c.columnType === "SQLiteBoolean",
+ })),
+ }));
+}
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index 3e6194fc..dc121e0c 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -1,13 +1,18 @@
import { relations } from "drizzle-orm";
-import { bigint, boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
+import { sql } from "drizzle-orm";
+import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
-const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
+// SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is
+// text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only.
+const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
+
+const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs);
const updatedAt = () =>
- timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date());
+ integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date());
/** People who log into the web, one per Gitea account. */
-export const users = pgTable("users", {
- id: serial("id").primaryKey(),
+export const users = sqliteTable("users", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
giteaId: integer("gitea_id").notNull().unique(),
login: text("login").notNull().unique(),
name: text("name"),
@@ -16,22 +21,22 @@ export const users = pgTable("users", {
// OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts).
accessTokenEnc: text("access_token_enc"),
refreshTokenEnc: text("refresh_token_enc"),
- tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }),
+ tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
// Long-lived Claude Code token from `claude setup-token` (encrypted); used for the
// Claude sessions of this user's projects.
claudeTokenEnc: text("claude_token_enc"),
- claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }),
+ claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }),
// Telegram chat paired from Settings; agent questions of this user's projects go there.
- telegramChatId: bigint("telegram_chat_id", { mode: "number" }).unique(),
- telegramUserId: bigint("telegram_user_id", { mode: "number" }),
+ telegramChatId: integer("telegram_chat_id").unique(),
+ telegramUserId: integer("telegram_user_id"),
telegramUsername: text("telegram_username"),
- telegramPairedAt: timestamp("telegram_paired_at", { withTimezone: true }),
+ telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
- lastLoginAt: timestamp("last_login_at", { withTimezone: true }),
+ lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }),
});
-export const projects = pgTable("projects", {
- id: serial("id").primaryKey(),
+export const projects = sqliteTable("projects", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
slug: text("slug").notNull().unique(),
// Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2…
key: text("key").notNull().unique(),
@@ -50,7 +55,7 @@ export const projects = pgTable("projects", {
});
/** People who work on a project besides its owner (projects.owner_id). */
-export const projectMembers = pgTable(
+export const projectMembers = sqliteTable(
"project_members",
{
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
@@ -62,7 +67,7 @@ export const projectMembers = pgTable(
);
/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */
-export const projectInvites = pgTable(
+export const projectInvites = sqliteTable(
"project_invites",
{
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
@@ -73,20 +78,20 @@ export const projectInvites = pgTable(
(t) => [primaryKey({ columns: [t.projectId, t.login] })],
);
-export const goalStatus = pgEnum("goal_status", ["open", "done", "archived"]);
+export const goalStatus = { enumValues: ["open", "done", "archived"] as const };
/** Top-level objectives set by the PM; tasks are broken out of them. */
-export const goals = pgTable("goals", {
- id: serial("id").primaryKey(),
+export const goals = sqliteTable("goals", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
title: text("title").notNull(),
description: text("description"),
- status: goalStatus("status").notNull().default("open"),
+ status: text("status", { enum: goalStatus.enumValues }).notNull().default("open"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
-export const taskStatus = pgEnum("task_status", [
+export const taskStatus = { enumValues: [
"backlog", // created, nobody working on it
"proposing", // agent is writing the OpenSpec change
"awaiting_approval", // proposal ready, PM must approve
@@ -94,18 +99,18 @@ export const taskStatus = pgEnum("task_status", [
"review", // PR open in Gitea
"done", // change archived, merged
"blocked",
-]);
+] as const };
-export const tasks = pgTable(
+export const tasks = sqliteTable(
"tasks",
{
- id: serial("id").primaryKey(),
+ id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
number: integer("number").notNull(),
title: text("title").notNull(),
description: text("description"),
- status: taskStatus("status").notNull().default("backlog"),
+ status: text("status", { enum: taskStatus.enumValues }).notNull().default("backlog"),
// OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth"
openspecChange: text("openspec_change"),
prUrl: text("pr_url"),
@@ -119,8 +124,8 @@ export const tasks = pgTable(
);
/** PEP-57: one deployment of a project to an environment (and its outcome). */
-export const releases = pgTable("releases", {
- id: serial("id").primaryKey(),
+export const releases = sqliteTable("releases", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
env: text("env", { enum: ["preview", "staging", "prod"] }).notNull(),
sha: text("sha").notNull(),
@@ -129,7 +134,7 @@ export const releases = pgTable("releases", {
host: text("host"),
prNumber: integer("pr_number"),
// Task keys in the release ("PAY-7"), from the merged commits.
- tasks: jsonb("tasks").$type().notNull().default([]),
+ tasks: text("tasks", { mode: "json" }).$type().notNull().default([]),
status: text("status", { enum: ["deploying", "healthy", "rolled_back", "failed", "removed"] }).notNull().default("deploying"),
// "ci" for automatic deploys, the PM's login for prod by the button.
deployedBy: text("deployed_by").notNull().default("ci"),
@@ -141,10 +146,10 @@ export const releases = pgTable("releases", {
});
/** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */
-export const checkRuns = pgTable(
+export const checkRuns = sqliteTable(
"check_runs",
{
- id: serial("id").primaryKey(),
+ id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
sha: text("sha").notNull(),
@@ -163,7 +168,7 @@ export const checkRuns = pgTable(
(t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)],
);
-export const sessionStatus = pgEnum("session_status", [
+export const sessionStatus = { enumValues: [
"starting",
"running",
"waiting_input", // Claude asked something / needs permission
@@ -172,11 +177,11 @@ export const sessionStatus = pgEnum("session_status", [
"rate_limited", // StopFailure with error=rate_limit, or limit banner on screen
"done",
"failed",
-]);
+] as const };
/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
-export const sessions = pgTable("sessions", {
- id: serial("id").primaryKey(),
+export const sessions = sqliteTable("sessions", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
tmuxName: text("tmux_name").notNull().unique(),
@@ -189,53 +194,53 @@ export const sessions = pgTable("sessions", {
autoNudges: integer("auto_nudges").notNull().default(0),
// Usage limit recovery (PEP-56): when to continue, current probe interval if the reset
// time is unknown, auto-resumes today (cap), and when the last auto-resume happened.
- resumeAt: timestamp("resume_at", { withTimezone: true }),
+ resumeAt: integer("resume_at", { mode: "timestamp_ms" }),
limitProbeMin: integer("limit_probe_min"),
limitResumes: integer("limit_resumes").notNull().default(0),
limitResumesDay: text("limit_resumes_day"),
- limitResumedAt: timestamp("limit_resumed_at", { withTimezone: true }),
- status: sessionStatus("status").notNull().default("starting"),
- lastActivityAt: timestamp("last_activity_at", { withTimezone: true }),
+ limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }),
+ status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"),
+ lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }),
startedAt: createdAt(),
- endedAt: timestamp("ended_at", { withTimezone: true }),
+ endedAt: integer("ended_at", { mode: "timestamp_ms" }),
});
/** Questions routed to the PM (Telegram / web) and their answers. */
-export const questions = pgTable("questions", {
- id: serial("id").primaryKey(),
+export const questions = sqliteTable("questions", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
// Null when asked from a session Peppa did not start (manual `claude`).
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
text: text("text").notNull(),
- options: jsonb("options").$type(),
+ options: text("options", { mode: "json" }).$type