@sssb/kit 0.0.0-stage → 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 -3
  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
@@ -0,0 +1,88 @@
1
+ import { Kysely, PostgresDialect, type Transaction } from 'kysely'
2
+ import { Pool, types, type CustomTypesConfig } from 'pg'
3
+ import { migrateToLatest } from '../../db/migrate'
4
+ import type { DB } from '../../db/schema'
5
+ import { runWithTenant } from '../../db/with-tenant'
6
+ import type { DbPort } from '../../ports/db'
7
+
8
+ /**
9
+ * A Postgres `date` is a calendar day — no time, no zone — and it reaches application code as the wire
10
+ * string (`'2026-10-03'`), never a JS `Date`. `pg`'s default parser builds `new Date(y, m, d)`: LOCAL
11
+ * midnight in whatever zone the server process runs in, which east of UTC is still the previous day
12
+ * once read back as UTC. There is no zone-safe `Date` to build from a value that was never an instant,
13
+ * so none is built. The schema types every `date` column as `string`, and this is what makes that true.
14
+ *
15
+ * `date[]` is parsed as a text array, so an array of days is an array of strings (its own default
16
+ * rebuilds each element with the same local-midnight `Date`). The fake adapter configures pglite
17
+ * identically (`openPglite`, ../fake/pglite-dialect.ts), and the fixture's `due_on` proof pins both.
18
+ *
19
+ * Scoped to THIS adapter's pool rather than `types.setTypeParser`, which would rewrite the parser for
20
+ * every `pg` client in the process, from whichever module happened to be imported first.
21
+ */
22
+ type Oid = Parameters<typeof types.getTypeParser>[0]
23
+ // pg-types' `TypeId` enum names scalar types only, so the two array OIDs are cast into it.
24
+ const DATE_ARRAY_OID = 1182 as Oid
25
+ const TEXT_ARRAY_OID = 1009 as Oid
26
+ const pgTypes: CustomTypesConfig = {
27
+ getTypeParser: (oid, format = 'text') => {
28
+ if (format === 'text' && oid === types.builtins.DATE) return (value: string) => value
29
+ if (format === 'text' && oid === DATE_ARRAY_OID) return types.getTypeParser(TEXT_ARRAY_OID, format)
30
+ return types.getTypeParser(oid, format)
31
+ },
32
+ }
33
+
34
+ /**
35
+ * AUTHORED — CUTOVER (`cloud-accounts`): typechecked, never run against Aurora. The migrator
36
+ * Lambda and the app share this adapter; connection details come from DATABASE_URL (Secrets
37
+ * Manager-injected in deployed environments). This is the default transport (`DATABASE_TRANSPORT=pg`),
38
+ * for a Lambda inside the database's VPC; the RDS Data API one is ./db-data-api.ts.
39
+ */
40
+ export function createRealDb(databaseUrl: string): DbPort {
41
+ const pool = new Pool({ connectionString: databaseUrl, max: 5, types: pgTypes })
42
+ // Every client gets its own listener as it connects, for its whole life, idle or checked out.
43
+ pool.on('connect', (client) => client.on('error', logConnectionError))
44
+ // pg-pool re-emits an IDLE client's error on the pool. The client's listener above has logged it, and
45
+ // any other error the pool emits (a failed connect, a client being removed) has already reached the
46
+ // caller that asked for it, so this listener exists only so the event is not an uncaught exception.
47
+ pool.on('error', () => undefined)
48
+ return dbPortFor(new Kysely<DB>({ dialect: new PostgresDialect({ pool }) }))
49
+ }
50
+
51
+ /**
52
+ * A pooled connection the server ended: a failover, a reboot, an idle-session timeout, a socket dropped
53
+ * while the Lambda sat frozen between invocations. pg reports it as an 'error' EVENT on the client, and an
54
+ * event with no listener is an uncaught exception, which crashes the process: between requests if the
55
+ * connection was idle, in the middle of one if a transaction held it. pg-pool listens to idle clients only,
56
+ * and Kysely adds no listener to the client it checks out, which it does for every transaction, every
57
+ * `withTenant` and the migrator's run. So every client gets this listener. If a query or transaction was
58
+ * using the connection, that query fails with its own error as usual. Either way, the pool drops the dead
59
+ * client and the next query opens a fresh one.
60
+ *
61
+ * Logged with `console.warn`, which reaches CloudWatch in Lambda. SSSB has no logger port, and Sentry is
62
+ * loaded only when a DSN is configured (../sentry/init.ts), so the adapter does not import it. Only the
63
+ * error's code and message are logged (57P01 is "terminating connection due to administrator command").
64
+ * They carry no credentials, unlike the error object itself, whose `client` holds the password. The Data
65
+ * API transport has no such pool: it speaks HTTPS through the SDK, whose failures reject the call that
66
+ * made them.
67
+ */
68
+ function logConnectionError(error: Error & { code?: string }): void {
69
+ console.warn(`SSSB db: a pooled database connection ended (${error.code ?? 'no code'}: ${error.message})`)
70
+ }
71
+
72
+ /** One port shape for both transports: they differ in how SQL reaches Postgres, never in what it says. */
73
+ export function dbPortFor(db: Kysely<DB>): DbPort {
74
+ return {
75
+ getDb() {
76
+ return db
77
+ },
78
+ async ready() {
79
+ // Real databases are provisioned/migrated by the deploy pipeline, not lazily.
80
+ },
81
+ async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
82
+ return runWithTenant(db, tenantId, fn)
83
+ },
84
+ async migrateToLatest() {
85
+ await migrateToLatest(db)
86
+ },
87
+ }
88
+ }
@@ -0,0 +1,22 @@
1
+ import Mailgun from 'mailgun.js'
2
+ import type { EmailPort } from '../../ports/email'
3
+
4
+ /**
5
+ * AUTHORED — CUTOVER (`email-outbound`): typechecked against mailgun.js, never sent for real.
6
+ */
7
+ export function createRealEmail(domain: string, apiKey: string, from: string): EmailPort {
8
+ const mailgun = new Mailgun(FormData)
9
+ const client = mailgun.client({ username: 'api', key: apiKey })
10
+
11
+ return {
12
+ async send(message) {
13
+ await client.messages.create(domain, {
14
+ from,
15
+ to: [message.to],
16
+ subject: message.subject,
17
+ html: message.html,
18
+ text: message.text,
19
+ })
20
+ },
21
+ }
22
+ }
@@ -0,0 +1,89 @@
1
+ import type { AnalyticsPort } from '../../ports/analytics'
2
+ import type { AuthPort } from '../../ports/auth'
3
+ import type { DbPort } from '../../ports/db'
4
+ import type { EmailPort } from '../../ports/email'
5
+ import { CutoverPendingError } from '../../ports/errors'
6
+ import type { JobsPort } from '../../ports/jobs'
7
+ import type { LlmPort } from '../../ports/llm'
8
+ import type { StoragePort } from '../../ports/storage'
9
+ import { fakeAnalytics } from '../fake/analytics'
10
+ import { createRealAnalytics } from './analytics'
11
+ import { realAuth } from './auth'
12
+ import { DATABASE_ENV, databaseTransport } from './database-transport'
13
+ import { createRealDb } from './db'
14
+ import { createRealEmail } from './email'
15
+ import { createRealJobs } from './jobs'
16
+ import { createRealLlm } from './llm'
17
+ import { createRealStorage } from './storage'
18
+
19
+ interface RealPorts {
20
+ auth: AuthPort
21
+ db: DbPort
22
+ storage: StoragePort
23
+ llm: LlmPort
24
+ email: EmailPort
25
+ analytics: AnalyticsPort
26
+ jobs: JobsPort
27
+ }
28
+
29
+ /** Env var -> cutover-checklist row. Fails fast with the full list, not one var at a time. */
30
+ const REQUIRED_ENV: Record<string, string> = {
31
+ NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: 'auth-dev',
32
+ CLERK_SECRET_KEY: 'auth-dev',
33
+ STORAGE_BUCKET: 'cloud-accounts',
34
+ AWS_REGION: 'cloud-accounts',
35
+ JOBS_CODEBUILD_PROJECT: 'job-runner',
36
+ WEBHOOK_SECRET: 'job-runner',
37
+ ANTHROPIC_API_KEY: 'llm-key',
38
+ MAILGUN_DOMAIN: 'email-outbound',
39
+ MAILGUN_API_KEY: 'email-outbound',
40
+ EMAIL_FROM: 'email-outbound',
41
+ // Inbound: the key Mailgun signs inbound-route webhooks with — verified by the
42
+ // /api/webhooks/email route (packages/kit/src/service-auth/mailgun.ts). Read at request time, not here.
43
+ MAILGUN_WEBHOOK_SIGNING_KEY: 'email-inbound',
44
+ }
45
+
46
+ export function assertRealEnv(): void {
47
+ const required = { ...REQUIRED_ENV, ...DATABASE_ENV[databaseTransport()] }
48
+ const missing = Object.keys(required).filter((name) => !process.env[name])
49
+ if (missing.length > 0) {
50
+ const rows = [...new Set(missing.map((name) => required[name]))]
51
+ throw new CutoverPendingError(
52
+ rows as string[],
53
+ `Missing env: ${missing.join(', ')}. See docs/cutover-checklist.md.`,
54
+ )
55
+ }
56
+ }
57
+
58
+ export async function createRealPorts(): Promise<RealPorts> {
59
+ assertRealEnv()
60
+ const env = process.env
61
+ // assertRealEnv above already proved every required variable is set; this narrows the type.
62
+ const need = (name: string): string => {
63
+ const value = env[name]
64
+ if (value === undefined) throw new Error(`missing env: ${name}`)
65
+ return value
66
+ }
67
+ // The Data API transport is a dynamic import, so a `pg` deployment never loads the RDS Data SDK.
68
+ const db =
69
+ databaseTransport() === 'data-api'
70
+ ? (await import('./db-data-api')).createRealDataApiDb({
71
+ resourceArn: need('DATABASE_CLUSTER_ARN'),
72
+ secretArn: need('DATABASE_SECRET_ARN'),
73
+ database: need('DATABASE_NAME'),
74
+ region: need('AWS_REGION'),
75
+ })
76
+ : createRealDb(need('DATABASE_URL'))
77
+ return {
78
+ auth: realAuth,
79
+ db,
80
+ storage: createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION')),
81
+ llm: createRealLlm(need('ANTHROPIC_API_KEY')),
82
+ email: createRealEmail(need('MAILGUN_DOMAIN'), need('MAILGUN_API_KEY'), need('EMAIL_FROM')),
83
+ jobs: createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION')),
84
+ // PostHog only where a key is configured (staging/prod per ADR-0010); no-op otherwise.
85
+ analytics: env['POSTHOG_KEY']
86
+ ? createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
87
+ : fakeAnalytics,
88
+ }
89
+ }
@@ -0,0 +1,32 @@
1
+ import { CodeBuildClient, StartBuildCommand } from '@aws-sdk/client-codebuild'
2
+ import type { JobsPort } from '../../ports/jobs'
3
+
4
+ /**
5
+ * AUTHORED — CUTOVER (`job-runner`): typechecked against @aws-sdk/client-codebuild, never run
6
+ * against a real project. Starting the build is ALL this seam does — the job stays 'queued' until
7
+ * the build's FINAL step POSTs /api/webhooks/jobs with `Authorization: Bearer $WEBHOOK_SECRET` and
8
+ * `{ jobId, tenantId, status: 'completed' | 'failed', resultKey?, error? }`, which records the
9
+ * terminal transition via packages/kit/src/db/jobs.recordWebhookCompletion (idempotent under redelivery). The
10
+ * build receives its context through environment overrides, mirroring the fake handler's args —
11
+ * including JOB_TENANT_ID, which the webhook echoes back as `tenantId` so the completion is scoped
12
+ * to the right tenant without the build having to look it up.
13
+ */
14
+ export function createRealJobs(project: string, region: string): JobsPort {
15
+ const client = new CodeBuildClient({ region })
16
+
17
+ return {
18
+ async start(job) {
19
+ await client.send(
20
+ new StartBuildCommand({
21
+ projectName: project,
22
+ environmentVariablesOverride: [
23
+ { name: 'JOB_ID', value: job.id, type: 'PLAINTEXT' },
24
+ { name: 'JOB_KIND', value: job.kind, type: 'PLAINTEXT' },
25
+ { name: 'JOB_TENANT_ID', value: job.tenantId, type: 'PLAINTEXT' },
26
+ { name: 'JOB_PAYLOAD', value: JSON.stringify(job.payload ?? {}), type: 'PLAINTEXT' },
27
+ ],
28
+ }),
29
+ )
30
+ },
31
+ }
32
+ }
@@ -0,0 +1,108 @@
1
+ import Anthropic from '@anthropic-ai/sdk'
2
+ import { LLM_MODELS } from '../../core/llm-models'
3
+ import type { LlmContentBlock, LlmPort, LlmRequest, LlmTurn } from '../../ports/llm'
4
+
5
+ /**
6
+ * AUTHORED — CUTOVER (`llm-key`): typechecked, never run against the real API. Also used by each
7
+ * app's own `scripts/llm-record.ts` to (re)record fixtures. The `llm-key` cutover row's deferred
8
+ * verification covers BOTH: re-recording the conversation fixtures AND running one live tool loop
9
+ * (`runToolLoop` below — tool_use/tool_result blocks, loop until end_turn or maxTurns).
10
+ */
11
+ export function createRealLlm(apiKey: string): LlmPort {
12
+ const client = new Anthropic({ apiKey })
13
+
14
+ const toParams = (request: LlmRequest) => ({
15
+ model: request.model ?? LLM_MODELS.default,
16
+ ...(request.system === undefined ? {} : { system: request.system }),
17
+ messages: request.messages,
18
+ max_tokens: request.maxTokens ?? 1024,
19
+ })
20
+
21
+ return {
22
+ async complete(request) {
23
+ const message = await client.messages.create(toParams(request))
24
+ const text = message.content
25
+ .filter((block): block is Anthropic.TextBlock => block.type === 'text')
26
+ .map((block) => block.text)
27
+ .join('')
28
+ return { text }
29
+ },
30
+
31
+ async *stream(request) {
32
+ const stream = client.messages.stream(toParams(request))
33
+ for await (const chunk of stream) {
34
+ if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {
35
+ yield chunk.delta.text
36
+ }
37
+ }
38
+ },
39
+
40
+ async runToolLoop(request) {
41
+ const tools: Anthropic.Tool[] = request.tools.map((t) => ({
42
+ name: t.name,
43
+ description: t.description,
44
+ input_schema: t.inputSchema,
45
+ }))
46
+ // Running SDK message history (assistant + tool_result turns), fed back each round.
47
+ const messages: Anthropic.MessageParam[] = request.messages.map((m) => ({
48
+ role: m.role,
49
+ content: m.content,
50
+ }))
51
+ // Port-shaped view of the same conversation (serializes to the fixture format).
52
+ const turns: LlmTurn[] = []
53
+ const maxTurns = request.maxTurns ?? 6
54
+
55
+ for (let round = 0; round < maxTurns; round++) {
56
+ const message = await client.messages.create({
57
+ model: request.model ?? LLM_MODELS.default,
58
+ ...(request.system === undefined ? {} : { system: request.system }),
59
+ messages,
60
+ tools,
61
+ max_tokens: request.maxTokens ?? 1024,
62
+ })
63
+
64
+ const assistantBlocks: LlmContentBlock[] = []
65
+ for (const block of message.content) {
66
+ if (block.type === 'text') assistantBlocks.push({ type: 'text', text: block.text })
67
+ else if (block.type === 'tool_use')
68
+ assistantBlocks.push({ type: 'tool_use', id: block.id, name: block.name, input: block.input })
69
+ // Other block types (thinking, server tools) aren't used by this surface.
70
+ }
71
+ turns.push({ role: 'assistant', content: assistantBlocks })
72
+ messages.push({ role: 'assistant', content: message.content })
73
+
74
+ if (message.stop_reason !== 'tool_use') {
75
+ return { text: textOf(assistantBlocks), turns }
76
+ }
77
+
78
+ // Relay each tool_use to the app's executor LIVE, then feed all results back at once.
79
+ const toolResults: Anthropic.ToolResultBlockParam[] = []
80
+ const resultBlocks: LlmContentBlock[] = []
81
+ for (const block of message.content) {
82
+ if (block.type !== 'tool_use') continue
83
+ // Defense-in-depth mirror of the fake adapter: never execute a tool_use whose
84
+ // name the app didn't supply — the model is untrusted (see the port trust model).
85
+ const known = request.tools.some((t) => t.name === block.name)
86
+ const result = known
87
+ ? await request.execute({ name: block.name, input: block.input })
88
+ : `unknown tool: ${block.name}`
89
+ toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: result })
90
+ resultBlocks.push({ type: 'tool_result', toolUseId: block.id, content: result })
91
+ }
92
+ messages.push({ role: 'user', content: toolResults })
93
+ turns.push({ role: 'user', content: resultBlocks })
94
+ }
95
+
96
+ // Hit maxTurns without an end_turn: return the last assistant text.
97
+ const lastAssistant = [...turns].reverse().find((t) => t.role === 'assistant')
98
+ return { text: lastAssistant ? textOf(lastAssistant.content) : '', turns }
99
+ },
100
+ }
101
+ }
102
+
103
+ function textOf(blocks: LlmContentBlock[]): string {
104
+ return blocks
105
+ .filter((b): b is Extract<LlmContentBlock, { type: 'text' }> => b.type === 'text')
106
+ .map((b) => b.text)
107
+ .join('')
108
+ }
@@ -0,0 +1,66 @@
1
+ import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager'
2
+ import { databaseTransport } from './database-transport'
3
+ import { createRealDb } from './db'
4
+
5
+ /**
6
+ * Migrator Lambda handler (ADR-0001): runs the same migration registry the app, unit tests, and
7
+ * contract tests use. Invoked by the CD pipeline before each release shifts traffic.
8
+ * AUTHORED — CUTOVER (`cloud-accounts`; `data-api` for the Data API path).
9
+ *
10
+ * ROLES. The credentials here are the migrator's, and migration 0015 grants that role the switch to
11
+ * `app_user`. If the application connects as a DIFFERENT role, that role needs the switch too. It cannot
12
+ * grant itself that; this role, which created `app_user` and so holds ADMIN on it, or any other role with
13
+ * ADMIN on `app_user`, runs: GRANT app_user TO <app role> WITH SET TRUE, INHERIT TRUE;
14
+ * A SECOND database's owner on the same cluster (staging beside production) has no ADMIN on the
15
+ * `app_user` the first one created: its run stops at 0015 and prints the GRANT to run; see the same row.
16
+ * (the `db-role-not-superuser` row in docs/cutover-checklist.md; ADR-0004, 2026-11-16 addendum).
17
+ *
18
+ * The transport follows the app's switch (`DATABASE_TRANSPORT`, ./index.ts), and the Data API one is a
19
+ * dynamic import here too. On the Data API, Kysely's Migrator runs every pending migration in ONE Data
20
+ * API transaction, as it does on `pg` (Postgres DDL is transactional). Two limits follow, and both fail
21
+ * loudly rather than half-apply: the transaction dies after an hour (AWS's BeginTransaction API
22
+ * reference) or three idle minutes, and any single statement still running at 45 seconds is cancelled. A
23
+ * migration that cannot fit — a long backfill, an index on a large table — needs the `pg` transport, from
24
+ * inside the VPC: a deployment on the `data-api` network shape has no other way in to run it.
25
+ *
26
+ * @public
27
+ */
28
+ export async function handler(): Promise<{ ok: true }> {
29
+ if (databaseTransport() === 'data-api') {
30
+ const { DATABASE_CLUSTER_ARN, DATABASE_SECRET_ARN, DATABASE_NAME } = process.env
31
+ if (!DATABASE_CLUSTER_ARN || !DATABASE_SECRET_ARN || !DATABASE_NAME) {
32
+ throw new Error('DATABASE_CLUSTER_ARN, DATABASE_SECRET_ARN and DATABASE_NAME must be set for the Data API')
33
+ }
34
+ const { createRealDataApiDb } = await import('./db-data-api')
35
+ const db = createRealDataApiDb({
36
+ resourceArn: DATABASE_CLUSTER_ARN,
37
+ secretArn: DATABASE_SECRET_ARN,
38
+ database: DATABASE_NAME,
39
+ })
40
+ await db.migrateToLatest()
41
+ return { ok: true }
42
+ }
43
+
44
+ const secretArn = process.env['DB_SECRET_ARN']
45
+ if (!secretArn) throw new Error('DB_SECRET_ARN is not set')
46
+
47
+ const client = new SecretsManagerClient({})
48
+ const secret = await client.send(new GetSecretValueCommand({ SecretId: secretArn }))
49
+ const { host, port, username, password, dbname } = JSON.parse(secret.SecretString ?? '{}') as {
50
+ host: string
51
+ port: number
52
+ username: string
53
+ password: string
54
+ dbname?: string
55
+ }
56
+
57
+ // The deployment names the database (SSSB's construct sets DATABASE_NAME); the secret's `dbname` is the fallback
58
+ // for infra that does not, and is there only if the cluster's secret attachment added it.
59
+ const database = process.env['DATABASE_NAME'] ?? dbname
60
+ if (!database) throw new Error('neither DATABASE_NAME nor the secret names the database to migrate')
61
+ const db = createRealDb(
62
+ `postgres://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}/${database}`,
63
+ )
64
+ await db.migrateToLatest()
65
+ return { ok: true }
66
+ }
@@ -0,0 +1,12 @@
1
+ 'use client'
2
+
3
+ import { ClerkProvider } from '@clerk/nextjs'
4
+ import type { ReactNode } from 'react'
5
+
6
+ /**
7
+ * Real-mode client providers. Only mounted when APP_MODE=real, so simulated mode ships zero Clerk
8
+ * code. AUTHORED — CUTOVER (`auth-dev`).
9
+ */
10
+ export function RealAuthProviders({ children }: { children: ReactNode }) {
11
+ return <ClerkProvider>{children}</ClerkProvider>
12
+ }