@sssb/kit 0.0.0 → 0.2.0

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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
package/src/db/jobs.ts ADDED
@@ -0,0 +1,300 @@
1
+ import { sql, type Kysely, type Transaction } from 'kysely'
2
+ import { exportKeyPrefix, type JobStatus, jobStatusMachine } from '../core/jobs'
3
+ import { InvalidTransitionError } from '../core/state-machine'
4
+ import type { DbPort } from '../ports/db'
5
+ import { NotFoundError } from '../ports/errors'
6
+ import type { JobsPort } from '../ports/jobs'
7
+ import type { DB } from './schema'
8
+ import { enqueueWebhookEvent } from './webhooks'
9
+
10
+ export interface JobTimelineEntry {
11
+ status: JobStatus
12
+ message: string | null
13
+ at: string
14
+ }
15
+
16
+ export interface JobView {
17
+ id: string
18
+ kind: string
19
+ status: JobStatus
20
+ createdAt: string
21
+ resultKey: string | null
22
+ error: string | null
23
+ timeline: JobTimelineEntry[]
24
+ }
25
+
26
+ /** timestamptz comes back from both pglite and real Postgres as a Date; views expose ISO strings. */
27
+ export function toIso(value: unknown): string {
28
+ return value instanceof Date ? value.toISOString() : String(value)
29
+ }
30
+
31
+ /**
32
+ * Submits a job: one tenant-scoped transaction persists the `jobs` row and its opening 'queued'
33
+ * timeline entry together, THEN — only once that has committed — hands off to the execution seam
34
+ * so the handler (fake: in-process; real: CodeBuild) can never observe a job that isn't durable yet.
35
+ */
36
+ export async function submitJob(
37
+ db: DbPort,
38
+ jobs: JobsPort,
39
+ input: { tenantId: string; orgId: string | null; kind: string; payload: unknown },
40
+ ): Promise<{ id: string }> {
41
+ const { id } = await db.withTenant(input.tenantId, async (trx) => {
42
+ const job = await trx
43
+ .insertInto('jobs')
44
+ .values({ tenant_id: input.tenantId, org_id: input.orgId, kind: input.kind, payload: input.payload })
45
+ .returning('id')
46
+ .executeTakeFirstOrThrow()
47
+ await trx
48
+ .insertInto('job_status_changes')
49
+ .values({ tenant_id: input.tenantId, job_id: job.id, status: 'queued', message: null })
50
+ .execute()
51
+ return job
52
+ })
53
+ await jobs.start({ id, kind: input.kind, tenantId: input.tenantId, orgId: input.orgId, payload: input.payload })
54
+ return { id }
55
+ }
56
+
57
+ /**
58
+ * THE choke point for every status change. One tenant-scoped transaction locks the job row
59
+ * (FOR UPDATE — concurrent transitions for the same job serialize instead of double-writing under
60
+ * pooled Postgres, e.g. a webhook redelivery), asserts the hop is legal (a bad transition throws
61
+ * InvalidTransitionError and rolls back), updates the job row, and appends an immutable timeline
62
+ * entry. Callers racing to *start* a job should treat InvalidTransitionError as "someone else
63
+ * already did" — see the fake executor.
64
+ */
65
+ export async function recordJobStatus(
66
+ db: DbPort,
67
+ tenantId: string,
68
+ jobId: string,
69
+ next: JobStatus,
70
+ extra?: { message?: string; resultKey?: string | undefined; error?: string | undefined },
71
+ ): Promise<void> {
72
+ const job = await db.withTenant(tenantId, async (trx) => {
73
+ const current = await trx
74
+ .selectFrom('jobs')
75
+ .select(['status', 'org_id', 'kind'])
76
+ .where('id', '=', jobId)
77
+ .forUpdate()
78
+ .executeTakeFirstOrThrow()
79
+ jobStatusMachine.assertTransition(current.status as JobStatus, next)
80
+ await trx
81
+ .updateTable('jobs')
82
+ .set({
83
+ status: next,
84
+ updated_at: sql`now()`,
85
+ ...(extra?.resultKey !== undefined ? { result_key: extra.resultKey } : {}),
86
+ ...(extra?.error !== undefined ? { error: extra.error } : {}),
87
+ })
88
+ .where('id', '=', jobId)
89
+ .execute()
90
+ await trx
91
+ .insertInto('job_status_changes')
92
+ .values({ tenant_id: tenantId, job_id: jobId, status: next, message: extra?.message ?? null })
93
+ .execute()
94
+ return { orgId: current.org_id, kind: current.kind }
95
+ })
96
+
97
+ // Outbound webhooks: a job status change is an emitted event. Enqueue only — cheap; the
98
+ // drain delivers async. Deliberately AFTER the status transaction commits (the audit precedent),
99
+ // and skipped when the job has no org (RLS-proof / legacy rows can't have subscribed endpoints).
100
+ if (job.orgId) {
101
+ await enqueueWebhookEvent(db, {
102
+ tenantId,
103
+ orgId: job.orgId,
104
+ kind: 'job.status_changed',
105
+ payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
106
+ })
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Lists a team's jobs newest-first, each with its full timeline embedded (two queries, one
112
+ * transaction). Org-filtered — the team collaboration boundary, an app-level WHERE on top of the
113
+ * tenant RLS scope (the same shape an app’s own list route has).
114
+ */
115
+ export async function listJobs(
116
+ db: DbPort,
117
+ tenantId: string,
118
+ orgId: string,
119
+ opts?: { kind?: string; limit?: number },
120
+ ): Promise<JobView[]> {
121
+ const limit = opts?.limit ?? 20
122
+ return db.withTenant(tenantId, async (trx) => {
123
+ const rows = await trx
124
+ .selectFrom('jobs')
125
+ .select(['id', 'kind', 'status', 'result_key', 'error', 'created_at'])
126
+ .where('org_id', '=', orgId)
127
+ .$if(opts?.kind !== undefined, (qb) => qb.where('kind', '=', opts!.kind!))
128
+ .orderBy('created_at', 'desc')
129
+ .limit(limit)
130
+ .execute()
131
+ if (rows.length === 0) return []
132
+ const timelines = await loadTimelines(
133
+ trx,
134
+ rows.map((r) => r.id),
135
+ )
136
+ return rows.map((r) => ({
137
+ id: r.id,
138
+ kind: r.kind,
139
+ status: r.status as JobStatus,
140
+ createdAt: toIso(r.created_at),
141
+ resultKey: r.result_key,
142
+ error: r.error,
143
+ timeline: timelines.get(r.id) ?? [],
144
+ }))
145
+ })
146
+ }
147
+
148
+ /** A job as an external service caller sees it: no timeline (polling stays light), payload included. */
149
+ export interface ServiceJobView {
150
+ id: string
151
+ kind: string
152
+ status: JobStatus
153
+ payload: unknown
154
+ createdAt: string
155
+ resultKey: string | null
156
+ error: string | null
157
+ }
158
+
159
+ /**
160
+ * The service-caller poll view: an org's jobs newest-first, optionally filtered by status, WITHOUT
161
+ * timelines (a poller wants current state, not the whole history — keep it light). Tenant-scoped by
162
+ * RLS AND org-filtered, same two boundaries as listJobs. Default limit 50.
163
+ */
164
+ export async function listServiceJobs(
165
+ db: DbPort,
166
+ tenantId: string,
167
+ orgId: string,
168
+ opts?: { status?: JobStatus; limit?: number },
169
+ ): Promise<ServiceJobView[]> {
170
+ const limit = opts?.limit ?? 50
171
+ return db.withTenant(tenantId, async (trx) => {
172
+ const rows = await trx
173
+ .selectFrom('jobs')
174
+ .select(['id', 'kind', 'status', 'payload', 'result_key', 'error', 'created_at'])
175
+ .where('org_id', '=', orgId)
176
+ .$if(opts?.status !== undefined, (qb) => qb.where('status', '=', opts!.status!))
177
+ .orderBy('created_at', 'desc')
178
+ .limit(limit)
179
+ .execute()
180
+ return rows.map((r) => ({
181
+ id: r.id,
182
+ kind: r.kind,
183
+ status: r.status as JobStatus,
184
+ payload: r.payload,
185
+ createdAt: toIso(r.created_at),
186
+ resultKey: r.result_key,
187
+ error: r.error,
188
+ }))
189
+ })
190
+ }
191
+
192
+ /**
193
+ * Resolves a job id to its status ONLY when it belongs to `orgId` within `tenantId` — returns null
194
+ * both when the job is absent and when it belongs to another org (a foreign org's job must be
195
+ * indistinguishable from a missing one, so a caller can't probe other teams' job ids).
196
+ */
197
+ export async function jobForOrg(
198
+ db: DbPort,
199
+ tenantId: string,
200
+ orgId: string,
201
+ jobId: string,
202
+ ): Promise<{ id: string; status: JobStatus } | null> {
203
+ return db.withTenant(tenantId, async (trx) => {
204
+ const row = await trx
205
+ .selectFrom('jobs')
206
+ .select(['id', 'status'])
207
+ .where('id', '=', jobId)
208
+ .where('org_id', '=', orgId)
209
+ .executeTakeFirst()
210
+ return row ? { id: row.id, status: row.status as JobStatus } : null
211
+ })
212
+ }
213
+
214
+ /**
215
+ * Idempotent inbound-webhook completion (the real CodeBuild build's final POST reports terminal
216
+ * status here). NotFoundError when the job isn't in the tenant. If the job is already in the
217
+ * requested terminal state → 'idempotent' (a webhook redelivery is expected, not an error). A job
218
+ * still 'queued' walks through 'running' (message 'completion webhook') first so the timeline always
219
+ * reads queued -> running -> terminal. Every write goes through recordJobStatus (the row-locked
220
+ * choke point).
221
+ *
222
+ * The webhook payload names the tenant, but the ORG namespace a resultKey may live in is the job
223
+ * row's to decide — a planted same-tenant foreign-org key dies here as 'invalid-result-key' (the
224
+ * service status route enforces the same prefix from its caller identity).
225
+ *
226
+ * Two deliveries can race the same still-queued job: the loser's mid-walk InvalidTransitionError is
227
+ * resolved by LOOKING AGAIN — idempotent when the world reached the requested state, one more walk
228
+ * while it's still in flight — never by bouncing the vendor with the 409 the idempotent-redelivery
229
+ * contract exists to avoid. A genuinely illegal hop (completed -> failed) still throws immediately
230
+ * via the terminal pre-check. The retry bound is generous: after one lost race the job is at least
231
+ * 'running', so the next walk is single-hop.
232
+ */
233
+ export async function recordWebhookCompletion(
234
+ db: DbPort,
235
+ input: { tenantId: string; jobId: string; status: 'completed' | 'failed'; resultKey?: string; error?: string },
236
+ ): Promise<'applied' | 'idempotent' | 'invalid-result-key'> {
237
+ const extra = { resultKey: input.resultKey, error: input.error }
238
+ for (let attempt = 0; ; attempt++) {
239
+ const row = await db.withTenant(input.tenantId, (trx) =>
240
+ trx.selectFrom('jobs').select(['status', 'org_id']).where('id', '=', input.jobId).executeTakeFirst(),
241
+ )
242
+ if (!row) throw new NotFoundError(`job not found in tenant: ${input.jobId}`)
243
+ if (input.resultKey !== undefined && !input.resultKey.startsWith(exportKeyPrefix(input.tenantId, row.org_id))) {
244
+ return 'invalid-result-key'
245
+ }
246
+ const current = row.status as JobStatus
247
+ if (current === input.status) return 'idempotent'
248
+ if (jobStatusMachine.isTerminal(current)) jobStatusMachine.assertTransition(current, input.status)
249
+ try {
250
+ if (current === 'queued') {
251
+ await recordJobStatus(db, input.tenantId, input.jobId, 'running', { message: 'completion webhook' })
252
+ }
253
+ await recordJobStatus(db, input.tenantId, input.jobId, input.status, extra)
254
+ return 'applied'
255
+ } catch (error) {
256
+ if (error instanceof InvalidTransitionError && attempt < 2) continue
257
+ throw error
258
+ }
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Resolves a job's kind + owning org by id within a tenant (RLS-scoped) — the notification fan-out
264
+ * needs both to decide whether a terminal job is user-facing and to address the org's admins.
265
+ * Null when the job isn't in the tenant. A thin read, deliberately not folded into recordJobStatus so
266
+ * the status choke point stays free of the notification/adapters layer (the webhook-enqueue precedent).
267
+ */
268
+ export async function jobKindAndOrg(
269
+ db: DbPort,
270
+ tenantId: string,
271
+ jobId: string,
272
+ ): Promise<{ kind: string; orgId: string | null } | null> {
273
+ return db.withTenant(tenantId, async (trx) => {
274
+ const row = await trx.selectFrom('jobs').select(['kind', 'org_id']).where('id', '=', jobId).executeTakeFirst()
275
+ return row ? { kind: row.kind, orgId: row.org_id } : null
276
+ })
277
+ }
278
+
279
+ /**
280
+ * Loads timeline entries for the given job ids (chronological), grouped by job. Accepts either a
281
+ * tenant-scoped transaction (product paths) or the raw handle (the simulated-mode cross-tenant world view).
282
+ */
283
+ export async function loadTimelines(
284
+ executor: Kysely<DB> | Transaction<DB>,
285
+ jobIds: string[],
286
+ ): Promise<Map<string, JobTimelineEntry[]>> {
287
+ const changes = await executor
288
+ .selectFrom('job_status_changes')
289
+ .select(['job_id', 'status', 'message', 'at'])
290
+ .where('job_id', 'in', jobIds)
291
+ .orderBy('at', 'asc')
292
+ .execute()
293
+ const grouped = new Map<string, JobTimelineEntry[]>()
294
+ for (const change of changes) {
295
+ const list = grouped.get(change.job_id) ?? []
296
+ list.push({ status: change.status as JobStatus, message: change.message, at: toIso(change.at) })
297
+ grouped.set(change.job_id, list)
298
+ }
299
+ return grouped
300
+ }
@@ -0,0 +1,18 @@
1
+ import { sql, type RawBuilder } from 'kysely'
2
+
3
+ /**
4
+ * Serialize a JS value for a `jsonb` column parameter, engine-safe on BOTH pglite and node-postgres.
5
+ *
6
+ * node-postgres serializes a JS ARRAY as a Postgres ARRAY literal (`{a,b}`), NOT as JSON — so inserting
7
+ * an array straight into a jsonb column throws `invalid input syntax for type json` on real Postgres,
8
+ * even though pglite happens to accept it. That is the same "a raw shape only *appears* to work on
9
+ * pglite" trap the build notes record for FORCE-RLS scans (docs/build-notes.md): the unit test (pglite)
10
+ * would pass while the contract test (embedded Postgres via `pg`) breaks. Passing a JSON string with an
11
+ * explicit `::jsonb` cast is unambiguous on both engines.
12
+ *
13
+ * Plain OBJECTS don't need this (node-postgres JSON.stringifies them — jobs.payload / schedules.spec
14
+ * rely on that), but ARRAYS do. Use this for any array-valued jsonb column (webhook_endpoints.event_kinds).
15
+ */
16
+ export function jsonb<T>(value: T): RawBuilder<T> {
17
+ return sql<T>`${JSON.stringify(value)}::jsonb`
18
+ }
@@ -0,0 +1,179 @@
1
+ import { sql, type SelectQueryBuilder, type SqlBool, type Transaction } from 'kysely'
2
+ import {
3
+ type KeysetCursorParse,
4
+ type KeysetPosition,
5
+ clampKeysetLimit,
6
+ encodeKeysetCursor,
7
+ parseKeysetCursor,
8
+ } from '../core/keyset'
9
+ import type { DbPort } from '../ports/db'
10
+ import type { DB } from './schema'
11
+
12
+ /**
13
+ * Keyset pagination over a tenant-scoped table — the SQL half of `@sssb/kit/core/keyset` (which carries
14
+ * the cursor grammar, the offset-vs-keyset argument, and the reason a cursor cannot widen a scope).
15
+ *
16
+ * This is a FRAMEWORK primitive rather than app code for the same reason `withTenant` is: a paginated
17
+ * read of a tenant-scoped table has a correctness property that must not be re-derived per list. Three
18
+ * things go wrong when a list hand-rolls its own paging, and all three are invisible until production:
19
+ *
20
+ * 1. **The scope is dropped on page 2.** The classic shape is a first query built from session state
21
+ * and a second built from the cursor — and the second forgets the org filter. Here the app cannot
22
+ * make that mistake, because there is only ever ONE query: `keysetPage` opens the `withTenant`
23
+ * transaction itself and the caller's `build` callback (which carries the org filter) runs on
24
+ * every page, cursor or no cursor. The cursor is an extra conjunct on that same query, never a
25
+ * query of its own.
26
+ * 2. **The ordering is not total.** `ORDER BY created_at DESC` alone is not an order: every row
27
+ * written in one transaction shares the identical `now()`, so the database is free to return them
28
+ * in any order and a cursor into the middle of the batch is meaningless. The tiebreak on the
29
+ * primary key is what makes the walk well-defined.
30
+ * 3. **The position loses precision.** `timestamptz` is microsecond-precision; the JS `Date` the
31
+ * driver hands back is millisecond-precision. Minting the cursor from that `Date` truncates it,
32
+ * and the next page's `created_at < cursor` then also excludes every row written inside the same
33
+ * millisecond — silently dropping rows, or (for a batch that shares one timestamp) returning an
34
+ * empty page 2 forever. So the pager never re-derives the position: it asks POSTGRES to render
35
+ * the ordering key it just read, at full precision, and puts that string in the cursor.
36
+ *
37
+ * The page predicate is a row-value comparison, `(created_at, id) < ($1, $2)`, which is both the
38
+ * exact meaning of "strictly after this position in `created_at DESC, id DESC`" and the form Postgres
39
+ * can satisfy from an index on `(…, created_at DESC, id DESC)` — see
40
+ * each app’s own `1004_*_keyset_index` migration for the index a paged table wants.
41
+ *
42
+ * **Ordering by another column.** `created_at` is the default ordering key, and the optional trailing
43
+ * `orderBy` argument swaps it for any other NOT NULL `timestamptz` column of the paged table — a list
44
+ * that wants "most recently touched first", say. It replaces the key in all three places the pager
45
+ * uses it (the row-value comparison, the cursor's rendered position, and the `ORDER BY`), because a
46
+ * cursor is only correct when those three agree. Everything else is untouched: `withTenant` on every
47
+ * page, the `id` tiebreak, the full-precision cursor, the one-extra-row probe, and the server-side
48
+ * clamp. Leave `orderBy` out and the SQL is exactly what it was before the argument existed.
49
+ *
50
+ * **What a cursor does not say.** `@sssb/kit/core/keyset`'s cursor grammar is `at` + `id` and nothing
51
+ * else — it names no column. A cursor minted while paging by one column is therefore
52
+ * indistinguishable from one minted while paging by another, and replaying it under the wrong
53
+ * ordering is not rejected: it is read as a position in THAT ordering and quietly skips or repeats
54
+ * rows. So the ordering must never be something the client chooses. Each list route owns ONE fixed
55
+ * ordering, picked server-side when the route is written. A route that wants to offer its caller a
56
+ * choice of orderings has to make that choice at the route level — separate routes, or separate
57
+ * server-side functions each passing its own `orderBy` — not carry it in the cursor or in a request
58
+ * parameter that reaches this function. The rest of the cursor contract is unchanged: the parser is
59
+ * total (`invalid` becomes a 400), the page size is clamped on the server, and every page is scoped
60
+ * the same.
61
+ */
62
+
63
+ /**
64
+ * The tables this pager can page: those with both an `id` and a `created_at`. Structural, not a
65
+ * hand-kept list, so an app table registered through the seam (`@sssb/app-config/db/schema`) qualifies
66
+ * automatically and a table without an ordering key is rejected by the compiler rather than by a
67
+ * runtime SQL error.
68
+ */
69
+ export type KeysetTableName = {
70
+ [K in keyof DB & string]: DB[K] extends { id: unknown; created_at: unknown } ? K : never
71
+ }[keyof DB & string]
72
+
73
+ /**
74
+ * The columns of table `TB` that `keysetPage` accepts as its `orderBy`: those declared NOT NULL.
75
+ *
76
+ * A nullable ordering column would be a silent trap. The page predicate is a row-value comparison,
77
+ * `(col, id) < (x, y)`, and once `col` is NULL that comparison is never true — so rows with a NULL
78
+ * key would drop out of the walk after the first page rather than raising anything. Excluding
79
+ * nullable columns turns that into a compile error.
80
+ *
81
+ * What the types cannot say is that the column is a `timestamptz`: the schema has no nominal
82
+ * timestamp type, so `created_at: Generated<string>` is the same TypeScript type as a text column
83
+ * such as `JobsTable.status`, and this type admits both. That half is enforced at the SQL boundary
84
+ * instead. The column goes in through `sql.ref` — a quoted identifier, never an interpolated string —
85
+ * and is then fed to `to_char(… at time zone 'UTC', …)` and compared against a `::timestamptz`
86
+ * parameter, so naming a non-timestamp column fails with a Postgres type error on the first page.
87
+ * It is loud, not a silently wrong order.
88
+ */
89
+ export type KeysetOrderColumn<TB extends KeysetTableName> = {
90
+ [K in keyof DB[TB] & string]: null extends DB[TB][K] ? never : K
91
+ }[keyof DB[TB] & string]
92
+
93
+ /** One page, plus the token for the next one (null when this page is the last). */
94
+ export interface KeysetPage<TRow> {
95
+ rows: TRow[]
96
+ nextCursor: string | null
97
+ }
98
+
99
+ /** Postgres's own id shape (`gen_random_uuid()`), which every table in this schema uses. */
100
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
101
+
102
+ /**
103
+ * `parseKeysetCursor` plus the one constraint only this layer knows about: the id half is bound to a
104
+ * `uuid`, so an id that is not one can never be a real row here and is rejected at the boundary
105
+ * rather than becoming a cast error (a 500, and a probe signal) inside the query. Routes over SQL
106
+ * tables should use THIS, not the core parser; an in-memory twin uses the core one, whose row handles
107
+ * are not uuids.
108
+ */
109
+ export function parseDbKeysetCursor(raw: string | null | undefined): KeysetCursorParse {
110
+ const parsed = parseKeysetCursor(raw)
111
+ if (parsed.kind === 'after' && !UUID_PATTERN.test(parsed.position.id)) return { kind: 'invalid' }
112
+ return parsed
113
+ }
114
+
115
+ /**
116
+ * Reads one page of `build`'s query, newest-first (by `created_at`, or by `orderBy` when given),
117
+ * inside a tenant-scoped transaction.
118
+ *
119
+ * `build` supplies the table, the columns, and the APP-LEVEL scope (the org filter, the two-sided
120
+ * one, whatever the table's boundary is). It must select `id`. Everything that makes the read a
121
+ * correct PAGE — the total order, the cursor predicate, the capped limit, and the next cursor — is
122
+ * this function's, on every page.
123
+ *
124
+ * `limit` is clamped here as well as at the route: the cap is a property of the primitive, not a
125
+ * discipline the caller has to remember.
126
+ *
127
+ * `orderBy` (optional, last) names a NOT NULL timestamptz column to order by instead of `created_at`;
128
+ * see the file header for what it changes and why it must be fixed per route, never client-chosen.
129
+ * Type inference note: pass `orderBy` with a `build` whose parameter is typed (a named function, or
130
+ * `(trx: Transaction<DB>) => …`). With an inline arrow whose `trx` is left to be inferred, TypeScript
131
+ * has to settle `TB` while checking the literal `orderBy` — before `build` has been read — and falls
132
+ * back to the whole `KeysetTableName` bound, which then rejects `build`'s return type.
133
+ *
134
+ * Two things `build` must NOT do. It must not add its own `orderBy` — the total order is what makes the
135
+ * cursor mean anything, and a caller's ordering would silently take precedence over it. And it should
136
+ * select the columns it wants rather than `selectAll()`, because the returned rows also carry the
137
+ * pager's internal `keyset_at` column; map to a view before anything reaches a client (the callers here
138
+ * all do). The ordering column and `id` are referenced UNQUALIFIED, so a `build` that joins another table
139
+ * carrying a column of the same name gets Postgres's "column reference is ambiguous".
140
+ */
141
+ export async function keysetPage<TB extends KeysetTableName, O extends { id: string }>(
142
+ db: DbPort,
143
+ request: { tenantId: string; after: KeysetPosition | null; limit: number },
144
+ build: (trx: Transaction<DB>) => SelectQueryBuilder<DB, TB, O>,
145
+ orderBy?: KeysetOrderColumn<TB>,
146
+ ): Promise<KeysetPage<O>> {
147
+ const limit = clampKeysetLimit(request.limit)
148
+ const after = request.after
149
+ // ONE reference to the ordering column, used by the comparison, the cursor rendering and the
150
+ // ORDER BY below. `sql.ref` quotes it as an identifier; the type already restricted it to a real
151
+ // column of `TB`, and nothing from a request ever reaches it.
152
+ const orderColumn = (orderBy ?? 'created_at') as KeysetOrderColumn<TB>
153
+ const orderRef = sql.ref(orderColumn)
154
+ return db.withTenant(request.tenantId, async (trx) => {
155
+ // The caller's scope, applied on EVERY page — this is the query, not a first-page-only one.
156
+ const scoped = build(trx)
157
+ // The cursor can only ADD a conjunct to it. Both halves are bound parameters, and both were
158
+ // pattern-checked before they got here (parseDbKeysetCursor).
159
+ const windowed = after
160
+ ? scoped.where(sql<SqlBool>`(${orderRef}, id) < (${after.at}::timestamptz, ${after.id}::uuid)`)
161
+ : scoped
162
+ // One extra row is the "is there a next page" probe — cheaper and race-free compared with a
163
+ // COUNT(*), which would be a second query against a moving table.
164
+ const probed = await windowed
165
+ .select(
166
+ sql<string>`to_char(${orderRef} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`.as('keyset_at'),
167
+ )
168
+ .orderBy(orderRef, 'desc')
169
+ .orderBy(sql`id`, 'desc')
170
+ .limit(limit + 1)
171
+ .execute()
172
+ const rows = probed.slice(0, limit)
173
+ const last = rows.at(-1)
174
+ return {
175
+ rows,
176
+ nextCursor: probed.length > limit && last ? encodeKeysetCursor({ at: last.keyset_at, id: last.id }) : null,
177
+ }
178
+ })
179
+ }
@@ -0,0 +1,73 @@
1
+ import { type Kysely, sql } from 'kysely'
2
+ import { type Migration, Migrator } from 'kysely/migration'
3
+ import { migrations } from './migrations/index'
4
+ import type { DB } from './schema'
5
+
6
+ /** Framework migrations are numbered 0001–0999 and the app's 1001 and up (ADR-0012). */
7
+ const sequenceOf = (name: string): 'framework' | 'app' => (name < '1000' ? 'framework' : 'app')
8
+
9
+ /**
10
+ * The pending migrations that would run out of order WITHIN their own sequence: a migration that sorts
11
+ * before one of the same sequence the database has already run. Unordered migration exists for the one
12
+ * case the two sequences create, a framework migration arriving after app migrations ran. Anything
13
+ * else out of order is still refused, such as two app branches whose 1006 ran before their 1005.
14
+ */
15
+ export function outOfSequence(executed: readonly string[], pending: readonly string[]): string[] {
16
+ return pending.filter((name) => executed.some((ran) => sequenceOf(ran) === sequenceOf(name) && ran > name))
17
+ }
18
+
19
+ export async function migrateToLatest(db: Kysely<DB>): Promise<void> {
20
+ await migrateRegistryToLatest(db, migrations)
21
+ }
22
+
23
+ /**
24
+ * {@link migrateToLatest} over an explicit registry, so a test can stand up a registry of its own (an app
25
+ * migration that builds on the newest framework one). Production code calls `migrateToLatest`.
26
+ */
27
+ export async function migrateRegistryToLatest(db: Kysely<DB>, registry: Record<string, Migration>): Promise<void> {
28
+ const migrator = new Migrator({
29
+ db,
30
+ provider: { getMigrations: async () => registry },
31
+ // Framework migrations (0001–0999) and the app's (≥1001) are TWO sequences interleaved by name
32
+ // (ADR-0012). So a framework migration that arrives in an SSSB update sorts BEFORE app migrations
33
+ // the database already ran. Kysely's default strict ordering refuses that as "corrupted
34
+ // migrations", which made every new framework migration unappliable to any database that had
35
+ // run one app migration. Unordered still runs the PENDING migrations in name order, and still
36
+ // fails if a migration the database ran has disappeared, so a rename stays loud. Order WITHIN a
37
+ // sequence is still enforced, by the check below.
38
+ allowUnorderedMigrations: true,
39
+ })
40
+ const state = await migrator.getMigrations()
41
+ const executed = state.filter((m) => m.executedAt !== undefined).map((m) => m.name)
42
+ const stray = outOfSequence(
43
+ executed,
44
+ state.filter((m) => m.executedAt === undefined).map((m) => m.name),
45
+ )
46
+ // A database that ran a migration this code no longer has (a rename) gets THAT error, as Kysely would
47
+ // raise it: getMigrations() lists only the registry, so the renamed one would otherwise look merely
48
+ // out of order here and the message would point at the wrong remedy.
49
+ if (stray.length > 0) {
50
+ const missing = await executedButUnknown(db, registry)
51
+ if (missing.length > 0) {
52
+ throw new Error(`corrupted migrations: previously executed migration ${missing.join(', ')} is missing`)
53
+ }
54
+ }
55
+ if (stray.length > 0) {
56
+ throw new Error(
57
+ `migrations out of order within their sequence: ${stray.join(', ')} would run after a later ` +
58
+ 'migration of the same sequence already ran. Renumber them after the last one applied.',
59
+ )
60
+ }
61
+ const { error } = await migrator.migrateToLatest()
62
+ if (error) throw error instanceof Error ? error : new Error(String(error))
63
+ }
64
+
65
+ /**
66
+ * The migrations the database recorded that the registry no longer has, read straight from Kysely's
67
+ * own table, since `Migrator.getMigrations()` reports only the registry's names. Only consulted when
68
+ * something already looks out of order, so a fresh database never reaches it.
69
+ */
70
+ async function executedButUnknown(db: Kysely<DB>, registry: Record<string, Migration>): Promise<string[]> {
71
+ const { rows } = await sql<{ name: string }>`SELECT name FROM kysely_migration`.execute(db)
72
+ return rows.map((row) => row.name).filter((name) => !Object.hasOwn(registry, name))
73
+ }
@@ -0,0 +1,25 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ export async function up(db: Kysely<any>): Promise<void> {
4
+ await db.schema
5
+ .createTable('tenants')
6
+ .addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
7
+ .addColumn('slug', 'text', (col) => col.notNull().unique())
8
+ .addColumn('name', 'text', (col) => col.notNull())
9
+ .execute()
10
+
11
+ // The non-superuser role every tenant-scoped transaction switches to (ADR-0004). Guarded:
12
+ // roles are cluster-wide on real Postgres and may already exist.
13
+ await sql`
14
+ DO $$ BEGIN
15
+ CREATE ROLE app_user NOLOGIN;
16
+ EXCEPTION WHEN duplicate_object THEN NULL;
17
+ END $$
18
+ `.execute(db)
19
+ await sql`GRANT USAGE ON SCHEMA public TO app_user`.execute(db)
20
+ await sql`GRANT SELECT ON tenants TO app_user`.execute(db)
21
+ }
22
+
23
+ export async function down(db: Kysely<any>): Promise<void> {
24
+ await db.schema.dropTable('tenants').execute()
25
+ }
@@ -0,0 +1,27 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * Organizations (product copy: "teams") group users within one tenant. Infra table like `tenants`
5
+ * (no RLS): a team is a collaboration boundary inside one customer, not a hostile-isolation boundary.
6
+ * App tables reference it (the app's own tables carry a nullable-or-NOT-NULL `org_id`
7
+ * that references organizations.id) — this framework migration creates the table those app migrations
8
+ * (≥1001, ADR-0012) point at; it never touches an app table itself (the showcase's own `org_id`
9
+ * columns live in its own >=1001 migrations).
10
+ */
11
+ export async function up(db: Kysely<any>): Promise<void> {
12
+ await db.schema
13
+ .createTable('organizations')
14
+ .addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
15
+ .addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
16
+ .addColumn('slug', 'text', (col) => col.notNull())
17
+ .addColumn('name', 'text', (col) => col.notNull())
18
+ // Slugs are unique within a tenant (globally unique in seed while clerk-dev is shared).
19
+ .addUniqueConstraint('organizations_tenant_slug_unique', ['tenant_id', 'slug'])
20
+ .execute()
21
+
22
+ await sql`GRANT SELECT ON organizations TO app_user`.execute(db)
23
+ }
24
+
25
+ export async function down(db: Kysely<any>): Promise<void> {
26
+ await db.schema.dropTable('organizations').execute()
27
+ }