@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,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,53 @@
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
+ // Best-effort telemetry — if capture itself fails there is nothing left to do but not crash.
52
+ await analytics.capture('deferred_work_failed', { label, message }).catch(() => {})
53
+ }
@@ -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
+ }
@@ -0,0 +1,92 @@
1
+ import { getTranslations } from 'next-intl/server'
2
+ import { analytics, auth, db, email } from '../adapters/index'
3
+ import type { Locale } from '../core/locale'
4
+ import type { Role } from '../core/roles'
5
+ import { recordAuditEvent } from '../db/audit'
6
+ import { sendTemplate } from '../email/send'
7
+ import { InviteEmail } from '../email/templates/invite-email'
8
+ import type { Membership } from '../ports/auth'
9
+ import { deferAfterResponse } from './defer'
10
+ import { notifyAdmins } from './notify'
11
+ import { makeNotifyDeps } from './notify-deps'
12
+
13
+ /**
14
+ * Inviting someone to a team, AFTER the caller has decided it may happen: mint the invite, audit it,
15
+ * mail the invitee their accept link, record the analytics event, and tell the team's other admins.
16
+ *
17
+ * Authorization, validation and the duplicate check stay with the CALLER, because they differ by
18
+ * caller: the org route authorizes the signed-in session and answers 400/409, while a demo preset's
19
+ * replay (./demo-presets.ts) has no session at all and was held to the same rules at build time
20
+ * (@sssb/kit/core/presets.ts `presetProblems`). What happens once an invite is allowed does not differ, so
21
+ * it lives here once — a preset that re-implemented it would be a second invite flow, free to drift.
22
+ */
23
+ export async function sendOrgInvite(input: {
24
+ /** Who is inviting: named in the email, excluded from the admins' notification, and the audit actor. */
25
+ inviter: { id: string; name: string; locale: Locale }
26
+ tenantSlug: string
27
+ tenantId: string
28
+ orgId: string
29
+ orgSlug: string
30
+ orgName: string
31
+ email: string
32
+ role: Role
33
+ /** The org's current members (the caller already fetched them for its duplicate check). */
34
+ members: Membership[]
35
+ /** Any absolute URL on this host; the accept link is built against its origin. */
36
+ baseUrl: string
37
+ }): Promise<Membership> {
38
+ const membership = await auth.createInvite({ email: input.email, role: input.role, orgSlug: input.orgSlug })
39
+
40
+ // Audit trail: the invite is the audited mutation — a Membership was created.
41
+ await recordAuditEvent(db, {
42
+ tenantId: input.tenantId,
43
+ orgId: input.orgId,
44
+ actorUserId: input.inviter.id,
45
+ action: 'membership.invited',
46
+ subjectType: 'Membership',
47
+ subjectId: membership.id,
48
+ })
49
+
50
+ const acceptUrl = new URL(
51
+ `/${input.inviter.locale}/accept-invite?invite=${membership.id}`,
52
+ input.baseUrl,
53
+ ).toString()
54
+ // The invitee has no account (and so no locale) yet — the inviter's locale is the best available
55
+ // signal for the email copy (ADR-0008).
56
+ const t = await getTranslations({ locale: input.inviter.locale, namespace: 'email' })
57
+ // Deferred: the notification email is a post-response side effect — a slow mail provider must never
58
+ // add latency to the invite request. Simulated mode runs it inline (deterministic + visible in
59
+ // Simulator events); real mode sends it via Next's after().
60
+ await deferAfterResponse('invite-email', () =>
61
+ sendTemplate(email, {
62
+ to: input.email,
63
+ subject: t('inviteSubject', { org: input.orgName }),
64
+ template: InviteEmail({
65
+ labels: {
66
+ preview: t('invitePreview', { org: input.orgName }),
67
+ heading: t('inviteHeading', { org: input.orgName }),
68
+ body: t('inviteBody', { inviter: input.inviter.name, org: input.orgName, role: input.role }),
69
+ button: t('inviteButton'),
70
+ linkFallback: t('inviteLinkFallback'),
71
+ },
72
+ acceptUrl,
73
+ }),
74
+ }),
75
+ )
76
+ await analytics.capture('org_invite_sent', { tenant: input.tenantSlug, org: input.orgSlug, role: input.role })
77
+
78
+ // Notification fan-out: tell the inviting team's OTHER admins that an invite went out. The invitee
79
+ // has no account yet, so they can't hold an in-app row — the admins are the demoable recipients
80
+ // (see the decision log). The inviter is excluded so they aren't notified of their own action.
81
+ // After-commit, like the audit.
82
+ await notifyAdmins(await makeNotifyDeps(), {
83
+ members: input.members,
84
+ tenantId: input.tenantId,
85
+ orgId: input.orgId,
86
+ kind: 'org.invited',
87
+ payload: { email: input.email, role: input.role, orgName: input.orgName },
88
+ excludeUserId: input.inviter.id,
89
+ })
90
+
91
+ return membership
92
+ }
@@ -0,0 +1,15 @@
1
+ import { db, email, isSimulated } from '../adapters/index'
2
+ import type { NotifyDeps } from './notify'
3
+ import { sendSms } from './sms'
4
+
5
+ /**
6
+ * Build the notification fan-out's injected dependencies for a request path (routes call this; the fake
7
+ * job executor assembles its own deps from the fake adapters directly, to stay off the @/adapters cycle).
8
+ * In simulated mode it wires the person-locale resolver so demo emails/SMS render in the recipient's
9
+ * language; in real mode `resolveLocale` is omitted and copy falls back to the app default (the auth
10
+ * port exposes no per-user locale — a noted simplification, see the decision log).
11
+ */
12
+ export async function makeNotifyDeps(): Promise<NotifyDeps> {
13
+ const resolveLocale = isSimulated ? (await import('../adapters/fake/auth')).personLocale : undefined
14
+ return { db, email, sms: sendSms, resolveLocale }
15
+ }