create-ailk 0.14.0 → 0.16.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 (184) hide show
  1. package/README.md +124 -0
  2. package/component-catalog.json +3 -3
  3. package/dist/add-module.d.ts +7 -0
  4. package/dist/add-module.js +80 -3
  5. package/dist/add-route.js +26 -2
  6. package/dist/adopt.d.ts +74 -0
  7. package/dist/adopt.js +314 -0
  8. package/dist/apply-design.d.ts +12 -1
  9. package/dist/apply-design.js +36 -4
  10. package/dist/cli.js +103 -3
  11. package/dist/derive-architecture.d.ts +37 -2
  12. package/dist/derive-architecture.js +92 -7
  13. package/dist/design-package.js +3 -2
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/lib/chrome-readers.d.ts +21 -0
  17. package/dist/lib/chrome-readers.js +100 -0
  18. package/dist/lib/declared-env.d.ts +142 -0
  19. package/dist/lib/declared-env.js +985 -0
  20. package/dist/lib/env-catalog.d.ts +17 -0
  21. package/dist/lib/env-catalog.js +234 -0
  22. package/dist/lib/extract-module-bundle.d.ts +20 -0
  23. package/dist/lib/extract-module-bundle.js +53 -6
  24. package/dist/lib/license-key-files.d.ts +6 -1
  25. package/dist/lib/license-key-files.js +9 -4
  26. package/dist/lib/module-tier.d.ts +2 -0
  27. package/dist/lib/module-tier.js +4 -0
  28. package/dist/module-architecture.d.ts +9 -0
  29. package/dist/module-architecture.js +82 -0
  30. package/dist/parse-args.d.ts +27 -0
  31. package/dist/parse-args.js +89 -0
  32. package/dist/programmatic.d.ts +28 -0
  33. package/dist/programmatic.js +181 -11
  34. package/dist/seed-flows.d.ts +65 -0
  35. package/dist/seed-flows.js +350 -0
  36. package/dist/site-chrome.d.ts +4 -0
  37. package/dist/site-chrome.js +34 -3
  38. package/dist/site-manifest.d.ts +55 -5
  39. package/dist/site-manifest.js +121 -12
  40. package/dist/site-roster.d.ts +13 -0
  41. package/dist/site-roster.js +22 -8
  42. package/dist/spoke-checkout.d.ts +42 -0
  43. package/dist/spoke-checkout.js +359 -0
  44. package/dist/surfaces.js +7 -0
  45. package/dist/sync-routes.js +29 -5
  46. package/dist/topology.d.ts +246 -0
  47. package/dist/topology.js +942 -0
  48. package/package.json +3 -3
  49. package/site-templates/designs/minimalism/DESIGN.md +3 -3
  50. package/templates/.env.example +10 -0
  51. package/templates/apps/api/CLAUDE.md +21 -4
  52. package/templates/apps/api/package.json +1 -0
  53. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +5 -1
  54. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +95 -16
  55. package/templates/apps/api/src/__tests__/openapi-keyless-hub.test.ts +122 -0
  56. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +362 -0
  57. package/templates/apps/api/src/bin/spokes.ts +62 -1
  58. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +75 -0
  59. package/templates/apps/api/src/config/index.ts +35 -0
  60. package/templates/apps/api/src/lib/__mocks__/prisma.ts +99 -0
  61. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +114 -1
  62. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +66 -5
  63. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +209 -0
  64. package/templates/apps/api/src/lib/__tests__/site.test.ts +54 -0
  65. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +20 -0
  66. package/templates/apps/api/src/lib/agent-store.ts +95 -3
  67. package/templates/apps/api/src/lib/deliverable-asset-store.ts +24 -5
  68. package/templates/apps/api/src/lib/hub-sign-in-store.ts +419 -0
  69. package/templates/apps/api/src/lib/site.ts +37 -0
  70. package/templates/apps/api/src/lib/spoke-store.ts +41 -3
  71. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +4 -0
  72. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +310 -0
  73. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +22 -0
  74. package/templates/apps/api/src/middleware/auth.ts +129 -0
  75. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +23 -0
  76. package/templates/apps/api/src/openapi/spec.ts +38 -2
  77. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +483 -0
  78. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +201 -0
  79. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +50 -2
  80. package/templates/apps/api/src/routes/checkout/sessions.ts +7 -0
  81. package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +282 -0
  82. package/templates/apps/api/src/routes/leads/index.ts +69 -6
  83. package/templates/apps/api/src/routes/webhooks/README.md +39 -0
  84. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +105 -0
  85. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +366 -0
  86. package/templates/apps/api/src/routes/webhooks/stripe.ts +133 -2
  87. package/templates/apps/api/src/server.ts +105 -0
  88. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +4 -4
  89. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +854 -0
  90. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +492 -0
  91. package/templates/apps/api/src/services/__tests__/person.test.ts +553 -0
  92. package/templates/apps/api/src/services/default-tenant.ts +41 -7
  93. package/templates/apps/api/src/services/hub-sign-in.ts +471 -0
  94. package/templates/apps/api/src/services/lead-routing.ts +278 -30
  95. package/templates/apps/api/src/services/person.ts +541 -0
  96. package/templates/apps/api/src/services/public-site-resolver.ts +48 -0
  97. package/templates/apps/mcp/__tests__/index.test.ts +5 -5
  98. package/templates/apps/mcp/src/index.ts +6 -4
  99. package/templates/apps/mcp/src/lib/content-adapter.ts +2 -2
  100. package/templates/apps/mcp/src/lib/topology.generated.ts +24 -0
  101. package/templates/apps/web/.env.example +58 -5
  102. package/templates/apps/web/CLAUDE.md +1 -0
  103. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -0
  104. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +206 -0
  105. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +256 -3
  106. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +5 -8
  107. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +205 -0
  108. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +82 -0
  109. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +98 -29
  110. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +6 -3
  111. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +19 -101
  112. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +90 -0
  113. package/templates/apps/web/app/[locale]/[slug]/[detail]/__tests__/page.test.tsx +3 -0
  114. package/templates/apps/web/app/[locale]/[slug]/__tests__/page.test.tsx +3 -0
  115. package/templates/apps/web/app/[locale]/contact/__tests__/page-renderer-migration.test.tsx +66 -14
  116. package/templates/apps/web/app/[locale]/contact/__tests__/site-contact-lines.test.ts +105 -11
  117. package/templates/apps/web/app/[locale]/contact/site-contact-lines.ts +12 -8
  118. package/templates/apps/web/app/[locale]/layout.tsx +83 -18
  119. package/templates/apps/web/app/[locale]/newsletter/__tests__/page.test.tsx +3 -0
  120. package/templates/apps/web/app/[locale]/projects/__tests__/page-renderer-migration.test.tsx +5 -2
  121. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/page.test.tsx +3 -0
  122. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +295 -0
  123. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +156 -0
  124. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +341 -0
  125. package/templates/apps/web/app/api/hub-session/callback/route.ts +168 -0
  126. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +76 -0
  127. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +63 -0
  128. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +104 -1
  129. package/templates/apps/web/app/openapi.json/route.ts +72 -7
  130. package/templates/apps/web/auth.ts +29 -2
  131. package/templates/apps/web/components/sign-out-trigger.tsx +20 -1
  132. package/templates/apps/web/components/signed-in-nav.tsx +17 -3
  133. package/templates/apps/web/instrumentation.ts +7 -4
  134. package/templates/apps/web/lib/__tests__/account-config.test.ts +5 -2
  135. package/templates/apps/web/lib/__tests__/closing-footer-path.test.ts +96 -0
  136. package/templates/apps/web/lib/__tests__/listings-config.test.ts +83 -0
  137. package/templates/apps/web/lib/__tests__/listings.test.tsx +49 -0
  138. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +49 -1
  139. package/templates/apps/web/lib/__tests__/relay.test.ts +317 -0
  140. package/templates/apps/web/lib/__tests__/site-brand.test.ts +52 -0
  141. package/templates/apps/web/lib/account-config.ts +130 -1
  142. package/templates/apps/web/lib/api-origin.generated.ts +11 -0
  143. package/templates/apps/web/lib/closing-footer-path.ts +50 -0
  144. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +262 -0
  145. package/templates/apps/web/lib/hub-session/config.ts +104 -0
  146. package/templates/apps/web/lib/hub-session/index.ts +23 -0
  147. package/templates/apps/web/lib/hub-session/seal.ts +82 -0
  148. package/templates/apps/web/lib/hub-session/session.ts +180 -0
  149. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +79 -0
  150. package/templates/apps/web/lib/listings-config.ts +31 -0
  151. package/templates/apps/web/lib/listings.tsx +7 -3
  152. package/templates/apps/web/lib/meeting-slugs.ts +11 -1
  153. package/templates/apps/web/lib/next-path.ts +35 -0
  154. package/templates/apps/web/lib/relay.ts +209 -3
  155. package/templates/apps/web/lib/server-api.ts +11 -1
  156. package/templates/apps/web/lib/site-brand.tsx +22 -1
  157. package/templates/apps/web/lib/site-chrome.ts +3 -0
  158. package/templates/apps/web/lib/topology.generated.ts +33 -0
  159. package/templates/apps/web/messages/en.json +32 -3
  160. package/templates/apps/web/package.json +1 -1
  161. package/templates/database/CHANGELOG.md +51 -0
  162. package/templates/database/__tests__/agents.db.test.ts +85 -0
  163. package/templates/database/__tests__/fixtures/person-backfill.json +264 -0
  164. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +92 -0
  165. package/templates/database/__tests__/member-area.db.test.ts +245 -0
  166. package/templates/database/__tests__/person.db.test.ts +584 -0
  167. package/templates/database/auth/schema.prisma +24 -0
  168. package/templates/database/config/schema.prisma +13 -0
  169. package/templates/database/inbox/schema.prisma +111 -0
  170. package/templates/database/jest.config.cjs +7 -11
  171. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +35 -0
  172. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +20 -0
  173. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +33 -0
  174. package/templates/database/migrations/20261010120000_person/migration.sql +106 -0
  175. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +132 -0
  176. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +20 -0
  177. package/templates/database/migrations/20261011120000_member_area/migration.sql +158 -0
  178. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +21 -0
  179. package/templates/database/package.json +1 -1
  180. package/templates/database/scripts/person-backfill.sql +132 -0
  181. package/templates/database/tenancy.ts +53 -0
  182. package/templates/tools/check-declared-env.ts +37 -0
  183. package/templates/tools/declared-env.ts +1163 -0
  184. package/versions.json +35 -34
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-ailk",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Scaffolder for AI Launch Kit — `pnpm create ailk@latest <dir>` produces a starter repo consuming @working-theory/* from npm (per ADR 0007).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,8 +27,8 @@
27
27
  "tar": "^7.5.21"
