create-ailk 0.40.0 → 0.40.2

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 (72) hide show
  1. package/README.md +26 -4
  2. package/component-catalog.json +1 -1
  3. package/component-catalog.md +1 -1
  4. package/dist/add-module.d.ts +2 -1
  5. package/dist/add-module.js +17 -1
  6. package/dist/cutover.d.ts +7 -3
  7. package/dist/cutover.js +8 -3
  8. package/dist/lib/declared-env.d.ts +5 -1
  9. package/dist/lib/declared-env.js +6 -1
  10. package/dist/lib/env-catalog.d.ts +3 -2
  11. package/dist/lib/env-catalog.js +4 -8
  12. package/dist/module-architecture.js +0 -1
  13. package/dist/programmatic.js +18 -9
  14. package/dist/remove-module.js +1 -1
  15. package/dist/seam-refresh.d.ts +60 -0
  16. package/dist/seam-refresh.js +214 -0
  17. package/dist/spoke-checkout.d.ts +12 -3
  18. package/dist/spoke-checkout.js +14 -5
  19. package/dist/sync-routes.d.ts +10 -1
  20. package/dist/sync-routes.js +61 -6
  21. package/dist/template-record.d.ts +14 -2
  22. package/dist/template-record.js +60 -22
  23. package/dist/topology.js +3 -4
  24. package/dist/update.d.ts +13 -1
  25. package/dist/update.js +100 -8
  26. package/package.json +3 -3
  27. package/templates/.env.example +6 -0
  28. package/templates/.github/workflows/ci.yml +3 -0
  29. package/templates/apps/api/.env.example +12 -0
  30. package/templates/apps/api/CLAUDE.md +10 -7
  31. package/templates/apps/mcp/CLAUDE.md +25 -5
  32. package/templates/apps/web/.env.example +7 -1
  33. package/templates/apps/web/CLAUDE.md +40 -13
  34. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
  35. package/templates/apps/web/app/[locale]/layout.tsx +41 -24
  36. package/templates/apps/web/app/api/revalidate/__tests__/route.test.ts +56 -1
  37. package/templates/apps/web/app/api/revalidate/route.ts +45 -4
  38. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +60 -0
  39. package/templates/apps/web/app/llms.txt/route.ts +17 -4
  40. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +15 -7
  41. package/templates/apps/web/auth.config.tsx +2 -0
  42. package/templates/apps/web/auth.ts +28 -4
  43. package/templates/apps/web/jest.config.cjs +1 -1
  44. package/templates/apps/web/lib/__tests__/auth-email.test.ts +21 -0
  45. package/templates/apps/web/lib/__tests__/docs-path.test.ts +20 -2
  46. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +246 -0
  47. package/templates/apps/web/lib/__tests__/profile-back-link.test.ts +58 -0
  48. package/templates/apps/web/lib/__tests__/relay.test.ts +127 -12
  49. package/templates/apps/web/lib/__tests__/served-pages.test.ts +163 -20
  50. package/templates/apps/web/lib/__tests__/server-api.test.ts +72 -7
  51. package/templates/apps/web/lib/__tests__/services-path.test.ts +22 -1
  52. package/templates/apps/web/lib/__tests__/site-brand.test.ts +77 -0
  53. package/templates/apps/web/lib/__tests__/site-contact-lines.test.ts +64 -0
  54. package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +144 -4
  55. package/templates/apps/web/lib/auth-email.ts +19 -0
  56. package/templates/apps/web/lib/docs-path.ts +1 -1
  57. package/templates/apps/web/lib/hub-site-config.ts +154 -0
  58. package/templates/apps/web/lib/mcp-oauth.ts +123 -17
  59. package/templates/apps/web/lib/profile-back-link.ts +49 -12
  60. package/templates/apps/web/lib/relay.ts +48 -9
  61. package/templates/apps/web/lib/served-pages.ts +144 -39
  62. package/templates/apps/web/lib/server-api.ts +37 -4
  63. package/templates/apps/web/lib/services-path.ts +1 -1
  64. package/templates/apps/web/lib/site-brand.tsx +66 -0
  65. package/templates/apps/web/lib/site-contact-email.ts +24 -4
  66. package/templates/apps/web/lib/site-contact-lines.ts +20 -4
  67. package/templates/apps/web/lib/site-identity.ts +38 -2
  68. package/templates/apps/web/messages/en.json +13 -8
  69. package/templates/apps/web/middleware.ts +4 -2
  70. package/templates/apps/web/src/lib/routes.ts +13 -0
  71. package/templates/tools/declared-env.ts +6 -1
  72. package/versions.json +51 -51
