peppa/packages/db/src/schema.ts
Асель c7283063c9 PEP-39: rotate a limited session to a free subscription of the pool at the turn boundary
Limit marks the subscription «лимит до …»; the watchdog relaunches the session on another
usable subscription of the same provider (Claude/OpenCode resume the conversation, Codex
starts afresh), threshold banner switches after the turn, max 3 switches/hour, simple
fairness between projects, subscription_switched events + Telegram message, web shows
subscription and switch history. Migration 0004 (sessions.rotate_reason).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:31:22 +05:00

521 lines
26 KiB
TypeScript

import { relations } from "drizzle-orm";
import { sql } from "drizzle-orm";
import { integer, primaryKey, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
// SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is
// text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only.
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" }),
// eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN.
egovIin: text("egov_iin").unique(),
egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }),
// Local login (PEP-68): scrypt hash "scrypt$N$r$p$salt$hash" (core/local-users.ts).
passwordHash: text("password_hash"),
passwordSetAt: integer("password_set_at", { mode: "timestamp_ms" }),
// Disabled by a superadmin: no login, sessions and MCP tokens stop working.
disabledAt: integer("disabled_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
lastLoginAt: integer("last_login_at", { mode: "timestamp_ms" }),
});
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" }),
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"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)],
);
/** 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<string[]>().notNull().default([]),
status: text("status", { enum: ["deploying", "healthy", "rolled_back", "failed", "removed"] }).notNull().default("deploying"),
// "ci" for automatic deploys, the PM's login for prod by the button.
deployedBy: text("deployed_by").notNull().default("ci"),
reason: text("reason"),
runUrl: text("run_url"),
logTail: text("log_tail"),
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<id>/codex); OpenCode: a model provider
* API key in `secret_enc`. Secrets are AES-256-GCM encrypted with PEPPA_SECRET.
*/
export const subscriptions = sqliteTable("subscriptions", {
id: integer("id").primaryKey({ autoIncrement: true }),
provider: text("provider", { enum: agentProviders.enumValues }).notNull(),
name: text("name").notNull(),
authKind: text("auth_kind", { enum: ["oauth", "api_key", "device"] }).notNull(),
secretEnc: text("secret_enc"),
// OpenCode: which model provider the key belongs to (anthropic | openai | openrouter).
keyProvider: text("key_provider"),
status: text("status", { enum: ["pending", "active", "limited", "auth_error"] }).notNull().default("pending"),
limitedUntil: integer("limited_until", { mode: "timestamp_ms" }),
lastError: text("last_error"),
checkedAt: integer("checked_at", { mode: "timestamp_ms" }),
// Became active at least once (a cancelled first login deletes the row).
activatedAt: integer("activated_at", { mode: "timestamp_ms" }),
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
createdAt: createdAt(),
});
/** PEP-67: a named set of subscriptions runners take from (rotation within it — PEP-39). */
export const subscriptionPools = sqliteTable("subscription_pools", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull().unique(),
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
createdAt: createdAt(),
});
export const subscriptionPoolMembers = sqliteTable(
"subscription_pool_members",
{
poolId: integer("pool_id").notNull().references(() => subscriptionPools.id, { onDelete: "cascade" }),
subscriptionId: integer("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }),
},
(t) => [primaryKey({ columns: [t.poolId, t.subscriptionId] })],
);
/** An agent CLI session (Claude Code, Codex or OpenCode) running in tmux on this machine. */
export const sessions = sqliteTable("sessions", {
id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
tmuxName: text("tmux_name").notNull().unique(),
provider: text("provider", { enum: 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"] }),
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" }),
});
/** 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(),
});
/** 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<Record<string, unknown>>().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<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" }),
});
/** 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<ReviewFinding[]>().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>.
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] }),
}));