28
28
  },
29
29
  "devDependencies": {
30
- "@working-theory/schema": "0.36.0",
31
- "@working-theory/templates": "0.36.0"
30
+ "@working-theory/schema": "0.38.0",
31
+ "@working-theory/templates": "0.38.0"
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",
@@ -325,7 +325,7 @@ Copy density: sparse — minimalism pages carry far fewer words than a standard
325
325
 
326
326
  <!-- generated:end -->
327
327
 
328
- Square corners everywhere (`theme.corners: square`) — buttons, cards, the auth card, image placeholders; the tokens above are the base foundation's defaults a site overrides.
328
+ Square corners everywhere (`theme.corners: square`) — cards, the auth card, image placeholders; the tokens above are the base foundation's defaults a site overrides.
329
329
 
330
330
  ## Components
331
331
 
@@ -354,7 +354,7 @@ Mark-only: no link row. On the deck home the header is bare: no bar, no rule and
354
354
 
355
355
  ### Footer
356
356
 
357
- On the deck home the footer is the deck's closing slide (#7742): one viewport tall with its content centred, the wordmark (an image wordmark at the display size), at most two contact lines and one muted legal line (copyright, Privacy, Terms, Cookie settings, FAQ), and an up-chevron button at its foot that returns to the first slide. No nav links, social icons, theme switch, language switcher or Sign in / Sign up. Every other page ends in one bar: the copyright, the legal links and Sign in / Sign up (the Account link when signed in). The cookie banner sits on the page ground with a hairline above it and no shadow, and the deck's chevron rises above it while it shows.
357
+ On the deck home the footer is the deck's closing slide (#7742): one viewport tall with its content centred, the wordmark (an image wordmark at the display size), at most two contact lines and one muted legal line (copyright, Privacy, Terms, Cookie settings, FAQ), up to two actions (the first a button, the second a text link: the closing slide's exception to the home-slide one-button rule, capped there; a third is not shown), and an up-chevron button at its foot that returns to the first slide. No nav links, social icons, theme switch, language switcher or Sign in / Sign up. Every other page ends in one bar: the copyright, the legal links and Sign in / Sign up (the Account link when signed in). The cookie banner sits on the page ground with a hairline above it and no shadow; its Accept is a text link beside the Decline, not a button, so the one-button rule holds. On the deck home it waits for the first slide to leave view (slide 1 is a clean landing) and first shows on slide 2, where the deck's chevron rises above it; on every other page it shows on load.
358
358
 
359
359
  ### Index and profile pages
360
360
 
@@ -366,7 +366,7 @@ The foundation's pinned direction is the pacing of a classic wireframe marketing
366
366
 
367
367
  | Trait | How it is set |
368
368
  | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
369
- | Square corners on buttons, cards and inputs | `theme.corners: square` in `_site.mdx` |
369
+ | Square corners on cards and inputs | `theme.corners: square` in `_site.mdx` |
370
370
  | Section label in sentence case, no tracking | `theme.eyebrowCase: sentence` |
371
371
  | Solid grey image placeholders, no outline | `theme.placeholders: fill` |
372
372
  | Bare check and cross marks, no circle badge | `theme.checkmarks: plain` |
@@ -552,6 +552,16 @@ CONTENT_ADAPTER=mdx
552
552
  # hub cannot yet tell whether it is a hub.
553
553
  # AILK_HUB_REQUIRE_SPOKE_KEY=
554
554
  #
555
+ # HUB (apps/api). Off unless set (#7876). `true` (or `1`) lets a registered
556
+ # spoke key write its OWN workspace's flow definitions through
557
+ # PUT /v1/flows/:slug/definition — what `create-ailk seed-flows` sends from a
558
+ # spoke's flows/ directory. Only the blocks a spoke's own flow pages render
559
+ # are accepted; emails, deliverables, pricing, registers and listings are
560
+ # refused. It warns at every boot while on. Any value other than true, 1,
561
+ # false, 0 or unset stops the API at boot. Runbook:
562
+ # docs/runbooks/site-configuration.md § Seeding a spoke's flows.
563
+ # AILK_SPOKE_FLOW_SEED=
564
+ #
555
565
  # SPOKE (apps/web and apps/mcp, server-only — never NEXT_PUBLIC_). The key the
556
566
  # hub's `spokes register` printed. Sent as `x-ailk-spoke-key` on every
557
567
  # server-side call to AILK_API_URL, and only when that is https (or
