@marinoscar/platform-db 0.0.0-stage → 0.1.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +525 -2
  4. package/bin/platform.js +28 -0
  5. package/dist/baseline/deps.d.ts +32 -0
  6. package/dist/baseline/deps.d.ts.map +1 -0
  7. package/dist/baseline/deps.js +66 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +36 -0
  10. package/dist/baseline/errors.d.ts.map +1 -0
  11. package/dist/baseline/errors.js +23 -0
  12. package/dist/baseline/errors.js.map +1 -0
  13. package/dist/baseline/fs.d.ts +9 -0
  14. package/dist/baseline/fs.d.ts.map +1 -0
  15. package/dist/baseline/fs.js +39 -0
  16. package/dist/baseline/fs.js.map +1 -0
  17. package/dist/baseline/index.d.ts +8 -0
  18. package/dist/baseline/index.d.ts.map +1 -0
  19. package/dist/baseline/index.js +24 -0
  20. package/dist/baseline/index.js.map +1 -0
  21. package/dist/baseline/mapping.d.ts +43 -0
  22. package/dist/baseline/mapping.d.ts.map +1 -0
  23. package/dist/baseline/mapping.js +80 -0
  24. package/dist/baseline/mapping.js.map +1 -0
  25. package/dist/baseline/normalise.d.ts +42 -0
  26. package/dist/baseline/normalise.d.ts.map +1 -0
  27. package/dist/baseline/normalise.js +133 -0
  28. package/dist/baseline/normalise.js.map +1 -0
  29. package/dist/baseline/plan.d.ts +66 -0
  30. package/dist/baseline/plan.d.ts.map +1 -0
  31. package/dist/baseline/plan.js +105 -0
  32. package/dist/baseline/plan.js.map +1 -0
  33. package/dist/baseline/report.d.ts +127 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +89 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +117 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +358 -0
  40. package/dist/baseline/run.js.map +1 -0
  41. package/dist/bin/db-commands.d.ts +31 -0
  42. package/dist/bin/db-commands.d.ts.map +1 -0
  43. package/dist/bin/db-commands.js +311 -0
  44. package/dist/bin/db-commands.js.map +1 -0
  45. package/dist/bin/fs-io.d.ts +7 -0
  46. package/dist/bin/fs-io.d.ts.map +1 -0
  47. package/dist/bin/fs-io.js +45 -0
  48. package/dist/bin/fs-io.js.map +1 -0
  49. package/dist/bin/platform.d.ts +21 -0
  50. package/dist/bin/platform.d.ts.map +1 -0
  51. package/dist/bin/platform.js +99 -0
  52. package/dist/bin/platform.js.map +1 -0
  53. package/dist/compose/api.d.ts +84 -0
  54. package/dist/compose/api.d.ts.map +1 -0
  55. package/dist/compose/api.js +101 -0
  56. package/dist/compose/api.js.map +1 -0
  57. package/dist/compose/compose.d.ts +51 -0
  58. package/dist/compose/compose.d.ts.map +1 -0
  59. package/dist/compose/compose.js +177 -0
  60. package/dist/compose/compose.js.map +1 -0
  61. package/dist/compose/diff.d.ts +7 -0
  62. package/dist/compose/diff.d.ts.map +1 -0
  63. package/dist/compose/diff.js +68 -0
  64. package/dist/compose/diff.js.map +1 -0
  65. package/dist/compose/errors.d.ts +31 -0
  66. package/dist/compose/errors.d.ts.map +1 -0
  67. package/dist/compose/errors.js +35 -0
  68. package/dist/compose/errors.js.map +1 -0
  69. package/dist/compose/index.d.ts +3 -0
  70. package/dist/compose/index.d.ts.map +1 -0
  71. package/dist/compose/index.js +11 -0
  72. package/dist/compose/index.js.map +1 -0
  73. package/dist/compose/parse.d.ts +65 -0
  74. package/dist/compose/parse.d.ts.map +1 -0
  75. package/dist/compose/parse.js +122 -0
  76. package/dist/compose/parse.js.map +1 -0
  77. package/dist/drift/app-objects.d.ts +107 -0
  78. package/dist/drift/app-objects.d.ts.map +1 -0
  79. package/dist/drift/app-objects.js +193 -0
  80. package/dist/drift/app-objects.js.map +1 -0
  81. package/dist/drift/db-conformance.d.ts +52 -0
  82. package/dist/drift/db-conformance.d.ts.map +1 -0
  83. package/dist/drift/db-conformance.js +89 -0
  84. package/dist/drift/db-conformance.js.map +1 -0
  85. package/dist/drift/index.d.ts +8 -0
  86. package/dist/drift/index.d.ts.map +1 -0
  87. package/dist/drift/index.js +43 -0
  88. package/dist/drift/index.js.map +1 -0
  89. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  90. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-indexes.js +113 -0
  92. package/dist/drift/raw-sql-indexes.js.map +1 -0
  93. package/dist/drift/raw-sql-tripwire.d.ts +191 -0
  94. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  95. package/dist/drift/raw-sql-tripwire.js +422 -0
  96. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  97. package/dist/drift/rls-policies.d.ts +226 -0
  98. package/dist/drift/rls-policies.d.ts.map +1 -0
  99. package/dist/drift/rls-policies.js +317 -0
  100. package/dist/drift/rls-policies.js.map +1 -0
  101. package/dist/drift/run.d.ts +152 -0
  102. package/dist/drift/run.d.ts.map +1 -0
  103. package/dist/drift/run.js +252 -0
  104. package/dist/drift/run.js.map +1 -0
  105. package/dist/drift/sql-expression.d.ts +27 -0
  106. package/dist/drift/sql-expression.d.ts.map +1 -0
  107. package/dist/drift/sql-expression.js +64 -0
  108. package/dist/drift/sql-expression.js.map +1 -0
  109. package/dist/index.d.ts +16 -0
  110. package/dist/index.d.ts.map +1 -0
  111. package/dist/index.js +33 -0
  112. package/dist/index.js.map +1 -0
  113. package/dist/lock/hash.d.ts +13 -0
  114. package/dist/lock/hash.d.ts.map +1 -0
  115. package/dist/lock/hash.js +19 -0
  116. package/dist/lock/hash.js.map +1 -0
  117. package/dist/lock/index.d.ts +5 -0
  118. package/dist/lock/index.d.ts.map +1 -0
  119. package/dist/lock/index.js +20 -0
  120. package/dist/lock/index.js.map +1 -0
  121. package/dist/lock/lock.d.ts +154 -0
  122. package/dist/lock/lock.d.ts.map +1 -0
  123. package/dist/lock/lock.js +151 -0
  124. package/dist/lock/lock.js.map +1 -0
  125. package/dist/lock/manifest.d.ts +68 -0
  126. package/dist/lock/manifest.d.ts.map +1 -0
  127. package/dist/lock/manifest.js +96 -0
  128. package/dist/lock/manifest.js.map +1 -0
  129. package/dist/lock/semver.d.ts +10 -0
  130. package/dist/lock/semver.d.ts.map +1 -0
  131. package/dist/lock/semver.js +13 -0
  132. package/dist/lock/semver.js.map +1 -0
  133. package/dist/seed/index.d.ts +5 -0
  134. package/dist/seed/index.d.ts.map +1 -0
  135. package/dist/seed/index.js +16 -0
  136. package/dist/seed/index.js.map +1 -0
  137. package/dist/seed/input.d.ts +52 -0
  138. package/dist/seed/input.d.ts.map +1 -0
  139. package/dist/seed/input.js +77 -0
  140. package/dist/seed/input.js.map +1 -0
  141. package/dist/seed/seed-platform.d.ts +41 -0
  142. package/dist/seed/seed-platform.d.ts.map +1 -0
  143. package/dist/seed/seed-platform.js +165 -0
  144. package/dist/seed/seed-platform.js.map +1 -0
  145. package/dist/seed/steps.d.ts +172 -0
  146. package/dist/seed/steps.d.ts.map +1 -0
  147. package/dist/seed/steps.js +136 -0
  148. package/dist/seed/steps.js.map +1 -0
  149. package/dist/seed/types.d.ts +287 -0
  150. package/dist/seed/types.d.ts.map +1 -0
  151. package/dist/seed/types.js +5 -0
  152. package/dist/seed/types.js.map +1 -0
  153. package/dist/sync/app-migrations.d.ts +52 -0
  154. package/dist/sync/app-migrations.d.ts.map +1 -0
  155. package/dist/sync/app-migrations.js +62 -0
  156. package/dist/sync/app-migrations.js.map +1 -0
  157. package/dist/sync/apply.d.ts +29 -0
  158. package/dist/sync/apply.d.ts.map +1 -0
  159. package/dist/sync/apply.js +38 -0
  160. package/dist/sync/apply.js.map +1 -0
  161. package/dist/sync/check.d.ts +59 -0
  162. package/dist/sync/check.d.ts.map +1 -0
  163. package/dist/sync/check.js +115 -0
  164. package/dist/sync/check.js.map +1 -0
  165. package/dist/sync/errors.d.ts +32 -0
  166. package/dist/sync/errors.d.ts.map +1 -0
  167. package/dist/sync/errors.js +23 -0
  168. package/dist/sync/errors.js.map +1 -0
  169. package/dist/sync/index.d.ts +10 -0
  170. package/dist/sync/index.d.ts.map +1 -0
  171. package/dist/sync/index.js +27 -0
  172. package/dist/sync/index.js.map +1 -0
  173. package/dist/sync/ledger.d.ts +65 -0
  174. package/dist/sync/ledger.d.ts.map +1 -0
  175. package/dist/sync/ledger.js +49 -0
  176. package/dist/sync/ledger.js.map +1 -0
  177. package/dist/sync/plan.d.ts +63 -0
  178. package/dist/sync/plan.d.ts.map +1 -0
  179. package/dist/sync/plan.js +86 -0
  180. package/dist/sync/plan.js.map +1 -0
  181. package/dist/sync/promote.d.ts +62 -0
  182. package/dist/sync/promote.d.ts.map +1 -0
  183. package/dist/sync/promote.js +95 -0
  184. package/dist/sync/promote.js.map +1 -0
  185. package/dist/sync/timestamps.d.ts +41 -0
  186. package/dist/sync/timestamps.d.ts.map +1 -0
  187. package/dist/sync/timestamps.js +68 -0
  188. package/dist/sync/timestamps.js.map +1 -0
  189. package/dist/sync/version.d.ts +28 -0
  190. package/dist/sync/version.d.ts.map +1 -0
  191. package/dist/sync/version.js +66 -0
  192. package/dist/sync/version.js.map +1 -0
  193. package/migrations/0001_initial/migration.sql +297 -0
  194. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  195. package/migrations/0003_add_credentials/migration.sql +20 -0
  196. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  197. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  198. package/migrations/0006_add_notifications/migration.sql +22 -0
  199. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  200. package/migrations/0008_add_jobs/migration.sql +110 -0
  201. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  202. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  203. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  204. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  205. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  206. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  207. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  208. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  209. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  210. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  211. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  212. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  213. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  214. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  215. package/migrations/0023_add_organizations/migration.sql +142 -0
  216. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  217. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  218. package/migrations/0026_add_groups/migration.sql +165 -0
  219. package/migrations/0027_add_grants/migration.sql +117 -0
  220. package/migrations/0028_add_org_settings/migration.sql +49 -0
  221. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  222. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  223. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  224. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  225. package/migrations/0033_add_android_app/migration.sql +60 -0
  226. package/migrations/0034_open_job_reason/migration.sql +16 -0
  227. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  228. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  229. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  230. package/migrations/manifest.json +379 -0
  231. package/package.json +78 -4
  232. package/raw-sql-indexes.json +94 -0
  233. package/rls-policies.json +74 -0
  234. package/schema/ai.prisma +444 -0
  235. package/schema/android-app.prisma +47 -0
  236. package/schema/base.prisma +11 -0
  237. package/schema/credentials.prisma +170 -0
  238. package/schema/db-backup.prisma +376 -0
  239. package/schema/identity.prisma +439 -0
  240. package/schema/jobs.prisma +760 -0
  241. package/schema/notifications.prisma +649 -0
  242. package/schema/settings.prisma +60 -0
  243. package/schema/sharing.prisma +223 -0
  244. package/schema/storage.prisma +84 -0
