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