@@ -40,12 +40,14 @@ Routes are versioned under `/v1/*`:
40
40
  - `/v1/leads/capture` (GET) — `{ ok: true, data: { contact, newsletter } }`, two booleans saying whether a submit / a subscribe would be accepted (#6730). The web contact page reads it to show the form or the site's contact email. Never names the delivery mode, an address or an env var. Registered at the top level, outside `leadsScope`'s strict per-IP limit. No MCP twin — a recorded exception on the same footing as the anonymous form-lifecycle routes: an agent needs no preflight, because the three lead-write tools already return the 503 when capture is not accepted.
41
41
  - `/v1/leads` (GET, `?cursor=&limit=`) — the leads INBOX read (#5678): the caller's OWN sites' leads, newest first, cursor-paginated (`limit` defaults to 50, max 200; `(createdAt desc, id desc)`; `cursor` is the previous page's last row id, and one that does not resolve within the caller's scope is a 400, never a silent page 1 — the API keeps that contract, and the web inbox deliberately softens it on its own side by re-reading page one when a URL-supplied cursor 400s, which is a rendering choice and not a change to this response). Five fields per row and nothing more — `id`, `name` (lifted from `payload.name` when the site's form captured one), `email`, `source`, `createdAt`; `payload`'s other keys, `siteId`, `promotedUserId` and `promotedAt` are never selected (`src/services/leads-inbox.ts` is the only read path). Registered in `authScope` only (auth, no tenant guard) and — alone in that scope — **unconditionally**, with no `isModuleEnabled()` gate: lead capture is a never-gate surface at every level, so reading a lead back cannot be gated either. Identity is `request.userId`; there is no site, org or workspace parameter, so the scope cannot be widened from the wire. It is resolved from the caller's own memberships by `src/services/owner-workspaces.ts`'s `resolveOwnerWorkspaces` — the ONE site→workspace resolution in this app, shared with `lead-promotion.ts` rather than written a second time — and every read filters `siteId ∈ workspaceIds`. Role floor: the `inbox-read` permission in `@working-theory/validation`'s permission table (#7636 D2) — every role, a member included (the operator's 2026-10-04 decision; contact PII is the inbox's job); the scope is the UNION of every workspace in the caller's organizations whose role holds `inbox-read`, not one active tenant, because this route registers outside the tenant scope. **Two deployment preconditions decide whether it returns anything, and both fail EMPTY rather than wide:** on a build with no `multi-tenant` module `resolveOwnerWorkspaces` resolves none (a deliberate scope limit since #5677), so there the scope is the default workspace, granted only through `services/default-tenant.ts`'s `resolveDefaultTenantForOperator` — `AILK_OPERATOR_EMAIL` set, the caller's verified email equal to it, a one-workspace deployment, a role holding `inbox-read` — and every other caller gets the empty page (#6730); and the `siteId` the leads were WRITTEN under must equal a workspace id. That `siteId` has TWO sources, and `currentSiteId()` is not the one on the primary path: the three POST capture routes read it from the REQUEST BODY (`routes/leads/index.ts`), which the capture sections declare in content and default to `"default"` (`ContactForm`/`Newsletter`/`StepFlow`, `ext.siteId ?? "default"`), while the recommender's capture path (`routes/flows/recommender.ts`) is the one that uses `currentSiteId()` (`lib/site.ts`, `AILK_SITE_ID ?? "default"`). A workspace id is `wksp_<uuidv7>`, so `siteId ∈ workspaceIds` matches only when the content-declared value — and, for recommender leads, `AILK_SITE_ID` — is set to it (the same convention `waitlist-dashboard.ts` already relies on). The rendered `name` is lifted from `payload.name` and truncated at 200 characters: the write side bounds `payload` at 64 keys and no per-value length, and `POST /v1/leads/submit` is anonymous with no ownership check on `siteId`. No MCP twin — identity-bound (#3591 exception, the same shape as `/v1/workspaces/*` and `/v1/billing/*`).
42
42
  - `/v1/flows/:slug` (GET), `/v1/flows/:slug/steps` (POST) — serve a flow config + submit a step's answers; server-side per-step partial-state persistence (#3956). The GET serves the stored config **minus `completionEmail`** (#7519 D5, SEC-7519-I1): `serveFlow` projects the owner's completion-email copy out, while completion reads the stored snapshot and sends it (`sendCompletionEmail`, for a flow with no `deliverables`). Module: `signal-collectors` (D-48, #5366) — registers only when the module is enabled; MCP twins `get_flow`/`submit_flow_step` carry the same `module` tag (D7).
43
+ - `/v1/flows/:slug/definition` (PUT) — a registered spoke seeds one of its declared `flows/<slug>.json` into its OWN workspace (#7876, `src/routes/flows/index.ts` over `services/flow-engine.ts`'s `seedDeclaredFlow`). No MCP twin — recorded exception: a seed is a deploy-time write by the site's owner, and a spoke's `apps/mcp` acts through the same key for every anonymous agent, so a twin would give each of them write access to the site's flows. Off until the hub's operator sets `AILK_SPOKE_FLOW_SEED` (`403 flow_seed_disabled`, answered before the key or the database is read). The workspace comes from the `x-ailk-spoke-key` alone, through `resolveCallerSite`: a keyless call is `403 spoke_key_required` on any deployment, and a refused key `503 tenant_unresolved`. The body is a flow config of `slug`, `defaultLocale`, `steps`, `thankYou` and `flags` only — every block the hub acts on outside the spoke's own pages (emails, deliverables, pricing, registers, listings) is `400 field_not_seedable`; a slug a listing owns, or a stored config the Admin extended with one of those blocks, is `409 slug_owned`, so a seed never deletes them. A config equal to the stored one (keys sorted) answers `unchanged` and writes nothing; otherwise `created` or `updated` through `upsertFlowDefinition`, so `kind`, `title` and `status` are written on create only. Route-level `bodyLimit` 256 KiB; the config is never echoed or logged. Module: `signal-collectors`.
43
44
  - `/v1/flows/:slug/aggregate` (GET) — anonymous, site-scoped per-question response counts across all completed respondents for the results reveal (#4771): respondents are completed `FlowSession` rows (not `Lead` rows — a recommending-mode respondent has no Lead until the email moment), question metadata + the chart flag come from the `WaitlistExperiment` register, and only `resultsReveal`-flagged `single`/`multi` questions are returned (`src/services/flow-aggregate.ts`). No individual answer, email, name, session id, or score in the response; no auth. Module: `signal-collectors`. No MCP twin — recorded exception (an agent walking a flow already gets everything it needs from `submit_flow_step`'s own response; "how everyone else answered" changes none of it).
44
45
  - `/v1/deliverables/:grantId` (GET) — the capability-token download route for gated PDFs and reports, including client deliverables (#3961 D5); the token itself is the sole gate, no auth preHandler applies (`src/routes/deliverables/index.ts`). Module: `signal-collectors` (D-48, #5366). No MCP twin — identity-bound capability-link download (#3591 exception, the same shape as `/v1/waitlist-signups/me`). **Three grant classes since #6310**, keyed on `grant.assetId`'s ADR-0031 prefix: `playbook:` (unchanged, the FEAT-074 U4b virtual asset); `asset_` — a workspace `Asset`, resolved through the named boundary `src/lib/deliverable-asset-store.ts`, scoped by `grant.workspaceId` (a serve-time tenancy re-check restored for this class — D15) — served `attachment` with an extension pinned to the stored content type, `nosniff`, a non-raster `Content-Security-Policy` (for EVERY content type, including raster — never `inline`), and `Cache-Control: private, no-store` so a deleted asset stops downloading immediately; `dasset_` — the LEGACY `DeliverableAsset` store (unchanged, tried only when a magnet's `assetKey` does not resolve against `Asset`). Every miss on the `asset_` class — a NULL `workspaceId`, no row, a foreign-workspace row — folds into the SAME uniform 404 as every other class; there is deliberately no redirect to the public `GET /v1/assets/:assetId` (that route's year-long `immutable` cache would defeat deletion as a revocation lever, and would collapse every lead's capability onto one workspace-canonical id — spec #6310 §9 SEC-001/SEC-002).
45
46
  - `/v1/flows/:slug/save` (POST), `/v1/flows/:slug/checkout` (POST) — the recommender's email moment (#4841): `save` creates the FlowSession + Lead (+ the T+0 DeliverableGrant) for the permalink's answers; `checkout` does the same, records the `FlowCheckout` buyer row at a SERVER-recomputed `price()` (the body carries no amount — `flowCheckoutInputSchema` is strict), and opens a Stripe TEST-mode Checkout Session whose metadata carries the permalink + offer key (`src/routes/flows/recommender.ts`, `src/services/recommender-capture.ts`, `packages/stripe-client`'s `createQuotedCheckoutSession`). Anonymous, rate-limited; a non-`sk_test_` key is refused before any side effect. No MCP twin — recorded exception: an agent walking a flow has no email to give and no card to pay with; the anonymous MCP surface is identity-blind.
46
47
  - `/v1/workspaces/:workspaceId/magnets` (GET, POST), `/v1/workspaces/:workspaceId/magnets/:id` (GET, PATCH), `/v1/workspaces/:workspaceId/magnets/:id/signups` (GET), `/v1/workspaces/:workspaceId/magnets/:id/subscribers` (GET), `/v1/workspaces/:workspaceId/magnets/:id/messages` (GET) — the tenant-scoped magnet Admin authoring surface over the flow engine's `FlowDefinition` rows (#6157 S5c, `src/routes/magnets/index.ts`): list (cursor-paginated, fixed 50-row page), create, get, update, and the three per-magnet captured-lead reads (#6246 S6h). Reads and writes only through `tenantDb(tenant).flows` — never `prisma.flowDefinition`, `currentSiteId()`, or `upsertFlowDefinition` (the PUBLIC/seed path below, which the admin path never calls). No DELETE — the reversible alternative is `status: "draft"` (#6156), which stops a NEW walk from starting while an in-flight walk finishes on its pinned snapshot. `slug` lives only inside `config.slug` and is immutable through this surface after create (`400 slug_immutable` on a mismatched PATCH). The two operator-writable config URLs (`abandonEmail.resumeUrl`, `followUps[].cta.href`) pass an exact-origin gate against `FRONTEND_URL` before any write, the same discipline the recommender's checkout redirect already applies (#4912). Role floors from `@working-theory/validation`'s permission table (#7636 D2) (D5): list and get serve the full row to `magnets-manage` (owner, admin) and, to a caller holding only `magnets-read` (a member), a LIVE-only summary of exactly `{ id, slug, kind, title, landingPage }` — a member's list is read to completion (at most 20 pages of 50, a `warn` at the cap) and answers `nextCursor: null`, a member's `?cursor=` is a 400, and a draft's get is the same 404 as an absent id — because a magnet's `config` carries `scoring` thresholds, `offers`/`rateTable` and `deliverables` asset keys and no draft is a member's; POST and PATCH need `magnets-manage`; the per-magnet captured-people lists need `inbox-read` (every role), and for a caller without `magnets-manage` a magnet that is not live is the same 404. Both writes declare a route-level `bodyLimit` (256 KiB) and each records one `recordAgentAction` audit row. Module: `multi-tenant || signal-collectors`, the same gate the review-surface dashboard (`/v1/waitlist-experiments/*`, `/v1/project-listings/*`) already registers under. No MCP twin on any of the seven — identity-bound tenant routes (#3591 exception, same shape as the sibling `/v1/workspaces/*` routes); the public `/v1/flows/*` routes and their two MCP tools are unchanged, pinned by `src/routes/flows/__tests__/parity.test.ts`. **The three new list routes (#6246 S6h)** join every magnet through `Lead.source = 'flow:' + <the resolved magnet's slug>` — the literal string `flow-engine.ts`'s `completeSubmission` stamps on every flow-engine `Lead` row regardless of kind, including `newsletter`/`waitlist` (`Subscriber` is written only by the separate, pre-flow-engine `subscribe_newsletter` path, unrelated to a magnet) — via ONE new `tenantDb(tenant).leads.listBySource(source, { limit })` accessor, an exact-source-equality sibling of #6204's allowlist-scoped `listUnhandledMessages`, served by a new `(workspaceId, source)` composite index on `Lead`. `/signups` expects `kind: "waitlist"`, `/subscribers` expects `"newsletter"`, `/messages` expects `"contact"`; a magnet id absent from the caller's workspace OR resolved to the WRONG kind for the called route is `404 not_found`, indistinguishably (mirrors the existing GET's absent-or-foreign fold). `/signups` and `/subscribers` serve four keys (`id`, `name`, `email`, `createdAt`); `/messages` serves those four plus `handledAt`. Bounded `?limit=` (default 50, max 200), newest-first — mirrors `workspaces/messages.ts`'s own query schema. Applications (Listicle) is deliberately OUT of this surface — `ProjectListing` carries no reverse link to the listicle-kind `FlowDefinition` that captured it, so "scoped to that magnet" cannot be honored without a schema change (split to #6314).
47
48
  - `/v1/content/{types,:type,:type/:slug}` — public content reads
48
49
  - `/v1/auth/tokens`, `/v1/user/{profile,data/:key}` — local auth + user data
50
+ - `/v1/hub-sign-in/codes` (POST), `/v1/hub-sign-in/token` (POST), `/v1/hub-sign-in/revoke` (POST), `/v1/hub-sign-in/me` (GET) — the hub signs in its spokes (#7894, `src/routes/auth/hub-sign-in.ts` over `src/services/hub-sign-in.ts`; spec `docs/specs/7894-the-hub-signs-in-its-spec.md`): an authorization code with PKCE between a spoke (a confidential client whose `OAuthClient.clientId` IS its `Spoke.id`) and this hub. `codes` is in `authScope` and answers a COOKIE session only (a personal `ApiToken` is 403, an agent key 403 at the preHandler, a hub credential 404): it mints a single-use 60 s code only for an email-verified person and a callback in the client's registered `redirectUris` (exact match), 30 a user per 10 minutes. `token` and `revoke` are in their OWN scope outside `authScope` (per-IP `rateLimitMiddleware`, scope `hubsignin`, 60/min; plus a per-client bucket of 120 exchanges a minute keyed on the VERIFIED client): the caller authenticates with `Authorization: Basic clientId:secret` AND `x-ailk-spoke-key`, which must resolve to the unrevoked spoke whose id is that client — either alone is `401 invalid_client`. `token` consumes the code first and exactly once, then checks the client, the callback and the PKCE verifier (`400 invalid_grant` for any failure, the code gone either way) and issues `ailk_hst_…`, a 24 h credential stored only as a SHA-256 digest in `OAuthAuthorization` (one row per person and spoke, so a new sign-in rotates it); it writes no `Session` row and sets no cookie. `revoke` ends a credential or burns an unexpired code of that client (`{ revoked }`, never an error). `me` answers the credential's person, read live, and is reachable only by that credential. **The credential is admitted by one branch of `middleware/auth.ts`** — only beside the same spoke's key, only while its grant is unrevoked and unexpired, its client enabled and its person's email verified, and only on `HUB_SESSION_ROUTES`, an exact list of four method + URL pairs (`GET /v1/hub-sign-in/me` and #7877's `GET /v1/member/{pieces,messages,messages/:id/file}`); every other route answers `404` with no handler run (the status the account area's `read()` loads as "nothing for this caller"), and the list is extended only by a reviewed edit. A completed password reset (`apps/web/auth.ts` `onPasswordReset`) revokes every credential of that person. The operator registers a spoke's client with `spokes sign-in-client --id <spoke_id> --redirect-uri <url>` (`bin/spokes.ts`; `--disable` switches it off) — `lib/hub-sign-in-store.ts` is the only file that names `prisma.oAuthClient` and `prisma.oAuthAuthorization`. No MCP twin for any of the four — a credential exchange between a site and its hub is not an agent-facing call (#3591 exception, the `/v1/auth/tokens` footing). The browser step lives on the hub's web app: `apps/web/app/api/auth/hub/authorize/route.ts`.
49
51
  - `/v1/checkout/sessions` — start a Stripe checkout
50
52
  - `/v1/workspaces/:workspaceId/{theme,identity,seo}` (GET/PUT) — per-workspace site config (multi-tenant module). PUT needs `workspace-settings` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)), checked before the body parse; GET stays open to every member.
51
53
  - `/v1/workspaces/:workspaceId/meetings` (GET/PUT) — the operator's enabled-slug gate for meeting types (#6183 S9b, `src/routes/workspaces/meetings.ts`). Beside the three siblings above in URL shape and tenant-isolation posture, but registered in its OWN scope, gated on `isModuleEnabled("scheduling")` ALONE — not the `workspace`/`multi-tenant` scope its siblings share, because its GET reaches `services/scheduling/` (see below), which a scaffold without that module does not carry (`tools/lint-slice-registration.ts`, #5701). PUT needs `meeting-types-manage` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)) because this blob decides which pages the public site serves. GET answers `meeting-types-manage` with the full join and `meeting-types-read` (every role, a member included) with the ENABLED rows only (#7636 D6) — since it does NOT just return the stored blob, it echoes the deployment's whole provider catalog, including the rows the operator chose not to publish (security review, 2026-09-19), which a member never sees. GET is the one segment in this file's family that does NOT just return the stored blob: it ALSO lists the scheduling provider's own bookable event types (`listEventTypes`, #6182), joined with `enabled: boolean`; an unconfigured/unreachable provider answers the same `SchedulingErrorKind` outcome `/v1/schedule/*` uses, distinct from an empty list. No MCP twin — identity-bound tenant route (#3591 exception).
@@ -54,12 +56,15 @@ Routes are versioned under `/v1/*`:
54
56
  - `/v1/workspaces/:workspaceId/messages` (GET, `?limit=`), `/v1/workspaces/:workspaceId/messages/:leadId` (GET, PATCH) — the Inbox message API (#6216 S7e, `src/routes/workspaces/messages.ts`): the workspace's unhandled messages newest first, the item read (resolves a message handled or not, serving `handledAt`), and the one-way idempotent handled stamp over #6204's `markMessageHandled`. Registered under `isModuleEnabled("workspace") || isModuleEnabled("multi-tenant")`, the same scope as the two routes above. A message is a `Lead` whose `source` is in #6204's closed `MESSAGE_LEAD_SOURCE_LIST` allowlist — checked only in `tenantDb(tenant).leads`, never in this file; a non-message lead is a 404 on the item read and the PATCH and absent from the list, the SAME 404 body as an absent id, another workspace's id, or an unbackfilled `workspaceId`. **One served row across all three routes** — `id`, `name`, `email`, `source`, `createdAt`, `handledAt` — and nothing else: no `payload`, no message body (operator ruling, 2026-09-19; `leads-inbox.ts`'s PII boundary is unchanged, not widened). PATCH takes `{ "handled": true }` only, `.strict()`; there is no un-handle path (#6204 D4), so `{ "handled": false }` is a 400. The stamp records the actor via `tenant.userId` in `Lead.handledBy` — written, not served. Role floor: `inbox-read` on the GETs and `inbox-act` on PATCH and accept (`@working-theory/validation`'s permission table (#7636 D2) — every role, a member included), the SAME rows `services/inbox-messages.ts` re-checks, checked before any read or write. The role is not self-servable: since #7523 `multi-tenant`'s null-binding fallback grants the default tenant only to the pinned, verified operator, the same check the base `workspace`-only guard applies (see the `AILK_OPERATOR_EMAIL` paragraph below). No anonymous MCP twin — identity-bound tenant routes, and the anonymous `/mcp` carries no caller identity. Each route's twin is a signed-in tool on `/mcp/workspace` (#3591 D13), which forwards the caller's agent key here: `list_inbox_messages` (list), `get_inbox_message` (item read), `mark_inbox_message_done` (PATCH) and `accept_inbox_message` (`POST …/:leadId/accept`).
55
57
  - `/v1/workspaces/:workspaceId/submissions` (GET, `?limit=&state=unhandled&magnetId=`), `/v1/workspaces/:workspaceId/submissions/:leadId` (GET, PATCH) — the Inbox submissions API (#7535, `src/routes/workspaces/submissions.ts` over `src/services/inbox-submissions.ts`): every flow completion and waitlist signup of the caller's active workspace, newest first and bounded (`?limit=` 1–200, default 50), the item read (handled or not), and the one-way idempotent handled stamp (`{ "handled": true }` only, `.strict()`; a second PATCH returns the first `handledAt`). Same registration, scope and tenant guard as the messages bullet above. A submission is a `Lead` whose `source` is a fixed submission source (`SUBMISSION_FIXED_SOURCE_LIST` in `@working-theory/validation`) or `flow:<slug>` for a NON-newsletter magnet of THIS workspace — decided only in `tenantDb(tenant).leads`, never in the route; a `flow:` row naming no magnet of the workspace never lists. The list row is seven keys — the message row's six plus `magnet: { slug, title } | null` — and never `payload`. `?magnetId=` narrows to one magnet (limit 1–50) and adds `answers`, `answersTruncated` and `deliverableSentAt` per row; the item read serves the same three. `answers` is `payload` narrowed by `toAnswers`: server-owned keys dropped, control and bidi characters stripped, every key, value and the entry count bounded. `?state=unhandled` filters `handledAt IS NULL` in the query (the Admin's For-you read); any other `state` is a 400. Every miss on the item read and the PATCH — a malformed, absent or foreign id, a message, an application, a newsletter-magnet lead — is the SAME `404 No such submission`; a `?magnetId=` that is absent, foreign or a newsletter magnet is `404 No such magnet`. Every success body is re-parsed against its own `.strict()` schema before it is sent. Role floor: `inbox-read` on the GETs and `inbox-act` on PATCH (`@working-theory/validation`'s permission table (#7636 D2) — every role, a member included), checked before any read or write. The handlers and the service never log a lead id, email, name or answer. No anonymous MCP twin — identity-bound tenant routes. Each route's twin is a signed-in tool on `/mcp/workspace` (#3591 D13): `list_inbox_submissions` (list), `get_inbox_submission` (item read) and `mark_inbox_submission_done` (PATCH).
56
58
  - `/v1/workspaces/:workspaceId/subscribers` (GET, `?limit=`) — the workspace's newsletter signups, read-only (#7535, `src/routes/workspaces/subscribers.ts`): `{ count, items }`, where `count` is every signup and `items` the newest (1–200, default 50), each `{ id, email, source, subscribedAt, magnet: { slug, title } | null }`. A signup is a `Subscriber` row of this workspace or the `Lead` a newsletter-kind magnet of this workspace wrote, both from `tenantDb(tenant).subscribers`, called directly. No item route and no write: a subscriber is never an item to open or mark handled. Same registration, scope, tenant guard and `inbox-read` floor as the submissions bullet above. No MCP twin — identity-bound tenant route (#3591 exception).
59
+ - `/v1/workspaces/:workspaceId/people` (GET, `?limit=&cursor=`), `/v1/workspaces/:workspaceId/people/:personId` (GET) — the workspace's clients (#852, `src/routes/workspaces/people.ts` over `tenantDb(tenant).people`; the Person writer is `src/services/person.ts`). A **Person** is one client of one workspace, keyed on a lowercased, trimmed email unique per workspace and created only by `findOrCreatePerson` — called by lead capture, the hub's own Stripe checkout webhook (a live-mode event's `session.customer` only), appointment creation and the inbox accept; `Person.userId` is stamped only on a verified-email match (`stampPersonUser`), never overwritten. The list serves `{ items, nextCursor }` — five keys per row (`id`, `email`, `name`, `planOffering`, `createdAt`), newest first, `limit` 1–200 (default 50); a cursor that does not resolve to a Person of this workspace is `400 invalid_cursor`. The record serves `{ person, timeline, timelineTruncated }`: the Person (`userId` projected to `hasAccount`, never served; the billing pair served) over a timeline derived at read time — leads and appointments by `personId`, flow sessions, checkouts, deliverable grants and project listings by the Person's newest 200 lead ids, plus an exact-normalized-email fallback for lead-less flow sessions and listings older than the Person backfill, and (since #7877) the Person's member-area messages as `message` entries carrying the subject, `hasFile` and `readAt` only — newest first, at most 50 entries; a malformed, absent or foreign id is one `404 not_found`. Never selected or served: a grant id, a flow-session id, a checkout id, a lead `payload`, a permalink, a Stripe session id, an attendee email, a founder email. Role floor: `people-read` (owner, admin — `@working-theory/validation`'s permission table) via `allows`, checked before any read, so an agent key granted `people-read` (the sixth `AGENT_GRANTABLE_PERMISSIONS` entry, clamped to its person's role) reads both in its one workspace. An operator read only: a Person groups rows by an unverified email, so no client-facing read may key on that grouping (#7877's feed keys on a verified link). Same registration, scope and tenant guard as the routes above (`workspace || multi-tenant`). No MCP twin, by decision — People MCP tools are a later phase of the CRM nucleus (#852 AC 6), recorded in `tests/parity/README.md`.
60
+ - `/v1/workspaces/:workspaceId/people/:personId/pieces` (GET, POST), `…/people/:personId/pieces/:pieceId` (PATCH), `/v1/workspaces/:workspaceId/piece-stages` (GET, PUT), `…/people/:personId/plan` (PUT), `…/people/:personId/messages` (GET, POST) — the member area as an operator keeps it (#7877, `src/routes/workspaces/{pieces,plan,messages-out}.ts` over `tenantDb(tenant).memberArea`; spec `docs/specs/7877-the-member-area-contract-a-spec.md`). A **Piece** is one deliverable for one client: a title (1–200), a **stage** drawn from the workspace's OWN declared list (`WorkspacePieceStages`, one row per workspace; no row is the product default `requested, in-progress, in-review, delivered`, which lives only in `lib/tenant-db.ts`'s `DEFAULT_PIECE_STAGES` — there is no stage enum anywhere), a `needsClient` flag and `updatedBy`. The **plan** is `Person.planOffering` (#852's field — never a Plan model), written only by `services/person.ts`'s `setPersonPlanOffering`. A **message** is an `Interaction` on the `member` channel, direction `outbound`: a plain-text subject (1–200) and body (1–10000), both stripped of control and bidi characters (the body keeps `\n`, `\t`), and an optional attachment that must be an `Asset` of THIS workspace tagged `private` with a raster-image or PDF type (never SVG) — `400 asset_not_found` / `400 asset_not_attachable` otherwise. Both records reference a Person of the same workspace through a composite `(person_id, workspace_id)` foreign key. Role floors from `@working-theory/validation`'s permission table: the two list reads need `people-read`, the stage PUT `workspace-settings`, the stage GET the guard alone, each checked with `can(tenant.role, …)` before any read, so an agent's `people-read` grant does not reach pieces or message bodies; the four writes — piece POST and PATCH, plan PUT, message POST — need `member-pieces-manage` (owner, admin), checked with `allows(tenant, "member-pieces-manage")` before any read, so an agent key granted it (#7878, the seventh `AGENT_GRANTABLE_PERMISSIONS` entry) keeps them in its one workspace, attaching only an asset the message's own checks admit. `people-write` (owner, admin) is never agent-grantable and is no longer read by these routes — the Admin person page reads it to render its forms. A malformed, absent or foreign Person or piece is one `404 not_found`; a stage outside the declared list `400 invalid_stage`; a stage-list PUT that drops a stage a piece still holds `409 stage_in_use` with nothing written — piece writes and stage changes take one per-workspace advisory lock first, in one transaction. Lists hold at most 50 rows, newest first. Every write that reaches the store records one `recordAuditAction` row naming the actor (`people.piece.create`, `people.piece.update`, `people.stages.set`, `people.plan.set`, `people.message.create`); no audit summary or log line carries a title, subject, body or offering. The operator's message read never stamps `readAt`, and serves an attachment by its sanitized download name, never its asset id. **The checkout plan rule:** a `POST /v1/leads/submit` from a registered spoke (`viaSpoke`) whose `Idempotency-Key` is a LIVE Checkout Session id (`cs_live_…`), with `source: "web"`, `payload.page: "checkout"`, a string `payload.offering` and `payload.site`, and an `amountTotal` that is absent, `null` or positive, sets its Person's plan to the offering minus a leading `<site>_` (`services/lead-routing.ts`) — never on a replay, never refusing or changing the lead, and with no spoke change. Same registration, scope and tenant guard as the routes above (`workspace || multi-tenant`). No MCP twin, by decision — member-area MCP tools are a later phase of the CRM nucleus, recorded in `tests/parity/README.md`.
61
+ - `/v1/member/pieces` (GET), `/v1/member/messages` (GET), `/v1/member/messages/:id/file` (GET) — the member reads: a client's OWN pieces and messages, served to the spoke that signed them in (#7877, `src/routes/member/{pieces,messages}.ts`). Registered in `authScope` only (auth, NOT tenant-guarded — a client holds no membership; an agent key is 403 at the preHandler) under the same `workspace || multi-tenant` predicate, at the exact URLs `HUB_SESSION_ROUTES` admits a hub credential on. Who and where come only from `services/member-area.ts`'s `resolveMember`, before any member read: the caller through `middleware/auth.ts`'s `memberCaller` — the hub's own cookie session or a hub credential, never a personal `ApiToken` (`401 { error: "unauthorized" }`); the workspace from the calling spoke's `x-ailk-spoke-key` (a keyless call only on a one-workspace deployment that is not a hub), and a hub credential must name that same workspace, else `503 tenant_unresolved`; an unverified email `403 email_unverified`. The Person is the one linked by `Person.userId`, else the one whose email is the caller's verified email, linked on that first read by `stampPersonUser`'s rule; no Person is `items: []`. Every read goes through the named boundary `src/lib/member-store.ts`, scoped by that resolved workspace AND Person: at most 50 rows, newest first; a message serves `{ id, subject, body, file: { filename, contentType } | null, createdAt, readAt }` — never an asset, creator, person or workspace id — and the first read stamps `readAt` ("shown to the client's spoke", not "read"; served as it stood before the stamp). The file read streams the attachment only when the message is the caller's own and its stored type is attachable — any other case is one `404 not_found` — `attachment` with a sanitized, extension-pinned name, `nosniff`, the sandbox `Content-Security-Policy` and `Cache-Control: private, no-store`. `@working-theory/api-client`'s `member.*` is the spoke's caller; a spoke that re-serves the bytes sends those five headers unchanged. No MCP twin, by decision — identity-bound client reads behind a hub credential; the anonymous MCP surface is identity-blind, recorded in `tests/parity/README.md`.
57
62
  - `/v1/workspaces/:workspaceId/members` (GET) — the org's member roster (`userId`, `name`, `email`, `role`), the Pro `workspace` module's Team tab (#5371). Read-only by design: granting a Membership is the invite flow, which is its own spec with a mandatory security review (§2.3), so no POST/PUT/DELETE is routed at this path. Scoped to `request.tenant.organizationId` — Membership is org-level — server-resolved from the validated session. Role floor: `members-read` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)): the roster carries every member's email, and who the other members are is not a member's job. No MCP twin — identity-bound tenant route (#3591 exception).
58
- - `/v1/workspaces/:workspaceId/agents` (GET `?userId=`, POST), `/v1/workspaces/:workspaceId/agents/:agentId/key` (POST), `/v1/workspaces/:workspaceId/agents/:agentId` (PATCH `{ enabled }`), and `/v1/agent/context` (GET) — the agent seat (#3591, `src/routes/workspaces/agents.ts` over `src/lib/agent-store.ts`, `// oss: false`). An agent is a stored delegate of one person, bound to one workspace. The four management routes refuse an agent caller outright (403), check `agents-manage` (owner, admin) before any read, and scope every read and write to `tenant.organizationId`, never a body or query value; an agent of another organization is the same 404 as a missing one. Create returns 201 with the key shown once; re-key returns the new key once. Each successful create, re-key and switch writes an `agents.*` audit record. `/v1/agent/context` is the agent's own read and needs no permission beyond the workspace guard. Same registration scope as the routes above (`workspace || multi-tenant`).
63
+ - `/v1/workspaces/:workspaceId/agents` (GET `?userId=`, POST), `/v1/workspaces/:workspaceId/agents/:agentId/key` (POST), `/v1/workspaces/:workspaceId/agents/:agentId` (PATCH `{ enabled }`), `PUT /v1/workspaces/:workspaceId/agents/:agentId/grants` (`{ grants }`, #7864), and `/v1/agent/context` (GET) — the agent seat (#3591, `src/routes/workspaces/agents.ts` over `src/lib/agent-store.ts`, `// oss: false`). An agent is a stored delegate of one person, bound to one workspace. The five management routes refuse an agent caller outright (403), check `agents-manage` (owner, admin) before any read, and scope every read and write to `tenant.organizationId`, never a body or query value; an agent of another organization is the same 404 as a missing one. Create returns 201 with the key shown once; re-key returns the new key once. Each successful create, re-key, switch and grant change writes an `agents.*` audit record. **Grants (#7864, `docs/specs/7864-agent-key-grants-spec.md`).** An agent acts at `member`, plus any of seven permissions an owner or admin granted it one by one — `content-edit`, `content-publish`, `assets-write`, `magnets-manage`, `meeting-types-manage`, `people-read` since #852, and `member-pieces-manage` since #7878 (`@working-theory/validation`'s `AGENT_GRANTABLE_PERMISSIONS`, held to that set by the `agents_grants_allowed` CHECK). The grant PUT replaces the whole set (an empty list removes every grant) and refuses a grant the agent's person's own role does not hold, `409 grant_exceeds_person`. The clamp is one function both tenant guards call (`services/default-tenant.ts`'s `agentTenant`): an agent holds a stored grant only while its person's role holds it, so a demoted person's agent keeps the row but not the permission. The routes for the seven check `allows(tenant, "<permission>")`, which reads the grants; every other check keeps `can(tenant.role, …)`, so no other owner or admin permission is reachable. Every agent write on content, assets and meeting types writes one `recordAgentWrite` row naming the agent and its person (magnets already did); a person's writes there stay unaudited. The member-area writes audit every caller through `recordAuditAction`, whose actor names an agent as the agent. No grant raises the ceiling. `/v1/agent/context` is the agent's own read, unchanged by grants, and needs no permission beyond the workspace guard. Same registration scope as the routes above (`workspace || multi-tenant`).
59
64
  - `/v1/workspaces/:workspaceId/content` (GET, POST), `/v1/workspaces/:workspaceId/content/:type/:slug` (GET, PATCH), `/v1/workspaces/:workspaceId/content/:type/:slug/{publish,unpublish}` (POST) — the tenant-guarded content editor's write surface (#5853, `src/routes/workspaces/content.ts`): list, create, read/save the draft tip (under `If-Match`), and publish/unpublish, all over `Artifact`/`ArtifactVersion`. `:type` is validated against the page-type registry (`z.enum(SCHEMA_ORG_TYPES)`) rather than accepted as a free string on every addressed operation — an unregistered type is a 400 before any lookup, since it is echoed back and passed to `notifyRevalidate` as the site's cache tag. Role floors from `@working-theory/validation`'s permission table (#7636 D2): publish and unpublish need `content-publish`, and create, read and save need `content-edit` (both owner, admin — an admin builds, a member operates). The list serves `content-edit` the editor's full view and a caller holding only `docs-read` (a member) a published-only projection (D4): draft rows dropped, every row `status: "published"`, `version: null`, `valid: true`, and a `published_with_draft` page's `type`/`tags` read from its PUBLISHED version — applied before every filter, so a member's `?status=draft` or a draft tip's `?tag=` matches nothing. **The GET list is a UNION of page artifacts and DOCUMENT assets** (#6093, D1/D9 — "one store, two views"): every row carries `tags: string[]` (never null, read from the draft tip's stored content for a page, from `Asset.tags` for a file) and a DERIVED `kind: "page" | "post" | "file"` (`BlogPosting` alone maps to `"post"`; an asset row is always `"file"`) — an optional `?tag=<slug>` filters the union AFTER it is built, so a file is returned under either its own tag or a shared one. The asset half of the union (`DOCUMENT_CONTENT_TYPES`, i.e. `application/pdf`) is skipped entirely when `locale`/`type` is supplied or `status` names anything but `"published"`, since a file row can never satisfy those. A foreign `:workspaceId` costs zero artifact **and** zero asset queries. No MCP twin — identity-bound tenant routes (#3591 exception, same shape as the sibling `/v1/workspaces/*` routes).
60
- - `/v1/workspaces/:workspaceId/assets` (GET, POST), `/v1/workspaces/:workspaceId/assets/:assetId` (PATCH, DELETE), `/v1/assets/:assetId` (GET, public/anonymous) — the workspace asset store (#5854 upload/read; #6093 list/PATCH/DELETE, `src/routes/assets/{index,upload,read,manage}.ts`). Upload accepts an allowlisted union of three named classes (`src/routes/assets/index.ts`): five RASTER images (`image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`), one VECTOR image (`image/svg+xml`, admitted under the operator's 2026-09-18 `allow-svg-assets` ruling — issue #6093 comment `5731573595` — superseding #5854's original SVG exclusion) and one DOCUMENT type (`application/pdf`), all under the existing 20 MB cap; `?tags=<slug>[,<slug>…]` stores tags on the row. The public read serves a RASTER type `inline` exactly as before; every OTHER admitted type (SVG, PDF) is served `attachment`, with the filename's extension pinned to the stored content type (closing extension spoofing) and a five-directive `Content-Security-Policy` (`default-src 'none'; sandbox; frame-ancestors 'none'; form-action 'none'; base-uri 'none'`) that makes the bytes never a document on this origin — this is what makes admitting SVG safe with NO server-side sanitizer. `GET …/assets` (`assets-read` — every role, a member included) lists a workspace's assets, metadata only, never `bytes`, with an optional `?tag=<slug>` filter; this is what narrows the store's prior "nothing lists assets" premise to its precise form — no ANONYMOUS and no CROSS-TENANT enumeration, both still true. `PATCH …/assets/:assetId` updates `title`/`description`/`tags` (`assets-write`, owner and admin, the upload's permission too; `null` clears a text field to SQL `NULL`, `""` stores empty; the asset's `id` and public URL are untouched). `DELETE …/assets/:assetId` (`assets-write`) removes the row and the bytes at the ORIGIN only — already-cached copies elsewhere are not recallable under the year-long `immutable` promise, and no reference check protects a page that still embeds the URL; absent and foreign ids both take the same 404. Every tenant route here is identity-bound; no MCP twin (#3591 exception). The public read has no MCP twin either — it serves bytes to an `<img>`/download, the same boundary `upload.ts` records for its own sibling.
65
+ - `/v1/workspaces/:workspaceId/assets` (GET, POST), `/v1/workspaces/:workspaceId/assets/:assetId` (PATCH, DELETE), `/v1/assets/:assetId` (GET, public/anonymous) — the workspace asset store (#5854 upload/read; #6093 list/PATCH/DELETE, `src/routes/assets/{index,upload,read,manage}.ts`). Upload accepts an allowlisted union of three named classes (`src/routes/assets/index.ts`): five RASTER images (`image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`), one VECTOR image (`image/svg+xml`, admitted under the operator's 2026-09-18 `allow-svg-assets` ruling — issue #6093 comment `5731573595` — superseding #5854's original SVG exclusion) and one DOCUMENT type (`application/pdf`), all under the existing 20 MB cap; `?tags=<slug>[,<slug>…]` stores tags on the row. The public read serves a RASTER type `inline` exactly as before; every OTHER admitted type (SVG, PDF) is served `attachment`, with the filename's extension pinned to the stored content type (closing extension spoofing) and a five-directive `Content-Security-Policy` (`default-src 'none'; sandbox; frame-ancestors 'none'; form-action 'none'; base-uri 'none'`) that makes the bytes never a document on this origin — this is what makes admitting SVG safe with NO server-side sanitizer. `GET …/assets` (`assets-read` — every role, a member included) lists a workspace's assets, metadata only, never `bytes`, with an optional `?tag=<slug>` filter; this is what narrows the store's prior "nothing lists assets" premise to its precise form — no ANONYMOUS and no CROSS-TENANT enumeration, both still true. `PATCH …/assets/:assetId` updates `title`/`description`/`tags` (`assets-write`, owner and admin, the upload's permission too; `null` clears a text field to SQL `NULL`, `""` stores empty; the asset's `id` and public URL are untouched). `DELETE …/assets/:assetId` (`assets-write`) removes the row and the bytes at the ORIGIN only — already-cached copies elsewhere are not recallable under the year-long `immutable` promise, and no reference check protects a page that still embeds the URL; absent and foreign ids both take the same 404. Every tenant route here is identity-bound; no MCP twin (#3591 exception). The public read has no MCP twin either — it serves bytes to an `<img>`/download, the same boundary `upload.ts` records for its own sibling. **A client's file is never in the library's public life (#7877 D18):** the default `GET …/assets` listing leaves out every asset tagged `private` — only `?tag=private` lists them (the Admin's Compose) — and the public read answers its uniform 404 for an asset tagged `private` or attached to any member-area message, so such a file's bytes are served only by its owner's `GET /v1/member/messages/:id/file`.
61
66
  - `/v1/billing` (GET), `/v1/billing/portal-session` (POST) — org-scoped billing read + Stripe customer-portal session creation. The read stays open to every member (the Admin's plan gate reads it); the portal needs `billing-manage` — the owner alone (`@working-theory/validation`'s permission table (#7636 D2); an admin is refused before any Stripe call). `/v1/billing/usage` (GET) needs `billing-read` (owner, admin).
62
- - `/v1/schedule/availability` (GET), `/v1/schedule/event-meta` (GET), `/v1/schedule/book` (POST) — anonymous scheduling proxy behind the provider seam (`src/services/scheduling/`); Cal.com v2 today, a self-hosted engine later, same three calls. `event-meta` is the meta-only read (title · duration · description · price) so rendering an event's facts never fetches an availability window (#4633). `CAL_API_KEY` is read server-side only. Which account answers is `resolvePublicSchedulingProvider` (#7533 D4), from `resolvePublicWorkspace()` and never the request: off the database adapter, the env credential as before; a resolved workspace, its own connection (or the env credential on a one-workspace deployment); an unresolved one, `503 not_configured` — fail closed. MCP twins: `list_availability` / `get_event_meta` / `create_booking` (#4416, #4633), unchanged — same arguments, same result shape
67
+ - `/v1/schedule/availability` (GET), `/v1/schedule/event-meta` (GET), `/v1/schedule/book` (POST) — anonymous scheduling proxy behind the provider seam (`src/services/scheduling/`); Cal.com v2 today, a self-hosted engine later, same three calls. `event-meta` is the meta-only read (title · duration · description · price) so rendering an event's facts never fetches an availability window (#4633). `CAL_API_KEY` is read server-side only. Which account answers is `resolvePublicSchedulingProvider` (#7533 D4), from `resolvePublicWorkspace()` and never the request: off the database adapter, the env credential as before; a resolved workspace, its own connection (or the env credential on a one-workspace deployment); an unresolved one, `503 not_configured` — fail closed. MCP twins: `list_availability` / `get_event_meta` / `create_booking` (#4416, #4633), unchanged — same arguments, same result shape. **A hub's spokes (#7944):** a call carrying a spoke key passes one gate before any event, slot or booking call — every calLink's slug must be one its workspace has enabled (no provider call at all), and every calLink's owner must equal the handle of the account the workspace's credential belongs to (`SchedulingProvider.getAccountHandle()`, Cal `GET /v2/me`, remembered 60 s per key, an empty answer never remembered); a refusal is `404 event_not_found`, an unreadable handle the read's own kind (`502 provider_error`), and each refusal logs one `warn` of `{ route, spokeId, reason }` and nothing else. A refused key keeps the answer each route gave it before; keyless callers skip the gate and never read the handle. The MCP twins forward no visitor identity, so every MCP caller shares the MCP host's one per-IP `schedule` bucket on the hub (`availability`, `event-meta` and `book` counted together): one caller's reads can make `create_booking` answer 429 for every other MCP caller of that host. This is accepted (#7944 D6) — the site's own booker carries the visitor's identity through the relay and is unaffected; the reopen trigger is recorded in `apps/mcp/src/tools/create_booking.ts`'s header
63
68
  - `/v1/schedule/meeting-types` (GET) — the enabled-meeting-slugs public read (#6183 S9b, `src/routes/schedule/meeting-types.ts`): the session-less read the public `/meet` surface needs to honour the operator's enabled-slug gate (`/v1/workspaces/:workspaceId/meetings`, above), since a public page holds no session. Resolves its workspace via `resolvePublicWorkspace()` (the same fail-closed predicate the public content read uses — no client-suppliable workspace, ever) and reads through a new named public-read boundary, `src/lib/public-meetings-config.ts` (modelled on `lib/asset-store.ts`): one `findUnique` by the resolved `workspaceId`, no write, no list. `{ slugs: string[] | null }` — `null` means "no stored list" (an unconfigured deployment, or the non-database adapter); the caller (`apps/web`'s `enabledMeetingSlugs()`) applies the `SCHEDULING_CAL_LINK`-derived singleton fallback for that state, since that env var is `apps/web`'s, not this app's. Reads no client input. No MCP twin — deferred to a named follow-up rather than silently skipped (the route's own header, §10 Q3 of the spec).
64
69
  - `POST /v1/webhooks/calcom` — the scheduling booking-event receiver (#6085, brief H7): verifies the provider's HMAC-SHA256 signature (`x-cal-signature-256`) over the raw body, then normalizes one of six `BOOKING_*` trigger events into an `Appointment` row (`src/services/scheduling/appointments.ts`). `CAL_WEBHOOK_SECRET` is read server-side only (`config/index.ts`); an unset secret answers `503`, never a silent accept. Registered on the same `webhooksScope` as `/v1/webhooks/stripe` (its raw-body content-type parser is what a signed receiver needs), module-conditional (`scheduling`, `src/routes/webhooks/index.ts`). No commerce-claim read: a booking event is not a money event (D-67 puts the payment on the provider's own side). No MCP twin — an inbound receiver for one named provider, not an endpoint an agent could reasonably call, the same footing `POST /v1/webhooks/stripe` already takes.
65
70
  - `POST /v1/webhooks/calcom/:connectionToken` — the same receiver for ONE workspace's own connection (#7533 D6, `calcomConnectionWebhookHandler`). The 43-character token in the path names one `SchedulingConnection` row, whose own decrypted secret verifies `x-cal-signature-256` and whose `workspaceId` the Appointment is written to — nothing in the body, query or headers reaches the workspace. A malformed or unknown token, or another provider's connection, is `404 not-found` (logged nothing); a secret that will not decrypt is `503 webhook-not-configured`; the rest of the ladder is the legacy route's, by the same code. Same module gate and `loadSlice` call as the legacy route, its own rate-limit bucket. The legacy `POST /v1/webhooks/calcom` is unchanged: the env account's receiver, writing into the `AILK_SITE_ID` workspace (SEC-7533-2, accepted). No MCP twin — the same inbound-receiver footing as the legacy route.
@@ -162,7 +167,19 @@ sweep's own DB constraint (never a caller-side lock).
162
167
  - Don't put session state in `apps/api`. It's stateless.
163
168
  - Don't bundle `apps/api` (esbuild, rollup, webpack). Slice specifiers cannot survive it — see `## Deploy path`.
164
169
 
165
- Last updated: 2026-10-05 — doc-sync: added the agent seat routes (#3591, #7678) to Endpoint conventions — verified against `apps/api/src/routes/workspaces/agents.ts`.
170
+ Last updated: 2026-10-09 — an agent key may be granted `member-pieces-manage` (#7878): the member-area bullet's four writes read it through `allows`, and the agent-seat bullet lists seven grantable permissions — verified against `apps/api/src/routes/workspaces/{pieces,plan,messages-out}.ts` and `packages/validation/src/schemas/permissions.ts`.
171
+
172
+ Prior: 2026-10-09 — a spoke's schedule calls bind the event owner to its workspace (#7944): the `/v1/schedule/*` bullet gains the spoke gate and the accepted shared MCP schedule budget — verified against `apps/api/src/routes/schedule/index.ts`, `apps/api/src/services/scheduling/{types,cal-provider}.ts` and `apps/api/src/middleware/rate-limit.ts`.
173
+
174
+ Prior: 2026-10-09 — the member area contract (#7877): added the operator-route bullet (pieces, piece stages, plan, outbound messages; `people-write`; the bounds, refusals and audit; the checkout plan rule; the no-twin reason) and the member-read bullet (`/v1/member/*`, the caller seam, the refusals, the never-served fields, the file headers), the timeline's `message` kind on the People bullet, and the private-asset rule on the asset-store bullet — verified against `apps/api/src/routes/{workspaces/{pieces,plan,messages-out},member/{pieces,messages}}.ts`, `apps/api/src/services/{member-area,person,lead-routing}.ts`, `apps/api/src/lib/{member-store,tenant-db,asset-store}.ts` and `apps/api/src/middleware/auth.ts`.
175
+
176
+ Prior: 2026-10-09 — Person, the per-workspace client record (#852): added the `/v1/workspaces/:workspaceId/people` bullet (the two reads, `people-read`, the grant, the bounds, the no-twin reason, the never-served columns) — verified against `apps/api/src/routes/workspaces/people.ts`, `apps/api/src/lib/tenant-db.ts` and `apps/api/src/services/person.ts`.
177
+
178
+ Last updated: 2026-10-09 — the hub signs in its spokes (#7894): the `/v1/hub-sign-in/*` bullet in Endpoint conventions — verified against `apps/api/src/routes/auth/hub-sign-in.ts`, `apps/api/src/services/hub-sign-in.ts`, `apps/api/src/lib/hub-sign-in-store.ts`, `apps/api/src/middleware/auth.ts` and `apps/api/src/bin/spokes.ts`.
179
+
180
+ Prior: 2026-10-08 — agent key grants (#7864): the agent-seat bullet names `PUT /v1/workspaces/:workspaceId/agents/:agentId/grants`, the five grantable permissions and the person clamp — verified against `apps/api/src/routes/workspaces/agents.ts`, `apps/api/src/services/default-tenant.ts` and `packages/validation/src/schemas/permissions.ts`.
181
+
182
+ Prior: 2026-10-05 — doc-sync: added the agent seat routes (#3591, #7678) to Endpoint conventions — verified against `apps/api/src/routes/workspaces/agents.ts`.
166
183
 
167
184
  Prior: 2026-10-04 — doc-sync: the agent seat, step E (#7684) — the messages and submissions bullets now name each route's signed-in MCP twin on `/mcp/workspace` (#3591 D13) in place of the retired no-twin exception — verified against `apps/api/src/routes/workspaces/{messages,submissions}.ts`, `apps/mcp/src/workspace-server.ts` and `tests/parity/api-parity/kinds/site.ts`.
168
185
 
@@ -15,6 +15,7 @@
15
15
  "deliverable:resend": "tsx src/bin/deliverable-resend.ts",
16
16
  "seed:presets": "tsx src/bin/seed-presets.ts",
17
17
  "spokes": "tsx src/bin/spokes.ts",
18
+ "flows:copy": "tsx src/bin/flows-copy.ts",
18
19
  "build": "tsc",
19
20
  "build:vercel": "cd ../../database && pnpm exec prisma generate && cd ../.. && pnpm --filter @working-theory/validation build && pnpm --filter @working-theory/api build && mkdir -p apps/api/public && echo '{}' > apps/api/public/.vercel",
20
21
  "start": "node dist/cli.js",
@@ -27,13 +27,15 @@ export interface AgentCaller {
27
27
  workspaceId: string;
28
28
  /** The person's own role; the guard clamps the agent to `member`. */
29
29
  role: "owner" | "admin" | "member";
30
+ /** The agent's stored grants (#7864); the guard keeps those `role` holds. */
31
+ grants: string[];
30
32
  headers: { authorization: string };
31
33
  }
32
34
 
33
35
  export function buildAgentCaller(
34
36
  scope: { organizationId: string; workspaceId: string },
35
37
  overrides: Partial<
36
- Pick<AgentCaller, "agentId" | "userId" | "membershipId" | "role">
38
+ Pick<AgentCaller, "agentId" | "userId" | "membershipId" | "role" | "grants">
37
39
  > = {},
38
40
  ): AgentCaller & { key: string } {
39
41
  const key = mintAgentKey();
@@ -42,6 +44,7 @@ export function buildAgentCaller(
42
44
  userId: "user_00000000-0000-7000-8000-00000000a9e2",
43
45
  membershipId: "member_00000000-0000-7000-8000-00000000a9e3",
44
46
  role: "member",
47
+ grants: [],
45
48
  ...scope,
46
49
  ...overrides,
47
50
  key,
@@ -64,6 +67,7 @@ export function agentKeyLookup(
64
67
  workspaceId: caller.workspaceId,
65
68
  organizationId: caller.organizationId,
66
69
  permissionLevel: "member",
70
+ grants: caller.grants,
67
71
  enabled: true,
68
72
  keyIssuedToMembershipId: caller.membershipId,
69
73
  lastActiveAt: null,
@@ -11,6 +11,23 @@
11
11
  * double does not model throws, so scoping that rides on one can never pass
12
12
  * for the wrong reason.
13
13
  *
14
+ * Unique keys (#852 D13). A model listed in `UNIQUE_KEYS` enforces its
15
+ * declared compound keys the way Postgres does (NULLs distinct): `createMany`
16
+ * with `skipDuplicates` skips a conflicting row (`ON CONFLICT DO NOTHING`),
17
+ * and a `create`, a `createMany` without it, or an `updateMany` that would
18
+ * give two rows one key throws `{ code: "P2002" }`.
19
+ *
20
+ * Member area (#7877 D17). `piece`, `interaction` and `workspacePieceStages`
21
+ * are ordinary delegates here — `where` on `workspaceId`, `personId`, `id`,
22
+ * `channel`, `direction`, `readAt: null` and `id: { in }`, and
23
+ * `orderBy`/`take`, all honoured as for any model — minted with their
24
+ * registry prefixes (`piece_`, `intx_`, `pstages_`) so a boundary id check
25
+ * accepts them, and one stage list per workspace is a declared unique key.
26
+ *
27
+ * Raw reads (#852 D13). `$queryRawUnsafe` is one recorded `jest.fn` per
28
+ * double (as are `$transaction` and `$executeRaw`, #7877); each call answers the next entry of the `__rawResults` queue
29
+ * (default `[]` when the queue is empty) — an `Error` entry is thrown.
30
+ *
14
31
  * Usage — the factory must run inside the hoisted `jest.mock` callback:
15
32
  *
16
33
  * jest.mock("../../../lib/prisma.js", () =>
@@ -56,6 +73,37 @@ export function createInMemoryPrisma(): { prisma: Record<string, unknown> } {
56
73
  return x < y ? -1 : x > y ? 1 : 0;
57
74
  };
58
75
  const table = (model: string) => (db[model] ??= []);
76
+ const UNIQUE_KEYS: Record<string, string[][]> = {
77
+ person: [
78
+ ["workspaceId", "email"],
79
+ ["workspaceId", "userId"],
80
+ ],
81
+ workspacePieceStages: [["workspaceId"]],
82
+ };
83
+ /** Column defaults a create omits, as the schema declares them. */
84
+ const DEFAULTS: Record<string, Row> = {
85
+ piece: { needsClient: false },
86
+ interaction: { assetId: null, readAt: null },
87
+ };
88
+ /** A model whose registry prefix is not its delegate name (`packages/ids`). */
89
+ const ID_PREFIX: Record<string, string> = {
90
+ interaction: "intx",
91
+ workspacePieceStages: "pstages",
92
+ };
93
+ /** Whether `row` would share a declared unique key with another row. */
94
+ function conflicts(model: string, row: Row, except?: Row): boolean {
95
+ return (UNIQUE_KEYS[model] ?? []).some((key) =>
96
+ key.every((k) => row[k] != null)
97
+ ? table(model).some(
98
+ (other) =>
99
+ other !== except && key.every((k) => eq(other[k], row[k])),
100
+ )
101
+ : false,
102
+ );
103
+ }
104
+ const uniqueViolation = () =>
105
+ Object.assign(new Error("Unique constraint failed"), { code: "P2002" });
106
+ const rawResults: unknown[] = [];
59
107
 
60
108
  function matchCond(value: unknown, cond: unknown): boolean {
61
109
  if (cond === undefined) return true;
@@ -220,15 +268,17 @@ export function createInMemoryPrisma(): { prisma: Record<string, unknown> } {
220
268
  (r) => pick({ ...r }, args.select ?? args.include) as Row,
221
269
  );
222
270
  };
271
+ const build = (data: Row): Row => ({
272
+ // A registry-shaped id, so an `isId` boundary check accepts it.
273
+ id: `${ID_PREFIX[model] ?? model}_00000000-0000-7000-8000-${String(++seq).padStart(12, "0")}`,
274
+ createdAt: new Date(),
275
+ updatedAt: new Date(),
276
+ ...DEFAULTS[model],
277
+ ...data,
278
+ });
223
279
  const create = (args: Row) => {
224
- const data = args.data as Row;
225
- const row: Row = {
226
- // A registry-shaped id, so an `isId` boundary check accepts it.
227
- id: `${model === "user" ? "user" : model}_00000000-0000-7000-8000-${String(++seq).padStart(12, "0")}`,
228
- createdAt: new Date(),
229
- updatedAt: new Date(),
230
- ...data,
231
- };
280
+ const row = build(args.data as Row);
281
+ if (conflicts(model, row)) throw uniqueViolation();
232
282
  table(model).push(row);
233
283
  return pick({ ...row }, args.select);
234
284
  };
@@ -258,6 +308,20 @@ export function createInMemoryPrisma(): { prisma: Record<string, unknown> } {
258
308
  ),
259
309
  ),
260
310
  create: jest.fn(async (args: Row) => (log("create"), create(args))),
311
+ createMany: jest.fn(async (args: Row) => {
312
+ log("createMany");
313
+ let count = 0;
314
+ for (const data of args.data as Row[]) {
315
+ const row = build(data);
316
+ if (conflicts(model, row)) {
317
+ if (args.skipDuplicates === true) continue;
318
+ throw uniqueViolation();
319
+ }
320
+ table(model).push(row);
321
+ count += 1;
322
+ }
323
+ return { count };
324
+ }),
261
325
  update: jest.fn(async (args: Row) => {
262
326
  log("update");
263
327
  const row = table(model).find((r) => matches(r, args.where as Where));
@@ -269,6 +333,11 @@ export function createInMemoryPrisma(): { prisma: Record<string, unknown> } {
269
333
  const rows = table(model).filter((r) =>
270
334
  matches(r, args.where as Where),
271
335
  );
336
+ for (const row of rows) {
337
+ if (conflicts(model, { ...row, ...(args.data as Row) }, row)) {
338
+ throw uniqueViolation();
339
+ }
340
+ }
272
341
  for (const row of rows) apply(row, args.data as Row);
273
342
  return { count: rows.length };
274
343
  }),
@@ -298,20 +367,30 @@ export function createInMemoryPrisma(): { prisma: Record<string, unknown> } {
298
367
  }
299
368
 
300
369
  const delegates: Record<string, ReturnType<typeof delegate>> = {};
370
+ const queryRawUnsafe = jest.fn(async (..._args: unknown[]) => {
371
+ const next = rawResults.length > 0 ? rawResults.shift() : [];
372
+ if (next instanceof Error) throw next;
373
+ return next;
374
+ });
375
+ // Recorded, so a suite can see a lock statement ran first in its
376
+ // transaction (#7877 D9): an interactive callback runs on this double.
377
+ const transaction = jest.fn(async (arg: unknown) =>
378
+ typeof arg === "function"
379
+ ? (arg as (tx: unknown) => unknown)(prisma)
380
+ : Promise.all(arg as Promise<unknown>[]),
381
+ );
382
+ const executeRaw = jest.fn(async (..._args: unknown[]) => 0);
301
383
  const prisma: Record<string, unknown> = new Proxy(
302
384
  {},
303
385
  {
304
386
  get(_target, prop) {
305
387
  if (prop === "__db") return db;
306
388
  if (prop === "__calls") return calls;
307
- if (prop === "$transaction") {
308
- return async (arg: unknown) =>
309
- typeof arg === "function"
310
- ? (arg as (tx: unknown) => unknown)(prisma)
311
- : Promise.all(arg as Promise<unknown>[]);
312
- }
313
- if (prop === "$queryRaw" || prop === "$executeRaw")
314
- return async () => [];
389
+ if (prop === "__rawResults") return rawResults;
390
+ if (prop === "$queryRawUnsafe") return queryRawUnsafe;
391
+ if (prop === "$transaction") return transaction;
392
+ if (prop === "$executeRaw") return executeRaw;
393
+ if (prop === "$queryRaw") return async () => [];
315
394
  if (typeof prop !== "string" || prop === "then") return undefined;
316
395
  return (delegates[prop] ??= delegate(prop));
317
396
  },
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @file openapi-keyless-hub.test.ts
3
+ * @description #7947 — a hub that refuses keyless public reads (#7633) still
4
+ * serves `GET /v1/openapi.json` to a caller with no spoke key, through the
5
+ * real `build()`. A spoke's `/openapi.json` proxies that document with a plain
6
+ * fetch (no `x-ailk-spoke-key`), so the exemption is what keeps a spoke's
7
+ * discovery surface from answering 502.
8
+ *
9
+ * The risk pinned here is the route moving into a keyed scope, which only a
10
+ * `build()`-level test can see (spec
11
+ * docs/specs/7947-spoke-openapi-keyless-discovery-spec.md D2). Each case also
12
+ * reads `GET /v1/schedule/meeting-types` keyless in the same app and expects
13
+ * the refusal answer, so a 200 on the document cannot pass on a hub that
14
+ * refuses nothing (D3). Two refusing modes (D4): strict `on`, and the default
15
+ * `auto` with a registered spoke.
16
+ */
17
+
18
+ // eslint-disable-next-line no-restricted-syntax -- prisma is a DB boundary; __mocks__/prisma.ts activates the auto-mock (Jest requires explicit call for local files)
19
+ jest.mock("../lib/prisma.js");
20
+
21
+ jest.mock("@fastify/cors", () => {
22
+ return jest.fn().mockResolvedValue(undefined);
23
+ });
24
+
25
+ jest.mock("@working-theory/email", () => ({
26
+ sendLeadNotification: jest.fn().mockResolvedValue({ ok: true }),
27
+ }));
28
+
29
+ import * as configModule from "../config/index.js";
30
+ import type { HubSpokeKeyMode } from "../config/index.js";
31
+ import { prisma } from "../lib/prisma.js";
32
+ import { __resetBuckets } from "../middleware/rate-limit";
33
+ import { build } from "../server";
34
+ import { __resetHubStatusForTests } from "../services/public-site-resolver.js";
35
+
36
+ const db = jest.mocked(prisma);
37
+
38
+ function setMode(mode: HubSpokeKeyMode): void {
39
+ jest.replaceProperty(configModule, "config", {
40
+ ...configModule.config,
41
+ AILK_HUB_REQUIRE_SPOKE_KEY: mode,
42
+ });
43
+ }
44
+
45
+ /** What a hub that refuses the caller answers on the public meeting-types read. */
46
+ const REFUSAL = { ok: true, data: { slugs: [] } };
47
+
48
+ describe("GET /v1/openapi.json against a hub that refuses keyless callers (#7947)", () => {
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- server is typed via Fastify generics; explicit any matches server.test.ts
50
+ let app: any;
51
+ const prior = {
52
+ modules: process.env.AILK_ENABLED_MODULES,
53
+ databaseUrl: process.env.DATABASE_URL,
54
+ };
55
+
56
+ async function startApp(): Promise<void> {
57
+ app = await build();
58
+ await app.ready();
59
+ }
60
+
61
+ beforeEach(() => {
62
+ __resetBuckets();
63
+ __resetHubStatusForTests();
64
+ process.env.AILK_ENABLED_MODULES = "scheduling";
65
+ });
66
+
67
+ afterEach(async () => {
68
+ if (app) await app.close();
69
+ app = undefined;
70
+ jest.restoreAllMocks();
71
+ db.spoke.findFirst.mockReset();
72
+ });
73
+
74
+ afterAll(() => {
75
+ for (const [name, value] of [
76
+ ["AILK_ENABLED_MODULES", prior.modules],
77
+ ["DATABASE_URL", prior.databaseUrl],
78
+ ] as const) {
79
+ if (value === undefined) delete process.env[name];
80
+ else process.env[name] = value;
81
+ }
82
+ });
83
+
84
+ it("mode `on`: a keyless caller gets the document and the same app refuses its keyless workspace read (AC-1)", async () => {
85
+ setMode("on");
86
+ await startApp();
87
+
88
+ const doc = await app.inject({ method: "GET", url: "/v1/openapi.json" });
89
+ expect(doc.statusCode).toBe(200);
90
+ expect(doc.json().openapi).toBe("3.1.0");
91
+
92
+ const refused = await app.inject({
93
+ method: "GET",
94
+ url: "/v1/schedule/meeting-types",
95
+ });
96
+ expect(refused.statusCode).toBe(200);
97
+ expect(refused.json()).toEqual(REFUSAL);
98
+ });
99
+
100
+ it("mode `auto` with a registered spoke: the same two answers (AC-2)", async () => {
101
+ process.env.DATABASE_URL ??=
102
+ "postgresql://placeholder:placeholder@localhost:5432/placeholder";
103
+ setMode("auto");
104
+ // A non-empty registry makes this deployment a hub (#7633 D1).
105
+ db.spoke.findFirst.mockResolvedValue({
106
+ id: "spoke_01920000-0000-7000-8000-0000000000c1",
107
+ } as never);
108
+ await startApp();
109
+
110
+ const doc = await app.inject({ method: "GET", url: "/v1/openapi.json" });
111
+ expect(doc.statusCode).toBe(200);
112
+ expect(doc.json().openapi).toBe("3.1.0");
113
+
114
+ const refused = await app.inject({
115
+ method: "GET",
116
+ url: "/v1/schedule/meeting-types",
117
+ });
118
+ expect(refused.statusCode).toBe(200);
119
+ expect(refused.json()).toEqual(REFUSAL);
120
+ expect(db.spoke.findFirst).toHaveBeenCalled();
121
+ });
122
+ });