@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,61 @@
1
+ /**
2
+ * Static-demo twin of the fake llm's runToolLoop (../adapters/fake/llm.ts, ADR-0006/-0009). That
3
+ * adapter reads its fixture off disk with node:fs, which no `file://` bundle can do — so the twin
4
+ * takes the already-imported fixture as data and replays it in the browser.
5
+ *
6
+ * The committed fixture holds the recorded MODEL turns; replay drives them one at a time and runs the
7
+ * caller's `execute` LIVE for each tool_use, so the tool RESULT comes from the in-memory demo world —
8
+ * canned utterances, live effects, exactly the replay-honesty split the server makes. Which fixture
9
+ * (and which tools) is APP vocabulary; the replay mechanism is not, so only the mechanism lives here.
10
+ */
11
+
12
+ /** One content block of a recorded assistant turn — `text` for an utterance, `tool_use` for a call. */
13
+ interface FixtureBlock {
14
+ type: string
15
+ text?: string
16
+ name?: string
17
+ /** A recorded tool_use's arguments. Relayed to `execute` so a tool that TAKES input behaves the
18
+ * same in the browser twin as it does on the server. */
19
+ input?: unknown
20
+ }
21
+
22
+ /** One recorded fixture entry. `request: null` marks the purpose's default/fallback answer. */
23
+ interface FixtureEntry {
24
+ request: { messages?: { role: string; content: string }[] } | null
25
+ response?: string | null
26
+ conversation?: { role: string; content: FixtureBlock[] }[]
27
+ }
28
+
29
+ /** The shape of a committed fixtures/llm/*.json file, as far as browser replay cares. */
30
+ export interface AssistantFixture {
31
+ entries: FixtureEntry[]
32
+ }
33
+
34
+ /**
35
+ * Replay `question` against `fixture`, running `execute(toolName, input)` for every recorded tool_use before
36
+ * returning the turn's text. Falls back to the fixture's default answer when the question matches no
37
+ * recorded conversation — the same fallback the fake adapter makes, so an unrecorded question is
38
+ * answered rather than thrown at a demo audience.
39
+ */
40
+ export async function replayAssistant(
41
+ fixture: AssistantFixture,
42
+ question: string,
43
+ execute: (toolName: string, input: unknown) => Promise<string>,
44
+ ): Promise<string> {
45
+ const fallback = fixture.entries.find((e) => e.request === null)?.response ?? 'fixture missing'
46
+ const conversation = fixture.entries.find(
47
+ (e) => e.conversation && e.request?.messages?.[0]?.content === question,
48
+ )?.conversation
49
+ if (!conversation) return fallback
50
+ for (const turn of conversation) {
51
+ const toolUses = turn.content.filter((b) => b.type === 'tool_use')
52
+ for (const call of toolUses) await execute(call.name ?? '', call.input)
53
+ if (toolUses.length === 0) {
54
+ return turn.content
55
+ .filter((b) => b.type === 'text')
56
+ .map((b) => b.text ?? '')
57
+ .join('')
58
+ }
59
+ }
60
+ return fallback
61
+ }
@@ -0,0 +1,282 @@
1
+ import type { SeedOrg, SeedPerson, SeedTenant, PersonRole } from '@sssb/app-config/seed'
2
+ import type { Dispatch, SetStateAction } from 'react'
3
+ import type { ActorLog, BuilderDriver, ServiceDriver } from '../components/simulator/actor-runtime'
4
+ import type { SimulatorNotice } from '../components/simulator/simulator-panel'
5
+ import type { Person } from '../components/simulator/people-app'
6
+ import type { AnalyticsEvent, AuditEntry } from '../components/simulator/events-app'
7
+ import type { InboundComposeInput, InboundEmailRow } from '../components/simulator/inbound-app'
8
+ import type { ScheduleRowLike } from '../components/simulator/jobs-app'
9
+ import type { MailItem } from '../components/simulator/mail-app'
10
+ import type { SmsMessageRow } from '../components/simulator/messages-app'
11
+ import type { FeatureFlag } from '../components/simulator/snapshots-app'
12
+ import type { PendingAgreement } from '../core/agreements'
13
+ import type {
14
+ NotificationChannel,
15
+ NotificationKind,
16
+ NotificationPayload,
17
+ NotificationPrefRow,
18
+ } from '../core/notifications'
19
+ import type { WebhookEventKind, WebhookEventPayload } from '../core/webhook-events'
20
+ import type { DemoServiceScope } from './actor-drivers'
21
+ import type {
22
+ DemoAcceptance,
23
+ DemoAgreement,
24
+ DemoDelivery,
25
+ DemoEndpoint,
26
+ DemoInvite,
27
+ DemoJob,
28
+ DemoNotification,
29
+ } from './rows'
30
+
31
+ /**
32
+ * The CONTRACT between the framework's simulated world (./world.ts) and an app's static-demo
33
+ * composition root — what the root must supply, and what it gets back. Kept as its own module for the
34
+ * same reason ../seed/contracts.ts is: it is the surface a second app codes against, and it should be
35
+ * readable end to end without scrolling through an implementation.
36
+ */
37
+
38
+ // ── What the composition root supplies ────────────────────────────────────────────────────────────
39
+
40
+ /**
41
+ * What a demo inbound handler is given — the in-memory twin of InboundContext
42
+ * (../inbound-email/handlers.ts). `members` stands in for the handler's `auth.listMembers(orgSlug)`
43
+ * call, and `recordAudit` for its `recordAuditEvent(db, …)`: intake owns org resolution here (the twin
44
+ * addresses the world by slug), so a handler that writes its own domain audit event hands it back
45
+ * rather than resolving a tenant itself.
46
+ */
47
+ export interface DemoInboundContext {
48
+ org: SeedOrg
49
+ members: SeedPerson[]
50
+ /** Normalized sender addr-spec (lowercased, display name stripped). */
51
+ fromEmail: string
52
+ subject: string
53
+ /** Normalized plain-text body (quoted reply chain stripped — ../core/inbound-email.ts). */
54
+ bodyText: string
55
+ recordAudit: (entry: { action: string; subjectType: string; subjectId: string; actorUserId: string }) => void
56
+ }
57
+
58
+ /** Same two outcomes the real handler contract has: it produced its effect, or it declined with a
59
+ * reason. A throw is the third, as in the real contract: the twin's intake files the message `failed`.
60
+ * Like
61
+ * the real contract, 'handled' may name the row it created (`subjectId`), which is what a demo preset's
62
+ * `inbound` step binds to its `as` name. */
63
+ export type DemoInboundResult =
64
+ { status: 'handled'; actorUserId: string; subjectId?: string } | { status: 'unmatched'; reason: string }
65
+
66
+ export type DemoInboundHandler = (ctx: DemoInboundContext) => DemoInboundResult
67
+
68
+ /**
69
+ * What a STATIC half of a demo-preset operation kind is given (@sssb/kit/core/presets.ts) — the twin of the
70
+ * server half's context, plus the handful of world operations an app twin needs to act as an EXPLICIT
71
+ * actor in an EXPLICIT team. Never "whoever is signed in": a preset replays before anyone is, and the
72
+ * world's ambient helpers (`logAudit`, the signed-in person) would attribute the step to the wrong desk.
73
+ */
74
+ export interface StaticPresetOperationContext {
75
+ /** Named results bound so far in this replay. `resolve` throws for a name no earlier step bound, and
76
+ * the replay then settles false — the twin of the server half's throw. */
77
+ refs: { resolve(name: string): string }
78
+ /** A person by id: the seed plus everyone who has accepted an invite in this world. */
79
+ findPerson: (personId: string) => SeedPerson | undefined
80
+ /** Append an audit row attributed to `entry.actorUserId`, in the named tenant and team — the twin of
81
+ * `recordAuditEvent` with the ids the server half resolved. */
82
+ recordAudit: (
83
+ entry: { action: string; subjectType: string; subjectId: string | null; actorUserId: string },
84
+ scope: { tenantSlug: string; orgSlug: string },
85
+ ) => void
86
+ /** The world's single-recipient notification twin (`DemoWorld.notifyMemberOf`). */
87
+ notifyMemberOf: DemoWorld['notifyMemberOf']
88
+ /** SSSB's own static halves, so an app entry that REPLACES a framework kind can wrap SSSB's twin
89
+ * rather than re-implement world state the context does not expose. */
90
+ framework: Readonly<Record<string, StaticPresetOperationHandler>>
91
+ }
92
+
93
+ /**
94
+ * One operation kind's STATIC half: perform the step in the in-memory world, answering `{ ref }` with the
95
+ * id of what it created (when it created something, so `as` can name it) or `false` when this world
96
+ * cannot perform it — which abandons the replay and settles it false, like the server half's throw.
97
+ * Synchronous: the replay runs one step per commit (@sssb/kit/demo-static/world.ts `applyPreset`).
98
+ *
99
+ * Written as a method type on purpose: method parameters are compared bivariantly, so a half typed for
100
+ * its own kind's arguments fits the `Record<string, StaticPresetOperationHandler>` registry.
101
+ */
102
+ export type StaticPresetOperationHandler<Args = unknown> = {
103
+ method(args: Args, ctx: StaticPresetOperationContext): { ref?: string | undefined } | false
104
+ }['method']
105
+
106
+ export interface DemoWorldOptions {
107
+ /**
108
+ * In-memory twins of the app's inbound-email handlers (@sssb/app-config/inbound-email). They cannot be
109
+ * the real ones — those take a db handle and are async — so the composition root supplies twins
110
+ * keyed by the same handler slugs, and the intake twin looks them up the same way.
111
+ */
112
+ inboundHandlers?: Record<string, DemoInboundHandler>
113
+ /**
114
+ * Twin of digestEmailHandler's app-row query (../jobs/digest-email.ts). The framework's scheduled
115
+ * digest summarizes APP rows, which the world cannot see; the composition root supplies their
116
+ * bodies newest-first, and the counting/snipping stays framework-side, like the real handler.
117
+ */
118
+ digestBodies?: (scope: { tenantSlug: string; orgSlug: string }) => string[]
119
+ /**
120
+ * Messages the world has ALREADY sent when it starts — the twin of an app seeding its opening
121
+ * state through the email port (@sssb/kit/db/seed.ts). Without it, a `file://` demo opens with an empty
122
+ * outbox while `pnpm dev` opens with a badge on the Simulator pill, which is a parity gap rather
123
+ * than a physics one. Restored on reset, like every other seeded thing.
124
+ */
125
+ initialMail?: { to: string; subject: string; html: string }[]
126
+ /** Clears the composition root's OWN rows when the world resets — the twin of wiping `.data/`. */
127
+ onReset?: () => void
128
+ /**
129
+ * Static halves of the app's demo-preset operation kinds, keyed by kind — the twins of its server
130
+ * halves (`@sssb/app-config/preset-operations`), supplied here for the same reason `inboundHandlers` are:
131
+ * they act on the composition root's own rows, and a server half could never be bundled. Composed over
132
+ * SSSB's own halves, so an entry with a framework kind's name replaces SSSB's. A registered kind with
133
+ * no static half makes any preset using it settle false in this world.
134
+ */
135
+ presetOperations?: Record<string, StaticPresetOperationHandler>
136
+ }
137
+
138
+ // ── What the composition root gets back ───────────────────────────────────────────────────────────
139
+
140
+ /**
141
+ * Everything ./shell.tsx renders and every operation an app's composition root can drive. Written out
142
+ * rather than inferred from the hook: this IS the framework's public seam for a second app's static
143
+ * demo, so it is worth reading as a list of what the simulated world can do.
144
+ */
145
+ export interface DemoWorld {
146
+ // Who is looking, and at what.
147
+ route: string
148
+ person: SeedPerson | null
149
+ activeOrgSlug: string
150
+ setActiveOrgSlug: Dispatch<SetStateAction<string>>
151
+ /** The ambient site — follows whoever is signed in, never user-switchable (orgs never span tenants). */
152
+ tenant: SeedTenant
153
+ org: SeedOrg
154
+ /** The signed-in display name, honouring an unsaved profile edit. */
155
+ name: string
156
+ /** Seed people plus everyone who has accepted an invite in this session. */
157
+ allPeople: SeedPerson[]
158
+ orgsForActivePerson: SeedOrg[]
159
+ roleInOrg: (person: SeedPerson, orgSlug: string) => PersonRole
160
+ signIn: (personId: string) => void
161
+ signOut: () => void
162
+ saveProfile: (values: { name: string }) => void
163
+
164
+ // Access gates (the twin of the protected layout's gate evaluation).
165
+ blockingAgreement: PendingAgreement | undefined
166
+ advisoryAgreements: PendingAgreement[]
167
+ acceptAgreement: (agreementId: string) => void
168
+
169
+ // Recording surfaces.
170
+ logEvent: (event: string, properties?: Record<string, unknown>) => void
171
+ logAudit: (action: string, subjectType: string, subjectId: string | null) => void
172
+ pushNotice: (text: string) => void
173
+
174
+ // Emissions an app's own mutations trigger, exactly as the real routes do after they commit.
175
+ enqueueWebhook: (kind: WebhookEventKind, payload: WebhookEventPayload) => void
176
+ notifyAdminsOf: (
177
+ orgSlug: string,
178
+ kind: NotificationKind,
179
+ payload: NotificationPayload,
180
+ excludePersonId?: string,
181
+ ) => void
182
+ /** The single-recipient twin: a kind addressed to a person, not to a team's managers. */
183
+ notifyMemberOf: (
184
+ orgSlug: string,
185
+ recipientPersonId: string,
186
+ kind: NotificationKind,
187
+ payload: NotificationPayload,
188
+ excludePersonId?: string,
189
+ ) => void
190
+
191
+ // Jobs.
192
+ jobs: DemoJob[]
193
+ /** Cross-tenant queued/running/completed counts — the Actors tab's world strip. */
194
+ jobCounts: { queued: number; running: number; completed: number }
195
+ /** Twin of POST /api/jobs + the fake executor: honours the 'jobs-held' knob and, on an instant
196
+ * completion, emits the same terminal webhook + notification the server emits. */
197
+ startJob: (kind: string) => void
198
+ /** Stable factories for the two actor-driver shapes; scope comes from the app's actor registry. */
199
+ serviceDriver: (scope: DemoServiceScope, log: ActorLog) => ServiceDriver
200
+ builderDriver: (serviceManagedOrgSlugs: readonly string[], log: ActorLog) => BuilderDriver
201
+
202
+ // Invites + membership.
203
+ invites: DemoInvite[]
204
+ inviteError: string | null
205
+ sendInvite: (input: { email: string; role: string }) => Promise<void>
206
+ acceptInvite: (inviteId: string, acceptedName: string) => void
207
+
208
+ // Notifications.
209
+ notifications: DemoNotification[]
210
+ notifPrefs: Record<string, NotificationPrefRow[]>
211
+ markNotificationsRead: () => void
212
+ toggleNotifPref: (kind: NotificationKind, channel: NotificationChannel, enabled: boolean) => void
213
+
214
+ // Webhook endpoints (the org screen's card).
215
+ endpoints: DemoEndpoint[]
216
+ newWebhookSecret: string | null
217
+ dismissNewWebhookSecret: () => void
218
+ createEndpoint: (input: { url: string; eventKinds: string[] }) => void
219
+ toggleEndpoint: (id: string, enabled: boolean) => void
220
+ deleteEndpoint: (id: string) => void
221
+
222
+ // Agreements (the profile screen's acceptances list + the Snapshots bump control).
223
+ agreements: DemoAgreement[]
224
+ acceptances: DemoAcceptance[]
225
+ bumpAgreement: (id: string) => void
226
+
227
+ // Everything the Simulator panel renders.
228
+ notices: SimulatorNotice[]
229
+ people: Person[]
230
+ viewpoint: string | null
231
+ personEmail: string | null
232
+ selectPerson: (key: string) => void
233
+ mail: {
234
+ scoped: MailItem[]
235
+ scope: 'person' | 'all'
236
+ setScope: Dispatch<SetStateAction<'person' | 'all'>>
237
+ allCount: number
238
+ seenAt: string | null
239
+ markSeen: () => void
240
+ openLink: (href: string) => void
241
+ copyLink: (href: string) => void
242
+ clear: () => void
243
+ }
244
+ inbound: InboundEmailRow[]
245
+ inboundDomain: string
246
+ /** Every team an inbound address can name — org slugs are globally unique, so the compose form
247
+ * offers the whole world, cross-tenant, exactly like a real MX would accept. */
248
+ inboundOrgs: { slug: string; name: string; tenantSlug: string }[]
249
+ /** The handler slugs the compose form suggests — the registry's own keys, so a newly registered
250
+ * handler shows up without the panel being told about it twice. */
251
+ inboundHandlerSlugs: string[]
252
+ composeInbound: (input: InboundComposeInput) => void
253
+ smsMessages: SmsMessageRow[]
254
+ events: AnalyticsEvent[]
255
+ auditEntries: AuditEntry[]
256
+ schedules: ScheduleRowLike[]
257
+ jobsHeld: boolean
258
+ runPendingJobs: () => void
259
+ clock: {
260
+ offsetMs: number
261
+ worldNowIso: string
262
+ advance: (deltaMs: number) => void
263
+ reset: () => void
264
+ runDue: () => void
265
+ }
266
+ deliveries: DemoDelivery[]
267
+ failingEndpointIds: string[]
268
+ toggleEndpointFailure: (endpointId: string, failing: boolean) => void
269
+ runDueDeliveriesNow: () => void
270
+ /** The actors a demo preset has individually held (`actor.hold`), by actor id; `true` = held. An actor
271
+ * host answers its shell's `held()` with this OR the app's world-wide hold flag — the twin of the
272
+ * server's per-actor `held` route. Cleared on reset. */
273
+ actorHolds: Record<string, boolean>
274
+ featureFlags: FeatureFlag[]
275
+ setFeatureFlag: (flag: string, enabled: boolean) => void
276
+ demoBannerOn: boolean
277
+ resetWorld: () => void
278
+ /** Load a registered demo preset (@sssb/kit/core/presets.ts): reset, replay its operations, sit down as its
279
+ * viewpoint. Resolves true once the world is ready; false when no preset has that id, or when the
280
+ * replay was abandoned (a reset or another load mid-replay) or hit a step it could not perform. */
281
+ applyPreset: (id: string) => Promise<boolean>
282
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Hand-built twins of the react-email templates in ../email/templates. Rendering the REAL templates
3
+ * in-browser was tried and reverted: @react-email/render (react-dom/server) added ~560 kB to the
4
+ * single-file demo, blowing its size budget (see docs/decision-log.md). The STRINGS still come from
5
+ * the same `email` messages namespace, so the copy can't drift even though the markup can — which is
6
+ * why every builder here takes its labels pre-resolved rather than reaching for a translator.
7
+ */
8
+
9
+ /** react-email escapes interpolations for the real template; the hand-built twin must too — the
10
+ * inviter's display name is user-editable and lands in the email body. */
11
+ function escapeHtml(value: string): string {
12
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
13
+ }
14
+
15
+ /** Twin of ../email/templates/invite-email.tsx. */
16
+ export function buildInviteEmailHtml(
17
+ labels: { heading: string; body: string; button: string; linkFallback: string },
18
+ acceptUrl: string,
19
+ ): string {
20
+ const safeUrl = escapeHtml(acceptUrl)
21
+ return (
22
+ `<body style="background-color:#f4f4f5;font-family:sans-serif">` +
23
+ `<div style="background-color:#ffffff;border-radius:8px;margin:40px auto;padding:24px;max-width:480px">` +
24
+ `<h2>${escapeHtml(labels.heading)}</h2><p>${escapeHtml(labels.body)}</p>` +
25
+ `<p style="text-align:center;margin:24px 0"><a href="${safeUrl}" ` +
26
+ `style="background-color:#4c6ef5;color:#ffffff;border-radius:6px;padding:12px 24px;` +
27
+ `text-decoration:none;display:inline-block">${escapeHtml(labels.button)}</a></p>` +
28
+ `<p style="font-size:12px;color:#666666">${escapeHtml(labels.linkFallback)} ${safeUrl}</p>` +
29
+ `</div></body>`
30
+ )
31
+ }
32
+
33
+ /** Twin of ../email/templates/digest-email.tsx. */
34
+ export function buildDigestEmailHtml(
35
+ labels: {
36
+ heading: string
37
+ intro: string
38
+ countLine: string
39
+ recentHeading: string
40
+ emptyLine: string
41
+ footer: string
42
+ },
43
+ recentTitles: string[],
44
+ ): string {
45
+ const list =
46
+ recentTitles.length > 0
47
+ ? `<p style="font-weight:600;margin-bottom:4px">${escapeHtml(labels.recentHeading)}</p>` +
48
+ recentTitles.map((title) => `<p style="margin:2px 0;color:#333333">• ${escapeHtml(title)}</p>`).join('')
49
+ : `<p style="color:#666666">${escapeHtml(labels.emptyLine)}</p>`
50
+ return (
51
+ `<body style="background-color:#f4f4f5;font-family:sans-serif">` +
52
+ `<div style="background-color:#ffffff;border-radius:8px;margin:40px auto;padding:24px;max-width:480px">` +
53
+ `<h2>${escapeHtml(labels.heading)}</h2><p>${escapeHtml(labels.intro)}</p>` +
54
+ `<p style="font-weight:600">${escapeHtml(labels.countLine)}</p>${list}` +
55
+ `<p style="font-size:12px;color:#666666;margin-top:16px">${escapeHtml(labels.footer)}</p>` +
56
+ `</div></body>`
57
+ )
58
+ }
@@ -0,0 +1,24 @@
1
+ import { useEffect, useState } from 'react'
2
+
3
+ /**
4
+ * The static demo's router (ADR-0006). App Router client navigation cannot run from `file://`, so the
5
+ * demo shell is ONE entry point that reads the location hash and picks a screen — which is why every
6
+ * screen in this codebase is router-agnostic in the first place. Deliberately not a router library:
7
+ * the whole contract is "a string, and a way to change it".
8
+ */
9
+
10
+ /** The current route: the hash with its leading `#/` stripped (so the welcome route is `''`). */
11
+ export function useHashRoute(): string {
12
+ const [route, setRoute] = useState(() => window.location.hash.replace(/^#\/?/, ''))
13
+ useEffect(() => {
14
+ const onChange = () => setRoute(window.location.hash.replace(/^#\/?/, ''))
15
+ window.addEventListener('hashchange', onChange)
16
+ return () => window.removeEventListener('hashchange', onChange)
17
+ }, [])
18
+ return route
19
+ }
20
+
21
+ /** Navigate. Setting the hash fires `hashchange`, which every mounted useHashRoute picks up. */
22
+ export function go(route: string) {
23
+ window.location.hash = `#/${route}`
24
+ }
@@ -0,0 +1,105 @@
1
+ import type { AgreementGating, AgreementKind } from '../core/agreements'
2
+ import type { NotificationKind, NotificationPayload } from '../core/notifications'
3
+ import type { WebhookEventPayload } from '../core/webhook-events'
4
+
5
+ /**
6
+ * The in-memory ROW TWINS of the framework's tables, for the `file://` static demo (ADR-0006).
7
+ * There is no server and no database in that host, so every table the framework owns becomes a
8
+ * plain array of these shapes in React state (see ./world.ts). They are deliberately structural
9
+ * mirrors of the real rows rather than the real row types: the real ones are Kysely selectables
10
+ * carrying uuids and timestamps, while the twin's world is addressed by SLUG (there are no ids to
11
+ * resolve against), and pulling the db types in would drag Kysely into a browser bundle.
12
+ *
13
+ * An app's own tables get their own twins in its composition root — only the FRAMEWORK half lives
14
+ * here (ADR-0012).
15
+ */
16
+
17
+ /**
18
+ * Twin of a jobs row (../db/jobs.ts) joined to its world slugs — carries both what a dashboard job
19
+ * card needs and what the Simulator Jobs/Actors tabs need. `orgSlug` is nullable exactly like the
20
+ * real `org_id` (internal jobs have no team).
21
+ */
22
+ export interface DemoJob {
23
+ id: string
24
+ kind: string
25
+ status: string
26
+ tenantSlug: string
27
+ orgSlug: string | null
28
+ createdAt: string
29
+ error: string | null
30
+ timeline: { status: string; at: string; message?: string | null }[]
31
+ }
32
+
33
+ /** Twin of a StoredInvite (../adapters/fake/auth.ts) — with no server an invite is just a row of
34
+ * state until someone accepts it into a dynamic person. */
35
+ export interface DemoInvite {
36
+ id: string
37
+ email: string
38
+ role: string
39
+ orgSlug: string
40
+ }
41
+
42
+ /** Twin of a notifications row. Per-recipient + org scoped: a fan-out delivers one row per admin
43
+ * recipient, and the header bell filters to the signed-in person. `readAt` flips on bell-open
44
+ * (mark-all-read). Notifications are just rows, so this is genuine parity. */
45
+ export interface DemoNotification {
46
+ id: string
47
+ recipientPersonId: string
48
+ orgSlug: string
49
+ kind: NotificationKind
50
+ payload: NotificationPayload
51
+ readAt: string | null
52
+ createdAt: string
53
+ }
54
+
55
+ /** Twin of a webhook_endpoints row. Org-scoped. The secret is a real random string, and the twin
56
+ * REALLY signs deliveries with it via the pure core signer (no server needed — genuine parity). */
57
+ export interface DemoEndpoint {
58
+ id: string
59
+ tenantSlug: string
60
+ orgSlug: string
61
+ url: string
62
+ secret: string
63
+ eventKinds: string[]
64
+ enabled: boolean
65
+ }
66
+
67
+ /** Twin of a webhook_deliveries row. The retry state machine (pending → failed → delivered | dead)
68
+ * runs the SAME core policy (backoffDelayMs / MAX_DELIVERY_ATTEMPTS) the server runs; the signature
69
+ * and body are computed by the pure core signer at delivery time. Times are ms so the world clock
70
+ * (mountedAtMs + offset) drives due-ness exactly like the schedules twin. */
71
+ export interface DemoDelivery {
72
+ id: string
73
+ endpointId: string
74
+ tenantSlug: string
75
+ orgSlug: string
76
+ eventKind: string
77
+ payload: WebhookEventPayload
78
+ status: string
79
+ attemptCount: number
80
+ nextAttemptAtMs: number
81
+ lastError: string | null
82
+ createdAtMs: number
83
+ deliveredAtMs: number | null
84
+ signature: string | null
85
+ body: string | null
86
+ }
87
+
88
+ /** Twin of an agreements row — tenant-scoped world content. */
89
+ export interface DemoAgreement {
90
+ id: string
91
+ tenantSlug: string
92
+ kind: AgreementKind
93
+ version: number
94
+ title: string
95
+ bodyMd: string
96
+ gating: AgreementGating
97
+ }
98
+
99
+ /** Twin of the append-only agreement_acceptances table — who accepted which version, when. */
100
+ export interface DemoAcceptance {
101
+ agreementId: string
102
+ userId: string
103
+ version: number
104
+ acceptedAt: string
105
+ }