create-ailk 0.35.1 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +12 -1
  3. package/component-catalog.md +6 -5
  4. package/dist/lib/env-catalog.js +8 -0
  5. package/dist/surfaces.js +6 -3
  6. package/dist/topology.d.ts +4 -4
  7. package/dist/topology.js +104 -60
  8. package/package.json +3 -3
  9. package/templates/.env.example +21 -0
  10. package/templates/apps/api/.env.example +7 -0
  11. package/templates/apps/api/CLAUDE.md +9 -4
  12. package/templates/apps/mcp/CLAUDE.md +4 -2
  13. package/templates/apps/web/.env.example +16 -0
  14. package/templates/apps/web/CLAUDE.md +46 -5
  15. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  16. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  17. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  18. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  19. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  20. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  21. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  22. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  23. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  24. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +12 -1
  25. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +55 -2
  26. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  27. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +1 -1
  28. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +60 -6
  29. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +32 -3
  30. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  31. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  32. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  33. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  34. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +47 -0
  35. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  36. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +214 -0
  37. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  38. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  39. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  40. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  41. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  42. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +6 -4
  43. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -1
  44. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  45. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  46. package/templates/apps/web/app/[locale]/layout.tsx +24 -75
  47. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  48. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  49. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  50. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
  51. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
  52. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  53. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  54. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  55. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  56. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  57. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  58. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  59. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +475 -7
  60. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  61. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  62. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  63. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  64. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  65. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  66. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  67. package/templates/apps/web/auth.ts +133 -6
  68. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  69. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  70. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  71. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  72. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  73. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  74. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  75. package/templates/apps/web/lib/auth-email.ts +62 -6
  76. package/templates/apps/web/lib/auth-env.ts +13 -0
  77. package/templates/apps/web/lib/auth-sms.ts +180 -0
  78. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  79. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  80. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  81. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  82. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  83. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  84. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  85. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  86. package/templates/apps/web/lib/site-header.ts +14 -1
  87. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  88. package/templates/apps/web/lib/topology.generated.ts +39 -0
  89. package/templates/apps/web/messages/en.json +112 -20
  90. package/templates/apps/web/middleware.ts +34 -2
  91. package/templates/apps/web/security-headers.config.ts +21 -0
  92. package/versions.json +47 -47
  93. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  94. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  95. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  96. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -69,9 +69,10 @@ Routes are versioned under `/v1/*`:
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.
70
70
  - `/v1/auth/tokens`, `/v1/user/{profile,data/:key}` — local auth + user data
