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