@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,1480 @@
1
+ import { presets } from '@sssb/app-config/presets'
2
+ import { flags as appSimulatorFlags } from '@sssb/app-config/simulator'
3
+ import {
4
+ agreements as seedAgreements,
5
+ findOrg,
6
+ jobSchedules as seedJobSchedules,
7
+ findTenant,
8
+ organizations,
9
+ people,
10
+ tenants,
11
+ type PersonRole,
12
+ type SeedPerson,
13
+ } from '@sssb/app-config/seed'
14
+ import { useTranslations } from 'next-intl'
15
+ import { useCallback, useEffect, useRef, useState } from 'react'
16
+ import type { ActorLog } from '../components/simulator/actor-runtime'
17
+ import type { SimulatorNotice } from '../components/simulator/simulator-panel'
18
+ import type { Person } from '../components/simulator/people-app'
19
+ import type { AnalyticsEvent, AuditEntry } from '../components/simulator/events-app'
20
+ import type { InboundComposeInput, InboundEmailRow } from '../components/simulator/inbound-app'
21
+ import type { ScheduleRowLike } from '../components/simulator/jobs-app'
22
+ import type { MailItem } from '../components/simulator/mail-app'
23
+ import type { SmsMessageRow } from '../components/simulator/messages-app'
24
+ import {
25
+ type AcceptanceView,
26
+ type AgreementView,
27
+ agreementFacts,
28
+ computePendingAgreements,
29
+ gatesForAgreements,
30
+ pendingAgreementForGateId,
31
+ } from '../core/agreements'
32
+ import { advisoryGates, evaluateGates, firstBlockingGate } from '../core/gates'
33
+ import {
34
+ DEMO_INBOUND_DOMAIN,
35
+ formatInboundRecipient,
36
+ type InboundReceivedDetail,
37
+ normalizeEmailAddress,
38
+ normalizeInboundBody,
39
+ parseInboundRecipient,
40
+ } from '../core/inbound-email'
41
+ import {
42
+ type NotificationKind,
43
+ type NotificationPayload,
44
+ type NotificationPrefRow,
45
+ FRAMEWORK_NOTIFICATION_NAMESPACE,
46
+ notificationCopy,
47
+ resolveEnabledChannels,
48
+ } from '../core/notifications'
49
+ import {
50
+ expandPreset,
51
+ type ActorHoldArgs,
52
+ type FlagArgs,
53
+ type InboundArgs,
54
+ type InviteArgs,
55
+ type PresetOperation,
56
+ } from '../core/presets'
57
+ import { canManageOrg, isAssignableRole } from '../core/roles'
58
+ import { computeNextRunAt } from '../core/schedules'
59
+ import {
60
+ backoffDelayMs,
61
+ MAX_DELIVERY_ATTEMPTS,
62
+ type WebhookEventKind,
63
+ type WebhookEventPayload,
64
+ } from '../core/webhook-events'
65
+ import { webhookSignatureHeader } from '../core/webhook-signing'
66
+ import { createDemoBuilderDriver, createDemoServiceDriver, type DemoServiceScope } from './actor-drivers'
67
+ import type {
68
+ DemoWorld,
69
+ DemoWorldOptions,
70
+ StaticPresetOperationContext,
71
+ StaticPresetOperationHandler,
72
+ } from './contracts'
73
+ import { buildDigestEmailHtml, buildInviteEmailHtml } from './email-html'
74
+ import { go, useHashRoute } from './hash-route'
75
+ import type {
76
+ DemoAcceptance,
77
+ DemoAgreement,
78
+ DemoDelivery,
79
+ DemoEndpoint,
80
+ DemoInvite,
81
+ DemoJob,
82
+ DemoNotification,
83
+ } from './rows'
84
+ /**
85
+ * THE in-memory framework world for the `file://` static demo (ADR-0006, ADR-0012). Everything the
86
+ * framework owns a table (or a `.data/` file) for on the server exists here as React state, mutated by
87
+ * twins of the same server operations and read by the SAME router-agnostic screens and the SAME pure
88
+ * `core/` logic. No server, no database, no fetch — which is exactly what makes it shareable as one
89
+ * HTML file, and what forces the handful of DEGRADEs marked below.
90
+ *
91
+ * The line this file sits on: everything here is FRAMEWORK — auth/invites/people, mail, inbound mail,
92
+ * notifications and prefs, jobs and schedules, the world clock, webhooks, agreements, audit, analytics,
93
+ * feature flags, the people/viewpoint/continuity model. An app's OWN tables stay in its composition root
94
+ * (src/demo-static/app.tsx), which calls this hook, adds its rows, and renders ./shell.tsx. Where the
95
+ * framework genuinely needs app vocabulary it comes through the ADR-0012 seam (`@sssb/app-config/*`) or
96
+ * through DemoWorldOptions — never from `@/*`, which the fence bans outright.
97
+ */
98
+
99
+ /** How long a Simulator notice stays up. */
100
+ const NOTICE_MS = 6_000
101
+
102
+ /** Fixed historical instant for seeded pre-acceptances (render-pure; shown only as a date). */
103
+ const SEED_ACCEPTED_AT = '2026-01-01T00:00:00.000Z'
104
+
105
+ /** The seeded weekly digest schedule (twin of ../db/seed.ts): research team, Monday 13:00 UTC. */
106
+
107
+ /** How many recent rows the digest lists, and the snippet length used as each row's "title" —
108
+ * the same two constants ../jobs/digest-email.ts uses. */
109
+ const DIGEST_RECENT_LIMIT = 5
110
+ const DIGEST_SNIPPET_LENGTH = 60
111
+
112
+ /** Attribution for intake events no handler claimed (twin of ../inbound-email/intake.ts). */
113
+ const INBOUND_SYSTEM_ACTOR = 'system:inbound-email'
114
+
115
+ /**
116
+ * The Snapshots knobs, off at world start — the twin of KNOWN_FLAGS in ../adapters/fake/analytics.ts, and
117
+ * composed the same way: the framework's own two, plus whatever the app registered on the seam. An app
118
+ * flag that only existed server-side would be a knob the `file://` demo could not reach.
119
+ */
120
+ const INITIAL_FLAGS: Record<string, boolean> = {
121
+ 'demo-banner': false,
122
+ 'jobs-held': false,
123
+ ...Object.fromEntries(appSimulatorFlags.map((flag) => [flag.id, false])),
124
+ }
125
+
126
+ const DEFAULT_ACTIVE_ORG = organizations[0]!.slug
127
+
128
+ /** One step of a demo-preset replay: the preset's own operations, then the two the replay adds — sitting
129
+ * down as the viewpoint, and announcing the load. Tagged by `step`, not by `op`, because operation kinds
130
+ * are an open registry: an app kind may be called anything, `viewpoint` included. */
131
+ type ReplayStep =
132
+ | { step: 'operation'; operation: PresetOperation }
133
+ | { step: 'viewpoint'; personId: string }
134
+ | { step: 'loaded'; title: string }
135
+
136
+ /** Truncating snippet used as a row's "title" in the digest (twin of the real handler's `snippet`). */
137
+ function digestSnippet(body: string): string {
138
+ const oneLine = body.replace(/\s+/g, ' ').trim()
139
+ return oneLine.length > DIGEST_SNIPPET_LENGTH ? `${oneLine.slice(0, DIGEST_SNIPPET_LENGTH - 1)}…` : oneLine
140
+ }
141
+
142
+ /** A team's digest recipient (twin of the server handler's `digestRecipient` in a simulated world): among everyone
143
+ * in the world (the seed and accepted invitees, as the fake auth adapter lists members), its admin, else its first
144
+ * member, else a synthetic per-org address. */
145
+ function digestRecipientEmail(orgSlug: string, everyone: readonly SeedPerson[]): string {
146
+ const members = everyone.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
147
+ const admin = members.find((p) => p.memberships.some((m) => m.orgSlug === orgSlug && m.role === 'admin'))
148
+ return (admin ?? members[0])?.email ?? `${orgSlug}@digest.example`
149
+ }
150
+
151
+ function makeSeedAgreements(): DemoAgreement[] {
152
+ return seedAgreements.map((a) => ({
153
+ id: `agr-${a.tenantSlug}-${a.kind}`,
154
+ tenantSlug: a.tenantSlug,
155
+ kind: a.kind,
156
+ version: a.version,
157
+ title: a.title,
158
+ bodyMd: a.bodyMd,
159
+ gating: a.gating,
160
+ }))
161
+ }
162
+
163
+ /** Seed the pre-acceptances that keep the world unblocked: every person in a tenant pre-accepts that
164
+ * tenant's `preAcceptedByAllInTenant` agreement at v1 (the alpha ToS), so nothing blocks until a bump.
165
+ * An agreement accepted by nobody is how the advisory banner gets something to show. */
166
+ function makeSeedAcceptances(): DemoAcceptance[] {
167
+ const rows: DemoAcceptance[] = []
168
+ for (const a of seedAgreements) {
169
+ if (!a.preAcceptedByAllInTenant) continue
170
+ const id = `agr-${a.tenantSlug}-${a.kind}`
171
+ for (const p of people.filter((person) => person.tenantSlug === a.tenantSlug)) {
172
+ rows.push({ agreementId: id, userId: p.id, version: a.version, acceptedAt: SEED_ACCEPTED_AT })
173
+ }
174
+ }
175
+ return rows
176
+ }
177
+
178
+ /**
179
+ * Twin of the framework seeder's job_schedules pass (../db/seed.ts): whatever the APP's seed data
180
+ * says, computed forward from now. It used to be one hard-coded row carrying one app's slugs — which
181
+ * meant the `file://` demo silently showed a different schedule list from `pnpm dev` the moment the
182
+ * app seeded a second one.
183
+ */
184
+ function makeSeedSchedules(): ScheduleRowLike[] {
185
+ return seedJobSchedules.map((schedule, index) => ({
186
+ id: `seed-schedule-${index}`,
187
+ kind: schedule.kind,
188
+ spec: schedule.spec,
189
+ nextRunAt: computeNextRunAt(schedule.spec, new Date()).toISOString(),
190
+ enabled: true,
191
+ tenantSlug: schedule.tenantSlug,
192
+ orgSlug: schedule.orgSlug,
193
+ }))
194
+ }
195
+
196
+ /** Demo-only signing secret: a random hex string, shown once on create (twin of the server's
197
+ * randomBytes secret). crypto.getRandomValues runs from file://, so this is real randomness. */
198
+ function makeWebhookSecret(): string {
199
+ const bytes = crypto.getRandomValues(new Uint8Array(24))
200
+ return `whsec_${[...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')}`
201
+ }
202
+
203
+ /** Resolve a person's role for one org, falling back to their first membership when the slug isn't
204
+ * (or is no longer) one they belong to — mirrors resolveMembership in the fake adapter. */
205
+ function roleInOrg(person: SeedPerson, orgSlug: string): PersonRole {
206
+ return person.memberships.find((m) => m.orgSlug === orgSlug)?.role ?? firstMembership(person).role
207
+ }
208
+
209
+ /** A person's first membership; a seed person always has at least one (SeedPerson.memberships). */
210
+ function firstMembership(person: SeedPerson): SeedPerson['memberships'][number] {
211
+ const first = person.memberships[0]
212
+ if (!first) throw new Error(`person ${person.id} has no memberships`)
213
+ return first
214
+ }
215
+
216
+ /** Turn the composition root's seeded outbox into MailItems (ids and timestamps are ours). */
217
+ function seededMail(initial: DemoWorldOptions['initialMail']): MailItem[] {
218
+ return (initial ?? []).map((mail, index) => ({
219
+ id: `seed-mail-${index}`,
220
+ to: mail.to,
221
+ subject: mail.subject,
222
+ html: mail.html,
223
+ at: new Date().toISOString(),
224
+ }))
225
+ }
226
+
227
+ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
228
+ const { inboundHandlers = {}, digestBodies, onReset, presetOperations: appPresetOperationHalves = {} } = options
229
+ const route = useHashRoute()
230
+ const tEmail = useTranslations('email')
231
+ const tSimulator = useTranslations('simulator')
232
+ const tOrg = useTranslations('org')
233
+ const tNotifications = useTranslations('notifications')
234
+ const tRoot = useTranslations()
235
+
236
+ const [person, setPerson] = useState<SeedPerson | null>(null)
237
+ const [inviteError, setInviteError] = useState<string | null>(null)
238
+ const [activeOrgSlug, setActiveOrgSlug] = useState(DEFAULT_ACTIVE_ORG)
239
+ const [displayName, setDisplayName] = useState<string | null>(null)
240
+ const [emails, setEmails] = useState<MailItem[]>(() => seededMail(options.initialMail))
241
+ const [invites, setInvites] = useState<DemoInvite[]>([])
242
+ // People created by accepting an invite (Bob's lifecycle) — merged with the seed list
243
+ // everywhere the seed list used to stand alone: People, the sign-in picker, the org member list.
244
+ const [dynamicPeople, setDynamicPeople] = useState<SeedPerson[]>([])
245
+ // The Simulator viewpoint when NO ONE is signed in (an invited-but-unregistered person's
246
+ // "desktop": signed-out main pane + their inbox in the panel). Cleared whenever a real
247
+ // person signs in; real sign-ins always derive their viewpoint from `person` instead.
248
+ const [invitedViewpoint, setInvitedViewpoint] = useState<string | null>(null)
249
+ const [events, setEvents] = useState<AnalyticsEvent[]>([])
250
+ // Twin of the audit_events table — appended by the twin's own mutations, shown read-only in the
251
+ // Simulator Events tab beneath the analytics events (full parity: audit is just rows).
252
+ const [auditEntries, setAuditEntries] = useState<AuditEntry[]>([])
253
+ const [flags, setFlags] = useState<Record<string, boolean>>(INITIAL_FLAGS)
254
+ // Twin of .data/simulator/actor-holds.json: the actors the world has individually held, by actor id.
255
+ // Only a demo preset's `actor.hold` writes it (the world-wide hold is the app's own flag, above).
256
+ const [actorHolds, setActorHolds] = useState<Record<string, boolean>>({})
257
+ const [jobs, setJobs] = useState<DemoJob[]>([])
258
+ // Twin of the inbound_emails table — the world's received mail, drives the Simulator Mail-tab
259
+ // inbound list. Filed by composeInbound below (the twin of intakeInboundEmail).
260
+ const [inbound, setInbound] = useState<InboundEmailRow[]>([])
261
+ // Twins of webhook_endpoints / webhook_deliveries + the fake failure toggle set.
262
+ const [endpoints, setEndpoints] = useState<DemoEndpoint[]>([])
263
+ const [deliveries, setDeliveries] = useState<DemoDelivery[]>([])
264
+ const [failingEndpoints, setFailingEndpoints] = useState<Set<string>>(() => new Set())
265
+ // The secret to show exactly once, right after creating an endpoint (twin of the create response).
266
+ const [newWebhookSecret, setNewWebhookSecret] = useState<string | null>(null)
267
+ // Twins of the notification fan-out: the notifications rows (header bell), the fake-SMS
268
+ // catch-store (Simulator Messages tab), and per-(person:org) preference rows (opt-out).
269
+ const [notifications, setNotifications] = useState<DemoNotification[]>([])
270
+ const [smsMessages, setSmsMessages] = useState<SmsMessageRow[]>([])
271
+ const [notifPrefs, setNotifPrefs] = useState<Record<string, NotificationPrefRow[]>>({})
272
+ // Twin of the job_schedules table — seeded with the weekly research digest.
273
+ const [schedules, setSchedules] = useState<ScheduleRowLike[]>(() => makeSeedSchedules())
274
+ // Twins of the agreements + agreement_acceptances tables — the access-gate worked example.
275
+ const [agreements, setAgreements] = useState<DemoAgreement[]>(() => makeSeedAgreements())
276
+ const [acceptances, setAcceptances] = useState<DemoAcceptance[]>(() => makeSeedAcceptances())
277
+ // Twin of the fake world-clock offset (.data/simulator/clock.json) — mount time + this = world "now".
278
+ const [clockOffsetMs, setClockOffsetMs] = useState(0)
279
+ // A fixed real-time anchor captured once at mount (lazy init — the one place an impure read is
280
+ // allowed). The seed schedule's next_run_at was computed from ~this same instant, so firing and the
281
+ // world-clock DISPLAY both read `mountedAtMs + offset`, keeping them consistent and render-pure.
282
+ const [mountedAtMs] = useState(() => Date.now())
283
+ const [mailScope, setMailScope] = useState<'person' | 'all'>('person')
284
+ // Twin of mailSeenAt (the real app persists this to .data/simulator/state.json, keyed by PersonKey).
285
+ const [mailSeenAt, setMailSeenAt] = useState<Record<string, string>>({})
286
+ const [notices, setNotices] = useState<SimulatorNotice[]>([])
287
+ const noticeSeq = useRef(0)
288
+ // Continuity twin (ADR-0006): the real app persists this to .data/simulator/state.json; with no
289
+ // server an in-memory map keyed by person id stands in for it.
290
+ const continuityMap = useRef(new Map<string, { route: string; org: string }>())
291
+ // The demo-preset replay queue (see applyPreset): the steps still to run, drained one per render.
292
+ const [replay, setReplay] = useState<ReplayStep[] | null>(null)
293
+ // Resolves the promise applyPreset handed out, once the queue drains.
294
+ const replayDone = useRef<((completed: boolean) => void) | null>(null)
295
+ // The replay's named results (an operation's `as` → the twin id of what it created). A ref, not state:
296
+ // only replay steps read it, each in its own timer tick. Cleared by every reset, so by every load.
297
+ const presetRefs = useRef(new Map<string, string>())
298
+ // Always-current mirror of `jobs` for the actor drivers: refs may not be written during render
299
+ // (react-hooks/refs), so an effect keeps it in sync instead — the drivers read through the ref
300
+ // rather than a stale closure, so they never need rebuilding when a tick fires.
301
+ const jobsRef = useRef<DemoJob[]>(jobs)
302
+ useEffect(() => {
303
+ jobsRef.current = jobs
304
+ }, [jobs])
305
+
306
+ const allPeople = [...people, ...dynamicPeople]
307
+ const org = organizations.find((o) => o.slug === activeOrgSlug) ?? organizations[0]!
308
+ // The tenant (ambient site) is never user-switchable — it follows whoever's signed in, not the
309
+ // active org (orgs never span tenants, so this always agrees with the active org's own site).
310
+ const tenant = findTenant(person ? person.tenantSlug : org.tenantSlug) ?? tenants[0]!
311
+ const name = displayName ?? person?.name ?? ''
312
+
313
+ function pushNotice(text: string) {
314
+ const id = (noticeSeq.current += 1)
315
+ setNotices((prev) => [...prev, { id, text }])
316
+ setTimeout(() => setNotices((prev) => prev.filter((notice) => notice.id !== id)), NOTICE_MS)
317
+ }
318
+
319
+ function logEvent(event: string, properties?: Record<string, unknown>) {
320
+ setEvents((prev) => [{ id: `evt-${prev.length}`, at: new Date().toISOString(), event, properties }, ...prev])
321
+ }
322
+
323
+ /** Twin of recordAuditEvent (../db/audit.ts): append a compliance-record row for the active
324
+ * tenant/org and whoever's signed in — the same who/what/when the real routes write post-mutation. */
325
+ function logAudit(action: string, subjectType: string, subjectId: string | null) {
326
+ appendAudit({ action, subjectType, subjectId, actorUserId: person?.id ?? '' }, tenant.slug, activeOrgSlug)
327
+ }
328
+
329
+ /** The same append, for a mutation whose tenant/org is RESOLVED rather than ambient (inbound mail
330
+ * files into the addressed team, not the team you happen to be looking at). */
331
+ function appendAudit(
332
+ entry: {
333
+ action: string
334
+ subjectType: string
335
+ subjectId: string | null
336
+ actorUserId: string
337
+ detail?: InboundReceivedDetail
338
+ },
339
+ tenantSlug: string,
340
+ orgSlug: string,
341
+ // The twin's WORLD clock, like the server's (DbPort.now in the fake database): real time plus the offset the
342
+ // demo advanced, so an event recorded after a jump is dated in that time and two events a moment apart still
343
+ // differ. (Not `mountedAtMs + offset`, which is frozen between advances; that is for the clock DISPLAY.)
344
+ at = new Date(Date.now() + clockOffsetMs).toISOString(),
345
+ ) {
346
+ setAuditEntries((prev) => [{ id: `audit-${prev.length}`, at, ...entry, tenantSlug, orgSlug }, ...prev])
347
+ }
348
+
349
+ // ── Access gates — the twin of the protected-layout gate evaluation ───────────────────────────
350
+ // Drives the SAME pure core (computePendingAgreements → gatesForAgreements → evaluateGates) the real
351
+ // server runs, over the in-memory agreements/acceptances. Full parity; the only "degrade" is that
352
+ // accept updates state in place instead of POST + reload.
353
+ const tenantAgreements: AgreementView[] = agreements
354
+ .filter((a) => a.tenantSlug === tenant.slug)
355
+ .map((a) => ({
356
+ id: a.id,
357
+ kind: a.kind,
358
+ version: a.version,
359
+ title: a.title,
360
+ bodyMd: a.bodyMd,
361
+ gating: a.gating,
362
+ }))
363
+ const myAcceptances: AcceptanceView[] = person
364
+ ? acceptances
365
+ .filter((x) => x.userId === person.id)
366
+ .map((x) => ({ agreementId: x.agreementId, version: x.version, acceptedAt: x.acceptedAt }))
367
+ : []
368
+ const pendingAgreements = computePendingAgreements(tenantAgreements, myAcceptances)
369
+ const pendingGates = evaluateGates(gatesForAgreements(tenantAgreements), agreementFacts(pendingAgreements))
370
+ const blockingGate = firstBlockingGate(pendingGates)
371
+ const blockingAgreement = blockingGate ? pendingAgreementForGateId(blockingGate.id, pendingAgreements) : undefined
372
+ const advisoryAgreements = advisoryGates(pendingGates).flatMap((gate) => {
373
+ const agreement = pendingAgreementForGateId(gate.id, pendingAgreements)
374
+ return agreement ? [agreement] : []
375
+ })
376
+
377
+ /** Accept an agreement for the signed-in person (twin of POST /api/agreements/accept): append an
378
+ * acceptance row at the agreement's CURRENT version + audit it. Re-render clears the gate naturally. */
379
+ function acceptAgreement(agreementId: string) {
380
+ if (!person) return
381
+ const agreement = agreements.find((a) => a.id === agreementId)
382
+ if (!agreement) return
383
+ setAcceptances((prev) => [
384
+ ...prev,
385
+ { agreementId, userId: person.id, version: agreement.version, acceptedAt: new Date().toISOString() },
386
+ ])
387
+ logAudit('agreement.accepted', 'AgreementAcceptance', agreementId)
388
+ }
389
+
390
+ /** Bump an agreement's version (twin of the Simulator bump god op): re-arms the gate for everyone
391
+ * whose latest acceptance is now stale. */
392
+ function bumpAgreement(id: string) {
393
+ const current = agreements.find((a) => a.id === id)
394
+ if (!current) return
395
+ setAgreements((prev) => prev.map((a) => (a.id === id ? { ...a, version: a.version + 1 } : a)))
396
+ pushNotice(tSimulator('noticeAgreementBumped', { version: current.version + 1 }))
397
+ }
398
+
399
+ // ── Notification fan-out ──────────────────────────────────────────────────────────────────────
400
+
401
+ /**
402
+ * Twin of the server notification fan-out (../server-lib/notify.ts): resolve the recipient's enabled
403
+ * channels via the SHARED core resolver (opt-out / default-on) and emit on each one — an in-app
404
+ * `notifications` row (the header bell), a MailItem (the same catch-store the invite email lands in),
405
+ * and a fake-SMS row (the Simulator Messages tab). The email + SMS copy comes from the SHARED core
406
+ * `notificationCopy` mapper, so the bell, the email, and the SMS can never drift.
407
+ */
408
+ function notifyPerson(
409
+ recipient: SeedPerson,
410
+ orgSlug: string,
411
+ kind: NotificationKind,
412
+ payload: NotificationPayload,
413
+ ) {
414
+ const prefs = notifPrefs[`${recipient.id}:${orgSlug}`] ?? []
415
+ const channels = resolveEnabledChannels(prefs, kind)
416
+ if (channels.includes('in_app')) {
417
+ setNotifications((prev) => [
418
+ {
419
+ id: crypto.randomUUID(),
420
+ recipientPersonId: recipient.id,
421
+ orgSlug,
422
+ kind,
423
+ payload,
424
+ readAt: null,
425
+ createdAt: new Date().toISOString(),
426
+ },
427
+ ...prev,
428
+ ])
429
+ }
430
+ if (channels.includes('email') || channels.includes('sms')) {
431
+ const copy = notificationCopy(kind, payload)
432
+ // Same rule as the server: an app kind's copy resolves in the app catalog's namespace.
433
+ const c = (key: string, values?: Record<string, string>) =>
434
+ tRoot(`${copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE}.${key}`, values)
435
+ if (channels.includes('email')) {
436
+ const html =
437
+ `<h2>${c(copy.titleKey, copy.values)}</h2>` +
438
+ `<p>${c(copy.bodyKey, copy.values)}</p>` +
439
+ `<p>${tNotifications('emailFooter')}</p>`
440
+ setEmails((prev) => [
441
+ {
442
+ id: `email-${prev.length}`,
443
+ to: recipient.email,
444
+ subject: c(copy.subjectKey, copy.values),
445
+ html,
446
+ at: new Date().toISOString(),
447
+ },
448
+ ...prev,
449
+ ])
450
+ }
451
+ if (channels.includes('sms')) {
452
+ setSmsMessages((prev) => [
453
+ {
454
+ id: crypto.randomUUID(),
455
+ to: recipient.name,
456
+ body: c(copy.smsKey, copy.values),
457
+ kind,
458
+ at: new Date().toISOString(),
459
+ },
460
+ ...prev,
461
+ ])
462
+ }
463
+ }
464
+ }
465
+
466
+ /**
467
+ * Twin of notifyMember: fan a notification to ONE named member of `orgSlug` — the recipient shape
468
+ * for a kind addressed to a person rather than to whoever manages the team. `excludePersonId`
469
+ * drops the actor, so handing something to yourself notifies nobody.
470
+ */
471
+ function notifyMemberOf(
472
+ orgSlug: string,
473
+ recipientPersonId: string,
474
+ kind: NotificationKind,
475
+ payload: NotificationPayload,
476
+ excludePersonId?: string,
477
+ ) {
478
+ if (recipientPersonId === excludePersonId) return
479
+ const recipient = allPeople.find(
480
+ (p) => p.id === recipientPersonId && p.memberships.some((m) => m.orgSlug === orgSlug),
481
+ )
482
+ if (recipient) notifyPerson(recipient, orgSlug, kind, payload)
483
+ }
484
+
485
+ /** Twin of notifyAdmins: fan a notification to every person who is an ACTIVE member of `orgSlug`
486
+ * with a role that passes canManageOrg, optionally excluding the acting person (org.invited
487
+ * addresses the inviter's peers, not the inviter). */
488
+ function notifyAdminsOf(
489
+ orgSlug: string,
490
+ kind: NotificationKind,
491
+ payload: NotificationPayload,
492
+ excludePersonId?: string,
493
+ ) {
494
+ for (const p of allPeople) {
495
+ if (p.id === excludePersonId) continue
496
+ if (!p.memberships.some((m) => m.orgSlug === orgSlug)) continue
497
+ if (!canManageOrg(roleInOrg(p, orgSlug))) continue
498
+ notifyPerson(p, orgSlug, kind, payload)
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Twin of notifyJobTerminal: a user-facing job reaching a terminal state notifies its OWN team's
504
+ * admins (jobs carry no creator column, so the team's admins are the recipients).
505
+ *
506
+ * The server gates this on NOTIFIED_JOB_KINDS — `appJobKinds`, i.e. "kinds the app registered are
507
+ * work someone submitted and is waiting on; the framework's scheduled kinds are internal machinery
508
+ * and would just be noise" (see the decision log). The twin gets the same gate STRUCTURALLY rather
509
+ * than from a list: only startJob puts a job in the queue, and it is the composition root's twin of
510
+ * a user submitting work, while runDueSchedules spawns its jobs already completed. So the two call
511
+ * sites below ARE the app-submitted kinds. Importing the seam's registry to re-derive that would
512
+ * have dragged every server handler's db/email dependencies into a bundle that has neither.
513
+ */
514
+ function notifyJobTerminal(job: { id: string; kind: string; orgSlug: string | null }) {
515
+ if (job.orgSlug === null) return
516
+ notifyAdminsOf(job.orgSlug, 'job.completed', { jobId: job.id, jobKind: job.kind, status: 'completed' })
517
+ }
518
+
519
+ // ── Outbound webhooks ─────────────────────────────────────────────────────────────────────────
520
+
521
+ /** Twin of enqueueWebhookEvent: fan an event to a pending delivery per matching enabled endpoint in
522
+ * the ACTIVE org (endpoints are org-scoped). next_attempt is world-now, so a drain fires it at once. */
523
+ function enqueueWebhook(kind: WebhookEventKind, payload: WebhookEventPayload) {
524
+ const worldNowMs = mountedAtMs + clockOffsetMs
525
+ const matching = endpoints.filter(
526
+ (e) =>
527
+ e.tenantSlug === tenant.slug && e.orgSlug === activeOrgSlug && e.enabled && e.eventKinds.includes(kind),
528
+ )
529
+ if (matching.length === 0) return
530
+ const created: DemoDelivery[] = matching.map((endpoint) => ({
531
+ id: crypto.randomUUID(),
532
+ endpointId: endpoint.id,
533
+ tenantSlug: endpoint.tenantSlug,
534
+ orgSlug: endpoint.orgSlug,
535
+ eventKind: kind,
536
+ payload,
537
+ status: 'pending',
538
+ attemptCount: 0,
539
+ nextAttemptAtMs: worldNowMs,
540
+ lastError: null,
541
+ createdAtMs: worldNowMs,
542
+ deliveredAtMs: null,
543
+ signature: null,
544
+ body: null,
545
+ }))
546
+ setDeliveries((prev) => [...created, ...prev])
547
+ }
548
+
549
+ /** Twin of runDueDeliveries: attempt each due pending/failed delivery, signing the envelope with the
550
+ * REAL core signer; a toggled-failing endpoint fails and re-arms on the SAME backoff the server
551
+ * uses, marking 'dead' at MAX_DELIVERY_ATTEMPTS. Reads current state from the closure (the house
552
+ * pattern here, like runDueSchedules). Returns how many were delivered. */
553
+ function runDueDeliveries(worldNowMs: number): number {
554
+ let delivered = 0
555
+ const next = deliveries.map((delivery) => {
556
+ if (!['pending', 'failed'].includes(delivery.status) || delivery.nextAttemptAtMs > worldNowMs) {
557
+ return delivery
558
+ }
559
+ const endpoint = endpoints.find((e) => e.id === delivery.endpointId)
560
+ const attempt = delivery.attemptCount + 1
561
+ if (!endpoint || !endpoint.enabled) {
562
+ return { ...delivery, status: 'dead', attemptCount: attempt, lastError: 'endpoint disabled' }
563
+ }
564
+ const body = JSON.stringify({
565
+ id: delivery.id,
566
+ kind: delivery.eventKind,
567
+ createdAt: new Date(delivery.createdAtMs).toISOString(),
568
+ data: delivery.payload,
569
+ })
570
+ const signature = webhookSignatureHeader(endpoint.secret, body, Math.floor(worldNowMs / 1000))
571
+ if (!failingEndpoints.has(endpoint.id)) {
572
+ delivered += 1
573
+ return {
574
+ ...delivery,
575
+ status: 'delivered',
576
+ attemptCount: attempt,
577
+ deliveredAtMs: worldNowMs,
578
+ lastError: null,
579
+ signature,
580
+ body,
581
+ }
582
+ }
583
+ const dead = attempt >= MAX_DELIVERY_ATTEMPTS
584
+ return {
585
+ ...delivery,
586
+ status: dead ? 'dead' : 'failed',
587
+ attemptCount: attempt,
588
+ nextAttemptAtMs: worldNowMs + backoffDelayMs(attempt),
589
+ lastError: 'fake failure toggle',
590
+ signature,
591
+ body,
592
+ }
593
+ })
594
+ setDeliveries(next)
595
+ return delivered
596
+ }
597
+
598
+ // ── Jobs, schedules and the world clock ───────────────────────────────────────────────────────
599
+
600
+ /**
601
+ * Twin of POST /api/jobs + fakeJobs.start: when the 'jobs-held' knob is on the job stays 'queued'
602
+ * for a later Run-pending step; otherwise it completes instantly with the full
603
+ * queued → running → completed story (a few hundred ms apart, exactly like the fake adapter) and
604
+ * emits what the terminal path emits server-side — the job.status_changed webhook recordJobStatus
605
+ * sends, and the org-admin notification notifyJobTerminal sends.
606
+ * DEGRADE: no downloadUrl — the static shell has no server to serve result bytes (physics forbid).
607
+ */
608
+ function startJob(kind: string) {
609
+ // One wall-clock read for the whole timeline, so the three hops are a fixed few hundred ms
610
+ // apart rather than however long React took between them (an event handler, not render, so
611
+ // reading the clock here is correct).
612
+ const now = Date.now()
613
+ const iso = (offset: number) => new Date(now + offset).toISOString()
614
+ const held = flags['jobs-held'] ?? false
615
+ const base = {
616
+ id: crypto.randomUUID(),
617
+ kind,
618
+ tenantSlug: tenant.slug,
619
+ orgSlug: activeOrgSlug,
620
+ createdAt: iso(0),
621
+ error: null,
622
+ }
623
+ const job: DemoJob = held
624
+ ? { ...base, status: 'queued', timeline: [{ status: 'queued', at: iso(0) }] }
625
+ : {
626
+ ...base,
627
+ status: 'completed',
628
+ timeline: [
629
+ { status: 'queued', at: iso(0) },
630
+ { status: 'running', at: iso(200) },
631
+ { status: 'completed', at: iso(400) },
632
+ ],
633
+ }
634
+ setJobs((prev) => [job, ...prev])
635
+ // Held jobs stay queued (no terminal transition), so they emit later — from the Run-pending
636
+ // step below, or from an actor claiming them.
637
+ if (held) return
638
+ enqueueWebhook('job.status_changed', {
639
+ jobId: base.id,
640
+ jobKind: kind,
641
+ status: 'completed',
642
+ orgId: activeOrgSlug,
643
+ })
644
+ notifyJobTerminal(job)
645
+ }
646
+
647
+ /**
648
+ * Simulator "Run pending jobs" twin: advance every queued job to completed with the full timeline,
649
+ * then fire each one's terminal notification. Pure in-memory logic (no server), so this is genuine
650
+ * parity — not a degrade.
651
+ */
652
+ function runPendingJobs() {
653
+ const completing = jobs.filter((job) => job.status === 'queued')
654
+ setJobs((prev) =>
655
+ prev.map((job) => {
656
+ if (job.status !== 'queued') return job
657
+ const now = Date.now()
658
+ return {
659
+ ...job,
660
+ status: 'completed',
661
+ timeline: [
662
+ ...job.timeline,
663
+ { status: 'running', at: new Date(now).toISOString() },
664
+ { status: 'completed', at: new Date(now + 200).toISOString() },
665
+ ],
666
+ }
667
+ }),
668
+ )
669
+ for (const job of completing) {
670
+ // The same terminal hop startJob's non-held branch takes, so it emits the same pair the
671
+ // server's recordJobStatus does: the webhook first, then the admin notification (both
672
+ // skip an org-less job, as notifyJobTerminal already does).
673
+ if (job.orgSlug !== null) {
674
+ enqueueWebhook('job.status_changed', {
675
+ jobId: job.id,
676
+ jobKind: job.kind,
677
+ status: 'completed',
678
+ orgId: job.orgSlug,
679
+ })
680
+ }
681
+ notifyJobTerminal(job)
682
+ }
683
+ pushNotice(tSimulator('noticeJobsRan', { count: completing.length }))
684
+ }
685
+
686
+ /**
687
+ * Twin of runDueSchedules: fire every enabled schedule due at the given world "now" — spawn a
688
+ * digest-email job (completed inline) and land the digest in the Mail store — then advance
689
+ * next_run_at, coalescing missed periods so a big clock jump fires once, never once per skipped
690
+ * week. Reads current schedules from the render closure (the house pattern here); returns how many
691
+ * fired. Genuine parity — schedules are just rows plus pure core.
692
+ */
693
+ function runDueSchedules(worldNowMs: number): number {
694
+ const fired: ScheduleRowLike[] = []
695
+ const advanced = schedules.map((schedule) => {
696
+ if (!schedule.enabled || new Date(schedule.nextRunAt).getTime() > worldNowMs) return schedule
697
+ fired.push(schedule)
698
+ let next = computeNextRunAt(schedule.spec, new Date(schedule.nextRunAt))
699
+ for (let i = 0; next.getTime() <= worldNowMs && i < 100_000; i++)
700
+ next = computeNextRunAt(schedule.spec, next)
701
+ if (next.getTime() <= worldNowMs) next = computeNextRunAt(schedule.spec, new Date(worldNowMs))
702
+ return { ...schedule, nextRunAt: next.toISOString() }
703
+ })
704
+ if (fired.length === 0) return 0
705
+ setSchedules(advanced)
706
+
707
+ const iso = new Date(worldNowMs).toISOString()
708
+ const newJobs: DemoJob[] = []
709
+ const newEmails: MailItem[] = []
710
+ for (const schedule of fired) {
711
+ const jobId = crypto.randomUUID()
712
+ newJobs.push({
713
+ id: jobId,
714
+ kind: 'digest-email',
715
+ status: 'completed',
716
+ tenantSlug: schedule.tenantSlug,
717
+ orgSlug: schedule.orgSlug,
718
+ createdAt: iso,
719
+ error: null,
720
+ timeline: [
721
+ { status: 'queued', at: iso, message: 'scheduled' },
722
+ { status: 'running', at: iso },
723
+ { status: 'completed', at: iso },
724
+ ],
725
+ })
726
+ const orgName = findOrg(schedule.orgSlug)?.name ?? schedule.orgSlug
727
+ const bodies = digestBodies?.({ tenantSlug: schedule.tenantSlug, orgSlug: schedule.orgSlug }) ?? []
728
+ const recent = bodies.slice(0, DIGEST_RECENT_LIMIT).map(digestSnippet)
729
+ newEmails.push({
730
+ id: `${worldNowMs}-${jobId.slice(0, 8)}`,
731
+ to: digestRecipientEmail(schedule.orgSlug, allPeople),
732
+ subject: tEmail('digestSubject', { org: orgName }),
733
+ at: iso,
734
+ html: buildDigestEmailHtml(
735
+ {
736
+ heading: tEmail('digestHeading', { org: orgName }),
737
+ intro: tEmail('digestIntro', { org: orgName }),
738
+ countLine: tEmail('digestCount', { count: bodies.length }),
739
+ recentHeading: tEmail('digestRecentHeading'),
740
+ emptyLine: tEmail('digestEmpty'),
741
+ footer: tEmail('digestFooter'),
742
+ },
743
+ recent,
744
+ ),
745
+ })
746
+ }
747
+ setJobs((prev) => [...newJobs, ...prev])
748
+ setEmails((prev) => [...newEmails, ...prev])
749
+ return fired.length
750
+ }
751
+
752
+ // World-clock controls (twin of the real glue's clock handlers). Advance moves the offset forward
753
+ // then drains due schedules at the new world "now"; run-due drains without moving; reset returns to
754
+ // real time. worldNow is computed directly from the new offset (setState is async).
755
+ function advanceClock(deltaMs: number) {
756
+ const newOffset = clockOffsetMs + deltaMs
757
+ setClockOffsetMs(newOffset)
758
+ const spawned = runDueSchedules(mountedAtMs + newOffset)
759
+ // Same tick drains due webhook deliveries — "advance past a retry's backoff and watch it fire"
760
+ // works in the twin too. Silent (the Hooks tab shows the result); the notice stays
761
+ // schedule-focused to match the real glue.
762
+ runDueDeliveries(mountedAtMs + newOffset)
763
+ pushNotice(
764
+ spawned > 0 ? tSimulator('noticeScheduleFired', { count: spawned }) : tSimulator('noticeClockAdvanced'),
765
+ )
766
+ }
767
+
768
+ function resetClock() {
769
+ setClockOffsetMs(0)
770
+ pushNotice(tSimulator('noticeClockReset'))
771
+ }
772
+
773
+ function runDueSchedulesNow() {
774
+ const spawned = runDueSchedules(mountedAtMs + clockOffsetMs)
775
+ pushNotice(spawned > 0 ? tSimulator('noticeScheduleFired', { count: spawned }) : tSimulator('noticeNoDue'))
776
+ }
777
+
778
+ // The actor drivers read/write jobs through the stable ref + setter, so these factories never need
779
+ // to change identity — an actor's tick closure can be rebuilt freely without restarting its loop.
780
+ const serviceDriver = useCallback(
781
+ (scope: DemoServiceScope, log: ActorLog) => createDemoServiceDriver({ jobsRef, setJobs, log }, scope),
782
+ [],
783
+ )
784
+ const builderDriver = useCallback(
785
+ (serviceManagedOrgSlugs: readonly string[], log: ActorLog) =>
786
+ createDemoBuilderDriver({ jobsRef, setJobs, log }, serviceManagedOrgSlugs),
787
+ [],
788
+ )
789
+
790
+ // ── Inbound mail ──────────────────────────────────────────────────────────────────────────────
791
+
792
+ /**
793
+ * Twin of intakeInboundEmail (../inbound-email/intake.ts): the world emails the app. Parse the
794
+ * recipient with the SAME pure core parser, resolve the org from the seed (org slugs are globally
795
+ * unique), then dispatch to the registered handler twin — an unregistered slug lands an 'unmatched'
796
+ * row, exactly like a missing entry in the real registry. Genuine parity (pure logic), no physics
797
+ * degrade. Audit is written for the RESOLVED org/actor (not the signed-in viewpoint), so inbound
798
+ * mail into a team you're not looking at is still attributed correctly.
799
+ */
800
+ function composeInbound(input: InboundComposeInput) {
801
+ intakeInbound(input)
802
+ }
803
+
804
+ /** composeInbound's body: answers what the handler twin created (`subjectId`, when it created
805
+ * something), or null when no row was filed at all — an address naming no team. */
806
+ function intakeInbound(input: InboundComposeInput): { subjectId?: string } | null {
807
+ const to = formatInboundRecipient(input.orgSlug, input.handler, DEMO_INBOUND_DOMAIN)
808
+ const parsed = parseInboundRecipient(to)
809
+ const seedOrg = parsed ? organizations.find((o) => o.slug === parsed.orgSlug) : null
810
+ if (!parsed || !seedOrg) {
811
+ pushNotice(tSimulator('noticeInboundSent', { status: tSimulator('inboundStatus_unmatched') }))
812
+ return null
813
+ }
814
+ const fromEmail = normalizeEmailAddress(input.from) || input.from.trim().toLowerCase()
815
+ const bodyText = normalizeInboundBody(input.body)
816
+ // The inbound ROW keeps real time, as the server's inbound_emails.created_at does (the database's own
817
+ // now()); its AUDIT rows take the world clock, through appendAudit's default.
818
+ const at = new Date().toISOString()
819
+ const id = `inbound-${at}-${inbound.length}`
820
+
821
+ let status = 'unmatched'
822
+ let handlerClaimed: string | null = null
823
+ let error: string | null = null
824
+ let actor = INBOUND_SYSTEM_ACTOR
825
+ let subjectId: string | undefined
826
+ // The same closed vocabulary the server intake records (@sssb/kit/core/inbound-email).
827
+ let detail: InboundReceivedDetail = { outcome: 'unmatched', cause: 'no-handler' }
828
+
829
+ // An own entry only, as in the server intake: `+constructor` names no handler.
830
+ const handler = Object.hasOwn(inboundHandlers, parsed.handler) ? inboundHandlers[parsed.handler] : undefined
831
+ if (!handler) {
832
+ error = `no handler: ${parsed.handler}`
833
+ } else {
834
+ handlerClaimed = parsed.handler
835
+ // A THROW is the third outcome, as in the server intake (@sssb/kit/inbound-email/intake.ts): the
836
+ // row is kept as 'failed' and nothing else stops — a preset replaying this email carries on
837
+ // with no named result, exactly as the server replay does.
838
+ try {
839
+ const result = handler({
840
+ org: seedOrg,
841
+ members: allPeople.filter((p) => p.memberships.some((m) => m.orgSlug === seedOrg.slug)),
842
+ fromEmail,
843
+ subject: input.subject,
844
+ bodyText,
845
+ recordAudit: (entry) => appendAudit(entry, seedOrg.tenantSlug, seedOrg.slug),
846
+ })
847
+ if (result.status === 'handled') {
848
+ status = 'handled'
849
+ actor = result.actorUserId
850
+ subjectId = result.subjectId
851
+ detail = { outcome: 'handled' }
852
+ } else {
853
+ error = result.reason
854
+ detail = { outcome: 'unmatched', cause: 'declined' }
855
+ }
856
+ } catch (thrown) {
857
+ status = 'failed'
858
+ error = thrown instanceof Error ? thrown.message : String(thrown)
859
+ detail = { outcome: 'failed', cause: 'handler-threw' }
860
+ }
861
+ }
862
+
863
+ setInbound((prev) => [
864
+ {
865
+ id,
866
+ toEmail: normalizeEmailAddress(to) || to,
867
+ fromEmail,
868
+ subject: input.subject,
869
+ status,
870
+ handler: handlerClaimed,
871
+ error,
872
+ createdAt: at,
873
+ tenantSlug: seedOrg.tenantSlug,
874
+ orgSlug: seedOrg.slug,
875
+ },
876
+ ...prev,
877
+ ])
878
+ appendAudit(
879
+ {
880
+ action: 'inbound-email.received',
881
+ subjectType: 'InboundEmail',
882
+ subjectId: id,
883
+ actorUserId: actor,
884
+ detail,
885
+ },
886
+ seedOrg.tenantSlug,
887
+ seedOrg.slug,
888
+ )
889
+ pushNotice(
890
+ tSimulator('noticeInboundSent', {
891
+ status: tSimulator(`inboundStatus_${status}` as 'inboundStatus_handled'),
892
+ }),
893
+ )
894
+ return subjectId === undefined ? {} : { subjectId }
895
+ }
896
+
897
+ // ── Invites and membership ────────────────────────────────────────────────────────────────────
898
+
899
+ /**
900
+ * Twin of `sendOrgInvite` (@sssb/kit/server-lib/invite.ts) — what happens once an invite is allowed: mint
901
+ * it, land its email in the catch-store, audit it, and notify the team's OTHER admins. The inviter and
902
+ * the team are explicit because the demo-preset replay names both; the org screen passes whoever is
903
+ * signed in. Answers false for a team the seed does not have, or for the duplicate the real API
904
+ * refuses with a 409.
905
+ *
906
+ * One known divergence: the server renders the email in the INVITER's locale (the invitee has none
907
+ * yet); this twin renders it in the locale the demo is being viewed in, because the static shell
908
+ * loads one catalog at a time. Same keys, same placeholders — only the language can differ.
909
+ */
910
+ function inviteInto(inviter: SeedPerson, orgSlug: string, email: string, role: string): boolean {
911
+ const target = findOrg(orgSlug)
912
+ // Never fall back to the ambient team: an invite always names the one it is for.
913
+ if (!target) return false
914
+ const taken = [...allPeople.map((p) => p.email), ...invites.map((i) => i.email)]
915
+ if (taken.some((existing) => existing.toLowerCase() === email.toLowerCase())) return false
916
+ // crypto.randomUUID keeps twin ids collision-free (and symmetric with the fake adapter) — a
917
+ // length-based id could be reused after an accept shrinks the list, making a stale email link
918
+ // accept the WRONG invite.
919
+ const id = crypto.randomUUID()
920
+ const html = buildInviteEmailHtml(
921
+ {
922
+ heading: tEmail('inviteHeading', { org: target.name }),
923
+ body: tEmail('inviteBody', { inviter: inviter.name, org: target.name, role }),
924
+ button: tEmail('inviteButton'),
925
+ linkFallback: tEmail('inviteLinkFallback'),
926
+ },
927
+ `#/accept-invite/${id}`,
928
+ )
929
+ setInvites((prev) => [...prev, { id, email, role, orgSlug: target.slug }])
930
+ setEmails((prev) => [
931
+ {
932
+ id: `email-${prev.length}`,
933
+ to: email,
934
+ subject: tEmail('inviteSubject', { org: target.name }),
935
+ html,
936
+ at: new Date().toISOString(),
937
+ },
938
+ ...prev,
939
+ ])
940
+ logEvent('org_invite_sent', { tenant: target.tenantSlug, org: target.slug, role })
941
+ appendAudit(
942
+ { action: 'membership.invited', subjectType: 'Membership', subjectId: id, actorUserId: inviter.id },
943
+ target.tenantSlug,
944
+ target.slug,
945
+ )
946
+ // Notify the inviting team's OTHER admins (the invitee has no account yet, so they can't hold
947
+ // an in-app row — see the decision log).
948
+ notifyAdminsOf(target.slug, 'org.invited', { email, role, orgName: target.name }, inviter.id)
949
+ pushNotice(tSimulator('noticeNewMail', { email }))
950
+ return true
951
+ }
952
+
953
+ /** Twin of POST /api/org/invite: the signed-in person invites into the active team. */
954
+ async function sendInvite({ email, role }: { email: string; role: string }) {
955
+ setInviteError(null)
956
+ // The same allowlist the real invite route enforces. The org screen only offers assignable
957
+ // roles, so no click reaches this — but a tour script or other non-UI caller can pass 'admin'
958
+ // straight in. The error is set before throwing because the org screen swallows the rejection
959
+ // and shows only `inviteError`. (A demo preset's invite never gets here: it is held to the same
960
+ // rule at build time, by the `invite` kind's check in @sssb/kit/core/presets.ts.)
961
+ if (!isAssignableRole(role)) {
962
+ setInviteError(tOrg('inviteFailed'))
963
+ throw new Error('role not assignable')
964
+ }
965
+ if (!person) return
966
+ // The display name honours an unsaved profile edit, like the rest of the signed-in header.
967
+ if (!inviteInto({ ...person, name }, activeOrgSlug, email, role)) {
968
+ setInviteError(tOrg('inviteDuplicate'))
969
+ throw new Error('duplicate')
970
+ }
971
+ }
972
+
973
+ /** Twin of the accept-invite route: mint the person, consume the invite, sign them in, and record
974
+ * clickwrap-on-join acceptance of the tenant's current agreements so they aren't immediately gated. */
975
+ function acceptInvite(inviteId: string, acceptedName: string) {
976
+ const invite = invites.find((i) => i.id === inviteId)
977
+ if (!invite) return
978
+ const joinTenant = findOrg(invite.orgSlug)?.tenantSlug ?? ''
979
+ const newPerson: SeedPerson = {
980
+ id: `person-invited-${invite.id.slice(0, 8)}`,
981
+ name: acceptedName,
982
+ email: invite.email,
983
+ locale: 'en',
984
+ tenantSlug: joinTenant,
985
+ memberships: [{ orgSlug: invite.orgSlug, role: invite.role as PersonRole }],
986
+ restricted: invite.role === 'restricted',
987
+ }
988
+ setDynamicPeople((prev) => [...prev, newPerson])
989
+ setInvites((prev) => prev.filter((i) => i.id !== invite.id))
990
+ setInvitedViewpoint(null)
991
+ setPerson(newPerson)
992
+ setActiveOrgSlug(invite.orgSlug)
993
+ setAcceptances((prev) => [
994
+ ...prev,
995
+ ...agreements
996
+ .filter((a) => a.tenantSlug === joinTenant)
997
+ .map((a) => ({
998
+ agreementId: a.id,
999
+ userId: newPerson.id,
1000
+ version: a.version,
1001
+ acceptedAt: new Date().toISOString(),
1002
+ })),
1003
+ ])
1004
+ go('dashboard')
1005
+ }
1006
+
1007
+ function signIn(personId: string) {
1008
+ const picked = allPeople.find((p) => p.id === personId)
1009
+ if (!picked) return
1010
+ setPerson(picked)
1011
+ setInvitedViewpoint(null)
1012
+ setActiveOrgSlug(firstMembership(picked).orgSlug)
1013
+ go('dashboard')
1014
+ }
1015
+
1016
+ function signOut() {
1017
+ setPerson(null)
1018
+ setInvitedViewpoint(null)
1019
+ go('')
1020
+ }
1021
+
1022
+ function saveProfile(values: { name: string }) {
1023
+ setDisplayName(values.name)
1024
+ }
1025
+
1026
+ // ── The Simulator people, viewpoint and mail scoping ────────────────────────────────────────────
1027
+
1028
+ // Keep the continuity map current on every route or org change for whoever's signed in.
1029
+ // A ref mutation, not state — this deliberately doesn't trigger a re-render.
1030
+ useEffect(() => {
1031
+ if (!person) return
1032
+ continuityMap.current.set(`person:${person.id}`, { route: route || 'dashboard', org: activeOrgSlug })
1033
+ }, [route, activeOrgSlug, person])
1034
+
1035
+ useEffect(() => {
1036
+ // Mirrors the real app's PageViewTracker beacon (fire on every route change); the static
1037
+ // shell has no server to send it to, so it goes straight into the in-memory event log.
1038
+ // Deliberately keyed on `route` only — an org switch alone shouldn't log a page_view.
1039
+ // eslint-disable-next-line react-hooks/set-state-in-effect
1040
+ logEvent('page_view', { tenant: tenant.slug, path: route || 'welcome' })
1041
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1042
+ }, [route])
1043
+
1044
+ const peopleRows: Person[] = [
1045
+ ...allPeople.map((p) => {
1046
+ const key = `person:${p.id}`
1047
+ const seenAt = mailSeenAt[key]
1048
+ return {
1049
+ key,
1050
+ name: p.name,
1051
+ email: p.email,
1052
+ role: p.memberships[0]?.role ?? '',
1053
+ orgs: p.memberships,
1054
+ tenantSlug: p.tenantSlug,
1055
+ status: 'active' as const,
1056
+ hasAccount: true as const,
1057
+ unreadMail: emails.filter((email) => email.to === p.email && (!seenAt || email.at > seenAt)).length,
1058
+ }
1059
+ }),
1060
+ ...invites.map((invite) => {
1061
+ const key = `invited:${invite.id}`
1062
+ const seenAt = mailSeenAt[key]
1063
+ return {
1064
+ key,
1065
+ name: null,
1066
+ email: invite.email,
1067
+ role: invite.role,
1068
+ orgs: [{ orgSlug: invite.orgSlug, role: invite.role }],
1069
+ tenantSlug: findOrg(invite.orgSlug)?.tenantSlug ?? '',
1070
+ status: 'invited' as const,
1071
+ hasAccount: false as const,
1072
+ unreadMail: emails.filter((email) => email.to === invite.email && (!seenAt || email.at > seenAt))
1073
+ .length,
1074
+ }
1075
+ }),
1076
+ ]
1077
+ const viewpoint = person ? `person:${person.id}` : invitedViewpoint
1078
+ // Mirrors the real glue's derivation (simulator-glue.tsx): resolve the viewpoint's email from
1079
+ // the same people list the People tab renders, rather than re-deriving it a second way.
1080
+ const personEmail = peopleRows.find((p) => p.key === viewpoint)?.email ?? null
1081
+ const scopedEmails =
1082
+ mailScope === 'all' || !personEmail ? emails : emails.filter((email) => email.to === personEmail)
1083
+
1084
+ function selectPerson(key: string) {
1085
+ if (key.startsWith('invited:')) {
1086
+ const inviteId = key.replace(/^invited:/, '')
1087
+ if (!invites.some((invite) => invite.id === inviteId)) return
1088
+ // Mirrors POST /api/simulator/viewpoint's invited: branch: a viewpoint change, not a
1089
+ // sign-in — the main pane goes to the signed-out welcome screen, the panel follows.
1090
+ setPerson(null)
1091
+ setInvitedViewpoint(key)
1092
+ go('')
1093
+ return
1094
+ }
1095
+ const personId = key.replace(/^person:/, '')
1096
+ const target = allPeople.find((p) => p.id === personId)
1097
+ if (!target) return
1098
+ const remembered = continuityMap.current.get(key)
1099
+ setPerson(target)
1100
+ setInvitedViewpoint(null)
1101
+ setActiveOrgSlug(remembered?.org ?? firstMembership(target).orgSlug)
1102
+ go(remembered?.route ?? 'dashboard')
1103
+ }
1104
+
1105
+ function markMailSeen() {
1106
+ if (!viewpoint) return
1107
+ setMailSeenAt((prev) => ({ ...prev, [viewpoint]: new Date().toISOString() }))
1108
+ }
1109
+
1110
+ function openMailLink(href: string) {
1111
+ // Mirrors the real glue's policy, translated to the shell's hash router — and like the
1112
+ // real glue, a link this shell won't follow gets a notice instead of a silent nothing.
1113
+ if (href.startsWith('#')) {
1114
+ go(href.replace(/^#\/?/, ''))
1115
+ return
1116
+ }
1117
+ pushNotice(tSimulator('noticeLinkUnusable', { href }))
1118
+ }
1119
+
1120
+ function copyMailLink(href: string) {
1121
+ void navigator.clipboard
1122
+ .writeText(href)
1123
+ .then(() => pushNotice(tSimulator('noticeLinkCopied')))
1124
+ .catch(() => pushNotice(tSimulator('noticeLinkCopyFailed')))
1125
+ }
1126
+
1127
+ function clearMail() {
1128
+ setEmails([])
1129
+ pushNotice(tSimulator('noticeMailCleared'))
1130
+ }
1131
+
1132
+ /**
1133
+ * Twin of the real Snapshots reset (ADR-0006): the shell has no `.data/` filesystem to wipe, so
1134
+ * "reset the world" just means setting every piece of in-memory state back to its initial value and
1135
+ * navigating to the welcome route — no save/restore here, there's no server to snapshot against
1136
+ * (SnapshotsApp hides that half of the UI when `snapshots` is undefined). The composition root's own rows
1137
+ * go back through `onReset`, since this world can't see them.
1138
+ */
1139
+ function resetWorld() {
1140
+ setPerson(null)
1141
+ setActiveOrgSlug(DEFAULT_ACTIVE_ORG)
1142
+ setDisplayName(null)
1143
+ // Back to the SEEDED outbox, not an empty one — reset restores the world the app described.
1144
+ setEmails(seededMail(options.initialMail))
1145
+ setInvites([])
1146
+ setDynamicPeople([])
1147
+ setInvitedViewpoint(null)
1148
+ setEvents([])
1149
+ setAuditEntries([])
1150
+ setFlags(INITIAL_FLAGS)
1151
+ setActorHolds({})
1152
+ setJobs([])
1153
+ setInbound([])
1154
+ setEndpoints([])
1155
+ setDeliveries([])
1156
+ setFailingEndpoints(new Set())
1157
+ setNewWebhookSecret(null)
1158
+ setNotifications([])
1159
+ setSmsMessages([])
1160
+ setNotifPrefs({})
1161
+ setSchedules(makeSeedSchedules())
1162
+ setAgreements(makeSeedAgreements())
1163
+ setAcceptances(makeSeedAcceptances())
1164
+ setClockOffsetMs(0)
1165
+ setMailScope('person')
1166
+ setMailSeenAt({})
1167
+ continuityMap.current.clear()
1168
+ // A reset abandons any preset replay still in flight, and settles whoever was waiting on it with
1169
+ // false: that world was never finished, so a tour must not start in it as if it had been.
1170
+ setReplay(null)
1171
+ replayDone.current?.(false)
1172
+ replayDone.current = null
1173
+ presetRefs.current.clear()
1174
+ onReset?.()
1175
+ setNotices([])
1176
+ go('')
1177
+ pushNotice(tSimulator('noticeWorldReset'))
1178
+ }
1179
+
1180
+ /**
1181
+ * Twin of the server's demo-preset replay (@sssb/kit/server-lib/demo-presets.ts): reset to the seed, then
1182
+ * replay the preset's operations through each kind's STATIC half — SSSB's below (the invite core,
1183
+ * compose-inbound and so the app's inbound handler twins, the flag store), or the app's from
1184
+ * `DemoWorldOptions.presetOperations` — and finally sit down as the preset's viewpoint. The preset is
1185
+ * its `extends` chain flattened (`expandPreset`), base first. Resolves true once the world is ready;
1186
+ * false for an id no preset has (or one whose chain is broken), or when the replay is abandoned (a
1187
+ * reset mid-replay) or reaches a step this world cannot perform.
1188
+ *
1189
+ * The steps run ONE PER RENDER, from the effect below, rather than in a loop here. Every twin reads
1190
+ * the world through this render's closure (the duplicate check reads `invites`, the inbound twin
1191
+ * reads the member list, an app twin reads its own rows), so a loop would replay every step against
1192
+ * the world as it stood BEFORE the reset. Draining a queue across commits gives each step the world
1193
+ * its predecessors left, which is what the server gets for free by writing to disk between steps.
1194
+ */
1195
+ function applyPreset(id: string): Promise<boolean> {
1196
+ const registered = presets.find((candidate) => candidate.id === id)
1197
+ const expanded = expandPreset(id, presets)
1198
+ if (!registered || !expanded) return Promise.resolve(false)
1199
+ // Also clears the named results (presetRefs): a name means a step of THIS replay, never the last.
1200
+ resetWorld()
1201
+ const steps: ReplayStep[] = expanded.operations.map((operation) => ({ step: 'operation', operation }))
1202
+ if (expanded.viewpoint !== undefined) steps.push({ step: 'viewpoint', personId: expanded.viewpoint })
1203
+ // The notice names the preset that was asked for, not a base it happened to build on.
1204
+ steps.push({ step: 'loaded', title: tRoot(registered.titleKey) })
1205
+ setReplay(steps)
1206
+ return new Promise((resolve) => {
1207
+ replayDone.current = resolve
1208
+ })
1209
+ }
1210
+
1211
+ /** SSSB's static halves — the twins of @sssb/kit/server-lib/preset-operations.ts. Rebuilt every render on
1212
+ * purpose: each reads the world through this render's closure (see applyPreset). */
1213
+ const frameworkPresetOperationHalves = {
1214
+ invite: ((args) => {
1215
+ const inviter = allPeople.find((p) => p.id === args.by)
1216
+ return inviter !== undefined && inviteInto(inviter, args.org, args.email, args.role) ? {} : false
1217
+ }) satisfies StaticPresetOperationHandler<InviteArgs>,
1218
+ inbound: ((args) => {
1219
+ if (!findOrg(args.org)) return false
1220
+ const filed = intakeInbound({
1221
+ from: args.from,
1222
+ orgSlug: args.org,
1223
+ handler: args.handler,
1224
+ subject: args.subject,
1225
+ body: args.body,
1226
+ })
1227
+ // The row the handler twin opened, if it opened one — a declined email names nothing.
1228
+ return filed ? { ref: filed.subjectId } : false
1229
+ }) satisfies StaticPresetOperationHandler<InboundArgs>,
1230
+ flag: ((args) => {
1231
+ if (!Object.hasOwn(INITIAL_FLAGS, args.flag)) return false
1232
+ setFlags((prev) => ({ ...prev, [args.flag]: args.enabled }))
1233
+ return {}
1234
+ }) satisfies StaticPresetOperationHandler<FlagArgs>,
1235
+ // Like the server half, no registry check: the world has no actor list to ask, and the seam
1236
+ // gate has already held every registered preset to the app's registered actors.
1237
+ 'actor.hold': ((args) => {
1238
+ setActorHolds((prev) => ({ ...prev, [args.actor]: args.held }))
1239
+ return {}
1240
+ }) satisfies StaticPresetOperationHandler<ActorHoldArgs>,
1241
+ }
1242
+
1243
+ /**
1244
+ * The ONE static dispatcher, twin of the server's `performPresetOperation`: SSSB's halves composed
1245
+ * with the app's (an app entry with SSSB's kind name replaces SSSB's), the step's arguments (all but
1246
+ * `op` and `as`), then `as` bound to what it created. False for a kind with no static half, a half
1247
+ * that cannot perform the step (or throws — an unresolved name does), and an `as` on a step that
1248
+ * created nothing.
1249
+ */
1250
+ function performPresetOperation(operation: PresetOperation): boolean {
1251
+ const halves: Record<string, StaticPresetOperationHandler> = {
1252
+ ...frameworkPresetOperationHalves,
1253
+ ...appPresetOperationHalves,
1254
+ }
1255
+ const { op, as, ...args } = operation
1256
+ const half = Object.hasOwn(halves, op) ? halves[op] : undefined
1257
+ if (!half) return false
1258
+ const context: StaticPresetOperationContext = {
1259
+ refs: {
1260
+ resolve(name) {
1261
+ const bound = presetRefs.current.get(name)
1262
+ if (bound === undefined) throw new Error(`no earlier operation is named "${name}"`)
1263
+ return bound
1264
+ },
1265
+ },
1266
+ findPerson: (personId) => allPeople.find((p) => p.id === personId),
1267
+ recordAudit: (entry, scope) => appendAudit(entry, scope.tenantSlug, scope.orgSlug),
1268
+ notifyMemberOf,
1269
+ framework: frameworkPresetOperationHalves,
1270
+ }
1271
+ let result: { ref?: string | undefined } | false
1272
+ try {
1273
+ result = half(args, context)
1274
+ } catch {
1275
+ return false
1276
+ }
1277
+ if (result === false) return false
1278
+ if (as === undefined) return true
1279
+ if (result.ref === undefined) return false
1280
+ presetRefs.current.set(as, result.ref)
1281
+ return true
1282
+ }
1283
+
1284
+ /** Runs one replay step; false when the world cannot perform it — the twin of the server replay
1285
+ * throwing. Only a preset that bypassed the conformance gate can get here. */
1286
+ function performReplayStep(step: ReplayStep): boolean {
1287
+ switch (step.step) {
1288
+ case 'operation':
1289
+ return performPresetOperation(step.operation)
1290
+ case 'viewpoint':
1291
+ if (!allPeople.some((p) => p.id === step.personId)) return false
1292
+ selectPerson(`person:${step.personId}`)
1293
+ return true
1294
+ case 'loaded':
1295
+ // The steps' own notices (new mail, inbound filed…) would bury the one that matters.
1296
+ setNotices([])
1297
+ pushNotice(tSimulator('noticePresetLoaded', { name: step.title }))
1298
+ return true
1299
+ }
1300
+ }
1301
+
1302
+ useEffect(() => {
1303
+ if (!replay) return
1304
+ // One step per commit (see applyPreset), run off a zero-delay timer: each step's own state updates
1305
+ // commit before the next one runs, and the cleanup means an abandoned queue (a reset mid-replay)
1306
+ // never fires a stale step. The step reads the world through the render that queued it, so a commit
1307
+ // landing between that render and the timer (an actor's tick) is one commit ahead of what the step
1308
+ // READS; its writes are functional updates and stay safe. No actor today creates anything a step
1309
+ // reads (an invite, a ticket) — if one ever does, hold the actors during a replay.
1310
+ const id = setTimeout(() => {
1311
+ const [step, ...rest] = replay
1312
+ const performed = step === undefined || performReplayStep(step)
1313
+ // A step the world cannot perform abandons the rest, like the server replay's throw — and SAYS
1314
+ // so: the world underneath is reset-plus-partial, which must not pass for the preset. The name
1315
+ // comes from the queue's own closing step.
1316
+ const done = !performed || rest.length === 0
1317
+ if (!performed) {
1318
+ const title = rest.find((pending) => pending.step === 'loaded')
1319
+ pushNotice(tSimulator('noticePresetFailed', { name: title?.step === 'loaded' ? title.title : '' }))
1320
+ }
1321
+ setReplay(done ? null : rest)
1322
+ if (done) {
1323
+ replayDone.current?.(performed)
1324
+ replayDone.current = null
1325
+ }
1326
+ }, 0)
1327
+ return () => clearTimeout(id)
1328
+ // Keyed on the queue alone: the step functions are re-created every render by design.
1329
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1330
+ }, [replay])
1331
+
1332
+ return {
1333
+ route,
1334
+ person,
1335
+ activeOrgSlug,
1336
+ setActiveOrgSlug,
1337
+ tenant,
1338
+ org,
1339
+ name,
1340
+ allPeople,
1341
+ // Orgs this person belongs to (drives the OrgSwitcher) — orgs never span tenants, so this
1342
+ // never crosses the person's own ambient site.
1343
+ orgsForActivePerson: person
1344
+ ? organizations.filter((o) => person.memberships.some((m) => m.orgSlug === o.slug))
1345
+ : [],
1346
+ roleInOrg,
1347
+ signIn,
1348
+ signOut,
1349
+ saveProfile,
1350
+
1351
+ blockingAgreement,
1352
+ advisoryAgreements,
1353
+ acceptAgreement,
1354
+
1355
+ logEvent,
1356
+ logAudit,
1357
+ pushNotice,
1358
+
1359
+ enqueueWebhook,
1360
+ notifyAdminsOf,
1361
+ notifyMemberOf,
1362
+
1363
+ jobs,
1364
+ jobCounts: {
1365
+ queued: jobs.filter((job) => job.status === 'queued').length,
1366
+ running: jobs.filter((job) => job.status === 'running').length,
1367
+ completed: jobs.filter((job) => job.status === 'completed').length,
1368
+ },
1369
+ startJob,
1370
+ serviceDriver,
1371
+ builderDriver,
1372
+
1373
+ invites,
1374
+ inviteError,
1375
+ sendInvite,
1376
+ acceptInvite,
1377
+
1378
+ notifications,
1379
+ notifPrefs,
1380
+ markNotificationsRead: () =>
1381
+ setNotifications((prev) =>
1382
+ prev.map((n) =>
1383
+ n.recipientPersonId === person?.id && n.readAt === null
1384
+ ? { ...n, readAt: new Date().toISOString() }
1385
+ : n,
1386
+ ),
1387
+ ),
1388
+ toggleNotifPref: (kind, channel, enabled) => {
1389
+ const key = `${person?.id ?? ''}:${activeOrgSlug}`
1390
+ setNotifPrefs((prev) => {
1391
+ const rows = (prev[key] ?? []).filter((r) => !(r.kind === kind && r.channel === channel))
1392
+ return { ...prev, [key]: [...rows, { kind, channel, enabled }] }
1393
+ })
1394
+ },
1395
+
1396
+ endpoints,
1397
+ newWebhookSecret,
1398
+ dismissNewWebhookSecret: () => setNewWebhookSecret(null),
1399
+ createEndpoint: ({ url, eventKinds }) => {
1400
+ const id = crypto.randomUUID()
1401
+ const secret = makeWebhookSecret()
1402
+ setEndpoints((prev) => [
1403
+ { id, tenantSlug: tenant.slug, orgSlug: activeOrgSlug, url, secret, eventKinds, enabled: true },
1404
+ ...prev,
1405
+ ])
1406
+ setNewWebhookSecret(secret)
1407
+ logAudit('webhook-endpoint.created', 'WebhookEndpoint', id)
1408
+ },
1409
+ toggleEndpoint: (id, enabled) => {
1410
+ setEndpoints((prev) => prev.map((e) => (e.id === id ? { ...e, enabled } : e)))
1411
+ logAudit(enabled ? 'webhook-endpoint.enabled' : 'webhook-endpoint.disabled', 'WebhookEndpoint', id)
1412
+ },
1413
+ deleteEndpoint: (id) => {
1414
+ setEndpoints((prev) => prev.filter((e) => e.id !== id))
1415
+ // Deliveries cascade with their endpoint (migration 0010's ON DELETE CASCADE).
1416
+ setDeliveries((prev) => prev.filter((d) => d.endpointId !== id))
1417
+ logAudit('webhook-endpoint.deleted', 'WebhookEndpoint', id)
1418
+ },
1419
+
1420
+ agreements,
1421
+ acceptances,
1422
+ bumpAgreement,
1423
+
1424
+ notices,
1425
+ people: peopleRows,
1426
+ viewpoint,
1427
+ personEmail,
1428
+ selectPerson,
1429
+ mail: {
1430
+ scoped: scopedEmails,
1431
+ scope: personEmail ? mailScope : 'all',
1432
+ setScope: setMailScope,
1433
+ allCount: emails.length,
1434
+ seenAt: viewpoint ? (mailSeenAt[viewpoint] ?? null) : null,
1435
+ markSeen: markMailSeen,
1436
+ openLink: openMailLink,
1437
+ copyLink: copyMailLink,
1438
+ clear: clearMail,
1439
+ },
1440
+ inbound,
1441
+ inboundDomain: DEMO_INBOUND_DOMAIN,
1442
+ inboundOrgs: organizations.map((o) => ({ slug: o.slug, name: o.name, tenantSlug: o.tenantSlug })),
1443
+ inboundHandlerSlugs: Object.keys(inboundHandlers),
1444
+ composeInbound,
1445
+ smsMessages,
1446
+ events,
1447
+ auditEntries,
1448
+ schedules,
1449
+ jobsHeld: flags['jobs-held'] ?? false,
1450
+ runPendingJobs,
1451
+ clock: {
1452
+ offsetMs: clockOffsetMs,
1453
+ worldNowIso: new Date(mountedAtMs + clockOffsetMs).toISOString(),
1454
+ advance: advanceClock,
1455
+ reset: resetClock,
1456
+ runDue: runDueSchedulesNow,
1457
+ },
1458
+ deliveries,
1459
+ failingEndpointIds: [...failingEndpoints],
1460
+ toggleEndpointFailure: (endpointId, failing) => {
1461
+ setFailingEndpoints((prev) => {
1462
+ const next = new Set(prev)
1463
+ if (failing) next.add(endpointId)
1464
+ else next.delete(endpointId)
1465
+ return next
1466
+ })
1467
+ pushNotice(failing ? tSimulator('noticeHookFailOn') : tSimulator('noticeHookFailOff'))
1468
+ },
1469
+ runDueDeliveriesNow: () => {
1470
+ const delivered = runDueDeliveries(mountedAtMs + clockOffsetMs)
1471
+ pushNotice(tSimulator('noticeHooksDelivered', { count: delivered }))
1472
+ },
1473
+ actorHolds,
1474
+ featureFlags: Object.keys(INITIAL_FLAGS).map((flag) => ({ flag, enabled: flags[flag] ?? false })),
1475
+ setFeatureFlag: (flag, enabled) => setFlags((prev) => ({ ...prev, [flag]: enabled })),
1476
+ demoBannerOn: flags['demo-banner'] ?? false,
1477
+ resetWorld,
1478
+ applyPreset,
1479
+ }
1480
+ }