Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history

schema.ts

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

schema.tsBlame4213 lines · 3 contributors
fc1817aClaude1import {
2 pgTable,
3 text,
4 timestamp,
5 uuid,
6 boolean,
7 integer,
8 uniqueIndex,
79136bbClaude9 index,
10 serial,
abfa9adClaude11 bigint,
12 jsonb,
5ca514aClaude13 numeric,
abfa9adClaude14 customType,
fc1817aClaude15} from "drizzle-orm/pg-core";
16
abfa9adClaude17// Postgres `bytea` — drizzle-orm doesn't ship a first-class bytea column, so
18// we declare one via customType that maps to Buffer on both read and write.
19// Used by `workflow_run_cache.content` where we really do need raw bytes
20// (unlike `workflow_artifacts.content`, which stayed base64-text for v1).
21const bytea = customType<{ data: Buffer; default: false }>({
22 dataType() {
23 return "bytea";
24 },
25});
26
a686079Claude27// pgvector `vector(N)` — drizzle-orm has no first-class pgvector column.
28// We map it to `number[]` and serialise/deserialise via Postgres's
29// canonical text format `[0.1,0.2,...]`. The `default: false` flag tells
30// drizzle this column has no default value.
31//
32// Migration 0057 creates the column with `vector(1024)`. If the migration
33// degraded (pgvector unavailable on the host), the column is missing and
34// every read/write throws; src/lib/semantic-index.ts catches at the
35// boundary and falls back to empty-result behaviour.
36const vector = customType<{ data: number[]; driverData: string; default: false }>({
37 dataType(config: unknown) {
38 const cfg = config as { dimensions?: number } | undefined;
39 return cfg?.dimensions ? `vector(${cfg.dimensions})` : "vector";
40 },
41 toDriver(value: number[]): string {
42 return "[" + value.join(",") + "]";
43 },
44 fromDriver(value: string | number[]): number[] {
45 if (Array.isArray(value)) return value as number[];
46 // Canonical format: "[0.1,0.2,0.3]"
47 const trimmed = String(value).trim();
48 if (!trimmed) return [];
49 const inner = trimmed.startsWith("[") && trimmed.endsWith("]")
50 ? trimmed.slice(1, -1)
51 : trimmed;
52 if (!inner) return [];
53 return inner.split(",").map((s) => parseFloat(s));
54 },
55});
56
fc1817aClaude57export const users = pgTable("users", {
58 id: uuid("id").primaryKey().defaultRandom(),
59 username: text("username").notNull().unique(),
60 email: text("email").notNull().unique(),
61 displayName: text("display_name"),
62 passwordHash: text("password_hash").notNull(),
63 avatarUrl: text("avatar_url"),
64 bio: text("bio"),
24cf2caClaude65 // Email notification preferences (Block A8). Default on; opt-out via /settings.
66 notifyEmailOnMention: boolean("notify_email_on_mention").default(true).notNull(),
67 notifyEmailOnAssign: boolean("notify_email_on_assign").default(true).notNull(),
68 notifyEmailOnGateFail: boolean("notify_email_on_gate_fail").default(true).notNull(),
08420cdClaude69 // Block I7 — weekly digest opt-in.
70 notifyEmailDigestWeekly: boolean("notify_email_digest_weekly").default(false).notNull(),
cb5a796Claude71 // Drizzle/0066 — Pending comment moderation requests. Defaults ON so
72 // a new repo owner is alerted as soon as the first comment lands in
73 // the queue. The in-app notification is always written regardless;
74 // this controls fan-out (currently the audit/notification surface,
75 // future email).
76 notifyEmailOnPendingComment: boolean("notify_email_on_pending_comment")
77 .default(true)
78 .notNull(),
08420cdClaude79 lastDigestSentAt: timestamp("last_digest_sent_at"),
46d6165Claude80 // Block L1 — Sleep Mode. When enabled, the autopilot sleep-mode-digest
81 // task delivers a daily "what Claude shipped overnight" report at the
e1fc7dbClaude82 // user-configured UTC hour (0-23, default 9). Uses its own independent
83 // cooldown anchor (lastSleepDigestSentAt) so the weekly digest timer is
84 // not reset when a sleep-mode digest fires, and vice versa.
85 // Migration 0077 adds the column.
86 lastSleepDigestSentAt: timestamp("last_sleep_digest_sent_at"),
46d6165Claude87 sleepModeEnabled: boolean("sleep_mode_enabled").default(false).notNull(),
88 sleepModeDigestHourUtc: integer("sleep_mode_digest_hour_utc").default(9).notNull(),
534f04aClaude89 // Block M2 — Web Push per-event preferences. Default on; opt-out via /settings.
90 notifyPushOnMention: boolean("notify_push_on_mention").default(true).notNull(),
91 notifyPushOnAssign: boolean("notify_push_on_assign").default(true).notNull(),
92 notifyPushOnReviewRequest: boolean("notify_push_on_review_request")
93 .default(true)
94 .notNull(),
95 notifyPushOnDeployFailed: boolean("notify_push_on_deploy_failed")
96 .default(true)
97 .notNull(),
a4f3e24Claude98 isAdmin: boolean("is_admin").default(false).notNull(),
c63b860Claude99 // Block P2 — set when the user clicks the verification link. Soft-gate
100 // only: registration succeeds regardless; /dashboard surfaces a banner
101 // until this is non-null.
102 emailVerifiedAt: timestamp("email_verified_at"),
103 // Block P5 — Account deletion with 30-day grace period.
104 // See drizzle/0049_account_deletion.sql.
105 deletedAt: timestamp("deleted_at"),
106 deletionScheduledFor: timestamp("deletion_scheduled_for"),
107 // Block P3 — Terms of Service / Privacy Policy acceptance audit trail.
108 // Set on /register when the user ticks the accept_terms checkbox.
109 // termsVersion bumps when Terms change; UI prompts re-acceptance later.
110 termsAcceptedAt: timestamp("terms_accepted_at"),
111 termsVersion: text("terms_version"),
cd4f63bTest User112 // Block Q3 — Anonymous playground accounts. When `isPlayground=true`, the
113 // account was minted by /play with a synthetic email + random password
114 // and is hard-deleted by the autopilot `playground-purge` task once
115 // `playgroundExpiresAt` passes. Real accounts always carry false/null.
116 // See drizzle/0052_playground_accounts.sql.
117 isPlayground: boolean("is_playground").default(false).notNull(),
118 playgroundExpiresAt: timestamp("playground_expires_at"),
ee7e577Claude119 // Migration 0071 — Personal cross-repo semantic index opt-in. When true,
120 // /chat (and the /api/v2/me/chat/messages endpoint) may search across
121 // every repo the user owns OR is an accepted collaborator on. Default
122 // OFF — privacy-first; the user must explicitly enable it via
123 // /settings/personal-semantic-toggle. The personal-semantic helpers
124 // hard-refuse to return any rows while this flag is false.
125 personalSemanticIndexEnabled: boolean("personal_semantic_index_enabled")
126 .default(false)
127 .notNull(),
b12f20dClaude128 // Onboarding drip sequence (migration 0081). Stores a JSON array of string
f65f600Claude129 // keys for emails already delivered, e.g. ["welcome","day1","day3"].
130 // The autopilot `onboarding-drip` task compares this against the canonical
131 // drip schedule and sends any outstanding emails. Never null — defaults to
132 // an empty array at insert time.
133 onboardingEmailsSent: jsonb("onboarding_emails_sent").$type<string[]>().default([]).notNull(),
fc1817aClaude134 createdAt: timestamp("created_at").defaultNow().notNull(),
135 updatedAt: timestamp("updated_at").defaultNow().notNull(),
136});
137
06d5ffeClaude138export const sessions = pgTable("sessions", {
139 id: uuid("id").primaryKey().defaultRandom(),
140 userId: uuid("user_id")
141 .notNull()
142 .references(() => users.id, { onDelete: "cascade" }),
143 token: text("token").notNull().unique(),
144 expiresAt: timestamp("expires_at").notNull(),
7298a17Claude145 // B4: true when the user has entered their password but not yet their TOTP
146 // code. softAuth/requireAuth treat such sessions as anonymous; only
147 // /login/2fa can consume them. Flips to false on successful 2FA.
148 requires2fa: boolean("requires_2fa").default(false).notNull(),
ba9e143Claude149 // Migration 0077 — SOC 2 session visibility. Populated at login and
150 // refreshed on each authenticated request (best-effort, non-blocking).
151 ip: text("ip"),
152 userAgent: text("user_agent"),
153 lastSeenAt: timestamp("last_seen_at"),
06d5ffeClaude154 createdAt: timestamp("created_at").defaultNow().notNull(),
155});
156
ba9e143Claude157/**
158 * Login attempt log — SOC 2 CC6.1 account-lockout evidence.
159 * Records every login attempt (success or failure) per email + IP.
160 * After 10 failures within 1 hour the login handler blocks the email
161 * for 15 minutes and emits `auth.login.locked` to the audit log.
162 * Migration 0078.
163 */
164export const loginAttempts = pgTable(
165 "login_attempts",
166 {
167 id: uuid("id").primaryKey().defaultRandom(),
168 email: text("email").notNull(),
169 ip: text("ip").notNull(),
170 success: boolean("success").notNull().default(false),
171 createdAt: timestamp("created_at").defaultNow().notNull(),
172 },
173 (table) => [
174 index("login_attempts_email_created").on(table.email, table.createdAt),
175 index("login_attempts_ip_created").on(table.ip, table.createdAt),
176 ]
177);
178
179export type LoginAttempt = typeof loginAttempts.$inferSelect;
180
45e31d0Claude181// @ts-ignore — self-referential FK on forkedFromId causes circular inference
fc1817aClaude182export const repositories = pgTable(
183 "repositories",
184 {
185 id: uuid("id").primaryKey().defaultRandom(),
186 name: text("name").notNull(),
7437605Claude187 // ownerId = creator / user-owner. Always set (for attribution + user
188 // namespace uniqueness). For org-owned repos, also represents "created by".
fc1817aClaude189 ownerId: uuid("owner_id")
190 .notNull()
191 .references(() => users.id),
7437605Claude192 // Block B2: nullable org owner. When set, the repo lives in the org
193 // namespace and URL resolution routes `/:orgSlug/:repo` to it.
194 orgId: uuid("org_id"),
fc1817aClaude195 description: text("description"),
196 isPrivate: boolean("is_private").default(false).notNull(),
3ef4c9dClaude197 isArchived: boolean("is_archived").default(false).notNull(),
71cd5ecClaude198 isTemplate: boolean("is_template").default(false).notNull(),
fc1817aClaude199 defaultBranch: text("default_branch").default("main").notNull(),
200 diskPath: text("disk_path").notNull(),
45e31d0Claude201 forkedFromId: uuid("forked_from_id"),
fc1817aClaude202 createdAt: timestamp("created_at").defaultNow().notNull(),
203 updatedAt: timestamp("updated_at").defaultNow().notNull(),
204 pushedAt: timestamp("pushed_at"),
205 starCount: integer("star_count").default(0).notNull(),
206 forkCount: integer("fork_count").default(0).notNull(),
79136bbClaude207 issueCount: integer("issue_count").default(0).notNull(),
534f04aClaude208 // Block M5: autopilot stale-sweep opt-out flags. Default true — the
209 // 2-stage close (poke at 7d/30d, close at 14d/60d after poke) runs on
210 // every repo unless an owner disables it via repo-settings.
211 autoCloseStalePrs: boolean("auto_close_stale_prs").default(true).notNull(),
212 autoCloseStaleIssues: boolean("auto_close_stale_issues")
213 .default(true)
214 .notNull(),
4bbacbeClaude215 // Migration 0062 — opt-out flag for per-branch preview URLs. Default on;
216 // owners can disable via repo-settings. When false, post-receive skips
217 // the enqueuePreviewBuild call entirely.
218 previewBuildsEnabled: boolean("preview_builds_enabled")
219 .default(true)
220 .notNull(),
0c3eee5Claude221 // Migration 0065 — opt-in flag for the AI test generator autopilot task.
222 // Default false (off) because writing tests against unreviewed code can
223 // produce noise; owners must explicitly enable it via repo-settings.
224 autoGenerateTests: boolean("auto_generate_tests")
225 .default(false)
226 .notNull(),
79ed944Claude227 // Migration 0067 — opt-in flag for auto-provisioning a runnable PR
228 // sandbox on every PR open. Default false (off) because each sandbox
229 // burns compute; owners must explicitly enable it via repo-settings.
230 autoPrSandbox: boolean("auto_pr_sandbox").default(false).notNull(),
9b3a183Claude231 // Migration 0072 — opt-in flag for hosted-in-browser dev environments
232 // (cloud Codespaces alternative). Default false (off) because each
233 // env burns a container until the idle sweep tears it down; owners
234 // must explicitly enable per-repo via repo-settings.
235 devEnvsEnabled: boolean("dev_envs_enabled").default(false).notNull(),
44f1a02Claude236 // Migration 0077 — data residency region. 'us' = US East (default),
237 // 'eu' = Frankfurt (EU). EU data residency requires a Pro plan or
238 // higher. Future values (e.g. 'apac') are additive — no constraint
239 // at the DB level so we can extend without a new migration.
240 dataRegion: text("data_region").default("us").notNull(),
fc1817aClaude241 },
7437605Claude242 (table) => [
243 // Partial: uniqueness only in the user namespace (org-owned rows exempt).
244 // Matches the partial index in migration 0004.
245 uniqueIndex("repos_owner_name").on(table.ownerId, table.name),
246 index("repos_org").on(table.orgId),
247 ]
fc1817aClaude248);
249
3ef4c9dClaude250/**
251 * Per-repository gate + auto-repair configuration.
252 * Every new repo is created with all gates ENABLED by default —
253 * the "full green ecosystem" default. Owners can manually opt-out per setting.
254 */
255export const repoSettings = pgTable("repo_settings", {
256 id: uuid("id").primaryKey().defaultRandom(),
257 repositoryId: uuid("repository_id")
258 .notNull()
259 .unique()
260 .references(() => repositories.id, { onDelete: "cascade" }),
261 // Gates
262 gateTestEnabled: boolean("gate_test_enabled").default(true).notNull(),
263 aiReviewEnabled: boolean("ai_review_enabled").default(true).notNull(),
264 secretScanEnabled: boolean("secret_scan_enabled").default(true).notNull(),
265 securityScanEnabled: boolean("security_scan_enabled").default(true).notNull(),
266 dependencyScanEnabled: boolean("dependency_scan_enabled").default(true).notNull(),
267 lintEnabled: boolean("lint_enabled").default(true).notNull(),
268 typeCheckEnabled: boolean("type_check_enabled").default(true).notNull(),
269 testEnabled: boolean("test_enabled").default(true).notNull(),
270 // Auto-repair
271 autoFixEnabled: boolean("auto_fix_enabled").default(true).notNull(),
272 autoMergeResolveEnabled: boolean("auto_merge_resolve_enabled").default(true).notNull(),
273 autoFormatEnabled: boolean("auto_format_enabled").default(true).notNull(),
274 // AI features
275 aiCommitMessagesEnabled: boolean("ai_commit_messages_enabled").default(true).notNull(),
276 aiPrSummaryEnabled: boolean("ai_pr_summary_enabled").default(true).notNull(),
277 aiChangelogEnabled: boolean("ai_changelog_enabled").default(true).notNull(),
278 // Deploy
279 autoDeployEnabled: boolean("auto_deploy_enabled").default(true).notNull(),
280 deployRequireAllGreen: boolean("deploy_require_all_green").default(true).notNull(),
281 createdAt: timestamp("created_at").defaultNow().notNull(),
282 updatedAt: timestamp("updated_at").defaultNow().notNull(),
283});
284
285/**
286 * Branch protection rules — enforced on push and merge.
287 * Every repo's default branch gets a protection rule on creation.
288 */
289export const branchProtection = pgTable(
290 "branch_protection",
291 {
292 id: uuid("id").primaryKey().defaultRandom(),
293 repositoryId: uuid("repository_id")
294 .notNull()
295 .references(() => repositories.id, { onDelete: "cascade" }),
296 pattern: text("pattern").notNull(), // branch name or glob (e.g. "main", "release/*")
297 requirePullRequest: boolean("require_pull_request").default(true).notNull(),
298 requireGreenGates: boolean("require_green_gates").default(true).notNull(),
299 requireAiApproval: boolean("require_ai_approval").default(true).notNull(),
300 requireHumanReview: boolean("require_human_review").default(false).notNull(),
301 requiredApprovals: integer("required_approvals").default(0).notNull(),
302 allowForcePush: boolean("allow_force_push").default(false).notNull(),
303 allowDeletion: boolean("allow_deletion").default(false).notNull(),
304 dismissStaleReviews: boolean("dismiss_stale_reviews").default(true).notNull(),
4626e61Claude305 // K2 — Auto-merge opt-in. When true, the autopilot ticker may auto-merge
306 // a PR whose base branch matches this rule, provided every gate the
307 // manual-merge path enforces is green. Default-deny.
308 enableAutoMerge: boolean("enable_auto_merge").default(false).notNull(),
3ef4c9dClaude309 createdAt: timestamp("created_at").defaultNow().notNull(),
310 updatedAt: timestamp("updated_at").defaultNow().notNull(),
311 },
312 (table) => [
313 uniqueIndex("branch_protection_repo_pattern").on(
314 table.repositoryId,
315 table.pattern
316 ),
317 ]
318);
319
320/**
321 * Gate run history. Every push + every PR creates gate_runs entries —
322 * one per configured gate. Serves as the source of truth for "is this green?".
323 */
324export const gateRuns = pgTable(
325 "gate_runs",
326 {
327 id: uuid("id").primaryKey().defaultRandom(),
328 repositoryId: uuid("repository_id")
329 .notNull()
330 .references(() => repositories.id, { onDelete: "cascade" }),
331 pullRequestId: uuid("pull_request_id").references(() => pullRequests.id, {
332 onDelete: "cascade",
333 }),
334 commitSha: text("commit_sha").notNull(),
335 ref: text("ref").notNull(),
336 gateName: text("gate_name").notNull(), // e.g. "GateTest", "AI Review", "Secret Scan", "Type Check"
337 status: text("status").notNull(), // pending, running, passed, failed, skipped, repaired
338 summary: text("summary"),
339 details: text("details"), // JSON: per-check output, affected files, etc
340 repairAttempted: boolean("repair_attempted").default(false).notNull(),
341 repairSucceeded: boolean("repair_succeeded").default(false).notNull(),
342 repairCommitSha: text("repair_commit_sha"),
343 durationMs: integer("duration_ms"),
344 createdAt: timestamp("created_at").defaultNow().notNull(),
345 completedAt: timestamp("completed_at"),
346 },
347 (table) => [
348 index("gate_runs_repo_sha").on(table.repositoryId, table.commitSha),
349 index("gate_runs_pr").on(table.pullRequestId),
350 index("gate_runs_created").on(table.createdAt),
351 ]
352);
353
354/**
355 * In-app notifications. Powered by the activity feed + explicit mentions.
356 */
357export const notifications = pgTable(
358 "notifications",
359 {
360 id: uuid("id").primaryKey().defaultRandom(),
361 userId: uuid("user_id")
362 .notNull()
363 .references(() => users.id, { onDelete: "cascade" }),
364 repositoryId: uuid("repository_id").references(() => repositories.id, {
365 onDelete: "cascade",
366 }),
367 kind: text("kind").notNull(), // mention, review_requested, pr_merged, pr_closed, gate_failed, gate_repaired, ai_review, assigned, security_alert, deploy_success, deploy_failed
368 title: text("title").notNull(),
369 body: text("body"),
370 url: text("url"), // link to the relevant page
371 readAt: timestamp("read_at"),
372 createdAt: timestamp("created_at").defaultNow().notNull(),
373 },
374 (table) => [
375 index("notifications_user_unread").on(table.userId, table.readAt),
376 index("notifications_user_created").on(table.userId, table.createdAt),
377 ]
378);
379
380/**
381 * Releases — named snapshots of a repo at a tag/commit.
382 * AI-generated changelogs bundled in notes field.
383 */
384export const releases = pgTable(
385 "releases",
386 {
387 id: uuid("id").primaryKey().defaultRandom(),
388 repositoryId: uuid("repository_id")
389 .notNull()
390 .references(() => repositories.id, { onDelete: "cascade" }),
391 authorId: uuid("author_id")
392 .notNull()
393 .references(() => users.id),
394 tag: text("tag").notNull(),
395 name: text("name").notNull(),
396 body: text("body"), // AI-generated release notes + changelog
397 targetCommit: text("target_commit").notNull(),
398 isDraft: boolean("is_draft").default(false).notNull(),
399 isPrerelease: boolean("is_prerelease").default(false).notNull(),
400 createdAt: timestamp("created_at").defaultNow().notNull(),
401 publishedAt: timestamp("published_at"),
402 },
403 (table) => [
404 uniqueIndex("releases_repo_tag").on(table.repositoryId, table.tag),
405 ]
406);
407
408/**
409 * Milestones — group issues + PRs toward a shared goal.
410 */
411export const milestones = pgTable(
412 "milestones",
413 {
414 id: uuid("id").primaryKey().defaultRandom(),
415 repositoryId: uuid("repository_id")
416 .notNull()
417 .references(() => repositories.id, { onDelete: "cascade" }),
418 title: text("title").notNull(),
419 description: text("description"),
420 state: text("state").notNull().default("open"), // open, closed
421 dueDate: timestamp("due_date"),
422 createdAt: timestamp("created_at").defaultNow().notNull(),
423 closedAt: timestamp("closed_at"),
424 },
425 (table) => [index("milestones_repo_state").on(table.repositoryId, table.state)]
426);
427
428/**
429 * Reactions on issues, PRs, and comments. Universal target pointer.
430 */
431export const reactions = pgTable(
432 "reactions",
433 {
434 id: uuid("id").primaryKey().defaultRandom(),
435 userId: uuid("user_id")
436 .notNull()
437 .references(() => users.id, { onDelete: "cascade" }),
438 targetType: text("target_type").notNull(), // issue, pr, issue_comment, pr_comment
439 targetId: uuid("target_id").notNull(),
440 emoji: text("emoji").notNull(), // thumbs_up, thumbs_down, rocket, heart, eyes, laugh, hooray, confused
441 createdAt: timestamp("created_at").defaultNow().notNull(),
442 },
443 (table) => [
444 uniqueIndex("reactions_unique").on(
445 table.userId,
446 table.targetType,
447 table.targetId,
448 table.emoji
449 ),
450 index("reactions_target").on(table.targetType, table.targetId),
451 ]
452);
453
454/**
455 * PR reviews (formal approve/request-changes).
456 * Separate from inline comments in pr_comments.
457 */
458export const prReviews = pgTable(
459 "pr_reviews",
460 {
461 id: uuid("id").primaryKey().defaultRandom(),
462 pullRequestId: uuid("pull_request_id")
463 .notNull()
464 .references(() => pullRequests.id, { onDelete: "cascade" }),
465 reviewerId: uuid("reviewer_id")
466 .notNull()
467 .references(() => users.id),
468 state: text("state").notNull(), // approved, changes_requested, commented
469 body: text("body"),
470 isAi: boolean("is_ai").default(false).notNull(),
471 createdAt: timestamp("created_at").defaultNow().notNull(),
472 },
473 (table) => [index("pr_reviews_pr").on(table.pullRequestId)]
474);
475
476/**
477 * Code owners — who owns which paths (auto-request review on PR).
478 * Parsed from a CODEOWNERS file at the root of the default branch.
479 */
480export const codeOwners = pgTable(
481 "code_owners",
482 {
483 id: uuid("id").primaryKey().defaultRandom(),
484 repositoryId: uuid("repository_id")
485 .notNull()
486 .references(() => repositories.id, { onDelete: "cascade" }),
487 pathPattern: text("path_pattern").notNull(),
488 ownerUsernames: text("owner_usernames").notNull(), // comma-separated
489 createdAt: timestamp("created_at").defaultNow().notNull(),
490 },
491 (table) => [index("code_owners_repo").on(table.repositoryId)]
492);
493
494/**
495 * Per-repo AI chat sessions — conversational repo assistant.
496 */
497export const aiChats = pgTable(
498 "ai_chats",
499 {
500 id: uuid("id").primaryKey().defaultRandom(),
501 userId: uuid("user_id")
502 .notNull()
503 .references(() => users.id, { onDelete: "cascade" }),
504 repositoryId: uuid("repository_id").references(() => repositories.id, {
505 onDelete: "cascade",
506 }),
507 title: text("title"),
508 messages: text("messages").notNull().default("[]"), // JSON array of {role, content}
509 createdAt: timestamp("created_at").defaultNow().notNull(),
510 updatedAt: timestamp("updated_at").defaultNow().notNull(),
511 },
512 (table) => [
513 index("ai_chats_user").on(table.userId),
514 index("ai_chats_repo").on(table.repositoryId),
515 ]
516);
517
518/**
519 * Audit log — every sensitive action. Who did what, when, from where.
520 */
521export const auditLog = pgTable(
522 "audit_log",
523 {
524 id: uuid("id").primaryKey().defaultRandom(),
525 userId: uuid("user_id").references(() => users.id, { onDelete: "set null" }),
526 repositoryId: uuid("repository_id").references(() => repositories.id, {
527 onDelete: "set null",
528 }),
529 action: text("action").notNull(), // repo.create, repo.delete, repo.transfer, token.create, token.revoke, merge, force_push, branch_protection.update, deploy, ...
530 targetType: text("target_type"),
531 targetId: text("target_id"),
532 ip: text("ip"),
533 userAgent: text("user_agent"),
534 metadata: text("metadata"), // JSON for extra context
535 createdAt: timestamp("created_at").defaultNow().notNull(),
536 },
537 (table) => [
538 index("audit_log_user").on(table.userId),
539 index("audit_log_repo").on(table.repositoryId),
540 index("audit_log_created").on(table.createdAt),
541 ]
542);
543
544/**
545 * Deployments — tracks every deploy to downstream systems (Crontech, etc).
546 * Each deploy is gated on ALL green gates passing.
547 */
548export const deployments = pgTable(
549 "deployments",
550 {
551 id: uuid("id").primaryKey().defaultRandom(),
552 repositoryId: uuid("repository_id")
553 .notNull()
554 .references(() => repositories.id, { onDelete: "cascade" }),
555 environment: text("environment").notNull().default("production"),
556 commitSha: text("commit_sha").notNull(),
557 ref: text("ref").notNull(),
a76d984Claude558 status: text("status").notNull(), // pending, running, success, failed, blocked, waiting_timer
3ef4c9dClaude559 blockedReason: text("blocked_reason"),
560 target: text("target"), // e.g. "crontech", "fly.io"
561 triggeredBy: uuid("triggered_by").references(() => users.id),
a76d984Claude562 /**
563 * Set when an approved deploy is held by `environments.wait_timer_minutes`.
564 * NULL = no wait; non-null = autopilot flips status from "waiting_timer"
565 * to "pending" once `now() >= ready_after`.
566 */
567 readyAfter: timestamp("ready_after"),
3ef4c9dClaude568 createdAt: timestamp("created_at").defaultNow().notNull(),
569 completedAt: timestamp("completed_at"),
570 },
571 (table) => [
572 index("deployments_repo").on(table.repositoryId),
573 index("deployments_created").on(table.createdAt),
574 ]
575);
576
577/**
578 * Rate-limit buckets — in-memory or persisted counter per IP / token / route.
579 */
580export const rateLimitBuckets = pgTable(
581 "rate_limit_buckets",
582 {
583 id: uuid("id").primaryKey().defaultRandom(),
584 bucketKey: text("bucket_key").notNull().unique(), // "ip:1.2.3.4:api" or "token:abc:api"
585 count: integer("count").default(0).notNull(),
586 windowStart: timestamp("window_start").defaultNow().notNull(),
587 expiresAt: timestamp("expires_at").notNull(),
588 },
589 (table) => [index("rate_limit_expires").on(table.expiresAt)]
fc1817aClaude590);
591
06d5ffeClaude592export const stars = pgTable(
593 "stars",
594 {
595 id: uuid("id").primaryKey().defaultRandom(),
596 userId: uuid("user_id")
597 .notNull()
598 .references(() => users.id, { onDelete: "cascade" }),
599 repositoryId: uuid("repository_id")
600 .notNull()
601 .references(() => repositories.id, { onDelete: "cascade" }),
602 createdAt: timestamp("created_at").defaultNow().notNull(),
603 },
79136bbClaude604 (table) => [
605 uniqueIndex("stars_user_repo").on(table.userId, table.repositoryId),
606 ]
607);
608
609export const issues = pgTable(
610 "issues",
611 {
612 id: uuid("id").primaryKey().defaultRandom(),
613 number: serial("number"),
614 repositoryId: uuid("repository_id")
615 .notNull()
616 .references(() => repositories.id, { onDelete: "cascade" }),
617 authorId: uuid("author_id")
618 .notNull()
619 .references(() => users.id),
620 title: text("title").notNull(),
621 body: text("body"),
622 state: text("state").notNull().default("open"), // open, closed
623 createdAt: timestamp("created_at").defaultNow().notNull(),
624 updatedAt: timestamp("updated_at").defaultNow().notNull(),
625 closedAt: timestamp("closed_at"),
626 },
627 (table) => [
628 index("issues_repo_state").on(table.repositoryId, table.state),
629 index("issues_repo_number").on(table.repositoryId, table.number),
630 ]
631);
632
633export const issueComments = pgTable(
634 "issue_comments",
635 {
636 id: uuid("id").primaryKey().defaultRandom(),
637 issueId: uuid("issue_id")
638 .notNull()
639 .references(() => issues.id, { onDelete: "cascade" }),
640 authorId: uuid("author_id")
641 .notNull()
642 .references(() => users.id),
643 body: text("body").notNull(),
cb5a796Claude644 // Comment moderation (drizzle/0066). 'approved' | 'pending' | 'rejected'
645 // | 'spam'. Default 'approved' keeps every legacy + collaborator path
646 // unchanged; the gate in `lib/comment-moderation.ts` only routes new
647 // non-collaborator comments into 'pending'.
648 moderationStatus: text("moderation_status").notNull().default("approved"),
649 moderatedAt: timestamp("moderated_at", { withTimezone: true }),
650 moderatedByUserId: uuid("moderated_by_user_id").references(() => users.id, {
651 onDelete: "set null",
652 }),
79136bbClaude653 createdAt: timestamp("created_at").defaultNow().notNull(),
654 updatedAt: timestamp("updated_at").defaultNow().notNull(),
655 },
656 (table) => [index("comments_issue").on(table.issueId)]
657);
658
659export const labels = pgTable(
660 "labels",
661 {
662 id: uuid("id").primaryKey().defaultRandom(),
663 repositoryId: uuid("repository_id")
664 .notNull()
665 .references(() => repositories.id, { onDelete: "cascade" }),
666 name: text("name").notNull(),
667 color: text("color").notNull().default("#8b949e"),
668 description: text("description"),
669 },
670 (table) => [
671 uniqueIndex("labels_repo_name").on(table.repositoryId, table.name),
672 ]
673);
674
675export const issueLabels = pgTable(
676 "issue_labels",
677 {
678 id: uuid("id").primaryKey().defaultRandom(),
679 issueId: uuid("issue_id")
680 .notNull()
681 .references(() => issues.id, { onDelete: "cascade" }),
682 labelId: uuid("label_id")
683 .notNull()
684 .references(() => labels.id, { onDelete: "cascade" }),
685 },
686 (table) => [
687 uniqueIndex("issue_labels_unique").on(table.issueId, table.labelId),
688 ]
06d5ffeClaude689);
690
0074234Claude691export const pullRequests = pgTable(
692 "pull_requests",
693 {
694 id: uuid("id").primaryKey().defaultRandom(),
695 number: serial("number"),
696 repositoryId: uuid("repository_id")
697 .notNull()
698 .references(() => repositories.id, { onDelete: "cascade" }),
699 authorId: uuid("author_id")
700 .notNull()
701 .references(() => users.id),
702 title: text("title").notNull(),
703 body: text("body"),
704 state: text("state").notNull().default("open"), // open, closed, merged
705 baseBranch: text("base_branch").notNull(),
706 headBranch: text("head_branch").notNull(),
3ef4c9dClaude707 isDraft: boolean("is_draft").default(false).notNull(),
708 mergeStrategy: text("merge_strategy").default("merge").notNull(), // merge, squash, rebase
709 milestoneId: uuid("milestone_id"),
0074234Claude710 mergedAt: timestamp("merged_at"),
711 mergedBy: uuid("merged_by").references(() => users.id),
712 createdAt: timestamp("created_at").defaultNow().notNull(),
713 updatedAt: timestamp("updated_at").defaultNow().notNull(),
714 closedAt: timestamp("closed_at"),
715 },
716 (table) => [
717 index("prs_repo_state").on(table.repositoryId, table.state),
718 index("prs_repo_number").on(table.repositoryId, table.number),
719 ]
720);
721
722export const prComments = pgTable(
723 "pr_comments",
724 {
725 id: uuid("id").primaryKey().defaultRandom(),
726 pullRequestId: uuid("pull_request_id")
727 .notNull()
728 .references(() => pullRequests.id, { onDelete: "cascade" }),
729 authorId: uuid("author_id")
730 .notNull()
731 .references(() => users.id),
732 body: text("body").notNull(),
733 isAiReview: boolean("is_ai_review").default(false).notNull(),
734 filePath: text("file_path"),
735 lineNumber: integer("line_number"),
cb5a796Claude736 // Comment moderation (drizzle/0066). See `issueComments.moderationStatus`.
737 moderationStatus: text("moderation_status").notNull().default("approved"),
738 moderatedAt: timestamp("moderated_at", { withTimezone: true }),
739 moderatedByUserId: uuid("moderated_by_user_id").references(() => users.id, {
740 onDelete: "set null",
741 }),
0074234Claude742 createdAt: timestamp("created_at").defaultNow().notNull(),
743 updatedAt: timestamp("updated_at").defaultNow().notNull(),
744 },
745 (table) => [index("pr_comments_pr").on(table.pullRequestId)]
746);
747
cb5a796Claude748/**
749 * Comment moderation (drizzle/0066) — per-repo allow/deny list for
750 * commenters. A 'trusted' row makes `shouldRequireApproval` short-circuit
751 * to false; a 'banned' row makes it short-circuit to "auto-reject without
752 * notifying the owner" so a single spam decision sticks.
753 *
754 * Indexed by (repository_id, commenter_user_id) for the per-comment gate
755 * lookup and by (repository_id, status) for the owner's trust-list page.
756 */
757export const repoCommenterTrust = pgTable(
758 "repo_commenter_trust",
759 {
760 id: uuid("id").primaryKey().defaultRandom(),
761 repositoryId: uuid("repository_id")
762 .notNull()
763 .references(() => repositories.id, { onDelete: "cascade" }),
764 commenterUserId: uuid("commenter_user_id")
765 .notNull()
766 .references(() => users.id, { onDelete: "cascade" }),
767 status: text("status").notNull(), // 'trusted' | 'banned'
768 grantedByUserId: uuid("granted_by_user_id").references(() => users.id, {
769 onDelete: "set null",
770 }),
771 grantedAt: timestamp("granted_at", { withTimezone: true })
772 .defaultNow()
773 .notNull(),
774 },
775 (table) => [
776 uniqueIndex("repo_commenter_trust_unique").on(
777 table.repositoryId,
778 table.commenterUserId
779 ),
780 index("repo_commenter_trust_repo_status").on(
781 table.repositoryId,
782 table.status
783 ),
784 ]
785);
786
0074234Claude787export const activityFeed = pgTable(
788 "activity_feed",
789 {
790 id: uuid("id").primaryKey().defaultRandom(),
791 repositoryId: uuid("repository_id")
792 .notNull()
793 .references(() => repositories.id, { onDelete: "cascade" }),
794 userId: uuid("user_id").references(() => users.id),
795 action: text("action").notNull(), // push, issue_open, issue_close, pr_open, pr_merge, star, comment
796 targetType: text("target_type"), // issue, pr, commit
797 targetId: text("target_id"),
798 metadata: text("metadata"), // JSON string for extra data
799 createdAt: timestamp("created_at").defaultNow().notNull(),
800 },
801 (table) => [
802 index("activity_repo").on(table.repositoryId),
803 index("activity_user").on(table.userId),
804 ]
805);
806
c81ab7aClaude807export const webhooks = pgTable(
808 "webhooks",
809 {
810 id: uuid("id").primaryKey().defaultRandom(),
811 repositoryId: uuid("repository_id")
812 .notNull()
813 .references(() => repositories.id, { onDelete: "cascade" }),
814 url: text("url").notNull(),
815 secret: text("secret"),
816 events: text("events").notNull().default("push"), // comma-separated: push,issue,pr
817 isActive: boolean("is_active").default(true).notNull(),
818 lastDeliveredAt: timestamp("last_delivered_at"),
819 lastStatus: integer("last_status"),
820 createdAt: timestamp("created_at").defaultNow().notNull(),
821 },
822 (table) => [index("webhooks_repo").on(table.repositoryId)]
823);
824
8405c43Claude825// Reliable webhook delivery (migration 0056). One row per (hook, event)
826// emission. Worker in src/lib/webhook-delivery.ts polls pending rows whose
827// next_attempt_at <= now() and retries with exponential backoff.
828export const webhookDeliveries = pgTable(
829 "webhook_deliveries",
830 {
831 id: uuid("id").primaryKey().defaultRandom(),
832 webhookId: uuid("webhook_id")
833 .notNull()
834 .references(() => webhooks.id, { onDelete: "cascade" }),
835 event: text("event").notNull(),
836 payload: text("payload").notNull(),
837 signature: text("signature").notNull(),
838 attemptCount: integer("attempt_count").default(0).notNull(),
839 nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }),
840 status: text("status").default("pending").notNull(), // pending | succeeded | failed | dead
841 lastStatusCode: integer("last_status_code"),
842 lastError: text("last_error"),
843 lastAttemptedAt: timestamp("last_attempted_at", { withTimezone: true }),
844 succeededAt: timestamp("succeeded_at", { withTimezone: true }),
845 createdAt: timestamp("created_at", { withTimezone: true })
846 .defaultNow()
847 .notNull(),
848 },
849 (table) => [
850 index("idx_webhook_deliveries_next_attempt").on(table.nextAttemptAt),
851 index("idx_webhook_deliveries_webhook_id").on(
852 table.webhookId,
853 table.createdAt
854 ),
855 ]
856);
857
c81ab7aClaude858export const apiTokens = pgTable("api_tokens", {
859 id: uuid("id").primaryKey().defaultRandom(),
860 userId: uuid("user_id")
861 .notNull()
862 .references(() => users.id, { onDelete: "cascade" }),
863 name: text("name").notNull(),
864 tokenHash: text("token_hash").notNull(),
865 tokenPrefix: text("token_prefix").notNull(), // first 8 chars for display
866 scopes: text("scopes").notNull().default("repo"), // comma-separated
867 lastUsedAt: timestamp("last_used_at"),
868 expiresAt: timestamp("expires_at"),
869 createdAt: timestamp("created_at").defaultNow().notNull(),
870});
871
872export const repoTopics = pgTable(
873 "repo_topics",
874 {
875 id: uuid("id").primaryKey().defaultRandom(),
876 repositoryId: uuid("repository_id")
877 .notNull()
878 .references(() => repositories.id, { onDelete: "cascade" }),
879 topic: text("topic").notNull(),
880 },
881 (table) => [
882 uniqueIndex("repo_topics_unique").on(table.repositoryId, table.topic),
883 index("topics_name").on(table.topic),
884 ]
885);
886
fc1817aClaude887export const sshKeys = pgTable("ssh_keys", {
888 id: uuid("id").primaryKey().defaultRandom(),
889 userId: uuid("user_id")
890 .notNull()
06d5ffeClaude891 .references(() => users.id, { onDelete: "cascade" }),
fc1817aClaude892 title: text("title").notNull(),
893 fingerprint: text("fingerprint").notNull(),
894 publicKey: text("public_key").notNull(),
895 lastUsedAt: timestamp("last_used_at"),
896 createdAt: timestamp("created_at").defaultNow().notNull(),
897});
898
845fd8aClaude899// OCI Container Registry — migration 0083_oci_registry.sql
900// oci_repositories tracks image namespaces (e.g. "alice/myapp").
901// oci_tags maps mutable tag names to a manifest digest for a repository.
902
903export const ociRepositories = pgTable(
904 "oci_repositories",
905 {
906 id: uuid("id").primaryKey().defaultRandom(),
907 ownerId: uuid("owner_id")
908 .notNull()
909 .references(() => users.id, { onDelete: "cascade" }),
910 /** Full image name in "<owner>/<image>" format. */
911 name: text("name").notNull(),
912 visibility: text("visibility").notNull().default("private"), // "public" | "private"
913 createdAt: timestamp("created_at").defaultNow().notNull(),
914 },
915 (table) => [
916 uniqueIndex("oci_repositories_owner_name").on(table.ownerId, table.name),
917 index("idx_oci_repositories_owner").on(table.ownerId),
918 ]
919);
920
921export const ociTags = pgTable(
922 "oci_tags",
923 {
924 id: uuid("id").primaryKey().defaultRandom(),
925 repositoryId: uuid("repository_id")
926 .notNull()
927 .references(() => ociRepositories.id, { onDelete: "cascade" }),
928 tag: text("tag").notNull(),
929 manifestDigest: text("manifest_digest").notNull(), // "sha256:<hex64>"
930 createdAt: timestamp("created_at").defaultNow().notNull(),
931 updatedAt: timestamp("updated_at").defaultNow().notNull(),
932 },
933 (table) => [
934 uniqueIndex("oci_tags_repo_tag").on(table.repositoryId, table.tag),
935 index("idx_oci_tags_repo").on(table.repositoryId),
936 ]
937);
938
939export type OciRepository = typeof ociRepositories.$inferSelect;
940export type NewOciRepository = typeof ociRepositories.$inferInsert;
941export type OciTag = typeof ociTags.$inferSelect;
942export type NewOciTag = typeof ociTags.$inferInsert;
943
534f04aClaude944// Block M2 — Web Push subscriptions. One row per (user, endpoint).
945// Endpoint is the browser-issued push URL; p256dh + auth are the W3C
946// payload-encryption keys (base64url). Stale endpoints (HTTP 410) are
947// deleted lazily on next `sendPushToUser` pass.
948export const pushSubscriptions = pgTable(
949 "push_subscriptions",
950 {
951 id: uuid("id").primaryKey().defaultRandom(),
952 userId: uuid("user_id")
953 .notNull()
954 .references(() => users.id, { onDelete: "cascade" }),
955 endpoint: text("endpoint").notNull(),
956 p256dh: text("p256dh").notNull(),
957 auth: text("auth").notNull(),
958 userAgent: text("user_agent"),
959 createdAt: timestamp("created_at").defaultNow().notNull(),
960 lastUsedAt: timestamp("last_used_at"),
961 },
962 (table) => [
963 uniqueIndex("push_subscriptions_user_endpoint").on(
964 table.userId,
965 table.endpoint
966 ),
967 index("idx_push_subscriptions_user").on(table.userId),
968 ]
969);
970
fc1817aClaude971export type User = typeof users.$inferSelect;
972export type NewUser = typeof users.$inferInsert;
973export type Repository = typeof repositories.$inferSelect;
974export type NewRepository = typeof repositories.$inferInsert;
06d5ffeClaude975export type Session = typeof sessions.$inferSelect;
976export type Star = typeof stars.$inferSelect;
977export type SshKey = typeof sshKeys.$inferSelect;
534f04aClaude978export type PushSubscription = typeof pushSubscriptions.$inferSelect;
979export type NewPushSubscription = typeof pushSubscriptions.$inferInsert;
79136bbClaude980export type Issue = typeof issues.$inferSelect;
981export type IssueComment = typeof issueComments.$inferSelect;
982export type Label = typeof labels.$inferSelect;
0074234Claude983export type PullRequest = typeof pullRequests.$inferSelect;
984export type PrComment = typeof prComments.$inferSelect;
cb5a796Claude985export type RepoCommenterTrust = typeof repoCommenterTrust.$inferSelect;
986export type NewRepoCommenterTrust = typeof repoCommenterTrust.$inferInsert;
0074234Claude987export type ActivityEntry = typeof activityFeed.$inferSelect;
c81ab7aClaude988export type Webhook = typeof webhooks.$inferSelect;
989export type ApiToken = typeof apiTokens.$inferSelect;
990export type RepoTopic = typeof repoTopics.$inferSelect;
3ef4c9dClaude991export type RepoSettings = typeof repoSettings.$inferSelect;
992export type BranchProtection = typeof branchProtection.$inferSelect;
993export type GateRun = typeof gateRuns.$inferSelect;
994export type Notification = typeof notifications.$inferSelect;
995export type Release = typeof releases.$inferSelect;
996export type Milestone = typeof milestones.$inferSelect;
997export type Reaction = typeof reactions.$inferSelect;
998export type PrReview = typeof prReviews.$inferSelect;
999export type CodeOwner = typeof codeOwners.$inferSelect;
1000export type AiChat = typeof aiChats.$inferSelect;
1001export type AuditLogEntry = typeof auditLog.$inferSelect;
1002export type Deployment = typeof deployments.$inferSelect;
24cf2caClaude1003
1004/**
1005 * Saved replies — per-user canned responses, insertable into any
1006 * issue / PR comment textarea. Shortcut name must be unique per user.
1007 */
1008export const savedReplies = pgTable(
1009 "saved_replies",
1010 {
1011 id: uuid("id").primaryKey().defaultRandom(),
1012 userId: uuid("user_id")
1013 .notNull()
1014 .references(() => users.id, { onDelete: "cascade" }),
1015 shortcut: text("shortcut").notNull(),
1016 body: text("body").notNull(),
1017 createdAt: timestamp("created_at").defaultNow().notNull(),
1018 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1019 },
1020 (table) => [
1021 uniqueIndex("saved_replies_user_shortcut").on(table.userId, table.shortcut),
1022 ]
1023);
1024
1025export type SavedReply = typeof savedReplies.$inferSelect;
5cc5d95Claude1026
1027/**
1028 * Organizations (Block B1) — multi-user namespaces. Distinct from `users`.
1029 * An org has members (with org-level roles) and may contain teams.
1030 * Repos can be owned by an org via `repositories.orgId` (added in Block B2).
1031 *
1032 * Slug is globally unique against itself; collision with a username is
1033 * checked at create time in the route handler (no DB-level cross-table
1034 * uniqueness in Postgres).
1035 */
1036export const organizations = pgTable("organizations", {
1037 id: uuid("id").primaryKey().defaultRandom(),
1038 slug: text("slug").notNull().unique(),
1039 name: text("name").notNull(),
1040 description: text("description"),
1041 avatarUrl: text("avatar_url"),
1042 billingEmail: text("billing_email"),
1043 createdById: uuid("created_by_id")
1044 .notNull()
1045 .references(() => users.id, { onDelete: "restrict" }),
1046 createdAt: timestamp("created_at").defaultNow().notNull(),
1047 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1048});
1049
1050/**
1051 * Org membership. Roles: owner (full control, billing), admin (manage
1052 * members + teams + repos), member (default; can be added to teams).
1053 */
1054export const orgMembers = pgTable(
1055 "org_members",
1056 {
1057 id: uuid("id").primaryKey().defaultRandom(),
1058 orgId: uuid("org_id")
1059 .notNull()
1060 .references(() => organizations.id, { onDelete: "cascade" }),
1061 userId: uuid("user_id")
1062 .notNull()
1063 .references(() => users.id, { onDelete: "cascade" }),
1064 role: text("role").notNull().default("member"), // owner | admin | member
1065 createdAt: timestamp("created_at").defaultNow().notNull(),
1066 },
1067 (table) => [
1068 uniqueIndex("org_members_unique").on(table.orgId, table.userId),
1069 index("org_members_user").on(table.userId),
1070 ]
1071);
1072
1073/**
1074 * Teams within an org. Slug is unique within an org.
1075 * `parentTeamId` allows nesting (GitHub-style child teams). Optional.
1076 */
1077export const teams = pgTable(
1078 "teams",
1079 {
1080 id: uuid("id").primaryKey().defaultRandom(),
1081 orgId: uuid("org_id")
1082 .notNull()
1083 .references(() => organizations.id, { onDelete: "cascade" }),
1084 slug: text("slug").notNull(),
1085 name: text("name").notNull(),
1086 description: text("description"),
1087 parentTeamId: uuid("parent_team_id"),
1088 createdAt: timestamp("created_at").defaultNow().notNull(),
1089 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1090 },
1091 (table) => [uniqueIndex("teams_org_slug").on(table.orgId, table.slug)]
1092);
1093
1094/**
1095 * Team membership. Roles: maintainer (can edit team), member (default).
1096 * A user can belong to many teams; team membership requires org membership
1097 * but that invariant is enforced at the route layer, not the DB layer.
1098 */
1099export const teamMembers = pgTable(
1100 "team_members",
1101 {
1102 id: uuid("id").primaryKey().defaultRandom(),
1103 teamId: uuid("team_id")
1104 .notNull()
1105 .references(() => teams.id, { onDelete: "cascade" }),
1106 userId: uuid("user_id")
1107 .notNull()
1108 .references(() => users.id, { onDelete: "cascade" }),
1109 role: text("role").notNull().default("member"), // maintainer | member
1110 createdAt: timestamp("created_at").defaultNow().notNull(),
1111 },
1112 (table) => [
1113 uniqueIndex("team_members_unique").on(table.teamId, table.userId),
1114 index("team_members_user").on(table.userId),
1115 ]
1116);
1117
1118export type Organization = typeof organizations.$inferSelect;
1119export type OrgMember = typeof orgMembers.$inferSelect;
1120export type Team = typeof teams.$inferSelect;
1121export type TeamMember = typeof teamMembers.$inferSelect;
1122export type OrgRole = "owner" | "admin" | "member";
1123export type TeamRole = "maintainer" | "member";
7298a17Claude1124
1125/**
1126 * 2FA / TOTP (Block B4).
1127 *
1128 * Secret is stored in plain Base32 for now — the DB has row-level-secure
1129 * access and the app boundary is the only code that reads it. A follow-up
1130 * (B4.1) will wrap it with AES-GCM at rest once we standardise the KEK.
1131 *
1132 * `enabledAt` is set only after the user has successfully entered their
1133 * first code (confirming the authenticator was set up correctly). Rows with
1134 * `enabledAt = NULL` represent pending enrolment.
1135 */
1136export const userTotp = pgTable("user_totp", {
1137 userId: uuid("user_id")
1138 .primaryKey()
1139 .references(() => users.id, { onDelete: "cascade" }),
1140 secret: text("secret").notNull(),
1141 enabledAt: timestamp("enabled_at"),
1142 lastUsedAt: timestamp("last_used_at"),
1143 createdAt: timestamp("created_at").defaultNow().notNull(),
1144});
1145
1146/**
1147 * Recovery codes — single-use fallback when the authenticator is lost.
1148 * Stored as SHA-256 hashes; used rows are marked with `usedAt` rather than
1149 * deleted so the audit log keeps the full history.
1150 */
1151export const userRecoveryCodes = pgTable(
1152 "user_recovery_codes",
1153 {
1154 id: uuid("id").primaryKey().defaultRandom(),
1155 userId: uuid("user_id")
1156 .notNull()
1157 .references(() => users.id, { onDelete: "cascade" }),
1158 codeHash: text("code_hash").notNull(),
1159 usedAt: timestamp("used_at"),
1160 createdAt: timestamp("created_at").defaultNow().notNull(),
1161 },
1162 (table) => [
1163 index("recovery_codes_user").on(table.userId),
1164 uniqueIndex("recovery_codes_user_hash").on(table.userId, table.codeHash),
1165 ]
1166);
1167
1168export type UserTotp = typeof userTotp.$inferSelect;
1169export type UserRecoveryCode = typeof userRecoveryCodes.$inferSelect;
2df1f8cClaude1170
1171/**
1172 * WebAuthn passkeys (Block B5).
1173 *
1174 * Each row is one registered authenticator. The `credentialId` is the
1175 * globally-unique identifier the browser returns; `publicKey` is the
1176 * COSE-encoded public key we use to verify signatures. `counter` tracks
1177 * the authenticator's signature counter for replay-protection.
1178 *
1179 * `transports` is a JSON array (stored as text) of the
1180 * AuthenticatorTransport values ("usb" | "nfc" | "ble" | "internal" | "hybrid").
1181 */
1182export const userPasskeys = pgTable(
1183 "user_passkeys",
1184 {
1185 id: uuid("id").primaryKey().defaultRandom(),
1186 userId: uuid("user_id")
1187 .notNull()
1188 .references(() => users.id, { onDelete: "cascade" }),
1189 credentialId: text("credential_id").notNull().unique(),
1190 publicKey: text("public_key").notNull(), // base64url of COSE key
1191 counter: integer("counter").default(0).notNull(),
1192 transports: text("transports"), // JSON array string
1193 name: text("name").notNull().default("Passkey"),
1194 lastUsedAt: timestamp("last_used_at"),
1195 createdAt: timestamp("created_at").defaultNow().notNull(),
1196 },
1197 (table) => [index("passkeys_user").on(table.userId)]
1198);
1199
1200/**
1201 * Short-lived WebAuthn challenges. A row is written when we issue options
1202 * (registration or authentication) and deleted after the verify step or when
1203 * it expires (5 min). Keeping them in the DB lets us verify without sticky
1204 * sessions or client-side state.
1205 */
1206export const webauthnChallenges = pgTable(
1207 "webauthn_challenges",
1208 {
1209 id: uuid("id").primaryKey().defaultRandom(),
1210 userId: uuid("user_id").references(() => users.id, { onDelete: "cascade" }),
1211 // For passwordless login we don't know the user yet, so userId is nullable
1212 // and we bind the challenge to a short-lived cookie token instead.
1213 sessionKey: text("session_key").notNull().unique(),
1214 challenge: text("challenge").notNull(),
1215 kind: text("kind").notNull(), // "register" | "authenticate"
1216 expiresAt: timestamp("expires_at").notNull(),
1217 createdAt: timestamp("created_at").defaultNow().notNull(),
1218 },
1219 (table) => [index("webauthn_challenges_expires").on(table.expiresAt)]
1220);
1221
1222export type UserPasskey = typeof userPasskeys.$inferSelect;
1223export type WebauthnChallenge = typeof webauthnChallenges.$inferSelect;
bfdb5e7Claude1224
1225/**
1226 * OAuth 2.0 provider (Block B6).
1227 *
1228 * `oauthApps` is a third-party app registered by a developer. Each app has
1229 * a public `client_id`, a hashed `client_secret`, and one or more allowed
1230 * `redirect_uris` (newline-separated). The plaintext secret is shown to the
1231 * developer exactly once at creation and cannot be recovered; they can
1232 * rotate it instead.
1233 *
1234 * `oauthAuthorizations` is a short-lived authorization code issued after
1235 * the user consents at /oauth/authorize. Single-use: `usedAt` is set on
1236 * redemption so a replay after-the-fact fails.
1237 *
1238 * `oauthAccessTokens` is a long-lived bearer token plus an optional
1239 * refresh token. Both are stored as SHA-256 hashes; the plaintext values
1240 * are only returned to the client once in the /oauth/token response.
1241 */
1242export const oauthApps = pgTable(
1243 "oauth_apps",
1244 {
1245 id: uuid("id").primaryKey().defaultRandom(),
1246 ownerId: uuid("owner_id")
1247 .notNull()
1248 .references(() => users.id, { onDelete: "cascade" }),
1249 name: text("name").notNull(),
1250 clientId: text("client_id").notNull().unique(),
1251 clientSecretHash: text("client_secret_hash").notNull(),
1252 clientSecretPrefix: text("client_secret_prefix").notNull(), // first 8 chars for display
1253 /** Newline-separated list of allowed redirect URIs. */
1254 redirectUris: text("redirect_uris").notNull(),
1255 homepageUrl: text("homepage_url"),
1256 description: text("description"),
1257 /**
1258 * If `true`, the app must present its client_secret at /oauth/token.
1259 * Public SPA/mobile apps should set this to `false` and use PKCE.
1260 */
1261 confidential: boolean("confidential").default(true).notNull(),
1262 revokedAt: timestamp("revoked_at"),
1263 createdAt: timestamp("created_at").defaultNow().notNull(),
1264 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1265 },
1266 (table) => [index("oauth_apps_owner").on(table.ownerId)]
1267);
1268
1269export const oauthAuthorizations = pgTable(
1270 "oauth_authorizations",
1271 {
1272 id: uuid("id").primaryKey().defaultRandom(),
1273 appId: uuid("app_id")
1274 .notNull()
1275 .references(() => oauthApps.id, { onDelete: "cascade" }),
1276 userId: uuid("user_id")
1277 .notNull()
1278 .references(() => users.id, { onDelete: "cascade" }),
1279 codeHash: text("code_hash").notNull().unique(),
1280 redirectUri: text("redirect_uri").notNull(),
1281 scopes: text("scopes").notNull().default(""),
1282 codeChallenge: text("code_challenge"),
1283 codeChallengeMethod: text("code_challenge_method"), // "S256" | "plain"
1284 expiresAt: timestamp("expires_at").notNull(),
1285 usedAt: timestamp("used_at"),
1286 createdAt: timestamp("created_at").defaultNow().notNull(),
1287 },
1288 (table) => [index("oauth_authorizations_expires").on(table.expiresAt)]
1289);
1290
1291export const oauthAccessTokens = pgTable(
1292 "oauth_access_tokens",
1293 {
1294 id: uuid("id").primaryKey().defaultRandom(),
1295 appId: uuid("app_id")
1296 .notNull()
1297 .references(() => oauthApps.id, { onDelete: "cascade" }),
1298 userId: uuid("user_id")
1299 .notNull()
1300 .references(() => users.id, { onDelete: "cascade" }),
1301 accessTokenHash: text("access_token_hash").notNull().unique(),
1302 refreshTokenHash: text("refresh_token_hash").unique(),
1303 scopes: text("scopes").notNull().default(""),
1304 expiresAt: timestamp("expires_at").notNull(),
1305 refreshExpiresAt: timestamp("refresh_expires_at"),
1306 revokedAt: timestamp("revoked_at"),
1307 lastUsedAt: timestamp("last_used_at"),
1308 createdAt: timestamp("created_at").defaultNow().notNull(),
1309 },
1310 (table) => [
1311 index("oauth_access_tokens_user").on(table.userId),
1312 index("oauth_access_tokens_app").on(table.appId),
1313 index("oauth_access_tokens_expires").on(table.expiresAt),
1314 ]
1315);
1316
1317export type OauthApp = typeof oauthApps.$inferSelect;
1318export type OauthAuthorization = typeof oauthAuthorizations.$inferSelect;
1319export type OauthAccessToken = typeof oauthAccessTokens.$inferSelect;
eafe8c6Claude1320
1321/**
1322 * Actions-equivalent workflow runner (Block C1).
1323 *
1324 * `workflows` rows are the YAML files discovered at `.gluecron/workflows/*.yml`
1325 * on the repo's default branch. `parsed` is the normalised JSON form used by
1326 * the runner so we don't re-parse on every trigger.
1327 *
1328 * `workflow_runs` is one execution: one row per trigger event. Status
1329 * progression: queued → running → success|failure|cancelled. `conclusion`
1330 * stays null until `status` is terminal.
1331 *
1332 * `workflow_jobs` is a single job within a run — each has its own steps
1333 * array and concatenated logs. We keep logs inline for v1 (no streaming)
1334 * to avoid a fifth table; they're truncated at the runner.
1335 *
1336 * `workflow_artifacts` persist files a job uploaded. `content` is a bytea;
1337 * we'll move this to object storage once we hit size limits.
1338 */
1339export const workflows = pgTable(
1340 "workflows",
1341 {
1342 id: uuid("id").primaryKey().defaultRandom(),
1343 repositoryId: uuid("repository_id")
1344 .notNull()
1345 .references(() => repositories.id, { onDelete: "cascade" }),
1346 name: text("name").notNull(),
1347 path: text("path").notNull(), // e.g. ".gluecron/workflows/ci.yml"
1348 yaml: text("yaml").notNull(),
1349 parsed: text("parsed").notNull(), // JSON string
1350 onEvents: text("on_events").notNull().default("[]"), // JSON array of event names
1351 disabled: boolean("disabled").default(false).notNull(),
1352 createdAt: timestamp("created_at").defaultNow().notNull(),
1353 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1354 },
1355 (table) => [
1356 index("workflows_repo").on(table.repositoryId),
1357 uniqueIndex("workflows_repo_path").on(table.repositoryId, table.path),
1358 ]
1359);
1360
1361export const workflowRuns = pgTable(
1362 "workflow_runs",
1363 {
1364 id: uuid("id").primaryKey().defaultRandom(),
1365 workflowId: uuid("workflow_id")
1366 .notNull()
1367 .references(() => workflows.id, { onDelete: "cascade" }),
1368 repositoryId: uuid("repository_id")
1369 .notNull()
1370 .references(() => repositories.id, { onDelete: "cascade" }),
1371 runNumber: integer("run_number").notNull(),
1372 event: text("event").notNull(), // "push" | "pull_request" | "manual" | ...
1373 ref: text("ref"),
1374 commitSha: text("commit_sha"),
1375 triggeredBy: uuid("triggered_by").references(() => users.id, {
1376 onDelete: "set null",
1377 }),
1378 status: text("status").notNull().default("queued"), // queued|running|success|failure|cancelled
1379 conclusion: text("conclusion"),
1380 queuedAt: timestamp("queued_at").defaultNow().notNull(),
1381 startedAt: timestamp("started_at"),
1382 finishedAt: timestamp("finished_at"),
1383 createdAt: timestamp("created_at").defaultNow().notNull(),
1384 },
1385 (table) => [
1386 index("workflow_runs_repo").on(table.repositoryId),
1387 index("workflow_runs_status").on(table.status),
1388 index("workflow_runs_workflow").on(table.workflowId),
1389 ]
1390);
1391
1392export const workflowJobs = pgTable(
1393 "workflow_jobs",
1394 {
1395 id: uuid("id").primaryKey().defaultRandom(),
1396 runId: uuid("run_id")
1397 .notNull()
1398 .references(() => workflowRuns.id, { onDelete: "cascade" }),
1399 name: text("name").notNull(),
1400 jobOrder: integer("job_order").default(0).notNull(),
1401 runsOn: text("runs_on").notNull().default("default"),
1402 status: text("status").notNull().default("queued"),
1403 conclusion: text("conclusion"),
1404 exitCode: integer("exit_code"),
1405 steps: text("steps").notNull().default("[]"), // JSON array of step results
1406 logs: text("logs").notNull().default(""),
1407 startedAt: timestamp("started_at"),
1408 finishedAt: timestamp("finished_at"),
1409 createdAt: timestamp("created_at").defaultNow().notNull(),
1410 },
1411 (table) => [index("workflow_jobs_run").on(table.runId)]
1412);
1413
1414export const workflowArtifacts = pgTable(
1415 "workflow_artifacts",
1416 {
1417 id: uuid("id").primaryKey().defaultRandom(),
1418 runId: uuid("run_id")
1419 .notNull()
1420 .references(() => workflowRuns.id, { onDelete: "cascade" }),
1421 jobId: uuid("job_id").references(() => workflowJobs.id, {
1422 onDelete: "set null",
1423 }),
1424 name: text("name").notNull(),
1425 sizeBytes: integer("size_bytes").default(0).notNull(),
1426 contentType: text("content_type")
1427 .default("application/octet-stream")
1428 .notNull(),
1429 // bytea — drizzle doesn't have a built-in bytea type at the level we use
1430 // elsewhere; store as text (base64) for v1. Migration uses real bytea so
1431 // we can swap the column type later.
1432 content: text("content"),
1433 createdAt: timestamp("created_at").defaultNow().notNull(),
1434 },
1435 (table) => [index("workflow_artifacts_run").on(table.runId)]
1436);
1437
1438export type Workflow = typeof workflows.$inferSelect;
1439export type WorkflowRun = typeof workflowRuns.$inferSelect;
1440export type WorkflowJob = typeof workflowJobs.$inferSelect;
1441export type WorkflowArtifact = typeof workflowArtifacts.$inferSelect;
e2da5c6Claude1442
1443// ---------------------------------------------------------------------------
1444// Block C2 — Package registry (npm-compatible)
1445// ---------------------------------------------------------------------------
1446
1447export const packages = pgTable(
1448 "packages",
1449 {
1450 id: uuid("id").primaryKey().defaultRandom(),
1451 repositoryId: uuid("repository_id")
1452 .notNull()
1453 .references(() => repositories.id, { onDelete: "cascade" }),
1454 ecosystem: text("ecosystem").notNull().default("npm"), // "npm" | "container"
1455 scope: text("scope"), // "@acme" for npm; null for unscoped
1456 name: text("name").notNull(), // "my-lib" (without scope)
1457 description: text("description"),
1458 readme: text("readme"),
1459 homepage: text("homepage"),
1460 license: text("license"),
1461 visibility: text("visibility").notNull().default("public"), // "public" | "private"
1462 createdAt: timestamp("created_at").defaultNow().notNull(),
1463 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1464 },
1465 (table) => [
1466 index("packages_repo").on(table.repositoryId),
1467 uniqueIndex("packages_eco_scope_name").on(
1468 table.ecosystem,
1469 table.scope,
1470 table.name
1471 ),
1472 ]
1473);
1474
1475export const packageVersions = pgTable(
1476 "package_versions",
1477 {
1478 id: uuid("id").primaryKey().defaultRandom(),
1479 packageId: uuid("package_id")
1480 .notNull()
1481 .references(() => packages.id, { onDelete: "cascade" }),
1482 version: text("version").notNull(), // "1.2.3"
1483 shasum: text("shasum").notNull(), // sha1 (for npm compat) hex
1484 integrity: text("integrity"), // "sha512-..." base64
1485 sizeBytes: integer("size_bytes").default(0).notNull(),
1486 metadata: text("metadata").notNull().default("{}"), // package.json JSON
1487 tarball: text("tarball"), // base64-encoded; bytea in migration
1488 publishedBy: uuid("published_by").references(() => users.id, {
1489 onDelete: "set null",
1490 }),
1491 yanked: boolean("yanked").default(false).notNull(),
1492 yankedReason: text("yanked_reason"),
1493 publishedAt: timestamp("published_at").defaultNow().notNull(),
1494 },
1495 (table) => [
1496 index("package_versions_pkg").on(table.packageId),
1497 uniqueIndex("package_versions_pkg_version").on(table.packageId, table.version),
1498 ]
1499);
1500
1501export const packageTags = pgTable(
1502 "package_tags",
1503 {
1504 id: uuid("id").primaryKey().defaultRandom(),
1505 packageId: uuid("package_id")
1506 .notNull()
1507 .references(() => packages.id, { onDelete: "cascade" }),
1508 tag: text("tag").notNull(), // "latest" | "beta" | ...
1509 versionId: uuid("version_id")
1510 .notNull()
1511 .references(() => packageVersions.id, { onDelete: "cascade" }),
1512 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1513 },
1514 (table) => [
1515 uniqueIndex("package_tags_pkg_tag").on(table.packageId, table.tag),
1516 ]
1517);
1518
1519export type Package = typeof packages.$inferSelect;
1520export type PackageVersion = typeof packageVersions.$inferSelect;
1521export type PackageTag = typeof packageTags.$inferSelect;
1522
1523// ---------------------------------------------------------------------------
1524// Block C3 — Pages / static hosting
1525// ---------------------------------------------------------------------------
1526
1527export const pagesDeployments = pgTable(
1528 "pages_deployments",
1529 {
1530 id: uuid("id").primaryKey().defaultRandom(),
1531 repositoryId: uuid("repository_id")
1532 .notNull()
1533 .references(() => repositories.id, { onDelete: "cascade" }),
1534 ref: text("ref").notNull().default("refs/heads/gh-pages"),
1535 commitSha: text("commit_sha").notNull(),
1536 status: text("status").notNull().default("success"), // "success" | "failed"
1537 triggeredBy: uuid("triggered_by").references(() => users.id, {
1538 onDelete: "set null",
1539 }),
1540 createdAt: timestamp("created_at").defaultNow().notNull(),
1541 },
1542 (table) => [
1543 index("pages_deployments_repo").on(table.repositoryId),
1544 index("pages_deployments_created").on(table.createdAt),
1545 ]
1546);
1547
1548export const pagesSettings = pgTable("pages_settings", {
1549 repositoryId: uuid("repository_id")
1550 .primaryKey()
1551 .references(() => repositories.id, { onDelete: "cascade" }),
1552 enabled: boolean("enabled").default(true).notNull(),
1553 sourceBranch: text("source_branch").notNull().default("gh-pages"),
1554 sourceDir: text("source_dir").notNull().default("/"), // e.g. "/" or "/docs"
1555 customDomain: text("custom_domain"),
1556 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1557});
1558
1559export type PagesDeployment = typeof pagesDeployments.$inferSelect;
1560export type PagesSettings = typeof pagesSettings.$inferSelect;
1561
1562// ---------------------------------------------------------------------------
1563// Block C4 — Environments with protected approvals
1564// ---------------------------------------------------------------------------
1565
1566export const environments = pgTable(
1567 "environments",
1568 {
1569 id: uuid("id").primaryKey().defaultRandom(),
1570 repositoryId: uuid("repository_id")
1571 .notNull()
1572 .references(() => repositories.id, { onDelete: "cascade" }),
1573 name: text("name").notNull(), // "production" | "staging" | "preview"
1574 requireApproval: boolean("require_approval").default(false).notNull(),
1575 // JSON array of user IDs that can approve deploys.
1576 reviewers: text("reviewers").notNull().default("[]"),
1577 waitTimerMinutes: integer("wait_timer_minutes").default(0).notNull(),
1578 allowedBranches: text("allowed_branches").notNull().default("[]"), // JSON glob patterns
1579 createdAt: timestamp("created_at").defaultNow().notNull(),
1580 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1581 },
1582 (table) => [
1583 uniqueIndex("environments_repo_name").on(table.repositoryId, table.name),
1584 ]
1585);
1586
1587export const deploymentApprovals = pgTable(
1588 "deployment_approvals",
1589 {
1590 id: uuid("id").primaryKey().defaultRandom(),
1591 deploymentId: uuid("deployment_id")
1592 .notNull()
1593 .references(() => deployments.id, { onDelete: "cascade" }),
1594 userId: uuid("user_id")
1595 .notNull()
1596 .references(() => users.id, { onDelete: "cascade" }),
1597 decision: text("decision").notNull(), // "approved" | "rejected"
1598 comment: text("comment"),
1599 createdAt: timestamp("created_at").defaultNow().notNull(),
1600 },
1601 (table) => [
1602 index("deployment_approvals_deployment").on(table.deploymentId),
1603 ]
1604);
1605
1606export type Environment = typeof environments.$inferSelect;
1607export type DeploymentApproval = typeof deploymentApprovals.$inferSelect;
3cbe3d6Claude1608
1609// ---------------------------------------------------------------------------
1610// Block D — AI-native differentiation (migration 0012)
1611// ---------------------------------------------------------------------------
1612
1613// D6 — cached "explain this codebase" markdown keyed on commit sha.
1614export const codebaseExplanations = pgTable(
1615 "codebase_explanations",
1616 {
1617 id: uuid("id").primaryKey().defaultRandom(),
1618 repositoryId: uuid("repository_id")
1619 .notNull()
1620 .references(() => repositories.id, { onDelete: "cascade" }),
1621 commitSha: text("commit_sha").notNull(),
1622 summary: text("summary").notNull(),
1623 markdown: text("markdown").notNull(),
1624 model: text("model").notNull(),
1625 generatedAt: timestamp("generated_at").defaultNow().notNull(),
1626 },
1627 (table) => [
1628 uniqueIndex("codebase_explanations_repo_sha").on(
1629 table.repositoryId,
1630 table.commitSha
1631 ),
1632 ]
1633);
1634
1635// D2 — AI dependency bumper run history.
1636export const depUpdateRuns = pgTable(
1637 "dep_update_runs",
1638 {
1639 id: uuid("id").primaryKey().defaultRandom(),
1640 repositoryId: uuid("repository_id")
1641 .notNull()
1642 .references(() => repositories.id, { onDelete: "cascade" }),
1643 status: text("status").notNull().default("pending"), // pending|running|success|failed|no_updates
1644 ecosystem: text("ecosystem").notNull(), // npm|bun
1645 manifestPath: text("manifest_path").notNull(),
1646 attemptedBumps: text("attempted_bumps").notNull().default("[]"), // JSON
1647 appliedBumps: text("applied_bumps").notNull().default("[]"), // JSON
1648 branchName: text("branch_name"),
1649 prNumber: integer("pr_number"),
1650 errorMessage: text("error_message"),
1651 triggeredBy: uuid("triggered_by").references(() => users.id, {
1652 onDelete: "set null",
1653 }),
1654 createdAt: timestamp("created_at").defaultNow().notNull(),
1655 completedAt: timestamp("completed_at"),
1656 },
1657 (table) => [
1658 index("dep_update_runs_repo").on(table.repositoryId),
1659 index("dep_update_runs_created").on(table.createdAt),
1660 ]
1661);
1662
1663// D1 — code chunks for semantic search. Embedding stored as JSON-encoded
1664// number array in text to avoid requiring pgvector; cosine similarity is
1665// computed in JS. Upgrade path: ALTER COLUMN embedding TYPE vector(1024).
1666export const codeChunks = pgTable(
1667 "code_chunks",
1668 {
1669 id: uuid("id").primaryKey().defaultRandom(),
1670 repositoryId: uuid("repository_id")
1671 .notNull()
1672 .references(() => repositories.id, { onDelete: "cascade" }),
1673 commitSha: text("commit_sha").notNull(),
1674 path: text("path").notNull(),
1675 startLine: integer("start_line").notNull(),
1676 endLine: integer("end_line").notNull(),
1677 content: text("content").notNull(),
1678 embedding: text("embedding"), // JSON number[]
1679 embeddingModel: text("embedding_model"),
1680 createdAt: timestamp("created_at").defaultNow().notNull(),
1681 },
1682 (table) => [
1683 index("code_chunks_repo").on(table.repositoryId),
1684 index("code_chunks_repo_path").on(table.repositoryId, table.path),
1685 ]
1686);
1687
1688export type CodebaseExplanation = typeof codebaseExplanations.$inferSelect;
1689export type DepUpdateRun = typeof depUpdateRuns.$inferSelect;
1e162a8Claude1690
1691// ---------------------------------------------------------------------------
c645a86Claude1692// Block E2 — Discussions (migration 0013 + 0077)
1e162a8Claude1693// ---------------------------------------------------------------------------
1694
c645a86Claude1695/**
1696 * Per-repo discussion categories (migration 0077).
1697 * Seeded lazily on first discussion creation: General, Q&A, Announcements, Ideas.
1698 * is_answerable = true surfaces "Mark as answer" on threads in that category.
1699 */
1700export const discussionCategories = pgTable(
1701 "discussion_categories",
1702 {
1703 id: serial("id").primaryKey(),
1704 repositoryId: uuid("repository_id")
1705 .notNull()
1706 .references(() => repositories.id, { onDelete: "cascade" }),
1707 name: text("name").notNull(),
1708 emoji: text("emoji").notNull().default("💬"),
1709 description: text("description"),
1710 isAnswerable: boolean("is_answerable").notNull().default(false),
1711 },
1712 (table) => [index("discussion_categories_repo").on(table.repositoryId)]
1713);
1714
1715export type DiscussionCategory = typeof discussionCategories.$inferSelect;
1716
1e162a8Claude1717/**
1718 * Discussions — forum-style threaded conversations attached to a repo.
1719 * Similar to GitHub Discussions: categorised + pinnable + answerable.
1720 */
1721export const discussions = pgTable(
1722 "discussions",
1723 {
1724 id: uuid("id").primaryKey().defaultRandom(),
1725 number: serial("number"),
1726 repositoryId: uuid("repository_id")
1727 .notNull()
1728 .references(() => repositories.id, { onDelete: "cascade" }),
1729 authorId: uuid("author_id")
1730 .notNull()
1731 .references(() => users.id),
1732 // one of: "general" | "q-and-a" | "ideas" | "announcements" | "show-and-tell"
1733 category: text("category").notNull().default("general"),
1734 title: text("title").notNull(),
1735 body: text("body"),
1736 state: text("state").notNull().default("open"), // open, closed
1737 locked: boolean("locked").notNull().default(false),
1738 answerCommentId: uuid("answer_comment_id"),
1739 pinned: boolean("pinned").notNull().default(false),
1740 createdAt: timestamp("created_at").defaultNow().notNull(),
1741 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1742 },
1743 (table) => [
1744 index("discussions_repo").on(table.repositoryId),
1745 uniqueIndex("discussions_repo_number").on(
1746 table.repositoryId,
1747 table.number
1748 ),
1749 ]
1750);
1751
1752export const discussionComments = pgTable(
1753 "discussion_comments",
1754 {
1755 id: uuid("id").primaryKey().defaultRandom(),
1756 discussionId: uuid("discussion_id")
1757 .notNull()
1758 .references(() => discussions.id, { onDelete: "cascade" }),
1759 parentCommentId: uuid("parent_comment_id"),
1760 authorId: uuid("author_id")
1761 .notNull()
1762 .references(() => users.id),
1763 body: text("body").notNull(),
1764 isAnswer: boolean("is_answer").notNull().default(false),
1765 createdAt: timestamp("created_at").defaultNow().notNull(),
1766 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1767 },
1768 (table) => [
1769 index("discussion_comments_discussion").on(table.discussionId),
1770 ]
1771);
1772
1773export type Discussion = typeof discussions.$inferSelect;
1774export type DiscussionComment = typeof discussionComments.$inferSelect;
3cbe3d6Claude1775export type CodeChunk = typeof codeChunks.$inferSelect;
1e162a8Claude1776
1777// ---------------------------------------------------------------------------
1778// Block E4 — Gists (migration 0014)
1779// ---------------------------------------------------------------------------
1780//
1781// User-owned small snippets/files that behave like tiny repos. DB-backed
1782// for v1 (no bare git repo): each gist owns a collection of gist_files and
1783// every edit appends a gist_revisions row with a JSON snapshot.
1784
1785export const gists = pgTable(
1786 "gists",
1787 {
1788 id: uuid("id").primaryKey().defaultRandom(),
1789 ownerId: uuid("owner_id")
1790 .notNull()
1791 .references(() => users.id, { onDelete: "cascade" }),
1792 // 8-char hex slug used in pretty URLs (e.g. /gists/a1b2c3d4).
1793 slug: text("slug").notNull().unique(),
1794 title: text("title").notNull().default(""),
1795 description: text("description").notNull().default(""),
1796 isPublic: boolean("is_public").default(true).notNull(),
1797 createdAt: timestamp("created_at").defaultNow().notNull(),
1798 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1799 },
1800 (table) => [index("gists_owner").on(table.ownerId)]
1801);
1802
1803export const gistFiles = pgTable(
1804 "gist_files",
1805 {
1806 id: uuid("id").primaryKey().defaultRandom(),
1807 gistId: uuid("gist_id")
1808 .notNull()
1809 .references(() => gists.id, { onDelete: "cascade" }),
1810 filename: text("filename").notNull(),
1811 // Optional explicit language override; falls back to filename detection.
1812 language: text("language"),
1813 content: text("content").notNull().default(""),
1814 sizeBytes: integer("size_bytes").default(0).notNull(),
1815 },
1816 (table) => [
1817 index("gist_files_gist").on(table.gistId),
1818 uniqueIndex("gist_files_gist_filename").on(table.gistId, table.filename),
1819 ]
1820);
1821
1822export const gistRevisions = pgTable(
1823 "gist_revisions",
1824 {
1825 id: uuid("id").primaryKey().defaultRandom(),
1826 gistId: uuid("gist_id")
1827 .notNull()
1828 .references(() => gists.id, { onDelete: "cascade" }),
1829 revision: integer("revision").notNull(),
1830 // JSON-encoded {filename: content} map capturing the full snapshot at
1831 // this revision. Stored as text to avoid requiring jsonb.
1832 snapshot: text("snapshot").notNull().default("{}"),
1833 authorId: uuid("author_id")
1834 .notNull()
1835 .references(() => users.id, { onDelete: "cascade" }),
1836 message: text("message"),
1837 createdAt: timestamp("created_at").defaultNow().notNull(),
1838 },
1839 (table) => [
1840 index("gist_revisions_gist_rev").on(table.gistId, table.revision),
1841 ]
1842);
1843
1844export const gistStars = pgTable(
1845 "gist_stars",
1846 {
1847 id: uuid("id").primaryKey().defaultRandom(),
1848 gistId: uuid("gist_id")
1849 .notNull()
1850 .references(() => gists.id, { onDelete: "cascade" }),
1851 userId: uuid("user_id")
1852 .notNull()
1853 .references(() => users.id, { onDelete: "cascade" }),
1854 createdAt: timestamp("created_at").defaultNow().notNull(),
1855 },
1856 (table) => [uniqueIndex("gist_stars_gist_user").on(table.gistId, table.userId)]
1857);
1858
1859export type Gist = typeof gists.$inferSelect;
1860export type GistFile = typeof gistFiles.$inferSelect;
1861export type GistRevision = typeof gistRevisions.$inferSelect;
1862export type GistStar = typeof gistStars.$inferSelect;
1863
1864// ---------------------------------------------------------------------------
1865// Block E1 — Projects / kanban (migration 0015)
1866// ---------------------------------------------------------------------------
1867
1868export const projects = pgTable(
1869 "projects",
1870 {
1871 id: uuid("id").primaryKey().defaultRandom(),
1872 number: serial("number"),
1873 repositoryId: uuid("repository_id")
1874 .notNull()
1875 .references(() => repositories.id, { onDelete: "cascade" }),
1876 ownerId: uuid("owner_id")
1877 .notNull()
1878 .references(() => users.id),
1879 title: text("title").notNull(),
1880 description: text("description").notNull().default(""),
1881 state: text("state").notNull().default("open"), // open | closed
1882 createdAt: timestamp("created_at").defaultNow().notNull(),
1883 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1884 },
1885 (table) => [
1886 index("projects_repo").on(table.repositoryId),
1887 uniqueIndex("projects_repo_number").on(table.repositoryId, table.number),
1888 ]
1889);
1890
1891export const projectColumns = pgTable(
1892 "project_columns",
1893 {
1894 id: uuid("id").primaryKey().defaultRandom(),
1895 projectId: uuid("project_id")
1896 .notNull()
1897 .references(() => projects.id, { onDelete: "cascade" }),
1898 name: text("name").notNull(),
1899 position: integer("position").notNull().default(0),
1900 createdAt: timestamp("created_at").defaultNow().notNull(),
1901 },
1902 (table) => [index("project_columns_project").on(table.projectId)]
1903);
1904
1905export const projectItems = pgTable(
1906 "project_items",
1907 {
1908 id: uuid("id").primaryKey().defaultRandom(),
1909 projectId: uuid("project_id")
1910 .notNull()
1911 .references(() => projects.id, { onDelete: "cascade" }),
1912 columnId: uuid("column_id")
1913 .notNull()
1914 .references(() => projectColumns.id, { onDelete: "cascade" }),
1915 position: integer("position").notNull().default(0),
1916 // "note" | "issue" | "pr" — application-level FK on itemId by type
1917 itemType: text("item_type").notNull().default("note"),
1918 itemId: uuid("item_id"),
1919 title: text("title").notNull().default(""),
1920 note: text("note").notNull().default(""),
1921 createdAt: timestamp("created_at").defaultNow().notNull(),
1922 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1923 },
1924 (table) => [
1925 index("project_items_project").on(table.projectId),
1926 index("project_items_column").on(table.columnId, table.position),
1927 ]
1928);
1929
1930export type Project = typeof projects.$inferSelect;
1931export type ProjectColumn = typeof projectColumns.$inferSelect;
1932export type ProjectItem = typeof projectItems.$inferSelect;
1933
1934// ---------------------------------------------------------------------------
1935// Block E3 — Wikis (migration 0016)
1936// ---------------------------------------------------------------------------
1937// DB-backed for v1; git-backed mirror is a future upgrade.
1938
1939export const wikiPages = pgTable(
1940 "wiki_pages",
1941 {
1942 id: uuid("id").primaryKey().defaultRandom(),
1943 repositoryId: uuid("repository_id")
1944 .notNull()
1945 .references(() => repositories.id, { onDelete: "cascade" }),
1946 slug: text("slug").notNull(),
1947 title: text("title").notNull(),
1948 body: text("body").notNull().default(""),
1949 revision: integer("revision").notNull().default(1),
1950 createdAt: timestamp("created_at").defaultNow().notNull(),
1951 updatedAt: timestamp("updated_at").defaultNow().notNull(),
1952 updatedBy: uuid("updated_by").references(() => users.id),
1953 },
1954 (table) => [
1955 index("wiki_pages_repo").on(table.repositoryId),
1956 uniqueIndex("wiki_pages_repo_slug").on(table.repositoryId, table.slug),
1957 ]
1958);
1959
1960export const wikiRevisions = pgTable(
1961 "wiki_revisions",
1962 {
1963 id: uuid("id").primaryKey().defaultRandom(),
1964 pageId: uuid("page_id")
1965 .notNull()
1966 .references(() => wikiPages.id, { onDelete: "cascade" }),
1967 revision: integer("revision").notNull(),
1968 title: text("title").notNull(),
1969 body: text("body").notNull().default(""),
1970 message: text("message"),
1971 authorId: uuid("author_id")
1972 .notNull()
1973 .references(() => users.id),
1974 createdAt: timestamp("created_at").defaultNow().notNull(),
1975 },
1976 (table) => [index("wiki_revisions_page").on(table.pageId, table.revision)]
1977);
1978
1979export type WikiPage = typeof wikiPages.$inferSelect;
1980export type WikiRevision = typeof wikiRevisions.$inferSelect;
a79a9edClaude1981
1982// ---------------------------------------------------------------------------
1983// Block E5 — Merge queues (migration 0017)
1984// ---------------------------------------------------------------------------
1985
1986export const mergeQueueEntries = pgTable(
1987 "merge_queue_entries",
1988 {
1989 id: uuid("id").primaryKey().defaultRandom(),
1990 repositoryId: uuid("repository_id")
1991 .notNull()
1992 .references(() => repositories.id, { onDelete: "cascade" }),
1993 pullRequestId: uuid("pull_request_id")
1994 .notNull()
1995 .references(() => pullRequests.id, { onDelete: "cascade" }),
1996 baseBranch: text("base_branch").notNull(),
1997 // queued | running | merged | failed | dequeued
1998 state: text("state").notNull().default("queued"),
1999 position: integer("position").notNull().default(0),
2000 enqueuedBy: uuid("enqueued_by").references(() => users.id),
2001 enqueuedAt: timestamp("enqueued_at").defaultNow().notNull(),
2002 startedAt: timestamp("started_at"),
2003 finishedAt: timestamp("finished_at"),
2004 errorMessage: text("error_message"),
2005 },
2006 (table) => [
2007 index("merge_queue_repo_branch").on(
2008 table.repositoryId,
2009 table.baseBranch,
2010 table.state
2011 ),
2012 ]
2013);
2014
2015export type MergeQueueEntry = typeof mergeQueueEntries.$inferSelect;
2016
2017// ---------------------------------------------------------------------------
2018// Block E6 — Required status checks matrix (migration 0018)
2019// ---------------------------------------------------------------------------
2020
2021export const branchRequiredChecks = pgTable(
2022 "branch_required_checks",
2023 {
2024 id: uuid("id").primaryKey().defaultRandom(),
2025 branchProtectionId: uuid("branch_protection_id")
2026 .notNull()
2027 .references(() => branchProtection.id, { onDelete: "cascade" }),
2028 checkName: text("check_name").notNull(),
2029 createdAt: timestamp("created_at").defaultNow().notNull(),
2030 },
2031 (table) => [
2032 index("branch_required_checks_rule").on(table.branchProtectionId),
2033 uniqueIndex("branch_required_checks_unique").on(
2034 table.branchProtectionId,
2035 table.checkName
2036 ),
2037 ]
2038);
2039
2040export type BranchRequiredCheck = typeof branchRequiredChecks.$inferSelect;
2041
2042// ---------------------------------------------------------------------------
2043// Block E7 — Protected tags (migration 0019)
2044// ---------------------------------------------------------------------------
2045
2046export const protectedTags = pgTable(
2047 "protected_tags",
2048 {
2049 id: uuid("id").primaryKey().defaultRandom(),
2050 repositoryId: uuid("repository_id")
2051 .notNull()
2052 .references(() => repositories.id, { onDelete: "cascade" }),
2053 pattern: text("pattern").notNull(),
2054 createdAt: timestamp("created_at").defaultNow().notNull(),
2055 createdBy: uuid("created_by").references(() => users.id),
2056 },
2057 (table) => [
2058 index("protected_tags_repo").on(table.repositoryId),
2059 uniqueIndex("protected_tags_repo_pattern").on(
2060 table.repositoryId,
2061 table.pattern
2062 ),
2063 ]
2064);
2065
2066export type ProtectedTag = typeof protectedTags.$inferSelect;
8f50ed0Claude2067
2068// ---------------------------------------------------------------------------
2069// Block F — Observability + admin (migration 0020)
2070// ---------------------------------------------------------------------------
2071
2072// F1 — Traffic analytics per repo
2073export const repoTrafficEvents = pgTable(
2074 "repo_traffic_events",
2075 {
2076 id: uuid("id").primaryKey().defaultRandom(),
2077 repositoryId: uuid("repository_id")
2078 .notNull()
2079 .references(() => repositories.id, { onDelete: "cascade" }),
2080 kind: text("kind").notNull(), // view | clone | api | ui
2081 path: text("path"),
2082 userId: uuid("user_id").references(() => users.id, { onDelete: "set null" }),
2083 ipHash: text("ip_hash"),
2084 userAgent: text("user_agent"),
2085 referer: text("referer"),
2086 createdAt: timestamp("created_at").defaultNow().notNull(),
2087 },
2088 (table) => [
2089 index("repo_traffic_events_repo_time").on(
2090 table.repositoryId,
2091 table.createdAt
2092 ),
2093 index("repo_traffic_events_kind").on(
2094 table.repositoryId,
2095 table.kind,
2096 table.createdAt
2097 ),
2098 ]
2099);
2100
2101export type RepoTrafficEvent = typeof repoTrafficEvents.$inferSelect;
2102
2103// F3 — Admin panel (site admins + toggleable flags)
2104export const systemFlags = pgTable("system_flags", {
2105 key: text("key").primaryKey(),
2106 value: text("value").notNull().default(""),
2107 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2108 updatedBy: uuid("updated_by").references(() => users.id),
2109});
2110
2111export type SystemFlag = typeof systemFlags.$inferSelect;
2112
2113export const siteAdmins = pgTable("site_admins", {
2114 userId: uuid("user_id")
2115 .primaryKey()
2116 .references(() => users.id, { onDelete: "cascade" }),
2117 grantedAt: timestamp("granted_at").defaultNow().notNull(),
2118 grantedBy: uuid("granted_by").references(() => users.id),
2119});
2120
2121export type SiteAdmin = typeof siteAdmins.$inferSelect;
2122
509c376Claude2123// /admin/integrations — DB-stored platform integration secrets (migration 0055).
2124// Loaded into process.env at boot so the existing synchronous config getters
2125// keep working transparently. Never exposes DATABASE_URL / SELF_HOST_REPO /
2126// PORT / GIT_REPOS_PATH — those stay env-only.
2127export const systemConfig = pgTable("system_config", {
2128 key: text("key").primaryKey(),
2129 value: text("value").notNull().default(""),
2130 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2131 updatedByUserId: uuid("updated_by_user_id").references(() => users.id, {
2132 onDelete: "set null",
2133 }),
2134});
2135
2136export type SystemConfig = typeof systemConfig.$inferSelect;
2137
8f50ed0Claude2138// F4 — Billing + quotas
2139export const billingPlans = pgTable("billing_plans", {
2140 id: uuid("id").primaryKey().defaultRandom(),
2141 slug: text("slug").notNull().unique(),
2142 name: text("name").notNull(),
2143 priceCents: integer("price_cents").notNull().default(0),
2144 repoLimit: integer("repo_limit").notNull().default(10),
2145 storageMbLimit: integer("storage_mb_limit").notNull().default(1024),
2146 aiTokensMonthly: integer("ai_tokens_monthly").notNull().default(100000),
2147 bandwidthGbMonthly: integer("bandwidth_gb_monthly").notNull().default(10),
2148 privateRepos: boolean("private_repos").notNull().default(false),
2149 createdAt: timestamp("created_at").defaultNow().notNull(),
2150});
2151
2152export type BillingPlan = typeof billingPlans.$inferSelect;
2153
2154export const userQuotas = pgTable("user_quotas", {
2155 userId: uuid("user_id")
2156 .primaryKey()
2157 .references(() => users.id, { onDelete: "cascade" }),
2158 planSlug: text("plan_slug").notNull().default("free"),
2159 storageMbUsed: integer("storage_mb_used").notNull().default(0),
2160 aiTokensUsedThisMonth: integer("ai_tokens_used_this_month")
2161 .notNull()
2162 .default(0),
2163 bandwidthGbUsedThisMonth: integer("bandwidth_gb_used_this_month")
2164 .notNull()
2165 .default(0),
2166 cycleStart: timestamp("cycle_start").defaultNow().notNull(),
2167 updatedAt: timestamp("updated_at").defaultNow().notNull(),
619109aClaude2168 // Stripe linkage (migration 0038). Null until the user first upgrades.
2169 stripeCustomerId: text("stripe_customer_id"),
2170 stripeSubscriptionId: text("stripe_subscription_id"),
2171 stripeSubscriptionStatus: text("stripe_subscription_status"),
2172 currentPeriodEnd: timestamp("current_period_end"),
8f50ed0Claude2173});
2174
2175export type UserQuota = typeof userQuotas.$inferSelect;
06139e6Claude2176
2177// Block H — App marketplace + bot identities (GitHub Apps equivalent)
2178
2179export const apps = pgTable(
2180 "apps",
2181 {
2182 id: uuid("id").primaryKey().defaultRandom(),
2183 slug: text("slug").notNull().unique(),
2184 name: text("name").notNull(),
2185 description: text("description").notNull().default(""),
2186 iconUrl: text("icon_url"),
2187 homepageUrl: text("homepage_url"),
2188 webhookUrl: text("webhook_url"),
2189 webhookSecret: text("webhook_secret"),
2190 creatorId: uuid("creator_id")
2191 .notNull()
2192 .references(() => users.id, { onDelete: "cascade" }),
2193 permissions: text("permissions").notNull().default("[]"), // JSON array
2194 defaultEvents: text("default_events").notNull().default("[]"), // JSON array
2195 isPublic: boolean("is_public").notNull().default(true),
2196 createdAt: timestamp("created_at").defaultNow().notNull(),
2197 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2198 },
2199 (table) => [index("apps_public_slug").on(table.isPublic, table.slug)]
2200);
2201
2202export type App = typeof apps.$inferSelect;
2203
2204export const appInstallations = pgTable(
2205 "app_installations",
2206 {
2207 id: uuid("id").primaryKey().defaultRandom(),
2208 appId: uuid("app_id")
2209 .notNull()
2210 .references(() => apps.id, { onDelete: "cascade" }),
2211 installedBy: uuid("installed_by")
2212 .notNull()
2213 .references(() => users.id, { onDelete: "cascade" }),
2214 targetType: text("target_type").notNull(), // user | org | repository
2215 targetId: uuid("target_id").notNull(),
2216 grantedPermissions: text("granted_permissions").notNull().default("[]"),
2217 suspendedAt: timestamp("suspended_at"),
2218 createdAt: timestamp("created_at").defaultNow().notNull(),
2219 uninstalledAt: timestamp("uninstalled_at"),
2220 },
2221 (table) => [
2222 index("app_installations_app").on(table.appId),
2223 index("app_installations_target").on(table.targetType, table.targetId),
2224 ]
2225);
2226
2227export type AppInstallation = typeof appInstallations.$inferSelect;
2228
2229export const appBots = pgTable("app_bots", {
2230 id: uuid("id").primaryKey().defaultRandom(),
2231 appId: uuid("app_id")
2232 .notNull()
2233 .unique()
2234 .references(() => apps.id, { onDelete: "cascade" }),
2235 username: text("username").notNull().unique(),
2236 displayName: text("display_name").notNull(),
2237 avatarUrl: text("avatar_url"),
2238 createdAt: timestamp("created_at").defaultNow().notNull(),
2239});
2240
2241export type AppBot = typeof appBots.$inferSelect;
2242
2243export const appInstallTokens = pgTable(
2244 "app_install_tokens",
2245 {
2246 id: uuid("id").primaryKey().defaultRandom(),
2247 installationId: uuid("installation_id")
2248 .notNull()
2249 .references(() => appInstallations.id, { onDelete: "cascade" }),
2250 tokenHash: text("token_hash").notNull().unique(),
2251 expiresAt: timestamp("expires_at").notNull(),
2252 createdAt: timestamp("created_at").defaultNow().notNull(),
2253 revokedAt: timestamp("revoked_at"),
2254 },
2255 (table) => [index("app_install_tokens_hash").on(table.tokenHash)]
2256);
2257
2258export type AppInstallToken = typeof appInstallTokens.$inferSelect;
2259
2260export const appEvents = pgTable(
2261 "app_events",
2262 {
2263 id: uuid("id").primaryKey().defaultRandom(),
2264 appId: uuid("app_id")
2265 .notNull()
2266 .references(() => apps.id, { onDelete: "cascade" }),
2267 installationId: uuid("installation_id"),
2268 kind: text("kind").notNull(), // installed | uninstalled | delivery_ok | delivery_fail
2269 payload: text("payload"),
2270 responseStatus: integer("response_status"),
2271 createdAt: timestamp("created_at").defaultNow().notNull(),
2272 },
2273 (table) => [index("app_events_app_time").on(table.appId, table.createdAt)]
2274);
2275
2276export type AppEvent = typeof appEvents.$inferSelect;
71cd5ecClaude2277
2278// ---------- Block I3 — Repository transfer history ----------
2279
2280export const repoTransfers = pgTable(
2281 "repo_transfers",
2282 {
2283 id: uuid("id").primaryKey().defaultRandom(),
2284 repositoryId: uuid("repository_id")
2285 .notNull()
2286 .references(() => repositories.id, { onDelete: "cascade" }),
2287 fromOwnerId: uuid("from_owner_id").notNull(),
2288 fromOrgId: uuid("from_org_id"),
2289 toOwnerId: uuid("to_owner_id").notNull(),
2290 toOrgId: uuid("to_org_id"),
2291 initiatedBy: uuid("initiated_by")
2292 .notNull()
2293 .references(() => users.id, { onDelete: "cascade" }),
2294 createdAt: timestamp("created_at").defaultNow().notNull(),
2295 },
2296 (table) => [
2297 index("repo_transfers_repo").on(table.repositoryId, table.createdAt),
2298 ]
2299);
2300
2301export type RepoTransfer = typeof repoTransfers.$inferSelect;
08420cdClaude2302
2303// ---------- Block I6 — Sponsors ----------
2304
2305export const sponsorshipTiers = pgTable(
2306 "sponsorship_tiers",
2307 {
2308 id: uuid("id").primaryKey().defaultRandom(),
2309 maintainerId: uuid("maintainer_id")
2310 .notNull()
2311 .references(() => users.id, { onDelete: "cascade" }),
2312 name: text("name").notNull(),
2313 description: text("description").default("").notNull(),
2314 monthlyCents: integer("monthly_cents").notNull(),
2315 oneTimeAllowed: boolean("one_time_allowed").default(true).notNull(),
2316 isActive: boolean("is_active").default(true).notNull(),
2317 createdAt: timestamp("created_at").defaultNow().notNull(),
2318 },
2319 (table) => [
2320 index("sponsor_tiers_maintainer").on(table.maintainerId, table.isActive),
2321 ]
2322);
2323
2324export type SponsorshipTier = typeof sponsorshipTiers.$inferSelect;
2325
2326export const sponsorships = pgTable(
2327 "sponsorships",
2328 {
2329 id: uuid("id").primaryKey().defaultRandom(),
2330 sponsorId: uuid("sponsor_id")
2331 .notNull()
2332 .references(() => users.id, { onDelete: "cascade" }),
2333 maintainerId: uuid("maintainer_id")
2334 .notNull()
2335 .references(() => users.id, { onDelete: "cascade" }),
2336 tierId: uuid("tier_id"),
2337 amountCents: integer("amount_cents").notNull(),
2338 kind: text("kind").notNull(), // one_time | monthly
2339 note: text("note"),
2340 isPublic: boolean("is_public").default(true).notNull(),
2341 externalRef: text("external_ref"),
2342 cancelledAt: timestamp("cancelled_at"),
2343 createdAt: timestamp("created_at").defaultNow().notNull(),
2344 },
2345 (table) => [
2346 index("sponsorships_maintainer").on(
2347 table.maintainerId,
2348 table.createdAt
2349 ),
2350 index("sponsorships_sponsor").on(table.sponsorId, table.createdAt),
2351 ]
2352);
2353
2354export type Sponsorship = typeof sponsorships.$inferSelect;
4c8f666Claude2355
2356// Block I8 — Code symbol index for xref navigation.
2357export const codeSymbols = pgTable(
2358 "code_symbols",
2359 {
2360 id: uuid("id").primaryKey().defaultRandom(),
2361 repositoryId: uuid("repository_id")
2362 .notNull()
2363 .references(() => repositories.id, { onDelete: "cascade" }),
2364 commitSha: text("commit_sha").notNull(),
2365 name: text("name").notNull(),
2366 kind: text("kind").notNull(), // function | class | interface | type | const | variable
2367 path: text("path").notNull(),
2368 line: integer("line").notNull(),
2369 signature: text("signature"),
2370 createdAt: timestamp("created_at").defaultNow().notNull(),
2371 },
2372 (table) => [
2373 index("code_symbols_repo_name_idx").on(table.repositoryId, table.name),
2374 index("code_symbols_repo_path_idx").on(table.repositoryId, table.path),
2375 ]
2376);
2377
2378export type CodeSymbol = typeof codeSymbols.$inferSelect;
4a0dea1Claude2379
2380// Block I9 — Repository mirroring. One row per mirrored repo + an
2381// append-only log of sync attempts.
2382export const repoMirrors = pgTable("repo_mirrors", {
2383 id: uuid("id").primaryKey().defaultRandom(),
2384 repositoryId: uuid("repository_id")
2385 .notNull()
2386 .unique()
2387 .references(() => repositories.id, { onDelete: "cascade" }),
2388 upstreamUrl: text("upstream_url").notNull(),
2389 intervalMinutes: integer("interval_minutes").default(1440).notNull(),
2390 lastSyncedAt: timestamp("last_synced_at"),
2391 lastStatus: text("last_status"), // "ok" | "error"
2392 lastError: text("last_error"),
2393 isEnabled: boolean("is_enabled").default(true).notNull(),
2394 createdAt: timestamp("created_at").defaultNow().notNull(),
2395 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2396});
2397
2398export type RepoMirror = typeof repoMirrors.$inferSelect;
2399
2400export const repoMirrorRuns = pgTable(
2401 "repo_mirror_runs",
2402 {
2403 id: uuid("id").primaryKey().defaultRandom(),
2404 mirrorId: uuid("mirror_id")
2405 .notNull()
2406 .references(() => repoMirrors.id, { onDelete: "cascade" }),
2407 startedAt: timestamp("started_at").defaultNow().notNull(),
2408 finishedAt: timestamp("finished_at"),
2409 status: text("status").default("running").notNull(),
2410 message: text("message"),
2411 exitCode: integer("exit_code"),
2412 },
2413 (table) => [
2414 index("repo_mirror_runs_mirror_id_idx").on(table.mirrorId, table.startedAt),
2415 ]
2416);
2417
2418export type RepoMirrorRun = typeof repoMirrorRuns.$inferSelect;
edf7c36Claude2419
2420// ----------------------------------------------------------------------------
2421// Block I10 — Enterprise SSO (OIDC)
2422// ----------------------------------------------------------------------------
2423
2424/** Site-wide SSO provider. Singleton row with id = 'default'. */
2425export const ssoConfig = pgTable("sso_config", {
2426 id: text("id").primaryKey(),
2427 enabled: boolean("enabled").default(false).notNull(),
2428 providerName: text("provider_name").default("SSO").notNull(),
2429 issuer: text("issuer"),
2430 authorizationEndpoint: text("authorization_endpoint"),
2431 tokenEndpoint: text("token_endpoint"),
2432 userinfoEndpoint: text("userinfo_endpoint"),
2433 clientId: text("client_id"),
2434 clientSecret: text("client_secret"),
2435 scopes: text("scopes").default("openid profile email").notNull(),
2436 allowedEmailDomains: text("allowed_email_domains"),
2437 autoCreateUsers: boolean("auto_create_users").default(true).notNull(),
2438 createdAt: timestamp("created_at").defaultNow().notNull(),
2439 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2440});
2441
2442export type SsoConfig = typeof ssoConfig.$inferSelect;
2443
2444/** Maps a local user to an IdP `sub` claim. */
2445export const ssoUserLinks = pgTable(
2446 "sso_user_links",
2447 {
2448 id: uuid("id").primaryKey().defaultRandom(),
2449 userId: uuid("user_id")
2450 .notNull()
2451 .references(() => users.id, { onDelete: "cascade" }),
2452 subject: text("subject").notNull().unique(),
2453 emailAtLink: text("email_at_link").notNull(),
2454 linkedAt: timestamp("linked_at").defaultNow().notNull(),
2455 },
2456 (table) => [index("sso_user_links_user_id_idx").on(table.userId)]
2457);
2458
2459export type SsoUserLink = typeof ssoUserLinks.$inferSelect;
8098672Claude2460
2461// ----------------------------------------------------------------------------
2462// Block J1 — Dependency graph
2463// ----------------------------------------------------------------------------
2464
2465/**
2466 * Last known set of dependencies parsed from manifest files. Each reindex
2467 * replaces the prior rows for that repo. One row per (ecosystem, name,
2468 * manifest_path) — same name in multiple manifests is kept.
2469 */
2470export const repoDependencies = pgTable(
2471 "repo_dependencies",
2472 {
2473 id: uuid("id").primaryKey().defaultRandom(),
2474 repositoryId: uuid("repository_id")
2475 .notNull()
2476 .references(() => repositories.id, { onDelete: "cascade" }),
2477 ecosystem: text("ecosystem").notNull(),
2478 name: text("name").notNull(),
2479 versionSpec: text("version_spec"),
2480 manifestPath: text("manifest_path").notNull(),
2481 isDev: boolean("is_dev").default(false).notNull(),
2482 commitSha: text("commit_sha").notNull(),
2483 indexedAt: timestamp("indexed_at").defaultNow().notNull(),
2484 },
2485 (table) => [
2486 index("repo_dependencies_repo_id_idx").on(
2487 table.repositoryId,
2488 table.ecosystem
2489 ),
2490 index("repo_dependencies_name_idx").on(table.name),
2491 ]
2492);
2493
2494export type RepoDependency = typeof repoDependencies.$inferSelect;
f60ccdeClaude2495
2496// ----------------------------------------------------------------------------
2497// Block J2 — Security advisories + alerts
2498// ----------------------------------------------------------------------------
2499
2500/** CVE-style package advisories. Populated via seed + admin import. */
2501export const securityAdvisories = pgTable(
2502 "security_advisories",
2503 {
2504 id: uuid("id").primaryKey().defaultRandom(),
2505 ghsaId: text("ghsa_id").unique(),
2506 cveId: text("cve_id"),
2507 summary: text("summary").notNull(),
2508 severity: text("severity").default("moderate").notNull(),
2509 ecosystem: text("ecosystem").notNull(),
2510 packageName: text("package_name").notNull(),
2511 affectedRange: text("affected_range").notNull(),
2512 fixedVersion: text("fixed_version"),
2513 referenceUrl: text("reference_url"),
2514 publishedAt: timestamp("published_at").defaultNow().notNull(),
2515 },
2516 (table) => [
2517 index("security_advisories_pkg_idx").on(
2518 table.ecosystem,
2519 table.packageName
2520 ),
2521 ]
2522);
2523
2524export type SecurityAdvisory = typeof securityAdvisories.$inferSelect;
2525
2526/** Per-repo match state. One row per (repo, advisory, manifest_path). */
2527export const repoAdvisoryAlerts = pgTable(
2528 "repo_advisory_alerts",
2529 {
2530 id: uuid("id").primaryKey().defaultRandom(),
2531 repositoryId: uuid("repository_id")
2532 .notNull()
2533 .references(() => repositories.id, { onDelete: "cascade" }),
2534 advisoryId: uuid("advisory_id")
2535 .notNull()
2536 .references(() => securityAdvisories.id, { onDelete: "cascade" }),
2537 dependencyName: text("dependency_name").notNull(),
2538 dependencyVersion: text("dependency_version"),
2539 manifestPath: text("manifest_path").notNull(),
2540 status: text("status").default("open").notNull(),
2541 dismissedReason: text("dismissed_reason"),
2542 createdAt: timestamp("created_at").defaultNow().notNull(),
2543 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2544 },
2545 (table) => [
2546 index("repo_advisory_alerts_status_idx").on(
2547 table.repositoryId,
2548 table.status
2549 ),
2550 ]
2551);
2552
2553export type RepoAdvisoryAlert = typeof repoAdvisoryAlerts.$inferSelect;
3951454Claude2554
2555// ----------------------------------------------------------------------------
2556// Block J3 — Commit signature verification (GPG + SSH)
2557// ----------------------------------------------------------------------------
2558
2559/** Per-user GPG/SSH public keys for commit signing. */
2560export const signingKeys = pgTable(
2561 "signing_keys",
2562 {
2563 id: uuid("id").primaryKey().defaultRandom(),
2564 userId: uuid("user_id")
2565 .notNull()
2566 .references(() => users.id, { onDelete: "cascade" }),
2567 keyType: text("key_type").notNull(), // 'gpg' | 'ssh'
2568 title: text("title").notNull(),
2569 fingerprint: text("fingerprint").notNull(),
2570 publicKey: text("public_key").notNull(),
2571 email: text("email"),
2572 expiresAt: timestamp("expires_at"),
2573 lastUsedAt: timestamp("last_used_at"),
2574 createdAt: timestamp("created_at").defaultNow().notNull(),
2575 },
2576 (table) => [
2577 uniqueIndex("signing_keys_fp_unique").on(table.keyType, table.fingerprint),
2578 index("signing_keys_user_idx").on(table.userId),
2579 ]
2580);
2581
2582export type SigningKey = typeof signingKeys.$inferSelect;
2583
2584/**
2585 * Cached verification result for a (repo, commit) pair. Repopulated on demand;
2586 * rows are invalidated implicitly by CASCADE when either side is removed.
2587 */
2588export const commitVerifications = pgTable(
2589 "commit_verifications",
2590 {
2591 id: uuid("id").primaryKey().defaultRandom(),
2592 repositoryId: uuid("repository_id")
2593 .notNull()
2594 .references(() => repositories.id, { onDelete: "cascade" }),
2595 commitSha: text("commit_sha").notNull(),
2596 verified: boolean("verified").default(false).notNull(),
2597 reason: text("reason").notNull(),
2598 signatureType: text("signature_type"),
2599 signerKeyId: uuid("signer_key_id").references(() => signingKeys.id, {
2600 onDelete: "set null",
2601 }),
2602 signerUserId: uuid("signer_user_id").references(() => users.id, {
2603 onDelete: "set null",
2604 }),
2605 signerFingerprint: text("signer_fingerprint"),
2606 verifiedAt: timestamp("verified_at").defaultNow().notNull(),
2607 },
2608 (table) => [
2609 uniqueIndex("commit_verifications_sha_unique").on(
2610 table.repositoryId,
2611 table.commitSha
2612 ),
2613 ]
2614);
2615
2616export type CommitVerification = typeof commitVerifications.$inferSelect;
7aa8b99Claude2617
2618// ----------------------------------------------------------------------------
2619// Block J4 — User following
2620// ----------------------------------------------------------------------------
2621
2622/**
2623 * Directed user→user follow edges. Primary key is the composite
2624 * (follower_id, following_id) at the SQL level; drizzle sees it as a
2625 * regular table with a unique index plus a secondary index on the
2626 * reverse-lookup column.
2627 */
2628export const userFollows = pgTable(
2629 "user_follows",
2630 {
2631 followerId: uuid("follower_id")
2632 .notNull()
2633 .references(() => users.id, { onDelete: "cascade" }),
2634 followingId: uuid("following_id")
2635 .notNull()
2636 .references(() => users.id, { onDelete: "cascade" }),
2637 createdAt: timestamp("created_at").defaultNow().notNull(),
2638 },
2639 (table) => [
2640 uniqueIndex("user_follows_pair_unique").on(
2641 table.followerId,
2642 table.followingId
2643 ),
2644 index("user_follows_following_idx").on(table.followingId),
2645 ]
2646);
2647
2648export type UserFollow = typeof userFollows.$inferSelect;
9ff7128Claude2649
2650// ----------------------------------------------------------------------------
2651// Block J6 — Repository rulesets
2652// ----------------------------------------------------------------------------
2653
2654/**
2655 * A ruleset groups N rules under a named policy at enforcement level active /
2656 * evaluate / disabled. Unique per (repo, name) so a repo can carry multiple
2657 * overlapping rulesets (e.g. "release branches" vs "everywhere").
2658 */
2659export const repoRulesets = pgTable(
2660 "repo_rulesets",
2661 {
2662 id: uuid("id").primaryKey().defaultRandom(),
2663 repositoryId: uuid("repository_id")
2664 .notNull()
2665 .references(() => repositories.id, { onDelete: "cascade" }),
2666 name: text("name").notNull(),
2667 enforcement: text("enforcement").default("active").notNull(),
2668 createdBy: uuid("created_by").references(() => users.id, {
2669 onDelete: "set null",
2670 }),
2671 createdAt: timestamp("created_at").defaultNow().notNull(),
2672 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2673 },
2674 (table) => [
2675 index("repo_rulesets_repo_idx").on(table.repositoryId),
2676 uniqueIndex("repo_rulesets_repo_name_unique").on(
2677 table.repositoryId,
2678 table.name
2679 ),
2680 ]
2681);
2682
2683export type RepoRuleset = typeof repoRulesets.$inferSelect;
2684
2685/** Individual rule — type tag plus JSON params. */
2686export const rulesetRules = pgTable(
2687 "ruleset_rules",
2688 {
2689 id: uuid("id").primaryKey().defaultRandom(),
2690 rulesetId: uuid("ruleset_id")
2691 .notNull()
2692 .references(() => repoRulesets.id, { onDelete: "cascade" }),
2693 ruleType: text("rule_type").notNull(),
2694 params: text("params").default("{}").notNull(),
2695 createdAt: timestamp("created_at").defaultNow().notNull(),
2696 },
2697 (table) => [index("ruleset_rules_set_idx").on(table.rulesetId)]
2698);
2699
2700export type RulesetRule = typeof rulesetRules.$inferSelect;
0cdfd89Claude2701
2702// ---------------------------------------------------------------------------
2703// Block J8 — Commit statuses.
2704// ---------------------------------------------------------------------------
2705
2706/**
2707 * External CI / automation posts per-commit (sha, context) statuses. Upsert
2708 * semantics keyed on (repository, commit_sha, context). State vocabulary:
2709 * pending | success | failure | error. Combined rollup logic lives in
2710 * `src/lib/commit-statuses.ts`.
2711 */
2712export const commitStatuses = pgTable(
2713 "commit_statuses",
2714 {
2715 id: uuid("id").primaryKey().defaultRandom(),
2716 repositoryId: uuid("repository_id")
2717 .notNull()
2718 .references(() => repositories.id, { onDelete: "cascade" }),
2719 commitSha: text("commit_sha").notNull(),
2720 state: text("state").notNull(),
2721 context: text("context").default("default").notNull(),
2722 description: text("description"),
2723 targetUrl: text("target_url"),
2724 creatorId: uuid("creator_id").references(() => users.id, {
2725 onDelete: "set null",
2726 }),
2727 createdAt: timestamp("created_at").defaultNow().notNull(),
2728 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2729 },
2730 (table) => [
2731 uniqueIndex("commit_statuses_repo_sha_context_unique").on(
2732 table.repositoryId,
2733 table.commitSha,
2734 table.context
2735 ),
2736 index("commit_statuses_repo_sha_idx").on(
2737 table.repositoryId,
2738 table.commitSha
2739 ),
2740 ]
2741);
2742
2743export type CommitStatus = typeof commitStatuses.$inferSelect;
23d1a81Claude2744
2745// ---------------------------------------------------------------------------
2746// Collaborators — per-repo role grants (read / write / admin).
2747// ---------------------------------------------------------------------------
2748
2749/**
2750 * A user granted access to a repository beyond ownership. Roles are
2751 * hierarchical — 'admin' implies write, write implies read. `invitedBy` tracks
2752 * who added them (nullable once that user is deleted); `acceptedAt` is null
2753 * until the invitee explicitly accepts. Unique per (repo, user) so a given
2754 * user has at most one role per repo.
2755 */
2756export const repoCollaborators = pgTable(
2757 "repo_collaborators",
2758 {
2759 id: uuid("id").primaryKey().defaultRandom(),
2760 repositoryId: uuid("repository_id")
2761 .notNull()
2762 .references(() => repositories.id, { onDelete: "cascade" }),
2763 userId: uuid("user_id")
2764 .notNull()
2765 .references(() => users.id, { onDelete: "cascade" }),
2766 role: text("role", { enum: ["read", "write", "admin"] })
2767 .notNull()
2768 .default("read"),
2769 invitedBy: uuid("invited_by").references(() => users.id, {
2770 onDelete: "set null",
2771 }),
2772 invitedAt: timestamp("invited_at").defaultNow().notNull(),
2773 acceptedAt: timestamp("accepted_at"),
febd4f0Claude2774 // sha256(plaintext) of the outstanding invite token. Set when the owner
2775 // sends an invite, cleared when the invitee accepts. NULL on older rows
2776 // that were auto-accepted before the email flow existed.
2777 inviteTokenHash: text("invite_token_hash"),
23d1a81Claude2778 },
2779 (table) => [
2780 uniqueIndex("repo_collaborators_repo_user_uq").on(
2781 table.repositoryId,
2782 table.userId
2783 ),
2784 index("repo_collaborators_repo_idx").on(table.repositoryId),
2785 index("repo_collaborators_user_idx").on(table.userId),
2786 ]
2787);
2788
2789export type RepoCollaborator = typeof repoCollaborators.$inferSelect;
abfa9adClaude2790
2791// ---------------------------------------------------------------------------
2792// Workflow engine v2 — Sprint 1 additions (drizzle/0037_workflow_engine_v2.sql)
2793//
2794// Strictly additive to Block C1. The original workflow tables defined above
2795// (workflows / workflow_runs / workflow_jobs / workflow_artifacts) are locked
2796// and must not be altered in-place; the four tables below extend the runner
2797// with secrets, workflow_dispatch inputs, a content-addressable cache, and a
2798// warm-runner worker pool.
2799// ---------------------------------------------------------------------------
2800
2801/**
2802 * Per-repo encrypted secrets exposed to workflow jobs as env vars.
2803 *
2804 * `encrypted_value` is base64 of `iv || authTag || ciphertext` produced by
2805 * AES-256-GCM — the crypto lives in `src/lib/workflow-crypto.ts` (Agent 2);
2806 * the DB only stores opaque ciphertext. `name` is validated against
2807 * `[A-Z_][A-Z0-9_]*` at the write-site, not the DB. Unique per (repo, name).
2808 */
2809export const workflowSecrets = pgTable(
2810 "workflow_secrets",
2811 {
2812 id: uuid("id").primaryKey().defaultRandom(),
2813 repositoryId: uuid("repository_id")
2814 .notNull()
2815 .references(() => repositories.id, { onDelete: "cascade" }),
2816 name: text("name").notNull(),
2817 encryptedValue: text("encrypted_value").notNull(),
2818 createdBy: uuid("created_by").references(() => users.id, {
2819 onDelete: "set null",
2820 }),
2821 createdAt: timestamp("created_at").defaultNow().notNull(),
2822 updatedAt: timestamp("updated_at").defaultNow().notNull(),
2823 },
2824 (table) => [
2825 uniqueIndex("workflow_secrets_repo_name_uq").on(
2826 table.repositoryId,
2827 table.name
2828 ),
2829 index("workflow_secrets_repo_idx").on(table.repositoryId),
2830 ]
2831);
2832
2833export type WorkflowSecret = typeof workflowSecrets.$inferSelect;
2834export type NewWorkflowSecret = typeof workflowSecrets.$inferInsert;
2835
2836/**
2837 * Parameter schema for the `workflow_dispatch` trigger. One row per input
2838 * declared in the workflow YAML. `type` is constrained to the four values
2839 * GitHub Actions supports; `options` is only meaningful for type='choice'
2840 * (a JSON array of allowed strings). `default_value` and `description` are
2841 * optional. Unique per (workflow, name) so two inputs on the same workflow
2842 * can't share an identifier.
2843 */
2844export const workflowDispatchInputs = pgTable(
2845 "workflow_dispatch_inputs",
2846 {
2847 id: uuid("id").primaryKey().defaultRandom(),
2848 workflowId: uuid("workflow_id")
2849 .notNull()
2850 .references(() => workflows.id, { onDelete: "cascade" }),
2851 name: text("name").notNull(),
2852 type: text("type", {
2853 enum: ["string", "boolean", "choice", "number"],
2854 }).notNull(),
2855 required: boolean("required").default(false).notNull(),
2856 defaultValue: text("default_value"),
2857 // JSON array of strings; only populated when type = 'choice'.
2858 options: jsonb("options"),
2859 description: text("description"),
2860 },
2861 (table) => [
2862 uniqueIndex("workflow_dispatch_inputs_wf_name_uq").on(
2863 table.workflowId,
2864 table.name
2865 ),
2866 ]
2867);
2868
2869export type WorkflowDispatchInput =
2870 typeof workflowDispatchInputs.$inferSelect;
2871export type NewWorkflowDispatchInput =
2872 typeof workflowDispatchInputs.$inferInsert;
2873
2874/**
2875 * Content-addressable cache backing the `gluecron/cache@v1` action. Rows are
2876 * keyed by user-chosen `cache_key` within a `scope` — 'repo' for repo-wide
2877 * entries, 'branch' or 'tag' when isolation is desired (with `scope_ref`
2878 * holding the branch/tag name). `content_hash` is the sha256 of `content`
2879 * so jobs can short-circuit redundant writes. `content` is real bytea; the
2880 * 100MB payload cap is enforced at the write-site, not by the DB. LRU
2881 * eviction reads (`repository_id`, `last_accessed_at`).
2882 */
2883export const workflowRunCache = pgTable(
2884 "workflow_run_cache",
2885 {
2886 id: uuid("id").primaryKey().defaultRandom(),
2887 repositoryId: uuid("repository_id")
2888 .notNull()
2889 .references(() => repositories.id, { onDelete: "cascade" }),
2890 cacheKey: text("cache_key").notNull(),
2891 // 'repo' | 'branch' | 'tag' — constraint enforced at the write-site.
2892 scope: text("scope").default("repo").notNull(),
2893 scopeRef: text("scope_ref"),
2894 contentHash: text("content_hash").notNull(),
2895 content: bytea("content").notNull(),
2896 sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
2897 createdAt: timestamp("created_at").defaultNow().notNull(),
2898 lastAccessedAt: timestamp("last_accessed_at").defaultNow().notNull(),
2899 },
2900 (table) => [
2901 uniqueIndex("workflow_run_cache_repo_key_scope_uq").on(
2902 table.repositoryId,
2903 table.cacheKey,
2904 table.scope,
2905 table.scopeRef
2906 ),
2907 index("workflow_run_cache_repo_lru_idx").on(
2908 table.repositoryId,
2909 table.lastAccessedAt
2910 ),
2911 ]
2912);
2913
2914export type WorkflowRunCache = typeof workflowRunCache.$inferSelect;
2915export type NewWorkflowRunCache = typeof workflowRunCache.$inferInsert;
2916
2917/**
2918 * Warm-runner worker registry. The scheduler reads idle rows to dispatch
2919 * queued jobs without paying cold-start cost; workers heartbeat here so
2920 * stale entries (>N seconds since `last_heartbeat_at`) can be reaped.
2921 * `worker_id` is a stable string (hostname:pid or similar) and is globally
2922 * unique so a restarted worker naturally replaces its predecessor.
2923 * `current_run_id` is set when status='busy' and cleared on completion.
2924 */
2925export const workflowRunnerPool = pgTable(
2926 "workflow_runner_pool",
2927 {
2928 id: uuid("id").primaryKey().defaultRandom(),
2929 workerId: text("worker_id").notNull().unique(),
2930 status: text("status", {
2931 enum: ["idle", "busy", "draining", "dead"],
2932 }).notNull(),
2933 currentRunId: uuid("current_run_id").references(() => workflowRuns.id, {
2934 onDelete: "set null",
2935 }),
2936 warmedAt: timestamp("warmed_at").defaultNow().notNull(),
2937 lastHeartbeatAt: timestamp("last_heartbeat_at").defaultNow().notNull(),
2938 capacity: integer("capacity").default(1).notNull(),
2939 },
2940 (table) => [index("workflow_runner_pool_status_idx").on(table.status)]
2941);
2942
2943export type WorkflowRunnerPoolEntry =
2944 typeof workflowRunnerPool.$inferSelect;
2945export type NewWorkflowRunnerPoolEntry =
2946 typeof workflowRunnerPool.$inferInsert;
e6bad81Claude2947
2948
2949/**
2950 * Repair Flywheel — every auto-repair attempt is recorded here so future
2951 * failures with the same signature can short-circuit straight to the cached
2952 * patch (Tier 0). After ~5000 entries the cache dominates and AI calls drop.
2953 * Migration: 0039_repair_flywheel.sql
2954 */
2955export const repairFlywheel = pgTable(
2956 "repair_flywheel",
2957 {
2958 id: uuid("id").primaryKey().defaultRandom(),
2959 repositoryId: uuid("repository_id").references(() => repositories.id, {
2960 onDelete: "cascade",
2961 }),
2962 // Fingerprint of the normalised failure text (variables/paths stripped).
2963 failureSignature: text("failure_signature").notNull(),
2964 // Original failure text (capped at write-site, ~4KB).
2965 failureText: text("failure_text").notNull(),
2966 // Mechanical classification or NULL if AI/human-driven.
2967 failureClassification: text("failure_classification"),
2968 // 'cached' | 'mechanical' | 'ai-sonnet' | 'human'
2969 repairTier: text("repair_tier").notNull(),
2970 patchSummary: text("patch_summary").notNull(),
2971 filesChanged: jsonb("files_changed").notNull().default([]),
2972 commitSha: text("commit_sha"),
2973 // 'pending' | 'success' | 'failed' | 'reverted'
2974 outcome: text("outcome").notNull().default("pending"),
2975 appliedAt: timestamp("applied_at").defaultNow().notNull(),
2976 outcomeAt: timestamp("outcome_at"),
2977 parentPatternId: uuid("parent_pattern_id"),
2978 cacheHitCount: integer("cache_hit_count").default(0).notNull(),
2979 isPublicPattern: boolean("is_public_pattern").default(false).notNull(),
2980 createdAt: timestamp("created_at").defaultNow().notNull(),
2981 },
2982 (table) => [
2983 index("repair_flywheel_signature_idx").on(table.failureSignature),
2984 index("repair_flywheel_repo_idx").on(table.repositoryId),
2985 index("repair_flywheel_outcome_idx").on(table.outcome),
2986 index("repair_flywheel_classification_idx").on(table.failureClassification),
2987 index("repair_flywheel_lookup_idx").on(
2988 table.repositoryId,
2989 table.failureSignature,
2990 table.outcome
2991 ),
2992 ]
2993);
2994
2995export type RepairFlywheelEntry = typeof repairFlywheel.$inferSelect;
2996export type NewRepairFlywheelEntry = typeof repairFlywheel.$inferInsert;
2997
534f04aClaude2998/**
2999 * Block M3 — AI pre-merge risk score cache.
3000 *
3001 * One row per (pull_request_id, commit_sha). The score is computed by a
3002 * transparent formula over `signals`; the LLM only writes `ai_summary`.
3003 * Pinning by head SHA means a new push invalidates the cache implicitly
3004 * (the new SHA won't have a row yet → cache miss → recompute).
3005 *
3006 * Migration: 0044_pr_risk_scores.sql
3007 */
3008export const prRiskScores = pgTable(
3009 "pr_risk_scores",
3010 {
3011 id: uuid("id").primaryKey().defaultRandom(),
3012 pullRequestId: uuid("pull_request_id")
3013 .notNull()
3014 .references(() => pullRequests.id, { onDelete: "cascade" }),
3015 commitSha: text("commit_sha").notNull(),
3016 // 0..10 integer score.
3017 score: integer("score").notNull(),
3018 // 'low' | 'medium' | 'high' | 'critical'
3019 band: text("band").notNull(),
3020 // Raw signal map — see PrRiskSignals in src/lib/pr-risk.ts.
3021 signals: jsonb("signals").notNull(),
3022 aiSummary: text("ai_summary"),
3023 generatedAt: timestamp("generated_at", { withTimezone: true })
3024 .defaultNow()
3025 .notNull(),
3026 },
3027 (table) => [
3028 uniqueIndex("pr_risk_scores_pr_sha_uq").on(
3029 table.pullRequestId,
3030 table.commitSha
3031 ),
3032 index("pr_risk_scores_pr_idx").on(table.pullRequestId),
3033 ]
3034);
3035
3036export type PrRiskScoreRow = typeof prRiskScores.$inferSelect;
3037export type NewPrRiskScoreRow = typeof prRiskScores.$inferInsert;
3038
c63b860Claude3039/**
3040 * Block P1 — Password reset tokens.
3041 *
3042 * One row per outstanding reset request. `tokenHash` is a SHA-256 of the
3043 * plaintext token mailed to the user; the plaintext never persists.
3044 * `usedAt` is flipped on consume so a replayed link cannot rotate the
3045 * password twice. `expiresAt` is enforced at consume time (1-hour TTL).
3046 *
3047 * Migration: 0047_password_reset_tokens.sql
3048 */
3049export const passwordResetTokens = pgTable(
3050 "password_reset_tokens",
3051 {
3052 id: uuid("id").primaryKey().defaultRandom(),
3053 userId: uuid("user_id")
3054 .notNull()
3055 .references(() => users.id, { onDelete: "cascade" }),
3056 tokenHash: text("token_hash").notNull().unique(),
3057 expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
3058 usedAt: timestamp("used_at", { withTimezone: true }),
3059 requestIp: text("request_ip"),
3060 createdAt: timestamp("created_at", { withTimezone: true })
3061 .defaultNow()
3062 .notNull(),
3063 },
3064 (table) => [
3065 index("idx_password_reset_tokens_user").on(table.userId),
3066 index("idx_password_reset_tokens_expires").on(table.expiresAt),
3067 ]
3068);
3069
3070export type PasswordResetToken = typeof passwordResetTokens.$inferSelect;
3071export type NewPasswordResetToken = typeof passwordResetTokens.$inferInsert;
3072
3073/**
3074 * Block P2 — email verification tokens.
3075 *
3076 * SHA-256 hashed at rest. `email` captured at issuance so a verification
3077 * link still resolves the right address even after a profile-email change.
3078 * Migration: drizzle/0048_email_verification.sql
3079 */
3080export const emailVerificationTokens = pgTable(
3081 "email_verification_tokens",
3082 {
3083 id: uuid("id").primaryKey().defaultRandom(),
3084 userId: uuid("user_id")
3085 .notNull()
3086 .references(() => users.id, { onDelete: "cascade" }),
3087 email: text("email").notNull(),
3088 tokenHash: text("token_hash").notNull().unique(),
3089 expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
3090 usedAt: timestamp("used_at", { withTimezone: true }),
3091 createdAt: timestamp("created_at", { withTimezone: true })
3092 .defaultNow()
3093 .notNull(),
3094 },
3095 (table) => [index("idx_email_verify_tokens_user").on(table.userId)]
3096);
3097
3098export type EmailVerificationToken = typeof emailVerificationTokens.$inferSelect;
3099export type NewEmailVerificationToken = typeof emailVerificationTokens.$inferInsert;
3100
cd4f63bTest User3101/**
3102 * Block Q2 — Magic-link sign-in tokens.
3103 *
3104 * Structurally identical to passwordResetTokens / emailVerificationTokens:
3105 * a short plaintext token is mailed to the user, only its sha256 hash is
3106 * persisted, the token is single-use (usedAt) and time-limited (expiresAt).
3107 *
3108 * Difference: `userId` is NULLABLE. When a user enters an email that does
3109 * NOT yet have an account, we still mint a row — consume will create the
3110 * account on click (autoCreate=true), using the click itself as proof the
3111 * recipient owns the address. See `src/lib/magic-link.ts`.
3112 *
3113 * Migration: drizzle/0051_magic_link_tokens.sql
3114 */
3115export const magicLinkTokens = pgTable(
3116 "magic_link_tokens",
3117 {
3118 id: uuid("id").primaryKey().defaultRandom(),
3119 email: text("email").notNull(),
3120 userId: uuid("user_id").references(() => users.id, { onDelete: "cascade" }),
3121 tokenHash: text("token_hash").notNull().unique(),
3122 expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
3123 usedAt: timestamp("used_at", { withTimezone: true }),
3124 requestIp: text("request_ip"),
3125 createdAt: timestamp("created_at", { withTimezone: true })
3126 .defaultNow()
3127 .notNull(),
3128 },
3129 (table) => [
3130 index("idx_magic_link_tokens_email").on(table.email),
3131 index("idx_magic_link_tokens_user").on(table.userId),
3132 index("idx_magic_link_tokens_expires").on(table.expiresAt),
3133 ]
3134);
3135
3136export type MagicLinkToken = typeof magicLinkTokens.$inferSelect;
3137export type NewMagicLinkToken = typeof magicLinkTokens.$inferInsert;
3138
b1be050CC LABS App3139// ---------------------------------------------------------------------------
3140// BLOCK S4 — Synthetic monitor history.
3141//
3142// Every autopilot tick runs `runSyntheticChecks()` (see
3143// `src/lib/synthetic-monitor.ts`) and inserts one row per check here.
3144// The /admin/status page reads the most-recent row per check_name and
3145// renders the red/green dashboard. On a green->red transition we fire
3146// MONITOR_ALERT_WEBHOOK_URL so the owner sees the site is on fire.
3147// ---------------------------------------------------------------------------
3148export const syntheticChecks = pgTable(
3149 "synthetic_checks",
3150 {
3151 id: uuid("id").primaryKey().defaultRandom(),
3152 checkName: text("check_name").notNull(),
3153 status: text("status").notNull(), // "green" | "red" | "yellow"
3154 statusCode: integer("status_code"),
3155 durationMs: integer("duration_ms").notNull(),
3156 error: text("error"),
3157 checkedAt: timestamp("checked_at", { withTimezone: true })
3158 .defaultNow()
3159 .notNull(),
3160 },
3161 (table) => [
3162 index("idx_synthetic_checks_checked_at").on(table.checkedAt),
3163 index("idx_synthetic_checks_name_checked_at").on(
3164 table.checkName,
3165 table.checkedAt
3166 ),
3167 ]
3168);
3169
3170export type SyntheticCheckRow = typeof syntheticChecks.$inferSelect;
3171export type NewSyntheticCheckRow = typeof syntheticChecks.$inferInsert;
3172
a686079Claude3173// ---------------------------------------------------------------------------
3174// 0057 — Continuous semantic index (per-push embeddings).
e75eddcClaude3175// One row per (repository_id, file_path). `indexChangedFiles()` upserts on
3176// every push, `searchSemantic()` ranks by cosine distance via pgvector.
a686079Claude3177// ---------------------------------------------------------------------------
3178export const codeEmbeddings = pgTable(
3179 "code_embeddings",
3180 {
3181 id: uuid("id").primaryKey().defaultRandom(),
3182 repositoryId: uuid("repository_id")
3183 .notNull()
3184 .references(() => repositories.id, { onDelete: "cascade" }),
3185 filePath: text("file_path").notNull(),
3186 blobSha: text("blob_sha").notNull(),
3187 commitSha: text("commit_sha").notNull(),
3188 contentSnippet: text("content_snippet").notNull().default(""),
3189 embedding: vector("embedding", { dimensions: 1024 }),
3190 embeddingModel: text("embedding_model"),
3191 updatedAt: timestamp("updated_at", { withTimezone: true })
3192 .defaultNow()
3193 .notNull(),
3194 },
3195 (table) => [
3196 uniqueIndex("code_embeddings_repo_path_uniq").on(
3197 table.repositoryId,
3198 table.filePath
3199 ),
3200 index("code_embeddings_repo_idx").on(table.repositoryId),
3201 ]
3202);
3203
3204export type CodeEmbedding = typeof codeEmbeddings.$inferSelect;
3205export type NewCodeEmbedding = typeof codeEmbeddings.$inferInsert;
3206
e75eddcClaude3207// ---------------------------------------------------------------------------
3208// 0058 — Agent multiplayer v1: per-agent namespacing + leases + budget caps.
3209// See src/lib/agent-multiplayer.ts for helpers and 0058_agent_multiplayer.sql
3210// for the canonical column docs. UNIQUE partial index on (target_type,
3211// target_id) WHERE status='active' is enforced in SQL (drizzle exposes it
3212// as a regular index here).
3213// ---------------------------------------------------------------------------
3214export const agentSessions = pgTable(
3215 "agent_sessions",
3216 {
3217 id: uuid("id").primaryKey().defaultRandom(),
3218 name: text("name").notNull(),
3219 ownerUserId: uuid("owner_user_id")
3220 .notNull()
3221 .references(() => users.id, { onDelete: "cascade" }),
3222 repositoryId: uuid("repository_id").references(() => repositories.id, {
3223 onDelete: "cascade",
3224 }),
3225 tokenHash: text("token_hash").notNull().unique(),
3226 branchNamespace: text("branch_namespace").notNull(),
3227 budgetCentsPerDay: integer("budget_cents_per_day").default(500).notNull(),
3228 spentCentsToday: integer("spent_cents_today").default(0).notNull(),
3229 lastActiveAt: timestamp("last_active_at", { withTimezone: true }),
3230 createdAt: timestamp("created_at", { withTimezone: true })
3231 .defaultNow()
3232 .notNull(),
3233 },
3234 (table) => [
3235 uniqueIndex("agent_sessions_owner_name").on(table.ownerUserId, table.name),
3236 index("agent_sessions_owner").on(table.ownerUserId),
3237 index("agent_sessions_repo").on(table.repositoryId),
3238 ]
3239);
3240
3241export const agentLeases = pgTable(
3242 "agent_leases",
3243 {
3244 id: uuid("id").primaryKey().defaultRandom(),
3245 agentSessionId: uuid("agent_session_id")
3246 .notNull()
3247 .references(() => agentSessions.id, { onDelete: "cascade" }),
3248 targetType: text("target_type").notNull(),
3249 targetId: text("target_id").notNull(),
3250 acquiredAt: timestamp("acquired_at", { withTimezone: true })
3251 .defaultNow()
3252 .notNull(),
3253 expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
3254 status: text("status").default("active").notNull(),
3255 createdAt: timestamp("created_at", { withTimezone: true })
3256 .defaultNow()
3257 .notNull(),
3258 },
3259 (table) => [
3260 index("agent_leases_active_target").on(table.targetType, table.targetId),
3261 index("agent_leases_agent").on(table.agentSessionId, table.status),
3262 index("agent_leases_expires").on(table.expiresAt),
3263 ]
3264);
3265
3266export type AgentSession = typeof agentSessions.$inferSelect;
3267export type NewAgentSession = typeof agentSessions.$inferInsert;
3268export type AgentLease = typeof agentLeases.$inferSelect;
3269export type NewAgentLease = typeof agentLeases.$inferInsert;
3270
38d31d3Claude3271// ---------------------------------------------------------------------------
3c03977Claude3272// 0060 — AI repo rubber-duck chat. See src/lib/repo-chat.ts.
38d31d3Claude3273// ---------------------------------------------------------------------------
3274export const repoChats = pgTable(
3275 "repo_chats",
3276 {
3277 id: uuid("id").primaryKey().defaultRandom(),
3278 repositoryId: uuid("repository_id")
3279 .notNull()
3280 .references(() => repositories.id, { onDelete: "cascade" }),
3281 ownerUserId: uuid("owner_user_id")
3282 .notNull()
3283 .references(() => users.id, { onDelete: "cascade" }),
3284 title: text("title"),
3285 createdAt: timestamp("created_at", { withTimezone: true })
3286 .defaultNow()
3287 .notNull(),
3288 updatedAt: timestamp("updated_at", { withTimezone: true })
3289 .defaultNow()
3290 .notNull(),
3291 },
3292 (table) => [
3293 index("repo_chats_owner_updated").on(table.ownerUserId, table.updatedAt),
3294 index("repo_chats_repo").on(table.repositoryId),
3295 ]
3296);
3297
3298export const repoChatMessages = pgTable(
3299 "repo_chat_messages",
3300 {
3301 id: uuid("id").primaryKey().defaultRandom(),
3302 chatId: uuid("chat_id")
3303 .notNull()
3304 .references(() => repoChats.id, { onDelete: "cascade" }),
3305 role: text("role").notNull(),
3306 content: text("content").notNull(),
3307 citations: jsonb("citations").$type<Array<{ file_path: string; blob_sha: string }>>().notNull().default([]),
3308 tokenCost: integer("token_cost").notNull().default(0),
3309 createdAt: timestamp("created_at", { withTimezone: true })
3310 .defaultNow()
3311 .notNull(),
3312 },
3313 (table) => [
3314 index("repo_chat_messages_chat_created").on(table.chatId, table.createdAt),
3315 ]
3316);
3317
3318export type RepoChat = typeof repoChats.$inferSelect;
3319export type NewRepoChat = typeof repoChats.$inferInsert;
3320export type RepoChatMessage = typeof repoChatMessages.$inferSelect;
3321export type NewRepoChatMessage = typeof repoChatMessages.$inferInsert;
3322
ee7e577Claude3323// ---------------------------------------------------------------------------
3324// 0071 — Personal cross-repo chat. Same shape as repoChats/repoChatMessages
3325// but user-scoped, not repo-scoped. The retrieval layer
3326// (src/lib/personal-semantic.ts) runs searchSemantic across the union of
3327// repos the owner has access to, then attaches a repo_name annotation to
3328// each citation. Gated on users.personalSemanticIndexEnabled.
3329// ---------------------------------------------------------------------------
3330export const personalChats = pgTable(
3331 "personal_chats",
3332 {
3333 id: uuid("id").primaryKey().defaultRandom(),
3334 ownerUserId: uuid("owner_user_id")
3335 .notNull()
3336 .references(() => users.id, { onDelete: "cascade" }),
3337 title: text("title"),
3338 createdAt: timestamp("created_at", { withTimezone: true })
3339 .defaultNow()
3340 .notNull(),
3341 updatedAt: timestamp("updated_at", { withTimezone: true })
3342 .defaultNow()
3343 .notNull(),
3344 },
3345 (table) => [
3346 index("personal_chats_owner_updated").on(
3347 table.ownerUserId,
3348 table.updatedAt
3349 ),
3350 ]
3351);
3352
3353export const personalChatMessages = pgTable(
3354 "personal_chat_messages",
3355 {
3356 id: uuid("id").primaryKey().defaultRandom(),
3357 chatId: uuid("chat_id")
3358 .notNull()
3359 .references(() => personalChats.id, { onDelete: "cascade" }),
3360 role: text("role").notNull(),
3361 content: text("content").notNull(),
3362 citations: jsonb("citations")
3363 .$type<
3364 Array<{ file_path: string; blob_sha: string; repo_name: string }>
3365 >()
3366 .notNull()
3367 .default([]),
3368 tokenCost: integer("token_cost").notNull().default(0),
3369 createdAt: timestamp("created_at", { withTimezone: true })
3370 .defaultNow()
3371 .notNull(),
3372 },
3373 (table) => [
3374 index("personal_chat_messages_chat_created").on(
3375 table.chatId,
3376 table.createdAt
3377 ),
3378 ]
3379);
3380
3381export type PersonalChat = typeof personalChats.$inferSelect;
3382export type NewPersonalChat = typeof personalChats.$inferInsert;
3383export type PersonalChatMessage = typeof personalChatMessages.$inferSelect;
3384export type NewPersonalChatMessage = typeof personalChatMessages.$inferInsert;
3385
3c03977Claude3386// ---------------------------------------------------------------------------
3387// 0061 — Live co-editing on PRs. See src/lib/pr-live.ts.
3388// ---------------------------------------------------------------------------
3389export const prLiveSessions = pgTable(
3390 "pr_live_sessions",
3391 {
3392 id: uuid("id").primaryKey().defaultRandom(),
3393 prId: uuid("pr_id")
3394 .notNull()
3395 .references(() => pullRequests.id, { onDelete: "cascade" }),
3396 userId: uuid("user_id").references(() => users.id, {
3397 onDelete: "cascade",
3398 }),
3399 agentSessionId: uuid("agent_session_id").references(
3400 () => agentSessions.id,
3401 { onDelete: "cascade" }
3402 ),
3403 cursorPosition: jsonb("cursor_position"),
3404 color: text("color").notNull(),
3405 joinedAt: timestamp("joined_at", { withTimezone: true })
3406 .defaultNow()
3407 .notNull(),
3408 lastSeenAt: timestamp("last_seen_at", { withTimezone: true })
3409 .defaultNow()
3410 .notNull(),
3411 status: text("status").default("active").notNull(),
3412 },
3413 (table) => [
3414 index("pr_live_sessions_active_pr").on(table.prId, table.lastSeenAt),
3415 index("pr_live_sessions_status_seen").on(table.status, table.lastSeenAt),
3416 ]
3417);
3418
3419export type PrLiveSession = typeof prLiveSessions.$inferSelect;
3420export type NewPrLiveSession = typeof prLiveSessions.$inferInsert;
3421
4bbacbeClaude3422// ---------------------------------------------------------------------------
3423// ---------------------------------------------------------------------------
23d0abfClaude3424// Migration 0062 — per-branch preview URLs. See src/lib/branch-previews.ts.
3425// ---------------------------------------------------------------------------
4bbacbeClaude3426export const branchPreviews = pgTable(
3427 "branch_previews",
3428 {
3429 id: uuid("id").primaryKey().defaultRandom(),
3430 repositoryId: uuid("repository_id")
3431 .notNull()
3432 .references(() => repositories.id, { onDelete: "cascade" }),
3433 branchName: text("branch_name").notNull(),
3434 commitSha: text("commit_sha").notNull(),
3435 previewUrl: text("preview_url").notNull(),
3436 status: text("status").default("building").notNull(),
3437 buildStartedAt: timestamp("build_started_at", { withTimezone: true })
3438 .defaultNow()
3439 .notNull(),
3440 buildCompletedAt: timestamp("build_completed_at", { withTimezone: true }),
3441 expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
3442 errorMessage: text("error_message"),
3443 createdAt: timestamp("created_at", { withTimezone: true })
3444 .defaultNow()
3445 .notNull(),
3446 },
3447 (table) => [
3448 uniqueIndex("branch_previews_repo_branch").on(
3449 table.repositoryId,
3450 table.branchName
3451 ),
3452 index("branch_previews_repo_status").on(table.repositoryId, table.status),
3453 ]
3454);
3455
3456export type BranchPreview = typeof branchPreviews.$inferSelect;
3457export type NewBranchPreview = typeof branchPreviews.$inferInsert;
3458
23d0abfClaude3459// ---------------------------------------------------------------------------
3460// 0063 — Multi-repo refactor agent. See src/lib/multi-repo-refactor.ts.
3461// ---------------------------------------------------------------------------
3462export const multiRepoRefactors = pgTable(
3463 "multi_repo_refactors",
3464 {
3465 id: uuid("id").primaryKey().defaultRandom(),
3466 ownerUserId: uuid("owner_user_id")
3467 .notNull()
3468 .references(() => users.id, { onDelete: "cascade" }),
3469 title: text("title").notNull(),
3470 description: text("description").notNull(),
3471 status: text("status").default("planning").notNull(),
3472 createdAt: timestamp("created_at").defaultNow().notNull(),
3473 updatedAt: timestamp("updated_at").defaultNow().notNull(),
3474 },
3475 (table) => [
3476 index("multi_repo_refactors_owner").on(table.ownerUserId, table.createdAt),
3477 index("multi_repo_refactors_status").on(table.status, table.updatedAt),
3478 ]
3479);
3480
3481export const multiRepoRefactorPrs = pgTable(
3482 "multi_repo_refactor_prs",
3483 {
3484 id: uuid("id").primaryKey().defaultRandom(),
3485 refactorId: uuid("refactor_id")
3486 .notNull()
3487 .references(() => multiRepoRefactors.id, { onDelete: "cascade" }),
3488 repositoryId: uuid("repository_id")
3489 .notNull()
3490 .references(() => repositories.id, { onDelete: "cascade" }),
3491 pullRequestId: uuid("pull_request_id").references(() => pullRequests.id, {
3492 onDelete: "set null",
3493 }),
3494 status: text("status").default("pending").notNull(),
3495 errorMessage: text("error_message"),
3496 createdAt: timestamp("created_at").defaultNow().notNull(),
3497 updatedAt: timestamp("updated_at").defaultNow().notNull(),
3498 },
3499 (table) => [
3500 uniqueIndex("multi_repo_refactor_prs_unique").on(
3501 table.refactorId,
3502 table.repositoryId
3503 ),
3504 index("multi_repo_refactor_prs_refactor").on(
3505 table.refactorId,
3506 table.status
3507 ),
3508 index("multi_repo_refactor_prs_repo").on(table.repositoryId),
3509 ]
3510);
3511
3512export type MultiRepoRefactor = typeof multiRepoRefactors.$inferSelect;
3513export type NewMultiRepoRefactor = typeof multiRepoRefactors.$inferInsert;
3514export type MultiRepoRefactorPr = typeof multiRepoRefactorPrs.$inferSelect;
3515export type NewMultiRepoRefactorPr = typeof multiRepoRefactorPrs.$inferInsert;
3516
e3c90cdClaude3517// ─── Chat integrations (migration 0064) ────────────────────────────────────
3518// Slack / Discord / Teams bindings. One row per (owner, kind, team, channel).
3519// `webhook_url` is the outbound Incoming-Webhook URL for posting back into
3520// the channel; `signing_secret` is the per-install verification key (HMAC for
3521// Slack, Ed25519 public key for Discord). See drizzle/0064_chat_integrations.sql
3522// for the full schema rationale.
3523export const chatIntegrations = pgTable(
3524 "chat_integrations",
3525 {
3526 id: uuid("id").primaryKey().defaultRandom(),
3527 ownerUserId: uuid("owner_user_id")
3528 .notNull()
3529 .references(() => users.id, { onDelete: "cascade" }),
3530 kind: text("kind").notNull(), // 'slack' | 'discord' | 'teams'
3531 teamId: text("team_id"),
3532 channelId: text("channel_id"),
3533 webhookUrl: text("webhook_url"),
3534 signingSecret: text("signing_secret"),
3535 enabled: boolean("enabled").default(true).notNull(),
3536 createdAt: timestamp("created_at").defaultNow().notNull(),
3537 lastUsedAt: timestamp("last_used_at"),
3538 },
3539 (table) => [
3540 index("chat_integrations_owner").on(table.ownerUserId, table.kind),
3541 ]
3542);
3543
3544export type ChatIntegration = typeof chatIntegrations.$inferSelect;
3545export type NewChatIntegration = typeof chatIntegrations.$inferInsert;
3546
0c3eee5Claude3547// ---------------------------------------------------------------------------
3548// 0065 — Per-call AI cost tracking. See src/lib/ai-cost-tracker.ts and
3549// src/routes/billing-usage.tsx. Best-effort: insert failures must NEVER
3550// throw out of the Claude caller, so every call site wraps recordAiCost in
3551// try/catch. Cents are computed at insert time from a hardcoded pricing
3552// table so historical aggregates stay stable across price changes.
3553// ---------------------------------------------------------------------------
3554export const aiCostEvents = pgTable(
3555 "ai_cost_events",
3556 {
3557 id: uuid("id").primaryKey().defaultRandom(),
3558 occurredAt: timestamp("occurred_at", { withTimezone: true })
3559 .defaultNow()
3560 .notNull(),
3561 ownerUserId: uuid("owner_user_id").references(() => users.id, {
3562 onDelete: "set null",
3563 }),
3564 repositoryId: uuid("repository_id").references(() => repositories.id, {
3565 onDelete: "set null",
3566 }),
3567 agentSessionId: uuid("agent_session_id").references(
3568 () => agentSessions.id,
3569 { onDelete: "set null" }
3570 ),
3571 model: text("model").notNull(),
3572 inputTokens: integer("input_tokens").default(0).notNull(),
3573 outputTokens: integer("output_tokens").default(0).notNull(),
3574 centsEstimate: integer("cents_estimate").default(0).notNull(),
3575 category: text("category").default("other").notNull(),
3576 sourceId: text("source_id"),
3577 sourceKind: text("source_kind"),
3578 createdAt: timestamp("created_at", { withTimezone: true })
3579 .defaultNow()
3580 .notNull(),
3581 },
3582 (table) => [
3583 index("ai_cost_events_owner_time").on(table.ownerUserId, table.occurredAt),
3584 index("ai_cost_events_repo_time").on(table.repositoryId, table.occurredAt),
3585 index("ai_cost_events_agent_time").on(
3586 table.agentSessionId,
3587 table.occurredAt
3588 ),
3589 index("ai_cost_events_category_time").on(table.category, table.occurredAt),
3590 ]
3591);
3592
3593export type AiCostEvent = typeof aiCostEvents.$inferSelect;
3594export type NewAiCostEvent = typeof aiCostEvents.$inferInsert;
3595
3596export const aiBudgets = pgTable("ai_budgets", {
3597 userId: uuid("user_id")
3598 .primaryKey()
3599 .references(() => users.id, { onDelete: "cascade" }),
3600 monthlyCents: integer("monthly_cents").default(0).notNull(),
3601 updatedAt: timestamp("updated_at", { withTimezone: true })
3602 .defaultNow()
3603 .notNull(),
3604});
3605
3606export type AiBudget = typeof aiBudgets.$inferSelect;
3607export type NewAiBudget = typeof aiBudgets.$inferInsert;
79ed944Claude3608
3609// ---------------------------------------------------------------------------
3610// Migration 0067 — per-PR runnable sandboxes. See src/lib/pr-sandbox.ts.
3611//
3612// Each open PR can hold at most one sandbox row (UNIQUE on pr_id). The row
3613// owns the lifecycle (provisioning → ready / failed / destroyed) plus the
3614// resolved playground.yml the sandbox was provisioned from. Re-provisioning
3615// the same PR upserts onto the existing row so a force-push always points
3616// at the newest head.
3617// ---------------------------------------------------------------------------
3618export const prSandboxes = pgTable(
3619 "pr_sandboxes",
3620 {
3621 id: uuid("id").primaryKey().defaultRandom(),
3622 prId: uuid("pr_id")
3623 .notNull()
3624 .references(() => pullRequests.id, { onDelete: "cascade" }),
3625 status: text("status").default("provisioning").notNull(),
3626 sandboxUrl: text("sandbox_url").notNull(),
3627 containerId: text("container_id"),
3628 playgroundYml: text("playground_yml"),
3629 provisionedAt: timestamp("provisioned_at", { withTimezone: true })
3630 .defaultNow()
3631 .notNull(),
3632 expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
3633 destroyedAt: timestamp("destroyed_at", { withTimezone: true }),
3634 errorMessage: text("error_message"),
3635 createdAt: timestamp("created_at", { withTimezone: true })
3636 .defaultNow()
3637 .notNull(),
3638 },
3639 (table) => [
3640 uniqueIndex("pr_sandboxes_pr_id").on(table.prId),
3641 index("pr_sandboxes_status_expires").on(table.status, table.expiresAt),
3642 ]
3643);
3644
3645export type PrSandbox = typeof prSandboxes.$inferSelect;
3646export type NewPrSandbox = typeof prSandboxes.$inferInsert;
d199847Claude3647
3648// ---------------------------------------------------------------------------
3649// 0068 — AI-tracked documentation sections. See src/lib/ai-doc-updater.ts.
3650//
3651// Stores the currently claimed source-file hash for each
3652// `<!-- gluecron:doc-track src=... -->` region in a tracked markdown file.
3653// The post-receive hook re-hashes the referenced source after every push
3654// and proposes a PR (tagged `ai:doc-update`) when the prose drifts from
3655// the truth.
3656// ---------------------------------------------------------------------------
3657export const docTracking = pgTable(
3658 "doc_tracking",
3659 {
3660 id: uuid("id").primaryKey().defaultRandom(),
3661 repositoryId: uuid("repository_id")
3662 .notNull()
3663 .references(() => repositories.id, { onDelete: "cascade" }),
3664 docPath: text("doc_path").notNull(),
3665 sectionMarker: text("section_marker").notNull(),
3666 srcPath: text("src_path").notNull(),
3667 claimedHash: text("claimed_hash").notNull(),
3668 lastCheckedAt: timestamp("last_checked_at", { withTimezone: true })
3669 .defaultNow()
3670 .notNull(),
3671 lastPrId: uuid("last_pr_id").references(() => pullRequests.id, {
3672 onDelete: "set null",
3673 }),
3674 createdAt: timestamp("created_at", { withTimezone: true })
3675 .defaultNow()
3676 .notNull(),
3677 },
3678 (table) => [
3679 uniqueIndex("doc_tracking_repo_doc_marker").on(
3680 table.repositoryId,
3681 table.docPath,
3682 table.sectionMarker
3683 ),
3684 index("doc_tracking_repo").on(table.repositoryId),
3685 ]
3686);
3687
3688export type DocTracking = typeof docTracking.$inferSelect;
3689export type NewDocTracking = typeof docTracking.$inferInsert;
c6db5eeClaude3690
3691// ---------------------------------------------------------------------------
3692// 0069 — Hosted Claude tool-use loops. See src/lib/hosted-claude-loop.ts and
3693// src/routes/claude-deploy.tsx.
3694//
3695// Users paste a Claude tool-use loop, get a hosted endpoint + budget meter.
3696// Each loop is paired to an agent_sessions row so it inherits multiplayer
3697// namespacing and the daily budget mutex.
3698// ---------------------------------------------------------------------------
3699export const hostedClaudeLoops = pgTable(
3700 "hosted_claude_loops",
3701 {
3702 id: uuid("id").primaryKey().defaultRandom(),
3703 ownerUserId: uuid("owner_user_id")
3704 .notNull()
3705 .references(() => users.id, { onDelete: "cascade" }),
3706 name: text("name").notNull(),
3707 sourceCode: text("source_code").notNull(),
3708 endpointPath: text("endpoint_path").notNull().unique(),
3709 agentSessionId: uuid("agent_session_id").references(
3710 () => agentSessions.id,
3711 { onDelete: "set null" }
3712 ),
3713 status: text("status").default("paused").notNull(),
3714 isPublic: boolean("is_public").default(false).notNull(),
3715 monthlyBudgetCents: integer("monthly_budget_cents").default(500).notNull(),
3716 lastRunAt: timestamp("last_run_at", { withTimezone: true }),
3717 totalInvocations: integer("total_invocations").default(0).notNull(),
3718 totalCentsSpent: integer("total_cents_spent").default(0).notNull(),
3719 createdAt: timestamp("created_at", { withTimezone: true })
3720 .defaultNow()
3721 .notNull(),
3722 updatedAt: timestamp("updated_at", { withTimezone: true })
3723 .defaultNow()
3724 .notNull(),
3725 },
3726 (table) => [
3727 index("hosted_claude_loops_owner").on(table.ownerUserId, table.updatedAt),
3728 index("hosted_claude_loops_status").on(table.status),
3729 ]
3730);
3731
3732export const hostedClaudeLoopRuns = pgTable(
3733 "hosted_claude_loop_runs",
3734 {
3735 id: uuid("id").primaryKey().defaultRandom(),
3736 loopId: uuid("loop_id")
3737 .notNull()
3738 .references(() => hostedClaudeLoops.id, { onDelete: "cascade" }),
3739 inputPayload: jsonb("input_payload").default({}).notNull(),
3740 outputPayload: jsonb("output_payload"),
3741 stdout: text("stdout"),
3742 stderr: text("stderr"),
3743 startedAt: timestamp("started_at", { withTimezone: true })
3744 .defaultNow()
3745 .notNull(),
3746 finishedAt: timestamp("finished_at", { withTimezone: true }),
3747 status: text("status").default("running").notNull(),
3748 centsEstimate: integer("cents_estimate").default(0).notNull(),
3749 claudeInputTokens: integer("claude_input_tokens").default(0).notNull(),
3750 claudeOutputTokens: integer("claude_output_tokens").default(0).notNull(),
3751 exitCode: integer("exit_code"),
3752 errorMessage: text("error_message"),
3753 createdAt: timestamp("created_at", { withTimezone: true })
3754 .defaultNow()
3755 .notNull(),
3756 },
3757 (table) => [
3758 index("hosted_claude_loop_runs_loop_time").on(
3759 table.loopId,
3760 table.startedAt
3761 ),
3762 index("hosted_claude_loop_runs_status").on(table.status, table.startedAt),
3763 ]
3764);
3765
3766export type HostedClaudeLoop = typeof hostedClaudeLoops.$inferSelect;
3767export type NewHostedClaudeLoop = typeof hostedClaudeLoops.$inferInsert;
3768export type HostedClaudeLoopRun = typeof hostedClaudeLoopRuns.$inferSelect;
3769export type NewHostedClaudeLoopRun = typeof hostedClaudeLoopRuns.$inferInsert;
5ca514aClaude3770
3771// ---------------------------------------------------------------------------
9b3a183Claude3772// 0070 — Agent Marketplace. See src/lib/agent-marketplace.ts.
5ca514aClaude3773// ---------------------------------------------------------------------------
3774export const agentMarketplaceListings = pgTable(
3775 "agent_marketplace_listings",
3776 {
3777 id: uuid("id").primaryKey().defaultRandom(),
3778 publisherUserId: uuid("publisher_user_id")
3779 .notNull()
3780 .references(() => users.id, { onDelete: "cascade" }),
3781 slug: text("slug").notNull().unique(),
3782 name: text("name").notNull(),
3783 tagline: text("tagline").default("").notNull(),
3784 description: text("description").default("").notNull(),
3785 category: text("category").default("custom").notNull(),
3786 pricingModel: text("pricing_model").default("free").notNull(),
3787 priceCents: integer("price_cents").default(0).notNull(),
3788 agentTemplate: jsonb("agent_template")
3789 .$type<{
3790 branchNamespace?: string;
3791 budgetCentsPerDay?: number;
3792 capabilities?: string[];
3793 [k: string]: unknown;
3794 }>()
3795 .default({})
3796 .notNull(),
3797 sourceUrl: text("source_url"),
3798 status: text("status").default("draft").notNull(),
3799 installCount: integer("install_count").default(0).notNull(),
3800 ratingAvg: numeric("rating_avg", { precision: 3, scale: 2 })
3801 .default("0")
3802 .notNull(),
3803 ratingCount: integer("rating_count").default(0).notNull(),
3804 createdAt: timestamp("created_at", { withTimezone: true })
3805 .defaultNow()
3806 .notNull(),
3807 updatedAt: timestamp("updated_at", { withTimezone: true })
3808 .defaultNow()
3809 .notNull(),
3810 },
3811 (table) => [
9b3a183Claude3812 index("agent_marketplace_listings_category").on(table.category, table.status),
3813 index("agent_marketplace_listings_rating").on(table.ratingAvg, table.ratingCount),
5ca514aClaude3814 index("agent_marketplace_listings_installs").on(table.installCount),
3815 index("agent_marketplace_listings_publisher").on(table.publisherUserId),
9b3a183Claude3816 index("agent_marketplace_listings_status_created").on(table.status, table.createdAt),
5ca514aClaude3817 ]
3818);
3819
3820export const agentMarketplaceInstalls = pgTable(
3821 "agent_marketplace_installs",
3822 {
3823 id: uuid("id").primaryKey().defaultRandom(),
3824 listingId: uuid("listing_id")
3825 .notNull()
3826 .references(() => agentMarketplaceListings.id, { onDelete: "cascade" }),
3827 repositoryId: uuid("repository_id")
3828 .notNull()
3829 .references(() => repositories.id, { onDelete: "cascade" }),
3830 installedByUserId: uuid("installed_by_user_id")
3831 .notNull()
3832 .references(() => users.id, { onDelete: "cascade" }),
3833 agentSessionId: uuid("agent_session_id").references(
3834 () => agentSessions.id,
3835 { onDelete: "set null" }
3836 ),
3837 status: text("status").default("active").notNull(),
3838 installedAt: timestamp("installed_at", { withTimezone: true })
3839 .defaultNow()
3840 .notNull(),
3841 lastInvokedAt: timestamp("last_invoked_at", { withTimezone: true }),
3842 createdAt: timestamp("created_at", { withTimezone: true })
3843 .defaultNow()
3844 .notNull(),
3845 },
3846 (table) => [
9b3a183Claude3847 uniqueIndex("agent_marketplace_installs_listing_repo").on(table.listingId, table.repositoryId),
5ca514aClaude3848 index("agent_marketplace_installs_repo").on(table.repositoryId, table.status),
3849 index("agent_marketplace_installs_installer").on(table.installedByUserId),
3850 ]
3851);
3852
3853export const agentMarketplaceReviews = pgTable(
3854 "agent_marketplace_reviews",
3855 {
3856 id: uuid("id").primaryKey().defaultRandom(),
3857 listingId: uuid("listing_id")
3858 .notNull()
3859 .references(() => agentMarketplaceListings.id, { onDelete: "cascade" }),
3860 reviewerUserId: uuid("reviewer_user_id")
3861 .notNull()
3862 .references(() => users.id, { onDelete: "cascade" }),
3863 rating: integer("rating").notNull(),
3864 body: text("body").default("").notNull(),
3865 createdAt: timestamp("created_at", { withTimezone: true })
3866 .defaultNow()
3867 .notNull(),
3868 },
3869 (table) => [
9b3a183Claude3870 index("agent_marketplace_reviews_listing_created").on(table.listingId, table.createdAt),
5ca514aClaude3871 index("agent_marketplace_reviews_reviewer").on(table.reviewerUserId),
3872 ]
3873);
3874
9b3a183Claude3875export type AgentMarketplaceListing = typeof agentMarketplaceListings.$inferSelect;
3876export type NewAgentMarketplaceListing = typeof agentMarketplaceListings.$inferInsert;
3877export type AgentMarketplaceInstall = typeof agentMarketplaceInstalls.$inferSelect;
3878export type NewAgentMarketplaceInstall = typeof agentMarketplaceInstalls.$inferInsert;
3879export type AgentMarketplaceReview = typeof agentMarketplaceReviews.$inferSelect;
3880export type NewAgentMarketplaceReview = typeof agentMarketplaceReviews.$inferInsert;
3881
3882// ---------------------------------------------------------------------------
3883// 0072 — per-(repo, user) cloud dev environments. See src/lib/dev-env.ts.
3884// ---------------------------------------------------------------------------
3885export const devEnvs = pgTable(
3886 "dev_envs",
3887 {
3888 id: uuid("id").primaryKey().defaultRandom(),
3889 repositoryId: uuid("repository_id")
3890 .notNull()
3891 .references(() => repositories.id, { onDelete: "cascade" }),
3892 ownerUserId: uuid("owner_user_id")
3893 .notNull()
3894 .references(() => users.id, { onDelete: "cascade" }),
3895 status: text("status").default("cold").notNull(),
3896 previewUrl: text("preview_url"),
3897 containerId: text("container_id"),
3898 machineSize: text("machine_size").default("small").notNull(),
3899 idleMinutes: integer("idle_minutes").default(30).notNull(),
3900 devYml: text("dev_yml"),
3901 errorMessage: text("error_message"),
3902 lastActiveAt: timestamp("last_active_at", { withTimezone: true })
3903 .defaultNow()
3904 .notNull(),
3905 expiresAt: timestamp("expires_at", { withTimezone: true }),
3906 createdAt: timestamp("created_at", { withTimezone: true })
3907 .defaultNow()
3908 .notNull(),
3909 },
3910 (table) => [
3911 uniqueIndex("dev_envs_repo_owner").on(table.repositoryId, table.ownerUserId),
3912 index("dev_envs_status_active").on(table.status, table.lastActiveAt),
3913 ]
3914);
3915
3916export type DevEnv = typeof devEnvs.$inferSelect;
3917export type NewDevEnv = typeof devEnvs.$inferInsert;
783dd46Claude3918
3919// ---------------------------------------------------------------------------
3920// Block ST — Server targets (drizzle/0073_server_targets.sql)
3921//
3922// Admin-managed remote boxes Gluecron can SSH into and run a deploy script
3923// on. Each target carries an encrypted private SSH key, a pinned host
3924// fingerprint, an optional repo+branch to watch, and a per-target list of
3925// env vars materialised on the box at deploy time. Customer-facing rollout
3926// is gated to a follow-up block (Block 2) that scopes by owner_user_id.
3927// ---------------------------------------------------------------------------
3928
3929export const serverTargets = pgTable(
3930 "server_targets",
3931 {
3932 id: uuid("id").primaryKey().defaultRandom(),
3933 name: text("name").notNull(),
3934 host: text("host").notNull(),
3935 port: integer("port").default(22).notNull(),
3936 sshUser: text("ssh_user").notNull(),
3937 encryptedPrivateKey: text("encrypted_private_key").notNull(),
3938 hostFingerprint: text("host_fingerprint"),
3939 deployPath: text("deploy_path").default("/var/www/app").notNull(),
3940 deployScript: text("deploy_script").default("bash deploy.sh").notNull(),
3941 watchedRepositoryId: uuid("watched_repository_id").references(
3942 () => repositories.id,
3943 { onDelete: "set null" }
3944 ),
3945 watchedBranch: text("watched_branch"),
3946 status: text("status").default("unverified").notNull(),
3947 lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
3948 createdBy: uuid("created_by").references(() => users.id, {
3949 onDelete: "set null",
3950 }),
3951 createdAt: timestamp("created_at", { withTimezone: true })
3952 .defaultNow()
3953 .notNull(),
3954 updatedAt: timestamp("updated_at", { withTimezone: true })
3955 .defaultNow()
3956 .notNull(),
3957 },
3958 (table) => [
3959 uniqueIndex("server_targets_name_uq").on(table.name),
3960 index("server_targets_watch_idx").on(
3961 table.watchedRepositoryId,
3962 table.watchedBranch
3963 ),
3964 ]
3965);
3966
3967export type ServerTarget = typeof serverTargets.$inferSelect;
3968export type NewServerTarget = typeof serverTargets.$inferInsert;
3969
3970export const serverTargetEnv = pgTable(
3971 "server_target_env",
3972 {
3973 id: uuid("id").primaryKey().defaultRandom(),
3974 targetId: uuid("target_id")
3975 .notNull()
3976 .references(() => serverTargets.id, { onDelete: "cascade" }),
3977 name: text("name").notNull(),
3978 encryptedValue: text("encrypted_value").notNull(),
3979 isSecret: boolean("is_secret").default(true).notNull(),
3980 updatedBy: uuid("updated_by").references(() => users.id, {
3981 onDelete: "set null",
3982 }),
3983 createdAt: timestamp("created_at", { withTimezone: true })
3984 .defaultNow()
3985 .notNull(),
3986 updatedAt: timestamp("updated_at", { withTimezone: true })
3987 .defaultNow()
3988 .notNull(),
3989 },
3990 (table) => [uniqueIndex("server_target_env_uq").on(table.targetId, table.name)]
3991);
3992
3993export type ServerTargetEnv = typeof serverTargetEnv.$inferSelect;
3994export type NewServerTargetEnv = typeof serverTargetEnv.$inferInsert;
3995
3996export const serverTargetDeployments = pgTable(
3997 "server_target_deployments",
3998 {
3999 id: uuid("id").primaryKey().defaultRandom(),
4000 targetId: uuid("target_id")
4001 .notNull()
4002 .references(() => serverTargets.id, { onDelete: "cascade" }),
4003 commitSha: text("commit_sha"),
4004 ref: text("ref"),
4005 status: text("status").default("pending").notNull(),
4006 exitCode: integer("exit_code"),
4007 stdout: text("stdout"),
4008 stderr: text("stderr"),
4009 triggeredBy: uuid("triggered_by").references(() => users.id, {
4010 onDelete: "set null",
4011 }),
4012 triggerSource: text("trigger_source").default("push").notNull(),
4013 startedAt: timestamp("started_at", { withTimezone: true })
4014 .defaultNow()
4015 .notNull(),
4016 finishedAt: timestamp("finished_at", { withTimezone: true }),
4017 },
4018 (table) => [
4019 index("server_target_deployments_target_idx").on(
4020 table.targetId,
4021 table.startedAt
4022 ),
4023 ]
4024);
4025
4026export type ServerTargetDeployment =
4027 typeof serverTargetDeployments.$inferSelect;
4028export type NewServerTargetDeployment =
4029 typeof serverTargetDeployments.$inferInsert;
4030
4031export const serverTargetAudit = pgTable(
4032 "server_target_audit",
4033 {
4034 id: uuid("id").primaryKey().defaultRandom(),
4035 targetId: uuid("target_id").references(() => serverTargets.id, {
4036 onDelete: "set null",
4037 }),
4038 actorId: uuid("actor_id").references(() => users.id, {
4039 onDelete: "set null",
4040 }),
4041 action: text("action").notNull(),
4042 detail: text("detail"),
4043 ip: text("ip"),
4044 createdAt: timestamp("created_at", { withTimezone: true })
4045 .defaultNow()
4046 .notNull(),
4047 },
4048 (table) => [
4049 index("server_target_audit_target_idx").on(table.targetId, table.createdAt),
4050 ]
4051);
4052
4053export type ServerTargetAudit = typeof serverTargetAudit.$inferSelect;
4054export type NewServerTargetAudit = typeof serverTargetAudit.$inferInsert;
90c7531Claude4055
4056// ---------------------------------------------------------------------------
4057// Block CW — Claude on the web (drizzle/0074_claude_web_sessions.sql)
4058//
4059// Per-repo interactive Claude Code sessions runnable from any browser.
4060// Each session owns a working dir on the web server (a fresh git clone of
4061// the repo's bare store) and persists turn-by-turn transcripts so an iPad
4062// user can resume the same conversation later from a laptop.
4063//
4064// v1 admin-only; v2 will scope by owner_user_id and isolate per-session
4065// containers. Schema is forward-compatible with both.
4066// ---------------------------------------------------------------------------
4067
4068export const claudeWebSessions = pgTable(
4069 "claude_web_sessions",
4070 {
4071 id: uuid("id").primaryKey().defaultRandom(),
4072 repositoryId: uuid("repository_id")
4073 .notNull()
4074 .references(() => repositories.id, { onDelete: "cascade" }),
4075 ownerUserId: uuid("owner_user_id")
4076 .notNull()
4077 .references(() => users.id, { onDelete: "cascade" }),
4078 title: text("title").default("New session").notNull(),
4079 branch: text("branch").default("main").notNull(),
4080 workdirPath: text("workdir_path").notNull(),
4081 claudeSessionId: text("claude_session_id"),
4082 status: text("status").default("cold").notNull(),
4083 lastActiveAt: timestamp("last_active_at", { withTimezone: true })
4084 .defaultNow()
4085 .notNull(),
4086 createdAt: timestamp("created_at", { withTimezone: true })
4087 .defaultNow()
4088 .notNull(),
4089 },
4090 (table) => [
4091 index("claude_web_sessions_repo_idx").on(
4092 table.repositoryId,
4093 table.lastActiveAt
4094 ),
4095 index("claude_web_sessions_owner_idx").on(
4096 table.ownerUserId,
4097 table.lastActiveAt
4098 ),
4099 ]
4100);
4101
4102export type ClaudeWebSession = typeof claudeWebSessions.$inferSelect;
4103export type NewClaudeWebSession = typeof claudeWebSessions.$inferInsert;
4104
4105export const claudeWebMessages = pgTable(
4106 "claude_web_messages",
4107 {
4108 id: uuid("id").primaryKey().defaultRandom(),
4109 sessionId: uuid("session_id")
4110 .notNull()
4111 .references(() => claudeWebSessions.id, { onDelete: "cascade" }),
4112 role: text("role").notNull(),
4113 body: text("body").notNull(),
4114 exitCode: integer("exit_code"),
4115 durationMs: integer("duration_ms"),
4116 createdAt: timestamp("created_at", { withTimezone: true })
4117 .defaultNow()
4118 .notNull(),
4119 },
4120 (table) => [
4121 index("claude_web_messages_session_idx").on(
4122 table.sessionId,
4123 table.createdAt
4124 ),
4125 ]
4126);
4127
4128export type ClaudeWebMessage = typeof claudeWebMessages.$inferSelect;
873f13cClaude4129
4130// ---------------------------------------------------------------------------
4131// 0077 — Status page: incident history + subscriber list.
4132//
4133// incidents: manually-filed or autopilot-detected outage records shown on
4134// the public /status page. severity: 'minor' | 'major' | 'critical'.
4135// status: 'investigating' | 'identified' | 'monitoring' | 'resolved'.
4136//
4137// status_subscribers: email addresses that have opted-in to receive alerts
4138// when a new incident is filed.
4139// ---------------------------------------------------------------------------
4140export const incidents = pgTable(
4141 "incidents",
4142 {
4143 id: uuid("id").primaryKey().defaultRandom(),
4144 title: text("title").notNull(),
4145 severity: text("severity").notNull().default("minor"),
4146 status: text("status").notNull().default("resolved"),
4147 startedAt: timestamp("started_at", { withTimezone: true })
4148 .defaultNow()
4149 .notNull(),
4150 resolvedAt: timestamp("resolved_at", { withTimezone: true }),
4151 body: text("body"),
4152 createdAt: timestamp("created_at", { withTimezone: true })
4153 .defaultNow()
4154 .notNull(),
4155 updatedAt: timestamp("updated_at", { withTimezone: true })
4156 .defaultNow()
4157 .notNull(),
4158 },
4159 (table) => [
4160 index("idx_incidents_started_at").on(table.startedAt),
4161 index("idx_incidents_status").on(table.status),
4162 ]
4163);
4164
4165export type Incident = typeof incidents.$inferSelect;
4166export type NewIncident = typeof incidents.$inferInsert;
4167
4168export const statusSubscribers = pgTable(
4169 "status_subscribers",
4170 {
4171 id: uuid("id").primaryKey().defaultRandom(),
4172 email: text("email").notNull().unique(),
4173 confirmedAt: timestamp("confirmed_at", { withTimezone: true }),
4174 confirmToken: text("confirm_token").unique(),
4175 unsubscribeToken: text("unsubscribe_token").unique(),
4176 createdAt: timestamp("created_at", { withTimezone: true })
4177 .defaultNow()
4178 .notNull(),
4179 },
4180 (table) => [
4181 index("idx_status_subscribers_email").on(table.email),
4182 ]
4183);
4184
4185export type StatusSubscriber = typeof statusSubscribers.$inferSelect;
4186export type NewStatusSubscriber = typeof statusSubscribers.$inferInsert;
90c7531Claude4187export type NewClaudeWebMessage = typeof claudeWebMessages.$inferInsert;
9f29b65Claude4188
4189// ---------------------------------------------------------------------------
4190// Migration 0077 — Enterprise leads (contact form submissions from /enterprise)
4191// ---------------------------------------------------------------------------
4192
4193/**
4194 * Enterprise leads — one row per /enterprise contact form submission.
4195 * Sales team reads these directly or via a future CRM sync.
4196 */
4197export const enterpriseLeads = pgTable(
4198 "enterprise_leads",
4199 {
4200 id: uuid("id").primaryKey().defaultRandom(),
4201 name: text("name").notNull(),
4202 company: text("company").notNull(),
4203 email: text("email").notNull(),
4204 teamSize: text("team_size").notNull(),
4205 message: text("message"),
4206 ip: text("ip"),
4207 createdAt: timestamp("created_at").defaultNow().notNull(),
4208 },
4209 (table) => [index("enterprise_leads_created").on(table.createdAt)]
4210);
4211
4212export type EnterpriseLead = typeof enterpriseLeads.$inferSelect;
4213export type NewEnterpriseLead = typeof enterpriseLeads.$inferInsert;