@sssb/kit 0.0.0 → 0.3.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 (227) 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 +212 -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 +313 -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 +248 -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 +93 -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 +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,27 @@
1
+ import { mkdirSync } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /** The directory all fake-adapter state lives under: APP_DATA_DIR, else `.data/` (gitignored). Creates nothing. */
5
+ export function dataRoot(): string {
6
+ return process.env['APP_DATA_DIR'] ?? path.join(process.cwd(), '.data')
7
+ }
8
+
9
+ /** A directory under the fake adapters' data root, created if missing. Tests point APP_DATA_DIR at a tmp dir. */
10
+ export function dataDir(...segments: string[]): string {
11
+ const dir = path.join(dataRoot(), ...segments)
12
+ mkdirSync(dir, { recursive: true })
13
+ return dir
14
+ }
15
+
16
+ /**
17
+ * Points every fake adapter at `dir` (undefined: back to the default) by ASSIGNING APP_DATA_DIR, and returns the
18
+ * value it replaced. For a harness that ships in a test suite and so runs under an adopter's Vitest config: a
19
+ * `vi.stubEnv` there is undone before every test by `unstubEnvs: true`, which would point the next test at the
20
+ * working directory's `.data`, the developer's own world.
21
+ */
22
+ export function setDataRoot(dir: string | undefined): string | undefined {
23
+ const previous = process.env['APP_DATA_DIR']
24
+ if (dir === undefined) delete process.env['APP_DATA_DIR']
25
+ else process.env['APP_DATA_DIR'] = dir
26
+ return previous
27
+ }
@@ -0,0 +1,88 @@
1
+ import type { PGlite } from '@electric-sql/pglite'
2
+ import { Kysely, type Transaction } from 'kysely'
3
+ import { migrateToLatest } from '../../db/migrate'
4
+ import type { DB } from '../../db/schema'
5
+ import { seedDb } from '../../db/seed'
6
+ import { runWithTenant } from '../../db/with-tenant'
7
+ import type { DbPort } from '../../ports/db'
8
+ import { worldNow } from './clock'
9
+ import { dataDir } from './data-dir'
10
+ import { fakeEmail } from './email'
11
+ import { openPglite, PGliteDialect } from './pglite-dialect'
12
+ import { fakeStorage } from './storage'
13
+
14
+ // Survive Next dev hot-reload: keep the single pglite instance on globalThis. The raw client is
15
+ // cached alongside db/ready (not just derivable from `db`) so closeFakeDb() below can actually
16
+ // close it — Kysely's own PGliteDriver.destroy() is a no-op (see pglite-dialect.ts).
17
+ const globalStore = globalThis as unknown as {
18
+ __appFakeDb?: { db: Kysely<DB>; ready: Promise<void>; client: PGlite }
19
+ }
20
+
21
+ function instance() {
22
+ if (!globalStore.__appFakeDb) {
23
+ // Persisted under .data so dev data survives restarts; delete .data/pglite to reset.
24
+ const client = openPglite(dataDir('pglite'))
25
+ const db = new Kysely<DB>({ dialect: new PGliteDialect(client) })
26
+ // Seeding is a FAKE-mode concern (real deployments migrate but never seed), so the fake
27
+ // adapters are the natural place to hand the seeder the storage and email it needs to furnish
28
+ // a world: an app's seeded attachments need bytes, and its opening state may include mail.
29
+ const ready = migrateToLatest(db).then(() => seedDb(db, { storage: fakeStorage, email: fakeEmail }))
30
+ globalStore.__appFakeDb = { db, ready, client }
31
+ }
32
+ return globalStore.__appFakeDb
33
+ }
34
+
35
+ /**
36
+ * Closes the cached pglite client and drops the global cache (simulated-mode-only, used by Simulator's
37
+ * Snapshots reset/save/restore — packages/kit/src/adapters/fake/simulator-admin.ts — before touching `.data/pglite`
38
+ * on disk). No-op if nothing has been created yet. Awaits `ready` first so a migration/seed in
39
+ * flight always finishes before the client closes underneath it — its rejection is swallowed
40
+ * (an already-failed migration shouldn't block the close) but never skipped. `client.close()`'s
41
+ * rejection is swallowed too: this is the ONE step that must not leave the global cache stuck
42
+ * pointing at a client that failed to close cleanly — a caller (Snapshots reset/restore) that can't
43
+ * drop its old pglite handle can never get a working fresh one either, since `instance()` only
44
+ * re-creates when the cache slot is empty. Because `instance()` is lazy, the very next call
45
+ * re-creates, re-migrates, and re-seeds a fresh pglite instance — no server restart needed.
46
+ */
47
+ export async function closeFakeDb(): Promise<void> {
48
+ const store = globalStore.__appFakeDb
49
+ if (!store) return
50
+ await store.ready.catch(() => {})
51
+ await store.client.close().catch(() => {})
52
+ delete globalStore.__appFakeDb
53
+ }
54
+
55
+ export const fakeDb: DbPort = {
56
+ getDb() {
57
+ return instance().db
58
+ },
59
+ async ready() {
60
+ await instance().ready
61
+ },
62
+ async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
63
+ const { db, ready } = instance()
64
+ await ready
65
+ return runWithTenant(db, tenantId, fn)
66
+ },
67
+ async migrateToLatest() {
68
+ await instance().ready
69
+ },
70
+ /**
71
+ * The Simulator's world clock (real time plus the offset a demo advanced), so audit rows follow it. Total on
72
+ * purpose: a hand-edited or corrupt `.data/simulator/clock.json`, or an offset past the Date range, must cost
73
+ * the demo its clock and not the app its audit writes (a route that has already committed would answer 500
74
+ * with no audit row), so anything but an instant Postgres can store falls back to real time. A valid JS Date
75
+ * is not enough: past year 9999 (or before year 0) `toISOString()` prints an extended-year string, which
76
+ * a timestamptz column rejects.
77
+ */
78
+ now() {
79
+ try {
80
+ const world = worldNow()
81
+ const year = world.getUTCFullYear() // NaN for an Invalid Date, which fails both comparisons
82
+ if (year >= 0 && year <= 9999) return world
83
+ } catch {
84
+ // an unreadable clock file: real time
85
+ }
86
+ return new Date()
87
+ },
88
+ }
@@ -0,0 +1,46 @@
1
+ import { readdirSync, readFileSync, rmSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import type { EmailMessage, EmailPort } from '../../ports/email'
4
+ import { writeJsonAtomic } from './atomic-write'
5
+ import { dataDir } from './data-dir'
6
+
7
+ /**
8
+ * Catches every send into .data/emails/ (ADR-0011) — the port is the catch-point, no SMTP
9
+ * catcher. The Simulator panel's Mail tab (GET /api/simulator/mail) renders this store;
10
+ * Playwright asserts against it.
11
+ */
12
+
13
+ export interface CaughtEmail extends EmailMessage {
14
+ id: string
15
+ at: string
16
+ }
17
+
18
+ let counter = 0
19
+
20
+ export const fakeEmail: EmailPort = {
21
+ async send(message) {
22
+ const caught: CaughtEmail = {
23
+ id: `${Date.now()}-${(counter++).toString().padStart(3, '0')}`,
24
+ at: new Date().toISOString(),
25
+ ...message,
26
+ }
27
+ await writeJsonAtomic(path.join(dataDir('emails'), `${caught.id}.json`), caught)
28
+ },
29
+ }
30
+
31
+ /** Simulated-mode-only surface for the Simulator Mail tab's "clear mailbox" (NOT part of EmailPort). */
32
+ export function clearCaughtEmails(): void {
33
+ const dir = dataDir('emails')
34
+ for (const file of readdirSync(dir)) {
35
+ if (file.endsWith('.json')) rmSync(path.join(dir, file), { force: true })
36
+ }
37
+ }
38
+
39
+ /** Simulated-mode-only surface for the Simulator Mail tab (NOT part of EmailPort). */
40
+ export function listCaughtEmails(): CaughtEmail[] {
41
+ const dir = dataDir('emails')
42
+ return readdirSync(dir)
43
+ .filter((f) => f.endsWith('.json'))
44
+ .map((f) => JSON.parse(readFileSync(path.join(dir, f), 'utf8')) as CaughtEmail)
45
+ .sort((a, b) => (a.id < b.id ? 1 : -1))
46
+ }
@@ -0,0 +1,248 @@
1
+ import { jobHandlers, serviceManagedOrgSlugs } from '@sssb/app-config/jobs'
2
+ import { isJobKind, type JobStatus } from '../../core/jobs'
3
+ import { type JobTimelineEntry, loadTimelines, toIso } from '../../db/jobs'
4
+ import { runJobInProcess } from '../../jobs/run-in-process'
5
+ import { NotFoundError } from '../../ports/errors'
6
+ import type { JobsPort, SubmittedJob } from '../../ports/jobs'
7
+ import { readFlags } from './analytics'
8
+ import { fakeAuth, personLocale } from './auth'
9
+ import { fakeDb } from './db'
10
+ import { fakeEmail } from './email'
11
+ import { fakeLlm } from './llm'
12
+ import { fakeSendSms } from './sms'
13
+ import { fakeStorage } from './storage'
14
+
15
+ /** Simulator flag: when set, submitted jobs stay 'queued' so an operator can step them forward. */
16
+ export const JOBS_HELD_FLAG = 'jobs-held'
17
+
18
+ function isHeld(): boolean {
19
+ return readFlags()[JOBS_HELD_FLAG] === true
20
+ }
21
+
22
+ /**
23
+ * Notify the job's org admins that a user-facing job reached a terminal state. Best-effort:
24
+ * a notification failure must never fail the job. The fan-out module is DYNAMICALLY imported so this
25
+ * adapter never statically depends on @/server-lib/notify (which pulls @/adapters via defer/sms) — the
26
+ * dispatchWebhook dynamic-import trick that keeps the fake off the @/adapters cycle. The seam filters
27
+ * to user-facing kinds and resolves the org itself, so passing the three facts is enough.
28
+ */
29
+ async function notifyTerminal(job: SubmittedJob, status: 'completed' | 'failed'): Promise<void> {
30
+ try {
31
+ const { notifyJobTerminal } = await import('../../server-lib/notify')
32
+ await notifyJobTerminal(
33
+ { db: fakeDb, email: fakeEmail, sms: fakeSendSms, resolveLocale: personLocale },
34
+ fakeAuth,
35
+ { tenantId: job.tenantId, jobId: job.id, status },
36
+ )
37
+ } catch {
38
+ // Notification is a side effect of a completed job, never a reason to fail it.
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Runs a submitted job to completion in-process (`runJobInProcess`, shared with the real in-process runner). An
44
+ * instant fake still records queued -> running -> completed (or -> failed), the transitions a CodeBuild run reports
45
+ * through the service-authenticated jobs webhook. A concurrent runner (a second run-pending click racing an instant
46
+ * start) that already claimed the job makes this return false. Never checks the held flag itself: holding only gates
47
+ * fakeJobs.start(); runPendingJobs() steps held jobs forward deliberately.
48
+ */
49
+ async function executeJob(job: SubmittedJob): Promise<boolean> {
50
+ await fakeDb.ready()
51
+ const ports = {
52
+ db: fakeDb,
53
+ storage: fakeStorage,
54
+ email: fakeEmail,
55
+ llm: fakeLlm,
56
+ auth: fakeAuth,
57
+ resolveLocale: personLocale,
58
+ }
59
+ return runJobInProcess(job, ports, (status) => notifyTerminal(job, status))
60
+ }
61
+
62
+ export const fakeJobs: JobsPort = {
63
+ async start(job) {
64
+ // Held world (Simulator): leave the job queued for a later runPendingJobs() step. Otherwise
65
+ // run it to completion instantly — the fake's whole point is a synchronous, inspectable world.
66
+ if (isHeld()) return
67
+ await executeJob(job)
68
+ },
69
+ }
70
+
71
+ /** One row of the simulated-mode cross-tenant world view (NOT part of JobsPort). */
72
+ export interface WorldJob {
73
+ id: string
74
+ kind: string
75
+ status: JobStatus
76
+ tenantSlug: string
77
+ orgSlug: string | null
78
+ createdAt: string
79
+ resultKey: string | null
80
+ error: string | null
81
+ timeline: JobTimelineEntry[]
82
+ }
83
+
84
+ /**
85
+ * Every job across ALL tenants, joined to tenant/org slugs, newest first (cap 50), timelines
86
+ * embedded — the Simulator Jobs tab's world view. A raw getDb() read on purpose: this is the
87
+ * simulated-world god view, deliberately reaching past the tenant RLS scope (simulated-mode-only).
88
+ */
89
+ export async function listWorldJobs(): Promise<WorldJob[]> {
90
+ await fakeDb.ready()
91
+ const db = fakeDb.getDb()
92
+ const rows = await db
93
+ .selectFrom('jobs')
94
+ .innerJoin('tenants', 'tenants.id', 'jobs.tenant_id')
95
+ .leftJoin('organizations', 'organizations.id', 'jobs.org_id')
96
+ .select([
97
+ 'jobs.id as id',
98
+ 'jobs.kind as kind',
99
+ 'jobs.status as status',
100
+ 'jobs.result_key as result_key',
101
+ 'jobs.error as error',
102
+ 'jobs.created_at as created_at',
103
+ 'tenants.slug as tenant_slug',
104
+ 'organizations.slug as org_slug',
105
+ ])
106
+ .orderBy('jobs.created_at', 'desc')
107
+ .limit(50)
108
+ .execute()
109
+ if (rows.length === 0) return []
110
+ const timelines = await loadTimelines(
111
+ db,
112
+ rows.map((r) => r.id),
113
+ )
114
+ return rows.map((r) => ({
115
+ id: r.id,
116
+ kind: r.kind,
117
+ status: r.status as JobStatus,
118
+ tenantSlug: r.tenant_slug,
119
+ orgSlug: r.org_slug,
120
+ createdAt: toIso(r.created_at),
121
+ resultKey: r.result_key,
122
+ error: r.error,
123
+ timeline: timelines.get(r.id) ?? [],
124
+ }))
125
+ }
126
+
127
+ /**
128
+ * Executes every currently-queued job across all tenants and returns how many actually ran (a job
129
+ * claimed by a concurrent runner mid-loop is skipped, not counted). The operator's "step the held
130
+ * world forward" action (Simulator) — runs jobs regardless of the held flag.
131
+ */
132
+ export async function runPendingJobs(): Promise<number> {
133
+ await fakeDb.ready()
134
+ const pending = await fakeDb
135
+ .getDb()
136
+ .selectFrom('jobs')
137
+ .select(['id', 'kind', 'tenant_id', 'org_id', 'payload'])
138
+ .where('status', '=', 'queued')
139
+ .orderBy('created_at', 'asc')
140
+ .execute()
141
+ let ran = 0
142
+ for (const job of pending) {
143
+ const executed = await executeJob({
144
+ id: job.id,
145
+ kind: job.kind,
146
+ tenantId: job.tenant_id,
147
+ orgId: job.org_id,
148
+ payload: job.payload,
149
+ })
150
+ if (executed) ran += 1
151
+ }
152
+ return ran
153
+ }
154
+
155
+ /** One pending build the builder-console actor may deliver a completion webhook for (NOT part of
156
+ * JobsPort). Structurally the component's PendingBuildLike — the actor twin's local view. */
157
+ export interface PendingBuild {
158
+ jobId: string
159
+ tenantId: string
160
+ tenantSlug: string
161
+ orgSlug: string | null
162
+ kind: string
163
+ status: 'queued' | 'running'
164
+ createdAt: string
165
+ }
166
+
167
+ /**
168
+ * The builder-console actor's work pool: every NON-terminal job (queued or running) across all
169
+ * tenants whose org is NOT a service-managed one (or has no org at all), oldest-first, joined to
170
+ * tenant/org slugs. Deliberately reaches past the tenant RLS scope via the raw god-view handle —
171
+ * same simulated-mode-only justification as listWorldJobs, beside which it lives. Excluding the
172
+ * service-managed orgs keeps the two actors' pools disjoint (see serviceManagedOrgSlugs in
173
+ * src/app-config/jobs.ts).
174
+ */
175
+ export async function listPendingBuilds(): Promise<PendingBuild[]> {
176
+ await fakeDb.ready()
177
+ const rows = await fakeDb
178
+ .getDb()
179
+ .selectFrom('jobs')
180
+ .innerJoin('tenants', 'tenants.id', 'jobs.tenant_id')
181
+ .leftJoin('organizations', 'organizations.id', 'jobs.org_id')
182
+ .select([
183
+ 'jobs.id as id',
184
+ 'jobs.kind as kind',
185
+ 'jobs.status as status',
186
+ 'jobs.tenant_id as tenant_id',
187
+ 'jobs.created_at as created_at',
188
+ 'tenants.slug as tenant_slug',
189
+ 'organizations.slug as org_slug',
190
+ ])
191
+ .where('jobs.status', 'in', ['queued', 'running'])
192
+ .orderBy('jobs.created_at', 'asc')
193
+ .execute()
194
+ return rows
195
+ .filter((r) => r.org_slug === null || !serviceManagedOrgSlugs.includes(r.org_slug))
196
+ .map((r) => ({
197
+ jobId: r.id,
198
+ tenantId: r.tenant_id,
199
+ tenantSlug: r.tenant_slug,
200
+ orgSlug: r.org_slug,
201
+ kind: r.kind,
202
+ status: r.status as 'queued' | 'running',
203
+ createdAt: toIso(r.created_at),
204
+ }))
205
+ }
206
+
207
+ /**
208
+ * (Re)produces a job's artifact by running its handler — artifact production ONLY, NEVER a status
209
+ * write (the actor reports status separately over the genuine service/webhook surface, so the
210
+ * timeline stays authored by those calls, not by this one). Loads the job row via the god-view
211
+ * handle; an unknown (tenantId, jobId) pair is a NotFoundError (→ 404 at the route). An unknown kind
212
+ * or a throwing handler returns `{ error }` so the actor can truthfully report the job failed.
213
+ * Idempotent: re-running overwrites the same storage key.
214
+ */
215
+ export async function produceJobArtifact(
216
+ tenantId: string,
217
+ jobId: string,
218
+ ): Promise<{ resultKey: string } | { error: string }> {
219
+ await fakeDb.ready()
220
+ const row = await fakeDb
221
+ .getDb()
222
+ .selectFrom('jobs')
223
+ .select(['id', 'kind', 'tenant_id', 'org_id', 'payload'])
224
+ .where('id', '=', jobId)
225
+ .where('tenant_id', '=', tenantId)
226
+ .executeTakeFirst()
227
+ if (!row) throw new NotFoundError(`unknown job: ${jobId}`)
228
+ if (!isJobKind(row.kind)) return { error: `unknown job kind: ${row.kind}` }
229
+ try {
230
+ const handler = jobHandlers[row.kind]
231
+ if (!handler) throw new Error(`no job handler registered for kind: ${row.kind}`)
232
+ const { resultKey } = await handler(row.payload, {
233
+ db: fakeDb,
234
+ storage: fakeStorage,
235
+ email: fakeEmail,
236
+ llm: fakeLlm,
237
+ auth: fakeAuth,
238
+ resolveLocale: personLocale,
239
+ tenantId: row.tenant_id,
240
+ orgId: row.org_id,
241
+ jobId: row.id,
242
+ })
243
+ if (!resultKey) return { error: 'handler produced no artifact' }
244
+ return { resultKey }
245
+ } catch (error) {
246
+ return { error: error instanceof Error ? error.message : String(error) }
247
+ }
248
+ }
@@ -0,0 +1,230 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import type { LlmMessage, LlmPort, LlmRequest, LlmToolDef, LlmToolLoopRequest, LlmTurn } from '../../ports/llm'
5
+ import { writeJsonAtomic } from './atomic-write'
6
+ import { dataDir } from './data-dir'
7
+
8
+ /**
9
+ * Deterministic replay of versioned fixtures (ADR-0009). Fixture files live in fixtures/llm/
10
+ * (committed).
11
+ *
12
+ * Single-turn (`complete`/`stream`): lookup by exact hash of {model, system, messages} -> the
13
+ * entry's `response`; else the purpose's default `response`; else a loud "record" error.
14
+ *
15
+ * Tool loops (`runToolLoop`): entries grow an optional `conversation` — the recorded
16
+ * sequence of model outputs (assistant turns, incl. tool_use requests). REPLAY drives those turns
17
+ * one at a time; between them the APP's `execute` runs LIVE against the fake world, so the tool
18
+ * RESULTS are real even though the model's utterances are canned (the replay-honesty split). The
19
+ * fixture never stores tool results. Matching is the same purpose+hash idea, extended to cover the
20
+ * tools + messages shape, with the same default-entry fallback (a `response`-only default becomes
21
+ * a one-turn text conversation).
22
+ *
23
+ * REQUEST CATCH: before any fixture lookup, every request is also written to .data/llm-requests/
24
+ * (the same port-as-catch-point shape as the fake email adapter, ADR-0011). A fixture proves what
25
+ * the app does with an answer; the catch proves what the app put into the prompt. It is recorded
26
+ * first so a request that matches no fixture — and so throws — is still inspectable.
27
+ */
28
+
29
+ interface LlmFixtureEntry {
30
+ name: string
31
+ /** Free-form provenance (e.g. "hand-authored pending re-record") — ignored by replay. */
32
+ note?: string
33
+ /** null request = the purpose's default/fallback. */
34
+ request: { model?: string; system?: string; messages: LlmMessage[]; tools?: LlmToolDef[] } | null
35
+ /** Single-turn answer for complete/stream. */
36
+ response: string | null
37
+ /** Recorded model outputs for a tool loop (assistant turns incl. tool_use), turn by turn. */
38
+ conversation?: LlmTurn[] | null
39
+ }
40
+
41
+ export interface LlmFixtureFile {
42
+ purpose: string
43
+ entries: LlmFixtureEntry[]
44
+ }
45
+
46
+ export interface CaughtLlmRequest {
47
+ id: string
48
+ at: string
49
+ purpose: string
50
+ system: string | null
51
+ messages: LlmMessage[]
52
+ /** Tool loops only: the model-facing tool definitions. The app's `execute` closure is never caught. */
53
+ tools: LlmToolDef[] | null
54
+ }
55
+
56
+ let counter = 0
57
+
58
+ /** Writes the request into the catch store. Ids sort oldest-first as strings; the counter breaks ties
59
+ * within one millisecond of one process (its six-digit pad keeps a long-lived process's ids sorting
60
+ * numerically), and the pid keeps two processes sharing one `.data` (a dev server and a script) from
61
+ * minting the same id and overwriting each other's catch. */
62
+ async function catchRequest(
63
+ request: { purpose: string; system?: string; messages: LlmMessage[] },
64
+ tools: LlmToolDef[] | null,
65
+ ): Promise<void> {
66
+ const caught: CaughtLlmRequest = {
67
+ id: `${Date.now()}-${process.pid}-${(counter++).toString().padStart(6, '0')}`,
68
+ at: new Date().toISOString(),
69
+ purpose: request.purpose,
70
+ system: request.system ?? null,
71
+ messages: request.messages,
72
+ tools: tools && tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
73
+ }
74
+ await writeJsonAtomic(path.join(dataDir('llm-requests'), `${caught.id}.json`), caught)
75
+ }
76
+
77
+ function hashLlmRequest(request: LlmRequest): string {
78
+ const canonical = JSON.stringify({
79
+ model: request.model ?? null,
80
+ system: request.system ?? null,
81
+ messages: request.messages,
82
+ })
83
+ return createHash('sha256').update(canonical).digest('hex')
84
+ }
85
+
86
+ /** Tool loops hash the tools + messages shape too, so an entry is matched to the request that
87
+ * built its tool set. Tools are canonicalized to their serializable {name, description,
88
+ * inputSchema} so the app's `execute` closure never enters the hash. */
89
+ function hashToolLoop(request: {
90
+ model?: string
91
+ system?: string
92
+ messages: LlmMessage[]
93
+ tools?: LlmToolDef[]
94
+ }): string {
95
+ const canonical = JSON.stringify({
96
+ model: request.model ?? null,
97
+ system: request.system ?? null,
98
+ messages: request.messages,
99
+ tools: (request.tools ?? []).map((t) => ({
100
+ name: t.name,
101
+ description: t.description,
102
+ inputSchema: t.inputSchema,
103
+ })),
104
+ })
105
+ return createHash('sha256').update(canonical).digest('hex')
106
+ }
107
+
108
+ function fixturePath(purpose: string): string {
109
+ if (!/^[a-z0-9-]+$/.test(purpose)) throw new Error(`invalid llm purpose: ${purpose}`)
110
+ // Fixtures are app-scoped (apps/<app>/fixtures), and the working directory IS the app for every
111
+ // command that runs the app (next dev/build, pnpm llm:record). APP_FIXTURES_DIR overrides that for
112
+ // runners whose cwd is the repo root — the unit suite runs every app's tests in one pass from
113
+ // there. Same override shape as APP_DATA_DIR.
114
+ const root = process.env['APP_FIXTURES_DIR'] ?? path.join(process.cwd(), 'fixtures')
115
+ return path.join(root, 'llm', `${purpose}.json`)
116
+ }
117
+
118
+ function readFixture(purpose: string): LlmFixtureFile {
119
+ const file = fixturePath(purpose)
120
+ if (!existsSync(file)) {
121
+ throw new Error(`no llm fixtures for purpose "${purpose}" — create ${file} and run pnpm llm:record`)
122
+ }
123
+ return JSON.parse(readFileSync(file, 'utf8')) as LlmFixtureFile
124
+ }
125
+
126
+ function lookup(request: LlmRequest): string {
127
+ const fixture = readFixture(request.purpose)
128
+ const hash = hashLlmRequest(request)
129
+ for (const entry of fixture.entries) {
130
+ if (entry.request && entry.response !== null) {
131
+ const entryHash = hashLlmRequest({ ...entry.request, purpose: request.purpose } as LlmRequest)
132
+ if (entryHash === hash) return entry.response
133
+ }
134
+ }
135
+ const fallback = fixture.entries.find((e) => e.request === null && e.response !== null)
136
+ if (fallback?.response) return fallback.response
137
+ throw new Error(
138
+ `no matching llm fixture in ${fixturePath(request.purpose)} (hash ${hash.slice(0, 12)}…) and no default entry`,
139
+ )
140
+ }
141
+
142
+ /** Resolve the recorded conversation (assistant model-outputs) for a tool-loop request. A default
143
+ * entry may carry a full `conversation` OR a single `response`, which becomes a one-turn text
144
+ * conversation — so a general question (no matching entry) still replays the deterministic answer. */
145
+ function lookupToolLoop(request: LlmToolLoopRequest): LlmTurn[] {
146
+ const fixture = readFixture(request.purpose)
147
+ const hash = hashToolLoop(request)
148
+ for (const entry of fixture.entries) {
149
+ if (entry.request && entry.conversation && entry.conversation.length > 0) {
150
+ if (hashToolLoop(entry.request) === hash) return entry.conversation
151
+ }
152
+ }
153
+ const fallback = fixture.entries.find((e) => e.request === null)
154
+ if (fallback?.conversation && fallback.conversation.length > 0) return fallback.conversation
155
+ if (fallback?.response) return [{ role: 'assistant', content: [{ type: 'text', text: fallback.response }] }]
156
+ throw new Error(
157
+ `no matching llm tool-loop fixture in ${fixturePath(request.purpose)} (hash ${hash.slice(0, 12)}…) and no default entry`,
158
+ )
159
+ }
160
+
161
+ function textOf(turn: LlmTurn): string {
162
+ return turn.content
163
+ .filter((b): b is Extract<typeof b, { type: 'text' }> => b.type === 'text')
164
+ .map((b) => b.text)
165
+ .join('')
166
+ }
167
+
168
+ export const fakeLlm: LlmPort = {
169
+ async complete(request) {
170
+ await catchRequest(request, null)
171
+ return { text: lookup(request) }
172
+ },
173
+
174
+ async *stream(request) {
175
+ // A generator body runs on first iteration, so the catch lands when the stream is consumed —
176
+ // the point a real adapter would open its connection too.
177
+ await catchRequest(request, null)
178
+ // Word-chunked so streaming UIs exercise their incremental path deterministically.
179
+ for (const chunk of lookup(request).split(/(?<= )/)) yield chunk
180
+ },
181
+
182
+ async runToolLoop(request) {
183
+ await catchRequest(request, request.tools)
184
+ const conversation = lookupToolLoop(request)
185
+ const turns: LlmTurn[] = []
186
+ const maxTurns = request.maxTurns ?? 6
187
+ for (let i = 0; i < conversation.length && i < maxTurns; i++) {
188
+ const assistantTurn = conversation[i]!
189
+ turns.push(assistantTurn)
190
+ const toolUses = assistantTurn.content.filter(
191
+ (b): b is Extract<typeof b, { type: 'tool_use' }> => b.type === 'tool_use',
192
+ )
193
+ if (toolUses.length === 0) return { text: textOf(assistantTurn), turns }
194
+ // Relay each tool_use to the app's executor LIVE — the result is real, not canned.
195
+ const resultBlocks: LlmTurn['content'] = []
196
+ for (const call of toolUses) {
197
+ // Defense-in-depth: a tool_use naming a tool the app never supplied (a hand-edited
198
+ // fixture, say) is refused here, before any execute dispatch could mis-route it.
199
+ const known = request.tools.some((t) => t.name === call.name)
200
+ const result = known
201
+ ? await request.execute({ name: call.name, input: call.input })
202
+ : `unknown tool: ${call.name}`
203
+ resultBlocks.push({ type: 'tool_result', toolUseId: call.id, content: result })
204
+ }
205
+ turns.push({ role: 'user', content: resultBlocks })
206
+ }
207
+ // Ran out of recorded turns (or hit maxTurns) with no terminal text-only turn: return the
208
+ // last assistant text we have rather than throwing — a truncated replay is still honest.
209
+ const lastAssistant = [...turns].reverse().find((t) => t.role === 'assistant')
210
+ return { text: lastAssistant ? textOf(lastAssistant) : '', turns }
211
+ },
212
+ }
213
+
214
+ /** Simulated-mode-only: every caught request, oldest first, optionally narrowed to one purpose (NOT part of LlmPort). */
215
+ export function listCaughtLlmRequests(purpose?: string): CaughtLlmRequest[] {
216
+ const dir = dataDir('llm-requests')
217
+ return readdirSync(dir)
218
+ .filter((f) => f.endsWith('.json'))
219
+ .map((f) => JSON.parse(readFileSync(path.join(dir, f), 'utf8')) as CaughtLlmRequest)
220
+ .filter((caught) => purpose === undefined || caught.purpose === purpose)
221
+ .sort((a, b) => (a.id < b.id ? -1 : 1))
222
+ }
223
+
224
+ /** Simulated-mode-only: forget every caught request (NOT part of LlmPort). */
225
+ export function clearCaughtLlmRequests(): void {
226
+ const dir = dataDir('llm-requests')
227
+ for (const file of readdirSync(dir)) {
228
+ if (file.endsWith('.json')) rmSync(path.join(dir, file), { force: true })
229
+ }
230
+ }