@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,69 @@
1
+ import type { Locale } from '../core/locale'
2
+ import type { AuthPort } from './auth'
3
+ import type { DbPort } from './db'
4
+ import type { EmailPort } from './email'
5
+ import type { LlmPort } from './llm'
6
+ import type { StoragePort } from './storage'
7
+
8
+ export interface SubmittedJob {
9
+ id: string
10
+ kind: string
11
+ tenantId: string
12
+ orgId: string | null
13
+ payload: unknown
14
+ }
15
+
16
+ /**
17
+ * What a running job handler is given: the ports it may touch plus the job's tenant/org/id context.
18
+ * The framework owns this contract; both framework handlers (packages/kit/src/jobs/digest-email.ts) and
19
+ * app-registered handlers (the seam's src/app-config/jobs.ts) implement JobHandler against it.
20
+ */
21
+ interface JobContext {
22
+ db: DbPort
23
+ storage: StoragePort
24
+ /** For handlers that send mail (e.g. digest-email); the export handler ignores it. */
25
+ email: EmailPort
26
+ /**
27
+ * For handlers whose work IS a model call — summarizing, classifying, extracting. Background work
28
+ * is where an LLM call belongs (it is slow, it can fail, and its result is an artifact), so the
29
+ * handler contract carries the port rather than making a handler reach for the adapter registry.
30
+ */
31
+ llm: LlmPort
32
+ /**
33
+ * For handlers that address people: who an org's members are, from the identity provider in a deployment (the
34
+ * same `listMembers` the jobs' notifications use). A handler never reads people from the seed, which a real
35
+ * deployment does not have.
36
+ */
37
+ auth: AuthPort
38
+ /**
39
+ * A person's own locale, by user id, where the runner knows it: the simulated world's runner does (its people's
40
+ * profiles); a deployment's does not (the auth port carries none), so it is absent there and copy falls back to
41
+ * the app's default, as the jobs' notifications do.
42
+ */
43
+ resolveLocale?: ((userId: string) => Locale | undefined) | undefined
44
+ tenantId: string
45
+ orgId: string | null
46
+ jobId: string
47
+ }
48
+
49
+ export type JobHandler = (payload: unknown, ctx: JobContext) => Promise<{ resultKey?: string }>
50
+
51
+ /**
52
+ * Jobs port — the execution SEAM only. The `jobs` row, its status column, and the
53
+ * `job_status_changes` timeline are app-owned in packages/kit/src/db/jobs.ts, where recordJobStatus is the
54
+ * single choke point for every transition (state-machine guarded). This port just kicks the work
55
+ * off: the fake adapter runs a registered handler in-process (instantly by default, or leaves the
56
+ * job 'queued' when the simulated world is held); in real mode `JOBS_RUNNER` picks the runner:
57
+ * `codebuild` starts a build whose terminal transition arrives later through the jobs webhook route,
58
+ * `in-process` runs the handler in the server before `start` returns
59
+ * (packages/kit/src/adapters/real/jobs-in-process.ts), and `none` throws `AbsentPortError`.
60
+ */
61
+ export interface JobsPort {
62
+ start(job: SubmittedJob): Promise<void>
63
+ /**
64
+ * Optional: for a runner whose jobs can be lost mid-run (the in-process runner, whose invocation can end before it
65
+ * records an outcome), fails each job it judges lost and says how many. The scheduled tick calls it, when the port
66
+ * has it, before it drains the due schedules.
67
+ */
68
+ sweep?(now: Date): Promise<number>
69
+ }
@@ -0,0 +1,85 @@
1
+ import type { LlmModelId } from '../core/llm-models'
2
+
3
+ export interface LlmMessage {
4
+ role: 'user' | 'assistant'
5
+ content: string
6
+ }
7
+
8
+ export interface LlmRequest {
9
+ /**
10
+ * Stable tag naming WHY the call is made (e.g. 'assistant-demo'). Fixtures are grouped by
11
+ * purpose, so replay stays deterministic per feature.
12
+ */
13
+ purpose: string
14
+ /** Defaults to LLM_MODELS.default. */
15
+ model?: LlmModelId
16
+ system?: string
17
+ messages: LlmMessage[]
18
+ maxTokens?: number
19
+ }
20
+
21
+ // --- Tool use --------------------------------------------------------------------------------
22
+ //
23
+ // A minimal, honest tool-loop surface: the APP supplies tool definitions and an initial message
24
+ // list; the port drives the model↔tool alternation and RELAYS each tool-call request to the
25
+ // app's `execute` callback. The port NEVER executes tools itself — it only carries the model's
26
+ // tool_use request out and the app's tool_result back in. This keeps the trust boundary sharp:
27
+ // the LLM widens no data access beyond whatever `execute` (an app closure) chooses to expose.
28
+ //
29
+ // TRUST MODEL (read this before adding a tool): tool results are USER CONTENT flowing into the
30
+ // model's context — in real mode a stored note can carry injection text that steers the model.
31
+ // Model output is therefore UNTRUSTED, always: display it, never branch on it, never wire it to a
32
+ // privileged action. A tool's blast radius is exactly its `execute` closure — scope the closure to
33
+ // the caller's session (resolved ids captured at build time, never model-supplied), validate the
34
+ // tool name with exact equality, and ignore model-controlled input unless each field is validated.
35
+ // Adapters additionally refuse to execute a tool_use whose name isn't among the supplied defs.
36
+
37
+ /** A tool the app exposes to the model. `description`/`inputSchema` are MODEL-facing prompt
38
+ * content (like `system`), not user-facing UI copy — so they are plain strings, not next-intl. */
39
+ export interface LlmToolDef {
40
+ name: string
41
+ /** Tells the model WHEN to call the tool (Anthropic tool `description`). */
42
+ description: string
43
+ /** JSON-schema-ish input shape (Anthropic tool `input_schema`). */
44
+ inputSchema: { type: 'object'; properties?: Record<string, unknown>; required?: string[]; [k: string]: unknown }
45
+ }
46
+
47
+ /** One content block in a conversation turn. Mirrors Anthropic's block shapes closely enough to
48
+ * serialize as a fixture, small enough to stay scoped to what this app needs. */
49
+ export type LlmContentBlock =
50
+ | { type: 'text'; text: string }
51
+ | { type: 'tool_use'; id: string; name: string; input: unknown }
52
+ | { type: 'tool_result'; toolUseId: string; content: string }
53
+
54
+ /** One turn in the returned conversation. Recorded fixture turns are always `assistant` (the
55
+ * model's utterances, incl. tool_use); the live `tool_result` turns the adapter interleaves are
56
+ * `user`. */
57
+ export interface LlmTurn {
58
+ role: 'assistant' | 'user'
59
+ content: LlmContentBlock[]
60
+ }
61
+
62
+ export interface LlmToolLoopRequest {
63
+ purpose: string
64
+ model?: LlmModelId
65
+ system?: string
66
+ messages: LlmMessage[]
67
+ tools: LlmToolDef[]
68
+ maxTokens?: number
69
+ /** Upper bound on model↔tool round-trips before the loop gives up (default 6). */
70
+ maxTurns?: number
71
+ /** APP-supplied tool executor. The port relays the model's call and takes back the result
72
+ * STRING; it never runs a tool itself. Throwing here surfaces to the caller. */
73
+ execute: (call: { name: string; input: unknown }) => Promise<string>
74
+ }
75
+
76
+ export interface LlmPort {
77
+ complete(request: LlmRequest): Promise<{ text: string }>
78
+ stream(request: LlmRequest): AsyncIterable<string>
79
+ /**
80
+ * Drive a tool-using conversation to its final text. Returns `text` (the FINAL assistant turn's
81
+ * text) and `turns` — the full conversation: recorded assistant turns (incl. tool_use)
82
+ * interleaved with the live `tool_result` turns produced by `execute`.
83
+ */
84
+ runToolLoop(request: LlmToolLoopRequest): Promise<{ text: string; turns: LlmTurn[] }>
85
+ }
@@ -0,0 +1,132 @@
1
+ export interface StoredObject {
2
+ body: Uint8Array
3
+ contentType: string
4
+ }
5
+
6
+ /** What `head` reports about a stored object: everything but its bytes. */
7
+ export interface StoredObjectInfo {
8
+ /** Size of the body in bytes. */
9
+ size: number
10
+ /** The content type the object was stored with, as `get` reports it. */
11
+ contentType: string
12
+ /**
13
+ * An OPAQUE identifier of this version of the object. Compare two for equality; pass one back UNCHANGED
14
+ * as `copy`'s `ifMatch`; never parse it or assume a format or a length. Heads of one key that give different
15
+ * `etag`s mean its bytes changed in between. The same `etag` means the same BYTES, not that the object was
16
+ * not rewritten: a rewrite with identical bytes and another content type keeps it on the fake, and S3
17
+ * promises nothing about it, so rely on neither. Compare etags only between heads of the SAME
18
+ * key: the port does not promise that a copy has its source's etag (the fake's does). The real adapter returns S3's ETag exactly as S3 sent it (quotes included);
19
+ * the fake returns a quoted SHA-256 of the bytes.
20
+ */
21
+ etag: string
22
+ /** When the object was last written: S3's `Last-Modified`, the fake's file modification time. */
23
+ lastModified: Date
24
+ }
25
+
26
+ /** Options for `StoragePort.copy`. */
27
+ export interface CopyOptions {
28
+ /**
29
+ * Copy only if the source is STILL the version `head` reported: pass `info.etag` unchanged. When it no
30
+ * longer matches, `copy` throws `PreconditionFailedError` and copies nothing. S3 evaluates this as part of
31
+ * the copy (`CopySourceIfMatch`); the fake compares the very bytes it is about to publish. Without it,
32
+ * `copy` copies whatever is at `from` when it runs. It pins the BYTES, and so the size; it does not pin the
33
+ * content type, which neither adapter's etag covers, so a content-type check made from `head` stays advisory
34
+ * (an upload target's `eq Content-Type` condition is what holds the type at upload).
35
+ */
36
+ ifMatch?: string
37
+ }
38
+
39
+ /** Constraints the storage backend must enforce on a browser upload (mirrored on both adapters). */
40
+ export interface UploadConstraints {
41
+ /** Exact content-type the upload must declare (S3: an `eq $Content-Type` policy condition). */
42
+ contentType: string
43
+ /** Hard ceiling on the object size in bytes (S3: a `content-length-range` policy condition). */
44
+ maxBytes: number
45
+ }
46
+
47
+ /**
48
+ * A browser-direct upload target. The browser POSTs `multipart/form-data` to `url` with every entry
49
+ * of `fields` appended first, then the file as the final `file` part — the exact shape S3's presigned
50
+ * POST expects, so the client code is identical whichever adapter minted it.
51
+ */
52
+ export interface UploadTarget {
53
+ url: string
54
+ fields: Record<string, string>
55
+ }
56
+
57
+ export interface StoragePort {
58
+ put(key: string, body: Uint8Array | string, contentType: string): Promise<void>
59
+ get(key: string): Promise<StoredObject | null>
60
+ /** Time-limited URL a browser can GET the object from. */
61
+ getSignedDownloadUrl(key: string, expiresInSeconds?: number): Promise<string>
62
+ /**
63
+ * Mint a target the browser uploads a file to directly (never through the app server). `key` is
64
+ * ALWAYS server-built by the caller (an upload route builds `<prefix>/<tenant>/<uuid>/<name>`);
65
+ * the browser cannot choose it. Real adapter = an S3 presigned POST; fake adapter = a local
66
+ * multipart endpoint that verifies the same constraints. The size ceiling is `constraints.maxBytes`
67
+ * above, which the app owns — only the app knows what it accepts.
68
+ */
69
+ createUploadTarget(key: string, constraints: UploadConstraints): Promise<UploadTarget>
70
+ /**
71
+ * Every stored key that begins with `prefix`, as FULL keys (never relative to the prefix), sorted
72
+ * ascending. `prefix` is a literal string prefix on the key, not a directory boundary — S3's
73
+ * `ListObjectsV2` `Prefix` semantics, which both adapters match: `'a/b'` also returns `'a/bc'`, so
74
+ * pass a trailing `/` to mean "inside this folder". No match is `[]`; `''` lists every key.
75
+ */
76
+ list(prefix: string): Promise<string[]>
77
+ /**
78
+ * Remove objects. Idempotent: a key that does not exist is not an error. Each entry is a FULL key,
79
+ * never a prefix — this method never scans, so to delete everything under a prefix `list` it first.
80
+ * Real adapter batches against S3's 1000-keys-per-request cap; an empty array does nothing. A failed
81
+ * batch throws naming its FIRST failing key only; earlier batches have already been deleted.
82
+ */
83
+ delete(keys: readonly string[]): Promise<void>
84
+ /**
85
+ * Copy the object at `from` to `to`, inside the one store. S3 does it server-side (one `CopyObject`),
86
+ * so the bytes never pass through the app — which is the point: a stage-then-finalize flow that read
87
+ * and re-`put` every file would stream each one through the app's Lambda.
88
+ *
89
+ * Both arguments are FULL keys, never prefixes, and the port inspects neither: tenant scoping is the
90
+ * CALLER's, as for `put` and `get`. Build both keys server-side from the same tenant (for example
91
+ * `uploads/<tenant>/<uuid>/<name>` to `<tenant>/<name>`), never from client input. The port cannot
92
+ * cross a bucket: the source is always the store's own.
93
+ *
94
+ * The copy keeps the source's content type and metadata, leaves the source where it is (follow with
95
+ * `delete` to move), and OVERWRITES an existing `to`, exactly as `put` does. It resolves once `to` is
96
+ * complete: neither adapter ever shows a half-copied `to` (S3 publishes it when the copy finishes; the
97
+ * fake renames it into place).
98
+ *
99
+ * With `options.ifMatch` it also throws `PreconditionFailedError` (`@sssb/kit/ports/errors`) when the source is
100
+ * no longer the version that etag names, and copies nothing; an `ifMatch` that is empty or `*` is refused first of all, with a plain `Error`
101
+ * (HTTP's If-Match gives them meanings an etag never has). The order of the other checks is: same key, missing
102
+ * source, then the precondition; the real adapter leaves the last two to S3, whose order for a missing source
103
+ * with an `ifMatch` is unconfirmed (cutover row `storage-head`).
104
+ *
105
+ * A missing `from` throws `NotFoundError` (`@sssb/kit/ports/errors`), on both adapters (the real one needs `s3:ListBucket`;
106
+ * without it S3 answers a missing key with an access-denied error, which is not mapped). `from === to` throws
107
+ * a plain `Error` on both, whether or not the key exists: a copy onto itself changes nothing, and is nearly always a caller that built
108
+ * its two keys the same way. The real adapter has one limit the fake does not: a single `CopyObject`
109
+ * copies at most 5 GB (AWS's CopyObject reference), and a larger object throws an `Error` saying so.
110
+ * Multipart copy is not implemented. `UploadConstraints.maxBytes` is the app's own, so an app that
111
+ * accepts uploads above that size cannot copy them with this method: keep `maxBytes` below it.
112
+ */
113
+ copy(from: string, to: string, options?: CopyOptions): Promise<void>
114
+ /**
115
+ * An object's size, content type, ETag and last-modified time WITHOUT its bytes (S3 `HeadObject`; the
116
+ * fake stats the file, reads its sidecar and hashes the body). `null` when nothing is stored at `key`, as
117
+ * for `get`: a read has a natural "nothing" to return, so a caller asks `if (!info)`. (`copy` throws
118
+ * instead, because it has nothing to return.) A bookkeeping name is `null` as it is for `get`; so is a
119
+ * directory, where the fake's `get` throws on one (it answers ENOENT for the missing sidecar).
120
+ *
121
+ * A check made from this is ADVISORY: the object can change between `head` and whatever the caller does
122
+ * next. To act on exactly the version that was checked, pass `info.etag` as `copy`'s `ifMatch`.
123
+ *
124
+ * Real adapter: needs `s3:GetObject`, and `s3:ListBucket` for a missing key to be a 404; without it S3
125
+ * answers 403, which is not mapped and throws (AWS's HeadObject reference). A HEAD response has no body, so
126
+ * S3 gives only a generic status ("It's not possible to retrieve the exact exception"): a missing BUCKET, which S3 also
127
+ * reports as a 404 (not stated on the HeadObject page; the cutover row confirms it), could not be told
128
+ * apart, and reads as `null` here as a missing key does. A response without a size, ETag or
129
+ * last-modified time throws rather than reporting a size of 0.
130
+ */
131
+ head(key: string): Promise<StoredObjectInfo | null>
132
+ }
@@ -0,0 +1,129 @@
1
+ import type { Kysely } from 'kysely'
2
+ import type { AgreementGating, AgreementKind } from '../core/agreements'
3
+ import type { Locale } from '../core/locale'
4
+ import type { Role } from '../core/roles'
5
+ import type { ScheduleSpec } from '../core/schedules'
6
+ import type { DB } from '../db/schema'
7
+ import type { EmailPort } from '../ports/email'
8
+ import type { StoragePort } from '../ports/storage'
9
+
10
+ /**
11
+ * The SEED CONTRACT — the shapes the framework's seeder (db/seed.ts), fake auth adapter and per-tenant
12
+ * theming read out of an app's seed package. ADR-0012 puts these types in the framework,
13
+ * so `packages/seed` (and any adopter's replacement for it) is a DATA package that conforms to a
14
+ * framework contract rather than the accidental source of truth for it.
15
+ *
16
+ * Data only: no runtime values here, and the seed package that implements these stays import-free at
17
+ * runtime (it imports types, which erase).
18
+ *
19
+ * The agreement/schedule shapes are ALIASES of the canonical core types rather than copies — the seed
20
+ * package used to inline them to stay import-free, which meant a core change could silently drift from
21
+ * the seed data. Type-only imports keep it import-free at runtime AND keep the shapes welded together.
22
+ */
23
+
24
+ export interface SeedTenant {
25
+ slug: string
26
+ name: string
27
+ /** Mantine primary color name; the app's getTenantTheme() maps tokens to a real theme. */
28
+ themePrimaryColor: string
29
+ /** Mantine radius token — a second, shape-level signal that per-tenant theming is real. */
30
+ themeRadius: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
31
+ }
32
+
33
+ /** Alias of the canonical core union (same weld as the agreement/schedule shapes above). */
34
+ export type PersonRole = Role
35
+
36
+ /**
37
+ * An organization (product copy: "team") groups users WITHIN one tenant site — the Clerk
38
+ * Organization analog. Slugs are globally unique for now: while the clerk-dev instance is shared
39
+ * across tenants, every org lands in one Clerk org namespace (see cutover checklist).
40
+ */
41
+ export interface SeedOrg {
42
+ slug: string
43
+ name: string
44
+ /** The tenant (site) this org belongs to. Orgs never span tenants. */
45
+ tenantSlug: string
46
+ }
47
+
48
+ /** A person's role within one org — role is per-membership, mirroring Clerk org-membership roles. */
49
+ export interface SeedMembership {
50
+ orgSlug: string
51
+ role: PersonRole
52
+ }
53
+
54
+ export interface SeedPerson {
55
+ id: string
56
+ name: string
57
+ email: string
58
+ locale: Locale
59
+ /** Home site (ambient) — a person's tenant never changes and is never user-switchable. */
60
+ tenantSlug: string
61
+ /** Orgs this person belongs to, each with its own role. Always at least one. */
62
+ memberships: SeedMembership[]
63
+ /** Restricted members exercise the limited-access seam (reduced feature surface). */
64
+ restricted: boolean
65
+ }
66
+
67
+ /** Agreement kind / gating, from the canonical core vocabulary (core/agreements.ts). */
68
+ export type SeedAgreementKind = AgreementKind
69
+ export type SeedAgreementGating = AgreementGating
70
+
71
+ /**
72
+ * A seed agreement — TENANT-scoped world content (like note bodies, not UI copy). `bodyMd`
73
+ * is markdown, rendered simply. `preAcceptedByAllInTenant` encodes the seed-shape decision that keeps
74
+ * every existing e2e green: an agreement can arrive already accepted by everyone in its tenant (so
75
+ * nothing is blocked until a Simulator version bump re-arms the gate) or accepted by nobody (so it
76
+ * demonstrates the advisory banner). See the decision log.
77
+ */
78
+ export interface SeedAgreement {
79
+ /** Tenant (site) this agreement governs — agreements are tenant-level, not per-team. */
80
+ tenantSlug: string
81
+ kind: SeedAgreementKind
82
+ version: number
83
+ title: string
84
+ bodyMd: string
85
+ gating: SeedAgreementGating
86
+ preAcceptedByAllInTenant: boolean
87
+ }
88
+
89
+ /** A recurring schedule spec, from the canonical core vocabulary (core/schedules.ts). */
90
+ export type SeedScheduleSpec = ScheduleSpec
91
+
92
+ /**
93
+ * A seeded recurring job schedule — WHICH org gets WHICH schedule is app/demo content, so it
94
+ * lives in the seed package rather than hard-coded in the framework seeder (db/seed.ts), which only
95
+ * takes what the data says. `kind` names a job kind the schedule fires; `createdBy` is a marker, not a
96
+ * real user id.
97
+ */
98
+ export interface SeedJobSchedule {
99
+ tenantSlug: string
100
+ orgSlug: string
101
+ kind: string
102
+ spec: SeedScheduleSpec
103
+ createdBy: string
104
+ }
105
+
106
+ /**
107
+ * What an app's product-row seeder is handed, once the framework's own tables (tenants, orgs,
108
+ * agreements, schedules) exist. The db handle is the PRIVILEGED migration-user connection the framework
109
+ * seeder itself uses, not a tenant-scoped one — seeding predates any session, so it writes rows for
110
+ * every tenant and RLS is not in tour. `storage` and `email` are here because a believable starting
111
+ * world is not only rows: an attachment needs its bytes on disk or its download link is dead, and a
112
+ * demo that opens with an empty outbox has to be talked into looking used.
113
+ */
114
+ export interface AppSeedContext {
115
+ db: Kysely<DB>
116
+ storage: StoragePort
117
+ email: EmailPort
118
+ }
119
+
120
+ /**
121
+ * The OPTIONAL app half of the seeder (ADR-0012). An app with product rows exports `appSeedRows` from
122
+ * `@sssb/app-config/seed`; the framework seeder looks for it and calls it last. An app with nothing to seed
123
+ * omits the export entirely — the registration is absent rather than empty, because there is no shape
124
+ * for "no rows" that is more honest than not having the function.
125
+ *
126
+ * The implementation owns its own idempotence: the seeder runs on EVERY boot and after every Simulator
127
+ * world reset, so it must decide for itself whether this world has already been furnished.
128
+ */
129
+ export type AppSeedRows = (ctx: AppSeedContext) => Promise<void>
@@ -0,0 +1,45 @@
1
+ import type { DbPort } from '../ports/db'
2
+ import type { LlmToolDef } from '../ports/llm'
3
+
4
+ /**
5
+ * The assistant tool-loop contract (framework — ADR-0012). The app registers its assistant purpose,
6
+ * system prompt, and tools (each a MODEL-facing definition + an app-side `execute`) via
7
+ * src/app-config/assistant.ts; the route drives a generic loop over them. This keeps the assistant a
8
+ * registration surface: an adopter swaps the seam's assistantConfig, not the route.
9
+ */
10
+
11
+ /** The per-request context an assistant tool's `execute` closes over — scoped to THIS caller's session. */
12
+ export interface AssistantToolCtx {
13
+ db: DbPort
14
+ tenantId: string
15
+ orgId: string
16
+ }
17
+
18
+ /** One registered tool: its MODEL-facing definition + the app-side executor the loop relays calls to. */
19
+ interface AssistantTool {
20
+ def: LlmToolDef
21
+ execute: (input: unknown, ctx: AssistantToolCtx) => Promise<string>
22
+ }
23
+
24
+ /** The app's assistant registration. `purpose`/`system` + the tool defs form the fixture-hashed request. */
25
+ export interface AssistantConfig {
26
+ purpose: string
27
+ system: string
28
+ tools: AssistantTool[]
29
+ }
30
+
31
+ /**
32
+ * Build the `execute` callback the llm port's runToolLoop relays each model tool-call to: dispatch by
33
+ * exact tool name to the registered tool, scoped to `ctx`. An unknown tool name returns an error string
34
+ * (never throws) — the model's request is untrusted. Shared by the route and the fixture recorder.
35
+ */
36
+ export function assistantExecutor(
37
+ config: AssistantConfig,
38
+ ctx: AssistantToolCtx,
39
+ ): (call: { name: string; input: unknown }) => Promise<string> {
40
+ return async (call) => {
41
+ const tool = config.tools.find((t) => t.def.name === call.name)
42
+ if (!tool) return `unknown tool: ${call.name}`
43
+ return tool.execute(call.input, ctx)
44
+ }
45
+ }
@@ -0,0 +1,57 @@
1
+ import { after } from 'next/server'
2
+ import { analytics, isSimulated } from '../adapters/index'
3
+
4
+ /**
5
+ * Deferred-work seam — a thin, systematized convention over Next's `after()` so slices don't
6
+ * each hand-roll "run this side effect once the response is out".
7
+ * The canonical use is notification email: send it AFTER the response is flushed, so a slow mail
8
+ * provider never adds latency to the user's request. When work outgrows the request lifecycle, this is
9
+ * the on-ramp to the jobs port — the same call site becomes `jobs.start(...)`.
10
+ *
11
+ * Two behaviours, one signature:
12
+ *
13
+ * - **Real mode**: `after(work)` — the work runs in a post-response continuation.
14
+ * A throw inside it is caught and reported via analytics (`deferred_work_failed`), never surfaced —
15
+ * the response has already been sent, so there is nothing to fail.
16
+ *
17
+ * - **Simulated mode** (dev, e2e, demo): run the work INLINE (awaited) instead — deliberately, for
18
+ * determinism, in the same spirit as every other fake here. A hermetic e2e that sends an invite and polls
19
+ * the fake mailbox must find the mail without racing a post-response microtask; running inline keeps
20
+ * that ordering exactly as it was before this seam existed. It ALSO captures a `deferred_work` event
21
+ * first, so the deferred work is VISIBLE in the Simulator Events tab (proof the seam fired at all),
22
+ * and captures `deferred_work_failed` on error — again without ever throwing into the caller.
23
+ *
24
+ * Errors are always swallowed after being recorded: a failing side effect must never crash the
25
+ * response (real) or the calling handler (fake).
26
+ */
27
+ export async function deferAfterResponse(label: string, work: () => Promise<void>): Promise<void> {
28
+ if (isSimulated) {
29
+ // Visible-in-Simulator marker first, then run inline so the world is deterministic.
30
+ await analytics.capture('deferred_work', { label })
31
+ try {
32
+ await work()
33
+ } catch (error) {
34
+ await captureFailure(label, error)
35
+ }
36
+ return
37
+ }
38
+ // Real mode: schedule after the response is flushed. A rejection here can't propagate to a caller
39
+ // that has already returned, so record it and move on.
40
+ after(async () => {
41
+ try {
42
+ await work()
43
+ } catch (error) {
44
+ await captureFailure(label, error)
45
+ }
46
+ })
47
+ }
48
+
49
+ async function captureFailure(label: string, error: unknown): Promise<void> {
50
+ const message = error instanceof Error ? error.message : String(error)
51
+ // In a deployment the analytics port may be the simulated one (no POSTHOG_KEY), which writes only to the server's
52
+ // local disk, so the log is the record that stays: console.warn reaches CloudWatch in Lambda. A port the
53
+ // deployment switched off (`<SWITCH>=none`) shows up here.
54
+ if (!isSimulated) console.warn(`SSSB deferred work "${label}" failed: ${message}`)
55
+ // Best-effort telemetry — if capture itself fails there is nothing left to do but not crash.
56
+ await analytics.capture('deferred_work_failed', { label, message }).catch(() => {})
57
+ }
@@ -0,0 +1,85 @@
1
+ import { appPresetOperationHandlers } from '@sssb/app-config/preset-operations'
2
+ import { presets } from '@sssb/app-config/presets'
3
+ import { devSignIn } from '../adapters/fake/auth'
4
+ import { resetWorldThen } from '../adapters/fake/simulator-admin'
5
+ import { expandPreset, type PresetOperation } from '../core/presets'
6
+ import { NotFoundError } from '../ports/errors'
7
+ import { frameworkPresetOperationHandlers, type ServerPresetOperationHandler } from './preset-operations'
8
+
9
+ /**
10
+ * The SERVER host's replay of a demo preset (@sssb/kit/core/presets.ts): reset the world to the seed, then
11
+ * perform each operation through its kind's server half — SSSB's (./preset-operations.ts) or the app's
12
+ * (`@sssb/app-config/preset-operations`) — and finally sign the RESTORING browser in as the preset's
13
+ * viewpoint. The static twin replays the same list through its in-memory world (@sssb/kit/demo-static/world.ts).
14
+ *
15
+ * Simulated mode only: every caller is a `/api/simulator/*` route behind its `isSimulated` 404. There
16
+ * is no session to authorize against — a preset is a simulated-world operation, like compose-inbound —
17
+ * so the authorization question is answered at BUILD time instead: SSSB's seam-conformance suite holds
18
+ * every registered preset to the rules the product enforces (`presetProblems`). An operation the
19
+ * world cannot perform therefore throws here rather than being skipped, because reaching one means the
20
+ * conformance gate was bypassed.
21
+ *
22
+ * The viewpoint is the restorer's alone (cookies on THIS response); other browsers watching the same
23
+ * world keep theirs. See `DemoPreset.viewpoint`.
24
+ */
25
+ export async function applyDemoPreset(id: string, options: { baseUrl: string }): Promise<{ signedIn: boolean }> {
26
+ // The `extends` chain flattened (@sssb/kit/core/presets.ts `expandPreset`): null is an unknown id, and also
27
+ // a preset whose chain names an unknown base or loops — both of which the conformance gate rejects.
28
+ const preset = expandPreset(id, presets)
29
+ if (!preset) throw new NotFoundError(`unknown preset: ${id}`)
30
+
31
+ // The reset and the whole script run as ONE turn of the world's queue, so a second load (or a reset,
32
+ // save or restore) arriving meanwhile waits for this one instead of interleaving with it.
33
+ return resetWorldThen(async () => {
34
+ // Named results live for one replay: a name is the id a step created in THIS world.
35
+ const refs = new Map<string, string>()
36
+ for (const operation of preset.operations) {
37
+ await performPresetOperation(operation, { baseUrl: options.baseUrl, refs })
38
+ }
39
+
40
+ if (preset.viewpoint === undefined) return { signedIn: false }
41
+ await devSignIn(preset.viewpoint)
42
+ return { signedIn: true }
43
+ })
44
+ }
45
+
46
+ /**
47
+ * Every kind's server half: SSSB's, then the app's, keyed by kind — so an app entry with SSSB's kind name
48
+ * REPLACES SSSB's (the same composition as the definitions, `composePresetOperations`). Exported for the
49
+ * seam-conformance suite, which holds it to the definitions both ways.
50
+ */
51
+ export const presetOperationHandlers: Readonly<Record<string, ServerPresetOperationHandler>> = {
52
+ ...frameworkPresetOperationHandlers,
53
+ ...appPresetOperationHandlers,
54
+ }
55
+
56
+ /**
57
+ * The ONE dispatcher: run an operation's kind's half with the operation's arguments (everything but `op`
58
+ * and `as`), then bind its result to `as`. An unregistered kind, a name no earlier step bound, and an `as`
59
+ * on a step that created nothing are all NotFoundErrors — each is a preset the conformance gate refuses.
60
+ */
61
+ async function performPresetOperation(
62
+ operation: PresetOperation,
63
+ ctx: { baseUrl: string; refs: Map<string, string> },
64
+ ): Promise<void> {
65
+ const { op, as, ...args } = operation
66
+ // An own-property lookup, so a kind named like an Object.prototype member is just unknown.
67
+ const handler = Object.hasOwn(presetOperationHandlers, op) ? presetOperationHandlers[op] : undefined
68
+ if (!handler) throw new NotFoundError(`unknown preset operation: ${op}`)
69
+
70
+ const result = await handler(args, {
71
+ baseUrl: ctx.baseUrl,
72
+ refs: {
73
+ resolve(name) {
74
+ const bound = ctx.refs.get(name)
75
+ if (bound === undefined) throw new NotFoundError(`no earlier operation is named "${name}"`)
76
+ return bound
77
+ },
78
+ },
79
+ })
80
+
81
+ if (as === undefined) return
82
+ const ref = result ? result.ref : undefined
83
+ if (ref === undefined) throw new NotFoundError(`operation "${op}" created nothing to name "${as}"`)
84
+ ctx.refs.set(as, ref)
85
+ }