import { relations } from "drizzle-orm"; import { sql } from "drizzle-orm"; import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; // SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is // text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only. 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" }), // Deprecated (PEP-67): the PEP-13 Claude token moved to `subscriptions`; the migration // copies it there and clears these columns. Not read by the code any more. claudeTokenEnc: text("claude_token_enc"), claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }), // Telegram chat paired from Settings; agent questions of this user's projects go there. telegramChatId: integer("telegram_chat_id").unique(), telegramUserId: integer("telegram_user_id"), telegramUsername: text("telegram_username"), telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }), // PEP-85: the user's own bot (created in BotFather): its token, AES-256-GCM like every secret, // and its @username. Null = the platform's shared bot. telegramBotTokenEnc: text("telegram_bot_token_enc"), telegramBotUsername: text("telegram_bot_username"), // eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN. egovIin: text("egov_iin").unique(), egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }), // Google login (PEP-90): the Google account's stable `sub` (identity) and its verified e-mail (display only). googleSub: text("google_sub").unique(), googleEmail: text("google_email"), googleLinkedAt: integer("google_linked_at", { mode: "timestamp_ms" }), // Local login (PEP-68): scrypt hash "scrypt$N$r$p$salt$hash" (core/local-users.ts). passwordHash: text("password_hash"), passwordSetAt: integer("password_set_at", { mode: "timestamp_ms" }), // Disabled by a superadmin: no login, sessions and MCP tokens stop working. disabledAt: integer("disabled_at", { mode: "timestamp_ms" }), createdAt: createdAt(), lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }), }); 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), // PEP-67: default subscription pool for the project's runners (set by a superadmin). subscriptionPoolId: integer("subscription_pool_id").references((): AnySQLiteColumn => subscriptionPools.id, { onDelete: "set null" }), // PEP-163: deleted by the owner — hidden from users, kept for the superadmin until purged. deletedAt: integer("deleted_at", { mode: "timestamp_ms" }), deletedBy: integer("deleted_by").references((): AnySQLiteColumn => users.id, { onDelete: "set null" }), 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 goalStatus = { enumValues: ["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: goalStatus.enumValues }).notNull().default("open"), createdAt: createdAt(), updatedAt: updatedAt(), }); export const taskStatus = { enumValues: [ "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: 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"), // PEP-57: red CI runs in a row (distinct head SHAs) since the last green one. ciAttempts: integer("ci_attempts").notNull().default(0), ciFailedSha: text("ci_failed_sha"), // PEP-46: the Gitea issue of the project's repo this story came from (or is linked to). giteaIssue: integer("gitea_issue"), // PEP-34: order on the board = priority for the dispatcher (lower first; shared by the project). position: real("position").notNull().default(0), // PEP-34: archived stories are hidden from the board, the dispatcher and epic progress. archivedAt: integer("archived_at", { mode: "timestamp_ms" }), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue)], ); /** PEP-42: "task waits for blocked_by" — a story is blocked until its predecessors reach review/done. */ export const taskDeps = sqliteTable( "task_deps", { taskId: integer("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }), blockedById: integer("blocked_by_id").notNull().references(() => tasks.id, { onDelete: "cascade" }), createdAt: createdAt(), }, (t) => [primaryKey({ columns: [t.taskId, t.blockedById] }), index("task_deps_blocked_by").on(t.blockedById)], ); /** PEP-57: one deployment of a project to an environment (and its outcome). */ 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(), previousSha: text("previous_sha"), image: text("image"), host: text("host"), prNumber: integer("pr_number"), // Task keys in the release ("PAY-7"), from the merged commits. tasks: 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"), reason: text("reason"), runUrl: text("run_url"), logTail: text("log_tail"), // PEP-44: screenshots of a preview taken by the CI step (files under $PEPPA_HOME/screenshots). screenshots: text("screenshots", { mode: "json" }).$type>().notNull().default([]), createdAt: createdAt(), updatedAt: updatedAt(), }); /** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */ export const checkRuns = sqliteTable( "check_runs", { 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(), branch: text("branch"), prNumber: integer("pr_number"), check: text("check").notNull(), state: text("state", { enum: ["pending", "success", "failure", "error"] }).notNull(), runUrl: text("run_url"), logTail: text("log_tail"), durationSec: integer("duration_sec"), // "report" — the CI step itself (with the log), "poll" — commit status read by the watchdog. source: text("source", { enum: ["report", "poll"] }).notNull().default("report"), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)], ); export const sessionStatus = { enumValues: [ "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 }; export const agentProviders = { enumValues: ["claude", "codex", "opencode"] as const }; /** * PEP-67: an agent subscription (Claude Code / Codex / OpenCode) managed by superadmins. * Claude: OAuth token from `claude setup-token` in `secret_enc`; Codex: the login lives in * its own CODEX_HOME ($PEPPA_HOME/subscriptions/s/codex); OpenCode: a model provider * API key in `secret_enc`. Secrets are AES-256-GCM encrypted with PEPPA_SECRET. */ export const subscriptions = sqliteTable("subscriptions", { id: integer("id").primaryKey({ autoIncrement: true }), provider: text("provider", { enum: agentProviders.enumValues }).notNull(), name: text("name").notNull(), authKind: text("auth_kind", { enum: ["oauth", "api_key", "device"] }).notNull(), secretEnc: text("secret_enc"), // OpenCode: which model provider the key belongs to (anthropic | openai | openrouter). keyProvider: text("key_provider"), status: text("status", { enum: ["pending", "active", "limited", "auth_error"] }).notNull().default("pending"), limitedUntil: integer("limited_until", { mode: "timestamp_ms" }), lastError: text("last_error"), checkedAt: integer("checked_at", { mode: "timestamp_ms" }), // Became active at least once (a cancelled first login deletes the row). activatedAt: integer("activated_at", { mode: "timestamp_ms" }), createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), createdAt: createdAt(), }); /** PEP-67: a named set of subscriptions runners take from (rotation within it — PEP-39). */ export const subscriptionPools = sqliteTable("subscription_pools", { id: integer("id").primaryKey({ autoIncrement: true }), name: text("name").notNull().unique(), createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), createdAt: createdAt(), }); export const subscriptionPoolMembers = sqliteTable( "subscription_pool_members", { poolId: integer("pool_id").notNull().references(() => subscriptionPools.id, { onDelete: "cascade" }), subscriptionId: integer("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }), }, (t) => [primaryKey({ columns: [t.poolId, t.subscriptionId] })], ); /** An agent CLI session (Claude Code, Codex or OpenCode) running in tmux on this machine. */ /** * PEP-40: a server runners run on. Peppa reaches it over SSH with its own key; tmux and the * agent's container live there (PEP-17). No daemon on the host. */ // PEP-75: the platform's team of agent personas — a name on the board and a character // (markdown) appended to the agent's prompt. A runner takes a free persona for its story. export const agents = sqliteTable("agents", { id: integer("id").primaryKey({ autoIncrement: true }), name: text("name").notNull().unique(), character: text("character").notNull().default(""), disabledAt: integer("disabled_at", { mode: "timestamp_ms" }), createdAt: createdAt(), }); export const runnerHosts = sqliteTable("runner_hosts", { id: integer("id").primaryKey({ autoIncrement: true }), name: text("name").notNull().unique(), sshTarget: text("ssh_target").notNull(), sshPort: integer("ssh_port").notNull().default(22), // Base directory on the host: ws/ (clones), runs/ (launch dirs), home/ (agent homes). workdir: text("workdir").notNull().default("peppa"), // Where the agent relay (/api/agent/*) is reached from the host; null = PEPPA_WEB_URL. peppaUrl: text("peppa_url"), status: text("status", { enum: ["unknown", "online", "offline"] }).notNull().default("unknown"), info: text("info", { mode: "json" }).$type(), lastSeenAt: integer("last_seen_at", { mode: "timestamp_ms" }), lastError: text("last_error"), disabledAt: integer("disabled_at", { mode: "timestamp_ms" }), createdAt: createdAt(), }); export interface RunnerHostInfo { os?: string; docker?: string; tmux?: string; cpus?: number; load?: number; image?: string | null; checkedAt?: number; } 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: agentProviders.enumValues }).notNull().default("claude"), // PEP-67: the subscription the session runs on (null = this machine's own login). subscriptionId: integer("subscription_id").references(() => subscriptions.id, { onDelete: "set null" }), // Claude session id or Codex thread id — the resume target. conversationId: text("claude_session_id"), // Bumped on every launch/resume; hooks from an older generation are ignored. 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" }), // PEP-39: switch to another subscription of the pool at the turn boundary ("limit" | "threshold"). rotateReason: text("rotate_reason", { enum: ["limit", "threshold"] }), // PEP-10/53: the runner's name (PM renames it; free runners get one at launch). name: text("name"), // PEP-27: the runner's own git worktree (null = the project's working copy). workspacePath: text("workspace_path"), // PEP-40: the host the runner lives on (null = Peppa's own machine). hostId: integer("host_id").references(() => runnerHosts.id, { onDelete: "set null" }), // PEP-17: the agent's docker container (null = the agent runs directly in tmux). container: text("container"), // PEP-75: the persona working in this runner (kept across resumes and across runners of a story). agentId: integer("agent_id").references(() => agents.id, { onDelete: "set null" }), // PEP-5: tokens (per conversation, from the transcript), cost (per generation, from the // statusLine), context window — see core/usage.ts. usage: text("usage", { mode: "json" }).$type(), // PEP-28: what the watchdog remembers about the runner (screen hash, alerts, restarts) — // survives its restart (core/sessions.ts WatchState). watchState: text("watch_state", { mode: "json" }).$type(), status: text("status", { enum: sessionStatus.enumValues }).notNull().default("starting"), lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }), startedAt: createdAt(), endedAt: integer("ended_at", { mode: "timestamp_ms" }), }); /** * PEP-10: stories of a runner — its history (`active` → `done`) and queue (`queued`, by id; * `front` items go first). The runner's current story is also `sessions.task_id`. */ export const runnerTasks = sqliteTable( "runner_tasks", { id: integer("id").primaryKey({ autoIncrement: true }), sessionId: integer("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }), taskId: integer("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }), status: text("status", { enum: ["queued", "active", "done"] }).notNull(), // Extra instructions for the agent when the story is taken (a PM comment, a CI failure). prompt: text("prompt"), front: integer("front", { mode: "boolean" }).notNull().default(false), queuedAt: createdAt(), startedAt: integer("started_at", { mode: "timestamp_ms" }), endedAt: integer("ended_at", { mode: "timestamp_ms" }), }, (t) => [index("runner_tasks_session_idx").on(t.sessionId, t.status)], ); /** 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(), // PEP-149: what the message is for the person — decides where it shows up (core/questions.ts). // null: a message of the factory itself (failures, limits, releases) and rows before PEP-149. msgType: text("msg_type", { enum: ["question", "done", "progress", "blocker"] }), // PEP-149: the option the agent goes on with while nobody answered (one of `options`). defaultOption: text("default_option"), 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), // PEP-28: reminders sent about it while unanswered (1, 2 = reminders; 3 = escalated to admins). reminders: integer("reminders").notNull().default(0), createdAt: createdAt(), answeredAt: integer("answered_at", { mode: "timestamp_ms" }), }); /** PEP-28: the watchdog's memory of a runner (sessions.watch_state). */ export type WatchState = { /** sha1 of the last seen screen. */ screen?: string; /** Generation whose limit banner was already handled / threshold warning already seen. */ limitGen?: number; /** PEP-166: limit banners already on screen when this generation started (a resumed conversation shows its history). */ limitBaseGen?: number; limitBase?: number; thresholdGen?: number; /** Times (ms) of automatic restarts — the limit counts those inside the window. */ restarts?: number[]; /** A planned automatic restart (ms) and why ("crash" | "gone" | "stall"). */ restartAt?: number; restartReason?: string; /** When the stall alert went out (ms). */ stallAlertAt?: number; }; /** * PEP-21: commands for the runner service (the watchdog process). Web, bot and the remote * MCP enqueue; the service claims (`queued` → `running`) and runs them; a client that gave * up marks a still-queued command `expired`, so it never runs late. */ export const runnerCommands = sqliteTable( "runner_commands", { id: integer("id").primaryKey({ autoIncrement: true }), kind: text("kind").notNull(), payload: text("payload", { mode: "json" }).$type>().notNull(), // Commands with the same key run one after another (task: / session:); null = at once. key: text("key"), status: text("status", { enum: ["queued", "running", "done", "failed", "expired"] }).notNull().default("queued"), result: text("result", { mode: "json" }).$type(), error: text("error"), // PeppaError (shown to the user as is) or an internal failure. errorKind: text("error_kind", { enum: ["peppa", "internal"] }), // Who asked (PEP-48 actor) — the service runs the command as them. actor: text("actor", { mode: "json" }).$type>(), // A runner machine for the command (several runner hosts later); null = any. host: text("host"), createdAt: createdAt(), startedAt: integer("started_at", { mode: "timestamp_ms" }), finishedAt: integer("finished_at", { mode: "timestamp_ms" }), }, (t) => [index("runner_commands_status_idx").on(t.status, t.id)], ); export type UsageTokens = { input: number; output: number; cacheRead: number; cacheWrite: number }; /** PEP-5: what a session spent (core/usage.ts). */ export type SessionUsage = { /** Tokens per Claude conversation, summed from the transcript (resume continues the same file). */ convs?: Record; /** statusLine `cost.total_cost_usd` per runner generation (the counter restarts with the process). */ costByGen?: Record; /** statusLine token totals per generation — fallback when there is no transcript. */ tokensByGen?: Record; context?: { used: number; size: number; pct: number }; model?: string; at?: number; }; export const actorKinds = ["user", "agent", "system"] as const; export const actorChannels = ["web", "telegram", "mcp", "cli", "terminal", "hook", "watchdog", "gitea"] as const; /** 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" }), // PEP-48: who did it (core/actor.ts). Null on events older than PEP-48. actorKind: text("actor_kind", { enum: actorKinds }), actorUserId: integer("actor_user_id").references(() => users.id, { onDelete: "set null" }), actorChannel: text("actor_channel", { enum: actorChannels }), actorClientId: text("actor_client_id"), createdAt: createdAt(), }, (t) => [index("events_created_at").on(t.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(), // PEP-143: `sendPhoto` uploads a local file (`params.photo_path`) — screenshots of a feedback. method: text("method", { enum: ["sendMessage", "editMessageText", "sendPhoto"] }).notNull(), params: text("params", { mode: "json" }).$type>().notNull(), questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }), // PEP-62: the chat message mirrored into a linked Telegram group (finds the thread of a reply). chatMessageId: integer("chat_message_id").references((): AnySQLiteColumn => chatMessages.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" }), }); /** PEP-62: a chat — one per project (a channel with threads) and one per user (the master chat). */ export const chats = sqliteTable("chats", { id: integer("id").primaryKey({ autoIncrement: true }), kind: text("kind", { enum: ["master", "project"] }).notNull(), userId: integer("user_id").unique().references(() => users.id, { onDelete: "cascade" }), projectId: integer("project_id").unique().references(() => projects.id, { onDelete: "cascade" }), // Linked Telegram group: messages are mirrored there, replies come back (one group — one chat). tgChatId: integer("tg_chat_id").unique(), tgTitle: text("tg_title"), tgLinkedAt: integer("tg_linked_at", { mode: "timestamp_ms" }), tgLinkedBy: integer("tg_linked_by").references(() => users.id, { onDelete: "set null" }), // PEP-109: the owner of the bot the group is linked through (null — the platform's shared bot). tgBotUserId: integer("tg_bot_user_id").references(() => users.id, { onDelete: "set null" }), createdAt: createdAt(), }); /** * PEP-62: a chat message, kept for PEPPA_CHAT_TTL_DAYS only. A thread is `thread_key` * (task: / incident: / release:; null = the channel); events, questions, * releases and incidents are projected here and stay in their own tables. */ export const chatMessages = sqliteTable( "chat_messages", { id: integer("id").primaryKey({ autoIncrement: true }), chatId: integer("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }), threadKey: text("thread_key"), threadTitle: text("thread_title"), kind: text("kind", { enum: ["event", "question", "user", "system"] }).notNull(), // Shown in the master chats of the project's people. important: integer("important", { mode: "boolean" }).notNull().default(false), authorKind: text("author_kind", { enum: ["system", "agent", "user"] }).notNull().default("system"), authorUserId: integer("author_user_id").references(() => users.id, { onDelete: "set null" }), authorLogin: text("author_login"), via: text("via", { enum: ["web", "telegram"] }), text: text("text").notNull(), questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), url: text("url"), dedupeKey: text("dedupe_key").unique(), // Came from a Telegram group: a reply to this message finds its thread. tgChatId: integer("tg_chat_id"), tgMessageId: integer("tg_message_id"), createdAt: createdAt(), }, (t) => [index("chat_messages_chat").on(t.chatId, t.id), index("chat_messages_created_at").on(t.createdAt), index("chat_messages_tg").on(t.tgChatId, t.tgMessageId)], ); /** 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(), }); /** PEP-55: a browser's Web Push subscription (PushSubscription.toJSON()). */ export const pushSubscriptions = sqliteTable("push_subscriptions", { id: integer("id").primaryKey({ autoIncrement: true }), userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), endpoint: text("endpoint").notNull().unique(), p256dh: text("p256dh").notNull(), auth: text("auth").notNull(), userAgent: text("user_agent"), createdAt: createdAt(), lastOkAt: integer("last_ok_at", { mode: "timestamp_ms" }), }); /** PEP-55: durable Web Push outbox, delivered by the bot with retries (like telegram_outbox). */ export const pushOutbox = sqliteTable("push_outbox", { id: integer("id").primaryKey({ autoIncrement: true }), dedupeKey: text("dedupe_key").notNull().unique(), subscriptionId: integer("subscription_id").references(() => pushSubscriptions.id, { onDelete: "set null" }), payload: text("payload", { mode: "json" }).$type>().notNull(), urgency: text("urgency", { enum: ["normal", "high"] }).notNull().default("normal"), 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), error: text("error"), createdAt: createdAt(), sentAt: integer("sent_at", { mode: "timestamp_ms" }), }); /** 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" }), }); /** * PEP-54: a project's secret for its agents (env name → AES-256-GCM value with PEPPA_SECRET). * The value is never shown after saving; the runner hands it to agent sessions as env. */ export const projectSecrets = sqliteTable( "project_secrets", { id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), name: text("name").notNull(), valueEnc: text("value_enc").notNull(), createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), updatedBy: integer("updated_by").references(() => users.id, { onDelete: "set null" }), createdAt: createdAt(), updatedAt: updatedAt(), // Last time a session got it in its env. lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), }, (t) => [uniqueIndex("project_secrets_project_name").on(t.projectId, t.name)], ); /** PEP-26: the reviewer agent of a project (no row = off). */ export const reviewSettings = sqliteTable("review_settings", { projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }), enabled: integer("enabled", { mode: "boolean" }).notNull().default(false), // Times the reviewer may send a story back before it goes to the PM as is. maxIterations: integer("max_iterations").notNull().default(2), // Extra rules of the PM for the reviewer, appended to the checklist. rules: text("rules"), updatedAt: updatedAt(), }); export type ReviewFinding = { file?: string; line?: number; severity?: string; text: string }; /** PEP-26: one review of a story's PR head by the reviewer agent. */ export const codeReviews = sqliteTable("code_reviews", { id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), taskId: integer("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }), prNumber: integer("pr_number").notNull(), sha: text("sha").notNull(), state: text("state", { enum: ["queued", "running", "done", "error"] }).notNull().default("queued"), verdict: text("verdict", { enum: ["ok", "changes"] }), summary: text("summary"), findings: text("findings", { mode: "json" }).$type().notNull().default([]), error: text("error"), startedAt: integer("started_at", { mode: "timestamp_ms" }), createdAt: createdAt(), updatedAt: updatedAt(), }); 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 feedbackStatuses = ["received", "analyzed", "planned", "fixed", "rejected"] as const; /** PEP-143: what the page knew when the user reported a problem. */ export interface FeedbackContext { url?: string; projectKey?: string; taskKey?: string; mode?: string; locale?: string; userAgent?: string; viewport?: string; /** Last browser errors of that page (ErrorReporter). */ errors?: Array<{ type: string; message: string; at?: string }>; } export interface FeedbackScreenshot { file: string; mime: string; size: number; } export interface FeedbackOption { title: string; what: string; pros: string; cons: string; size: "S" | "M" | "L"; } /** PEP-143: the feedback agent's reading of a report. */ export interface FeedbackAnalysis { summary: string; kind: "bug" | "wish" | "question"; cause: string; /** false — the agent says it is not sure. */ confident: boolean; options: FeedbackOption[]; /** 1-based index into `options`; null — no recommendation. */ recommended: number | null; /** Key of an existing story this report repeats. */ duplicateOf: string | null; } /** * PEP-143: a user's report about a problem in Peppa itself (text + screenshots), the feedback * agent's analysis and the superadmin's decision. received → analyzed → planned → fixed | rejected. */ export const feedback = sqliteTable( "feedback", { id: integer("id").primaryKey({ autoIncrement: true }), userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), via: text("via", { enum: ["web", "telegram"] }).notNull(), text: text("text").notNull(), context: text("context", { mode: "json" }).$type().notNull().default({}), // Files in $PEPPA_HOME/feedback// under names of our own. screenshots: text("screenshots", { mode: "json" }).$type().notNull().default([]), status: text("status", { enum: feedbackStatuses }).notNull().default("received"), analysis: text("analysis", { mode: "json" }).$type(), // Why there is no analysis (the agent failed, is off) — said to the superadmin once. analysisError: text("analysis_error"), analysisStartedAt: integer("analysis_started_at", { mode: "timestamp_ms" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), // Which option of the analysis became the story (1-based); null — linked to an existing one. optionIndex: integer("option_index"), rejectReason: text("reject_reason"), decidedBy: integer("decided_by").references(() => users.id, { onDelete: "set null" }), decidedAt: integer("decided_at", { mode: "timestamp_ms" }), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [index("feedback_user").on(t.userId, t.createdAt), index("feedback_status").on(t.status)], ); /** * PEP-159: a file attached to a chat message, a story comment or a story. Uploaded first * (task/message/event empty, `user_id` = uploader), linked when the form is sent. Bytes live in * `$PEPPA_HOME/files///` under a name of our own; `name` is for display only. */ export const attachments = sqliteTable( "attachments", { id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), userId: integer("user_id").references(() => users.id, { onDelete: "set null" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), chatMessageId: integer("chat_message_id").references((): AnySQLiteColumn => chatMessages.id, { onDelete: "set null" }), // The story comment (an `events` row). eventId: integer("event_id").references(() => events.id, { onDelete: "set null" }), name: text("name").notNull(), // Name on disk inside the attachment's directory. file: text("file").notNull(), mime: text("mime").notNull(), size: integer("size").notNull(), createdAt: createdAt(), }, (t) => [index("attachments_task").on(t.taskId), index("attachments_message").on(t.chatMessageId), index("attachments_event").on(t.eventId), index("attachments_project").on(t.projectId)], ); 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] }), }));