@@ -0,0 +1,760 @@
1
+ // =============================================================================
2
+ // Jobs (issue #255, epic #254)
3
+ // =============================================================================
4
+ //
5
+ // A generic background-job queue table: one row per unit of work a worker
6
+ // node claims, runs, and reports the outcome of. This issue adds only the
7
+ // schema — the enqueue path, the claim query, and the node plane that
8
+ // actually pulls jobs off this table all arrive in later issues of #254
9
+ // (the claim query's `RETURNING` aliases land in #260, the `WorkerNode` model
10
+ // that `claimedByNodeId` will finally point at lands with the node plane).
11
+ // What is here is deliberately complete on its own: every column and index a
12
+ // worker needs to claim, execute, retry, and rate-limit a job, so nothing
13
+ // downstream requires a follow-up migration to `jobs` itself.
14
+ //
15
+ // -----------------------------------------------------------------------------
16
+ // subjectType / subjectId — plain nullable TEXT, not typed or FK'd columns
17
+ // -----------------------------------------------------------------------------
18
+ // REJECTED: a column per subject shape (`mediaItemId`, `circleId`, ...). This
19
+ // table is generic across every handler `type` this app will ever register,
20
+ // present and future. A typed column per subject means every new job kind
21
+ // that targets a new kind of thing is a migration to this table, which is
22
+ // exactly the coupling a job queue must not have to its callers — the whole
23
+ // point of `type` being a free-form handler key is that new handlers cost
24
+ // zero schema changes. `subjectType` (a short discriminator string the
25
+ // handler itself defines, e.g. `'media_item'`) plus `subjectId` (that
26
+ // subject's id, stored as text specifically so it is not assumed to be a
27
+ // UUID — some future subject might key by something else) covers every shape
28
+ // with two columns, forever.
29
+ //
30
+ // REJECTED: payload-only, with no subject columns at all (dig the subject id
31
+ // out of the JSONB `payload` when you need it). This is what `[subjectType,
32
+ // subjectId]` below exists to make wrong: "cancel every pending job for this
33
+ // media item" and "is there already an active job for this exact subject"
34
+ // (the dedup index just below) are both real, known queries (not
35
+ // speculative), and neither is expressible as an index over JSONB without a
36
+ // GIN index and a much more awkward query. Two plain columns, indexed
37
+ // normally, are simpler and cheaper than making Postgres reach into JSON for
38
+ // a value that is known and named at enqueue time regardless.
39
+ //
40
+ // Both nullable, and BOTH null together is the documented spelling of "this
41
+ // is a global/system job" (a nightly sweep, a cache warm) that is not about
42
+ // any one row elsewhere in the database — there is no sentinel subjectType
43
+ // like `'system'` to keep in sync with anything.
44
+ //
45
+ // -----------------------------------------------------------------------------
46
+ // dedupKey / the active-dedup unique index — enforced by a hand-written
47
+ // partial index, NOT `findFirst` then `create` in the enqueue service
48
+ // -----------------------------------------------------------------------------
49
+ // REJECTED: "check whether an active job with this key already exists, and
50
+ // only insert if not" as application logic. That is a check-then-act race:
51
+ // two concurrent enqueue calls can both see "no active duplicate" and both
52
+ // insert, which is precisely the failure a dedup key exists to prevent, and
53
+ // under real concurrent load (a webhook retried while the first delivery is
54
+ // still being handled, two nodes reacting to the same event) it is not a
55
+ // rare edge case. Only the database can make "is there already an active job
56
+ // with this key" atomic with the insert that would violate it, which is what
57
+ // `jobs_active_dedup_uniq_idx` below is for: a partial UNIQUE index on
58
+ // `dedup_key` filtered to `status IN ('pending','running')`. The enqueue path
59
+ // (arriving with #260) inserts optimistically and treats the resulting
60
+ // unique-violation as "a duplicate is already in flight", not as an error —
61
+ // no pre-check query, no race window.
62
+ //
63
+ // The partial filter is exactly what makes the key reusable: once a job
64
+ // reaches `succeeded` (or `failed`) it drops out of the index's predicate, so
65
+ // the same `dedup_key` is free again for a new active job — retrying or
66
+ // re-triggering the same logical work later is not permanently blocked by
67
+ // its own history. `dedup_key IS NOT NULL` in the predicate is what lets
68
+ // jobs that opt out of dedup (most ad-hoc jobs) insert freely with a NULL key
69
+ // — Postgres does not consider NULLs equal for uniqueness, but the explicit
70
+ // clause documents that this is relied upon, not incidental.
71
+ //
72
+ // The key's actual format (`type:subjectType:subjectId`) is defined ONCE, in
73
+ // `buildDedupKey()` (`src/jobs/job-keys.ts`), which this comment and the
74
+ // migration's raw SQL both point back to rather than restating it — see that
75
+ // file for why the format is what it is.
76
+ //
77
+ // -----------------------------------------------------------------------------
78
+ // priority — ASCENDING is more urgent
79
+ // -----------------------------------------------------------------------------
80
+ // Chosen so `ORDER BY priority ASC, created_at ASC` is both "most urgent
81
+ // first" and "oldest first within a priority", the same direction Postgres
82
+ // already walks a plain ascending b-tree index in — no `DESC` index variant
83
+ // needed for the hot claim-query ordering that `[status, priority,
84
+ // createdAt]` and `[status, scheduledFor, priority, createdAt]` below exist
85
+ // to serve. `0` is the default (normal) priority; more urgent work is a
86
+ // smaller (including negative) number, not a larger one.
87
+ //
88
+ // -----------------------------------------------------------------------------
89
+ // attempts vs rateLimitedAt/rateLimitHits — two counters for two different
90
+ // reasons a job didn't finish, deliberately not merged into one
91
+ // -----------------------------------------------------------------------------
92
+ // `attempts` is charged AT CLAIM TIME (incremented when a worker takes the
93
+ // job, not when it fails) and is what a max-retry policy reads. Being rate
94
+ // limited by a downstream provider is not the job's fault and is not a
95
+ // retry in that sense — charging it against `attempts` would make a job that
96
+ // is simply waiting its turn look like a job that keeps failing, and could
97
+ // exhaust its retry budget for a reason that has nothing to do with the
98
+ // job's own correctness. `rateLimitedAt` / `rateLimitHits` track that
99
+ // separately: `scheduledFor` is pushed out to defer the job, `rateLimitHits`
100
+ // records how often this has happened (for observability/alerting on a
101
+ // provider that is persistently saturated), and neither touches `attempts`.
102
+ //
103
+ // -----------------------------------------------------------------------------
104
+ // providerKey / modelVersion — audit of WHAT ran the job, not inputs to it
105
+ // -----------------------------------------------------------------------------
106
+ // Both nullable and both write-once-at-completion-time metadata: which
107
+ // downstream provider handled this job and which model/version it ran
108
+ // against, for after-the-fact questions ("did the incident affect jobs that
109
+ // ran on provider X" / "which jobs ran before the model version bump").
110
+ // Neither is read back by the claim query — they exist for audit, not for
111
+ // scheduling.
112
+ //
113
+ // -----------------------------------------------------------------------------
114
+ // claimedByNodeId — a real relation as of issue #267, epic #254
115
+ // -----------------------------------------------------------------------------
116
+ // This column existed unconstrained (`String? @db.Uuid`) from #255 onward, so
117
+ // the claim query and its indexes ([status, leaseExpiresAt],
118
+ // [claimedByNodeId]) could be built against their final shape before the
119
+ // `WorkerNode` table it references existed. #267 adds that table and wires
120
+ // the FK on top of this already-populated column: `onDelete: SetNull`, so a
121
+ // node's disappearance (deregistered, pruned, or manually deleted by an
122
+ // admin) frees the jobs it was holding — via `leaseExpiresAt` already having
123
+ // them look abandoned to the reaper — rather than deleting job history. See
124
+ // the block comment above the `WorkerNode` model for the corresponding
125
+ // `onDelete` decision on `WorkerNode.createdBy`, which is a different
126
+ // question (what happens to the NODE when its owning USER is deleted, not
127
+ // what happens to a JOB when its claiming NODE is deleted).
128
+ //
129
+ // -----------------------------------------------------------------------------
130
+ // claimToken — per-claim identity, closing the two-replica lease hole
131
+ // (issue #361)
132
+ // -----------------------------------------------------------------------------
133
+ // `claimedByNodeId` distinguishes a node's claim from the server's, but every
134
+ // API replica claims with `claimedByNodeId: null` — so two different server
135
+ // replicas produce an IDENTICAL `heldLeaseWhere` predicate for the same job,
136
+ // and one replica's renewal cannot be told apart from another's. `claimToken`
137
+ // is minted fresh per claim (not per process, not per batch — see the field
138
+ // comment below for why that distinction matters) and is the extra predicate
139
+ // that makes a specific claim, not just a specific kind of claimant,
140
+ // checkable. Nullable with no default, same as `claimedByNodeId` and
141
+ // `leaseExpiresAt`: `NULL` iff not currently claimed, no backfill, no index —
142
+ // see the migration header (`20260908120000_add_job_claim_token`) for the
143
+ // full argument, which this comment does not restate.
144
+ //
145
+ // -----------------------------------------------------------------------------
146
+ // sumDurationMs on JobStatsRollup — Float (double precision), NOT BigInt
147
+ // -----------------------------------------------------------------------------
148
+ // REJECTED: BigInt. Prisma maps a BigInt column to the JS `bigint` primitive,
149
+ // which `JSON.stringify` refuses outright ("Do not know how to serialize a
150
+ // BigInt") — the not-yet-built insights endpoint that reads this rollup would
151
+ // crash on its very first response, not degrade gracefully. A running sum of
152
+ // per-job durations in milliseconds, even at very high job volume, never
153
+ // approaches the ~2^53 safe-integer boundary where `Float` would start
154
+ // losing precision that matters for an aggregate (an average duration off by
155
+ // fractions of a millisecond at that scale is not a real-world concern);
156
+ // BigInt's exactness buys nothing here and costs a runtime crash.
157
+ //
158
+ // -----------------------------------------------------------------------------
159
+ // Prisma-expressible indexes vs the three below written directly in the
160
+ // migration (INTENTIONAL SCHEMA DRIFT — see migration.sql in
161
+ // 20260906120000_add_jobs)
162
+ // -----------------------------------------------------------------------------
163
+ // Everything Prisma's index DSL can express is declared with `@@index` below.
164
+ // Three more indexes exist ONLY in `migration.sql` because the Prisma schema
165
+ // language has no syntax for a partial index (a `WHERE` clause on the index
166
+ // itself) — `@@index` always builds a full index over every row:
167
+ //
168
+ // - "jobs_active_dedup_uniq_idx": the partial UNIQUE index described above
169
+ // that actually enforces the active-dedup constraint (`dedup_key` where
170
+ // `status IN ('pending','running') AND dedup_key IS NOT NULL`).
171
+ // - "jobs_attempts_gt1_idx": a partial index on `attempts` where
172
+ // `attempts > 1`, sized to the small minority of jobs that have ever
173
+ // been retried, for "show me flaky jobs" without indexing the (large)
174
+ // majority that succeeded on the first attempt.
175
+ // - "jobs_succeeded_duration_idx": a partial index on
176
+ // `(finished_at, started_at, type)` where `status = 'succeeded' AND
177
+ // started_at IS NOT NULL AND finished_at IS NOT NULL`, for computing
178
+ // per-type duration stats (what feeds `JobStatsRollup`) without scanning
179
+ // jobs that were never actually timed.
180
+ //
181
+ // Because `prisma migrate dev`/`diff` cannot regenerate these from the
182
+ // schema file, they will show up as "drift" if anyone ever diffs this schema
183
+ // against the live database with a tool that expects `@@index` to be the
184
+ // full story. That drift is intentional and this comment (plus the ones in
185
+ // the migration itself) is the record of why — do not "fix" it by dropping
186
+ // these three indexes, and do not try to force them into `@@index` syntax
187
+ // that does not exist.
188
+ // @extensible — back-relations only, added with "extend model Job { ... }" in a fragment
189
+ model Job {
190
+ id String @id @default(uuid()) @db.Uuid
191
+
192
+ // The handler key a worker dispatches on (e.g. `'email.send'`,
193
+ // `'export.csv'`). A small, code-owned, growing set — deliberately a plain
194
+ // string and not a Prisma enum, for the same reason `NotificationDelivery
195
+ // .channel` and `.eventKey` are plain strings: new handlers must cost zero
196
+ // migrations, and a row must be able to outlive the handler that produced
197
+ // it (a removed/renamed handler's historical jobs stay queryable).
198
+ type String
199
+
200
+ // See the block comment above for why these are plain nullable TEXT rather
201
+ // than typed/FK'd columns, and why both null together means a
202
+ // global/system job.
203
+ subjectType String? @map("subject_type")
204
+ subjectId String? @map("subject_id")
205
+
206
+ // See the block comment above ("dedupKey / the active-dedup unique index")
207
+ // for the full mechanism. Built by `buildDedupKey()`
208
+ // (`src/jobs/job-keys.ts`); nullable because most jobs opt out of dedup
209
+ // entirely.
210
+ dedupKey String? @map("dedup_key")
211
+
212
+ status JobStatus @default(pending)
213
+
214
+ // Why the job was queued: a plain string (an open vocabulary), not a Prisma
215
+ // enum, for the reason `Job.type` is one. The built-ins are `upload`, `rerun`
216
+ // and `backfill`; an app adds its own through `registerJobReason`
217
+ // (`@marinoscar/platform-api/jobs`) at zero migrations. The set a row may
218
+ // carry is bounded by the contract's `jobReasonSchema` pattern at the API
219
+ // edge, not by a CHECK constraint, so a row outlives the reason that wrote it.
220
+ reason String
221
+
222
+ // Ascending = more urgent. See the block comment above.
223
+ priority Int @default(0)
224
+
225
+ // Audit of what actually ran this job — see the block comment above.
226
+ // Written once, at completion; never read by the claim query.
227
+ providerKey String? @map("provider_key")
228
+ modelVersion String? @map("model_version")
229
+
230
+ // Handler-defined input, opaque to this table.
231
+ payload Json? @db.JsonB
232
+
233
+ // Charged AT CLAIM TIME (see the block comment above for why this is kept
234
+ // separate from rateLimitHits).
235
+ attempts Int @default(0)
236
+
237
+ lastError String? @map("last_error")
238
+
239
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
240
+ startedAt DateTime? @map("started_at") @db.Timestamptz
241
+ finishedAt DateTime? @map("finished_at") @db.Timestamptz
242
+
243
+ // NULL means eligible now. A non-null value in the future is what makes a
244
+ // job invisible to the claim query until then (deferred rate-limit retries,
245
+ // deliberately scheduled work).
246
+ scheduledFor DateTime? @map("scheduled_for") @db.Timestamptz
247
+
248
+ // Deferral bookkeeping, deliberately separate from `attempts` — see the
249
+ // block comment above.
250
+ rateLimitedAt DateTime? @map("rate_limited_at") @db.Timestamptz
251
+ rateLimitHits Int @default(0) @map("rate_limit_hits")
252
+
253
+ // Node claiming. See the block comment above ("claimedByNodeId") for why
254
+ // this relation arrived a migration after the column did, and why
255
+ // `onDelete: SetNull` is correct here specifically.
256
+ claimedByNodeId String? @map("claimed_by_node_id") @db.Uuid
257
+ claimedByNode WorkerNode? @relation("NodeClaimedJobs", fields: [claimedByNodeId], references: [id], onDelete: SetNull)
258
+ leaseExpiresAt DateTime? @map("lease_expires_at") @db.Timestamptz
259
+ // 'server' | 'node' — which side actually executed the job. A plain
260
+ // string, not an enum, for the same "small closed set, but code-owned and
261
+ // not this table's own state machine" reasoning as
262
+ // NotificationDelivery.channel above.
263
+ executor String?
264
+
265
+ // The identity of ONE CLAIM, not one KIND of claimant (issue #361). Minted
266
+ // fresh by the claim statement itself (`gen_random_uuid()` in
267
+ // `job-claim.service.ts`) every time a job is claimed, so "do I still hold
268
+ // this row" is answerable without reference to who is asking —
269
+ // `claimedByNodeId` distinguishes a node's claim from the server's, but
270
+ // every server replica claims with `claimedByNodeId: null`, which makes
271
+ // two different replicas holding the SAME job at different times
272
+ // indistinguishable from each other. A token minted per row closes that:
273
+ // it must be minted PER CLAIM, not once per claiming process or per batch,
274
+ // because a process-level token has the identical defect one level up — it
275
+ // cannot tell one process apart from itself across two separate claims of
276
+ // the same job (claim, lose it to the reaper, claim it again).
277
+ //
278
+ // Non-null exactly while the row is claimed — the same "non-null iff held"
279
+ // invariant `claimedByNodeId`/`leaseExpiresAt` already carry. The claim
280
+ // writes it alongside them; every un-claim path (settle, the lease reaper,
281
+ // a retry reset) clears it in the same statement that clears them, never
282
+ // on its own.
283
+ //
284
+ // Deliberately NOT exposed by the admin API — `JOB_LIST_SELECT`
285
+ // (`job-admin.service.ts`) omits it. It is internal ownership machinery
286
+ // with no operator-facing meaning; an admin reading the job list cares
287
+ // which node holds a job, not which of that node's (or the server's)
288
+ // claims it currently is.
289
+ claimToken String? @map("claim_token") @db.Uuid
290
+
291
+ // The W3C `traceparent` of the span that was active when this job was
292
+ // ENQUEUED (issue #607), or NULL when nothing was being traced (OTel off, a
293
+ // cron tick with no active span, a row written before this column existed).
294
+ // Written once, by `JobsService` at insert time (`job-trace-context.ts`
295
+ // validates the format and bounds it at 256 characters); never updated.
296
+ // The server worker starts the job's span as a CHILD of it, and the node
297
+ // claim hands it to the node, so queued work stays connected to the request
298
+ // that queued it. Plain nullable TEXT: it is an opaque correlation handle,
299
+ // never a key, never indexed, never read by the claim query's WHERE.
300
+ traceContext String? @map("trace_context")
301
+
302
+ // The organization the work belongs to (issue #734), or NULL for a
303
+ // deployment-wide (system) job: housekeeping, fleet sweeps, backups. Written
304
+ // once at enqueue (`EnqueueJobInput.orgId`, else the app's ambient scope);
305
+ // never updated. `SetNull`: deleting an organization keeps its job history
306
+ // (offboarding cancels the org's pending jobs explicitly first, #743).
307
+ //
308
+ // ⚠ NO ROW-LEVEL SECURITY ON `jobs`, deliberately. The claim is ONE
309
+ // cross-organization statement (`FOR UPDATE SKIP LOCKED` over the whole
310
+ // queue, `job-claim.service.ts`), and a per-org policy would need the bypass
311
+ // connection for every claim, renewal and settle. Isolation is enforced at
312
+ // the API: the admin routes are system routes (`jobs:read` / `jobs:write`).
313
+ // A handler that touches an org table runs under `JobScope.run(job, fn)`.
314
+ //
315
+ // ⚠ NOT PART OF THE DEDUP KEY. `jobs_active_dedup_uniq_idx` is unchanged; an
316
+ // org-scoped job with no natural subject uses `subjectType: 'organization',
317
+ // subjectId: orgId`, so two organizations never collide.
318
+ orgId String? @map("org_id") @db.Uuid
319
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: SetNull)
320
+
321
+ // See the block comment above ("Prisma-expressible indexes...") for why
322
+ // these eight are declared here and three more exist only in
323
+ // migration.sql.
324
+ //
325
+ // The hot claim-query orderings:
326
+ @@index([status, priority, createdAt])
327
+ @@index([status, scheduledFor, priority, createdAt])
328
+ // "Every job for this subject" / "is there already a job for this exact
329
+ // subject":
330
+ @@index([subjectType, subjectId])
331
+ // "How is this handler doing" (per-type status breakdown):
332
+ @@index([type, status])
333
+ // Lease expiry sweep (finding jobs whose claiming node went away):
334
+ @@index([status, leaseExpiresAt])
335
+ // "What is this node holding right now" — also backs the FK added by #267:
336
+ @@index([claimedByNodeId])
337
+ // Recency listings (admin job list, "what just happened"):
338
+ @@index([createdAt(sort: Desc)])
339
+ // Covering index: the two unconditional admin groupBy counts
340
+ // (`groupBy({ by: ['status'] })`-shaped queries) are answered entirely from
341
+ // this index — status, type and id are all it needs to project — so
342
+ // Postgres never has to visit the heap for them (index-only scan).
343
+ @@index([status, type, id])
344
+ // "This organization's jobs by status" (the admin list's `orgId` filter,
345
+ // offboarding's pending-job cancel; #734). Built CONCURRENTLY in a migration
346
+ // of its own (`0031_add_jobs_org_id_status_index`): `jobs` is a big table.
347
+ @@index([orgId, status])
348
+ @@map("jobs")
349
+ }
350
+
351
+ enum JobStatus {
352
+ pending
353
+ running
354
+ succeeded
355
+ failed
356
+ }
357
+
358
+ // =============================================================================
359
+ // Job Stats Rollup (issue #255, epic #254)
360
+ // =============================================================================
361
+ //
362
+ // One row per `type` (Job.type), maintained incrementally as jobs finish
363
+ // rather than computed by aggregating the full `jobs` table on every read —
364
+ // `jobs` is expected to grow without bound (or be pruned independently of
365
+ // this rollup's needs), so a per-type COUNT/AVG over it is not something the
366
+ // not-yet-built insights endpoint should be doing on every request.
367
+ //
368
+ // `sumDurationMs` is `Float`, deliberately not `BigInt` — see the block
369
+ // comment above the `Job` model ("sumDurationMs on JobStatsRollup") for why
370
+ // BigInt would crash `JSON.stringify` at the exact place this rollup is
371
+ // meant to be read from. Average duration for a type is
372
+ // `sumDurationMs / durationSamples`, computed by the reader; this table
373
+ // stores the two accumulators, not the derived average, so re-deriving after
374
+ // a correction never requires touching historical precision.
375
+ model JobStatsRollup {
376
+ type String @id
377
+
378
+ succeededCount Int @default(0) @map("succeeded_count")
379
+ failedCount Int @default(0) @map("failed_count")
380
+
381
+ // See the block comment above for why Float, not BigInt.
382
+ sumDurationMs Float @default(0) @map("sum_duration_ms")
383
+ durationSamples Int @default(0) @map("duration_samples")
384
+
385
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
386
+
387
+ @@map("job_stats_rollup")
388
+ }
389
+
390
+ // =============================================================================
391
+ // Worker Nodes (issue #267, epic #254)
392
+ // =============================================================================
393
+ //
394
+ // This issue adds only the schema half of the node plane: `WorkerNode`
395
+ // itself, `NodeCredential` (the `nod_` bearer credential a node authenticates
396
+ // with), and the `Job.claimedByNode` relation deferred by #255 (see the
397
+ // block comment above the `Job` model, "claimedByNodeId"). The service that
398
+ // mints/validates `NodeCredential` tokens, the `/api/node-credentials`
399
+ // endpoints, and the `Bearer nod_` branch in `jwt-auth.guard.ts` all arrive
400
+ // in the same issue's backend half; the register/heartbeat/claim control
401
+ // plane that actually populates and mutates `WorkerNode` rows is #268. What
402
+ // is here is deliberately complete on its own for that later work: every
403
+ // column and index the control plane needs already exists, so #268 requires
404
+ // no follow-up migration to either table.
405
+ //
406
+ // -----------------------------------------------------------------------------
407
+ // Why a `NodeCredential` distinct from `PersonalAccessToken`, not a reused PAT
408
+ // -----------------------------------------------------------------------------
409
+ // A worker node runs unattended for months on a machine its operator may not
410
+ // tightly control. A leaked PAT carries its owning user's FULL authority —
411
+ // admin routes included, if the owner is an admin. A node only ever needs to
412
+ // talk to `/api/nodes/*` (enforced by a route allowlist in the guard, not by
413
+ // this schema), so its credential is a distinct token family precisely so a
414
+ // leak's blast radius is confined to that allowlist even for an admin owner.
415
+ // `NodeCredential` mirrors `PersonalAccessToken`'s shape — same hash/prefix
416
+ // pattern, same show-once-in-full contract — MINUS the duration bookkeeping;
417
+ // see the block comment on `NodeCredential.expiresAt` below for why that one
418
+ // column is deliberately not carried over.
419
+ model WorkerNode {
420
+ id String @id @default(uuid()) @db.Uuid
421
+
422
+ name String
423
+
424
+ // Self-reported identity, refreshed on every successful register/reattach
425
+ // and heartbeat (#268) — none of these three are queried on individually,
426
+ // they exist for the fleet page and for operators diagnosing "which
427
+ // process is this row". Not part of any uniqueness: a node can rename its
428
+ // hostname or upgrade its CLI without becoming a different node, because
429
+ // identity is `(createdById, name)`, not any of these.
430
+ hostname String
431
+ platform String
432
+ cliVersion String @map("cli_version")
433
+
434
+ // The handler `type` keys (see `Job.type`'s own comment for why that column
435
+ // is a plain string, not an enum) this node is willing to claim. #268's
436
+ // claim endpoint INTERSECTS a request's requested types with this list — a
437
+ // node can only ever narrow what it claims, never broaden it beyond what it
438
+ // last declared itself capable of running.
439
+ eligibleTypes String[] @map("eligible_types")
440
+
441
+ // The node's own claimed concurrency ceiling, read LIVE by #268's claim
442
+ // endpoint (not cached at claim time) so a runtime `appctl node
443
+ // set-concurrency` takes effect on the very next claim without a
444
+ // re-register.
445
+ concurrency Int
446
+
447
+ // Operator/administrative state, NOT liveness — a node can be `online` and
448
+ // still be silently dead; that question is answered by comparing
449
+ // `lastHeartbeatAt` against the heartbeat interval, elsewhere (#270's fleet
450
+ // cron), not by this column. `disabled` is the operator-driven kill switch
451
+ // (refuse this node's claims regardless of what it reports); `draining` is
452
+ // "finish what you're holding, claim nothing new" — both are decisions a
453
+ // human or #270's lifecycle cron makes, not facts the node reports about
454
+ // itself.
455
+ status NodeStatus @default(offline)
456
+
457
+ // The node's last self-reported capability summary (CPU/RAM, GPU
458
+ // presence, disk headroom, ... — the exact shape is #268/#276's to define,
459
+ // not this schema's) from register or heartbeat. JSONB, not typed columns,
460
+ // for the same reason `Job.payload` is JSONB: this is opaque, evolving,
461
+ // node-supplied data that no query here needs to filter or index on —
462
+ // it exists for the fleet page to display, not for this table to reason
463
+ // about. Nullable: a node that has never heartbeated has reported nothing
464
+ // yet.
465
+ capabilities Json? @db.JsonB
466
+
467
+ // When this row was first created (register), vs. `lastHeartbeatAt` below
468
+ // which moves on every liveness ping. Distinct on purpose: "how long has
469
+ // this node existed" and "is it still alive" are different questions, and
470
+ // collapsing them into one timestamp would lose the first once the second
471
+ // starts moving.
472
+ registeredAt DateTime @default(now()) @map("registered_at") @db.Timestamptz
473
+
474
+ // NULL until the first heartbeat. #270's liveness/prune cron reads this to
475
+ // decide a node has gone dark; #268's lease reaper reads `Job
476
+ // .leaseExpiresAt` for the same question about an individual claim — the
477
+ // two are deliberately independent so a node with no jobs currently
478
+ // claimed still shows up as stale when it stops heartbeating.
479
+ lastHeartbeatAt DateTime? @map("last_heartbeat_at") @db.Timestamptz
480
+
481
+ // The node's last self-reported vitals snapshot (load, memory, disk, ...)
482
+ // carried on the heartbeat (#604). Opaque JSONB like `capabilities`: it is
483
+ // displayed, never filtered or indexed. `lastVitalsAt` is when the API
484
+ // stored it, so a stale snapshot is distinguishable from a fresh one.
485
+ // Both NULL until a heartbeat carries vitals.
486
+ lastVitals Json? @map("last_vitals") @db.JsonB
487
+ lastVitalsAt DateTime? @map("last_vitals_at") @db.Timestamptz
488
+
489
+ // The user who registered this node — see the long comment below for why
490
+ // this is required (not nullable) and `onDelete: Cascade`.
491
+ createdById String @map("created_by_id") @db.Uuid
492
+
493
+ // Relations
494
+ //
495
+ // -----------------------------------------------------------------------------
496
+ // createdBy — onDelete: Cascade, and `createdById` stays required
497
+ // -----------------------------------------------------------------------------
498
+ // This is NOT the audit-trail pattern this schema uses elsewhere
499
+ // (`AuditEvent.actorUserId`, `Credential.updatedByUser`,
500
+ // `NotificationDelivery.user` — all `SetNull`, all deliberately preserving a
501
+ // history record after its actor is gone). A `WorkerNode` is closer to
502
+ // `PushSubscription`: a LIVE registration with no standalone value once its
503
+ // owner is gone, not a record of a past event. Concretely:
504
+ //
505
+ // 1. `NodeCredential.user` is `onDelete: Cascade` (mirroring
506
+ // `PersonalAccessToken`, per this table's own design above) — so
507
+ // deleting the owning user ALREADY destroys every credential that
508
+ // could ever authenticate as this node. A `WorkerNode` row surviving
509
+ // its owner would be permanently unauthenticatable inventory: no
510
+ // token can ever heartbeat, claim, or deregister it again.
511
+ // 2. `assertOwnership` (#268) is `node.createdById === callerId` with no
512
+ // concept of "unowned" — a `SetNull`'d, ownerless node could not be
513
+ // managed (deregistered, disabled, viewed via `GET /nodes`) by
514
+ // anyone, ever, through the API this issue's sibling adds. It would
515
+ // sit as a permanently orphaned row no admin surface reaches.
516
+ // 3. `@@unique([createdById, name])` below is #268's register-or-reattach
517
+ // anchor. Keeping `createdById` NOT NULL keeps that constraint doing
518
+ // real work: two different (deleted-owner) nodes could otherwise both
519
+ // carry `createdById: null` with the same `name` and NOT collide
520
+ // (Postgres does not treat two NULLs as equal for uniqueness) — a
521
+ // silent hole in the exact invariant #268 depends on "existing
522
+ // exactly this way" for.
523
+ //
524
+ // Cascade does not touch job HISTORY: `Job.claimedByNode` is its own
525
+ // separate `onDelete: SetNull` (see the block comment above the `Job`
526
+ // model), so a cascaded `WorkerNode` deletion still only nulls out
527
+ // `claimedByNodeId` on whatever it was holding — it never deletes a `Job`
528
+ // row. Losing the fleet-inventory row (hostname, platform, capabilities
529
+ // history) when its owner's account is gone is an acceptable, even
530
+ // correct, cleanup; losing job history is not, and nothing here does that.
531
+ createdBy User @relation("UserWorkerNodes", fields: [createdById], references: [id], onDelete: Cascade)
532
+
533
+ // The jobs this node currently holds or has ever held. See `Job
534
+ // .claimedByNode`'s own comment for the `onDelete: SetNull` that keeps
535
+ // this list from ever forcing a `Job` deletion.
536
+ claimedJobs Job[] @relation("NodeClaimedJobs")
537
+
538
+ // THE register-or-reattach anchor (#268's own words: "existing exactly
539
+ // this way"). A node identifies itself to `/nodes/register` by
540
+ // `(callerId, name)`; this is what lets that endpoint find-or-create
541
+ // instead of always inserting, so a restarted container reattaches to its
542
+ // existing row (refreshing hostname/platform/cliVersion/eligibleTypes/
543
+ // concurrency and flipping back to `online`) rather than leaking a new
544
+ // node row on every restart. `name` is caller-chosen precisely so one
545
+ // user can register many distinctly-named nodes while each individual
546
+ // name stays idempotent for them.
547
+ @@unique([createdById, name])
548
+ // "Every online/draining/offline/disabled node" — the fleet page's own
549
+ // primary filter, and what #270's lifecycle cron scans to find nodes to
550
+ // act on.
551
+ @@index([status])
552
+ // "This user's own nodes" — backs `GET /nodes` (#268: "the caller's own
553
+ // nodes") and the ownership check inside `assertOwnership`, in addition to
554
+ // already being the left half of the composite unique index above.
555
+ @@index([createdById])
556
+ @@map("worker_nodes")
557
+ }
558
+
559
+ enum NodeStatus {
560
+ online
561
+ draining
562
+ offline
563
+ disabled
564
+ }
565
+
566
+ // -----------------------------------------------------------------------------
567
+ // NodeCredential — mirrors PersonalAccessToken minus the duration bookkeeping
568
+ // -----------------------------------------------------------------------------
569
+ // Same token lifecycle as `PersonalAccessToken` (`pat.service.ts` is the
570
+ // documented model for `NodeCredentialService`): a `nod_`-prefixed token is
571
+ // minted, hashed with sha256 into `tokenHash`, a short `tokenPrefix` is kept
572
+ // for display, and the raw value is shown exactly once. `validateToken`
573
+ // rejects an unknown hash, a `revokedAt`, an expired `expiresAt`, or an
574
+ // inactive owning user, then stamps `lastUsedAt` fire-and-forget — all of
575
+ // that is `NodeCredentialService`'s job (#267's backend half), not this
576
+ // schema's; this model exists to make those checks possible.
577
+ //
578
+ // -----------------------------------------------------------------------------
579
+ // expiresAt — nullable here, REQUIRED on PersonalAccessToken. This is the one
580
+ // deliberate divergence from the PAT shape, and it is worth writing out why.
581
+ // -----------------------------------------------------------------------------
582
+ // A PAT is typically minted for a person's own convenience (the CLI, a
583
+ // script they wrote) and a forced expiry is a reasonable default nudge
584
+ // toward rotation — a human is around to notice it expired and mint a new
585
+ // one. A `NodeCredential` authenticates a worker node that is expected to
586
+ // run UNATTENDED FOR MONTHS: a spare box, a container in someone else's
587
+ // cluster, a machine nobody is watching a dashboard for. If that credential
588
+ // had a mandatory expiry the way a PAT does, the failure mode is an entire
589
+ // fleet going dark at 3am because a timer nobody scheduled fired — the
590
+ // worker can't heartbeat, can't claim, can't report results, and the first
591
+ // anyone learns of it is jobs silently piling up unclaimed. That is a WORSE
592
+ // failure than a long-lived credential, because the credential's blast
593
+ // radius is already confined to `/api/nodes/*` by the guard's route
594
+ // allowlist (issue #267) even if it leaks — the thing a mandatory expiry on
595
+ // a PAT protects against (a leaked token with the owner's full authority)
596
+ // simply does not apply here to the same degree. So `expiresAt` is nullable
597
+ // and NULL is a real, supported, expected value meaning "never expires,
598
+ // authenticate indefinitely until revoked" — not "not yet set". Revocation
599
+ // (`revokedAt`) is the actual control for a node credential, and it is
600
+ // immediate: an operator who needs to cut a node off does so by revoking,
601
+ // not by waiting for a clock. An operator who DOES want an expiring node
602
+ // credential can still set one; the column supports it, it is just not
603
+ // forced.
604
+ model NodeCredential {
605
+ id String @id @default(uuid()) @db.Uuid
606
+
607
+ userId String @map("user_id") @db.Uuid
608
+
609
+ // Operator-chosen label ("prod-worker-1", "gpu-box-3"), shown alongside
610
+ // `tokenPrefix` in list views — same role as `PersonalAccessToken.name`.
611
+ name String
612
+
613
+ // sha256 hash of the full `nod_...` token; the only form of the token this
614
+ // table ever stores. Never the plaintext — see `NodeCredentialService
615
+ // .validateToken`'s own documentation for the lookup this backs.
616
+ tokenHash String @unique @map("token_hash")
617
+
618
+ // Short, non-secret display fragment (e.g. the first several characters
619
+ // after `nod_`) so an operator can tell two credentials apart in a list
620
+ // without either one's full value ever being shown again after creation.
621
+ tokenPrefix String @map("token_prefix")
622
+
623
+ // See the block comment above for why this is nullable, unlike
624
+ // `PersonalAccessToken.expiresAt` which is required. NULL = never expires.
625
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
626
+
627
+ // Stamped fire-and-forget by `validateToken` on each successful
628
+ // authentication — the operator-facing answer to "is this node actually
629
+ // still using this credential, or is it dead and safe to revoke".
630
+ lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz
631
+
632
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
633
+
634
+ // NULL means active. Set once, never cleared — revocation is a one-way
635
+ // door, matching `PersonalAccessToken.revokedAt` and `RefreshToken
636
+ // .revokedAt` elsewhere in this schema. Revocation is immediate: the
637
+ // block comment above explains why this, not a clock, is the real control
638
+ // for a node credential.
639
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
640
+
641
+ // Relations
642
+ //
643
+ // onDelete: Cascade, matching `PersonalAccessToken.user` exactly (per
644
+ // issue #267's own instruction) and for the identical reason: a node
645
+ // credential is a live, personal authentication artifact with no
646
+ // standalone value once its owning account is gone — there is no one left
647
+ // to authorize a node acting on this user's behalf, and no audit value in
648
+ // keeping hashed token material around for an account that no longer
649
+ // exists. See `WorkerNode.createdBy`'s own comment above for how this
650
+ // Cascade is part of the same reasoning that made `WorkerNode.createdBy`
651
+ // Cascade too: the two tables are designed to disappear together.
652
+ user User @relation("UserNodeCredentials", fields: [userId], references: [id], onDelete: Cascade)
653
+
654
+ // "This user's own credentials" — backs `GET /api/node-credentials`
655
+ // (#267's list endpoint), matching `PersonalAccessToken`'s own
656
+ // `@@index([userId])` for the identical query shape.
657
+ @@index([userId])
658
+ @@map("node_credentials")
659
+ }
660
+
661
+ // =============================================================================
662
+ // Job Node Secrets (issue #349, epic #345)
663
+ // =============================================================================
664
+ //
665
+ // THE AUDIT RECORD OF A CREDENTIAL A WORKER NODE ONCE HELD — and, precisely,
666
+ // NOT the credential. A node has no database access and no storage credentials
667
+ // by design (`docs/specs/worker-nodes.md` §8); epic #345 needs it to run work
668
+ // that genuinely requires one (a `pg_dump` needs a connection), so the server
669
+ // mints one per job, hands it over once, and destroys it on settlement. This
670
+ // table exists so that "which node held a credential to this deployment's
671
+ // database, of what kind, from when until when, and was it revoked" is a
672
+ // question with an answer.
673
+ //
674
+ // -----------------------------------------------------------------------------
675
+ // ⚠ THERE IS NO COLUMN HERE CAPABLE OF HOLDING SECRET MATERIAL, AND THERE MUST
676
+ // NEVER BE — NOT PLAINTEXT, NOT ENCRYPTED
677
+ // -----------------------------------------------------------------------------
678
+ //
679
+ // `handle` is an IDENTIFIER for the grant — a role name, a token id — and it is
680
+ // what `JobSecretBroker.revoke(handle)` takes. It is never the password. The
681
+ // material itself is serialised into exactly one HTTP response
682
+ // (`POST /api/nodes/:id/jobs/:jobId/secret`) and then dropped; nothing in this
683
+ // process, this database, or any backup of it retains a copy.
684
+ //
685
+ // REJECTED: an `encryptedMaterial` column, reusing `SECRETS_ENCRYPTION_KEY` the
686
+ // way the `credentials` table does. A credential that can be re-read is a
687
+ // credential that can be STOLEN TWICE, and nothing needs to re-read this one:
688
+ // the node received it once, and revocation is by handle rather than by
689
+ // presenting the secret back. `credentials` stores material because an SMTP
690
+ // password must be replayed on every send; a job credential must not be
691
+ // replayed at all. Storing it — even encrypted — would buy nothing and would
692
+ // put a live database password into this table, into every `pg_dump` of it,
693
+ // and into every copy of that dump, protected by a key that lives in the same
694
+ // deployment. That is the owner's rule for epic #345 expressed in schema rather
695
+ // than in a convention somebody can forget.
696
+ //
697
+ // -----------------------------------------------------------------------------
698
+ // `@@unique([jobId, kind])` — ONE CREDENTIAL PER JOB, EVER
699
+ // -----------------------------------------------------------------------------
700
+ //
701
+ // A node asks for its secret more than once as a matter of course: a process
702
+ // restarted while holding the lease, a response lost on the way back, a retry
703
+ // of the same job. Every one of those calls must land on the SAME grant,
704
+ // extended — never on a second one, because the revocation paths know exactly
705
+ // one handle per (job, kind) and a sibling grant would be one nothing ever
706
+ // destroys. The unique index makes the second row unrepresentable; the broker's
707
+ // own `issue` idempotence (see `job-secret-broker.ts`) is the other half.
708
+ //
709
+ // `@@index([expiresAt])` backs the sweeper, which scans unrevoked grants whose
710
+ // own clock has lapsed. See `NodeSecretBrokerService.sweep` for why the sweeper
711
+ // is NOT redundant with the settle-event revoker: three real cases emit no
712
+ // event at all.
713
+ //
714
+ // NO RELATIONS, DELIBERATELY. `jobId` and `nodeId` are plain UUID columns with
715
+ // no foreign key either way, for two reasons. `jobs` rows are deleted on a
716
+ // retention schedule (`job.history.purge`) that has nothing to do with a
717
+ // grant's lifetime, and a cascade from that purge would silently erase the
718
+ // audit record of a credential — which is the one thing this table is for. And
719
+ // a grant must stay revocable by handle after its job row is gone, which is
720
+ // why the sweeper resolves a broker by `kind` rather than by the job's `type`.
721
+ model JobNodeSecret {
722
+ id String @id @default(uuid()) @db.Uuid
723
+
724
+ jobId String @map("job_id") @db.Uuid
725
+ nodeId String @map("node_id") @db.Uuid
726
+
727
+ // Which broker minted this — `JobSecretBroker.kind`, e.g.
728
+ // `'postgres.readonly'`. Also how the revocation paths find their way back
729
+ // to the broker that can destroy the grant. A plain string, not an enum, for
730
+ // the same reason `Job.type` is: a fork's broker must cost zero migrations.
731
+ kind String
732
+
733
+ // The grant's identifier. ⚠ THE ROLE NAME. NEVER THE PASSWORD. See the block
734
+ // comment above.
735
+ handle String
736
+
737
+ issuedAt DateTime @default(now()) @map("issued_at") @db.Timestamptz
738
+ // The credential's own backstop, bounded by the job's lease (never a second
739
+ // clock of its own — see `JobSecretBroker.issue`). It is what makes a grant
740
+ // worthless if BOTH revocation paths somehow miss it.
741
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
742
+ // NULL means the grant is still live as far as this server knows. Set by
743
+ // whichever revocation path got there first; both tolerate the other having
744
+ // won.
745
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
746
+
747
+ @@unique([jobId, kind])
748
+ @@index([expiresAt])
749
+ @@map("job_node_secrets")
750
+ }
751
+
752
+ extend model User {
753
+ workerNodes WorkerNode[] @relation("UserWorkerNodes")
754
+ nodeCredentials NodeCredential[] @relation("UserNodeCredentials")
755
+ }
756
+
757
+ extend model Organization {
758
+ // The organization's jobs (issue #734): see `Job.orgId` for why `SetNull`.
759
+ jobs Job[]
760
+ }