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