@@ -63,7 +63,7 @@ Routes are versioned under `/v1/*`:
63
63
  - `/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`, `flags`, `ending`, `landing` (#8840 D4) and `unsubscribe` (#8847 D1) 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, a stored config the Admin extended with one of those blocks, or a standard magnet's slug (`onboarding`, #8515 D15, `contact`, #8661 D4, `job-application`, #8746 D3, and `newsletter`, #8847 D3 — `RESERVED_FLOW_SLUGS`, before any read) is `409 slug_owned`, so a seed never deletes them or replaces the owner's onboarding questions or Contact form. `upsertFlowDefinition` itself refuses the reserved slugs the same way, so no preset, approved listing or waitlist register writes one either, and a new listing's derived slug skips them (`contact-2`). 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`.
64
64
  - `/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).
65
65
  - `/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`). A client's file — tagged `private`, attached to a member-area message, or (#8171 D3) named by a delivered piece version — is never minted or served as a deliverable. 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).
66
- - `/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. **An Offerings offer is never quoted here (#9071 D2):** a `checkout` whose register offer or flow config offer carries `lookupKey` is `409 checkout_not_configured` before any write (the flow config's is checked inside the capture, before the email moment's session and lead — #9970 D9) — logged `{ slug, outcome: "offerings_offer_refused" }`; such an offer is sold on `/pricing` at Stripe's own Price. 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.
66
+ - `/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 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 key `assertAdmittedStripeKey` refuses is refused before any side effect. **An Offerings offer is never quoted here (#9071 D2):** a `checkout` whose register offer or flow config offer carries `lookupKey` is `409 checkout_not_configured` before any write (the flow config's is checked inside the capture, before the email moment's session and lead — #9970 D9) — logged `{ slug, outcome: "offerings_offer_refused" }`; such an offer is sold on `/pricing` at Stripe's own Price. 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.
67
67
  - `/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`. **A PATCH whose `config.slug` differs renames the magnet (#8641 D8):** `tenantDb(tenant).flows.rename` moves the row, this workspace's `Lead.source = 'flow:<slug>'` rows and its `FlowSession.flowSlug` rows to the new slug in one transaction, so its submissions follow it; `FlowCheckout` rows and lead payload copies are never rewritten. Refused before any write: `409 slug_fixed` (the stored slug is `onboarding`, `request-quote`, `contact` (#8661 D5), `job-application` (#8746 D3), `newsletter` (#8847 D4), `recommender` (#9071 D12) or `trial` (#9287 D11), which the server reads by name, or the row belongs to a listing) and `409 slug_reserved` (the new slug is one of those seven); inside the transaction, `409 conflict` first (another magnet holds it — #8734 D1; also the loser of two renames racing for one free slug, which fails on the `(site_id, slug)` key because the definition row is the rename's first write, D4), then `409 slug_bound` (a checkout or a waitlist register of this workspace names either slug, or a session of this workspace already sits at the new one). A lead of this workspace at `flow:<new slug>` that no magnet owns does not refuse: the rename re-stamps it `unclaimed:flow:<new slug>` (`unclaimedLeadSource`, `@working-theory/validation`) so the magnet never adopts it (#8734 D3). A rename records a `magnet.rename` audit row whose summary is `{ from, to, leads, sessions, unclaimed }`. 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. **`who` (#8171 D6, #10819)** — who can use the magnet, a People type (`flowWhoSchema`: `visitor` | `lead` | `user`, column default `visitor`, closed by the `flow_definitions_who_domain` CHECK); `user` is the member-area customer switch — is served on every full row and written by the PATCH (a value outside the three is `400`; a PATCH of it alone skips the plan check); the member summary row never carries it. **The completion setting (#8757 D1–D4):** every magnet carries `completion` (`lead` | `invite` | `checkout`, column default `lead`) and `checkoutOffering` (set exactly when `checkout`), two `FlowDefinition` columns closed by three CHECKs and read and written only through `lib/flow-completion-store.ts` (`tenant-db.ts` stays closed under the #8746 contract; `architecture.yaml` lists the store under `paths_scoped`). The migration backfilled `onboarding`, `request-quote` and `job-application` to `invite` by slug (`STANDARD_MAGNET_COMPLETIONS`); a magnet created later is `lead` until #8759. Every full row serves the pair; the member summary never does. The PATCH writes it ALONE — `{ completion, checkoutOffering }` beside any other key is `400 completion_alone`, an offering without a completion or a pair `flowCompletionSettingSchema` refuses `400 validation_failed` — with no plan check, and records `magnet.update` with summary `{ completion }`. `checkout` also needs a person (`403 completion_needs_person` for an agent key), the `commerce` claim (`409 commerce_required`, `503 license-undetermined`) and a key `services/plan-offerings.ts`'s `listPlanOfferings` lists right now (`409 offering_unknown`; a failed read `503 offerings_unavailable`). **The standard onboarding magnet (#8515 D2–D4):** every workspace holds one `diagnostic` magnet at slug `onboarding` (`ONBOARDING_FLOW_SLUG`, `onboardingFlowConfig` in `@working-theory/validation`), `draft` and `who: "user"`, written only by `lib/tenant-db.ts`'s insert-only seed (`createMany` with `skipDuplicates`, so a re-seed creates nothing and never overwrites the owner's edits or an owner's own magnet at that slug): `POST /v1/workspaces` seeds the workspace it just created, after its transaction commits (a failed seed is one `error` line and still a `201`), and the seed-presets CLI (`node dist/bin/seed-presets.js`, run once after deploy) seeds every existing workspace and prints counts only. Its two bare-id exports have one production caller each, pinned by `tests/architecture/onboarding-seed-callers.test.ts`. **The standard Contact form magnet (#8661 D1–D3):** every workspace also holds one `contact` magnet at slug `contact` (`CONTACT_FORM_FLOW_SLUG`, `contactFormFlowConfig`), titled "Contact form", `live`, `who: "visitor"`, landing page `/contact` — Name, Email, a five-option Subject, Message and a required terms checkbox. It is written by the same insert-only seed, from the same two callers (a failed seed is one `contact-form-seed` `error` line and still a `201`), and by `database/seed.ts` for the default workspace; a re-seed never duplicates it or overwrites an edit. The web /contact page reads it on every request through `GET /v1/flows/contact`, and a submission that used it is stamped `flow:contact`, an Inbox submission under "Contact form". **The standard Job application magnet (#8746 D3, D4):** every workspace also holds one `diagnostic` magnet at slug `job-application` (`JOB_APPLICATION_FLOW_SLUG`, `jobApplicationFlowConfig`), titled "Job application", `live`, `who: "visitor"`, landing page `/careers` — First name, Last name and Email (required), Phone and LinkedIn URL — with no `completion` field. It is written by the same insert-only seed, from the same two callers (a failed seed is one `job-application-seed` `error` line and still a `201`), and by `database/seed.ts` for the default workspace; `RESERVED_FLOW_SLUGS` carries its slug, so no flow-engine write, spoke seed or new listing takes it. Each web job page `/careers/<slug>` carries an Apply button to `/careers/<slug>/apply` (#8849), whose Free apply page reads it through `GET /v1/flows/job-application` and draws its field step as a one-step form, and a submission is stamped `flow:job-application`, an Inbox submission under "Job application" whose `name` is first + last and whose `job` is the posting's slug. **The standard trial magnet (#9287 D11, #9301):** every workspace also holds one `diagnostic` magnet at slug `trial` (`TRIAL_FLOW_SLUG`, `trialFlowConfig`), titled "Free trial", `live`, `who: "visitor"`, completion `lead`, landing page `/trial` — First name, Last name, Work email and a required terms box; a site may add a `company`-tagged field, which fills the Person's company. It is written by the same insert-only seed, from the same two callers (a failed seed is one `trial-seed` `error` line and still a `201`), by `database/seed.ts` for the default workspace and by the `20261025120000_trial_magnet` migration for existing workspaces; `RESERVED_FLOW_SLUGS` carries its slug. A completed walk is stamped `flow:trial`, an Inbox submission under "Free trial" whose Person carries the given name, family name and email. 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).
68
68
  - `/v1/deliverables/open/:slug` (GET) — an UNGATED file deliverable's bytes, keyed by the flow slug (#8848 D5, `deliverableOpenRoute` in `src/routes/deliverables/index.ts`). Anonymous; the workspace is the caller's (`resolveCallerWorkspace`, keyless through the one-workspace predicate as the flows bullet says; a refused spoke key or an ambiguous deployment `503 tenant_unresolved`), never a request value; no `DATABASE_URL` is `503 deliverables_not_configured`. The flow must be live and carry `deliverable` with `kind: "file"` and `gated: false`; the bytes are its `deliverables` default entry's `Asset`, through `lib/deliverable-asset-store.ts` (a client's file refused), never the legacy store, never a `playbook:` key; served with the grant route's `asset_` headers (`attachment`, pinned extension, `nosniff`, the sandbox CSP, `private, no-store`). Every miss is the file's one uniform 404. Registered in its own encapsulated `deliverableopen` rate-limit scope (60 a minute) with the visitor forward-key digests, and on `FORWARDED_VISITOR_ROUTES`, so a site's proxied reads (`/reports/<slug>/file`) are counted per visitor; the grant route's own budget is unchanged. Module: `signal-collectors`. No MCP twin — a byte download on the grant route's footing, recorded in `tests/parity/README.md`.
69
69
  - `/v1/content/{types,search,offerings,pricing,shown-offerings,discovery,:type,:type/:slug}` — public content reads. `GET /v1/content/search`, `GET /v1/content/:type` and `GET /v1/content/:type/:slug` are `search_content`'s, `list_pages`' and `read_content`'s twins (#7167, #7168, #7169): each parses its request with the `@working-theory/validation` exports in `content-reads.ts` (`contentSearchQuerySchema`; `contentListParamsSchema` + `contentListQuerySchema`; `contentPageParamsSchema` + `contentPageQuerySchema`) and answers through the shared builder in `@working-theory/content-adapters` the tool also calls (`searchContentItemList`, `listPagesItemList`, `readContentDocument`), so the pair takes the same arguments and returns the same result — the tool adopted the API; the `/v1` wire shapes are unchanged. `GET /v1/content/offerings` (`?type=&locale=`) is `get_offerings`' twin (#7177), answering `{ ok: true, data: { offerings } }` through `listOfferings` in `@working-theory/content-adapters`, the seam the tool also calls. `GET /v1/content/pricing` (`?slug=&locale=`) is `get_pricing`'s twin (#7178), answering `{ ok: true, data: { tiers } | null }` through `getPricingTiers`. `GET /v1/content/shown-offerings` is the `/pricing` page's Offerings read (#8924), answering `{ ok: true, data: { status: "shown", shownSet } | { status: "unconnected" } | { status: "empty" } }` behind the `commerce` claim, refreshing the snapshot on the bounded non-forced path, with no MCP twin. On a connected workspace with a current shown set, `GET /v1/content/pricing` (the `pricing` page) and `GET /v1/content/offerings` (unless `type=service`) answer that set through `readShownOfferings` (exported from `shown-offerings.ts`, the one read all three share, registered with one `shownSetRouteOptions` in `server.ts`) and `@working-theory/content-adapters`' shown-set mapping (`pricingTiersFromShownSet`, `listOfferingsWithShownSet`), with major-unit prices, `interval` and the full `lookupKey` (offerings: the Service pages, then the shown Products in place of the Product pages, each with `prices`); every other case — no connection, no claim, an expired or empty set, a failed read or mapping (one `warn { outcome: "shown_set_failed", errName }`) — answers page content as before; their MCP twins read the same answer through `apiClient.offerings.shown` (#8933). `GET /v1/content/discovery` is the owner's discovery switch as the deployment itself reads it (#10510, `packages/api/src/routes/content/discovery.ts`): no argument (a query string is ignored); with no `DATABASE_URL` it answers `{ ok: true, data: { discoverable: true } }` before any resolver or database import; otherwise the workspace is `resolveCallerWorkspace`'s (a spoke's key, else the one workspace) — `unresolved` is `404 not_found`, `resolved` answers `readSiteDiscovery` (`packages/api/src/services/site-discovery.ts`, the one reader and writer of the `site.discovery` `SiteSetting` row; no row or an unparsable one reads as on), a throw is `500 internal_error` logged by class name only; every answer appends `x-ailk-spoke-key` to `Vary` (`lib/vary-spoke-key.ts`, the one copy the offerings, pricing and shown-offerings routes share). apps/web and apps/mcp read it through `siteDiscoverable()` in `@working-theory/api-client`; no MCP twin, by decision.
@@ -77,7 +77,7 @@ Routes are versioned under `/v1/*`:
77
77
  - `/v1/workspaces/:workspaceId/slack-connection` (GET, POST, DELETE) — the Organization's own Slack connection (#9748, `packages-paid/api-workspace/src/routes/workspaces/slack-connection.ts`; data access, the Slack calls and the cipher in `packages/api/src/services/slack/connection.ts`, the only file that touches `prisma.slackConnection`). One `TENANCY` row in the `tenant:settings` scope, so it loads on single-tenant Pro, multi-tenant Pro Plus and the hub, and a selected but unlicensed build answers `403 feature_required`; the tenant guard refuses another Organization's `:workspaceId`, and every route acts on `request.tenant.organizationId` only. GET needs any tenant (an agent included) and answers exactly `{ connected: false }` or `{ connected: true, teamName, connectedAt }` — a missing row, a row failing its grammar and a value that does not decrypt all read as not connected, never a throw (there is no environment credential). POST and DELETE need `billing-manage` (the owner alone) and refuse an agent tenant (`403`). POST's order: tenant → owner → write budget (`slackconn`, 10 an hour per Organization, 20 per person, `429` with `Retry-After`) → `SLACK_CONNECTION_KEY` (`503 credential_key_not_configured`) → the strict `{ botToken, signingSecret }` body (4 KiB, `400 validation_failed`) → Slack: `auth.test` (validity, a bot token of one workspace, the granted scopes) then `team.billing.info` (the plan), one 10 s budget, the token only in the `Authorization` header with redirects refused. Refusals: `400 slack_token_refused` (`reason` `token_refused`, `not_bot_token` or `enterprise_install`), `400 slack_scopes_missing` naming every missing one of the nine bot scopes (`conversations.connect:write`, `groups:write`, `channels:manage`, `chat:write`, `team.billing:read`, and since #9854 `groups:read`, `groups:history`, `users:read`, `users:read.email` — an Organization connected before #9854 still reads connected, but its owner lookup answers `missing_scope` and no events arrive until the owner reconnects), `400 slack_paid_plan_required` on Slack's free plan, `502 slack_unavailable`, `409 slack_team_connected_elsewhere` (one Slack team, one Organization) and `409 connection_changed` (the row moved during verification) — each storing nothing. Success answers the status shape; the token and secret are AES-256-GCM ciphertext under `SLACK_CONNECTION_KEY` (`_PREVIOUS` decrypts during a rotation), bound to the Organization, the Slack team and the column. DELETE needs no key, touches no prospect-channel settings or channel record, and answers `{ removed }` — it does NOT revoke the token at Slack, which stays valid until the owner rotates it or uninstalls the app. Connect, replace and remove each write one `integrations.slack_connection.{connect,replace,remove}` audit row (summary: the team id) and email every owner, the actor included, through `sendSlackConnectionChangedEmail`; neither can change the answer. No response, log line, audit row or email carries the token, the secret or a ciphertext. No MCP twin for connect or disconnect — a person's act, recorded as no-tool rows in `tests/parity/README.md`; the status read's twin is the signed-in `get_slack_connection_status` (#9749), for which GET parses its `:workspaceId` (`400 validation_failed` when malformed).
78
78
  - `/v1/workspaces/:workspaceId/connections` (GET), `/v1/workspaces/:workspaceId/connections/:provider` (GET, PUT, DELETE), `/v1/workspaces/:workspaceId/connections/:provider/oauth/start` and `…/oauth/callback` (POST) — the shared connection model (#11173, ADR 0039; `packages-paid/api-workspace/src/routes/workspaces/connections.ts`; the five verbs in `packages/api/src/services/connections/`, whose `store.ts` is the only file that touches `prisma.connection`). One `TENANCY` row in the `tenant:settings` scope beside the Slack routes above, behind the same tenant guard. The list and the one-provider read answer every registered provider record's four-state status — `google`, `stripe`, `slack`, and `cal-com` where the scheduling slice is present — to a caller who may read it (a record's `readPermission` / `agentReadable`; an omitted record is absent from the list and `404 provider_unknown` alone, so the gate leaks nothing). Every write is a person's act: the scope's permission (`billing-manage` for an Organization-scoped record, `workspace-settings` for a workspace-scoped one), never an agent; the `connwrite` budget (10 an hour per Organization, 20 per person); `CONNECTION_KEY` (503 `credential_key_not_configured`). `PUT` is the key-only and webhook connect (`{ credential, settings? }`, the record's own strict schemas); a legacy name (Stripe, Slack, Cal.com) is `409 provider_legacy` — their own routes stay the way to change them. The OAuth pair: start answers `{ authorizeUrl, state }` with a sealed, bound state the Admin keeps in the browser that started; the callback verifies the state locally before the budget is charged, exchanges the code with the PKCE verifier, and writes the grant as `connect`, `replace` or `reconnect`. `DELETE` deletes by compare-and-swap and then revokes the deleted row's own grant, answering `{ removed, revoked }`. After a write: one audit row (`integrations` / `connection.<action>`, the opaque account id, never an email) and one `sendConnectionChangedEmail` to every owner. No response or log line carries a token, a code, a verifier, a state token or a ciphertext; every response is `Cache-Control: private, no-store`. No MCP twin for any of the six, by decision (tests/parity/README.md): the status reads' twin is deferred to the Google Analytics unit.
79
79
  - `/v1/workspaces/:workspaceId/prospect-channel` (GET, PUT) — the workspace's prospect-channel settings (#9749, spec `docs/specs/9749-workspace-prospect-channel-settings-get-spec.md`; `packages-paid/api-scheduling/src/routes/workspaces/meetings.ts`, beside the meetings routes, so the same `SCHEDULING` row and `tenant:schedule` scope; data access only through `tenantDb(tenant).prospectChannelSettings`). The blob is `prospectChannelSettingsSchema` (#9747): `enabled`, `memberIds` (Slack member ids invited in addition to the owner who connected Slack, who the channel step always invites), `welcomeTemplate?`, `channelPrefix`, `archiveDays`. GET needs `meeting-types-read` and answers the schema's defaults (`{ enabled: false, memberIds: [], channelPrefix: "prospect", archiveDays: 30 }`) when no row — or a row the schema refuses, logged `settings_unreadable` — is stored. PUT needs `meeting-types-manage` (owner, admin, or an agent an owner or admin granted it; a member is `403` before the body is read), replaces the whole blob after the strict schema accepts the body (32 KiB limit; an omitted field returns to its default; last writer wins), and is refused `409 slack_not_connected` whenever `getSlackConnectionStatus(tenant.organizationId)` answers not connected, whatever the body. An agent's PUT may change `enabled`, `channelPrefix` and `archiveDays` only: a `memberIds` or `welcomeTemplate` different from what is stored is `403 prospect_channel_needs_person`. Every saved PUT writes one `scheduling.prospect_channel.update` audit row naming its actor, person or agent, with the saved `enabled` and `memberIds` and whether the welcome changed (never its text). Every answer is `Cache-Control: private, no-store`; an unexpected error is `500 internal`, logged by class name. Twins: the signed-in `get_prospect_channel_settings` and `set_prospect_channel_settings`, served from `@working-theory/mcp-scheduling`.
80
- - `/v1/workspaces/:workspaceId/general` (GET/PUT) — the workspace's own display name and logo, the Pro `workspace` module's general-settings surface (#5371). Registered under `isModuleEnabled("workspace") || isModuleEnabled("multi-tenant")` alongside the site-config routes above, behind the same tenant guard; the scope is always `request.tenant.workspaceId`, never the path param (the guard 403s a mismatch before any handler runs). PUT takes a strict `{ name, logo }` body (name 1–200 chars, trimmed; `logo` an https:// URL, or `null`/empty to clear it) and answers `{ name, logo }`; GET answers `{ name, logo, emailFrom }` (`logo` `null` when the organization's applies, #10021; `emailFrom` #7519 D6), where `emailFrom` is the deployment's sender (`deliverableSenderAddress()` — `AILK_DELIVERABLE_EMAIL_FROM ?? AILK_LEAD_NOTIFICATION_FROM`, the resolver the fulfillment service sends with) or `null` when neither is set, so the Admin's magnet wizard can show it read-only. Role floor on PUT: `workspace-settings` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)) — renaming is an org-level settings write; GET stays open to every member. MCP parity: the GET's twin is `get_workspace_settings` on `/mcp/workspace` (#10951); the PUT has no tool — it needs `workspace-settings`, which is never agent-grantable — recorded in `tests/parity/README.md`.
80
+ - `/v1/workspaces/:workspaceId/general` (GET/PUT) — the workspace's own display name and logo, the Pro `workspace` module's general-settings surface (#5371). Registered under `isModuleEnabled("workspace") || isModuleEnabled("multi-tenant")` alongside the site-config routes above, behind the same tenant guard; the scope is always `request.tenant.workspaceId`, never the path param (the guard 403s a mismatch before any handler runs). PUT takes a strict `{ name, logo }` body (name 1–200 chars, trimmed; `logo` an https:// URL, or `null`/empty to clear it) and answers `{ name, logo }`; GET answers `{ name, logo, emailFrom }` (`logo` `null` when the organization's applies, #10021; `emailFrom` #7519 D6), where `emailFrom` is the full From line the workspace's emails carry — `"<workspace> via <organization>" <address>` (`workspaceSenderHeader`) over the deployment's sender (`deliverableSenderAddress()` — `AILK_DELIVERABLE_EMAIL_FROM ?? AILK_LEAD_NOTIFICATION_FROM`, the resolver the fulfillment service sends with) — or `null` when neither is set, so the Admin's magnet wizard can show it read-only. Role floor on PUT: `workspace-settings` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)) — renaming is an org-level settings write; GET stays open to every member. MCP parity: the GET's twin is `get_workspace_settings` on `/mcp/workspace` (#10951); the PUT has no tool — it needs `workspace-settings`, which is never agent-grantable — recorded in `tests/parity/README.md`.
81
81
  - `/v1/workspaces/:workspaceId/messages/threads` (GET, `?view=&page=`), `/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 thread list (#9686 — a client with a message, or a message with no client, newest first, 25 to a page, with a true count per view `open`/`resolved`/`all`/`archived`; twin `list_inbox_threads`), the workspace's messages whose thread is not archived newest first, the item read (resolves a message handled or not, serving `handledAt`), and Done, which archives the message's thread (#9686 D4). 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 and that is not an order (#9170, the orders bullet below) — both 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 four routes** — `id`, `name`, `email`, `source`, `createdAt`, `handledAt`, `personId`, `body`, `excerpt` — and nothing else (#9349, superseding the 2026-09-19 six-key ruling): `personId` is the lead's Person or `null`; `body` is `payload.message` alone — cut to 16384 code units, line breaks normalized, control, bidi, zero-width and tag characters stripped (`\t` and `\n` kept), trimmed and cut at 4096 code points (`inbox-messages.ts`'s `readMessageBody`), else `null`; `excerpt` is its first line, cut at 140 code points. `payload` itself and every other payload key never cross, and every success body is re-parsed against `inboxMessageSchema` (`inboxMessageListSchema` for the list) — a mismatch is `500 internal_error` logged with issue codes and paths only. `leads-inbox.ts`'s `GET /v1/leads` row is unchanged. PATCH takes `{ "handled": true }` only, `.strict()`, so `{ "handled": false }` is a 400 — Unarchive is #9681's `PATCH …/people/:personId/thread`. **Since #9686 Done is Archive:** it archives the message's client thread through `tenantDb.people.setThreadState` (idempotent) and writes no `handledAt` — that column is read-only legacy, loaded as Archived by the `20261030120000_inbox_thread_state_backfill` migration — and a message with no client is `409 no_thread`; accept no longer marks the message handled. Role floor: the inbox gate `inboxAllowed` (`services/inbox-messages.ts`) — `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), and an AGENT also needs the per-agent `inbox-act` grant on every inbox route, the member-area `…/people/:personId/messages` pair included (#9686 D9, closing SEC-9679-1); checked before any read or write. An Admin listing decision that changes the listing resolves the applicant's thread (`services/thread-auto-resolve.ts`, #9686 D8). 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`). **Agent-session audit (#9683, spec `docs/specs/9683-agent-session-audit-knowledge-spec.md`):** an AGENT's call to any of these four routes, or to the member-area `GET`/`POST …/people/:personId/messages`, writes exactly one audit row whatever its outcome (`inbox.list_messages`, `inbox.get_message`, `inbox.mark_message_done`, `inbox.accept_message`, `people.message.list`, `people.message.create`; a `403`/`400` is `refused` against the workspace), carrying `metadata.agentSession` `{ sessionId, threadId, reason }` from `X-Agent-Session` / `X-Agent-Reason` through `api-workspace/src/lib/agent-session.ts`. `threadId` is derived by the route, never a header: `hub:<personId>` when the call resolved that Person in this workspace, else `workspace:<workspaceId>`. A person's call writes what it wrote before — nothing on these routes (#3591 § 2.3) — except Done, which is a state change and writes one `inbox.mark_message_done` row for every actor (#9686 D10); the thread list writes `inbox.list_threads` per agent call. **Accept links, never creates (#9690 D5, closing #8601):** `POST …/messages/:leadId/accept` stamps `promotedUserId` with the user the lead's Person is already linked to, and only when `personAddressProved` holds; a sender with no proved account is `409 no_account` ("Invite them to sign up"), nothing written — no code path creates a user from an inbox message, and nothing reads the deployment-wide `User` table by a typed address.
82
82
  - `/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, plus `personId` — the lead's Person or `null` — on the item read and the PATCH alone (#9348, `inboxSubmissionItemSchema`); no list row carries it. `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).
83
83
  - `/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).
@@ -91,16 +91,17 @@ Routes are versioned under `/v1/*`:
91
91
  - `/v1/consent/cookie` (POST), `/v1/consent/unsubscribe` (POST), `/v1/consent/sign-up` (GET), `/v1/consent/account` (GET, POST), `/v1/consent/platform` (GET, POST), `/v1/member/consents` (GET, POST), `/v1/workspaces/:workspaceId/people/:personId/consents` (GET) — the consent ledger's routes (#8438, spec `docs/specs/8438-consent-registry-and-ledger-step-spec.md`; #8765, spec `docs/specs/8765-sign-up-refuses-without-the-spec.md`). `consent_grants` is THE ledger: append-only (the database refuses any change to a stored row, and any truncation, on it and on `consent_visitor_links`), every row naming its `source`, its `policyVersion` and, when known, its Person; it has two writers — `src/services/consent.ts` (`recordConsent`, `recordPersonConsent`, `recordCookieChoice`, `linkConsentVisitor`, `recordCheckoutConsent`; every source) and the web's sign-up hook `apps/web/lib/sign-up-agreements.ts` (#8765 D4), which writes only `sign_up` rows (subject `user`) of a user it creates in the same Better Auth transaction, from the evidence `GET /v1/consent/sign-up` built with `consent.ts`'s own functions — and every reader is `src/lib/consent-store.ts` (`DISTINCT ON` current-state reads, never a window). **Two readings of a Person's rows:** the OWN reading (`sign_up`, `account_settings`, `email_unsubscribe` — a verified caller or a signed link) is what the member's screens and any send read; the ANY-SOURCE reading (adds `magnet`, `api`, `cookie_banner`, `checkout`, and linked visitors' cookie rows) is the operator's, marked `unverified` — an anonymous form's row never changes a member's own answer. **The checkout grant (#8765 D13, D14):** `checkout` is the eighth source (the `consent_grants_source_known` CHECK names all eight). The hub webhook's `checkout.session.completed` arm, after the flow-checkout Person step, writes one `account_terms` row (subject `person`, source `checkout`, `sourceRef` the Checkout Session id, locale `en`, the current statement and version) through `recordCheckoutConsent` — one transaction under the `ailk:consent:<workspaceId>:checkout:<sessionId>` lock, nothing written when that Person already holds that session's row — only when `consent.terms_of_service` is `accepted` and `metadata.ailk_terms` is `account_terms@<current version>`; the Person is `services/checkout-buyer.ts`'s `checkoutBuyerPerson` (a proposal session → the piece's Person in its `ailk_workspace` through `lib/proposal-paid-store.ts`'s `proposalPersonId`; a flow checkout → the Person the Person step's `resolveCheckoutPerson` found or created, never created here; a signed-in buyer's `ailk_user_id` → the Person of that user's verified email in the site workspace, test mode included; else, for a paid live-mode session only, `customer_details.email`'s Person). **A spoke purchase records the same grant (#8778):** a spoke's checkout runs on the spoke's own Stripe account, so the hub webhook never sees it; instead the first write of a `spokeCheckout` lead with a Person (`services/lead-routing.ts`) whose `payload.termsAccepted` equals the current `account_terms@<version>` stamp (`currentAccountTermsStamp`) calls `recordCheckoutConsent` for the lead's Person, `sourceRef` the lead's `Idempotency-Key` (the Checkout Session id) — a `null` or absent value writes nothing (`consent_absent`), any other value nothing (`terms_unstamped`), a replay never reaches it (and `termsAccepted` is left out of the replay comparison, so a redelivery across a spoke's update still replays), and the store's per-session guard keeps it to one row; it logs `{ event: "checkout-consent", outcome, siteId }` only and never changes the lead's answer. A `checkout` row is unverified: the payer is not a signed-in user, so it never satisfies the account interstitial. It logs `{ event: "checkout-consent", outcome, eventIdPrefix }` only (`consent_absent`, `terms_unstamped`, `person_unresolved`, `recorded`, `unchanged`, `version_changed` — the site registry has moved past the stamped version, so nothing is written — and `failed`, which adds the error's `errName`) and never changes the 200. A write appends only when the answer changes the reading it is checked against, under an advisory lock on the (subject, purpose) pair. `POST /v1/consent/cookie` takes `{ visitorId, choice, locale }` and never a workspace (it comes from `resolvePublicWorkspace`); `POST /v1/consent/unsubscribe` takes a token signed with `AILK_CONSENT_LINK_SECRET` (≥ 32 bytes, optional; unset ⇒ `503 link_secret_not_configured`) and answers every defect as one `400 invalid_link`. Both are top-level, outside every module gate, in their own rate-limit scopes (`consent`, `unsubscribe`) and on `FORWARDED_VISITOR_ROUTES`. **A sign-up agreement is the account's (#8765 C3, D5, D6):** a `signUp` purpose (`account_terms`) is recorded once per `User`, subject `user` / the user id in the deployment's own site workspace (`resolveSiteWorkspaceId()`, the owner platform consents' footing, read by `userPlatformRows`), never per Person, so the hub and every spoke signed in through it read one row. `GET /v1/consent/sign-up` is anonymous: `{ workspaceId, agreements: [{ purposeId, policyVersion, locale, statement, statementHash }] }` for the site workspace (`locale` default `en`, `null` workspace `503 tenant_unresolved`, `Cache-Control: no-store`), top level beside the cookie route in its own rate-limit scope `signupevidence`, outside every module gate. **Its budget is per site key (#8805):** a request presenting a valid `x-ailk-spoke-key` (`resolveCallerSite` → a registered, unrevoked spoke) is counted against that key's `site,<spokeId>` bucket at `DEFAULT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE` (120; `AILK_RATE_LIMIT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE` overrides) and let through the server-wide per-IP ceiling, so a spoofed `X-Forwarded-For` cannot spend it; an invalid or absent key, or a failed lookup, keeps `DEFAULT_PER_IP_PER_MINUTE_STRICT` per IP. The key picks the bucket only — the workspace stays `resolveSiteWorkspaceId()` (`middleware/rate-limit.ts`'s `siteKeyReader`, `SITE_KEYED_ROUTES`). `GET /v1/consent/account` answers `{ agreements: [{ id, statement, policyVersion, acceptedVersion, acceptedAt, current }], complete }` for the caller (`memberCaller` — a cookie session or a hub credential; a personal token `401`); `POST` takes `{ purposeIds, locale? }`, refuses any id that is not a `signUp` agreement `404 purpose_unknown` before writing anything, writes each through `recordPersonConsent` (source `account_settings`, `sourceRef: spoke:<id>` for a hub credential) and answers the GET body; both register in `authScope` unconditionally and log `{ event: "account-agreements", outcome }` only. The member pair reads and writes that same row for a `signUp` purpose (no Person is created) and is unchanged for every other purpose; a `null` site workspace keeps the old per-Person reading; a hub credential's `via: "sign_up"` is `400 sign_up_window_closed` with nothing written (SEC-8765-B). The member pair and the account pair are in `HUB_SESSION_ROUTES` (26 entries since #8765); the anonymous `GET /v1/consent/sign-up` is not, and neither is `/v1/consent/platform` — it is the deployment owner's own consent to Working Theory, a cookie session holding `platform-consents`, under `multi-tenant`. The banner's visitor id travels in `x-ailk-consent-visitor` (only a v4 UUID counts) on the lead and flow routes and the member write, linking the visitor to the Person; the header is never echoed or logged. A `consent` flow field now stores `{ [purposeId]: boolean }` and writes the ledger at completion (source `magnet`, `sourceRef` the flow slug). The operator's `…/consents` answers `{ own, anySource, history, nextCursor }` (history 500 a page, `Cache-Control: private, no-store`, never a subject id). No MCP twin for any of them, recorded in `tests/parity/README.md`.
92
92
  - `/v1/workspaces/:workspaceId/requests` (GET, `?limit=`), `/v1/workspaces/:workspaceId/requests/:requestId` (GET), `/v1/workspaces/:workspaceId/people/:personId/pieces/:pieceId/versions` (POST) — the provider routes (#8171, `src/routes/workspaces/{requests,pieces}.ts` over `tenantDb(tenant).memberArea`; spec `docs/specs/8171-provider-routes-the-workspace-requests-spec.md`). **The Requests read** lists the workspace's inbound member rows (#8170's messages, quote requests and reviews), newest first, `limit` 1–50 (default 50, no cursor), behind `inbox-read` (every role) checked with `can(tenant.role, …)`. It is tiered: a role holding `people-read` (owner, admin) gets the full row — the subject, body and the kind's own fields (a message's `link`, a quote's `items`, a review's `pieceId`, `version`, `review`); every other caller, every agent key included, gets `{ id, kind, person, createdAt }` and the content is never selected. A row whose payload fails its kind's schema, or whose Person is gone, is left out and counted in one `warn`. **Deliver a version** numbers version n+1 under the piece lock (`withPieceStagesLock`), behind `member-pieces-manage` through `allows` (an agent granted it delivers); the body is exactly one of an `https` link (`isHttpsLink`, else `400 link_not_https`) and a private attachable asset of this workspace (`400 asset_not_found` / `asset_not_attachable`), plus an optional note; `version`, `deliveredBy` and `deliveredAt` are the server's (a body naming one is `400 validation_failed`); a piece with `approvedAt` set is `409 piece_approved`; a malformed, absent or foreign Person or piece is `404 not_found`. There is no round count, limit or remaining count (#8140 disposition 3). It answers `201 { version: { id, pieceId, version, file, link, note, deliveredAt } }` — the file's download name, never an asset id or `deliveredBy` — and every call that reaches the store writes one `people.version.create` audit row. **The single Requests read (#9847, spec `docs/specs/9847-agent-reads-member-request-spec.md`):** `GET /v1/workspaces/:workspaceId/requests/:requestId` answers one inbound member row of the caller's workspace in the list's full shape (`workspaceRequestSchema`, `{ ok: true, data: <row> }`) through `tenantDb(tenant).memberArea.getRequest`. Gate: `inboxAllowed(tenant, "people-read")` before any read — a person whose role holds `people-read`, an agent holding BOTH the `people-read` and `inbox-act` grants (the reply grant, #9714 D5; `member-pieces-manage` is not an alternative); a refusal is `403`. A malformed, absent, outbound, other workspace's or unservable id (payload failing its kind's schema, Person gone — logged `dropped: 1` at `warn`) is one `404 not_found`. The subject, body and each quote answer pass `inbox-messages.ts`'s `stripHiddenText` (zero-width, bidi, BOM and tag characters, SEC-9847-1); the stored row is untouched. Every agent call writes exactly one `people.request.read` audit row — `refused`/`failed` against the workspace, `succeeded` against the interaction with summary `{ kind }` and thread `hub:<personId>` — carrying its session; a person's call writes none. The list's agent view stays the summary row. The thread's `request` entry carries `requestId`, the row's `intx_` id, so an agent can find it. 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`.
93
93
  - `/v1/workspaces/:workspaceId/callbacks` (GET, `?limit=`) — the Inbox callbacks read (#9254, `src/routes/workspaces/callbacks.ts` over `tenantDb(tenant).callbacks`; spec `docs/specs/9254-callback-rows-inbox-spec.md`): the workspace's request-and-confirm `Callback` rows (#5970), newest first, `limit` 1–50 (default 50, the Requests read's own query; any other key `400 validation_failed`), behind `inbox-read` (every role, a member and an agent key included) through `permitted`, checked before any read. Same registration, scope and tenant guard as the Requests read (`workspace || multi-tenant`); the scope is always `request.tenant.workspaceId`. The row is `id`, `name`, `phone`, `preferredTime` (the window asked for, as typed), `personId` (`null` for a callback captured with no email), `confirmedAt`, `confirmedTime`, `paidAt` and `createdAt` — read through the fixed `CALLBACK_ROW_SELECT`, so never `payload`, the confirm digest or expiry, `buyerEmail`, `amountMinor`, `currency` or a Stripe id. The confirm state is the reader's to derive (`paidAt` → paid, else `confirmedAt` → confirmed, else awaiting). No item read, no cursor, no stamp, no audit row; the body is re-parsed against its own `.strict()` schema. The Admin Inbox lists each row under Interested. No MCP twin, recorded in `tests/parity/README.md`.
94
- - `/v1/workspaces/:workspaceId/submissions/:leadId/trial` (POST), `/v1/workspaces/:workspaceId/people/:personId/trial` (GET), `/v1/workspaces/:workspaceId/people/:personId/trial/extend` (POST) — the operator's Start, Get and Extend trial (#9287 C3, `src/routes/workspaces/trial.ts` over `src/services/trial.ts`; spec `docs/specs/9287-operator-started-trials-spec.md` DD2–DD7; Start trial since #9342, spec `docs/specs/9342-start-trial-needs-customers-and-spec.md` DD1–DD7). Same registration, scope and tenant guard as the callbacks read (`workspace || multi-tenant`); the scope is always `request.tenant`. All three need `billing-manage` by role — the owner alone; an admin, a member and every agent key are `403` before any read or Stripe call — and the two POSTs charge a write budget of 30 an hour per person (`chargeWriteBudget` scope `trial`, `429 rate_limited` with `Retry-After`) before their strict body (`bodyLimit` 4 KiB, `400 validation_failed`). The Stripe client is the tenant's own Organization's, `stripeClientForOrganization` only, never the env key (`409 stripe_not_connected`; unusable, or any thrown Stripe error, a fixed `502 stripe_unavailable`, logged by class name only). **Start trial** is a hosted Checkout trial (#9342): it accepts a lead only when it is a `flow:trial` submission of this workspace whose `trial` magnet is a `diagnostic` and names a Person (else one `404 not_found`); the `{ lookupKey }` must be a `plan` `listPlanOfferings` lists (`400 plan_unknown`; a failed read `503 offerings_unavailable`); with no usable `FRONTEND_URL` it is `503 checkout_not_configured` before any Stripe call. It then makes exactly three Stripe calls, all within the Offerings key contract (#8879 §3.3, unchanged): `prices.list` for exactly one active recurring Price under the key (`409 plan_unavailable`); `checkout.sessions.list` of the Person's email's completed sessions, where one tagged `ailk_origin: ailk-trial` is `409 trial_exists` with nothing created; and one session through `lib/stripe.ts`'s `createTrialCheckoutSession` (`@working-theory/stripe-client`) — subscription mode, `trial_period_days: 14`, `payment_method_collection: "if_required"`, `trial_settings.end_behavior.missing_payment_method: "pause"`, the terms box required (`409 terms_not_configured` when the account has no Terms of service URL), `customer_email` the Person's, `subscription_data.metadata` `{ ailk_origin: "ailk-trial", ailk_workspace, ailk_person, site }` with `site` the workspace id (`TRIAL_ORIGIN_TAG`), returning to `<FRONTEND_URL origin>/trial`, keyed `trial-checkout:<leadId>:<lookupKey>`. It calls no Customers or Subscriptions endpoint and writes nothing to the Person: Stripe creates the customer and the trialing subscription when the person completes Checkout, and the hub's licensing module (`@working-theory/api-hub`'s `src/licensing/`, #9383 DD3) mints from `customer.subscription.created` only for a subscription traced to the session Start trial recorded. A session URL `isStripeCheckoutUrl` refuses is `502 stripe_unavailable` with nothing sent. Before anyone is sent the link the session is recorded (`recordCheckoutSession`, #9383) with the workspace, the Organization, the Price and key it read and the connection's mode; a failed record expires the session on the same client and is `502 stripe_unavailable` with nothing sent, and a `conflict` whose stored record is equal in every field is the idempotent replay and succeeds. The person is then emailed the link (`@working-theory/email`'s `sendTrialCheckoutEmail`, from `deliverableSenderAddress()`); a failed send is one `warn` with its kind and still a success. The answer is `201 { checkout: { url, emailed } }` with `Cache-Control: private, no-store`, re-parsed against `startTrialResponseSchema`. **Get trial** reads the Person's newest RECORDED Start-trial session (#8047 DD5): of the Person's email's ten newest complete sessions, those tagged `ailk-trial`, this workspace and this Person, the newest whose session record names this Organization, workspace and mode — never a customer found by email or stored on the Person — and serves its subscription as `{ subscriptionId, status, trialEnd, lookupKey }`, or `null`. **Extend trial** moves that trial's `trial_end` with `proration_behavior: "none"` only while it is `trialing` (`409 trial_not_active`), to a `trialEnd` strictly later than the current one and no later than 90 days after the request (`400 trial_end_invalid`), nothing written on a refusal. **Get and Extend trial need Subscriptions access, which a key that keeps §3.3 lacks** (#9342 DD7): on such a key Stripe refuses, the route answers `502 stripe_unavailable` and the Person page hides its Trial box; they work on a key that grants that access. Each success writes one `recordAuditAction` row naming the actor and the Person — `people.trial.start` (summary `{ emailed }`, `"true"` or `"false"`) and `people.trial.extend`; a refusal writes none, and Start trial does not mark the lead handled. No log line or audit summary carries the Checkout URL, and no response, log line or audit summary carries an email, a key or a `cus_`/`price_` id (the one `cs_` id served is inside Start trial's URL); Get and Extend's bodies are re-parsed against `trialResponseSchema` (`@working-theory/validation`'s `trial.ts`). No MCP twin — owner-only, recorded in `tests/parity/README.md`. **The managed-service licence** (#9402, spec `docs/specs/9402-managed-service-trials-deliver-the-spec.md` DD5): `/v1/workspaces/:workspaceId/people/:personId/trial/licence` (GET) and `…/trial/licence/reveal` (POST) sit in the same plugin and, like the trial routes, need `billing-manage` by role (#9841, narrowing #9402 DD5's staff audience) — the owner alone; an admin, a member and every agent key are `403` before any read. They read a managed-service trial's licence through the fulfilment seam's optional `readManagedLicence` (`services/offerings/fulfilment-hooks.ts`, built with `fulfilmentContextFor` from the tenant's own client): the GET answers `{ licence }` — `null`, `{ live: false }` or `{ live: true, tier, expiresAt }`, never a key — and the POST charges its own write budget (scope `licencereveal`, 30 an hour per person), takes a strict empty body, and answers `{ key }` only after one `people.trial.licence_reveal` audit row is written (`503 audit_unavailable` and no key when it is not). A licence the issuer recorded for the customer at mint reads as `none` (#9402 AC 5, entitlements#19), whatever the Product is today. `none`/`not_live` on the reveal, and an Organization whose hook has no staff read, are `404 licence_not_found`; a read that cannot be made is `502 licence_unavailable`. Both answer `Cache-Control: private, no-store`; no log line or audit row carries the key. No MCP twin, recorded in `tests/parity/README.md`.
94
+ - `/v1/workspaces/:workspaceId/submissions/:leadId/trial` (POST), `/v1/workspaces/:workspaceId/people/:personId/trial` (GET), `/v1/workspaces/:workspaceId/people/:personId/trial/extend` (POST) — the operator's Start, Get and Extend trial (#9287 C3, `src/routes/workspaces/trial.ts` over `src/services/trial.ts`; spec `docs/specs/9287-operator-started-trials-spec.md` DD2–DD7; Start trial since #9342, spec `docs/specs/9342-start-trial-needs-customers-and-spec.md` DD1–DD7). Same registration, scope and tenant guard as the callbacks read (`workspace || multi-tenant`); the scope is always `request.tenant`. All three need `billing-manage` by role — the owner alone; an admin, a member and every agent key are `403` before any read or Stripe call — and the two POSTs charge a write budget of 30 an hour per person (`chargeWriteBudget` scope `trial`, `429 rate_limited` with `Retry-After`) before their strict body (`bodyLimit` 4 KiB, `400 validation_failed`). The Stripe client is the tenant's own Organization's, `stripeClientForOrganization` only, never the env key (`409 stripe_not_connected`; unusable, or any thrown Stripe error, a fixed `502 stripe_unavailable`, logged by class name only). **Start trial** is a hosted Checkout trial (#9342): it accepts a lead only when it is a `flow:trial` submission of this workspace whose `trial` magnet is a `diagnostic` and names a Person (else one `404 not_found`); the `{ lookupKey }` must be a `plan` `listPlanOfferings` lists (`400 plan_unknown`; a failed read `503 offerings_unavailable`); with no usable `FRONTEND_URL` it is `503 checkout_not_configured` before any Stripe call. It then makes exactly three Stripe calls, all within the Offerings key contract (#8879 §3.3, unchanged): `prices.list` for exactly one active recurring Price under the key (`409 plan_unavailable`); `checkout.sessions.list` of the Person's email's completed sessions, where one tagged `ailk_origin: ailk-trial` is `409 trial_exists` with nothing created; and one session through `lib/stripe.ts`'s `createTrialCheckoutSession` (`@working-theory/stripe-client`) — subscription mode, `trial_period_days: 14`, `payment_method_collection: "if_required"`, `trial_settings.end_behavior.missing_payment_method: "pause"`, the terms box required (`409 terms_not_configured` when the account has no Terms of service URL), `customer_email` the Person's, `subscription_data.metadata` `{ ailk_origin: "ailk-trial", ailk_workspace, ailk_person, site }` with `site` the workspace id (`TRIAL_ORIGIN_TAG`), returning to `<FRONTEND_URL origin>/trial`, keyed `trial-checkout:<leadId>:<lookupKey>`. It calls no Customers or Subscriptions endpoint and writes nothing to the Person: Stripe creates the customer and the trialing subscription when the person completes Checkout, and the hub's licensing module (`@working-theory/api-hub`'s `src/licensing/`, #9383 DD3) mints from `customer.subscription.created` only for a subscription traced to the session Start trial recorded. A session URL `isStripeCheckoutUrl` refuses is `502 stripe_unavailable` with nothing sent. Before anyone is sent the link the session is recorded (`recordCheckoutSession`, #9383) with the workspace, the Organization, the Price and key it read and the connection's mode; a failed record expires the session on the same client and is `502 stripe_unavailable` with nothing sent, and a `conflict` whose stored record is equal in every field is the idempotent replay and succeeds. The person is then emailed the link (`@working-theory/email`'s `sendTrialCheckoutEmail`, from `deliverableSenderAddress()` named "<workspace> via <organization>"); a failed send is one `warn` with its kind and still a success. The answer is `201 { checkout: { url, emailed } }` with `Cache-Control: private, no-store`, re-parsed against `startTrialResponseSchema`. **Get trial** reads the Person's newest RECORDED Start-trial session (#8047 DD5): of the Person's email's ten newest complete sessions, those tagged `ailk-trial`, this workspace and this Person, the newest whose session record names this Organization, workspace and mode — never a customer found by email or stored on the Person — and serves its subscription as `{ subscriptionId, status, trialEnd, lookupKey }`, or `null`. **Extend trial** moves that trial's `trial_end` with `proration_behavior: "none"` only while it is `trialing` (`409 trial_not_active`), to a `trialEnd` strictly later than the current one and no later than 90 days after the request (`400 trial_end_invalid`), nothing written on a refusal. **Get and Extend trial need Subscriptions access, which a key that keeps §3.3 lacks** (#9342 DD7): on such a key Stripe refuses, the route answers `502 stripe_unavailable` and the Person page hides its Trial box; they work on a key that grants that access. Each success writes one `recordAuditAction` row naming the actor and the Person — `people.trial.start` (summary `{ emailed }`, `"true"` or `"false"`) and `people.trial.extend`; a refusal writes none, and Start trial does not mark the lead handled. No log line or audit summary carries the Checkout URL, and no response, log line or audit summary carries an email, a key or a `cus_`/`price_` id (the one `cs_` id served is inside Start trial's URL); Get and Extend's bodies are re-parsed against `trialResponseSchema` (`@working-theory/validation`'s `trial.ts`). No MCP twin — owner-only, recorded in `tests/parity/README.md`. **The managed-service licence** (#9402, spec `docs/specs/9402-managed-service-trials-deliver-the-spec.md` DD5): `/v1/workspaces/:workspaceId/people/:personId/trial/licence` (GET) and `…/trial/licence/reveal` (POST) sit in the same plugin and, like the trial routes, need `billing-manage` by role (#9841, narrowing #9402 DD5's staff audience) — the owner alone; an admin, a member and every agent key are `403` before any read. They read a managed-service trial's licence through the fulfilment seam's optional `readManagedLicence` (`services/offerings/fulfilment-hooks.ts`, built with `fulfilmentContextFor` from the tenant's own client): the GET answers `{ licence }` — `null`, `{ live: false }` or `{ live: true, tier, expiresAt }`, never a key — and the POST charges its own write budget (scope `licencereveal`, 30 an hour per person), takes a strict empty body, and answers `{ key }` only after one `people.trial.licence_reveal` audit row is written (`503 audit_unavailable` and no key when it is not). A licence the issuer recorded for the customer at mint reads as `none` (#9402 AC 5, entitlements#19), whatever the Product is today. `none`/`not_live` on the reveal, and an Organization whose hook has no staff read, are `404 licence_not_found`; a read that cannot be made is `502 licence_unavailable`. Both answer `Cache-Control: private, no-store`; no log line or audit row carries the key. No MCP twin, recorded in `tests/parity/README.md`.
95
95
  - `/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).
96
96
  - `GET /v1/workspaces/:workspaceId/knowledge` — the workspace knowledge read (#9683, spec `docs/specs/9683-agent-session-audit-knowledge-spec.md`; `packages-paid/api-workspace/src/routes/workspaces/knowledge.ts`, `// oss: false`): what the business offers, runs and serves, as `workspaceKnowledgeSchema` — `offerings` (the shown offering set, only while the commerce claim is held), `magnets` (the newest flows page's `live` rows), `meetingTypes` (the enabled slugs minus `privateSlugs`, titled by slug), `sitesServed` (the installed hub's live spokes for this workspace, read only when the hub's own gate answers `claimed`, through the optional `HubRegistry.listLiveSpokesForWorkspace`) and `strategyDocs` (`lib/strategy-docs.ts`, `[]` until a store exists) — every key always present, each entry an id, a title and a summary (`null` when it fails its check; an entry whose id or title fails is skipped and counted). Takes no query. Gate: `allows(people-read) || allows(people-memory-propose)` — a person member holds both; an agent only by grant. Every authenticated call writes one `workspace.knowledge.read` audit row (counts only; an agent's carries its session, thread `workspace:<workspaceId>`); `Cache-Control: private, no-store`. Same registration scope as the routes above (`workspace || multi-tenant`, `tenant:settings`). MCP twin: `get_workspace_knowledge` on `/mcp/workspace`.
97
97
  - `/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 nine 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, `member-pieces-manage` since #7878, and `people-memory-propose` and `inbox-act` since #9679 (`@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 nine check `allows(tenant, "<permission>")`, which reads the grants — except that the six existing inbox `inbox-act` checks still read `can(tenant.role, …)` until #9686 moves them, and `people-memory-propose` is read today only by the workspace knowledge read (#9683, beside `people-read`); 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`).
98
98
  - `GET /v1/workspaces/:workspaceId/clients` and `DELETE /v1/workspaces/:workspaceId/clients/:clientId[?userId=]` — the workspace's Connected clients (#10393, `src/routes/workspaces/clients.ts` over `src/lib/connected-clients-store.ts`, `// oss: false`). The GET lists, as one table, the workspace's live OAuth authorizations (one row per client and person, from the token rows bound to this workspace; `lastUsedAt` is the newest sign-in or refresh) and its enabled agent keys, each row `kind`, `id`, `client.name`, `person`, `scopes`, `lastUsedAt` and never a token or key. A person holding `agents-manage` (owner, admin) sees every row; anyone else, an agent principal included, sees only their own person's. The DELETE refuses every agent caller (403), ends an OAuth authorization by deleting its token rows for this workspace only (a caller without `agents-manage` may name only themselves — another person's row is the same 404 as a missing one) and an agent key by switching it off (`agents-manage`), touches no session, and writes one audit row and one `connected-client-revoked` log line. The GET's MCP twin is `list_connected_clients`; the DELETE has no tool, by decision. Same registration scope as the routes above (`workspace || multi-tenant`).
99
99
  - `GET /v1/workspaces/:workspaceId/discovery` and `PUT /v1/workspaces/:workspaceId/discovery` — the owner's discovery switch, whether AI and search tools can find the workspace's site (#10510, `src/routes/workspaces/discovery.ts`, `// oss: false`, over `packages/api/src/services/site-discovery.ts`). Both parse `:workspaceId` with `inboxWorkspaceParamsSchema` (`400 validation_failed`) and act on `request.tenant.workspaceId` only. The GET needs any tenant, an agent included, and answers `{ ok: true, data: { discoverable } }`; the PUT needs `workspace-settings` (owner, admin — an agent is refused, `403`), checked before the strict `{ discoverable: boolean }` body (`400 validation_failed` on anything else), and answers the stored value. The GET's MCP twin is `get_site_discovery`; the PUT has no tool, by decision. Same registration scope as the routes above (`workspace || multi-tenant`, one `tenant:settings` row).
100
100
  - `/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 `X-Draft-Version`; `If-Match` still accepted for one release, #10264), 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. MCP parity: on `/mcp/workspace`, the create's twin is `create_page` (#10956), the draft read and save are `read_report` and `save_draft` (#10336), and the publish is `publish_draft` (#10661); the list and unpublish have none, as `tests/parity/README.md` and the registry record.
101
+ - `/v1/workspaces/:workspaceId/library/pages` (GET, `?type=&status=&limit=&page=`) and `/v1/workspaces/:workspaceId/library/assets` (GET, `?tag=&type=&limit=&page=`) — the library reads, each answering `{ workspace: { id, name }, items, total, page, nextPage }` newest first (`limit` 1–200, default 50; `page` from 1; `libraryPageListQuerySchema` / `libraryAssetListQuerySchema` in `@working-theory/validation`). The page list (`packages-paid/api-content-write/src/routes/workspaces/library-pages.ts`, in the content-write tenant scope) serves every page, drafts included, as `{ id, type, slug, locale, title, status, updatedAt }`; `status` is the Docs list's rule — `disabled` when switched off, else `live` when a version is published (a newer draft included), else `draft` — and the route needs `content-edit` (`allows`, so an agent needs the grant). A disabled page is asked for only on a person's behalf: `tenantDb` keeps every disabled row from an agent. The asset list (`packages-paid/api-workspace/src/routes/assets/manage.ts`, beside the manage list, `assets-read`) serves `{ id, key, filename, type, tags, url, updatedAt }` — `type` is the content type, `url` the public read's path, `updatedAt` when the current file was uploaded — the `createdAt` of the version `currentVersion` names (`tenantDb.assets.currentVersionTimes`), so a replace moves it, a restore takes the restored version's upload time, and a metadata edit does not move it; the list is ordered by it, newest first — narrowed by an exact `tag` and a `type` that is a whole content type (`image/png`) or its top-level part (`image`); a file tagged `private` never lists, `?tag=private` included. MCP parity: `list_workspace_pages` and `list_assets` on `/mcp/workspace`.
101
102
  - `/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`, attached to any member-area message, or (#8171 D3) named by a delivered piece version (one `pieceVersion.count`, since the tag can be removed after delivery), so such a file's bytes are served only by its owner's member reads.
102
103
  - `/v1/subscription/me` (GET) — `?include=billing` (#8171 D7), from a cookie session only, adds the optional `planName` and `paymentMethod` (brand, last four, expiry) read from Stripe through `lib/stripe.ts`'s `readCustomerBillingSummary` for the caller's own resolved customer: cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure leaves both keys absent, a value outside the schema's bounds is `null`, and no id is served or logged. A bearer token, another value or none answers exactly as before.
103
- - `/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). **The read's `commerce` field (#8907 D14)** is the deployment's commerce claim, `claimed | unclaimed | undetermined` (`resolveCommerceClaim()`; a rejected read is `undetermined` and the answer stays `200`) — what the Admin's Billing card reads (#8908 D10). **`?include=billing` (#9067 D1)** — exactly that string, never an array — adds `details` only for a caller holding `billing-manage` (the owner; an agent never qualifies): `licenseExpiresAt` (`checkLicense().expiresAt`, `null` on a failed read) always, and for an Organization with a Stripe customer `renewsAt` (the current subscription's first item's `current_period_end`, only while it will renew), `sites` (its quantity) and `paymentMethod` (brand, last four, expiry), read through `lib/stripe.ts`'s `readCustomerBillingSummary` by `services/entitlements.ts`'s `readOrgBillingSummary` — cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure answers `details: { licenseExpiresAt }` and still `200`, a value outside `orgBillingDetailsSchema`'s bounds is `null`, no id is served or logged, and the reply carries `Cache-Control: private, no-store`. Every other request is answered exactly as before, with no Stripe or licence read. **`POST /v1/billing/plan-checkout` (#9067 D3, `routes/billing/plan-checkout.ts`)** is the Billing tab's Purchase plan: a subscription Checkout for the caller's own Organization's plan (`planPurchaseLookupKey` — `ailk-pro_monthly` / `ailk-pro-plus_monthly`, `PLAN_PURCHASE_LOOKUP_KEYS` built by the Offerings lookup-key grammar, #9338 DD1), sandbox-only like the portal. **It sells only an Offerings plan (#9338 DD4):** `createCheckoutSession` gets a `refuseProduct` that refuses every Product whose `metadata.ailk_group` is not exactly `plan` (`isOfferingsPlanProduct`, `services/offerings/catalog.ts`), checked on the same expanded Price it sells; a refused or unexpanded Product answers `500 plan_price_missing`. Check order: tenant → `billing-manage` (403 before any lookup) → write budget (`chargeWriteBudget` scope `plancheckout`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{ returnUrl }` (`bodyLimit` 4 KiB, `400 validation_failed`) → the return URL (canonical, no userinfo, query, fragment or `//` path, `https:` or a local `http:`, on `config.TRUSTED_ORIGINS`; `400 return_url_refused`, `500 config-error` when none is trusted) → no customer yet (`409 billing_customer_exists`) and a purchasable tier (`409 plan_not_purchasable`) → `STRIPE_SECRET_KEY` and `assertSandboxKey` → one payable session (an open earlier one is expired first, a completed one is `409 purchase_pending`) → `createCheckoutSession` with `mode: "subscription"`, 1–50 sites, `metadata` and `subscriptionMetadata` `{ organizationId, ...siteStamp() }` and `PLATFORM_TERMS_OF_SERVICE`, never a `buyer` → a Checkout URL only → the session id recorded on `Organization.planCheckoutSessionId` by compare-and-set (a lost race or a failed write expires the new session). It answers `{ url }` with `Cache-Control: private, no-store`; no body or log line carries the return URL, an id or a Stripe message. **The webhook's Organization arm binds only that recorded session (#9067 D13):** a `checkout.session.completed` with `metadata.organizationId` links `session.customer` through one guarded `updateMany` on `{ id, planCheckoutSessionId: session.id, billingCustomerId: null }` (clearing the session); anything else — an unrecorded session, a bound customer, every `customer.created` — writes nothing and logs `org_bind_unproven`. No MCP twin for the purchase — owner-only, recorded in `tests/parity/README.md`.
104
+ - `/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). **The read's `commerce` field (#8907 D14)** is the deployment's commerce claim, `claimed | unclaimed | undetermined` (`resolveCommerceClaim()`; a rejected read is `undetermined` and the answer stays `200`) — what the Admin's Billing card reads (#8908 D10). **`?include=billing` (#9067 D1)** — exactly that string, never an array — adds `details` only for a caller holding `billing-manage` (the owner; an agent never qualifies): `licenseExpiresAt` (`checkLicense().expiresAt`, `null` on a failed read) always, and for an Organization with a Stripe customer `renewsAt` (the current subscription's first item's `current_period_end`, only while it will renew), `sites` (its quantity) and `paymentMethod` (brand, last four, expiry), read through `lib/stripe.ts`'s `readCustomerBillingSummary` by `services/entitlements.ts`'s `readOrgBillingSummary` — cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure answers `details: { licenseExpiresAt }` and still `200`, a value outside `orgBillingDetailsSchema`'s bounds is `null`, no id is served or logged, and the reply carries `Cache-Control: private, no-store`. Every other request is answered exactly as before, with no Stripe or licence read. **`POST /v1/billing/plan-checkout` (#9067 D3, `routes/billing/plan-checkout.ts`)** is the Billing tab's Purchase plan: a subscription Checkout for the caller's own Organization's plan (`planPurchaseLookupKey` — `ailk-pro_monthly` / `ailk-pro-plus_monthly`, `PLAN_PURCHASE_LOOKUP_KEYS` built by the Offerings lookup-key grammar, #9338 DD1), on the admitted key like the portal (#8463). **It sells only an Offerings plan (#9338 DD4):** `createCheckoutSession` gets a `refuseProduct` that refuses every Product whose `metadata.ailk_group` is not exactly `plan` (`isOfferingsPlanProduct`, `services/offerings/catalog.ts`), checked on the same expanded Price it sells; a refused or unexpanded Product answers `500 plan_price_missing`. Check order: tenant → `billing-manage` (403 before any lookup) → write budget (`chargeWriteBudget` scope `plancheckout`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{ returnUrl }` (`bodyLimit` 4 KiB, `400 validation_failed`) → the return URL (canonical, no userinfo, query, fragment or `//` path, `https:` or a local `http:`, on `config.TRUSTED_ORIGINS`; `400 return_url_refused`, `500 config-error` when none is trusted) → no customer yet (`409 billing_customer_exists`) and a purchasable tier (`409 plan_not_purchasable`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` → one payable session (an open earlier one is expired first, a completed one is `409 purchase_pending`) → `createCheckoutSession` with `mode: "subscription"`, 1–50 sites, `metadata` and `subscriptionMetadata` `{ organizationId, ...siteStamp() }` and `PLATFORM_TERMS_OF_SERVICE`, never a `buyer` → a Checkout URL only → the session id recorded on `Organization.planCheckoutSessionId` by compare-and-set (a lost race or a failed write expires the new session). It answers `{ url }` with `Cache-Control: private, no-store`; no body or log line carries the return URL, an id or a Stripe message. **The webhook's Organization arm binds only that recorded session (#9067 D13):** a `checkout.session.completed` with `metadata.organizationId` links `session.customer` through one guarded `updateMany` on `{ id, planCheckoutSessionId: session.id, billingCustomerId: null }` (clearing the session); anything else — an unrecorded session, a bound customer, every `customer.created` — writes nothing and logs `org_bind_unproven`. No MCP twin for the purchase — owner-only, recorded in `tests/parity/README.md`.
104
105
  - `/v1/billing/stripe-connection` (GET, PUT, DELETE), `/v1/billing/stripe-connection/live` (POST), `/v1/billing/stripe-connection/webhook-secret` (PUT), `/v1/billing/stripe-connection/webhook-reset` (POST) — the Organization's own Stripe connection (#8907, `src/routes/billing/stripe-connection.ts`; spec `docs/specs/8907-the-organization-stripe-connection-custody-spec.md`; contract `docs/specs/8879-the-offerings-security-contract-key-spec.md`). Registered from `routes/billing/index.ts`, so the same multi-tenant tenant scope and module gate; the target is always `request.tenant.organizationId`. **Data access and the cipher** are `src/services/offerings/connection.ts`, the only file that touches the StripeConnection model (exactly ten delegate calls, `architecture.yaml` `paths_scoped`): the key and the webhook secret are AES-256-GCM ciphertext under `STRIPE_CONNECTION_KEY`, bound to the Organization, the column and (for the secret) the mode; decryption also tries `STRIPE_CONNECTION_KEY_PREVIOUS`. The GET needs `billing-read` and answers `null` or exactly `{ mode, last4, webhookPath, webhookSecretSet, connectedAt, liveAt, updatedAt }` (a corrupt row `500 connection_unreadable`); with no stored row it answers `{ source: "environment", mode }` to the Organization that owns `STRIPE_SECRET_KEY` and `null` to every other (#9285 — without the `multi-tenant` module selected the single Organization owns it; with it selected in `AILK_ENABLED_MODULES`, whether or not the licence claims it (#9968), only the one `STRIPE_ENV_ORGANIZATION_ID` names, so unset is nobody: a deployment that selects `multi-tenant` must set `STRIPE_ENV_ORGANIZATION_ID` for any Organization to own the environment key, a downgraded one whose licence no longer claims the module included), and that Organization's Offerings reads and shown set go through the same key (`services/offerings/connection.ts`'s `getOfferingsConnectionState` and the `stripeClientForOrganization` fallback), but its checkout stays on the env path — `resolveOfferingsCheckoutPath` returns the Offerings path only for a stored connection, because a session stamped `ailk_offering` on the environment key is acked `offerings_path` by the legacy webhook and never recorded (#9296; the bridge until a stored connection exists, #8936); every write needs `billing-manage` (the owner alone), checked before the body is read, and answers `{ mode, webhookSecretSet, liveAt, updatedAt }` — never `last4` or the path. PUT `{ key }` admits a restricted test key only (`400 stripe_key_refused` with a `reason` from the class table: `key_unrestricted`, `key_publishable`, `live_key_needs_go_live`, `key_unrecognized`); a replace keeps the webhook token and returns the connection to test mode, clearing a live secret. POST `…/live` `{ key, webhookSecret, confirm: "go-live" }` admits a restricted live key only when a cookie session (`403 session_required`), the commerce claim (`409 commerce_required`, `503 license_undetermined`), a production build (`409 live_mode_unavailable` — `lib/stripe.ts`'s `isProductionBuild`), the confirmation (`400 confirmation_required`) and a `whsec_` secret (`400 webhook_secret_invalid`) all hold. Connect and go-live run three read probes — `products.list`, `prices.list`, `checkout.sessions.list`, together, 10 s — through `lib/stripe.ts`'s `stripeClientForConnection` (the per-key factory's one caller, confined in `architecture.yaml`) before anything is stored: `400 stripe_key_refused` `key_not_usable` or `502 stripe_unavailable`, nothing written. The secret PUT binds it to the row's mode; the reset mints a new token and clears the secret; DELETE removes the row, so the token's lookup (`findStripeConnectionByWebhookToken`, #8861's receiver) answers `not-found` at once; it is a compare-and-swap on the row it read, so it answers `{ revoked: false }` when that read found none, and `409 connection_changed` when the row keeps changing between the read and the delete. On a build that is not production, every write to a live row is `409 live_mode_unavailable` and nothing decrypts one. With `STRIPE_CONNECTION_KEY` unset, connect, go-live and the secret answer `503 credential_key_not_configured`; the GET, reset and DELETE need no key and no claim. **The write budget (K10):** every write but DELETE that passes the permission is counted, refused keys included — 10 an hour per Organization, 20 per person (`middleware/rate-limit.ts`'s `chargeWriteBudget`, always its own database store) — `429 rate_limited` with `Retry-After`. Every success writes one `billing.stripe_connection.<connect|replace|go_live|webhook_secret|webhook_reset|remove>` audit row whose summary is `{ mode, last4 }` and emails every owner, the actor included (`@working-theory/email`'s `sendStripeConnectionChangedEmail`); neither can change the answer. Every response is `Cache-Control: private, no-store`; no response, log line, audit row or email carries the key, the secret, the token or a ciphertext. The rekey bin is `stripe-connections:rekey` (`node dist/bin/stripe-connections-rekey.js`), run with the production environment; anywhere else it answers `not_production` and touches nothing. No MCP twin — owner-only key custody that no agent can hold, recorded in `tests/parity/README.md`.
105
106
  - `/v1/billing/stripe-products` (GET, PUT) — the may-sell product list and the org-enabled write (#8922, `src/routes/billing/stripe-products.ts`; spec `docs/specs/8922-the-may-sell-product-list-spec.md`; contract A12, G3, G4, T6). Registered from `routes/billing/index.ts`, so the same multi-tenant tenant scope and module gate; the target is always `request.tenant.organizationId`. Check order: tenant → permission (GET `billing-read`, owner and admin; PUT `billing-manage`, the owner alone — checked before the body, so an admin, a member and an agent key get `403` whatever they send) → the commerce claim (`409 commerce_required`, `503 license_undetermined` with `Retry-After: 300`) → the body → the connection → the catalog read. The GET answers `{ ok: true, data: { connected, products } }`: every active Product `normalizeCatalog` keeps, offerings first in its order then the held ones, each exactly `{ productId, name, description, enabled, heldReason }` — `heldReason` an `OFFERINGS_HELD_REASONS` value or `null`, a held entry always `enabled: false` with `description: null`, and no price, lookup key, image or URL. No connection is `connected: false, products: []`; a corrupt one is `409 connection_unreadable` on both routes, never the empty list. The PUT takes a strict `{ productIds }` (`bodyLimit` 32 KiB; `400 validation_failed` for a malformed body, a duplicate or a malformed id) and replaces the whole set: more than 100 ids, an id in neither list, and a held id are `400 offerings_enabled_refused` with `reason` `too_many_products`, `product_not_in_catalog` or `product_held` (the lookup-key gate — `needs_lookup_key` covers a missing `{plan}_{period}` key and a period that disagrees with the Price, `plan_conflict` a plan two Products share), nothing written; no connection is `409 stripe_not_connected`. It answers the GET body for the new set, parsed before the write. The set's one writer is `services/offerings/store.ts`'s `writeEnabledProductIds` (an `upsert`, `architecture.yaml` `paths_scoped`), through `services/offerings/index.ts`'s `listOrgProducts` and `setOrgEnabledProducts`; both share the per-Organization catalog read (one a minute per process, T7), so `getOrgEnabledProducts` afterwards reads the row with no Stripe call. The catalog comes from `services/offerings/source.ts`'s `stripeCatalogSourceFor` — the Organization's own client (`stripeClientForOrganization`), paged at most 10 product and 30 price calls, 20 s for the whole read, confined in `architecture.yaml`; a disconnected or unusable connection rejects rather than reading as empty, and any source failure is `502 offerings_source_unavailable` with a fixed message. Every successful write records one `offerings.enabled.set` audit row naming the actor, whose summary is `{ enabled, added, removed }` counts only; a failed audit write is one `error` line and the answer stays `200`. Every response is `Cache-Control: private, no-store`, every error message is fixed, and no log line carries a product or price id, a name or the body. The wire names are #8923's, the Admin card that reads it. No MCP twin — owner and admin settings that no agent can hold, recorded in `tests/parity/README.md`.
106
107
  - `/v1/workspaces/:workspaceId/offerings` (GET, PUT) — the Library → Offerings tab's read and the workspace's selection write (#8926, `src/routes/workspaces/offerings.ts`; spec `docs/specs/8926-the-workspace-offerings-route-get-spec.md`; contract A12, T6, T7; the wire shape is #8928 D10's, made per Stripe Price by #9070, spec `docs/specs/9070-the-workspace-offerings-page-becomes-spec.md`). Registered in the multi-tenant tenant scope beside the billing routes; every read and write keys on `request.tenant`, never the path or the body. The GET is open to every member, an agent key included: with the `commerce` claim `unclaimed` it answers `{ status: "unavailable", reason: "no_commerce" }`, with no StripeConnection `reason: "no_connection"` (both `200`, no catalog read); `undetermined` is `503 license_undetermined` with `Retry-After: 300`, and an unreadable connection is `502 offerings_source_unavailable`, never unconnected or an empty list. Available, it answers `{ status: "available", products, shown, recommended: { plan, addon } }`: `products` are `getOrgEnabledProducts`' offerings (enabled and sellable, the normalizer's order, plans before add-ons, each `recommended: false`, never a held product), `shown` one `{ productId, periods }` per Product with an effective shown Price, in products order with each Product's periods in its Price order, and each Recommended only while it is such a Product of its group, read from the selection row (`readWorkspaceSelection`), never the snapshot; a read never rewrites the row. **The shown set is per Stripe Price (#9070):** the row stores `shown_price_ids` beside `shown_product_ids` (the Products with at least one of them), and `services/offerings/index.ts`'s `shownPriceIdsFor` is the one rule every reader applies — the stored Price ids the catalog still carries, or, for a row saved before #9070 (none stored), every Price of each shown Product; a Price the seller replaced in Stripe is off until switched on. The PUT needs `workspace-settings` (owner, admin; never agent-grantable) checked by role before the body, then the claim (`409 offerings_unavailable`, `503 license_undetermined`), then a write budget charged before the body — 30 saves an hour per person, then 60 per Organization only while the person is within theirs (`chargeWriteBudget`, scope `offeringsshown`; `429 rate_limited` with `Retry-After`) — then a strict `{ productId, period, shown }` — ONE Price's switch, named by its Product and period, never a price id (`bodyLimit` 32 KiB, `400 validation_failed`, so no body can name a Recommended or a whole set) — the connection (`409 offerings_unavailable` for none, `502` for unreadable) and the catalog read (`502 offerings_source_unavailable`). A Product that is not enabled and sellable is `400 offerings_shown_refused` `reason: "product_not_enabled"`, a period it has no Price for `reason: "price_not_offered"`, nothing written; it never writes the Organization's enabled set. The save adds or removes that Price from the previous row's effective set (a legacy row expanded once, here), and keeps each stored Recommended while its Product keeps a shown Price, clearing it otherwise — it never sets one (a Recommended is written only by code or a recommender). A save goes through `services/offerings/store.ts`'s `updateWorkspaceSelection`, which reads the stored selection and `upsert`s the next one in one transaction under the advisory lock `ailk:workspace-offerings:<workspaceId>` (#9970 D7), creating the row on a first save and never naming the snapshot (`architecture.yaml` `paths_scoped`), records one `offerings.shown.set` audit row whose summary is `{ shown, added, removed, recommended }` counts only — `shown`, `added` and `removed` count Prices against the previous effective set since #9070 (a failed audit is one `error` line and the answer stays `200`), and awaits `refreshWorkspaceSnapshot` with `force` — logged once as `snapshot_refreshed` or `snapshot_pending`; a failed refresh never fails the save — then answers `{ shown, recommended }`. Every response is `Cache-Control: private, no-store`, every error message is fixed, and no log line carries a product or price id, a name or the body. MCP parity: the GET's twin is `get_workspace_offerings` on `/mcp/workspace` (#10949); the PUT has no tool — it needs `workspace-settings`, which is never agent-grantable — recorded in `tests/parity/README.md`.
@@ -112,7 +113,7 @@ Routes are versioned under `/v1/*`:
112
113
  - `POST /v1/slack/events` — the prospect channel's Slack Events API receiver (#9854, `packages-paid/api-scheduling/src/routes/webhooks/slack-events.ts`). Every Organization's Slack app points its Request URL here; the path carries no parameter and no token (#9339). The event's `team_id` finds the one `SlackConnection` (`findSlackConnectionByTeam`, which answers the Organization, the team and the decrypted signing secret — never the bot token — and logs nothing), and THAT connection's own signing secret verifies Slack's `v0` signature over the raw body with a 300 s timestamp tolerance; the Organization is always the connection's, never a payload value (#7522). `url_verification` (no `team_id`) is answered `200 { challenge }` from a shape check alone, reading and writing nothing; a malformed challenge or body is `400 invalid-payload`. A missing or repeated header, a stale timestamp, a malformed or unknown team and a bad signature all answer one identical empty `401`; a connection-store failure is `503`, so Slack retries. A verified `member_joined_channel` from outside the connection's team stamps `prospectJoinedAt`, and a later `message` from the connection's own team by a person or another app stamps `firstAgentMessageAt`, on the record found by (team, channel) inside that Organization (`stampProspectChannelActivity`); no message content is read or stored. One `SCHEDULING` row in the `webhooks` scope (`slackEventsRoutes`, `loadSlice`), so it loads on every build that carries the scheduling module and on no other, with its own 6,000 req/min/IP bucket. Logs a `reason` kind only. No MCP twin — a signed inbound receiver for one provider, the same footing as `POST /v1/webhooks/calcom` and `/v1/slack/actions`. The booking side is `src/services/scheduling/prospect-channel.ts`: both Cal.com receivers await its step, bounded at 8 s, after a lifecycle create committed, and its outcome never changes their reply.
113
114
  - `GET /v1/cron/prospect-channel-archive` — the prospect-channel archive sweep's cron entry (#9855, `packages-paid/api-scheduling/src/routes/cron/prospect-channel-archive.ts` over `src/services/scheduling/prospect-channel-archive.ts`; spec `docs/specs/9855-the-prospect-channel-archive-sweep-spec.md`). The scaffold's `apps/api/vercel.json` (`packages/create-ailk/template-overlay/apps/api/vercel.json`, delivered to existing sites by `create-ailk update`) schedules it daily at `0 7 * * *`; this repo's own `apps/api/vercel.json` does not, since neither of its deployments runs the prospect channel. The ladder: `CRON_SECRET` (`config`) unset or shorter than 32 characters → `503 { error: "cron-not-configured" }`; an `Authorization` that is not exactly `Bearer <token>` → empty `401` (`missing_bearer`); a token whose SHA-256 digest does not `timingSafeEqual` the secret's → empty `401` (`bad_secret`); otherwise the sweep runs with a 12 s deadline and answers `200 { summary }` — or `500 { error: "sweep-failed" }` for a failed or throwing sweep, never a throw. The query string and the body are never read; no `HEAD` twin. The sweep archives, with each Organization's own bot token, a channel the prospect never joined once their latest booking (a start, or a cancellation with no rebook) is more than the workspace's `archiveDays` old, after Slack confirms it is neither shared nor archived, and stamps `archivedAt`; a second run makes no Slack call. One `SCHEDULING` row in the `webhooks` scope (`prospectChannelArchiveCronRoute`), so it loads only with the scheduling module (a build without it answers the daily call `404`), with its own 10 req/min/IP bucket. Logs a refusal `reason`, the summary or the error kind — never the header, the secret or a token. No MCP twin — a scheduler's entry behind a deployment secret, the footing of `POST /v1/webhooks/calcom` and `POST /v1/slack/events`.
114
115
  - `POST /v1/webhooks/stripe/:connectionToken` — the per-Organization Stripe receiver (#8932, `src/routes/webhooks/stripe-offerings.ts`; spec `docs/specs/8932-the-per-organization-stripe-webhook-spec.md`; contract W1, W3–W11, G5, T8). The 43-character token names one `StripeConnection` row (`findStripeConnectionByWebhookToken`, #8907), whose own decrypted secret verifies the signature through `verifyWebhookSignatureKeyless` (`@working-theory/stripe-client`, no env key) and whose `organizationId` is the only Organization the event can act for — nothing in the body, query or headers changes it. It acts only on `checkout.session.completed` / `.async_payment_succeeded` for a session the hub's own checkout recorded (`readCheckoutSessionRecord`, #8930) for that Organization, whose signed `metadata.site` is the record's workspace, whose mode is the row's, and whose one line item — re-read with the connection's own client, never the env key — has the record's Price id; then it writes ONE lead through `routeLead` (key `"stripe-offerings " + sessionId`, a space no `Idempotency-Key` header can carry; `offeringsCheckout: true`; offering the record's full lookup key), marked `spokeCheckout` for a live session so #8793's release holds the plan, unmarked for a test one. A malformed or unknown token is `404 not-found` and logs nothing; a store failure `503 webhook-unavailable`; no usable secret `503 webhook-not-configured`; the claim, signature and livemode steps are the legacy route's; an unreadable record, Stripe read or lead write is a non-2xx that is never marked seen, so Stripe retries. Every `200` body is `{ received: true }` (the outcome is the log line's: `unrecorded`, `foreign_organization`, `offering_mismatch`, `fulfilled`, …). Dedup is its own per-Organization store (`hasSeenForOrganization`); the legacy `POST /v1/webhooks/stripe` acks any `ailk_offering`-stamped event `offerings_path` before `markSeen` and writes nothing. Log lines carry `organizationId`, `eventType`, an 8-character event-id prefix and the outcome only, and the request and error lines log the path with the token replaced whole (`lib/error-serializer.ts`'s `redactLogPath`, which also covers the calcom token route). No billing identity is bound from a connection's event (W11). **The fulfilment seam (#9383 DD1, `src/services/offerings/fulfilment-hooks.ts`):** for an Organization a paid package registered a hook for (the hub's licensing module, for the one Organization it is configured to mint for), `onFulfilledSession` runs after `fulfilled` / `already_fulfilled` and the event is marked seen only once it answers without `retry`; the five licence types (`customer.subscription.{created,updated,deleted}`, `invoice.paid`, `charge.refunded`) are deduplicated after the livemode step and handed to `onLifecycleEvent` in place of `ignored_type`; a `retry` answer, an unusable connection or a throwing hook is `503 licence-unavailable`, never seen. Every other Organization answers as before. A recorded session tagged `ailk_origin: ailk-trial` writes no lead (`trial_recorded`). Its own 100/min per-IP bucket. No MCP twin — the same inbound-receiver footing as the legacy route.
115
- - `/v1/schedule/appointments` (GET, `?limit=&cursor=&window=`) — the SITE's own appointments (#6085), tenant-guarded and role-floored at `appointments-read` (`@working-theory/validation`'s permission table (#7636 D2) — every role, a member included; the rows carry attendee contact PII, which the operator opened to the member who works the inbox). Registered in its OWN tenant scope, gated on `isModuleEnabled("scheduling")` alone, behind `tenantPreHandlerForBuild()` — NOT the anonymous schedule scope above (a prospect booking a call has no account). Scope is ALWAYS `request.tenant.workspaceId`, NEVER `currentSiteId()` (the receiver's own write scope) — and deliberately carries NO platform-operator escape hatch, unlike `/v1/waitlist-experiments/*`: an appointment book is a seller's customer list. `window` defaults to `upcoming`; `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 `/v1/waitlist-experiments/*/signups` cursor discipline). Nine fields per row and nothing more — `id`, `startTime`, `endTime`, `title`, `attendeeName`, `attendeeEmail`, `status`, `paid`, `personId` (#9348 — the Person the booking was stored against when it was created, or `null`; a later provider event that rewrites the attendee does not move it); `siteId`, `providerBookingUid`, `provider`, the three watermark columns, `paymentInitiatedAt`, `noShow`, `cancelledAt`, `createdAt` and `updatedAt` are never selected (`src/services/scheduling/appointments.ts`'s `listAppointments` is the only read path). No anonymous MCP twin — identity-bound tenant route (#3591 exception); its twin is the signed-in `list_appointments` (#10950, `@working-theory/mcp-scheduling`).
116
+ - `/v1/schedule/appointments` (GET, `?limit=&cursor=&window=`) — the SITE's own appointments (#6085), tenant-guarded and role-floored at `appointments-read` (`@working-theory/validation`'s permission table (#7636 D2) — every role, a member included; the rows carry attendee contact PII, which the operator opened to the member who works the inbox); an agent also needs the `people-read` grant (#10986). Registered in its OWN tenant scope, gated on `isModuleEnabled("scheduling")` alone, behind `tenantPreHandlerForBuild()` — NOT the anonymous schedule scope above (a prospect booking a call has no account). Scope is ALWAYS `request.tenant.workspaceId`, NEVER `currentSiteId()` (the receiver's own write scope) — and deliberately carries NO platform-operator escape hatch, unlike `/v1/waitlist-experiments/*`: an appointment book is a seller's customer list. `window` defaults to `upcoming`; `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 `/v1/waitlist-experiments/*/signups` cursor discipline). Nine fields per row and nothing more — `id`, `startTime`, `endTime`, `title`, `attendeeName`, `attendeeEmail`, `status`, `paid`, `personId` (#9348 — the Person the booking was stored against when it was created, or `null`; a later provider event that rewrites the attendee does not move it); `siteId`, `providerBookingUid`, `provider`, the three watermark columns, `paymentInitiatedAt`, `noShow`, `cancelledAt`, `createdAt` and `updatedAt` are never selected (`src/services/scheduling/appointments.ts`'s `listAppointments` is the only read path). No anonymous MCP twin — identity-bound tenant route (#3591 exception); its twin is the signed-in `list_appointments` (#10950, `@working-theory/mcp-scheduling`).
116
117
  - `/v1/aeo/score` (POST), `/v1/aeo/score/example` (GET) — anonymous instant AEO score for a respondent-supplied URL, and the bundled pre-launch example, both fed by the SSRF-guarded crawler at `@working-theory/aeo/fetch` and the pure scorer at `@working-theory/aeo` (`src/services/aeo-score.ts`, #4666). No MCP twin — recorded exception, brief D7 (exposing an arbitrary-URL crawler to anonymous agents is a security-posture decision; `apps/mcp/src/tools/audit.ts` deliberately stays same-origin-locked instead).
117
118
  - `/v1/waitlist-experiments` (GET), `/v1/waitlist-experiments/:experimentId` (GET), `/v1/waitlist-experiments/:experimentId/signups` (GET), `/v1/waitlist-experiments/:experimentId/signups/:leadId` (GET) — the operator-dashboard read API for Parallel Waitlist Validation (#4665 D7, B0): tenant-scoped list + rollup, per-waitlist comparison, paginated signups, and a signup drill-down over A1's `WaitlistExperiment` / `WaitlistScore` / `Lead` rows (`src/services/waitlist-dashboard.ts`, #4671). Role floor `waitlist-read` (`@working-theory/validation`'s permission table (#7636 D2) — every role, a member included; signup PII); the platform-operator scope (`isSentinel(organizationId)` and the `platform-read-all-sites` permission, owner only, ALSO requiring the caller's VERIFIED email to equal `AILK_OPERATOR_EMAIL` — fail-closed, PR #4687, compared to the caller since #7523) sees every site, every other caller sees only its own `siteId`. No MCP twin — identity-bound tenant routes (#3591 exception, same shape as `/v1/billing/*`).
118
119
  - `/v1/waitlist-signups/me` (GET, `?experimentKey=<slug>`) — the respondent read (#4731): a signed-in, **email-verified** user's OWN newest signup for one experiment (`experimentKey`, `waitlistKey`, `completedAt`, `tier`, `score`, `aeoScore`, `answers.q3` — seven fields, nothing more; `src/services/waitlist-signups.ts` is the only read path). Registered in `authScope` only (auth, no tenant guard — a respondent has no workspace). Identity is `request.userId`; the email is the `User`'s, never a parameter; `emailVerified !== true` → 403 `email_unverified` before any `Lead` read; no match → 404 `signup_not_found`; every read scoped to `currentSiteId()`. Module: `signal-collectors` (D-48, #5366). No MCP twin — identity-bound (#3591 exception).
@@ -222,7 +223,7 @@ sweep's own DB constraint (never a caller-side lock).
222
223
  - **The env key sells the hub's own products only (#9142).** `STRIPE_SECRET_KEY` on this API is the hub's own-products path (the env path above); a seller's Products sell through the Organization's Stripe connection (the Offerings path). A spoke holds no selling key: it sells through its hub's Offerings buy route, and its legacy env-key buy route and webhook are retired.
223
224
  - Don't assume Stripe is configured. Read at startup; if missing, disable commerce endpoints and log a warning.
224
225
  - Never log secret keys, even at debug.
225
- - **A restricted live key can run live (#8450, D-68's apps/api leg).** `build()` admits the key once at boot through `lib/stripe.ts`'s `admitApiStripeKey()` — the one apps/api file `architecture.yaml` lets name the SDK's admission call. It admits only a restricted live key beside `STRIPE_MODE=live` on a production build (`VERCEL_ENV=production`, or `NODE_ENV=production` off Vercel); `STRIPE_MODE` unset or `test` is the old sandbox-only boot, and every other combination stops the server. At request time the member portal session and the checkout start and read call `assertAdmittedStripeKey`, which passes the admitted restricted key and still refuses an unrestricted or publishable live key; the Organization portal, the recommender checkout and request-and-confirm stay on `assertSandboxKey`, sandbox-only until their own issues. The Billing page's plan read and webhook signature checks have no route guard and go live with the process. A live process gives both checkout routes their own per-IP `checkout` rate-limit bucket (`AILK_RATE_LIMIT_CHECKOUT_PER_MINUTE`). The webhook drops, with a 200 and a `livemode_mismatch` warn, any signed event whose `livemode` is not the admitted key class (`stripeKeyMode()`), before any write and without marking it seen. **The proposal paid stamp (#8516 D13):** a `checkout.session.completed` carrying the server-written `metadata.ailk_proposal` and `ailk_workspace` stamps that proposal's `paid_at` and `paid_session_id` once through the base-tree boundary `lib/proposal-paid-store.ts` (the webhook may import no slice-owned file), and writes one `people.proposal.paid` audit row as the `stripe` system actor keyed by the event id — `succeeded`, or `failed` with `already_paid` (a second charge) or `not_paid`; a same-session replay writes none. Proposal payment stays on `assertSandboxKey` until its own issue moves it live.
226
+ - **A restricted live key can run live (#8450, D-68's apps/api leg).** `build()` admits the key once at boot through `lib/stripe.ts`'s `admitApiStripeKey()` — the one apps/api file `architecture.yaml` lets name the SDK's admission call. It admits only a restricted live key beside `STRIPE_MODE=live` on a production build (`VERCEL_ENV=production`, or `NODE_ENV=production` off Vercel); `STRIPE_MODE` unset or `test` is the old sandbox-only boot, and every other combination stops the server. At request time the member portal session and the checkout start and read call `assertAdmittedStripeKey`, which passes the admitted restricted key and still refuses an unrestricted or publishable live key; the Organization portal, the plan checkout, the recommender checkout and request-and-confirm call it too (#8463). Request-and-confirm runs on single-tenant builds only, and there a live process key (the seller's own) needs Prices (write), Products (write) and Payment Links (write) as well; without them the confirm POST fails after it has spent the tenant's link. The hub key is never given them: it shares a live account whose catalog and Payment Links it must not write. The Billing page's plan read and webhook signature checks have no route guard and go live with the process. A live process gives both checkout routes and the recommender checkout their own per-IP `checkout` rate-limit bucket (`AILK_RATE_LIMIT_CHECKOUT_PER_MINUTE`; the recommender registers its hook on its own route but shares the scope's per-IP count, #8463 D6). The webhook drops, with a 200 and a `livemode_mismatch` warn, any signed event whose `livemode` is not the admitted key class (`stripeKeyMode()`), before any write and without marking it seen. **The proposal paid stamp (#8516 D13):** a `checkout.session.completed` carrying the server-written `metadata.ailk_proposal` and `ailk_workspace` stamps that proposal's `paid_at` and `paid_session_id` once through the base-tree boundary `lib/proposal-paid-store.ts` (the webhook may import no slice-owned file), and writes one `people.proposal.paid` audit row as the `stripe` system actor keyed by the event id — `succeeded`, or `failed` with `already_paid` (a second charge) or `not_paid`; a same-session replay writes none. Proposal payment stays on `assertSandboxKey` until its own issue moves it live.
226
227
  - **The env key needs Products: Read for checkout (#8931 D8).** The env checkout's lookup expands each Price's Product to refuse an Offerings product, so a restricted key without Products: Read gets a Stripe permission error there, which the route answers `502` — fail closed, never a sale of a Product it could not check.
227
228
  - **Every Checkout session shows a terms box (#8765 D12).** `@working-theory/stripe-client`'s creators set `consent_collection.terms_of_service: "required"` on every session, so **the seller's Stripe account must have a Terms of service URL set in the Stripe Dashboard** (Settings → Business → Public details); without one Stripe refuses the session and the creator throws `TermsOfServiceUrlMissingError`, which each caller answers with its existing failure. Every session also carries `metadata.ailk_terms` — the stamp the webhook's checkout grant requires (see the consent bullet).
228
229
 
@@ -236,7 +237,9 @@ sweep's own DB constraint (never a caller-side lock).
236
237
  - Don't bundle `apps/api` (esbuild, rollup, webpack). Slice specifiers cannot survive it — see `## Deploy path`.
237
238
  - Don't construct Fastify with `logger: true` or any `logger:` option. Pass `loggerInstance` built from `createLogger` in `@working-theory/observability` (see `packages/api/src/server.ts`). Fastify's own pino carries none of the redaction.
238
239
 
239
- Last updated: 2026-11-08 — #11122 (D4–D6): the workspace meetings bullet names `visibility` on every row, the provider's `providerEventTypeId`, `createdAt` and manage-only `providerEditUrl`, the removed `include` query and the exclusive `customerSlugs` / `privateSlugs`; the member reads join `customerSlugs` ∩ `enabledSlugs`; the `/v1/schedule/meetings` Live set is `enabledSlugs` less `customerSlugs` — per spec `docs/specs/11122-the-appointment-detail-on-the-spec.md`, against `packages/validation/src/schemas/scheduling.ts` and `packages-paid/api-scheduling/src/routes/workspaces/meetings.ts`.
240
+ Last updated: 2026-11-12 — #10986: the `/v1/schedule/appointments` bullet names the `people-read` grant an agent also needs, beside the `appointments-read` role floor — verified against `packages-paid/api-scheduling/src/routes/schedule/appointments.ts` and `packages/metadata/src/mcp-tool-catalog.ts`.
241
+
242
+ Prior: 2026-11-08 — #11122 (D4–D6): the workspace meetings bullet names `visibility` on every row, the provider's `providerEventTypeId`, `createdAt` and manage-only `providerEditUrl`, the removed `include` query and the exclusive `customerSlugs` / `privateSlugs`; the member reads join `customerSlugs` ∩ `enabledSlugs`; the `/v1/schedule/meetings` Live set is `enabledSlugs` less `customerSlugs` — per spec `docs/specs/11122-the-appointment-detail-on-the-spec.md`, against `packages/validation/src/schemas/scheduling.ts` and `packages-paid/api-scheduling/src/routes/workspaces/meetings.ts`.
240
243
 
241
244
  Prior: 2026-11-09 — #11173: the shared connection model's six routes, their check order, the read gate and the no-twin footing — verified against `packages-paid/api-workspace/src/routes/workspaces/connections.ts`, `packages/api/src/services/connections/{index,oauth,provider,store}.ts` and `packages/api/src/config/modules.ts`.
242
245
 
@@ -137,7 +137,7 @@ Every tool maps 1:1 to an `apps/api` endpoint. When you change a tool, change th
137
137
 
138
138
  - **22 in the `TOOLS` array / parity test**: the `TOOLS` array in
139
139
  `packages/metadata/src/mcp-tool-catalog.ts` defines 22 anonymous tools; the
140
- parity test counts that full array. It also holds the sixty signed-in
140
+ parity test counts that full array. It also holds the sixty-two signed-in
141
141
  workspace tools (#3591; the content-suggestion pair `draft_page_suggestions`
142
142
  and `decide_page_suggestion` since #10218; the draft pair `save_draft` and
143
143
  `read_report` since #10336; the knowledge-base pair `read_knowledge` and
@@ -187,7 +187,7 @@ here. Spec: `docs/specs/3591-tenant-scoped-agent-auth-secure-spec.md` D13–D16.
187
187
  - **apps/mcp checks only the key's shape.** The key is attached as the SDK's `req.auth` for that
188
188
  request alone and reaches a tool as `extra.authInfo.token`. apps/api is the one place it is
189
189
  checked, and its tenant guard and the caller's clamped role decide every answer.
190
- - **Sixty tools (fifty-seven plus three deprecated aliases), each a `twin`.** The catalog rows carry `surface: "workspace"`, `tier: "pro"`
190
+ - **Sixty-two tools (fifty-nine plus three deprecated aliases), each a `twin`.** The catalog rows carry `surface: "workspace"`, `tier: "pro"`
191
191
  and `modulesAnyOf` (the modules any one of which registers the tool — its twin route's gate):
192
192
  `get_agent_context`, (#9683) `get_workspace_knowledge` — twin of `GET
193
193
  /v1/workspaces/:workspaceId/knowledge`: the business's shown offerings, live magnets, listed
@@ -209,7 +209,7 @@ here. Spec: `docs/specs/3591-tenant-scoped-agent-auth-secure-spec.md` D13–D16.
209
209
  tools, `list_proposals` and `create_proposal`, twinning `GET`/`POST
210
210
  /v1/workspaces/:workspaceId/people/:personId/proposals` with the same grant: a proposal is
211
211
  private to one client, `payments` says whether approval leads to a Stripe page, and an agent's
212
- price is refused `proposal_needs_person` (a person prices) — and (#10957) `send_person_message`, twinning `POST …/people/:personId/messages`: one message on a client's member feed, saved then emailed (an agent's only to a proved address), needing `inbox-act` with `people-read` or `member-pieces-manage`, and `assets-write` for a file; the operator's message list has no tool, by decision — and (#9681) the four person-thread tools, `get_person_thread`, `set_person_thread_state`, `list_external_threads` and `add_external_thread`, twinning `GET`/`PATCH …/people/:personId/thread` and `GET`/`POST …/people/:personId/external-threads`: a client's whole thread page by page with its read/archived/resolved state, and pointers to email and Slack threads (never message text); reading needs the `people-read` grant, writing also `inbox-act`, and the client erasure route has no tool, by decision — and (#9682) the three person-memory tools, `list_person_memories`, `get_person_memory` and `propose_person_memory`, twinning `GET …/people/:personId/memories`, `GET …/memories/:path` and `POST …/memories`: an agent reads only live, unexpired memories (confirmed by a person, read within 180 days) and its proposal is never live — a new path is a draft, a confirmed one gets a pending version — needing the `people-read` or `people-memory-propose` grant to read and `people-memory-propose` to propose; the six person-only memory routes (edit, delete, confirm, redact, the versions list, restore) have no tool, by decision — and (#9749) `get_slack_connection_status`, twin of `GET /v1/workspaces/:workspaceId/slack-connection` (registered with `workspace`/`multi-tenant`, its route's `TENANCY` row: whether the Organization's Slack is connected, its team name and the date, never a credential; connect and disconnect are a person's act and have no tool, by decision), and `get_prospect_channel_settings` / `set_prospect_channel_settings`, twins of `GET`/`PUT …/prospect-channel` (registered with `scheduling`, their routes' module): the update replaces every field, needs the `meeting-types-manage` grant, is refused `slack_not_connected` while the Organization has no Slack connection, and an agent may change only `enabled`, `channelPrefix` and `archiveDays` — a change to `memberIds` or `welcomeTemplate` is refused `prospect_channel_needs_person` — and (#10950) the three meeting tools, `list_meeting_types`, `save_meeting_types` and `list_appointments`, twinning `GET`/`PUT …/meetings` and `GET /v1/schedule/appointments` (registered with `scheduling`): the meeting types from the connected calendar, each with whether it is Live (`enabled`) and who can book it (`visibility`: `public`, `private` or `authenticated`), the provider's `providerEventTypeId` and `createdAt` when it serves them, and, with the `meeting-types-manage` grant, `providerEditUrl` — the read takes no `include` (#11122 D4); the save needs that grant and its required `enabledSlugs` replaces the Live list, while `customerSlugs` (Authenticated) and `privateSlugs` (Private) are exclusive — a slug in both is refused — and an omitted one keeps the stored list less the sent list's slugs, and no price is set there; the appointments read is every role's, takes `eventTypeId` for one type's bookings (#11122 D12), and its attendee names and emails are public-written text; the three scheduling-connection routes have no tool, by decision — and (#10218) the content-suggestion pair, `draft_page_suggestions` and `decide_page_suggestion` — and (#10336) the draft pair, `save_draft` and `read_report`, twinning `PATCH`/`GET …/content/:type/:slug` with the `content-edit` grant: `save_draft` takes the page's `content` whole as the PATCH body and its `version` as `X-Draft-Version`, writes a draft version that never goes live, and answers 409 `conflict` with `currentVersion` when the draft moved; `read_report` returns the draft tip, the version a save must send, the page's stored layout (`structure`, #10962) and the token `save_structure` must send, its open suggestions and the route's check report (`ready`, `needs repair` or `needs your words`), computed by the route and never by the tool — and (#10956) `create_page`, twinning `POST …/content` with the `content-edit` grant: it creates a page and its first draft from `content` sent whole (its `type` and `slug` are the address), never publishes, and answers 409 `conflict` when the page exists and 409 `slug_taken` when another page holds the link — and (#10661) `publish_draft`, twinning `POST …/content/:type/:slug/publish` with the `content-publish` grant: it publishes the draft tip (or a named version) exactly as a person holding that permission does, an agent without the grant is refused 403 `agent_refused` before anything is read, and it never widens Audience or re-enables a doc — and (#10345) the knowledge-base pair, `read_knowledge` and `read_knowledge_doc`, twinning `GET …/knowledge-base` and `GET …/knowledge-base/:type/:slug` with no grant (`docs-read` is every role's): the docs a named member may read (`userId`, by default the agent's own person), at the lower of the agent's person's role and that member's, so naming someone only narrows; Live does not gate them and a disabled doc never appears; `filter: "workspace-memory"` answers the always-loaded set with its `totalTokens` and an 8000-token `warning` — and (#10951) `get_workspace_settings`, twin of `GET /v1/workspaces/:workspaceId/general` (`mcp-workspace`'s `workspace_settings.ts`, no grant): the workspace's name, its own logo (`null` when the organization's applies) and the deployment's deliverable sender (`null` when none is configured, so a magnet's results and completion emails do not go out); the PUT, which renames the workspace and sets its logo, has no tool, by decision — it needs `workspace-settings`, which is never agent-grantable — and (#10733, issue 10905, #10952) the seven Language tools, `list_language_items`, `get_language_item`, `save_language_item`, `set_language_item_live`, `delete_language_item`, `list_language_item_pages` and `get_topic_brief`, twinning `GET …/language`, `GET`/`PUT`/`DELETE …/language/:kind/:slug`, `POST …/language/:kind/:slug/live`, `GET …/language/:kind/:slug/appears-on` and `GET …/language/topic/:slug/brief` (`mcp-workspace`'s `language.ts`): a workspace's glossary terms, FAQs and topics; reading needs no grant, saving the `content-edit` grant (`version: null` creates, a tip id updates, 409 `slug_taken` / `stale` otherwise), the Live switch `content-publish` with the `version` the person reviewed, and the delete `content-publish` too — it removes the item from every Live page, no route restores it, and its slug stays taken; tags are the hub's and never written by a tool; a topic is a keyword cluster for agents and is never shown to visitors, and `get_topic_brief` reads it as a writing brief — its kept rows scored best bets first, from the Live version when Live; the Topic's Keyword Planner import and the value-thresholds pair are a person's and have no tool, by decision — and (#10948) the three magnet tools, `list_magnets`, `get_magnet` and `save_magnet`, twinning `GET …/magnets`, `GET …/magnets/:id` and `PATCH …/magnets/:id` (`mcp-workspace`'s `magnets.ts`, registered with `multi-tenant` or `signal-collectors`): with the `magnets-manage` grant every magnet in full, without it only live ones as `{ id, slug, kind, title, landingPage, tags }`; `save_magnet` takes the PATCH body whole, so going live is `status: "live"` and the route alone refuses it (`402 plan_required`, `409 conversion_needs_email`), and an agent cannot change what a magnet charges (`403 magnet_pricing_needs_person`); create and the four captured-people lists have no tool, by decision — and (#10949) `get_workspace_offerings`, twin of `GET /v1/workspaces/:workspaceId/offerings` (registered with `multi-tenant` alone, its route's module; `mcp-workspace`'s `offerings.ts`): the Offerings tab's view — unavailable with `no_commerce` or `no_connection`, or the Organization's enabled products with this workspace's shown Prices and Recommended — read with no grant; its PUT, which switches a Price on or off, needs `workspace-settings`, which is never agent-grantable, and has no tool, by decision. No workspace tool widens Audience or re-enables a doc, and only `publish_draft` and `set_language_item_live`, with the `content-publish` grant, set Live (and `delete_language_item`, with the same grant, clears it) — the access route answers every agent 403 `agent_refused`, and the publish, Live and Language delete routes an agent without the grant, which reaches a tool as the code and status. Each takes its route's params, query and body and returns the route's
212
+ price is refused `proposal_needs_person` (a person prices) — and (#10957) `send_person_message`, twinning `POST …/people/:personId/messages`: one message on a client's member feed, saved then emailed (an agent's only to a proved address), needing `inbox-act` with `people-read` or `member-pieces-manage`, and `assets-write` for a file; the operator's message list has no tool, by decision — and (#9681) the four person-thread tools, `get_person_thread`, `set_person_thread_state`, `list_external_threads` and `add_external_thread`, twinning `GET`/`PATCH …/people/:personId/thread` and `GET`/`POST …/people/:personId/external-threads`: a client's whole thread page by page with its read/archived/resolved state, and pointers to email and Slack threads (never message text); reading needs the `people-read` grant, writing also `inbox-act`, and the client erasure route has no tool, by decision — and (#9682) the three person-memory tools, `list_person_memories`, `get_person_memory` and `propose_person_memory`, twinning `GET …/people/:personId/memories`, `GET …/memories/:path` and `POST …/memories`: an agent reads only live, unexpired memories (confirmed by a person, read within 180 days) and its proposal is never live — a new path is a draft, a confirmed one gets a pending version — needing the `people-read` or `people-memory-propose` grant to read and `people-memory-propose` to propose; the six person-only memory routes (edit, delete, confirm, redact, the versions list, restore) have no tool, by decision — and (#9749) `get_slack_connection_status`, twin of `GET /v1/workspaces/:workspaceId/slack-connection` (registered with `workspace`/`multi-tenant`, its route's `TENANCY` row: whether the Organization's Slack is connected, its team name and the date, never a credential; connect and disconnect are a person's act and have no tool, by decision), and `get_prospect_channel_settings` / `set_prospect_channel_settings`, twins of `GET`/`PUT …/prospect-channel` (registered with `scheduling`, their routes' module): the update replaces every field, needs the `meeting-types-manage` grant, is refused `slack_not_connected` while the Organization has no Slack connection, and an agent may change only `enabled`, `channelPrefix` and `archiveDays` — a change to `memberIds` or `welcomeTemplate` is refused `prospect_channel_needs_person` — and (#10950) the three meeting tools, `list_meeting_types`, `save_meeting_types` and `list_appointments`, twinning `GET`/`PUT …/meetings` and `GET /v1/schedule/appointments` (registered with `scheduling`): the meeting types from the connected calendar, each with whether it is Live (`enabled`) and who can book it (`visibility`: `public`, `private` or `authenticated`), the provider's `providerEventTypeId` and `createdAt` when it serves them, and, with the `meeting-types-manage` grant, `providerEditUrl` — the read takes no `include` (#11122 D4); the save needs that grant and its required `enabledSlugs` replaces the Live list, while `customerSlugs` (Authenticated) and `privateSlugs` (Private) are exclusive — a slug in both is refused — and an omitted one keeps the stored list less the sent list's slugs, and no price is set there; the appointments read is every role's, and an agent's only with the `people-read` grant (#10986), takes `eventTypeId` for one type's bookings (#11122 D12), and its attendee names and emails are public-written text; the three scheduling-connection routes have no tool, by decision — and (#10218) the content-suggestion pair, `draft_page_suggestions` and `decide_page_suggestion` — and (#10336) the draft pair, `save_draft` and `read_report`, twinning `PATCH`/`GET …/content/:type/:slug` with the `content-edit` grant: `save_draft` takes the page's `content` whole as the PATCH body and its `version` as `X-Draft-Version`, writes a draft version that never goes live, and answers 409 `conflict` with `currentVersion` when the draft moved; `read_report` returns the draft tip, the version a save must send, the page's stored layout (`structure`, #10962) and the token `save_structure` must send, its open suggestions and the route's check report (`ready`, `needs repair` or `needs your words`), computed by the route and never by the tool — and (#10956) `create_page`, twinning `POST …/content` with the `content-edit` grant: it creates a page and its first draft from `content` sent whole (its `type` and `slug` are the address), never publishes, and answers 409 `conflict` when the page exists and 409 `slug_taken` when another page holds the link — and (#10661) `publish_draft`, twinning `POST …/content/:type/:slug/publish` with the `content-publish` grant: it publishes the draft tip (or a named version) exactly as a person holding that permission does, an agent without the grant is refused 403 `agent_refused` before anything is read, and it never widens Audience or re-enables a doc — and (#10345) the knowledge-base pair, `read_knowledge` and `read_knowledge_doc`, twinning `GET …/knowledge-base` and `GET …/knowledge-base/:type/:slug` with no grant (`docs-read` is every role's): the docs a named member may read (`userId`, by default the agent's own person), at the lower of the agent's person's role and that member's, so naming someone only narrows; Live does not gate them and a disabled doc never appears; `filter: "workspace-memory"` answers the always-loaded set with its `totalTokens` and an 8000-token `warning` — and (#10951) `get_workspace_settings`, twin of `GET /v1/workspaces/:workspaceId/general` (`mcp-workspace`'s `workspace_settings.ts`, no grant): the workspace's name, its own logo (`null` when the organization's applies) and the deployment's deliverable sender (`null` when none is configured, so a magnet's results and completion emails do not go out); the PUT, which renames the workspace and sets its logo, has no tool, by decision — it needs `workspace-settings`, which is never agent-grantable — and the six site-profile tools, `get_site_identity`, `set_site_identity`, `get_site_seo`, `set_site_seo`, `get_welcome_email` and `set_welcome_email` (`mcp-workspace`'s `site_profile.ts`), twinning `GET`/`PUT …/identity`, `…/seo` and `…/welcome-email`: any member reads; each write needs the `site-profile` grant (`ailk:site-profile`), under which every logo and every SEO field but the description — robots and indexing above all — must be sent as read, else `site_profile_field_locked`; the theme pair has no tool, by decision — and (#10733, issue 10905, #10952) the seven Language tools, `list_language_items`, `get_language_item`, `save_language_item`, `set_language_item_live`, `delete_language_item`, `list_language_item_pages` and `get_topic_brief`, twinning `GET …/language`, `GET`/`PUT`/`DELETE …/language/:kind/:slug`, `POST …/language/:kind/:slug/live`, `GET …/language/:kind/:slug/appears-on` and `GET …/language/topic/:slug/brief` (`mcp-workspace`'s `language.ts`): a workspace's glossary terms, FAQs and topics; reading needs no grant, saving the `content-edit` grant (`version: null` creates, a tip id updates, 409 `slug_taken` / `stale` otherwise), the Live switch `content-publish` with the `version` the person reviewed, and the delete `content-publish` too — it removes the item from every Live page, no route restores it, and its slug stays taken; tags are the hub's and never written by a tool; a topic is a keyword cluster for agents and is never shown to visitors, and `get_topic_brief` reads it as a writing brief — its kept rows scored best bets first, from the Live version when Live; the Topic's Keyword Planner import and the value-thresholds pair are a person's and have no tool, by decision — and (#10948) the three magnet tools, `list_magnets`, `get_magnet` and `save_magnet`, twinning `GET …/magnets`, `GET …/magnets/:id` and `PATCH …/magnets/:id` (`mcp-workspace`'s `magnets.ts`, registered with `multi-tenant` or `signal-collectors`): with the `magnets-manage` grant every magnet in full, without it only live ones as `{ id, slug, kind, title, landingPage, tags }`; `save_magnet` takes the PATCH body whole, so going live is `status: "live"` and the route alone refuses it (`402 plan_required`, `409 conversion_needs_email`), and an agent cannot change what a magnet charges (`403 magnet_pricing_needs_person`); create and the four captured-people lists have no tool, by decision — and (#10949) `get_workspace_offerings`, twin of `GET /v1/workspaces/:workspaceId/offerings` (registered with `multi-tenant` alone, its route's module; `mcp-workspace`'s `offerings.ts`): the Offerings tab's view — unavailable with `no_commerce` or `no_connection`, or the Organization's enabled products with this workspace's shown Prices and Recommended — read with no grant; its PUT, which switches a Price on or off, needs `workspace-settings`, which is never agent-grantable, and has no tool, by decision — and the two library reads, `list_workspace_pages` and `list_assets` (`mcp-workspace`'s `library.ts`, registered with `workspace` or `multi-tenant`), twinning `GET …/library/pages` and `GET …/library/assets`: every page with drafts included and its status (`live`, `draft`, or `disabled` — a person editor's alone), needing the `content-edit` grant, and the asset library read-only with each file's public path, for every role; both filter, page and name the workspace `{ id, name }` they read, and uploading has no tool. No workspace tool widens Audience or re-enables a doc, and only `publish_draft` and `set_language_item_live`, with the `content-publish` grant, set Live (and `delete_language_item`, with the same grant, clears it) — the access route answers every agent 403 `agent_refused`, and the publish, Live and Language delete routes an agent without the grant, which reaches a tool as the code and status. Each takes its route's params, query and body and returns the route's
213
213
  `data`. They are in the parity guard like every other tool, and never in
214
214
  `/.well-known/mcp.json`.
215
215
  - **The OAuth bearer branch (#10391).** When `BETTER_AUTH_URL` (the site's origin, its OAuth
@@ -228,9 +228,29 @@ here. Spec: `docs/specs/3591-tenant-scoped-agent-auth-secure-spec.md` D13–D16.
228
228
  with `Retry-After: 5` — never a pass and never a 401. Issuer and resource come from env only,
229
229
  never a request's `Host`. Either name unset, the route takes agent keys only, exactly as before;
230
230
  a spoke has no authorization server, so it leaves `BETTER_AUTH_URL` unset. `/mcp` is untouched.
231
+ - **The all-workspaces principal and its session (#11607).** The hub's Admin issues a token that
232
+ reaches every workspace of every organization its person belongs to; its token-info answers
233
+ the second strict shape (`allWorkspaces: true` plus one `workspaces` row per workspace — id,
234
+ names, role, acting role, grants), and `tokenInfoSchema` is the union of that and the
235
+ single-workspace shape (`oauth-bearer.ts`). For it alone: a `tools/call` naming any
236
+ `workspaceId` passes here (apps/api checks each against the live membership); an `initialize`
237
+ answers a minted `Mcp-Session-Id` (exposed by `Access-Control-Expose-Headers`); a later request's
238
+ `mcp-session-id` — a lowercase UUID — runs its tools inside `request-context.ts`'s `mcpSession`
239
+ store, a malformed one is 404 `session_not_found`, and none means no session (apps/api then
240
+ refuses writes `session_required`). The transport stays stateless; `workspace-server.ts` hands
241
+ the id to every agent-key call as `x-ailk-mcp-session` (`setAgentCallHeaderSource`,
242
+ `@working-theory/api-client`), which keys the server-side write pin: the session's first write
243
+ pins it to a workspace, and a write elsewhere is refused `workspace_pinned` until
244
+ `use_workspace` (twin of `POST /v1/workspaces/:workspaceId/mcp-session`) moves it.
245
+ `list_workspaces` (twin of `GET /v1/agent/workspaces`) lists the reach. Its results answer
246
+ `{ ok, workspace: { id, name }, data }`, and a `workspace_pinned` error carries `pinned` and
247
+ `requested` (`name: null` once out of reach); single-workspace tokens and agent keys never read
248
+ the header and their results are unchanged. **Deploy apps/mcp before the Admin:** an older
249
+ apps/mcp parses the new token-info with the single shape alone and answers every
250
+ all-workspaces token 503 `authorization_unavailable`.
231
251
  - **Handlers forward, nothing else.** `workspace-server.ts` resolves each tool from
232
252
  `@working-theory/mcp-workspace`'s `workspaceTools` (`agent_context.ts`, `knowledge.ts`, `inbox_messages.ts`,
233
- `inbox_submissions.ts`, `inbox_applications.ts`, `people_list.ts`, `person_notes.ts`, `person_thread.ts`, `person_memory.ts`, `proposals.ts`, `slack_connection.ts`, `page_suggestions.ts`, `content_draft.ts`, `content_publish.ts`, `knowledge_base.ts`, `workspace_settings.ts`, all
253
+ `inbox_submissions.ts`, `inbox_applications.ts`, `people_list.ts`, `person_notes.ts`, `person_thread.ts`, `person_memory.ts`, `proposals.ts`, `slack_connection.ts`, `page_suggestions.ts`, `content_draft.ts`, `content_publish.ts`, `knowledge_base.ts`, `workspace_settings.ts`, `library.ts`, all
234
254
  `// oss: false`) and, for the two prospect-channel settings tools, `@working-theory/mcp-scheduling`'s
235
255
  `workspaceTools` (`prospect_channel_settings.ts`, #9749, and the three meeting tools in `meetings.ts`, #10950 — the pack the scheduling module carries, so a
236
256
  scheduling-only build serves what it lists), loaded through the site's generated registry, as `server.ts` resolves the
@@ -314,7 +334,7 @@ Example (lead routing):
314
334
  - Don't add a tool without the matching `apps/api` endpoint.
315
335
  - Don't put business logic in tool handlers — they're adapters.
316
336
 
317
- Last updated: 2026-11-09 — #11275 unit E: `set_doc_class` and `write_memory` (`mcp-workspace`'s `knowledge_base.ts`, `content-edit` grant) twin `PUT …/knowledge-base/class` and `POST …/knowledge-base/memory` — set a doc's or a File's context class, and write a dated Memory entry or mark one stale; each takes its route's params and one flat `@working-theory/validation` body — the signed-in workspace surface is sixty tools — verified against `packages/metadata/src/mcp-tool-catalog.ts`, `packages-paid/mcp-workspace/src/index.ts` and `tests/parity/api-parity/kinds/site.ts`.
337
+ Last updated: 2026-11-12 — #10986: `list_appointments` needs the `people-read` grant for an agent (its gate is the `appointments-read` role floor and that grant, the route's own check) — verified against `packages/metadata/src/mcp-tool-catalog.ts` and `packages-paid/api-scheduling/src/routes/schedule/appointments.ts`.
318
338
 
319
339
  Prior: 2026-11-08 — #11122 (D4, D5, D12): `list_meeting_types` loses `include` and its rows carry `visibility`, `providerEventTypeId`, `createdAt` and (manage view) `providerEditUrl`; `save_meeting_types`' two lists are exclusive; `list_appointments` takes `eventTypeId` — verified against `packages/metadata/src/mcp-tool-catalog.ts` and `tests/parity/api-parity/fixtures/site-wire.ts`.
320
340
 
@@ -40,7 +40,7 @@ CONTENT_ADAPTER=mdx
40
40
  #
41
41
  # POST /v1/leads/submit POST /v1/leads/subscribe
42
42
  # POST /v1/leads/callback GET /v1/schedule/availability
43
- # POST /v1/schedule/book POST /v1/commerce/invoices
43
+ # POST /v1/schedule/book POST /v1/commerce/invoices (a hub only)
44
44
  #
45
45
  # An authored form `action` must name one of them. Adding one is a reviewed
46
46
  # change to RELAY_ROUTES in lib/relay.ts and to this list. The visitor's
@@ -186,6 +186,12 @@ CONTENT_ADAPTER=mdx
186
186
  # only sign-in. It must be an https: URL (http: only on a loopback host).
187
187
  # BETTER_AUTH_URL=http://localhost:3000
188
188
  #
189
+ # The hub Admin's absolute https URL (admin-team-invitation-accept). Optional:
190
+ # a team invitation link mailed before invitations moved to the Admin
191
+ # (/account/invitations/<id>) is sent on to <Admin>/invitations/<id>. Unset,
192
+ # or not a valid https URL, it uses admin.<BETTER_AUTH_URL host>.
193
+ # AILK_ADMIN_URL=https://admin.example.com
194
+ #
189
195
  # Secret used to sign session cookies AND the email-verification tokens.
190
196
  # REQUIRED in production: apps/web/auth.ts now THROWS at boot without it rather
191
197
  # than falling back to a development string that is published in this