bench/sqlite (outside the workspace): Peppa-like load with 10/20 runners, a hook process per event, MCP, bot, web and watchdog; bun:sqlite, node:sqlite, better-sqlite3, a single-writer service and Postgres; notify replacements (cursor polling, fs.watch on WAL, unix-socket push); a ceiling test; a schema port to sqlite with a data copy from Postgres and a check of drizzle transactions. openspec/changes/pep-36-lightweight-stack: proposal, design with the numbers, specs (platform-storage, service-monitoring), phased tasks. No product code changes; the move waits for the PM's decision. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
358 lines
17 KiB
TypeScript
358 lines
17 KiB
TypeScript
import { relations } from "drizzle-orm";
|
|
import { sql } from "drizzle-orm";
|
|
import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
|
|
// PEP-36 prototype: the Peppa schema mechanically ported to SQLite (not used by the product).
|
|
const nowMs = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
|
|
|
|
const createdAt = () => integer("created_at", { mode: "timestamp_ms" }).notNull().default(nowMs);
|
|
const updatedAt = () =>
|
|
integer("updated_at", { mode: "timestamp_ms" }).notNull().default(nowMs).$onUpdate(() => new Date());
|
|
|
|
/** People who log into the web, one per Gitea account. */
|
|
export const users = sqliteTable("users", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
giteaId: integer("gitea_id").notNull().unique(),
|
|
login: text("login").notNull().unique(),
|
|
name: text("name"),
|
|
email: text("email"),
|
|
avatarUrl: text("avatar_url"),
|
|
// OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts).
|
|
accessTokenEnc: text("access_token_enc"),
|
|
refreshTokenEnc: text("refresh_token_enc"),
|
|
tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
|
|
// Long-lived Claude Code token from `claude setup-token` (encrypted); used for the
|
|
// Claude sessions of this user's projects.
|
|
claudeTokenEnc: text("claude_token_enc"),
|
|
claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }),
|
|
// Telegram chat paired from Settings; agent questions of this user's projects go there.
|
|
telegramChatId: integer("telegram_chat_id").unique(),
|
|
telegramUserId: integer("telegram_user_id"),
|
|
telegramUsername: text("telegram_username"),
|
|
telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
|
|
createdAt: createdAt(),
|
|
lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }),
|
|
});
|
|
|
|
export const projects = sqliteTable("projects", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
slug: text("slug").notNull().unique(),
|
|
// Task key prefix, e.g. "PEP" → tasks PEP-1, PEP-2…
|
|
key: text("key").notNull().unique(),
|
|
name: text("name").notNull(),
|
|
description: text("description"),
|
|
giteaOwner: text("gitea_owner").notNull(),
|
|
giteaRepo: text("gitea_repo").notNull(),
|
|
defaultBranch: text("default_branch").notNull().default("main"),
|
|
workspacePath: text("workspace_path").notNull(),
|
|
// Null for projects created by the bot/CLI; only the owner sees a project in the web.
|
|
ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }),
|
|
// Next task number to hand out; bumped atomically on task creation.
|
|
nextTaskNumber: integer("next_task_number").notNull().default(1),
|
|
createdAt: createdAt(),
|
|
updatedAt: updatedAt(),
|
|
});
|
|
|
|
/** People who work on a project besides its owner (projects.owner_id). */
|
|
export const projectMembers = sqliteTable(
|
|
"project_members",
|
|
{
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
addedBy: integer("added_by").references(() => users.id, { onDelete: "set null" }),
|
|
createdAt: createdAt(),
|
|
},
|
|
(t) => [primaryKey({ columns: [t.projectId, t.userId] })],
|
|
);
|
|
|
|
/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */
|
|
export const projectInvites = sqliteTable(
|
|
"project_invites",
|
|
{
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
login: text("login").notNull(), // lower-cased Gitea login
|
|
invitedBy: integer("invited_by").references(() => users.id, { onDelete: "set null" }),
|
|
createdAt: createdAt(),
|
|
},
|
|
(t) => [primaryKey({ columns: [t.projectId, t.login] })],
|
|
);
|
|
|
|
export const goalStatusValues = ["open", "done", "archived"] as const;
|
|
|
|
/** Top-level objectives set by the PM; tasks are broken out of them. */
|
|
export const goals = sqliteTable("goals", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
title: text("title").notNull(),
|
|
description: text("description"),
|
|
status: text("status", { enum: goalStatusValues }).notNull().default("open"),
|
|
createdAt: createdAt(),
|
|
updatedAt: updatedAt(),
|
|
});
|
|
|
|
export const taskStatusValues = [
|
|
"backlog", // created, nobody working on it
|
|
"proposing", // agent is writing the OpenSpec change
|
|
"awaiting_approval", // proposal ready, PM must approve
|
|
"in_progress", // agent applying the change
|
|
"review", // PR open in Gitea
|
|
"done", // change archived, merged
|
|
"blocked",
|
|
] as const;
|
|
|
|
export const tasks = sqliteTable(
|
|
"tasks",
|
|
{
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
|
|
number: integer("number").notNull(),
|
|
title: text("title").notNull(),
|
|
description: text("description"),
|
|
status: text("status", { enum: taskStatusValues }).notNull().default("backlog"),
|
|
// OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth"
|
|
openspecChange: text("openspec_change"),
|
|
prUrl: text("pr_url"),
|
|
createdAt: createdAt(),
|
|
updatedAt: updatedAt(),
|
|
},
|
|
(t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)],
|
|
);
|
|
|
|
export const sessionStatusValues = [
|
|
"starting",
|
|
"running",
|
|
"waiting_input", // Claude asked something / needs permission
|
|
"idle", // turn finished, nothing pending
|
|
"stalled", // watchdog saw no activity
|
|
"rate_limited", // StopFailure with error=rate_limit, or limit banner on screen
|
|
"done",
|
|
"failed",
|
|
] as const;
|
|
|
|
/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
|
|
export const sessions = sqliteTable("sessions", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
|
tmuxName: text("tmux_name").notNull().unique(),
|
|
provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"),
|
|
// Claude session id or Codex thread id — the resume target.
|
|
conversationId: text("claude_session_id"),
|
|
// Bumped on every launch/resume; hooks from an older generation are ignored.
|
|
generation: integer("generation").notNull().default(0),
|
|
// Consecutive "keep going" nudges from the Stop hook; reset when a human answers.
|
|
autoNudges: integer("auto_nudges").notNull().default(0),
|
|
// Usage limit recovery (PEP-56): when to continue, current probe interval if the reset
|
|
// time is unknown, auto-resumes today (cap), and when the last auto-resume happened.
|
|
resumeAt: integer("resume_at", { mode: "timestamp_ms" }),
|
|
limitProbeMin: integer("limit_probe_min"),
|
|
limitResumes: integer("limit_resumes").notNull().default(0),
|
|
limitResumesDay: text("limit_resumes_day"),
|
|
limitResumedAt: integer("limit_resumed_at", { mode: "timestamp_ms" }),
|
|
status: text("status", { enum: sessionStatusValues }).notNull().default("starting"),
|
|
lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }),
|
|
startedAt: createdAt(),
|
|
endedAt: integer("ended_at", { mode: "timestamp_ms" }),
|
|
});
|
|
|
|
/** Questions routed to the PM (Telegram / web) and their answers. */
|
|
export const questions = sqliteTable("questions", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
|
// Null when asked from a session Peppa did not start (manual `claude`).
|
|
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
|
kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
|
|
text: text("text").notNull(),
|
|
options: text("options", { mode: "json" }).$type<string[]>(),
|
|
answer: text("answer"),
|
|
// "system": closed by Peppa itself (session stopped/resumed), not by a person.
|
|
answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }),
|
|
telegramMessageId: integer("telegram_message_id"),
|
|
// A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer,
|
|
// so it must not also be typed into the terminal.
|
|
awaitingHook: integer("awaiting_hook", { mode: "boolean" }).notNull().default(false),
|
|
createdAt: createdAt(),
|
|
answeredAt: integer("answered_at", { mode: "timestamp_ms" }),
|
|
});
|
|
|
|
/** Event log: hook / watchdog events, progress reports, status changes. */
|
|
export const events = sqliteTable("events", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
|
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
|
type: text("type").notNull(),
|
|
payload: text("payload", { mode: "json" }),
|
|
createdAt: createdAt(),
|
|
});
|
|
|
|
/** Small key/value store for service state (Telegram offset, pairing, binding). */
|
|
export const settings = sqliteTable("settings", {
|
|
key: text("key").primaryKey(),
|
|
value: text("value", { mode: "json" }).notNull(),
|
|
updatedAt: updatedAt(),
|
|
});
|
|
|
|
/**
|
|
* Durable Telegram outbox: every message/edit is queued here first, then delivered with
|
|
* retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message).
|
|
*/
|
|
export const telegramOutbox = sqliteTable("telegram_outbox", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
dedupeKey: text("dedupe_key").notNull().unique(),
|
|
method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(),
|
|
params: text("params", { mode: "json" }).$type<Record<string, unknown>>().notNull(),
|
|
questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }),
|
|
status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"),
|
|
attempts: integer("attempts").notNull().default(0),
|
|
nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs),
|
|
telegramMessageId: integer("telegram_message_id"),
|
|
error: text("error"),
|
|
createdAt: createdAt(),
|
|
sentAt: integer("sent_at", { mode: "timestamp_ms" }),
|
|
});
|
|
|
|
/** Telegram updates already taken: recorded before acting, so a restart never replays one. */
|
|
export const telegramUpdates = sqliteTable("telegram_updates", {
|
|
updateId: integer("update_id").primaryKey(),
|
|
status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(),
|
|
createdAt: createdAt(),
|
|
});
|
|
|
|
/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */
|
|
export const oauthClients = sqliteTable("oauth_clients", {
|
|
id: text("id").primaryKey(),
|
|
name: text("name").notNull(),
|
|
redirectUris: text("redirect_uris", { mode: "json" }).$type<string[]>().notNull(),
|
|
createdAt: createdAt(),
|
|
});
|
|
|
|
/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */
|
|
export const oauthCodes = sqliteTable("oauth_codes", {
|
|
codeHash: text("code_hash").primaryKey(),
|
|
clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }),
|
|
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
redirectUri: text("redirect_uri").notNull(),
|
|
codeChallenge: text("code_challenge").notNull(),
|
|
scope: text("scope"),
|
|
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
|
|
usedAt: integer("used_at", { mode: "timestamp_ms" }),
|
|
});
|
|
|
|
/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */
|
|
export const oauthTokens = sqliteTable("oauth_tokens", {
|
|
tokenHash: text("token_hash").primaryKey(),
|
|
kind: text("kind", { enum: ["access", "refresh"] }).notNull(),
|
|
clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }),
|
|
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
scope: text("scope"),
|
|
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
|
|
revokedAt: integer("revoked_at", { mode: "timestamp_ms" }),
|
|
createdAt: createdAt(),
|
|
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
|
|
});
|
|
|
|
export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const;
|
|
export type IncidentPolicy = (typeof incidentPolicies)[number];
|
|
|
|
/** Error tracking of a project (PEP-58): webhook secret and how new errors are handled. */
|
|
export const incidentSettings = sqliteTable("incident_settings", {
|
|
projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),
|
|
// Part of the webhook URL Bugsink posts alerts to: /api/hooks/bugsink/<hookSecret>.
|
|
hookSecret: text("hook_secret").notNull().unique(),
|
|
policy: text("policy", { enum: incidentPolicies }).notNull().default("backlog"),
|
|
// The PM's mini-prompt for the triage agent ("how to decide").
|
|
triagePrompt: text("triage_prompt"),
|
|
environments: text("environments", { mode: "json" }).$type<string[]>().notNull().default(["prod", "production"]),
|
|
dailyLimit: integer("daily_limit").notNull().default(5),
|
|
ignorePattern: text("ignore_pattern"),
|
|
goalId: integer("goal_id").references(() => goals.id, { onDelete: "set null" }),
|
|
// False: the alert webhook still has to be added in Bugsink by hand (polling covers it).
|
|
webhookAuto: integer("webhook_auto", { mode: "boolean" }).notNull().default(false),
|
|
createdAt: createdAt(),
|
|
updatedAt: updatedAt(),
|
|
});
|
|
|
|
/** Bugsink projects feeding a Peppa project: one for the frontend, one for the backend. */
|
|
export const errorSources = sqliteTable(
|
|
"error_sources",
|
|
{
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
kind: text("kind", { enum: ["web", "api"] }).notNull(),
|
|
bugsinkProjectId: integer("bugsink_project_id").notNull().unique(),
|
|
dsn: text("dsn").notNull(),
|
|
createdAt: createdAt(),
|
|
},
|
|
(t) => [uniqueIndex("error_sources_project_kind").on(t.projectId, t.kind)],
|
|
);
|
|
|
|
export const incidentStatuses = ["new", "open", "pending", "task", "ignored", "resolved", "regressed"] as const;
|
|
|
|
/** A Bugsink issue seen in Peppa. Repeated events update the same row. */
|
|
export const incidents = sqliteTable("incidents", {
|
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
source: text("source", { enum: ["web", "api"] }).notNull(),
|
|
bugsinkIssueId: text("bugsink_issue_id").notNull().unique(),
|
|
friendlyId: text("friendly_id"),
|
|
title: text("title").notNull(),
|
|
culprit: text("culprit"),
|
|
level: text("level"),
|
|
environment: text("environment"),
|
|
firstRelease: text("first_release"),
|
|
lastRelease: text("last_release"),
|
|
events: integer("events").notNull().default(1),
|
|
firstSeen: integer("first_seen", { mode: "timestamp_ms" }).notNull(),
|
|
lastSeen: integer("last_seen", { mode: "timestamp_ms" }).notNull(),
|
|
url: text("url"),
|
|
stack: text("stack"),
|
|
// new → open | pending | task | ignored; task → resolved → regressed (see design.md)
|
|
status: text("status", { enum: incidentStatuses }).notNull().default("new"),
|
|
decision: text("decision", { enum: ["notify", "backlog", "start", "ask", "ignore"] }),
|
|
decidedBy: text("decided_by", { enum: ["policy", "triage", "pm"] }),
|
|
decisionReason: text("decision_reason"),
|
|
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
|
taskCreatedAt: integer("task_created_at", { mode: "timestamp_ms" }),
|
|
resolvedRelease: text("resolved_release"),
|
|
resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }),
|
|
regressions: integer("regressions").notNull().default(0),
|
|
createdAt: createdAt(),
|
|
updatedAt: updatedAt(),
|
|
});
|
|
|
|
export const projectsRelations = relations(projects, ({ many }) => ({
|
|
goals: many(goals),
|
|
tasks: many(tasks),
|
|
sessions: many(sessions),
|
|
}));
|
|
export const goalsRelations = relations(goals, ({ one, many }) => ({
|
|
project: one(projects, { fields: [goals.projectId], references: [projects.id] }),
|
|
tasks: many(tasks),
|
|
}));
|
|
export const tasksRelations = relations(tasks, ({ one, many }) => ({
|
|
project: one(projects, { fields: [tasks.projectId], references: [projects.id] }),
|
|
goal: one(goals, { fields: [tasks.goalId], references: [goals.id] }),
|
|
sessions: many(sessions),
|
|
questions: many(questions),
|
|
events: many(events),
|
|
}));
|
|
export const sessionsRelations = relations(sessions, ({ one, many }) => ({
|
|
project: one(projects, { fields: [sessions.projectId], references: [projects.id] }),
|
|
task: one(tasks, { fields: [sessions.taskId], references: [tasks.id] }),
|
|
questions: many(questions),
|
|
events: many(events),
|
|
}));
|
|
export const questionsRelations = relations(questions, ({ one }) => ({
|
|
project: one(projects, { fields: [questions.projectId], references: [projects.id] }),
|
|
task: one(tasks, { fields: [questions.taskId], references: [tasks.id] }),
|
|
session: one(sessions, { fields: [questions.sessionId], references: [sessions.id] }),
|
|
}));
|
|
export const eventsRelations = relations(events, ({ one }) => ({
|
|
project: one(projects, { fields: [events.projectId], references: [projects.id] }),
|
|
task: one(tasks, { fields: [events.taskId], references: [tasks.id] }),
|
|
session: one(sessions, { fields: [events.sessionId], references: [sessions.id] }),
|
|
}));
|