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

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 +86 -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,444 @@
1
+ // =============================================================================
2
+ // AI Platform (issue #423, epic #419, umbrella #418)
3
+ // =============================================================================
4
+ //
5
+ // Four tables — the model catalog, per-user encrypted provider keys,
6
+ // background AI run results, and usage accounting — for the whole platform
7
+ // this epic builds. THIS ISSUE OWNS SCHEMA ONLY: no service or controller in
8
+ // this build reads or writes any of these tables yet (that is #427, #428,
9
+ // #431, #432). They land ahead of their consumers, on the same "declare the
10
+ // collision hotspot once, let every other AI story run in parallel" logic
11
+ // `system-settings.service.ts`'s operations-namespaces header already argues
12
+ // for `system_settings`: `schema.prisma`, `seed-data.ts`,
13
+ // `roles.constants.ts` and `settings.schema.ts` are each touched by every
14
+ // story in the epic, so this one story claims them in a single migration
15
+ // instead of every later story racing to edit the same four files.
16
+ //
17
+ // -----------------------------------------------------------------------------
18
+ // ⚠ NO COLUMN HERE CAN EVER HOLD A PLAINTEXT PROVIDER KEY
19
+ // -----------------------------------------------------------------------------
20
+ // `UserAiKey.secret` is ciphertext ONLY — the output of `encryptSecret(
21
+ // plaintext, 'ai_user_key')` (`@marinoscar/platform-api/core`), the same
22
+ // AES-GCM helper `Credential.secret` already uses, keyed under a purpose
23
+ // label specific to this table so a ciphertext lifted from one row cannot be
24
+ // decrypted as if it were the other's. `hint` is the non-secret display aid
25
+ // (`'••••' + last 4`, mirroring `Credential.hint`), never enough on its own
26
+ // to reconstruct the key. `AiRun.request` is explicitly a NORMALIZED request
27
+ // — model id, parameters, truncated/redacted prompt shape — never the
28
+ // caller's raw provider key, which the run's own executor already holds
29
+ // separately (from `UserAiKey`, decrypted for that one call and discarded).
30
+ //
31
+ // -----------------------------------------------------------------------------
32
+ // `UserAiKey` — Cascade, NOT SetNull, and the contrast with `Credential` is
33
+ // deliberate
34
+ // -----------------------------------------------------------------------------
35
+ // `Credential.updatedByUser` is `SetNull`: that table is shared
36
+ // infrastructure (an SMTP password, a storage secret) that outlives whoever
37
+ // last edited it, because the credential belongs to the DEPLOYMENT, not to
38
+ // the editor. `UserAiKey.user` is the opposite shape on purpose — a BYOK key
39
+ // belongs to the ONE ACCOUNT that typed it in, has no meaning to anyone else,
40
+ // and (like `PushSubscription.user`, which makes the identical argument for a
41
+ // live per-device credential) has no reader once that account is gone. There
42
+ // is no "the deployment's OpenAI key" here, only "this user's OpenAI key", so
43
+ // deleting the user is what should delete it.
44
+ //
45
+ // -----------------------------------------------------------------------------
46
+ // `AiRun.user` / `AiUsageEvent.user` — SetNull, matching `NotificationDelivery
47
+ // .user`
48
+ // -----------------------------------------------------------------------------
49
+ // Both are HISTORY, not live state: a run's output and a usage event's token
50
+ // counts remain meaningful — for billing reconciliation, for "was this
51
+ // account affected by the incident on provider X" — after the account that
52
+ // triggered them is gone, exactly the argument `NotificationDelivery.user`'s
53
+ // own block comment makes for a delivery attempt. Nulling the FK preserves
54
+ // that record; cascading it would erase usage accounting as a side effect of
55
+ // an unrelated account-deletion path elsewhere in the app. Both are also
56
+ // deliberately nullable up front (not merely nullable-after-cascade), the same
57
+ // "global job" shape `Job.subjectType`/`subjectId` use: a background run or a
58
+ // catalog-discovery usage event may have no requesting user at all.
59
+ //
60
+ // -----------------------------------------------------------------------------
61
+ // `capabilities` / `units` — JSONB, not typed columns, and Zod-validated in
62
+ // code
63
+ // -----------------------------------------------------------------------------
64
+ // `AiModel.capabilities` (what a model can do — text, vision, tool calling,
65
+ // structured output, ...) and `AiUsageEvent.units` (a per-operation unit
66
+ // count that varies by kind: `{ images: 2 }`, `{ audioSeconds: 31.4 }`) are
67
+ // each shaped differently per provider and per operation, and neither is
68
+ // filtered or indexed on by any query this issue's schema needs to support.
69
+ // Both follow `Job.payload`'s and `WorkerNode.capabilities`' own precedent:
70
+ // opaque JSONB here, a real Zod schema (`AiModelCapabilities`) at the
71
+ // consuming layer that arrives with #427/#428. A typed column per capability
72
+ // would be a migration every time a provider ships a new one.
73
+ //
74
+ // -----------------------------------------------------------------------------
75
+ // `provider` / `operation` / `status` / `keySource` — plain strings, not
76
+ // Prisma enums
77
+ // -----------------------------------------------------------------------------
78
+ // Same reasoning as `Job.type`, `NotificationDelivery.channel` and
79
+ // `WorkerNode.executor` throughout this file: these are small, code-owned,
80
+ // GROWING sets (`AI_PROVIDER_IDS` names `'openai'` today and Phase 3 appends
81
+ // to it; new operations and key sources are exactly the shape of change a
82
+ // provider integration adds), so a Postgres enum would reintroduce the
83
+ // migration this design otherwise avoids, and a row must be able to outlive
84
+ // whatever build produced it. `AiRun.status` and `AiUsageEvent.status` are
85
+ // each that model's OWN closed state machine in every other sense — but they
86
+ // are kept as strings rather than promoted to a Prisma enum for the same
87
+ // forward-compatibility reason the rest of this section gives, not because
88
+ // they are open-ended in practice.
89
+ //
90
+ // -----------------------------------------------------------------------------
91
+ // `AiModel.capabilitySource` — `'catalog' | 'admin_override' | 'unclassified'`
92
+ // -----------------------------------------------------------------------------
93
+ // Records WHERE `capabilities` came from, because the three sources disagree
94
+ // in trustworthiness and in how long they last: `'catalog'` is the
95
+ // provider's own advertised capability list (refreshed on discovery, and the
96
+ // first thing a later sync overwrites), `'admin_override'` is a deployment
97
+ // operator's manual correction (must survive a catalog refresh that would
98
+ // otherwise clobber it — that survival rule belongs to #427's sync logic, not
99
+ // to this column), and `'unclassified'` is the default for a model this
100
+ // deployment has seen but never classified at all. A model discovered before
101
+ // any classification runs is `'unclassified'`, never a guess.
102
+ model AiModel {
103
+ id String @id @default(uuid()) @db.Uuid
104
+
105
+ // The provider registration this model belongs to, e.g. `'openai'`. See
106
+ // `AI_PROVIDER_IDS` (`common/schemas/settings.schema.ts`) — a growing,
107
+ // code-owned list, and a plain string here for the reason given above.
108
+ provider String
109
+
110
+ // The provider's own raw model identifier (e.g. `'gpt-4o-mini'`), as
111
+ // opposed to `id` above, which is this table's own row identity.
112
+ modelId String @map("model_id")
113
+
114
+ // Operator/UI-facing label. Nullable: a freshly discovered model has none
115
+ // until an admin (or a later sync) names it.
116
+ displayName String? @map("display_name")
117
+
118
+ // AiModelCapabilities, Zod-validated at the consuming layer (#427) — see
119
+ // the block comment above for why this is JSONB rather than typed columns.
120
+ capabilities Json
121
+
122
+ // Where `capabilities` came from — see the block comment above.
123
+ // `'unclassified'` is the default: a model this deployment has observed but
124
+ // not yet classified, one way or the other.
125
+ capabilitySource String @default("unclassified") @map("capability_source")
126
+
127
+ // Whether this deployment offers the model to callers at all. Defaults to
128
+ // `false`: a freshly discovered model is inert until an administrator (or a
129
+ // later sync's own policy) turns it on, the same "nothing changes behaviour
130
+ // on discovery alone" posture `WorkerNode.status` defaulting to `offline`
131
+ // and `databaseBackup.enabled` defaulting to `false` both take elsewhere in
132
+ // this schema.
133
+ enabled Boolean @default(false)
134
+
135
+ contextWindow Int? @map("context_window")
136
+ maxOutputTokens Int? @map("max_output_tokens")
137
+
138
+ // When this row was first created, vs. `lastSeenAt` below, which moves on
139
+ // every discovery sync that still finds the model — the same "creation time
140
+ // vs. liveness" split `WorkerNode.registeredAt`/`.lastHeartbeatAt` make for
141
+ // an entirely different kind of inventory.
142
+ discoveredAt DateTime @default(now()) @map("discovered_at") @db.Timestamptz
143
+ lastSeenAt DateTime @default(now()) @map("last_seen_at") @db.Timestamptz
144
+ // Set by a discovery sync (#427) that no longer sees this model in the
145
+ // provider's own catalog. Nullable: most rows are never deprecated.
146
+ // Deliberately not deleted — a deprecated model may still be referenced by
147
+ // historical `AiRun`/`AiUsageEvent` rows via its `provider`/`modelId` pair,
148
+ // and losing the row would lose the display name and capability record for
149
+ // that history.
150
+ deprecatedAt DateTime? @map("deprecated_at") @db.Timestamptz
151
+
152
+ // Provenance of the last edit — see the block comment above for why this
153
+ // is `SetNull`, matching `Credential.updatedByUser` rather than
154
+ // `UserAiKey.user` below.
155
+ updatedByUserId String? @map("updated_by_user_id") @db.Uuid
156
+ updatedByUser User? @relation("AiModelUpdatedBy", fields: [updatedByUserId], references: [id], onDelete: SetNull)
157
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
158
+
159
+ // One row per (provider, model) pair, ever — a discovery sync upserts on
160
+ // this rather than inserting duplicates on every re-run.
161
+ @@unique([provider, modelId])
162
+ // "Which models may this deployment currently offer" — the catalog read
163
+ // every AI-calling path needs, filtered to the provider in play.
164
+ @@index([provider, enabled])
165
+ @@map("ai_models")
166
+ }
167
+
168
+ // BYOK ("bring your own key"): one encrypted provider key per (user,
169
+ // provider), never per deployment. See the block comment above this section
170
+ // for why `user` is `Cascade` here and NOT `SetNull` like `Credential
171
+ // .updatedByUser` or `AiModel.updatedByUser` above — this key has exactly one
172
+ // owner and no meaning to anyone else once that owner's account is gone.
173
+ model UserAiKey {
174
+ id String @id @default(uuid()) @db.Uuid
175
+ userId String @map("user_id") @db.Uuid
176
+
177
+ // Which provider this key authenticates against, e.g. `'openai'`. Plain
178
+ // string for the same forward-compatibility reason `AiModel.provider` is.
179
+ provider String
180
+
181
+ // Ciphertext ONLY — `encryptSecret(plaintext, 'ai_user_key')`. See the
182
+ // block comment above this section (and `Credential.secret`'s own comment)
183
+ // for the full argument; @db.Text for the identical reason
184
+ // `Credential.secret` is: an AES-GCM payload has no meaningful length
185
+ // bound, so it must never be truncated.
186
+ secret String @db.Text
187
+
188
+ // Non-secret display aid (`'••••' + last 4`), mirroring `Credential.hint`.
189
+ // Nullable: a key can exist before anyone has decided how to hint it.
190
+ hint String?
191
+
192
+ // The last time this key was proven to work against its provider (a live
193
+ // probe call, not merely "was saved"). Nullable: never verified yet.
194
+ verifiedAt DateTime? @map("verified_at") @db.Timestamptz
195
+ // The provider's own error code from the most recent failed verification or
196
+ // use, so a user who cannot see why a key stopped working has somewhere to
197
+ // look. Nullable: no failure recorded (yet, or ever).
198
+ lastErrorCode String? @map("last_error_code")
199
+
200
+ // Which of this provider's models this specific key was actually able to
201
+ // reach on its last verification, as opposed to `AiModel.enabled`, which is
202
+ // a DEPLOYMENT-WIDE policy decision independent of any one key. A key with
203
+ // a narrower API scope, or one hitting a provider-side allowlist, can
204
+ // legitimately reach fewer models than the deployment otherwise offers.
205
+ reachableModelIds String[] @default([]) @map("reachable_model_ids")
206
+ reachableCheckedAt DateTime? @map("reachable_checked_at") @db.Timestamptz
207
+
208
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
209
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
210
+
211
+ // Relations
212
+ //
213
+ // Cascade — see the block comment above this section for why this
214
+ // deliberately reverses `Credential.updatedByUser`'s `SetNull`.
215
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
216
+
217
+ // One key per (user, provider) — saving a new key for a provider replaces
218
+ // the old one rather than accumulating a history of them.
219
+ @@unique([userId, provider])
220
+ @@map("user_ai_keys")
221
+ }
222
+
223
+ // One row per AI call this platform ever ran through the background queue —
224
+ // the record `#432`'s job handler(s) read from and write progress/output to.
225
+ // This issue is schema only, matching every other table in this section: no
226
+ // enqueue path, no job handler and no controller exists yet.
227
+ // @extensible — back-relations only, added with "extend model AiRun { ... }" in a fragment
228
+ // (an app's own annotation of a run, for example a review verdict). The table is org-owned
229
+ // with row-level security forced, so a table of the app's that holds `org_id` links to a run
230
+ // with a composite foreign key `(ai_run_id, org_id)` -> `ai_runs (id, org_id)`; the
231
+ // `@@unique([id, orgId])` below exists for it.
232
+ model AiRun {
233
+ id String @id @default(uuid()) @db.Uuid
234
+
235
+ // Nullable, deliberately — see the block comment above this section for why
236
+ // this is `SetNull` rather than `Cascade`, and why a run may have no
237
+ // requesting user at all (a system-initiated run, mirroring `Job.subjectType`
238
+ // /`subjectId` both being null together for a global job).
239
+ userId String? @map("user_id") @db.Uuid
240
+
241
+ // The `jobs` row this run executes under, when it runs through the queue at
242
+ // all. Nullable, and deliberately NOT a foreign key — mirrors
243
+ // `DatabaseBackupRun`'s OWN relation to `Job` in spirit (a dedicated table
244
+ // outliving the generic queue's retention) but stays a plain column rather
245
+ // than a `@relation`+`@unique` pair: unlike a backup run, an `AiRun` is not
246
+ // one-to-one with its job in every future shape this platform may take
247
+ // (a retried run may reuse the id, or a future synchronous path may have no
248
+ // job at all), so this issue commits only to recording the id, not to the
249
+ // stronger one-to-one relation `DatabaseBackupRun.jobId` commits to.
250
+ jobId String? @map("job_id") @db.Uuid
251
+
252
+ // pending|running|succeeded|failed|cancelled — this run's own state
253
+ // machine, kept as a plain string rather than a Prisma enum for the
254
+ // forward-compatibility reason given in the block comment above this
255
+ // section.
256
+ status String @default("pending")
257
+
258
+ provider String
259
+ modelId String @map("model_id")
260
+
261
+ // The NORMALIZED request — model id, parameters, and the FULL prompt shape
262
+ // (instructions, input, tools, structured-output schema) `toStoredRunRequest`
263
+ // (`runtime/ai-run-request.ts`) built from it — and NEVER the caller's key
264
+ // material, which this run's executor holds separately and only for the
265
+ // duration of the call. Deliberately not redacted or truncated: the
266
+ // worker that claims this job re-issues the user's exact request, and a
267
+ // truncated prompt would make the replayed call diverge from the one the
268
+ // user actually asked for. See the ⚠ block comment above this section.
269
+ request Json
270
+
271
+ output Json?
272
+ errorCode String? @map("error_code")
273
+ errorMessage String? @map("error_message")
274
+
275
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
276
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
277
+ completedAt DateTime? @map("completed_at") @db.Timestamptz
278
+
279
+ // The organization the run belongs to (#725). NOT NULL, row-level security
280
+ // forced (policy `ai_runs_org_isolation`). `Restrict`, not `SetNull`: the
281
+ // column is NOT NULL, so history cannot survive an organization's deletion
282
+ // by nulling it; deleting an organization first purges its runs.
283
+ orgId String @map("org_id") @db.Uuid
284
+
285
+ // The registered AI feature the run was started for (`registerAiFeature`,
286
+ // PP-14.17, #935): a bounded id the feature registry validated, NEVER free
287
+ // text. Nullable (a run started without a feature, and every row written
288
+ // before this column existed), and a plain string rather than a reference:
289
+ // a feature is code, not data, and a row must outlive the feature that
290
+ // wrote it. Carried onto the run's usage rows, so per-feature usage is
291
+ // answerable from the database.
292
+ feature String?
293
+
294
+ // Relations
295
+ //
296
+ // SetNull — see the block comment above this section.
297
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
298
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
299
+
300
+ // "This user's run history, most recent first" — the one query this table
301
+ // is known to need today (a user's own run list).
302
+ @@index([userId, createdAt])
303
+ // The same query behind the policy filter `org_id = X`.
304
+ @@index([orgId, userId, createdAt])
305
+ // The retention sweep (`ai.runs.purge`, #681): "oldest first, older than
306
+ // the cutoff" across every user, which `[userId, createdAt]` cannot serve.
307
+ @@index([createdAt])
308
+ // The target of an app table's composite foreign key (id, org_id), like
309
+ // `Group` and `StorageObject`: a plain FK on `id` would let a row of one
310
+ // organization point at another's (an FK check bypasses row-level security).
311
+ @@unique([id, orgId])
312
+ @@map("ai_runs")
313
+ }
314
+
315
+ // One row per AI operation attempted, successful or not — the usage/billing
316
+ // accounting ledger, deliberately separate from `AiRun` above. `AiRun` is
317
+ // "what did this background call do" (one row per queued call, with its own
318
+ // request/output); `AiUsageEvent` is "what did this cost", covering every
319
+ // operation kind (`responses|images|audio.transcribe|audio.speech|
320
+ // embeddings|catalog`) whether or not it went through the queue at all — a
321
+ // synchronous catalog-listing call has no `AiRun` but still consumes a
322
+ // provider call worth recording.
323
+ model AiUsageEvent {
324
+ id String @id @default(uuid()) @db.Uuid
325
+
326
+ // Nullable, `SetNull` — see the block comment above this section. A
327
+ // catalog-discovery sync run by the deployment itself, not by any one
328
+ // user, is the concrete case that leaves this null.
329
+ userId String? @map("user_id") @db.Uuid
330
+
331
+ provider String
332
+ modelId String @map("model_id")
333
+
334
+ // responses|images|audio.transcribe|audio.speech|embeddings|catalog — the
335
+ // kind of provider call this event records. Plain string for the
336
+ // forward-compatibility reason given above: a new operation kind (a future
337
+ // provider capability) must cost zero migrations here.
338
+ operation String
339
+
340
+ // user|org|admin_discovery — WHOSE key paid for this call. Distinct from
341
+ // `provider`/`modelId` (which model answered) and from `userId` (who asked):
342
+ // an admin-triggered catalog discovery sync can be `keySource:
343
+ // 'admin_discovery'` with no requesting `userId` at all, and a BYOK-only
344
+ // deployment's every real usage event is `keySource: 'user'`. `'org'` is
345
+ // reserved for a future org-wide fallback key, matching `AI_KEY_POLICIES`'
346
+ // `'byok_with_org_fallback'` in `common/schemas/settings.schema.ts`.
347
+ keySource String @map("key_source")
348
+
349
+ // Token accounting. All nullable: an `images`/`audio.*` operation has no
350
+ // token counts at all, and `reasoningTokens`/`cachedInputTokens` are
351
+ // provider-specific breakdowns that not every provider or model reports.
352
+ inputTokens Int? @map("input_tokens")
353
+ outputTokens Int? @map("output_tokens")
354
+ reasoningTokens Int? @map("reasoning_tokens")
355
+ cachedInputTokens Int? @map("cached_input_tokens")
356
+
357
+ // Non-token unit accounting for operations tokens don't measure — e.g.
358
+ // `{ images: 2 }` for an image generation call, `{ audioSeconds: 31.4 }` for
359
+ // transcription/speech. JSONB for the reason given in the block comment
360
+ // above this section: the shape varies by `operation` and no query here
361
+ // filters or indexes on it.
362
+ units Json?
363
+
364
+ latencyMs Int @map("latency_ms")
365
+
366
+ // succeeded|failed|cancelled — this event's own closed outcome, kept as a
367
+ // plain string for the identical forward-compatibility reason `AiRun
368
+ // .status` is.
369
+ status String
370
+ errorCode String? @map("error_code")
371
+
372
+ // The provider's own request/trace id, for reconciling a usage row against
373
+ // that provider's dashboard or support ticket. Nullable: not every provider
374
+ // call surfaces one.
375
+ providerRequestId String? @map("provider_request_id")
376
+
377
+ // The `jobs` row this usage event was incurred under, when it was. Plain
378
+ // column, no relation — same reasoning as `AiRun.jobId` above.
379
+ jobId String? @map("job_id") @db.Uuid
380
+
381
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
382
+
383
+ // The organization that incurred the call (#725). Nullable on purpose: a
384
+ // deployment-wide event (a catalogue sync) has none, and `SetNull` keeps the
385
+ // history of a deleted organization. Row-level security forced (policy
386
+ // `ai_usage_events_org_isolation`): a NULL row is visible to the system
387
+ // client only.
388
+ orgId String? @map("org_id") @db.Uuid
389
+
390
+ // The registered AI feature the call was made for (`registerAiFeature`,
391
+ // PP-14.17, #935), so usage can be filtered and grouped per feature from
392
+ // the database. Nullable: a call made without a feature, a catalogue sync,
393
+ // and every row written before this column existed have none. A plain
394
+ // string, never a reference, and never free text: only an id the feature
395
+ // registry validated is written.
396
+ feature String?
397
+
398
+ // Relations
399
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
400
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: SetNull)
401
+
402
+ // "This user's usage history, most recent first" — mirrors `AiRun`'s own
403
+ // index for the identical reason.
404
+ @@index([userId, createdAt])
405
+ // The same query behind the policy filter `org_id = X`, and the per-org
406
+ // usage window.
407
+ @@index([orgId, userId, createdAt])
408
+ @@index([orgId, createdAt])
409
+ // "This organization's usage of one feature in a window" (PP-14.17, #935):
410
+ // the per-feature filter and group-by of the usage report.
411
+ @@index([orgId, feature, createdAt])
412
+ // "Usage across all users in a time window" — the deployment-wide
413
+ // accounting/billing query, independent of any one user.
414
+ @@index([createdAt])
415
+ @@map("ai_usage_events")
416
+ }
417
+
418
+ extend model User {
419
+ // AI platform (#423, epic #419). Four relations, four different
420
+ // `onDelete` answers — see each model's own block comment for why:
421
+ // - `aiModelsUpdated` (`AiModel.updatedByUser`) is provenance on a
422
+ // CATALOG row nobody owns, so `SetNull`, matching `Credential
423
+ // .updatedByUser` above.
424
+ // - `aiKeys` (`UserAiKey.user`) is `Cascade`: a BYOK key belongs to the
425
+ // user who typed it in, in exactly the sense `PushSubscription.user`
426
+ // does — there is no reader for it once the account is gone.
427
+ // - `aiRuns` (`AiRun.user`) is `SetNull`: a run is history, kept for
428
+ // usage/audit purposes independent of whether its requester's account
429
+ // still exists, matching `NotificationDelivery.user`.
430
+ // - `aiUsageEvents` (`AiUsageEvent.user`) is `SetNull` for the identical
431
+ // reason `aiRuns` is: usage accounting must outlive the account it
432
+ // billed.
433
+ aiModelsUpdated AiModel[] @relation("AiModelUpdatedBy")
434
+ aiKeys UserAiKey[]
435
+ aiRuns AiRun[]
436
+ aiUsageEvents AiUsageEvent[]
437
+ }
438
+
439
+ extend model Organization {
440
+ // AI runs and usage events (#725): see `AiRun.orgId` and `AiUsageEvent.orgId`
441
+ // for why one is `Restrict` and the other `SetNull`.
442
+ aiRuns AiRun[]
443
+ aiUsageEvents AiUsageEvent[]
444
+ }
@@ -0,0 +1,47 @@
1
+ /// An Android APK this deployment hosts (#746, PP-9.4; merged from EvoPath and
2
+ /// MemoriaHub). Uploaded by an administrator (the admin Android app page, or
3
+ /// `appctl android publish`), streamed into object storage under the
4
+ /// `android-releases/` key prefix, downloaded by signed-in users through a
5
+ /// short-lived signed link (`/api/android-app/download/<token>`).
6
+ ///
7
+ /// AT MOST ONE RELEASE IS CURRENT deployment-wide: the raw-SQL partial unique
8
+ /// index `android_app_releases_one_current_uniq_idx` (migration SQL only;
9
+ /// Prisma cannot express a partial unique index). Never declare it as
10
+ /// @@unique and never replace it with a findFirst pre-check: make-current
11
+ /// clears the old flag and sets the new one in one transaction, and the
12
+ /// database rejects a second current row (P2002, mapped to 409
13
+ /// RELEASE_CURRENT_CONFLICT).
14
+ ///
15
+ /// `sizeBytes` is BigInt (MemoriaHub's choice; EvoPath used Int): the API
16
+ /// returns it as a decimal string. `storageProvider` and `bucket` record where
17
+ /// the bytes were written (the DatabaseBackupRun precedent), so a doctor check
18
+ /// can tell a release stranded by a provider switch. A deployment artifact:
19
+ /// kept by the user-data reset (uploader SetNull) and by the factory reset
20
+ /// (its prefix is registered `survivesFactoryReset: true`).
21
+ model AndroidAppRelease {
22
+ id String @id @default(uuid()) @db.Uuid
23
+ packageName String @map("package_name")
24
+ versionName String @map("version_name") @db.VarChar(50)
25
+ versionCode Int @map("version_code")
26
+ signingSha256 String @map("signing_sha256")
27
+ fileSha256 String @map("file_sha256") @db.Char(64)
28
+ sizeBytes BigInt @map("size_bytes")
29
+ storageKey String @map("storage_key")
30
+ storageProvider String? @map("storage_provider")
31
+ bucket String?
32
+ notes String? @db.VarChar(2000)
33
+ isCurrent Boolean @default(false) @map("is_current")
34
+ uploadedById String? @map("uploaded_by_id") @db.Uuid
35
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
36
+
37
+ uploadedBy User? @relation("AndroidAppReleaseUploader", fields: [uploadedById], references: [id], onDelete: SetNull)
38
+
39
+ @@unique([packageName, versionCode])
40
+ @@index([createdAt])
41
+ @@index([uploadedById])
42
+ @@map("android_app_releases")
43
+ }
44
+
45
+ extend model User {
46
+ androidAppReleases AndroidAppRelease[] @relation("AndroidAppReleaseUploader")
47
+ }
@@ -0,0 +1,11 @@
1
+ // =============================================================================
2
+ // Prisma Schema - Web Application Foundation
3
+ // =============================================================================
4
+
5
+ generator client {
6
+ provider = "prisma-client-js"
7
+ }
8
+
9
+ datasource db {
10
+ provider = "postgresql"
11
+ }