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

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 +88 -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,26 @@
1
+ -- =============================================================================
2
+ -- `database_backup_runs.pg_dump_version` (issue #352, epic #345)
3
+ -- =============================================================================
4
+ -- The fourth member of this table's audit block: WHICH `pg_dump` wrote the
5
+ -- archive.
6
+ --
7
+ -- It was worth nothing while the dump could only run in the API process — the
8
+ -- client is whatever `apps/api/Dockerfile` installed, the same for every run,
9
+ -- and the node-credential preflight already reports it. #352 makes the dump
10
+ -- claimable by a worker node, and on that path the binary lives on a machine
11
+ -- this deployment may not own and cannot inspect after the fact. Without this
12
+ -- column, nothing anywhere records which client produced the file, and
13
+ -- "`pg_restore` cannot read an archive written by a NEWER `pg_dump`" becomes a
14
+ -- fact an operator discovers during a restore rather than one they can check
15
+ -- before starting it (see docs/runbooks/postgres-client-version.md).
16
+ --
17
+ -- Nullable, no default, NO BACKFILL. Every existing row was written by a
18
+ -- client nobody recorded, and inventing this deployment's CURRENT client
19
+ -- version for them would be a lie that reads exactly like evidence. NULL means
20
+ -- "not recorded", which is the truth for every run taken before this migration
21
+ -- and for any run whose `pg_dump --version` could not be read — the same
22
+ -- "warn and proceed" rule the other three audit columns already follow.
23
+ -- =============================================================================
24
+
25
+ -- AlterTable
26
+ ALTER TABLE "database_backup_runs" ADD COLUMN "pg_dump_version" TEXT;
@@ -0,0 +1,92 @@
1
+ -- =============================================================================
2
+ -- jobs.claim_token — per-claim identity, closing the two-replica lease hole
3
+ -- (issue #361)
4
+ -- =============================================================================
5
+ -- `heldLeaseWhere` (`src/jobs/job-lease.service.ts`) answers "does the caller
6
+ -- still hold this row" as `{ id, status: 'running', leaseExpiresAt: { gt: now
7
+ -- }, claimedByNodeId }`. That predicate identifies a CLAIMANT KIND — "a node"
8
+ -- (a real `WorkerNode.id`) vs. "the server" (`claimedByNodeId: null`) — not a
9
+ -- particular claim. Every API replica claims with `claimedByNodeId: null`, so
10
+ -- two server replicas produce the exact same `heldLeaseWhere` predicate for
11
+ -- the same job. Concretely: replica A claims a job, then stalls long enough
12
+ -- for the lease reaper to reclaim it as abandoned; replica B claims the
13
+ -- now-pending job and starts running it; replica A, still alive and unaware
14
+ -- it lost the row, calls `renew` — which matches `heldLeaseWhere` (status is
15
+ -- `running`, `claimedByNodeId` is `null`, and the lease B just set is still
16
+ -- in the future) and happily extends B's lease. A never learns it lost the
17
+ -- job, and now believes it owns work it does not.
18
+ --
19
+ -- The fix is a column that identifies ONE CLAIM, not one KIND of claimant:
20
+ -- `claim_token`, minted fresh (`gen_random_uuid()`) by the claim statement
21
+ -- itself and folded into `heldLeaseWhere` alongside `claimedByNodeId` (wiring
22
+ -- lands in a later slice — this migration and its schema.prisma companion are
23
+ -- schema-only, per the issue's stated scope). Once every renew/settle/reap
24
+ -- statement also matches on `claim_token`, replica A's renewal after losing
25
+ -- the row targets a token that is no longer on the row (B's claim overwrote
26
+ -- it with a new one) and the `UPDATE` matches zero rows, exactly like a node
27
+ -- losing a lease already does today.
28
+ --
29
+ -- -----------------------------------------------------------------------------
30
+ -- Why NULLABLE, with no DEFAULT
31
+ -- -----------------------------------------------------------------------------
32
+ -- The invariant this codebase will maintain from here on is `claim_token IS
33
+ -- NOT NULL` IFF the row is currently held under a claim. A `pending` job has
34
+ -- no claimant at all, so writing it a token would assert a claim that does
35
+ -- not exist — a lie the column has no business telling. `DEFAULT
36
+ -- gen_random_uuid()` would do exactly that: every row, including ones freshly
37
+ -- enqueued and never claimed, would carry a token that means nothing,
38
+ -- indistinguishable from a real one to anybody reading the column.
39
+ --
40
+ -- No backfill, and none is wanted. Every row that exists at deploy time is
41
+ -- either not currently claimed (`pending`, `succeeded`, `failed` — `NULL` is
42
+ -- simply correct) or `running` under a claim taken by a REPLICA RUNNING THE
43
+ -- OLD CODE, which never wrote a token and has no token to reconcile against.
44
+ -- `NULL` is still correct there, but the reason an old replica keeps renewing
45
+ -- successfully has nothing to do with NULL comparison semantics — it is
46
+ -- simpler than that: an old replica is running the OLD `heldLeaseWhere`,
47
+ -- which has no `claim_token` clause at all, so it never passes a token,
48
+ -- remembered or otherwise, and this column is invisible to its predicate.
49
+ -- The later slice's `heldLeaseWhere(jobId, { nodeId?, claimToken? })` treats
50
+ -- `claimToken` the same three-valued way `nodeId` already works: a string
51
+ -- constrains the match to that one claim, `undefined` omits the clause
52
+ -- entirely (what the node control plane and this migration-era code both do),
53
+ -- and `null` is passed straight through to Prisma and renders as an actual
54
+ -- `claim_token IS NULL` check — matching only a row that carries no token.
55
+ --
56
+ -- That makes the rolling-deploy story a narrowing, not a full close, and only
57
+ -- in one direction: a NEW replica's claim writes a real token, so no other
58
+ -- NEW replica can renew it out from under the claimant — the hole
59
+ -- is closed between new replicas from the moment this ships. An OLD
60
+ -- replica's `renew` still ignores `claim_token` altogether, so an old
61
+ -- replica that lost a row to the reaper can still extend a NEW replica's
62
+ -- lease for as long as the old replica keeps ticking — the same failure mode
63
+ -- this column exists to fix, just now confined to "one side of the pair is
64
+ -- still running pre-#361 code" instead of "always". That window is bounded
65
+ -- and ordinary: it closes for good once the last old replica has rolled off,
66
+ -- the same way any predicate change behaves during a rolling deploy, and is
67
+ -- not a reason to change this design.
68
+ --
69
+ -- -----------------------------------------------------------------------------
70
+ -- Why no index
71
+ -- -----------------------------------------------------------------------------
72
+ -- `claim_token` is never queried on its own — every read of it is one more
73
+ -- predicate bolted onto a single-row lookup already keyed by `jobs`'s primary
74
+ -- key (`WHERE id = $1 AND claim_token = $2 AND ...`), the same shape
75
+ -- `heldLeaseWhere` already has for `claimedByNodeId` and `leaseExpiresAt`,
76
+ -- neither of which is indexed on its own either. An index earns its keep by
77
+ -- narrowing a scan that would otherwise be large; there is no query here that
78
+ -- scans `jobs` by `claim_token` and needs narrowing. Adding one would be pure
79
+ -- write overhead on the hottest path this table has — every claim, every
80
+ -- renewal, every settle — for a lookup nothing performs.
81
+ --
82
+ -- -----------------------------------------------------------------------------
83
+ -- Online-safety
84
+ -- -----------------------------------------------------------------------------
85
+ -- `ADD COLUMN` of a NULLABLE column with NO DEFAULT is a metadata-only change
86
+ -- on PostgreSQL 11+: no table rewrite, no full-table scan to populate a
87
+ -- default, just a brief ACCESS EXCLUSIVE lock to update the catalog. Safe to
88
+ -- run against a live, populated `jobs` table with no maintenance window.
89
+ -- =============================================================================
90
+
91
+ -- AlterTable
92
+ ALTER TABLE "jobs" ADD COLUMN "claim_token" UUID;
@@ -0,0 +1,108 @@
1
+ -- CreateTable
2
+ CREATE TABLE "ai_models" (
3
+ "id" UUID NOT NULL,
4
+ "provider" TEXT NOT NULL,
5
+ "model_id" TEXT NOT NULL,
6
+ "display_name" TEXT,
7
+ "capabilities" JSONB NOT NULL,
8
+ "capability_source" TEXT NOT NULL DEFAULT 'unclassified',
9
+ "enabled" BOOLEAN NOT NULL DEFAULT false,
10
+ "context_window" INTEGER,
11
+ "max_output_tokens" INTEGER,
12
+ "discovered_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
13
+ "last_seen_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
14
+ "deprecated_at" TIMESTAMPTZ,
15
+ "updated_by_user_id" UUID,
16
+ "updated_at" TIMESTAMPTZ NOT NULL,
17
+
18
+ CONSTRAINT "ai_models_pkey" PRIMARY KEY ("id")
19
+ );
20
+
21
+ -- CreateTable
22
+ CREATE TABLE "user_ai_keys" (
23
+ "id" UUID NOT NULL,
24
+ "user_id" UUID NOT NULL,
25
+ "provider" TEXT NOT NULL,
26
+ "secret" TEXT NOT NULL,
27
+ "hint" TEXT,
28
+ "verified_at" TIMESTAMPTZ,
29
+ "last_error_code" TEXT,
30
+ "reachable_model_ids" TEXT[] DEFAULT ARRAY[]::TEXT[],
31
+ "reachable_checked_at" TIMESTAMPTZ,
32
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
33
+ "updated_at" TIMESTAMPTZ NOT NULL,
34
+
35
+ CONSTRAINT "user_ai_keys_pkey" PRIMARY KEY ("id")
36
+ );
37
+
38
+ -- CreateTable
39
+ CREATE TABLE "ai_runs" (
40
+ "id" UUID NOT NULL,
41
+ "user_id" UUID,
42
+ "job_id" UUID,
43
+ "status" TEXT NOT NULL DEFAULT 'pending',
44
+ "provider" TEXT NOT NULL,
45
+ "model_id" TEXT NOT NULL,
46
+ "request" JSONB NOT NULL,
47
+ "output" JSONB,
48
+ "error_code" TEXT,
49
+ "error_message" TEXT,
50
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
51
+ "updated_at" TIMESTAMPTZ NOT NULL,
52
+ "completed_at" TIMESTAMPTZ,
53
+
54
+ CONSTRAINT "ai_runs_pkey" PRIMARY KEY ("id")
55
+ );
56
+
57
+ -- CreateTable
58
+ CREATE TABLE "ai_usage_events" (
59
+ "id" UUID NOT NULL,
60
+ "user_id" UUID,
61
+ "provider" TEXT NOT NULL,
62
+ "model_id" TEXT NOT NULL,
63
+ "operation" TEXT NOT NULL,
64
+ "key_source" TEXT NOT NULL,
65
+ "input_tokens" INTEGER,
66
+ "output_tokens" INTEGER,
67
+ "reasoning_tokens" INTEGER,
68
+ "cached_input_tokens" INTEGER,
69
+ "units" JSONB,
70
+ "latency_ms" INTEGER NOT NULL,
71
+ "status" TEXT NOT NULL,
72
+ "error_code" TEXT,
73
+ "provider_request_id" TEXT,
74
+ "job_id" UUID,
75
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
76
+
77
+ CONSTRAINT "ai_usage_events_pkey" PRIMARY KEY ("id")
78
+ );
79
+
80
+ -- CreateIndex
81
+ CREATE INDEX "ai_models_provider_enabled_idx" ON "ai_models"("provider", "enabled");
82
+
83
+ -- CreateIndex
84
+ CREATE UNIQUE INDEX "ai_models_provider_model_id_key" ON "ai_models"("provider", "model_id");
85
+
86
+ -- CreateIndex
87
+ CREATE UNIQUE INDEX "user_ai_keys_user_id_provider_key" ON "user_ai_keys"("user_id", "provider");
88
+
89
+ -- CreateIndex
90
+ CREATE INDEX "ai_runs_user_id_created_at_idx" ON "ai_runs"("user_id", "created_at");
91
+
92
+ -- CreateIndex
93
+ CREATE INDEX "ai_usage_events_user_id_created_at_idx" ON "ai_usage_events"("user_id", "created_at");
94
+
95
+ -- CreateIndex
96
+ CREATE INDEX "ai_usage_events_created_at_idx" ON "ai_usage_events"("created_at");
97
+
98
+ -- AddForeignKey
99
+ ALTER TABLE "ai_models" ADD CONSTRAINT "ai_models_updated_by_user_id_fkey" FOREIGN KEY ("updated_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
100
+
101
+ -- AddForeignKey
102
+ ALTER TABLE "user_ai_keys" ADD CONSTRAINT "user_ai_keys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
103
+
104
+ -- AddForeignKey
105
+ ALTER TABLE "ai_runs" ADD CONSTRAINT "ai_runs_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
106
+
107
+ -- AddForeignKey
108
+ ALTER TABLE "ai_usage_events" ADD CONSTRAINT "ai_usage_events_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,32 @@
1
+ -- =============================================================================
2
+ -- Revoke `ai:use` from the Viewer role on existing deployments (issue #499)
3
+ -- =============================================================================
4
+ -- Viewer is the DEFAULT role every new user lands in (see `ROLES` in
5
+ -- `prisma/seed-data.ts` and the allowlist-driven signup path). Seeding
6
+ -- `ai:use` onto it (issue #423, epic #419) meant every fresh signup could
7
+ -- call AI with no explicit grant — harmless under the `byok` key policy (no
8
+ -- key, no calls succeed), but wrong under `byok_with_org_fallback`: a
9
+ -- brand-new Viewer would silently spend the deployment's own org key the
10
+ -- first time they touched an AI surface, with no administrator having
11
+ -- decided that person should be able to.
12
+ --
13
+ -- This migration is DATA-ONLY (no `schema.prisma` change — the shape of
14
+ -- `role_permissions` is unchanged) and undoes exactly that one grant on
15
+ -- deployments that already ran the old seed: it deletes the single
16
+ -- `role_permissions` row joining the role named 'viewer' and the permission
17
+ -- named 'ai:use', and touches nothing else — not Admin's or Contributor's
18
+ -- grants, not any other Viewer permission.
19
+ --
20
+ -- IDEMPOTENT: a `DELETE ... WHERE` naming both rows by subquery is a no-op if
21
+ -- the row is already gone, or if either the 'viewer' role or the 'ai:use'
22
+ -- permission does not exist at all (a fork that renamed or removed either).
23
+ -- Safe to run against a database that never had the row (a fresh install
24
+ -- seeded from the already-updated `seed-data.ts`) and safe to re-run.
25
+ --
26
+ -- An administrator who wants a specific Viewer (or all of them) to use AI
27
+ -- again grants it back explicitly — re-insert a `role_permissions` row for
28
+ -- `('viewer', 'ai:use')` — or promotes the account to Contributor, which
29
+ -- still carries the grant.
30
+ DELETE FROM "role_permissions"
31
+ WHERE "role_id" = (SELECT "id" FROM "roles" WHERE "name" = 'viewer')
32
+ AND "permission_id" = (SELECT "id" FROM "permissions" WHERE "name" = 'ai:use');
@@ -0,0 +1,29 @@
1
+ -- =============================================================================
2
+ -- Per-user encrypted credentials (issue #387)
3
+ -- =============================================================================
4
+ -- A sibling of "credentials", which is NOT modified. Rows are addressed by
5
+ -- (user_id, purpose, name); `secret` is ciphertext encrypted under the
6
+ -- owner-bound sub-key domain `user:<user_id>:<purpose>`. All three unique
7
+ -- columns are NOT NULL so the unique index is a real constraint. Rows cascade
8
+ -- with their owner.
9
+
10
+ -- CreateTable
11
+ CREATE TABLE "user_credentials" (
12
+ "id" UUID NOT NULL,
13
+ "user_id" UUID NOT NULL,
14
+ "purpose" TEXT NOT NULL,
15
+ "name" TEXT NOT NULL,
16
+ "secret" TEXT NOT NULL,
17
+ "hint" TEXT,
18
+ "label" TEXT,
19
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
20
+ "updated_at" TIMESTAMPTZ NOT NULL,
21
+
22
+ CONSTRAINT "user_credentials_pkey" PRIMARY KEY ("id")
23
+ );
24
+
25
+ -- CreateIndex
26
+ CREATE UNIQUE INDEX "user_credentials_user_id_purpose_name_key" ON "user_credentials"("user_id", "purpose", "name");
27
+
28
+ -- AddForeignKey
29
+ ALTER TABLE "user_credentials" ADD CONSTRAINT "user_credentials_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,52 @@
1
+ -- =============================================================================
2
+ -- Device session <-> issued credential link (issue #518)
3
+ -- =============================================================================
4
+ -- Today nothing links a `DeviceCode` row to what it issued: once the polling
5
+ -- client collects a PAT (and that PAT is used to mint refresh tokens),
6
+ -- revoking the `DeviceCode` "session" does nothing to the credential the
7
+ -- device is actually holding. This migration adds the columns that let a
8
+ -- device-session revocation reach both:
9
+ --
10
+ -- 1. `device_codes.pat_id`: the PAT minted for this device once collected.
11
+ -- Nullable until collection. `SetNull` on delete — a `DeviceCode` history
12
+ -- row must survive its PAT being deleted (or aging out) independently.
13
+ -- 2. `device_codes.collected_at` / `credential_expires_at`: collection state
14
+ -- copied from the PAT at collection time, so the sessions list can filter
15
+ -- "approved, not yet collected" vs. "collected, still valid" without a
16
+ -- join against `personal_access_tokens`.
17
+ -- 3. `device_codes.revoked_at`: marks the device session (and whatever it
18
+ -- issued) as revoked. Distinct from `PersonalAccessToken.revokedAt` /
19
+ -- `RefreshToken.revokedAt`, which the revocation service also sets on the
20
+ -- linked rows — this column is what the sessions list itself filters on.
21
+ -- 4. `refresh_tokens.device_code_id`: the device-authorization session that
22
+ -- minted this refresh token, if any, so that same revocation can reach
23
+ -- refresh tokens too. `SetNull` on delete for the same reason as above.
24
+ --
25
+ -- Additive only: every new column is nullable, no backfill, no data migration.
26
+ -- =============================================================================
27
+
28
+ -- AlterTable
29
+ ALTER TABLE "device_codes"
30
+ ADD COLUMN "pat_id" UUID,
31
+ ADD COLUMN "collected_at" TIMESTAMPTZ,
32
+ ADD COLUMN "credential_expires_at" TIMESTAMPTZ,
33
+ ADD COLUMN "revoked_at" TIMESTAMPTZ;
34
+
35
+ -- AlterTable
36
+ ALTER TABLE "refresh_tokens" ADD COLUMN "device_code_id" UUID;
37
+
38
+ -- CreateIndex
39
+ -- Serves the sessions list: "this user's device sessions that are not
40
+ -- revoked" (approved-uncollected and collected-unexpired both satisfy
41
+ -- `revoked_at IS NULL`); the remaining collected/expiry filtering is done in
42
+ -- the query predicate, not a second index.
43
+ CREATE INDEX "device_codes_user_id_revoked_at_idx" ON "device_codes"("user_id", "revoked_at");
44
+
45
+ -- CreateIndex
46
+ CREATE INDEX "refresh_tokens_device_code_id_idx" ON "refresh_tokens"("device_code_id");
47
+
48
+ -- AddForeignKey
49
+ ALTER TABLE "device_codes" ADD CONSTRAINT "device_codes_pat_id_fkey" FOREIGN KEY ("pat_id") REFERENCES "personal_access_tokens"("id") ON DELETE SET NULL ON UPDATE CASCADE;
50
+
51
+ -- AddForeignKey
52
+ ALTER TABLE "refresh_tokens" ADD CONSTRAINT "refresh_tokens_device_code_id_fkey" FOREIGN KEY ("device_code_id") REFERENCES "device_codes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
1
+ -- AlterTable
2
+ ALTER TABLE "worker_nodes" ADD COLUMN "last_vitals" JSONB,
3
+ ADD COLUMN "last_vitals_at" TIMESTAMPTZ;
@@ -0,0 +1,6 @@
1
+ -- Issue #607: carry the enqueuing request's W3C trace context on the job row.
2
+ -- Nullable, no default, no index: existing rows simply have no trace context.
3
+ -- The partial unique index jobs_active_dedup_uniq_idx is deliberately untouched.
4
+
5
+ -- AlterTable
6
+ ALTER TABLE "jobs" ADD COLUMN "trace_context" TEXT;
@@ -0,0 +1,13 @@
1
+ -- Retention sweeps (#681): each purge reads "the oldest rows older than the
2
+ -- cutoff", across every user. Plain btree indexes on the timestamp, so a batch
3
+ -- is an index range scan rather than a sequential scan. `audit_events` already
4
+ -- has `audit_events_created_at_idx`.
5
+
6
+ -- CreateIndex
7
+ CREATE INDEX "notification_deliveries_created_at_idx" ON "notification_deliveries"("created_at");
8
+
9
+ -- CreateIndex
10
+ CREATE INDEX "notifications_created_at_idx" ON "notifications"("created_at");
11
+
12
+ -- CreateIndex
13
+ CREATE INDEX "ai_runs_created_at_idx" ON "ai_runs"("created_at");
@@ -0,0 +1,142 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "MembershipStatus" AS ENUM ('active', 'suspended');
3
+
4
+ -- CreateEnum
5
+ CREATE TYPE "InviteStatus" AS ENUM ('pending', 'accepted', 'revoked', 'expired');
6
+
7
+ -- AlterTable
8
+ ALTER TABLE "device_codes" ADD COLUMN "org_id" UUID;
9
+
10
+ -- AlterTable
11
+ ALTER TABLE "personal_access_tokens" ADD COLUMN "org_id" UUID;
12
+
13
+ -- AlterTable
14
+ ALTER TABLE "refresh_tokens" ADD COLUMN "org_id" UUID;
15
+
16
+ -- CreateTable
17
+ CREATE TABLE "organizations" (
18
+ "id" UUID NOT NULL,
19
+ "name" TEXT NOT NULL,
20
+ "slug" TEXT NOT NULL,
21
+ "is_default" BOOLEAN NOT NULL DEFAULT false,
22
+ "created_by_id" UUID,
23
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
24
+ "updated_at" TIMESTAMPTZ NOT NULL,
25
+
26
+ CONSTRAINT "organizations_pkey" PRIMARY KEY ("id")
27
+ );
28
+
29
+ -- CreateTable
30
+ CREATE TABLE "memberships" (
31
+ "id" UUID NOT NULL,
32
+ "org_id" UUID NOT NULL,
33
+ "user_id" UUID NOT NULL,
34
+ "status" "MembershipStatus" NOT NULL DEFAULT 'active',
35
+ "last_active_at" TIMESTAMPTZ,
36
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
37
+ "updated_at" TIMESTAMPTZ NOT NULL,
38
+
39
+ CONSTRAINT "memberships_pkey" PRIMARY KEY ("id")
40
+ );
41
+
42
+ -- CreateTable
43
+ CREATE TABLE "org_invites" (
44
+ "id" UUID NOT NULL,
45
+ "org_id" UUID NOT NULL,
46
+ "email" TEXT NOT NULL,
47
+ "status" "InviteStatus" NOT NULL DEFAULT 'pending',
48
+ "token_hash" TEXT,
49
+ "expires_at" TIMESTAMPTZ,
50
+ "invited_by_id" UUID,
51
+ "accepted_by_id" UUID,
52
+ "accepted_at" TIMESTAMPTZ,
53
+ "notes" TEXT,
54
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
55
+
56
+ CONSTRAINT "org_invites_pkey" PRIMARY KEY ("id")
57
+ );
58
+
59
+ -- CreateIndex
60
+ CREATE UNIQUE INDEX "organizations_slug_key" ON "organizations"("slug");
61
+
62
+ -- CreateIndex
63
+ CREATE INDEX "memberships_user_id_idx" ON "memberships"("user_id");
64
+
65
+ -- CreateIndex
66
+ CREATE UNIQUE INDEX "memberships_org_id_user_id_key" ON "memberships"("org_id", "user_id");
67
+
68
+ -- CreateIndex
69
+ CREATE UNIQUE INDEX "org_invites_token_hash_key" ON "org_invites"("token_hash");
70
+
71
+ -- CreateIndex
72
+ CREATE INDEX "org_invites_email_idx" ON "org_invites"("email");
73
+
74
+ -- CreateIndex
75
+ CREATE UNIQUE INDEX "org_invites_org_id_email_key" ON "org_invites"("org_id", "email");
76
+
77
+ -- CreateIndex
78
+ CREATE INDEX "device_codes_org_id_idx" ON "device_codes"("org_id");
79
+
80
+ -- CreateIndex
81
+ CREATE INDEX "personal_access_tokens_org_id_idx" ON "personal_access_tokens"("org_id");
82
+
83
+ -- CreateIndex
84
+ CREATE INDEX "refresh_tokens_org_id_idx" ON "refresh_tokens"("org_id");
85
+
86
+ -- AddForeignKey
87
+ ALTER TABLE "refresh_tokens" ADD CONSTRAINT "refresh_tokens_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
88
+
89
+ -- AddForeignKey
90
+ ALTER TABLE "personal_access_tokens" ADD CONSTRAINT "personal_access_tokens_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
91
+
92
+ -- AddForeignKey
93
+ ALTER TABLE "device_codes" ADD CONSTRAINT "device_codes_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
94
+
95
+ -- AddForeignKey
96
+ ALTER TABLE "organizations" ADD CONSTRAINT "organizations_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
97
+
98
+ -- AddForeignKey
99
+ ALTER TABLE "memberships" ADD CONSTRAINT "memberships_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
100
+
101
+ -- AddForeignKey
102
+ ALTER TABLE "memberships" ADD CONSTRAINT "memberships_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
103
+
104
+ -- AddForeignKey
105
+ ALTER TABLE "org_invites" ADD CONSTRAINT "org_invites_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
106
+
107
+ -- AddForeignKey
108
+ ALTER TABLE "org_invites" ADD CONSTRAINT "org_invites_invited_by_id_fkey" FOREIGN KEY ("invited_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
109
+
110
+ -- AddForeignKey
111
+ ALTER TABLE "org_invites" ADD CONSTRAINT "org_invites_accepted_by_id_fkey" FOREIGN KEY ("accepted_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
112
+
113
+ -- =============================================================================
114
+ -- Raw SQL (hand-written; Prisma cannot express a partial unique index)
115
+ -- =============================================================================
116
+
117
+ -- Exactly one default organization: a constant-expression partial unique index.
118
+ -- Intentional schema drift: never replace it with @@unique or a findFirst check.
119
+ CREATE UNIQUE INDEX "organizations_default_uniq_idx" ON "organizations" ((true)) WHERE "is_default";
120
+
121
+ -- =============================================================================
122
+ -- Backfill (forward-only). Every INSERT names its id: the server-side uuid
123
+ -- defaults were dropped (0005_drop_stale_uuid_defaults).
124
+ -- =============================================================================
125
+
126
+ -- 1. The default organization.
127
+ INSERT INTO "organizations" ("id", "name", "slug", "is_default", "created_at", "updated_at")
128
+ VALUES (gen_random_uuid(), 'Default organization', 'default', true, now(), now())
129
+ ON CONFLICT DO NOTHING;
130
+
131
+ -- 2. One active membership per existing user.
132
+ INSERT INTO "memberships" ("id", "org_id", "user_id", "status", "last_active_at", "created_at", "updated_at")
133
+ SELECT gen_random_uuid(), o."id", u."id", 'active', now(), now(), now()
134
+ FROM "users" u
135
+ CROSS JOIN "organizations" o
136
+ WHERE o."is_default"
137
+ ON CONFLICT ("org_id", "user_id") DO NOTHING;
138
+
139
+ -- 3. Every existing credential row acts in the default organization.
140
+ UPDATE "refresh_tokens" SET "org_id" = (SELECT "id" FROM "organizations" WHERE "is_default") WHERE "org_id" IS NULL;
141
+ UPDATE "personal_access_tokens" SET "org_id" = (SELECT "id" FROM "organizations" WHERE "is_default") WHERE "org_id" IS NULL;
142
+ UPDATE "device_codes" SET "org_id" = (SELECT "id" FROM "organizations" WHERE "is_default") WHERE "org_id" IS NULL;
@@ -0,0 +1,131 @@
1
+ -- =============================================================================
2
+ -- Split RBAC into system roles and org roles (PP-6.3, issue #723)
3
+ -- =============================================================================
4
+ --
5
+ -- System roles operate the deployment and stay in "user_roles" (admin). Org
6
+ -- roles operate one organization and move onto the membership
7
+ -- ("memberships"."role_id"): org_admin, contributor, viewer. Every role and
8
+ -- permission gains a "scope". Effective permissions become the system roles'
9
+ -- grants plus the grants of the current organization's membership role, so the
10
+ -- data below is moved so that every user keeps exactly what they had.
11
+ --
12
+ -- Forward-only and in one transaction: the expand (columns) and the data move
13
+ -- happen together, so no request between "migrate deploy" and the seed run
14
+ -- sees an administrator without a permission. Nothing is dropped: "user_roles"
15
+ -- keeps its shape (expand/contract); only rows pointing at org roles go.
16
+ -- Every INSERT names its id (0005_drop_stale_uuid_defaults).
17
+ -- =============================================================================
18
+
19
+ -- CreateEnum
20
+ CREATE TYPE "RoleScope" AS ENUM ('system', 'org');
21
+
22
+ -- AlterTable: nullable first, backfilled below, then NOT NULL.
23
+ ALTER TABLE "memberships" ADD COLUMN "role_id" UUID;
24
+
25
+ -- AlterTable: NULL means the default org role (viewer).
26
+ ALTER TABLE "org_invites" ADD COLUMN "role_id" UUID;
27
+
28
+ -- AlterTable
29
+ ALTER TABLE "permissions" ADD COLUMN "scope" "RoleScope" NOT NULL DEFAULT 'system';
30
+
31
+ -- AlterTable
32
+ ALTER TABLE "roles" ADD COLUMN "scope" "RoleScope" NOT NULL DEFAULT 'system';
33
+
34
+ -- -----------------------------------------------------------------------------
35
+ -- 1. The org roles exist. org_admin is new; viewer is the fallback role of
36
+ -- step 4 and may be missing on a database the seed has not reached yet.
37
+ -- The seed refreshes both descriptions.
38
+ -- -----------------------------------------------------------------------------
39
+ INSERT INTO "roles" ("id", "name", "description", "scope")
40
+ VALUES (gen_random_uuid(), 'org_admin', 'Organization administrator - everything a contributor can do, plus manage the organization members and invites', 'org')
41
+ ON CONFLICT ("name") DO NOTHING;
42
+
43
+ INSERT INTO "roles" ("id", "name", "description", "scope")
44
+ VALUES (gen_random_uuid(), 'viewer', 'Read-only organization member - view content and manage own settings', 'org')
45
+ ON CONFLICT ("name") DO NOTHING;
46
+
47
+ -- -----------------------------------------------------------------------------
48
+ -- 2. Scopes. admin stays 'system' (the column default), like every
49
+ -- operational permission. An app's own roles and permissions keep the
50
+ -- default until the seed writes the scope their declarations name.
51
+ -- -----------------------------------------------------------------------------
52
+ UPDATE "roles" SET "scope" = 'org' WHERE "name" IN ('org_admin', 'contributor', 'viewer');
53
+
54
+ UPDATE "permissions" SET "scope" = 'org'
55
+ WHERE "name" IN (
56
+ 'user_settings:read', 'user_settings:write', 'storage:read', 'storage:write', 'ai:use',
57
+ 'org_members:read', 'org_members:write', 'org_invites:read', 'org_invites:write'
58
+ );
59
+
60
+ -- -----------------------------------------------------------------------------
61
+ -- 3. admin's grants of org permissions move to org_admin: copy first, then
62
+ -- delete. Every admin gets org_admin on their membership in step 4, in this
63
+ -- same transaction, so no administrator loses a permission. Grants an
64
+ -- administrator made to contributor or viewer are left as they are.
65
+ -- -----------------------------------------------------------------------------
66
+ INSERT INTO "role_permissions" ("role_id", "permission_id")
67
+ SELECT oa."id", rp."permission_id"
68
+ FROM "role_permissions" rp
69
+ JOIN "roles" a ON a."id" = rp."role_id" AND a."name" = 'admin'
70
+ JOIN "permissions" p ON p."id" = rp."permission_id" AND p."scope" = 'org'
71
+ CROSS JOIN "roles" oa
72
+ WHERE oa."name" = 'org_admin'
73
+ ON CONFLICT DO NOTHING;
74
+
75
+ DELETE FROM "role_permissions" rp
76
+ USING "roles" a, "permissions" p
77
+ WHERE rp."role_id" = a."id" AND a."name" = 'admin'
78
+ AND rp."permission_id" = p."id" AND p."scope" = 'org';
79
+
80
+ -- -----------------------------------------------------------------------------
81
+ -- 4. Every user is a member of the default organization (0023 did this for
82
+ -- the users that existed then; this catches any created since through a
83
+ -- path that skipped it), and every membership gets its role from the
84
+ -- user's global roles: admin -> org_admin; otherwise the highest of
85
+ -- contributor > viewer; none -> viewer (the default org role).
86
+ -- -----------------------------------------------------------------------------
87
+ INSERT INTO "memberships" ("id", "org_id", "user_id", "status", "last_active_at", "created_at", "updated_at")
88
+ SELECT gen_random_uuid(), o."id", u."id", 'active', now(), now(), now()
89
+ FROM "users" u
90
+ CROSS JOIN "organizations" o
91
+ WHERE o."is_default"
92
+ ON CONFLICT ("org_id", "user_id") DO NOTHING;
93
+
94
+ UPDATE "memberships" m
95
+ SET "role_id" = (
96
+ SELECT r."id" FROM "roles" r
97
+ WHERE r."name" = CASE
98
+ WHEN EXISTS (
99
+ SELECT 1 FROM "user_roles" ur JOIN "roles" x ON x."id" = ur."role_id"
100
+ WHERE ur."user_id" = m."user_id" AND x."name" = 'admin'
101
+ ) THEN 'org_admin'
102
+ WHEN EXISTS (
103
+ SELECT 1 FROM "user_roles" ur JOIN "roles" x ON x."id" = ur."role_id"
104
+ WHERE ur."user_id" = m."user_id" AND x."name" = 'contributor'
105
+ ) THEN 'contributor'
106
+ ELSE 'viewer'
107
+ END
108
+ )
109
+ WHERE m."role_id" IS NULL;
110
+
111
+ ALTER TABLE "memberships" ALTER COLUMN "role_id" SET NOT NULL;
112
+
113
+ -- -----------------------------------------------------------------------------
114
+ -- 5. Contract, in data only: the global assignments of org roles are now
115
+ -- carried by the memberships. admin rows (system) stay.
116
+ -- -----------------------------------------------------------------------------
117
+ DELETE FROM "user_roles" ur
118
+ USING "roles" r
119
+ WHERE ur."role_id" = r."id" AND r."scope" = 'org';
120
+
121
+ -- CreateIndex
122
+ CREATE INDEX "memberships_role_id_idx" ON "memberships"("role_id");
123
+
124
+ -- CreateIndex
125
+ CREATE INDEX "org_invites_role_id_idx" ON "org_invites"("role_id");
126
+
127
+ -- AddForeignKey
128
+ ALTER TABLE "memberships" ADD CONSTRAINT "memberships_role_id_fkey" FOREIGN KEY ("role_id") REFERENCES "roles"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
129
+
130
+ -- AddForeignKey
131
+ ALTER TABLE "org_invites" ADD CONSTRAINT "org_invites_role_id_fkey" FOREIGN KEY ("role_id") REFERENCES "roles"("id") ON DELETE RESTRICT ON UPDATE CASCADE;