71
71
  - `/v1/hub-sign-in/codes` (POST), `/v1/hub-sign-in/token` (POST), `/v1/hub-sign-in/revoke` (POST), `/v1/hub-sign-in/me` (GET) — the hub signs in its spokes (#7894, `packages-paid/api-hub/src/routes/auth/hub-sign-in.ts` over `packages-paid/api-hub/src/services/hub-sign-in.ts` — `@working-theory/api-hub` since #9571, which owns the spoke registry and the sign-in trio and hands them to `buildServer({ hub })` through `packages/api/src/lib/hub.ts`; spec `docs/specs/7894-the-hub-signs-in-its-spec.md`): an authorization code with PKCE between a spoke (a confidential client whose `OAuthClient.clientId` IS its `Spoke.id`) and this hub. `codes` is in `authScope` and answers a COOKIE session only (a personal `ApiToken` is 403, an agent key 403 at the preHandler, a hub credential 404): it mints a single-use 60 s code only for an email-verified person and a callback in the client's registered `redirectUris` (exact match), 30 a user per 10 minutes. `token` and `revoke` are in their OWN scope outside `authScope` (per-IP `rateLimitMiddleware`, scope `hubsignin`, 60/min; plus a per-client bucket of 120 exchanges a minute keyed on the VERIFIED client): the caller authenticates with `Authorization: Basic clientId:secret` AND `x-ailk-spoke-key`, which must resolve to the unrevoked spoke whose id is that client — either alone is `401 invalid_client`. `token` consumes the code first and exactly once, then checks the client, the callback and the PKCE verifier (`400 invalid_grant` for any failure, the code gone either way) and issues `ailk_hst_…`, a 24 h credential stored only as a SHA-256 digest in `OAuthAuthorization` (one row per person and spoke, so a new sign-in rotates it); it writes no `Session` row and sets no cookie. `revoke` ends a credential or burns an unexpired code of that client (`{ revoked }`, never an error). `me` answers the credential's person, read live, and is reachable only by that credential, and `billingCustomerId` — the Stripe customer of the caller's Person in the spoke's workspace, read only while that Person's `userId` is the caller and the id is the caller's own Stripe binding, else `null`; since #8047 no anonymous checkout writes it, and the one writer is the hub site's signed-in checkout, so on a spoke's workspace it is `null` until a later writer exists. Its first read links the caller's Person under the verified-email rule (`stampPersonUser` through `resolveMemberPersonId`), so this GET can write. **The credential is admitted by one branch of `middleware/auth.ts`** — only beside the same spoke's key, only while its grant is unrevoked and unexpired, its client enabled and its person's email verified, and only on `HUB_SESSION_ROUTES`, an exact list of 26 method + registered-URL strings, never a prefix (#8220): `GET /v1/hub-sign-in/me`, #7877's three member reads, #8169's eight member reads, #8170's six member writes, #8435's two contact routes, #8438's two consent routes, #8765's account-agreements pair and #8515's onboarding read and write; every other route answers `404` with no handler run (the status the account area's `read()` loads as "nothing for this caller"), and the list is extended only by a reviewed edit. **The per-person budget (#8220 D2, SEC-8169-4):** each person at each spoke gets 60 requests and 10 writes a minute and 30 writes an hour (a fixed hour window from the first admitted write, so up to twice that across a window edge), keyed on the VERIFIED spoke and person and charged only after admission (a refused credential or an off-list route never gets a bucket); over budget is `429 rate_limited` with `Retry-After`. The write limits refuse only writes, and a refused request is not counted. Every line the request logger writes for an admitted request after admission carries `spokeId` (never the key or the credential); a helper logging through the module-level `logger` carries no request binding. The server-wide per-IP limiter still counts all of one spoke's members together — a named residual whose follow-up (the visitor forward key on member calls) must land before Phase 3 (#8163) ships to a live spoke. A bearer write skips the origin check, so the cross-site-request protection for the member writes is the spoke's: its server actions that send a sealed credential carry it (Phase 3, #8163; SEC-8220-11). A completed password reset (`apps/web/auth.ts` `onPasswordReset`) revokes every credential of that person. The operator registers a spoke's client with `spokes sign-in-client --id <spoke_id> --redirect-uri <url>` (`packages-paid/api-hub/src/bin/spokes.ts`; `--disable` switches it off) — `packages-paid/api-hub/src/lib/hub-sign-in-store.ts` is the only file that names `prisma.oAuthClient` and `prisma.oAuthAuthorization`. **The `hub` claim (#9571 D4; #9568 D5):** read only inside `@working-theory/api-hub` (`src/claim.ts`), through `checkLicense()`, registry first — with no `DATABASE_URL` or no registered spoke the gate answers `not-serving` and never reads the licence; with a spoke and the claim, `claimed`; with a spoke and no claim, `unclaimed`, and `codes`, `token`, `me` (a verified credential) and `clients/:clientId` answer `403 feature_required` naming `hub`; an unreadable licence is `undetermined`, `503 license_undetermined` with `Retry-After: 300`. `revoke` is never gated; a definite answer is held 300 s, `not-serving` 30 s, `undetermined` never; `spokes register` refuses without the claim (`hub-claim-missing`). Lead capture, the resolver and magnet completion never read it, and a boot without the package answers as an empty registry (the four routes `404`). No MCP twin for any of the four — a credential exchange between a site and its hub is not an agent-facing call (#3591 exception, the `/v1/auth/tokens` footing). The browser step lives on the hub's web app: `apps/web/app/api/auth/hub/authorize/route.ts`.
72
+ - `/v1/hub-sign-in/entry` (POST), `/v1/hub-sign-in/google` (POST) — the spoke-hosted sign-in entry (#11096, spec `docs/specs/11096-the-spoke-hosts-the-sign-spec.md` D2, D10), in `hubSignInClientRoutes` beside `token`: each authenticates the calling spoke as `token` does (`Authorization: Basic clientId:secret` AND `x-ailk-spoke-key`). `entry` is the hub web's check before it mails a magic link a spoke's form asked for (`{ clientId, redirectUri, email }`, the client's own id and a registered callback, 60 a client a minute and 5 per client and SHA-256 of the lower-cased email per 10 minutes); it sends and writes nothing and logs no email. `google` trades a returning Google person's One Tap ID token (`{ idToken, nonce, origin }`, the origin equal to the client's registered one) for the same credential the code exchange mints, verified against Google's keys with `AILK_GOOGLE_ONE_TAP_CLIENT_ID` as its audience (unset: `404`; set, client info names it as `oneTapClientId`); a `sub` with no Google account row is `404`, never a new user. No MCP twin for either — a site's sign-in step, the `token` footing.
72
73
  - `/v1/checkout/sessions` — start a Stripe checkout. **Two paths (#8931, `src/routes/checkout/sessions.ts` over `src/services/offerings/checkout-authorization.ts`; spec `docs/specs/8931-offerings-checkout-authorization-server-side-spec.md`; contract A1–A11, A13).** The path comes from `resolvePublicWorkspace()` and the workspace's own Organization alone — no body field names either: a resolved workspace whose Organization has a Stripe connection takes the **Offerings path**; a presented `x-ailk-spoke-key` the resolver refuses is `503 { error: "tenant_unresolved" }` with no Stripe call; a corrupt connection, or a database read that fails while choosing, is `502 checkout-unavailable`; everything else (keyless, `ambiguous`, off the database adapter, no Organization, no connection) takes the **env path**, today's code. **A spoke authenticates with its key on a hub that sets `OSS_API_INTERNAL_SECRET` (#9910; spec `docs/specs/9910-a-spoke-can-start-an-spec.md`):** a call with no `x-internal-auth` header and an `x-ailk-spoke-key` `resolveCallerSite` resolves to a registered, unrevoked spoke is a spoke call — it sells only that spoke's own workspace (a path naming any other is `401`), and its `successUrl` and `cancelUrl` must be on the origin of the spoke's enabled hub sign-in client's first redirect URI (`registeredSpokeOrigins`, read through `installedHub()`), else `400 validation-error`; a spoke with no such origin is `500 config-error`, both before any Stripe call. A refused key, no credential at all, or a presented `x-internal-auth` that does not match is `401 internal-auth-required` — the keyless and wrong-secret `401` before any read — and a matching `x-internal-auth` keeps its redirects. On a hub without the secret every caller is unchanged. **The env path is the hub's own-products path only, never a spoke's (#9142):** a spoke sells only through its `apps/web` Offerings buy route, which calls this route only for a lookup key its connected workspace's shown set holds, so a spoke's buy always takes the Offerings path; the spoke's own env-key buy route and Stripe webhook are retired. The Offerings path charges `chargeWriteBudget` scope `offeringscheckout` before the body is read — 10 a minute per `request.ip` and 60 per workspace (`OFFERINGS_CHECKOUT_PER_WORKSPACE_PER_MINUTE`), charged one at a time with the IP first, so a request its IP bucket refuses never spends the workspace's, whatever the process's mode — answering `429 { error: "rate_limited", retryAfterSeconds }` with `Retry-After`. It parses `productCode` (the full lookup key) by the one grammar first, builds the connection's own client (`stripeClientForOrganization` with `{ storedOnly: true }` — the stored connection only, never the environment key, so a connection deleted between the path read and this one is `502`, #9346), reads org-enabled ∩ workspace-shown from the rows (`getSellableProductIds`, never the snapshot), looks the key up live on that client, and sells only when the Price's own Product is in the set — and, for a workspace saved per Price (#9070 D5), the Price itself is one of its stored shown Prices (`getSellableProductIds`' `priceIds`; `null` for a row saved per Product) — and `normalizeCatalog` keeps that Price under that key and period. Every miss — ungrammatical, not enabled, not shown, moved, archived, nonexistent — is the one `404 { error: "unknown-product-code" }`, never echoing the key; Stripe, the rows or the connection failing is `502`, never the snapshot or the env key. The session is anonymous (no `customer`, no signed-in buyer, so no `ailk_user_id`), sells the authorized Price id, allows promotion codes, `customer_creation: "always"` in payment mode, and is stamped by the server `metadata` and `subscription_data.metadata` `{ site: <workspaceId>, ailk_offering: <lookup key> }`; it is recorded through `recordCheckoutSession` before the route answers, and a failed record expires it on the same client and answers `502`. **The env path refuses an Offerings product (A9):** `createCheckoutSession` gets `{ refuseProduct: isOfferingsProduct }`, so a Price whose Product carries `metadata.ailk_group` (or whose Product did not expand) is the same `404`. **The Offerings path refuses the hub's own plans (#9338 DD5):** right after the grammar parse, a key whose plan begins `ailk-` (`HUB_PLAN_PREFIX`, any period — `ailk-pro`, `ailk-pro-plus` and any hub plan added later, #9968) is the same `404`, before any read or Stripe call, for every Organization but the one whose fulfilment hook mints licences (#9383 DD5, `fulfilmentFor(organizationId)?.mintsLicences`, read with no Stripe call) — anywhere else such a sale would stamp `ailk_offering` with no licence minted for it. Every hub plan's lookup key begins `ailk-` (`ailk-<plan>_<period>`, as `PLAN_PURCHASE_LOOKUP_KEYS` builds them): a hub plan keyed outside that namespace is outside this refusal. The request schema and the `201 { sessionId, url }` body are unchanged, so the `start_purchase` parity row is too. **`GET /v1/checkout/sessions/:id` (A13):** when `DATABASE_URL` is set, a session `readCheckoutSessionRecord` holds is read with that record's Organization's own client (keeping the environment fallback, so a session Start trial recorded on the owner's environment key stays readable), only in the record's mode; its line-item names pass the catalog's T1 `normalizeText`; a record that cannot be read, or a connection gone, unusable or in another mode, is `502`, never the env path; no record is today's env read. Logs carry the workspace or Organization, an 8-character session prefix and a fixed reason only.
73
74
  - `/v1/workspaces/:workspaceId/{theme,identity,seo}` (GET/PUT) — per-workspace site config (multi-tenant module). PUT needs `workspace-settings` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)), checked before the body parse; GET stays open to every member.
74
- - `/v1/workspaces/:workspaceId/meetings` (GET/PUT) — the operator's enabled-slug gate for meeting types (#6183 S9b, `src/routes/workspaces/meetings.ts`). Beside the three siblings above in URL shape and tenant-isolation posture, but registered in its OWN scope, gated on `isModuleEnabled("scheduling")` ALONE — not the `workspace`/`multi-tenant` scope its siblings share, because its GET reaches `services/scheduling/` (see below), which a scaffold without that module does not carry (#5701; since #9565 the package boundary — `@working-theory/api-scheduling` owns both files). PUT needs `meeting-types-manage` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)) because this blob decides which pages the public site serves. GET answers `meeting-types-manage` with the full join and `meeting-types-read` (every role, a member included) with the ENABLED rows only (#7636 D6) — since it does NOT just return the stored blob, it echoes the deployment's whole provider catalog, including the rows the operator chose not to publish (security review, 2026-09-19), which a member never sees. GET is the one segment in this file's family that does NOT just return the stored blob: it ALSO lists the scheduling provider's own bookable event types (`listEventTypes`, #6182), joined with `enabled: boolean`; an unconfigured/unreachable provider answers the same `SchedulingErrorKind` outcome `/v1/schedule/*` uses, distinct from an empty list. **`customerSlugs` (#8171 D5)** — who may book from the member area, independent of `enabledSlugs`: `GET ?include=customers` adds `customer: boolean` per row, and without it the body is unchanged; the PUT carries `customerSlugs`, and a PUT without it keeps the stored list (a read then a write, last-writer-wins), so the public toggle never erases it. `enabledSlugs` keeps its whole-list meaning, so a writer of `customerSlugs` sends the `enabledSlugs` it read. **`include` is a comma list (#9128)** — `?include=customers,private`, in either order, or a repeated `include` key; an unknown value is ignored, so `?include=customers` alone reads as before. **`private` adds `private: boolean` per row** — membership of the stored `privateSlugs` (#8843 D2), the Admin meeting page's Private switch — on the `meeting-types-manage` full join only: a `meeting-types-read` caller never receives it, whatever it asks. The PUT carries `privateSlugs` whole-list and keeps a stored list a body leaves out, as it does `customerSlugs`. An agent's PUT is audited `meetings.set_customers` when it carries `customerSlugs`, else `meetings.set_enabled`. Its MCP twins are the signed-in `list_meeting_types` (GET) and `save_meeting_types` (PUT) (#10950, `@working-theory/mcp-scheduling`); both parse `@working-theory/validation` schemas — `inboxWorkspaceParamsSchema`, `workspaceMeetingsQuerySchema`, `meetingsConfigSchema` (site-config's `MeetingsSchema`, moved). The `…/meetings/connection` routes have no tool, by decision (`scheduling-connection` is never agent-grantable).
75
+ - `/v1/workspaces/:workspaceId/meetings` (GET/PUT) — the operator's enabled-slug gate for meeting types (#6183 S9b, `src/routes/workspaces/meetings.ts`). Beside the three siblings above in URL shape and tenant-isolation posture, but registered in its OWN scope, gated on `isModuleEnabled("scheduling")` ALONE — not the `workspace`/`multi-tenant` scope its siblings share, because its GET reaches `services/scheduling/` (see below), which a scaffold without that module does not carry (#5701; since #9565 the package boundary — `@working-theory/api-scheduling` owns both files). PUT needs `meeting-types-manage` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2)) because this blob decides which pages the public site serves. GET answers `meeting-types-manage` with the full join and `meeting-types-read` (every role, a member included) with the ENABLED rows only (#7636 D6) — since it does NOT just return the stored blob, it echoes the deployment's whole provider catalog, including the rows the operator chose not to publish (security review, 2026-09-19), which a member never sees. GET is the one segment in this file's family that does NOT just return the stored blob: it ALSO lists the scheduling provider's own bookable event types (`listEventTypes`, #6182), joined with `enabled: boolean` (Live, at any visibility) and `visibility`; an unconfigured/unreachable provider answers the same `SchedulingErrorKind` outcome `/v1/schedule/*` uses, distinct from an empty list. **`visibility` is on every row (#11122 D4)** — `public`, `private` or `authenticated`, from the stored lists by `@working-theory/validation`'s `meetingVisibilityOf` (`authenticated` when `customerSlugs` holds the slug, else `private` when `privateSlugs` does, else `public`) — with the provider's `providerEventTypeId` and `createdAt` when it serves them; `providerEditUrl` (the provider's edit page for the type) is on the `meeting-types-manage` full join only, never a `meeting-types-read` caller's. There is no `include` query any more (it was a comma list, #9128): a caller still sending one gets the same body. **`customerSlugs` (#8171 D5) and `privateSlugs` (#8843 D2) are exclusive (#11122 D5)** — `customerSlugs` makes a type Authenticated (booked from the member area only, never listed on the site), `privateSlugs` Private (listed on `/private` rather than `/meet`). A body naming one slug in both is `400 validation_failed`; a list the body leaves out keeps the stored list less every slug the sent list holds, so the sent list wins (a read then a write, last-writer-wins) and the public toggle never erases either. `enabledSlugs` keeps its whole-list meaning — Live at any visibility — so a writer of either list sends the `enabledSlugs` it read. An agent's PUT is audited `meetings.set_customers` when it carries `customerSlugs`, else `meetings.set_enabled`. Its MCP twins are the signed-in `list_meeting_types` (GET) and `save_meeting_types` (PUT) (#10950, `@working-theory/mcp-scheduling`); both parse `@working-theory/validation` schemas — `inboxWorkspaceParamsSchema`, `meetingsConfigSchema` (site-config's `MeetingsSchema`, moved). The `…/meetings/connection` routes have no tool, by decision (`scheduling-connection` is never agent-grantable).
75
76
  - `/v1/workspaces/:workspaceId/meetings/connection` (GET, PUT, DELETE) — the workspace's own scheduling connection (#7533, `src/routes/workspaces/meetings.ts`; data access and the cipher in `src/services/scheduling/connections.ts`, the only file that touches `prisma.schedulingConnection`). Same registration, scope and tenant guard as the meetings route above. GET, PUT and DELETE all need `scheduling-connection` (owner, admin — `@working-theory/validation`'s permission table (#7636 D2), the operator's 2026-10-04 decision overturning SEC-7533-11's owner-only write). GET answers `null` or a summary — `provider`, `baseUrl`, `webhookPath`, `createdAt`, `updatedAt` — with no credential, secret, ciphertext or hint of one. PUT takes a strict `{ provider, apiKey, baseUrl? }`; create and replace are one operation, and every PUT mints a new webhook token and secret, returning the secret this once (`Cache-Control: no-store`) so the operator can paste it into the provider — a replace cuts off the previous entry point. `baseUrl` must be `https://api.cal.com` or the deployment's own `CAL_API_BASE_URL` origin, with no path, query or userinfo (`400 base_url_not_allowed`); only the bare origin is stored. The credential and the secret are AES-256-GCM ciphertext under `SCHEDULING_CREDENTIAL_KEY`, bound to the workspace and the column; with the key unset, PUT answers `503 credential_key_not_configured` before any write. DELETE is idempotent (`{ revoked }`) and unconfigures the workspace at once. Because a connection replaces the account every provider call uses, every successful PUT, and every DELETE that revoked a row, writes one `recordAgentAction` audit row (`scheduling.connection.{connect,replace,remove}`; a PUT is `replace` whenever the workspace was served by any provider before it — its own row, or the env credential on a one-workspace deployment) and emails every OTHER owner of the organization through `@working-theory/email`'s `sendSchedulingConnectionChangedEmail` (#7636 D7). Neither step can fail the write: a failed audit is logged at `error`, and the notify step runs in its own `try`, so the one-time secret is always returned; with no sender address or no Resend key it is skipped with a `warn`. Logs carry the recipient count, never an address. The meetings GET above, and the three anonymous `/v1/schedule/*` provider routes below, resolve their provider through `src/services/scheduling/resolve.ts`: a workspace's own row always wins; `CAL_API_KEY` serves a workspace only on a one-workspace deployment; otherwise `not_configured`. No MCP twin — identity-bound tenant routes (#3591 exception).
76
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).
77
78
  - `/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`.
@@ -84,7 +85,7 @@ Routes are versioned under `/v1/*`:
84
85
  - `/v1/workspaces/:workspaceId/people/:personId/pieces` (GET, POST), `…/people/:personId/pieces/:pieceId` (PATCH), `/v1/workspaces/:workspaceId/piece-stages` (GET, PUT), `…/people/:personId/plan` (PUT), `…/people/:personId/messages` (GET, POST) — the member area as an operator keeps it (#7877, `src/routes/workspaces/{pieces,plan,messages-out}.ts` over `tenantDb(tenant).memberArea`; spec `docs/specs/7877-the-member-area-contract-a-spec.md`). A **Piece** is one deliverable for one client: a title (1–200), a **stage** drawn from the workspace's OWN declared list (`WorkspacePieceStages`, one row per workspace; no row is the product default `requested, in-progress, in-review, delivered`, which lives only in `lib/tenant-db.ts`'s `DEFAULT_PIECE_STAGES` — there is no stage enum anywhere), a `needsClient` flag and `updatedBy`. The **plan** is `Person.planOffering` (#852's field — never a Plan model), written only by `services/person.ts`'s `setPersonPlanOffering`. A **message** is an `Interaction` on the `member` channel, direction `outbound`: a plain-text subject (1–200) and body (1–10000), both stripped of control and bidi characters (the body keeps `\n`, `\t`), and an optional attachment that must be an `Asset` of THIS workspace tagged `private` with a raster-image or PDF type (never SVG) — `400 asset_not_found` / `400 asset_not_attachable` otherwise. Both records reference a Person of the same workspace through a composite `(person_id, workspace_id)` foreign key. Role floors from `@working-theory/validation`'s permission table: the two list reads need `people-read`, the stage PUT `workspace-settings`, the stage GET the guard alone, each checked by role (`roleAllows(tenant, …)`) before any read, so an agent's `people-read` grant does not reach pieces or message bodies; the four writes — piece POST and PATCH, plan PUT, message POST — need `member-pieces-manage` (owner, admin, member since #8514), checked with `allows(tenant, "member-pieces-manage")` before any read, so an agent key granted it (#7878, the seventh `AGENT_GRANTABLE_PERMISSIONS` entry) keeps them in its one workspace, attaching only an asset the message's own checks admit; attaching a file to a message or delivering one as a version also needs `assets-write` (#8514 D19), so a member sends text and link versions, never a private file. `GET …/plan-offerings` (#8514 D9, `people-read`) lists plan keys for the Admin's picker from one of two sources (#8934, `services/plan-offerings.ts`): with the `commerce` claim, a connected workspace with a current Offerings snapshot lists one item per sellable Price in its shown set (`getWorkspaceShownSet`, never Stripe) — `key` the full lookup key, `name` the product name and its billing word, `type` `plan` or `addon`; an unclaimed workspace, or one with no connection or no selection, lists its own Service then Product pages (`services/public-site-resolver.ts`'s `workspaceContentAdapter`: off the database adapter only the default workspace has content, every other workspace `[]`). An undetermined licence or an expired or empty snapshot is a failed read (`{ offerings: [] }` and one warn line), and so the magnet checkout check and the purchase name fail closed. `people-write` (owner, admin, member since #8514) is never agent-grantable and is no longer read by these routes — the Admin person page reads it to render its forms. A malformed, absent or foreign Person or piece is one `404 not_found`; a stage outside the declared list `400 invalid_stage`; a stage-list PUT that drops a stage a piece still holds `409 stage_in_use` with nothing written — piece writes and stage changes take one per-workspace advisory lock first, in one transaction. Lists hold at most 50 rows, newest first. Every write that reaches the store records one `recordAuditAction` row naming the actor (`people.piece.create`, `people.piece.update`, `people.stages.set`, `people.plan.set`, `people.message.create`); no audit summary or log line carries a title, subject, body or offering. The operator's message read never stamps `readAt`, and serves an attachment by its sanitized download name, never its asset id. **The checkout plan rule:** a `POST /v1/leads/submit` from a registered spoke (`viaSpoke`) whose `Idempotency-Key` is a LIVE Checkout Session id (`cs_live_…`), with `source: "web"`, `payload.page: "checkout"`, a string `payload.offering` and `payload.site`, and an `amountTotal` that is absent, `null` or positive, names a plan — the offering minus a leading `<site>_` — but never writes one (#8793): its email is what the buyer typed at Stripe Checkout, so the lead HOLDS the plan (`services/lead-routing.ts`, one `{ event: "checkout-plan", outcome: "held" | "skipped", siteId }` line, no Person call; a request relayed for a visitor never reaches it). `services/person.ts`'s `releaseHeldCheckoutPlan` releases it once, when `resolveMemberPersonId` (a member read, or `GET /v1/hub-sign-in/me`) first links the Person to the signed-in user whose verified email is the Person's own (a fresh `stamped` only — never a Person linked earlier, never the Inbox accept's link): into a blank plan only, through `setPersonPlanOffering`'s link guard, and only when the Person has at most 50 marked leads and those under that email all name one key — two keys, or more than 50 marked leads, release nothing and the operator sets the plan. Never on a replay, never refusing or changing the lead, the purchase message, the purchase email or the consent grant, and with no spoke change. Same registration, scope and tenant guard as the routes above (`workspace || multi-tenant`). **Proposals (#8516, spec `docs/specs/8516-proposals-as-an-artifact-kind-spec.md`):** a piece now carries a `kind` — `deliverable` (every piece before #8516, the column default) or `proposal` — served on every piece row and never set or changed through the piece routes (a body naming it is `400 validation_failed`), plus a proposal's optional price (minor units of `usd`/`eur`/`gbp`/`cad`/`aud`). `GET …/people/:personId/proposals` (a person's `people-read` role or an agent's `member-pieces-manage` grant) lists the Person's proposals with their price, approval, paid stamp and latest version, and `payments` (`on-approval` or `off`); `POST …/people/:personId/proposals` (`member-pieces-manage`; a file version also `assets-write`) is Send proposal — the proposal (`needsClient: true`, the first declared stage unless named) and its version 1 in one transaction under the piece lock, one `people.proposal.create` audit row whose summary is `{ priced }` alone. **Only a person prices (C4, the money gate):** an agent's create with a price, and an agent's PATCH or Deliver a version on a priced proposal, are `403 proposal_needs_person` with nothing written. Both read and write through `tenantDb(tenant).memberArea`. The proposals pair has MCP twins on `/mcp/workspace`: `list_proposals` and `create_proposal` (#8516 D7). **Start onboarding (#8515 D5, D6):** `POST …/people/:personId/onboarding` (`member-pieces-manage` through `allows`) takes `{ subject, body }` (the message bounds, no attachment — a body naming `assetId` is `400 validation_failed`) and writes one outbound member message whose `payload` is `{ action: "onboarding" }` — the one outbound payload `interactions_outbound_shape` admits — which the client's own site renders as a link to its `/account/onboarding`; it reads the workspace's onboarding magnet through `tenantDb(tenant).flows.bySlug` and never seeds one: no `diagnostic` row at that slug with `who: "user"` is `409 onboarding_off` with nothing written. A malformed, absent or foreign Person is the same `404 not_found`; one `people.onboarding.start` audit row, no summary. The message POST never carries the action. The message POST has its MCP twin, `send_person_message` on `/mcp/workspace` (#10957); the other member-area routes have no MCP twin, by decision — the message list checks `people-read` by role, which no agent holds — recorded in `tests/parity/README.md`.
85
86
  - `…/people/:personId/messages` (POST) emails, and `/v1/workspaces/:workspaceId/people/:personId/invitation` (GET, POST) invites (#9690, spec `docs/specs/9690-invite-and-reply-spec.md`): a reply is saved, then emailed in full with a link to the member area (`/account/inbox/message/:id`) when the Person's address is proved, else to sign-up — `201 { message, delivery }`, where a failed email never fails the 201 and an agent's reply goes only to a proved address (`withheld` otherwise); it writes no thread state. The invitation pair (a person only — every agent is `403` with one `refused` row) reports `{ hasAccount, lastInvitedAt }` and, on `{ "invite": true }`, emails the site's sign-in link and creates nothing; a repeat is a Resend, a proved Person is `409 has_account`. Both emails come from `AILK_INBOX_FROM`, else `AILK_LEAD_NOTIFICATION_FROM`, through `@working-theory/api/services/inbox-mail.js`. Per-caller send caps (`api-workspace/src/services/send-caps.ts`: 20 sends an hour per caller, 10 replies an hour and 3 invitations a day per caller to one Person) are counted from the rows each send writes before its email, under a per-workspace advisory lock (`tenantDb.inboxSends`); a capped send is `429` with `Retry-After` and the named reason, a lock or count failure `503 send_cap_unavailable`. No MCP twin for the invitation pair (it refuses agents; `tests/parity/README.md`).
86
87
  - `/v1/member/pieces` (GET), `/v1/member/messages` (GET), `/v1/member/messages/:id/file` (GET) — the member reads: a client's OWN pieces and messages, served to the spoke that signed them in (#7877, `src/routes/member/{pieces,messages}.ts`). Registered in `authScope` only (auth, NOT tenant-guarded — a client holds no membership; an agent key is 403 at the preHandler) under the same `workspace || multi-tenant` predicate, at the exact URLs `HUB_SESSION_ROUTES` admits a hub credential on. Who and where come only from `services/member-area.ts`'s `resolveMember`, before any member read: the caller through `middleware/auth.ts`'s `memberCaller` — the hub's own cookie session or a hub credential, never a personal `ApiToken` (`401 { error: "unauthorized" }`); the workspace from the calling spoke's `x-ailk-spoke-key` (a keyless call only on a one-workspace deployment that is not a hub), and a hub credential must name that same workspace, else `503 tenant_unresolved`; an unverified email `403 email_unverified`. The Person is the one linked by `Person.userId`, else the one whose email is the caller's verified email, linked on that first read by `stampPersonUser`'s rule; no Person is `items: []`. Every read goes through the named boundary `src/lib/member-store.ts`, scoped by that resolved workspace AND Person: at most 50 rows, newest first; a message serves `{ id, subject, body, file: { filename, contentType } | null, createdAt, readAt }` — never an asset, creator, person or workspace id — and the first read stamps `readAt` ("shown to the client's spoke", not "read"; served as it stood before the stamp). The file read streams the attachment only when the message is the caller's own and its stored type is attachable — any other case is one `404 not_found` — `attachment` with a sanitized, extension-pinned name, `nosniff`, the sandbox `Content-Security-Policy` and `Cache-Control: private, no-store`. `@working-theory/api-client`'s `member.*` is the spoke's caller; a spoke that re-serves the bytes sends those five headers unchanged. No MCP twin, by decision — identity-bound client reads behind a hub credential; the anonymous MCP surface is identity-blind, recorded in `tests/parity/README.md`.
87
- - `/v1/member/purchases`, `/v1/member/appointments`, `/v1/member/artifacts`, `/v1/member/artifacts/:pieceId/versions/:version/file`, `/v1/member/meeting-types`, `/v1/member/availability`, `/v1/member/request-form`, `/v1/member/billing` (all GET) — the Phase 1 member reads (#8169, `src/routes/member/{purchases,appointments,artifacts,meeting-types,availability,request-form,billing}.ts`; spec `docs/specs/8169-member-reads-spec.md`). Same caller seam, refusals and registration as the bullet above, each read through one `src/lib/member-store.ts` function, each success body re-parsed against its `@working-theory/validation` `member.ts` schema. All eight are in `HUB_SESSION_ROUTES` (#8220). Appointments, artifacts and the file read are scoped by the resolved workspace AND Person (≤ 50, never an attendee's name, email or time zone; never a version or asset id; the file read is one `404 not_found` for every miss, a version above the 32-bit column included, and sends `messages.ts`'s five headers). **Purchases and billing read at workspace grain** (#9966 D4, replacing #8140's organization grain): only Persons in the calling workspace whose `userId` is ALREADY the caller (`lib/member-store.ts`'s `linkedPersonsInWorkspace`, pinned by `src/__tests__/member-isolation.test.ts`) — they link nothing, and a spoke's credential never reads a sibling workspace of its organization. A purchase is a completed hub `FlowCheckout` whose lead carries the caller's VERIFIED `User.email` (case-insensitive; never the Person's email, which is whatever a buyer typed at intake — #8241), or (#8185) a `Lead` the hub marked `spokeCheckout` when it was written — a registered spoke's unrelayed (`x-ailk-relayed` absent), LIVE paid checkout, the #7877 plan rule's own predicate evaluated in `services/lead-routing.ts` before the create and never updated, or (#8932) the per-Organization Stripe webhook's live, recorded, paid Offerings session, marked by that predicate's Offerings twin — served with the same Person-workspace and verified-email rules, its offering kept only if it is a plan-offering key (SEC-8169-6); an anonymous, relayed, test-mode or pre-#8185 lead is never marked and never served (no backfill), and `tests/architecture/idempotency-key-producers.test.ts` fails if any spoke-side file, MCP tool or client wrapper starts sending an `Idempotency-Key`. **Billing answers a hub credential only**: any other caller gets `404 not_found` before `resolveMember` and before any read, and no log line ever names a `cus_` id; a hub credential reads it at the workspace grain. Meeting types and availability join the workspace's `customerSlugs` (independent of `enabledSlugs`) to the scheduling provider — a provider failure is its `SCHEDULING_ERROR_STATUS`, never an empty list; a slug outside `customerSlugs` is `404 meeting_type_not_offered` with no provider call — and register under `scheduling && (workspace || multi-tenant)`, because only the `scheduling` module delivers `services/scheduling/`. The request form is the `request-quote` contact row while `who` is `user`, whatever its status, else `{ form: null }`. **`GET /v1/member/onboarding` (#8515 D7)** serves the standard onboarding magnet — the `diagnostic` row at slug `onboarding` while `who` is `user`, whatever its status — reduced to display keys (a field's name, input type, `required`, select options and label/help/placeholder; a choice question's name, options, `multi` and `exclusiveValues`; never a `showIf`, `mapsTo`, `purposes`, field rule, `segments`, `whenHidden` or `resultsReveal`), else `{ form: null }`. `GET /v1/member/messages` items carry `action: "onboarding" | null` (#8515 D6). No MCP twin, by decision — the same reason, recorded in `tests/parity/README.md`.
88
+ - `/v1/member/purchases`, `/v1/member/appointments`, `/v1/member/artifacts`, `/v1/member/artifacts/:pieceId/versions/:version/file`, `/v1/member/meeting-types`, `/v1/member/availability`, `/v1/member/request-form`, `/v1/member/billing` (all GET) — the Phase 1 member reads (#8169, `src/routes/member/{purchases,appointments,artifacts,meeting-types,availability,request-form,billing}.ts`; spec `docs/specs/8169-member-reads-spec.md`). Same caller seam, refusals and registration as the bullet above, each read through one `src/lib/member-store.ts` function, each success body re-parsed against its `@working-theory/validation` `member.ts` schema. All eight are in `HUB_SESSION_ROUTES` (#8220). Appointments, artifacts and the file read are scoped by the resolved workspace AND Person (≤ 50, never an attendee's name, email or time zone; never a version or asset id; the file read is one `404 not_found` for every miss, a version above the 32-bit column included, and sends `messages.ts`'s five headers). **Purchases and billing read at workspace grain** (#9966 D4, replacing #8140's organization grain): only Persons in the calling workspace whose `userId` is ALREADY the caller (`lib/member-store.ts`'s `linkedPersonsInWorkspace`, pinned by `src/__tests__/member-isolation.test.ts`) — they link nothing, and a spoke's credential never reads a sibling workspace of its organization. A purchase is a completed hub `FlowCheckout` whose lead carries the caller's VERIFIED `User.email` (case-insensitive; never the Person's email, which is whatever a buyer typed at intake — #8241), or (#8185) a `Lead` the hub marked `spokeCheckout` when it was written — a registered spoke's unrelayed (`x-ailk-relayed` absent), LIVE paid checkout, the #7877 plan rule's own predicate evaluated in `services/lead-routing.ts` before the create and never updated, or (#8932) the per-Organization Stripe webhook's live, recorded, paid Offerings session, marked by that predicate's Offerings twin — served with the same Person-workspace and verified-email rules, its offering kept only if it is a plan-offering key (SEC-8169-6); an anonymous, relayed, test-mode or pre-#8185 lead is never marked and never served (no backfill), and `tests/architecture/idempotency-key-producers.test.ts` fails if any spoke-side file, MCP tool or client wrapper starts sending an `Idempotency-Key`. **Billing answers a hub credential only**: any other caller gets `404 not_found` before `resolveMember` and before any read, and no log line ever names a `cus_` id; a hub credential reads it at the workspace grain. Meeting types and availability join the workspace's `customerSlugs` that are also in `enabledSlugs` (#11122 D6: an Authenticated type that is Off is bookable nowhere, the account included) to the scheduling provider — a provider failure is its `SCHEDULING_ERROR_STATUS`, never an empty list; a slug outside `customerSlugs` is `404 meeting_type_not_offered` with no provider call — and register under `scheduling && (workspace || multi-tenant)`, because only the `scheduling` module delivers `services/scheduling/`. The request form is the `request-quote` contact row while `who` is `user`, whatever its status, else `{ form: null }`. **`GET /v1/member/onboarding` (#8515 D7)** serves the standard onboarding magnet — the `diagnostic` row at slug `onboarding` while `who` is `user`, whatever its status — reduced to display keys (a field's name, input type, `required`, select options and label/help/placeholder; a choice question's name, options, `multi` and `exclusiveValues`; never a `showIf`, `mapsTo`, `purposes`, field rule, `segments`, `whenHidden` or `resultsReveal`), else `{ form: null }`. `GET /v1/member/messages` items carry `action: "onboarding" | null` (#8515 D6). No MCP twin, by decision — the same reason, recorded in `tests/parity/README.md`.
88
89
  - `/v1/member/requests` (POST), `/v1/member/messages` (POST), `/v1/member/bookings` (POST), `/v1/member/artifacts/:pieceId/review` (POST), `/v1/member/profile` (PATCH), `/v1/member/profile/contact` (GET, PATCH), `/v1/member/deletion-request` (POST) — the Phase 1 member writes (#8170, the contact pair #8435, `src/routes/member/{requests,messages,bookings,artifact-review,profile,deletion-request}.ts`; spec `docs/specs/8170-member-writes-spec.md`). Same caller seam and refusals as the reads, and a cookie write must carry a trusted `Origin` (the preHandler's 401). Nothing in a body, path or query names a person, user or workspace; every body parses its `@working-theory/validation` `member.ts` schema (`400 invalid_input`, or `400 link_not_https` when a link is why) and every success body is re-parsed before it is sent. **Requests, messages and reviews are each ONE inbound `Interaction` on the caller's own Person** — channel `member`, direction `inbound`, `createdBy` the caller — and never a `Lead`: a request is checked against the `request-quote` magnet's CURRENT field steps (`400 answers_invalid` for a key the form does not ask, a missing required answer, an array answer or a failed field rule; `409 request_form_off` when the form is off or the caller has no Person) and stores `{ flowSlug, items }` with each label as the form shows it; a message stores `{ link }` when one is sent (`404 not_found` with no Person). **The cap:** every inbound write runs in one transaction whose first statement is the Person's advisory lock (`ailk:member-inbound:<personId>`), then counts the Person's inbound rows of the last hour — 30 or more is `429 too_many_requests` with nothing written. **The review** lands only on the piece's LATEST version (`409 version_not_latest`), only once per version and never after `Piece.approvedAt` is set (`409 review_closed`); a missing, foreign or approved piece is refused from one read before any lock, otherwise the Person lock then the workspace's piece lock (`lib/tenant-db.ts`'s `pieceStagesLockKey`, the key the operator's piece writes take), and it writes the version's `review`, `reviewComment`, `reviewedAt`, the piece's `approvedAt` on an approval and the `review` Interaction in that one transaction — never a title, stage, link, asset or note; asking for changes stays open on every new latest version (#8140 disposition 3). **The booking** books an offered `customerSlugs` meeting type at `<handle>/<slug>` as the caller (verified email, own name), refuses a Person holding 10 upcoming non-cancelled appointments `429` before any provider call, answers a provider failure through `SCHEDULING_ERROR_STATUS`, and binds a spoke caller's booking to its workspace as `/v1/schedule/book` does; it registers under `scheduling && (workspace || multi-tenant)`. **The profile** writes only the caller's own `User.name` / `User.image` (https only) and answers `{ name, image }`. **The contact** (`profile/contact`, #8435) is the caller's contact details on THIS site, never on the hub `User` and never synced to another site: the GET serves the contact of the caller's linked Person only once a human saved it (`contactConfirmedAt` set — a value only an anonymous capture wrote is `{ contact: null }`, SEC-8435-B); the PATCH takes all six keys, each nullable and required, and REPLACES the whole contact (so no value the client never saw survives), stamping `contactConfirmedBy: "client"`. With no Person yet it finds or creates the Person for the caller's VERIFIED email and links it through `stampPersonUser`'s rule; any outcome but linked is `409 contact_unavailable`, nothing written. Only the caller's own linked Person (`{ id, workspaceId, userId }`) is ever written; `400 invalid_input` or `400 telephone_invalid` for a refused body, an 8 KiB body bound, and `{ event: "member-contact", outcome }` as its one log line. **The deletion request** is filed through `routeLead` as a `web` message lead (kind `deletion`, the caller's verified email, no idempotency key) into `resolveSiteWorkspaceId()` — the deployment's own site workspace, so a spoke caller's request reaches the hub operator (`sentTo: "hub-operator"`), never the spoke's. Every data write goes through `src/lib/member-store.ts`; every write logs only `{ event, outcome }` and a `ref` of at most 8 characters (`services/member-area.ts`'s `memberWriteLog`), never a subject, body, answer, link, note, name, email or full id. All six (and the two contact routes) are in `HUB_SESSION_ROUTES` (#8220): a spoke's deletion request reaches the hub operator, and a spoke's profile write changes the name and photo the hub's `me` answers. **The onboarding submission (#8515 D8–D10):** `POST /v1/member/onboarding` takes the request body's `{ answers }` (`plainText`, ≤ 64), checks them against the served onboarding form (every key a served field or question; a required field non-blank; `email`, https `url`, `select` options and `minLength` as the request checker applies them; a single choice one option value; a `multi` choice 1…options distinct option values, an exclusive value only alone — `400 answers_invalid` / `link_not_https`; `409 onboarding_off` with no Person or no form) and writes ONE `flow:onboarding` `Lead` — never an `Interaction` — on the caller's own Person with the Person's email, the answers, `flowSlug`, `locale` and the server-written `submittedBy` (the caller's user id, a server-owned key the Inbox never shows as an answer), so it is an Inbox submission and a `lead` Activity entry with no reader change. Under the Person's inbound lock, at most five of the caller's OWN submissions an hour (`429 too_many_requests`) — only leads carrying the caller's `submittedBy` count, so an anonymous `POST /v1/leads/submit` with that source and the client's email never fills the allowance. Both onboarding routes are in `HUB_SESSION_ROUTES`. **A proposal (#8516):** the artifacts read and the review answer carry `kind`, `price` and `payment` (`{ status: "due" }` for an approved, priced, unpaid proposal where payment runs; `{ status: "paid", paidAt }` once paid; else `null`), and a proposal's review — the same write, which is how a proposal is accepted or sent back — also writes one `people.proposal.client_review` audit row as the client (`recordWorkspaceAuditAction`). **`POST /v1/member/artifacts/:pieceId/payment`** opens the client's Stripe Checkout page for their own approved, priced, unpaid proposal and answers `{ url }` — a `checkout.stripe.com` URL only (`isStripeCheckoutUrl`, checked before anything is stored), `Cache-Control: private, no-store`. It sits behind the commerce claim (`requireCommerceClaim`, the module-disabled 404 before any read) and its own strict per-IP limiter (`proposalpay`); it is NOT on `HUB_SESSION_ROUTES`. **Same site, sandbox only:** `services/proposal-payments.ts`'s `proposalPaymentsFor` is `on-approval` only with the claim, on a one-workspace deployment whose workspace is the proposal's (the deployment's one Stripe account is provably that seller's), with a key `assertSandboxKey` admits and `FRONTEND_URL` set — and never for a call carrying a spoke key or a hub credential; anywhere else approval records acceptance only and the pay route is `404 not_found`. The session is card only, expires in an hour, carries a fixed product name and the stored amount (never a request value), and is reused while it has more than five minutes left; a concurrent second session is expired. `409 proposal_not_approved` / `409 proposal_paid` / `502 payment_unavailable`; each opened session writes one `people.proposal.checkout` audit row. No MCP twin, by decision — identity-bound client writes, recorded in `tests/parity/README.md`.
89
90
  - `/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`.
90
91
  - `/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`.
@@ -104,7 +105,7 @@ Routes are versioned under `/v1/*`:
104
105
  - `/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`.
105
106
  - `/v1/schedule/availability` (GET), `/v1/schedule/event-meta` (GET), `/v1/schedule/book` (POST) — anonymous scheduling proxy behind the provider seam (`src/services/scheduling/`); Cal.com v2 today, a self-hosted engine later, same three calls. `event-meta` is the meta-only read (title · duration · description · price) so rendering an event's facts never fetches an availability window (#4633). `CAL_API_KEY` is read server-side only. Which account answers is `resolvePublicSchedulingProvider` (#7533 D4), from `resolvePublicWorkspace()` and never the request: off the database adapter, the env credential as before; a resolved workspace, its own connection (or the env credential on a one-workspace deployment); an unresolved one, `503 not_configured` — fail closed. MCP twins: `list_availability` / `get_event_meta` / `create_booking` (#4416, #4633), unchanged — same arguments, same result shape. **A hub's spokes (#7944):** a call carrying a spoke key passes one gate before any event, slot or booking call — every calLink's slug must be one its workspace has enabled (no provider call at all), and every calLink's owner must equal the handle of the account the workspace's credential belongs to (`SchedulingProvider.getAccountHandle()`, Cal `GET /v2/me`, remembered 60 s per key, an empty answer never remembered); a refusal is `404 event_not_found`, an unreadable handle the read's own kind (`502 provider_error`), and each refusal logs one `warn` of `{ route, spokeId, reason }` and nothing else. A refused key keeps the answer each route gave it before; keyless callers skip the gate and never read the handle. The MCP twins forward no visitor identity, so every MCP caller shares the MCP host's one per-IP `schedule` bucket on the hub (`availability`, `event-meta` and `book` counted together): one caller's reads can make `create_booking` answer 429 for every other MCP caller of that host. This is accepted (#7944 D6) — the site's own booker carries the visitor's identity through the relay and is unaffected; the reopen trigger is recorded in `apps/mcp/src/tools/create_booking.ts`'s header
106
107
  - `/v1/schedule/meeting-types` (GET) — the enabled-meeting-slugs public read (#6183 S9b, `src/routes/schedule/meeting-types.ts`): the session-less read the public `/meet` surface needs to honour the operator's enabled-slug gate (`/v1/workspaces/:workspaceId/meetings`, above), since a public page holds no session. Resolves its workspace via `resolvePublicWorkspace()` (the same fail-closed predicate the public content read uses — no client-suppliable workspace, ever) and reads through a new named public-read boundary, `src/lib/public-meetings-config.ts` (modelled on `lib/asset-store.ts`): one `findUnique` by the resolved `workspaceId`, no write, no list. `{ slugs: string[] | null }` — `null` means "no stored list" (an unconfigured deployment, or the non-database adapter). Since #8843 no in-tree page calls it: the booking pages read `/v1/schedule/meetings` below, whose no-row rule replaced the web app's env-derived singleton; it stays for a spoke on an older `apps/web`. Reads no client input. No MCP twin — deferred to a named follow-up rather than silently skipped (the route's own header, §10 Q3 of the spec).
107
- - `/v1/schedule/meetings` (GET) — the meetings read (#8843 D1–D3, `src/routes/schedule/index.ts`; spec `docs/specs/8843-the-meet-index-and-meeting-spec.md`): the caller's workspace's Live meetings with every fact a booking page shows, so no title, length, description or price is copied into content. Anonymous, in the same `scheduling`-gated schedule scope and strict per-IP limit as its siblings. It takes no argument (a query parameter is `400 invalid_input`, as its twin refuses one): the workspace comes from `resolvePublicWorkspace()`, the provider from `resolvePublicSchedulingProvider`, a refused spoke key, no provider or an unresolved workspace answering `503 not_configured`. The Live set is the stored row's `enabledSlugs` that pass `MeetingSlugSchema`; with no row a spoke's is empty (and no provider call is made), and a keyless caller's is every event type the account lists. Rows: each listed event type whose slug is Live, in the provider's order, `bookable: true` with `calLink` (`<account handle>/<slug>`), `title`, `durationMinutes` and the optional `description` and `price`; then each Live slug the provider does not list, `bookable: false` (a `null` handle makes every row non-bookable); each with `visibility` (`private` when the row's `privateSlugs` holds it, else `public`) and `position`, at most 20 rows. These rules live in `src/services/scheduling/meetings.ts`'s `listWorkspaceMeetings` (#9129), which the route calls with the account handle read; `GET /v1/member/meeting-types` calls the same function's `customers` list without it, so the member read makes no `/v2/me` call. **`privateSlugs` (#8843 D2)** is a fourth optional list on the meetings blob — what a site lists on `/private` rather than `/meet`; the meetings PUT keeps a stored list a body leaves out, as it keeps `customerSlugs`, and `meeting-types` ignores it. `enabledSlugs` keeps its whole-list meaning (a body without it parses to `[]`), so a writer of `privateSlugs` sends the `enabledSlugs` it read. **Private means unlisted, not access-controlled:** the read and its twin serve private rows to any caller, and `availability`, `event-meta` and `book` accept a private Live slug like a public one. The body is re-parsed against `MeetingListSchema` before it is sent (a failure is `502 provider_error`); a provider failure logs `{ route: "meetings", kind, detail }`, and nothing is logged on success. MCP twin: `list_meetings` (D5).
108
+ - `/v1/schedule/meetings` (GET) — the meetings read (#8843 D1–D3, `src/routes/schedule/index.ts`; spec `docs/specs/8843-the-meet-index-and-meeting-spec.md`): the caller's workspace's Live meetings with every fact a booking page shows, so no title, length, description or price is copied into content. Anonymous, in the same `scheduling`-gated schedule scope and strict per-IP limit as its siblings. It takes no argument (a query parameter is `400 invalid_input`, as its twin refuses one): the workspace comes from `resolvePublicWorkspace()`, the provider from `resolvePublicSchedulingProvider`, a refused spoke key, no provider or an unresolved workspace answering `503 not_configured`. The Live set is the stored row's `enabledSlugs` that pass `MeetingSlugSchema`, less its `customerSlugs` (#11122 D6: an Authenticated type is booked from the member area only, so it is never on `/meet`, `/private` or the public booker — `public-meetings-config.ts` answers that difference to every public route); with no row a spoke's is empty (and no provider call is made), and a keyless caller's is every event type the account lists. Rows: each listed event type whose slug is Live, in the provider's order, `bookable: true` with `calLink` (`<account handle>/<slug>`), `title`, `durationMinutes` and the optional `description` and `price`; then each Live slug the provider does not list, `bookable: false` (a `null` handle makes every row non-bookable); each with `visibility` (`private` when the row's `privateSlugs` holds it, else `public`) and `position`, at most 20 rows. These rules live in `src/services/scheduling/meetings.ts`'s `listWorkspaceMeetings` (#9129), which the route calls with the account handle read; `GET /v1/member/meeting-types` calls the same function's `customers` list without it, so the member read makes no `/v2/me` call. **`privateSlugs` (#8843 D2)** is a fourth optional list on the meetings blob — what a site lists on `/private` rather than `/meet`; the meetings PUT keeps a stored list a body leaves out, as it keeps `customerSlugs`, and `meeting-types` ignores it. `enabledSlugs` keeps its whole-list meaning (a body without it parses to `[]`), so a writer of `privateSlugs` sends the `enabledSlugs` it read. **Private means unlisted, not access-controlled:** the read and its twin serve private rows to any caller, and `availability`, `event-meta` and `book` accept a private Live slug like a public one. The body is re-parsed against `MeetingListSchema` before it is sent (a failure is `502 provider_error`); a provider failure logs `{ route: "meetings", kind, detail }`, and nothing is logged on success. MCP twin: `list_meetings` (D5).
108
109
  - `POST /v1/webhooks/calcom` — the scheduling booking-event receiver (#6085, brief H7): verifies the provider's HMAC-SHA256 signature (`x-cal-signature-256`) over the raw body, then normalizes one of six `BOOKING_*` trigger events into an `Appointment` row (`src/services/scheduling/appointments.ts`). `CAL_WEBHOOK_SECRET` is read server-side only (`config/index.ts`); an unset secret answers `503`, never a silent accept. Registered on the same `webhooksScope` as `/v1/webhooks/stripe` (its raw-body content-type parser is what a signed receiver needs), module-conditional (`scheduling`, `src/routes/webhooks/index.ts`). No commerce-claim read: a booking event is not a money event (D-67 puts the payment on the provider's own side). No MCP twin — an inbound receiver for one named provider, not an endpoint an agent could reasonably call, the same footing `POST /v1/webhooks/stripe` already takes.
109
110
  - `POST /v1/webhooks/calcom/:connectionToken` — the same receiver for ONE workspace's own connection (#7533 D6, `calcomConnectionWebhookHandler`). The 43-character token in the path names one `SchedulingConnection` row, whose own decrypted secret verifies `x-cal-signature-256` and whose `workspaceId` the Appointment is written to — nothing in the body, query or headers reaches the workspace. A malformed or unknown token, or another provider's connection, is `404 not-found` (logged nothing); a secret that will not decrypt is `503 webhook-not-configured`; the rest of the ladder is the legacy route's, by the same code. Same module gate and `loadSlice` call as the legacy route, its own rate-limit bucket. The legacy `POST /v1/webhooks/calcom` is unchanged: the env account's receiver, writing into the `AILK_SITE_ID` workspace (SEC-7533-2, accepted). No MCP twin — the same inbound-receiver footing as the legacy route.
110
111
  - `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.
@@ -234,7 +235,11 @@ sweep's own DB constraint (never a caller-side lock).
234
235
  - Don't bundle `apps/api` (esbuild, rollup, webpack). Slice specifiers cannot survive it — see `## Deploy path`.
235
236
  - 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.
236
237
 
237
- Last updated: 2026-11-04 — #10819: the magnets bullet names `who` (a People type) in place of the member-area customer boolean, and the standard-magnet, onboarding, request-form and `409 onboarding_off` mentions key on `who: "user"` — verified against `packages-paid/api-signal-collectors/src/routes/magnets/index.ts`, `packages/api/src/lib/{tenant-db,member-store}.ts`, `packages/api/src/services/tenant-context.ts` and `packages-paid/api-workspace/src/routes/workspaces/messages-out.ts`.
238
+ 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`.
239
+
240
+ Prior: 2026-11-07 — #11096: the `/v1/hub-sign-in/entry` and `/v1/hub-sign-in/google` bullet, their client authentication, buckets, One Tap setting and no-twin footing — verified against `packages-paid/api-hub/src/routes/auth/hub-sign-in.ts` and `packages-paid/api-hub/src/services/hub-sign-in.ts`.
241
+
242
+ Prior: 2026-11-04 — #10819: the magnets bullet names `who` (a People type) in place of the member-area customer boolean, and the standard-magnet, onboarding, request-form and `409 onboarding_off` mentions key on `who: "user"` — verified against `packages-paid/api-signal-collectors/src/routes/magnets/index.ts`, `packages/api/src/lib/{tenant-db,member-store}.ts`, `packages/api/src/services/tenant-context.ts` and `packages-paid/api-workspace/src/routes/workspaces/messages-out.ts`.
238
243
 
239
244
  Prior: 2026-11-01 — #10510: the public content reads bullet names `GET /v1/content/discovery`, and a bullet for `GET`/`PUT /v1/workspaces/:workspaceId/discovery` — verified against `packages/api/src/routes/content/discovery.ts`, `packages/api/src/services/site-discovery.ts` and `packages-paid/api-workspace/src/routes/workspaces/discovery.ts`.
240
245
 
@@ -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 with whether each is offered (`include` adds `customer` and, with the `meeting-types-manage` grant, `private`); the save needs that grant and its required `enabledSlugs` replaces the public list, while an omitted `customerSlugs` or `privateSlugs` keeps the stored list, and no price is set there; the appointments read is every role's 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, 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, 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, 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
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
@@ -314,7 +314,9 @@ Example (lead routing):
314
314
  - Don't add a tool without the matching `apps/api` endpoint.
315
315
  - Don't put business logic in tool handlers — they're adapters.
316
316
 
317
- Last updated: 2026-11-06 — #10952 (D1–D6): `delete_language_item` (`mcp-workspace`'s `language.ts`) twins `DELETE …/language/:kind/:slug`, whose blanket agent refusal becomes the Live switch's `content-publish` gate — the signed-in workspace surface gains one tool — verified against `packages/metadata/src/mcp-tool-catalog.ts`, `packages-paid/mcp-workspace/src/index.ts`, `packages-paid/api-workspace/src/routes/workspaces/language.ts` and `tests/parity/api-parity/kinds/site.ts`.
317
+ Last updated: 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`.
318
+
319
+ Prior: 2026-11-06 — #10952 (D1–D6): `delete_language_item` (`mcp-workspace`'s `language.ts`) twins `DELETE …/language/:kind/:slug`, whose blanket agent refusal becomes the Live switch's `content-publish` gate — the signed-in workspace surface gains one tool — verified against `packages/metadata/src/mcp-tool-catalog.ts`, `packages-paid/mcp-workspace/src/index.ts`, `packages-paid/api-workspace/src/routes/workspaces/language.ts` and `tests/parity/api-parity/kinds/site.ts`.
318
320
 
319
321
  Prior: 2026-11-06 — #10949 (D1, D3, D4): `get_workspace_offerings` (`mcp-workspace`'s `offerings.ts`) twins `GET /v1/workspaces/:workspaceId/offerings`, registered with `multi-tenant` alone; the PUT has no tool — the signed-in workspace surface is fifty-four tools — verified against `packages/metadata/src/mcp-tool-catalog.ts`, `packages-paid/mcp-workspace/src/index.ts`, `packages-paid/api-multi-tenant/src/routes/workspaces/offerings.ts` and `tests/parity/api-parity/kinds/site.ts`.
320
322
 
@@ -225,6 +225,15 @@ CONTENT_ADAPTER=mdx
225
225
  # must never tell a visitor "check your email" for mail nothing can send.
226
226
  # AUTH_EMAIL_WEBHOOK_SECRET=
227
227
  #
228
+ # Phone verification (#11106 D9). With AUTH_EMAIL_WEBHOOK_SECRET and
229
+ # BETTER_AUTH_URL set (and never on a spoke), the Account page lets a signed-in
230
+ # person with a verified email set and verify a phone: the code is signed with
231
+ # the secret above and texted by apps/api's /v1/auth/transactional-sms
232
+ # (TWILIO_* live on the apps/api deployment). Phone is never a sign-in method.
233
+ # The calling codes a code may be texted to, comma-separated, default "1" —
234
+ # set the same value on apps/api, whose relay re-checks it.
235
+ # AILK_SMS_COUNTRY_CODES=1
236
+ #
228
237
  # Comma-separated CIDRs of YOUR edge/proxy, for Better Auth's rate-limit IP key.
229
238
  #
230
239
  # Unset is the honest default — this repo cannot know your deployment's edge
@@ -272,6 +281,13 @@ CONTENT_ADAPTER=mdx
272
281
  # The redirect URI is built from this site's NEXT_PUBLIC_BASE_URL (else the
273
282
  # baseUrl in content/_site.mdx) — never from a request's Host — so set it to
274
283
  # the origin you registered on the hub.
284
+ #
285
+ # Google One Tap for a returning Google person (#11096 D10), off by default.
286
+ # "on" renders Google's prompt on the signed-out /account and widens this
287
+ # site's CSP to Google's One Tap origins. It works only once the hub sets
288
+ # AILK_GOOGLE_ONE_TAP_CLIENT_ID and this origin is listed on that Google
289
+ # client's authorized JavaScript origins. Anything else, or unset, is off.
290
+ # AILK_HUB_ONE_TAP=on
275
291
 
276
292
  # =============================================================================
277
293
  # Observability
@@ -161,8 +161,47 @@ to the same route, which accepts only `Sec-Fetch-Site: same-origin` with the
161
161
  pinned `Origin` (a missing or `null` one is refused) and is the one call site
162
162
  that sends `consent: true` — beside `x-internal-auth` under the Offerings buy
163
163
  route's rule, since the API honours consent only with it where
164
- `OSS_API_INTERNAL_SECRET` is set. A password reset or a sign-out revokes the
165
- grant, so the next sign-in asks again. `ref` is in both telemetry scrub lists.
164
+ `OSS_API_INTERNAL_SECRET` is set. Its navigating page is built only for an
165
+ `https:` or loopback `http:` callback; any other scheme answers 503 (#11095
166
+ D10). A client whose row is `trusted` (every client the operator CLI registers)
167
+ never sees the page: its code mints with no consent read (#11095 D1). A
168
+ password reset revokes the grant, so the next sign-in of an untrusted client
169
+ asks again; a spoke sign-out ends only the credential (#11095 D2). `ref` is in
170
+ both telemetry scrub lists.
171
+
172
+ **A spoke's sign-in entry is the spoke's own form (#11096).** On a spoke
173
+ that signs in through its hub, the gate seam renders
174
+ `lib/hub-session/spoke-sign-in.tsx` (`SpokeSignIn`) for every signed-out
175
+ `(authed)` path: one email field, the hub's sign-up agreements under "New
176
+ here?" (read from the hub web's `GET /api/auth/hub/sign-up`, shared 60 s, each
177
+ policy link the hub's) and Continue with Google — a native form, no password
178
+ field and no link to a hub sign-in page. It reads its state from
179
+ `x-search`, which `middleware.ts` sets from the request's own query
180
+ (`?sent=1`, `?error=agreements | unavailable | exists | claim`, `?claim=`).
181
+ The email POSTs to `/api/hub-session/email`, which starts a flow
182
+ (`startHubFlow`) and asks the hub web's `POST /api/auth/hub/email` server to
183
+ server, as the spoke's client (Basic + spoke key); the hub API's
184
+ `/v1/hub-sign-in/entry` checks the client before Better Auth mails its magic
185
+ link, whose use returns through redirects only. Ticked agreements make it a
186
+ sign-up request (#9667's shape); none ticked is a sign-in. Google goes to the
187
+ spoke's sign-in route with `provider=google`, which rides as `provider_hint`
188
+ and sends a visitor with no hub session straight to Google from the
189
+ authorize step. **The purchase link:** after a paid Offerings session the hub
190
+ mails "Open your account" to `<spoke>/account?claim=<claim>`; that page's GET
191
+ changes nothing, and its one "Open my account" button POSTs the claim to
192
+ `/api/hub-session/open`, which spends it at the hub web's
193
+ `POST /api/auth/hub/purchase` and 303s to the hub's verify URL (`409` →
194
+ `?error=exists`, anything else → `?error=claim`). `/account/billing` lists the
195
+ member's purchases (`member.purchases`, the verified-email join) on such a
196
+ spoke only. **One Tap** (off by default): `AILK_HUB_ONE_TAP=on` on the spoke
197
+ and `AILK_GOOGLE_ONE_TAP_CLIENT_ID` on the hub API render the `OneTap`
198
+ island, which takes a nonce from `/api/hub-session/one-tap/nonce` (a 300 s
199
+ sealed cookie) and posts Google's credential to `/api/hub-session/one-tap`;
200
+ the hub verifies it and the route seals the session (`sessionCookieFor`) before
201
+ the page moves. `middleware.ts` adds Google's One Tap origins
202
+ (`ONE_TAP_CSP`) to every page's CSP only while that setting is on. Every new
203
+ spoke route is same-origin only, and every body is `.strict()`: a password is
204
+ never accepted. `claim` is in both telemetry scrub lists.
166
205
 
167
206
  ## The MCP authorization server
168
207
 
@@ -598,7 +637,7 @@ A site serves its docs at `/docs` unless `content/_site.mdx` sets a top-level `d
598
637
 
599
638
  - **Build.** `next.config.mjs` reads `docsPath`, bakes it into `NEXT_PUBLIC_AILK_DOCS_PATH`, and fails the build naming the value when it breaks the pattern, starts with `api`, `og`, `v1` or an enabled locale, sits under `/docs`, shadows a `ROUTES` page (a `:param` segment matches any segment, so `/products/docs` is refused) or sits under a catch-all (`/blog/...`), or when this site's `lib/source.ts` does not set `baseUrl: DOCS_PATH` — a site with no docs-blog module, or one whose docs-blog files predate the setting. Links inside a doc's body are re-pointed only on a site that sets `docsPath`; there they render through `Link`, which forwards a fixed prop set, so a body anchor's `title` / `target` / `rel` are not kept.
600
639
  - **Request.** `middleware.ts` hands next-intl the internal `/docs/...` path for a request at or under `docsPath` (bare or locale-prefixed), so the browser keeps the public URL, and maps a redirect's `Location` and each hreflang `Link` entry back onto it. `/docs` and `/docs/...` answer with the site's 404 — rewritten to `/_ailk-docs-unmounted`, whose first segment is no locale, so the locale layout calls `notFound()`.
601
- - **Surfaces.** The docs sidebar, index and search index (both sources' `baseUrl`), the doc's breadcrumb, links inside a doc's body, every nav and footer entry at `/docs` (mapped at render in the locale layout and `components/signed-in-nav.tsx`; `nav-config.ts` is never edited), and the docs entries in `/sitemap.xml` and `/llms.txt` (`lib/docs-index.ts`, default locale only) all follow it. A site with no `docsPath` serves every URL exactly as before.
640
+ - **Surfaces.** The docs sidebar, index and search index (both sources' `baseUrl`), the doc's breadcrumb, links inside a doc's body, every nav and footer entry at `/docs` (mapped at render in the locale layout; `nav-config.ts` is never edited), and the docs entries in `/sitemap.xml` and `/llms.txt` (`lib/docs-index.ts`, default locale only) all follow it. A site with no `docsPath` serves every URL exactly as before.
602
641
  - **Existing docs sites.** `create-ailk update` carries the base readers but never refreshes a module bundle's files, so a docs-blog site installed before this release keeps a `lib/source.ts` without `DOCS_PATH` and its build refuses a `docsPath` until those files are re-installed — a standing gap no command fills yet (#10076).
603
642
  - **Rollout.** A `@working-theory/site-config` older than this setting rejects a `_site.mdx` carrying `docsPath` (its schema is strict), and `@working-theory/api` / `@working-theory/mcp-server` then read the site as having no config. Set `docsPath` only once the site's packages carry it.
604
643
 
@@ -609,7 +648,7 @@ A site serves its services at `/services` unless `content/_site.mdx` sets `servi
609
648
  - **Categories.** A category is itself a `Service` page. A service names its category with frontmatter `parent: <category-slug>` and is served at `/<base>/<category>/<slug>` (`services/[slug]/[child]/page.tsx`); its flat URL answers a permanent redirect there, and the nested URL answers 404 unless the `parent` names that category and the category has no `parent` of its own. A category page lists its services after its body (`lib/service-listing.ts`, the `services` messages' `childrenHeading` / `viewService`). One level only.
610
649
  - **Build.** `next.config.mjs` reads `services.path`, bakes it into `NEXT_PUBLIC_AILK_SERVICES_PATH`, and fails the build naming the value when it breaks the pattern, starts with an enabled locale, shadows a `ROUTES` page, sits under a catch-all, or overlaps `docsPath` either way. It also fails, naming the file, on a default-locale `Service` whose `parent` names no Service or a Service with its own `parent`, and on any `parent` when the nested route is missing (`create-ailk sync-routes` adds it).
611
650
  - **Request.** `middleware.ts` hands next-intl the internal `/services/...` path for a request at or under the base, keeps `x-pathname` public, and maps a redirect's `Location` and each hreflang `Link` entry back. `/services` and `/services/...` answer `308` onto the same rest under the base (query and locale prefix kept), so old links keep working; links inside content are not rewritten.
612
- - **Surfaces.** The canonical, hreflang and `BreadcrumbList` (the base's title-cased last segment, then the category's title), `/sitemap.xml` and `/llms.txt` (`pagePathFor`), every nav and footer entry at `/services` (mapped in the locale layout and `components/signed-in-nav.tsx`), the hub's own section links, and route-family chrome (`lib/page-chrome.ts`) all follow it. A site that sets neither `services.path` nor any `parent` serves every URL exactly as before.
651
+ - **Surfaces.** The canonical, hreflang and `BreadcrumbList` (the base's title-cased last segment, then the category's title), `/sitemap.xml` and `/llms.txt` (`pagePathFor`), every nav and footer entry at `/services` (mapped in the locale layout), the hub's own section links, and route-family chrome (`lib/page-chrome.ts`) all follow it. A site that sets neither `services.path` nor any `parent` serves every URL exactly as before.
613
652
  - **Moving it.** `/ailk:growth-ops page rename` moves the base (`--from <current base> --to <new base>`): it writes `services.path` and keeps a previous moved base redirecting.
614
653
 
615
654
  ## Nav-only lists (`navOnly`)
@@ -645,7 +684,9 @@ A list page whose frontmatter sets `navOnly: true` (valid on a registry list typ
645
684
  - Don't reach into `apps/api` or `apps/mcp` from `apps/web`. They're peer apps — talk via HTTP/MCP.
646
685
  - Don't commit images to `screenshots/` — only the `.gitkeep` is tracked.
647
686
 
648
- Last updated: 2026-11-05 — § The MCP authorization server: one issuer per token — the plugin's optional `issuerTag` and `signInLocation`, the refusal of another issuer's token, refresh and code, and the Admin's byte-identical copy (#10912) — verified against `lib/mcp-oauth.ts` and `auth.ts`.
687
+ Last updated: 2026-11-07 — § The `(auth)` route group: a spoke's sign-in entry is the spoke's own form — the email route, Google's `provider_hint`, the purchase link's "Open my account", the billing Purchases list and One Tap with its CSP (#11096) — verified against `lib/hub-session/{spoke-sign-in.tsx,entry.ts,one-tap.tsx,session.ts}`, `app/api/hub-session/{email,open,one-tap}/` and `middleware.ts`.
688
+
689
+ Prior: 2026-11-05 — § The MCP authorization server: one issuer per token — the plugin's optional `issuerTag` and `signInLocation`, the refusal of another issuer's token, refresh and code, and the Admin's byte-identical copy (#10912) — verified against `lib/mcp-oauth.ts` and `auth.ts`.
649
690
 
650
691
  Prior: 2026-11-02 — § Theme & styling: `consent.appearance` named beside the other `_site.mdx` chrome keys, and the minimal deck home's hold-back is the band's alone, so a minimal site that picks the card sees it on load there too (#10721) — verified against `app/[locale]/layout.tsx`.
651
692
 
@@ -29,6 +29,8 @@ jest.mock("../../../../lib/auth-env", () => ({
29
29
  isSignUpOpen: () => mockIsSignUpOpen(),
30
30
  isResetAvailable: () => mockIsResetAvailable(),
31
31
  resetSendConfigured: () => mockResetSendConfigured(),
32
+ // #11106 D9 — auth.ts asks whether to install the phone plugin.
33
+ phoneVerificationConfigured: () => false,
32
34
  }));
33
35
 
34
36
  const mockRequestPasswordReset = jest.fn();
@@ -78,6 +78,15 @@ jest.mock("../../../../../auth", () => ({
78
78
  __esModule: true,
79
79
  resolveSecret: () => TEST_SECRET,
80
80
  }));
81
+ // #11095 D7 — the remembered-method cookie, read through `cookies()`.
82
+ const mockCookies: Record<string, string> = {};
83
+ jest.mock("next/headers", () => ({
84
+ __esModule: true,
85
+ cookies: async () => ({
86
+ get: (name: string) =>
87
+ name in mockCookies ? { name, value: mockCookies[name] } : undefined,
88
+ }),
89
+ }));
81
90
  const mockClientInfo = jest.fn();
82
91
  jest.mock("@working-theory/api-client", () => ({
83
92
  __esModule: true,
@@ -123,6 +132,7 @@ async function renderPage(next?: string, error?: string): Promise<void> {
123
132
  }
124
133
 
125
134
  beforeEach(() => {
135
+ for (const name of Object.keys(mockCookies)) delete mockCookies[name];
126
136
  mockGetActiveProviderIds.mockReset().mockReturnValue(["google"]);
127
137
  mockIsResetAvailable.mockReset().mockReturnValue(false);
128
138
  mockSocial.mockReset().mockResolvedValue({ data: {}, error: null });
@@ -365,7 +375,8 @@ describe("/sign-in page — the spoke back link (#8790 D2)", () => {
365
375
  await renderPage(`/api/auth/hub/continue/${ref}`);
366
376
  expect(mockClientInfo).toHaveBeenCalledWith("spoke_1");
367
377
  const back = screen.getByTestId("auth-back-link");
368
- expect(back).toHaveAttribute("href", "https://wendihenry.com/account");
378
+ // #11095 D5: the spoke's home — its /account would start the hub hop again.
379
+ expect(back).toHaveAttribute("href", "https://wendihenry.com/");
369
380
  // This suite's next-intl shim returns messages uninterpolated, so the
370
381
  // label's shape is what is asserted here; the ICU fill is next-intl's.
371
382
  expect(back).toHaveTextContent(/^Back to/);
@@ -575,3 +586,43 @@ describe("/sign-in page — the Sign up toggle keeps the next (#9912 D4)", () =>
575
586
  );
576
587
  });
577
588
  });
589
+
590
+ // #11095 AC-6 (D7): a returning person's card leads with the provider they
591
+ // last launched; a value that does not parse changes nothing.
592
+ describe("/sign-in page — the remembered method (#11095 D7)", () => {
593
+ it("with ailk-sign-in-method=google: Continue with Google first, no email field, and Use another way restores the card", async () => {
594
+ const user = userEvent.setup();
595
+ mockGetActiveProviderIds.mockReturnValue(["google", "magic-link"]);
596
+ mockCookies["ailk-sign-in-method"] = "google";
597
+ await renderPage();
598
+ const lead = screen.getByTestId("auth-sso-google");
599
+ expect(lead).toHaveTextContent(`${en.signIn.continueWith} ${en.signIn.google}`);
600
+ expect(screen.getAllByRole("button")[0]).toBe(lead);
601
+ expect(screen.queryByTestId("auth-email")).toBeNull();
602
+ const another = screen.getByTestId("sign-in-use-another-way");
603
+ expect(another).toHaveTextContent(en.signIn.useAnotherWay);
604
+
605
+ await user.click(another);
606
+ expect(screen.getByTestId("auth-email")).toBeInTheDocument();
607
+ expect(screen.getByTestId("auth-social-google")).toBeInTheDocument();
608
+ });
609
+
610
+ it.each([
611
+ ["evil", ["google", "magic-link"]],
612
+ ["github", ["google", "magic-link"]],
613
+ ["", ["google", "magic-link"]],
614
+ ])(
615
+ "a cookie of %j (not an active provider) renders exactly the no-cookie card",
616
+ async (value, active) => {
617
+ mockGetActiveProviderIds.mockReturnValue(active);
618
+ await renderPage();
619
+ const today = document.body.innerHTML;
620
+ document.body.innerHTML = "";
621
+
622
+ mockCookies["ailk-sign-in-method"] = value;
623
+ await renderPage();
624
+ expect(document.body.innerHTML).toBe(today);
625
+ expect(screen.queryByTestId("sign-in-use-another-way")).toBeNull();
626
+ },
627
+ );
628
+ });
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The remembered-method cookie (#11095 D7, AC-6): it names one provider id
3
+ * and nothing else, and only an id the page offers parses.
4
+ */
5
+ import {
6
+ REMEMBERED_METHOD_COOKIE,
7
+ parseRememberedMethod,
8
+ rememberMethod,
9
+ } from "../remembered-method";
10
+
11
+ afterEach(() => {
12
+ document.cookie = `${REMEMBERED_METHOD_COOKIE}=; Max-Age=0; Path=/`;
13
+ });
14
+
15
+ describe("parseRememberedMethod", () => {
16
+ it("answers an active google or github", () => {
17
+ expect(parseRememberedMethod("google", ["google", "github"])).toBe(
18
+ "google",
19
+ );
20
+ expect(parseRememberedMethod("github", ["github"])).toBe("github");
21
+ });
22
+
23
+ it.each([
24
+ [undefined, ["google"]],
25
+ ["", ["google"]],
26
+ ["evil", ["google"]],
27
+ ["github", ["google"]],
28
+ ["Google", ["google"]],
29
+ ["google ", ["google"]],
30
+ ] as const)("refuses %j with providers %j", (raw, providers) => {
31
+ expect(parseRememberedMethod(raw, [...providers])).toBeUndefined();
32
+ });
33
+ });
34
+
35
+ describe("rememberMethod", () => {
36
+ it("writes the provider id alone, and null clears it", () => {
37
+ expect(REMEMBERED_METHOD_COOKIE).toBe("ailk-sign-in-method");
38
+ rememberMethod("google");
39
+ expect(document.cookie).toBe("ailk-sign-in-method=google");
40
+ rememberMethod(null);
41
+ expect(document.cookie).toBe("");
42
+ });
43
+ });