create-ailk 0.46.5 → 0.46.6

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.
@@ -11580,8 +11580,95 @@
11580
11580
  ]
11581
11581
  }
11582
11582
  },
11583
+ "grid": {
11584
+ "oneOf": [
11585
+ {
11586
+ "type": "object",
11587
+ "properties": {
11588
+ "kind": {
11589
+ "type": "string",
11590
+ "const": "capabilities"
11591
+ },
11592
+ "products": {
11593
+ "minItems": 1,
11594
+ "maxItems": 3,
11595
+ "type": "array",
11596
+ "items": {
11597
+ "type": "string",
11598
+ "pattern": "^[a-z0-9][a-z0-9-]{0,39}$"
11599
+ }
11600
+ },
11601
+ "levels": {
11602
+ "minItems": 1,
11603
+ "maxItems": 12,
11604
+ "type": "array",
11605
+ "items": {
11606
+ "type": "string",
11607
+ "pattern": "^[a-z0-9][a-z0-9-]{0,39}$"
11608
+ }
11609
+ },
11610
+ "show": {
11611
+ "type": "string",
11612
+ "enum": [
11613
+ "capabilities",
11614
+ "features"
11615
+ ]
11616
+ }
11617
+ },
11618
+ "required": [
11619
+ "kind",
11620
+ "products",
11621
+ "show"
11622
+ ],
11623
+ "additionalProperties": false
11624
+ },
11625
+ {
11626
+ "type": "object",
11627
+ "properties": {
11628
+ "kind": {
11629
+ "type": "string",
11630
+ "const": "alternatives"
11631
+ },
11632
+ "category": {
11633
+ "type": "string",
11634
+ "pattern": "^[a-z0-9](?:[a-z0-9-]{0,118}[a-z0-9])?$"
11635
+ },
11636
+ "ours": {
11637
+ "type": "string",
11638
+ "pattern": "^[a-z0-9][a-z0-9-]{0,39}$"
11639
+ },
11640
+ "columns": {
11641
+ "minItems": 1,
11642
+ "maxItems": 12,
11643
+ "type": "array",
11644
+ "items": {
11645
+ "type": "string",
11646
+ "pattern": "^[a-z0-9](?:[a-z0-9-]{0,118}[a-z0-9])?$"
11647
+ }
11648
+ },
11649
+ "show": {
11650
+ "type": "string",
11651
+ "enum": [
11652
+ "capabilities",
11653
+ "features"
11654
+ ]
11655
+ },
11656
+ "source": {
11657
+ "type": "boolean",
11658
+ "const": true
11659
+ }
11660
+ },
11661
+ "required": [
11662
+ "kind",
11663
+ "category",
11664
+ "show"
11665
+ ],
11666
+ "additionalProperties": false
11667
+ }
11668
+ ]
11669
+ },
11583
11670
  "columns": {
11584
- "minItems": 1,
11671
+ "default": [],
11585
11672
  "type": "array",
11586
11673
  "items": {
11587
11674
  "type": "object",
@@ -11606,7 +11693,7 @@
11606
11693
  }
11607
11694
  },
11608
11695
  "groups": {
11609
- "minItems": 1,
11696
+ "default": [],
11610
11697
  "type": "array",
11611
11698
  "items": {
11612
11699
  "type": "object",
@@ -11842,11 +11929,7 @@
11842
11929
  "ink"
11843
11930
  ]
11844
11931
  }
11845
- },
11846
- "required": [
11847
- "columns",
11848
- "groups"
11849
- ]
11932
+ }
11850
11933
  },
11851
11934
  "schemaError": null,
11852
11935
  "look": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-ailk",
3
- "version": "0.46.5",
3
+ "version": "0.46.6",
4
4
  "description": "Scaffolder for AI Launch Kit — `pnpm create ailk@latest <dir>` produces a starter repo consuming @working-theory/* from npm (per ADR 0007).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -28,8 +28,8 @@
28
28
  "tar": "^7.5.21"
29
29
  },
30
30
  "devDependencies": {
31
- "@working-theory/schema": "0.79.0",
32
- "@working-theory/templates": "0.79.0"
31
+ "@working-theory/schema": "0.80.0",
32
+ "@working-theory/templates": "0.80.0"
33
33
  },
34
34
  "repository": {
35
35
  "type": "git",
@@ -111,7 +111,7 @@ Routes are versioned under `/v1/*`:
111
111
  - `/v1/workspaces/:workspaceId/kinds` (GET) — the kinds read (#11805; the same file and scope), any tenant of the workspace, no query, no row read. It answers `listKinds(request.tenant, isModuleEnabled)` from `@working-theory/metadata`: `{ kinds: [{ kind, address, fields, moreFields, sectionTypes, states, moves }] }`, one entry per kind of `ADMIN_KIND_REGISTRY` (`@working-theory/validation`) — page, document, language_item, magnet, asset — whose address, fields and states are read off that kind's own schemas, and whose `moves` are the catalog rows tagged with the kind, kept only when the row's gate holds for the CLAMPED tenant the guard built (never an agent's stored grants or a token's raw scopes) and one of its modules runs on this hub; a page's `sectionTypes` names `list_section_types` rather than repeating it. Beside `kinds` (#11878) it answers `forms` (`[{ kind, field, values }]` — each kind's form field and its values, read off that field's own schema through `KIND_FORMS`, then an offering's `ailkGroup` and an appointment with no form), `offSiteForms` (`[{ form, formats }]`), `formats` and `origins`, all from `adminKinds()` and the same for every caller and hub. Advice, never an entitlement: no write path may gate on it. MCP parity: `list_kinds` on `/mcp/workspace`.
112
112
  - `/v1/workspaces/:workspaceId/assets` (GET, POST), `/v1/workspaces/:workspaceId/assets/:assetId` (PATCH, DELETE), `/v1/assets/:assetId` (GET, public/anonymous) — the workspace asset store (#5854 upload/read; #6093 list/PATCH/DELETE, `src/routes/assets/{index,upload,read,manage}.ts`). Upload accepts an allowlisted union of three named classes (`src/routes/assets/index.ts`): five RASTER images (`image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`), one VECTOR image (`image/svg+xml`, admitted under the operator's 2026-09-18 `allow-svg-assets` ruling — issue #6093 comment `5731573595` — superseding #5854's original SVG exclusion) and one DOCUMENT type (`application/pdf`), all under the existing 20 MB cap; `?tags=<slug>[,<slug>…]` stores tags on the row. The public read serves a RASTER type `inline` exactly as before; every OTHER admitted type (SVG, PDF) is served `attachment`, with the filename's extension pinned to the stored content type (closing extension spoofing) and a five-directive `Content-Security-Policy` (`default-src 'none'; sandbox; frame-ancestors 'none'; form-action 'none'; base-uri 'none'`) that makes the bytes never a document on this origin — this is what makes admitting SVG safe with NO server-side sanitizer. `GET …/assets` (`assets-read` — every role, a member included) lists a workspace's assets, metadata only, never `bytes`, with an optional `?tag=<slug>` filter; this is what narrows the store's prior "nothing lists assets" premise to its precise form — no ANONYMOUS and no CROSS-TENANT enumeration, both still true. `PATCH …/assets/:assetId` updates `title`/`description`/`tags` (`assets-write`, owner and admin, the upload's permission too; `null` clears a text field to SQL `NULL`, `""` stores empty; the asset's `id` and public URL are untouched). `DELETE …/assets/:assetId` (`assets-write`) removes the row and the bytes at the ORIGIN only — already-cached copies elsewhere are not recallable under the year-long `immutable` promise, and no reference check protects a page that still embeds the URL; absent and foreign ids both take the same 404. Every tenant route here is identity-bound; no MCP twin (#3591 exception). The public read has no MCP twin either — it serves bytes to an `<img>`/download, the same boundary `upload.ts` records for its own sibling. **A client's file is never in the library's public life (#7877 D18):** the default `GET …/assets` listing leaves out every asset tagged `private` — only `?tag=private` lists them (the Admin's Compose) — and the public read answers its uniform 404 for an asset tagged `private`, attached to any member-area message, or (#8171 D3) named by a delivered piece version (one `pieceVersion.count`, since the tag can be removed after delivery), so such a file's bytes are served only by its owner's member reads.
113
113
  - `/v1/subscription/me` (GET) — `?include=billing` (#8171 D7), from a cookie session only, adds the optional `planName` and `paymentMethod` (brand, last four, expiry) read from Stripe through `lib/stripe.ts`'s `readCustomerBillingSummary` for the caller's own resolved customer: cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure leaves both keys absent, a value outside the schema's bounds is `null`, and no id is served or logged. A bearer token, another value or none answers exactly as before.
114
- - `/v1/billing` (GET), `/v1/billing/portal-session` (POST) — org-scoped billing read + Stripe customer-portal session creation. The read stays open to every member (the Admin's plan gate reads it); the portal needs `billing-manage` — the owner alone (`@working-theory/validation`'s permission table (#7636 D2); an admin is refused before any Stripe call). `/v1/billing/usage` (GET) needs `billing-read` (owner, admin). **The read's `commerce` field (#8907 D14)** is the deployment's commerce claim, `claimed | unclaimed | undetermined` (`resolveCommerceClaim()`; a rejected read is `undetermined` and the answer stays `200`) — what the Admin's Billing card reads (#8908 D10). **`?include=billing` (#9067 D1)** — exactly that string, never an array — adds `details` only for a caller holding `billing-manage` (the owner; an agent never qualifies): `licenseExpiresAt` (`checkLicense().expiresAt`, `null` on a failed read) always, and for an Organization with a Stripe customer `renewsAt` (the current subscription's first item's `current_period_end`, only while it will renew), `sites` (its quantity) and `paymentMethod` (brand, last four, expiry), read through `lib/stripe.ts`'s `readCustomerBillingSummary` by `services/entitlements.ts`'s `readOrgBillingSummary` — cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure answers `details: { licenseExpiresAt }` and still `200`, a value outside `orgBillingDetailsSchema`'s bounds is `null`, no id is served or logged, and the reply carries `Cache-Control: private, no-store`. **The same gate adds `plugins` (#12009 D2, `routes/billing/plugin-billing.ts`):** the Organization's workspaces (`{ id, name }`, `readOrgWorkspaces`) and one row per plugin in `PLUGIN_IDS` order — `has` (the workspaces `workspaceHasPlugin` answers yes for), `billingReasons` (the union of their reasons, in `PLUGIN_REASONS` order; Billing is the reason's one reader, guarded by `plugin-entitlement-confinement.test.ts`), `bought` (the workspaces on the Organization's active `PluginPurchase` rows, by interval — what their subscriptions bill), `prices` (integer US cents from `services/entitlements.ts`'s `readPluginCatalogue`, the entitlements service's catalogue read on #12001's call, cached 60 s; `null` for growth-ops, an unsold plugin, a placeholder or non-`usd` price, or an unread catalogue — never a fallback) and `forSale` (a shown price, a Stripe customer, the commerce claim `claimed` and a registered grant writer — `services/plugin-purchases.ts`'s `pluginGrantWriter()`, which only the hub's licensing module registers, so a hub without it sells nothing). A failed plugin read leaves the key out and logs `plugins_unavailable`; the rest of the answer stands. Every other request is answered exactly as before, with no Stripe or licence read. **`POST /v1/billing/plan-checkout` (#9067 D3, `routes/billing/plan-checkout.ts`)** is the Billing tab's Purchase plan: a subscription Checkout for the caller's own Organization's plan (`planPurchaseLookupKey` — `ailk-pro_monthly` / `ailk-pro-plus_monthly`, `PLAN_PURCHASE_LOOKUP_KEYS` built by the Offerings lookup-key grammar, #9338 DD1), on the admitted key like the portal (#8463). **It sells only an Offerings plan (#9338 DD4):** `createCheckoutSession` gets a `refuseProduct` that refuses every Product whose `metadata.ailk_group` is not exactly `plan` (`isOfferingsPlanProduct`, `services/offerings/catalog.ts`), checked on the same expanded Price it sells; a refused or unexpanded Product answers `500 plan_price_missing`. Check order: tenant → `billing-manage` (403 before any lookup) → write budget (`chargeWriteBudget` scope `plancheckout`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{ returnUrl }` (`bodyLimit` 4 KiB, `400 validation_failed`) → the return URL (canonical, no userinfo, query, fragment or `//` path, `https:` or a local `http:`, on `config.TRUSTED_ORIGINS`; `400 return_url_refused`, `500 config-error` when none is trusted) → no customer yet (`409 billing_customer_exists`) and a purchasable tier (`409 plan_not_purchasable`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` → one payable session (an open earlier one is expired first, a completed one is `409 purchase_pending`) → `createCheckoutSession` with `mode: "subscription"`, 1–50 sites, `metadata` and `subscriptionMetadata` `{ organizationId, ...siteStamp() }` and `PLATFORM_TERMS_OF_SERVICE`, never a `buyer` → a Checkout URL only → the session id recorded on `Organization.planCheckoutSessionId` by compare-and-set (a lost race or a failed write expires the new session). It answers `{ url }` with `Cache-Control: private, no-store`; no body or log line carries the return URL, an id or a Stripe message. **The webhook's Organization arm binds only that recorded session (#9067 D13):** a `checkout.session.completed` with `metadata.organizationId` links `session.customer` through one guarded `updateMany` on `{ id, planCheckoutSessionId: session.id, billingCustomerId: null }` (clearing the session); anything else — an unrecorded session, a bound customer, every `customer.created` — writes nothing and logs `org_bind_unproven`. No MCP twin for the purchase — owner-only, recorded in `tests/parity/README.md`. **`POST /v1/billing/plugin-checkout` (#12009 D5, `routes/billing/plugin-checkout.ts`)** is the Billing tab's "+ Add" on a plugin row: a subscription Checkout for one plugin at one interval (`year` or `month`), one unit per chosen workspace, on the Organization's own bound customer. Check order: tenant → `billing-manage` (403 before any read) → write budget (scope `plugincheckout`, 10 an hour per Organization and per person) → the commerce claim → a strict `{ plugin, interval, workspaceIds (1–50, distinct), returnUrl }` → plan-checkout's own return-URL rule (`isAcceptableReturnUrl`) → a registered grant writer (`409 purchase_unavailable`) → a bound customer (`409 billing_customer_missing` — no plugin before the plan) → the catalogue (`503 catalogue_unavailable` on an unread one; `409 plugin_not_for_sale` for growth-ops, an unsold plugin or a placeholder price) → the workspaces (each a `wksp_` id of the caller's own Organization, else `400 workspace_refused`; a failed entitlement read for any of them, `503 entitlement_unavailable` — `workspaceHasPluginForSale`, which fails closed where `workspaceHasPlugin` answers no; one it answers yes for, or an active purchase of the plugin names, `409 plugin_already_added`) → the admitted Stripe key → one open Checkout per workspace, from one read of the plugin's `created` and `active` purchases (one confirmed since the step before, `active`, naming a chosen workspace answers `409 plugin_already_added`; an earlier `created` one is expired and ended; a completed one answers `409 purchase_pending`) → `createCheckoutSession` at the catalogue's lookup key with `quantity` equal to the workspace count, no `adjustableQuantity`, `metadata` and `subscriptionMetadata` `{ organizationId, ailk_plugin, ...siteStamp() }`, and a `refusePrice` that refuses any Price whose `unit_amount`, currency or interval is not the catalogue's, or that is not billed per unit, once per interval, with no quantity transform (`500 plugin_price_mismatch`) → a Checkout URL only → the session recorded as a `PluginPurchase` with the Price id `refusePrice` accepted (`state: created`; no accepted Price, or a failed write, expires the session and answers 502) → no rival recorded or confirmed meanwhile for a chosen workspace (else the new session is expired and ended: `409 purchase_pending` for a `created` rival, `409 plugin_already_added` for an `active` one; a recheck that cannot be read does the same and answers 502). **The webhook's plugin path (#12009 D9, `services/plugin-purchases.ts` `fulfilPluginEvent`)** runs once after the site filter and before the `switch`, and only on a hub with billing's grant writer: for a `checkout.session.completed`, `customer.subscription.*`, `invoice.paid` or `invoice.payment_failed` whose object carries the `ailk_plugin` stamp (`PLUGIN_SUBSCRIPTION_METADATA_KEY` — a filter only, never a grant) it traces the event's subscription to a recorded purchase (bound, or by `checkout.sessions.list` and a once-only bind), re-reads the subscription from Stripe, stores `state` and `exp` (the item's `current_period_end` while `active` or `trialing` and still paying for the record — quantity at least the recorded workspaces, the recorded Price and interval, collection not paused — else now; `ended_at` or now, `state: ended`, when `canceled` or `incomplete_expired`; nothing while `incomplete`; now otherwise — no grace), and writes one `add_on` grant per workspace with the latest `exp` among the purchases covering it and that purchase's subscription. It never throws, an untraced subscription grants nothing, and no grant is written without an `exp`. When a read or a grant write fails (Stripe, the database or entitlements down) it answers `"retry"`: the webhook un-marks the event (`unmarkSeen`) and answers `503`, before any arm of the `switch` runs, so Stripe redelivers it and the idempotent path re-derives every grant.
114
+ - `/v1/billing` (GET), `/v1/billing/portal-session` (POST) — org-scoped billing read + Stripe customer-portal session creation. The read stays open to every member (the Admin's plan gate reads it); the portal needs `billing-manage` — the owner alone (`@working-theory/validation`'s permission table (#7636 D2); an admin is refused before any Stripe call). `/v1/billing/usage` (GET) needs `billing-read` (owner, admin). **The read's `commerce` field (#8907 D14)** is the deployment's commerce claim, `claimed | unclaimed | undetermined` (`resolveCommerceClaim()`; a rejected read is `undetermined` and the answer stays `200`) — what the Admin's Billing card reads (#8908 D10). **`?include=billing` (#9067 D1)** — exactly that string, never an array — adds `details` only for a caller holding `billing-manage` (the owner; an agent never qualifies): `licenseExpiresAt` (`checkLicense().expiresAt`, `null` on a failed read) always, and for an Organization with a Stripe customer `renewsAt` (the current subscription's first item's `current_period_end`, only while it will renew), `sites` (its quantity) and `paymentMethod` (brand, last four, expiry), read through `lib/stripe.ts`'s `readCustomerBillingSummary` by `services/entitlements.ts`'s `readOrgBillingSummary` — cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure answers `details: { licenseExpiresAt }` and still `200`, a value outside `orgBillingDetailsSchema`'s bounds is `null`, no id is served or logged, and the reply carries `Cache-Control: private, no-store`. **The same gate adds `plugins` (#12009 D2, `routes/billing/plugin-billing.ts`):** the Organization's workspaces (`{ id, name }`, `readOrgWorkspaces`) and one row per plugin in `PLUGIN_IDS` order — `has` (the workspaces `workspaceHasPlugin` answers yes for), `billingReasons` (the union of their reasons, in `PLUGIN_REASONS` order; Billing is the reason's one reader, guarded by `plugin-entitlement-confinement.test.ts`), `bought` (the workspaces on the Organization's active `PluginPurchase` rows, by interval — what their subscriptions bill), `prices` (integer US cents from `services/entitlements.ts`'s `readPluginCatalogue`, the entitlements service's catalogue read on #12001's call, cached 60 s; `null` for growth-ops, an unsold plugin, a placeholder or non-`usd` price, or an unread catalogue — never a fallback) and `forSale` (a shown price, a Stripe customer, the commerce claim `claimed` and a registered grant writer — `services/plugin-purchases.ts`'s `pluginGrantWriter()`, which only the hub's licensing module registers, so a hub without it sells nothing). A failed plugin read leaves the key out and logs `plugins_unavailable`; the rest of the answer stands. Every other request is answered exactly as before, with no Stripe or licence read. **`POST /v1/billing/plan-checkout` (#9067 D3, `routes/billing/plan-checkout.ts`)** is the Billing tab's Purchase plan: a subscription Checkout for the caller's own Organization's plan (`planPurchaseLookupKey` — `ailk-pro_monthly` / `ailk-pro-plus_monthly`, `PLAN_PURCHASE_LOOKUP_KEYS` built by the Offerings lookup-key grammar, #9338 DD1), on the admitted key like the portal (#8463). **It sells only an Offerings plan (#9338 DD4):** `createCheckoutSession` gets a `refuseProduct` that refuses every Product whose `metadata.ailk_group` is not exactly `plan` (`isOfferingsPlanProduct`, `services/offerings/catalog.ts`), checked on the same expanded Price it sells; a refused or unexpanded Product answers `500 plan_price_missing`. Check order: tenant → `billing-manage` (403 before any lookup) → write budget (`chargeWriteBudget` scope `plancheckout`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{ returnUrl }` (`bodyLimit` 4 KiB, `400 validation_failed`) → the return URL (canonical, no userinfo, query, fragment or `//` path, `https:` or a local `http:`, on `config.TRUSTED_ORIGINS`; `400 return_url_refused`, `500 config-error` when none is trusted) → no customer yet (`409 billing_customer_exists`) and a purchasable tier (`409 plan_not_purchasable`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` → one payable session (an open earlier one is expired first, a completed one is `409 purchase_pending`) → `createCheckoutSession` with `mode: "subscription"`, 1–50 sites, `metadata` and `subscriptionMetadata` `{ organizationId, ...siteStamp() }` and `PLATFORM_TERMS_OF_SERVICE`, never a `buyer` → a Checkout URL only → the session id recorded on `Organization.planCheckoutSessionId` by compare-and-set (a lost race or a failed write expires the new session). It answers `{ url }` with `Cache-Control: private, no-store`; no body or log line carries the return URL, an id or a Stripe message. **A body with `change` (#12336 D6)** — `{ period, level, writers, builders }`, names only (`planChangeRequestSchema`), `null` for "None" — changes the bound customer's plan instead: after steps 1–6 and the key, a bound customer (`409 billing_customer_missing`) → a fresh read of the change (`readPlanChangeBasis`, never the cache; `409 plan_change_unavailable` when Plan overview would offer none — a plan Stripe paused when its trial ended with no card included, #12337) → each name a choice of its row at that period, re-priced on the server (`400 choice_refused`) → an order that differs from what is held (`409 plan_unchanged`) → one change at a time on `Organization.planChangeSessionId` (`settlePlanChange`: an open recorded session is expired, a paid one nothing finished is finished, a pending one is `409 purchase_pending`) → one subscription Checkout on the bound customer for the whole order at one period (`createPlanChangeCheckoutSession`: `billing_mode` flexible, no discount or trial, metadata `ailk_plan_change: "1"` and `ailk_replaces`) → a Checkout URL only → the session recorded by compare-and-set → `forgetPlanOverview`. Nothing changes until the customer pays on Stripe. **The webhook's Organization arm binds only that recorded session (#9067 D13):** a `checkout.session.completed` with `metadata.organizationId` links `session.customer` through one guarded `updateMany` on `{ id, planCheckoutSessionId: session.id, billingCustomerId: null }` (clearing the session); anything else — an unrecorded session, a bound customer, every `customer.created` — writes nothing and logs `org_bind_unproven`. No MCP twin for the purchase — owner-only, recorded in `tests/parity/README.md`. **`POST /v1/billing/trial-card` (#12337 D6, `routes/billing/trial-card.ts`)** is Plan overview's "Add card" coming back: on the caller's own Organization's plan, read fresh on the deployment's key (`finishPlanTrialCard`), it moves a running no-card trial's end 14 days later once (`extended`), or — only with a live return token — starts a paused plan with a charge that day (`started`); else `unchanged`. Check order: tenant (401) → `billing-manage` (403 before any lookup or budget) → write budget (scope `plantrial`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{}` or `{ token }` (`400 validation_failed`; no id, date or price is taken from the body) → the Organization's billing customer (`404 no-billing-customer`) → its payer, `readOrgPayer`, must be `own` (`409 not-own-plan` for an agency's client, bound or not, or a failed classification) → a customer a User shares (`409 billing-customer-shared`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` (500) → the token spent by `consumeReservation` (one delete of the live `plan-trial-card` reservation of the caller's own Workspace and Organization whose `ref` is the token's SHA-256; only a deleted row allows a start), then the one write (`500 config-error`, `502 trial-unavailable`) → `{ outcome }` with `Cache-Control: private, no-store`. From the token step on the customer's cached Plan overview is forgotten on every answer, and an `extended` or `started` answer records one audit row. The token is minted by the portal session's Plan overview path (`returnUrl` `/workspaces/<id>/settings/org-plan`, the payment-method screen only), which holds its hash for an hour; every portal-session path also refuses any payer but `own` with `409 not-own-plan` after its key checks and before a token or any call on the deployment's key. No MCP twin — owner-only, recorded in `tests/parity/README.md`. **`POST /v1/billing/plugin-checkout` (#12009 D5, `routes/billing/plugin-checkout.ts`)** is the Billing tab's "+ Add" on a plugin row: a subscription Checkout for one plugin at one interval (`year` or `month`), one unit per chosen workspace, on the Organization's own bound customer. Check order: tenant → `billing-manage` (403 before any read) → write budget (scope `plugincheckout`, 10 an hour per Organization and per person) → the commerce claim → a strict `{ plugin, interval, workspaceIds (1–50, distinct), returnUrl }` → plan-checkout's own return-URL rule (`isAcceptableReturnUrl`) → a registered grant writer (`409 purchase_unavailable`) → a bound customer (`409 billing_customer_missing` — no plugin before the plan) → the catalogue (`503 catalogue_unavailable` on an unread one; `409 plugin_not_for_sale` for growth-ops, an unsold plugin or a placeholder price) → the workspaces (each a `wksp_` id of the caller's own Organization, else `400 workspace_refused`; a failed entitlement read for any of them, `503 entitlement_unavailable` — `workspaceHasPluginForSale`, which fails closed where `workspaceHasPlugin` answers no; one it answers yes for, or an active purchase of the plugin names, `409 plugin_already_added`) → the admitted Stripe key → one open Checkout per workspace, from one read of the plugin's `created` and `active` purchases (one confirmed since the step before, `active`, naming a chosen workspace answers `409 plugin_already_added`; an earlier `created` one is expired and ended; a completed one answers `409 purchase_pending`) → `createCheckoutSession` at the catalogue's lookup key with `quantity` equal to the workspace count, no `adjustableQuantity`, `metadata` and `subscriptionMetadata` `{ organizationId, ailk_plugin, ...siteStamp() }`, and a `refusePrice` that refuses any Price whose `unit_amount`, currency or interval is not the catalogue's, or that is not billed per unit, once per interval, with no quantity transform (`500 plugin_price_mismatch`) → a Checkout URL only → the session recorded as a `PluginPurchase` with the Price id `refusePrice` accepted (`state: created`; no accepted Price, or a failed write, expires the session and answers 502) → no rival recorded or confirmed meanwhile for a chosen workspace (else the new session is expired and ended: `409 purchase_pending` for a `created` rival, `409 plugin_already_added` for an `active` one; a recheck that cannot be read does the same and answers 502). **The webhook's plugin path (#12009 D9, `services/plugin-purchases.ts` `fulfilPluginEvent`)** runs once after the site filter and before the `switch`, and only on a hub with billing's grant writer: for a `checkout.session.completed`, `customer.subscription.*`, `invoice.paid` or `invoice.payment_failed` whose object carries the `ailk_plugin` stamp (`PLUGIN_SUBSCRIPTION_METADATA_KEY` — a filter only, never a grant) it traces the event's subscription to a recorded purchase (bound, or by `checkout.sessions.list` and a once-only bind), re-reads the subscription from Stripe, stores `state` and `exp` (the item's `current_period_end` while `active` or `trialing` and still paying for the record — quantity at least the recorded workspaces, the recorded Price and interval, collection not paused — else now; `ended_at` or now, `state: ended`, when `canceled` or `incomplete_expired`; nothing while `incomplete`; now otherwise — no grace), and writes one `add_on` grant per workspace with the latest `exp` among the purchases covering it and that purchase's subscription. It never throws, an untraced subscription grants nothing, and no grant is written without an `exp`. When a read or a grant write fails (Stripe, the database or entitlements down) it answers `"retry"`: the webhook un-marks the event (`unmarkSeen`) and answers `503`, before any arm of the `switch` runs, so Stripe redelivers it and the idempotent path re-derives every grant. **The webhook's plan-change path (#12336 D8, `services/offerings/plan-change.ts` `fulfilPlanChangeEvent`)** runs right after it, the same way: for a `checkout.session.*` stamped `ailk_plan_change: "1"` by this site, whose Organization recorded that session for that customer, a completed or async-succeeded session whose new subscription is live and its first invoice paid (`isLivePaidSubscription`, never `payment_status` alone) reaches `finishPlanChange` — the one function that stamps (`ailk_plan_change: "replaced"`) and cancels each replaced subscription, prorated only for paid, unpaused time, keeping one that now holds an item the order never showed — and an expired or failed one only clears the column; `"retry"` un-marks the event and answers `503`. The owner's Plan overview read and the next change press reach the same function for a change whose event never arrived.
115
115
  - `/v1/billing/stripe-connection` (GET, PUT, DELETE), `/v1/billing/stripe-connection/live` (POST), `/v1/billing/stripe-connection/webhook-secret` (PUT), `/v1/billing/stripe-connection/webhook-reset` (POST) — the Organization's own Stripe connection (#8907, `src/routes/billing/stripe-connection.ts`; spec `docs/specs/8907-the-organization-stripe-connection-custody-spec.md`; contract `docs/specs/8879-the-offerings-security-contract-key-spec.md`). Registered from `routes/billing/index.ts`, so the same multi-tenant tenant scope and module gate; the target is always `request.tenant.organizationId`. **Data access and the cipher** are `src/services/offerings/connection.ts`, the only file that touches the StripeConnection model (exactly ten delegate calls, `architecture.yaml` `paths_scoped`): the key and the webhook secret are AES-256-GCM ciphertext under `STRIPE_CONNECTION_KEY`, bound to the Organization, the column and (for the secret) the mode; decryption also tries `STRIPE_CONNECTION_KEY_PREVIOUS`. The GET needs `billing-read` and answers `null` or exactly `{ mode, last4, webhookPath, webhookSecretSet, connectedAt, liveAt, updatedAt }` (a corrupt row `500 connection_unreadable`); with no stored row it answers `{ source: "environment", mode }` to the Organization that owns `STRIPE_SECRET_KEY` and `null` to every other (#9285 — without the `multi-tenant` module selected the single Organization owns it; with it selected in `AILK_ENABLED_MODULES`, whether or not the licence claims it (#9968), only the one `STRIPE_ENV_ORGANIZATION_ID` names, so unset is nobody: a deployment that selects `multi-tenant` must set `STRIPE_ENV_ORGANIZATION_ID` for any Organization to own the environment key, a downgraded one whose licence no longer claims the module included), and that Organization's Offerings reads and shown set go through the same key (`services/offerings/connection.ts`'s `getOfferingsConnectionState` and the `stripeClientForOrganization` fallback), but its checkout stays on the env path — `resolveOfferingsCheckoutPath` returns the Offerings path only for a stored connection, because a session stamped `ailk_offering` on the environment key is acked `offerings_path` by the legacy webhook and never recorded (#9296; the bridge until a stored connection exists, #8936); every write needs `billing-manage` (the owner alone), checked before the body is read, and answers `{ mode, webhookSecretSet, liveAt, updatedAt }` — never `last4` or the path. PUT `{ key }` admits a restricted test key only (`400 stripe_key_refused` with a `reason` from the class table: `key_unrestricted`, `key_publishable`, `live_key_needs_go_live`, `key_unrecognized`); a replace keeps the webhook token and returns the connection to test mode, clearing a live secret. POST `…/live` `{ key, webhookSecret, confirm: "go-live" }` admits a restricted live key only when a cookie session (`403 session_required`), the commerce claim (`409 commerce_required`, `503 license_undetermined`), a production build (`409 live_mode_unavailable` — `lib/stripe.ts`'s `isProductionBuild`), the confirmation (`400 confirmation_required`) and a `whsec_` secret (`400 webhook_secret_invalid`) all hold. Connect and go-live run three read probes — `products.list`, `prices.list`, `checkout.sessions.list`, together, 10 s — through `lib/stripe.ts`'s `stripeClientForConnection` (the per-key factory's one caller, confined in `architecture.yaml`) before anything is stored: `400 stripe_key_refused` `key_not_usable` or `502 stripe_unavailable`, nothing written. The secret PUT binds it to the row's mode; the reset mints a new token and clears the secret; DELETE removes the row, so the token's lookup (`findStripeConnectionByWebhookToken`, #8861's receiver) answers `not-found` at once; it is a compare-and-swap on the row it read, so it answers `{ revoked: false }` when that read found none, and `409 connection_changed` when the row keeps changing between the read and the delete. On a build that is not production, every write to a live row is `409 live_mode_unavailable` and nothing decrypts one. With `STRIPE_CONNECTION_KEY` unset, connect, go-live and the secret answer `503 credential_key_not_configured`; the GET, reset and DELETE need no key and no claim. **The write budget (K10):** every write but DELETE that passes the permission is counted, refused keys included — 10 an hour per Organization, 20 per person (`middleware/rate-limit.ts`'s `chargeWriteBudget`, always its own database store) — `429 rate_limited` with `Retry-After`. Every success writes one `billing.stripe_connection.<connect|replace|go_live|webhook_secret|webhook_reset|remove>` audit row whose summary is `{ mode, last4 }` and emails every owner, the actor included (`@working-theory/email`'s `sendStripeConnectionChangedEmail`); neither can change the answer. Every response is `Cache-Control: private, no-store`; no response, log line, audit row or email carries the key, the secret, the token or a ciphertext. The rekey bin is `stripe-connections:rekey` (`node dist/bin/stripe-connections-rekey.js`), run with the production environment; anywhere else it answers `not_production` and touches nothing. No MCP twin — owner-only key custody that no agent can hold, recorded in `tests/parity/README.md`.
116
116
  - `/v1/billing/stripe-products` (GET, PUT) — the may-sell product list and the org-enabled write (#8922, `src/routes/billing/stripe-products.ts`; spec `docs/specs/8922-the-may-sell-product-list-spec.md`; contract A12, G3, G4, T6). Registered from `routes/billing/index.ts`, so the same multi-tenant tenant scope and module gate; the target is always `request.tenant.organizationId`. Check order: tenant → permission (GET `billing-read`, owner and admin; PUT `billing-manage`, the owner alone — checked before the body, so an admin, a member and an agent key get `403` whatever they send) → the commerce claim (`409 commerce_required`, `503 license_undetermined` with `Retry-After: 300`) → the body → the connection → the catalog read. The GET answers `{ ok: true, data: { connected, products } }`: every active Product `normalizeCatalog` keeps, offerings first in its order then the held ones, each exactly `{ productId, name, description, enabled, heldReason }` — `heldReason` an `OFFERINGS_HELD_REASONS` value or `null`, a held entry always `enabled: false` with `description: null`, and no price, lookup key, image or URL. No connection is `connected: false, products: []`; a corrupt one is `409 connection_unreadable` on both routes, never the empty list. The PUT takes a strict `{ productIds }` (`bodyLimit` 32 KiB; `400 validation_failed` for a malformed body, a duplicate or a malformed id) and replaces the whole set: more than 100 ids, an id in neither list, and a held id are `400 offerings_enabled_refused` with `reason` `too_many_products`, `product_not_in_catalog` or `product_held` (the lookup-key gate — `needs_lookup_key` covers a missing `{plan}_{period}` key and a period that disagrees with the Price, `plan_conflict` a plan two Products share), nothing written; no connection is `409 stripe_not_connected`. It answers the GET body for the new set, parsed before the write. The set's one writer is `services/offerings/store.ts`'s `writeEnabledProductIds` (an `upsert`, `architecture.yaml` `paths_scoped`), through `services/offerings/index.ts`'s `listOrgProducts` and `setOrgEnabledProducts`; both share the per-Organization catalog read (one a minute per process, T7), so `getOrgEnabledProducts` afterwards reads the row with no Stripe call. The catalog comes from `services/offerings/source.ts`'s `stripeCatalogSourceFor` — the Organization's own client (`stripeClientForOrganization`), paged at most 10 product and 30 price calls, 20 s for the whole read, confined in `architecture.yaml`; a disconnected or unusable connection rejects rather than reading as empty, and any source failure is `502 offerings_source_unavailable` with a fixed message. Every successful write records one `offerings.enabled.set` audit row naming the actor, whose summary is `{ enabled, added, removed }` counts only; a failed audit write is one `error` line and the answer stays `200`. Every response is `Cache-Control: private, no-store`, every error message is fixed, and no log line carries a product or price id, a name or the body. The wire names are #8923's, the Admin card that reads it. No MCP twin — owner and admin settings that no agent can hold, recorded in `tests/parity/README.md`.
117
117
  - `/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`.
@@ -247,7 +247,11 @@ sweep's own DB constraint (never a caller-side lock).
247
247
  - Don't bundle `apps/api` (esbuild, rollup, webpack). Slice specifiers cannot survive it — see `## Deploy path`.
248
248
  - 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.
249
249
 
250
- Last updated: 2026-11-20 — #12009 U2: plugin-checkout's workspace check fails closed (`503 entitlement_unavailable`); the `/v1/billing` bullet names `bought` from the purchase record and the registered grant writer behind `forSale`, `POST /v1/billing/plugin-checkout` with its check order, and the webhook's plugin path — verified against `packages-paid/api-multi-tenant/src/routes/billing/{read,plugin-billing,plugin-checkout}.ts`, `packages/api/src/services/plugin-purchases.ts` and `packages/api/src/routes/webhooks/stripe.ts`.
250
+ Last updated: 2026-11-25 — #12337: `POST /v1/billing/trial-card` and its check order beside plan-checkout, the portal session's payer check and Plan overview return token, and a paused plan offering no change — verified against `packages-paid/api-multi-tenant/src/routes/billing/{trial-card,portal}.ts`, `packages/api/src/lib/write-reservations.ts` and `packages/api/src/services/offerings/{plan-change,member-billing}.ts`.
251
+
252
+ Prior: 2026-11-25 — #12336: the plan-checkout sentence names the `change` branch and its check order, and the webhook gains the plan-change path after the plugin path — verified against `packages-paid/api-multi-tenant/src/routes/billing/plan-checkout.ts`, `packages/api/src/services/offerings/{plan-change,member-billing}.ts` and `packages/api/src/routes/webhooks/stripe.ts`.
253
+
254
+ Prior: 2026-11-20 — #12009 U2: plugin-checkout's workspace check fails closed (`503 entitlement_unavailable`); the `/v1/billing` bullet names `bought` from the purchase record and the registered grant writer behind `forSale`, `POST /v1/billing/plugin-checkout` with its check order, and the webhook's plugin path — verified against `packages-paid/api-multi-tenant/src/routes/billing/{read,plugin-billing,plugin-checkout}.ts`, `packages/api/src/services/plugin-purchases.ts` and `packages/api/src/routes/webhooks/stripe.ts`.
251
255
 
252
256
  Prior: 2026-11-20 — #12009: the `/v1/billing` bullet names the owner's `plugins` rows under `?include=billing`, their fields and the catalogue read behind `prices` — verified against `packages-paid/api-multi-tenant/src/routes/billing/{read,plugin-billing}.ts` and `packages/api/src/services/entitlements.ts`.
253
257
 
@@ -138,6 +138,21 @@ export const prisma = {
138
138
  update: jest.fn(),
139
139
  updateMany: jest.fn(),
140
140
  },
141
+ // #12343 D1, D2 — the hub's agency mark and each client's customer in the
142
+ // agency's connection, written and read only by services/entitlements.ts.
143
+ // Bare `jest.fn()`s: an unprogrammed `findUnique` answers `undefined`, which
144
+ // that file reads as no agency, so a suite that never marks one is FR6.
145
+ hubAgency: {
146
+ findUnique: jest.fn(),
147
+ create: jest.fn(),
148
+ updateMany: jest.fn(),
149
+ deleteMany: jest.fn(),
150
+ },
151
+ agencyClientCustomer: {
152
+ findMany: jest.fn(),
153
+ create: jest.fn(),
154
+ updateMany: jest.fn(),
155
+ },
141
156
  workspace: {
142
157
  // #6335 — NO default implementation, deliberately. Until this issue the
143
158
  // delegate carried a PERMISSIVE one (#6203): it resolved ANY requested
@@ -813,6 +813,18 @@ key), so the page names none. It renders one of three pages:
813
813
  reading that workspace has taken this release with or before its hub: an
814
814
  older site's strict shown-set readers refuse such a product and show the
815
815
  contact email in place of its Stripe cards.
816
+ - **A comparison table that reads an Offerings grid (#12370).** A
817
+ `comparison-table` section holds typed `columns` and `groups`, or one
818
+ `grid` setting — the Grid block's own fields, less `price` and `button`
819
+ (the section's `planBar` is its one header control) — never both. On every
820
+ Pricing page `pricingSections` runs `withGrids` before `withPlanColumns`:
821
+ each grid-bound table takes its columns and groups from `gridTable`
822
+ (`lib/grid-read.ts`, the one read a `<Grid … />` block line also uses) and
823
+ keeps every field it sets itself, so a grid's plan columns then resolve
824
+ from the shown set like a typed table's. A read that fails, takes longer
825
+ than 3,000 ms or answers no row draws no table, and nothing typed is kept
826
+ as a fallback. On a page that is not a Pricing page the setting is not
827
+ resolved and the table draws nothing.
816
828
  - **A comparison table's plan columns (#12246).** A `comparison-table`
817
829
  column is a typed name (`{ key, name }`) or a Stripe plan named by its slug
818
830
  (`{ key, plan }`, `name` optional and winning when set), and one table
@@ -0,0 +1,212 @@
1
+ /**
2
+ * lib/grid-read.ts — the one read of an Offerings grid for a page (#12370,
3
+ * spec docs/specs/12370-a-comparison-table-reads-an-offerings-grid-spec.md
4
+ * D3, D9): AC-3, AC-6, AC-12, AC-13.
5
+ *
6
+ * A `<Grid … />` block line and a `comparison-table` section's `grid` go
7
+ * through the same `gridTable`. The grid read is mocked at
8
+ * `@working-theory/api-client`, so this suite pins what each path asks the
9
+ * hub for and that the two give the same table.
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+ import path from "node:path";
13
+
14
+ import { PageSectionsSchema, parseBlockLine, type GridAnswer, type GridBlock, type PageSection } from "@working-theory/validation";
15
+
16
+ jest.mock("@working-theory/api-client", () => ({
17
+ content: { grid: jest.fn() },
18
+ offerings: { shown: jest.fn() },
19
+ flows: { get: jest.fn() },
20
+ leads: { captureStatus: jest.fn() },
21
+ }));
22
+
23
+ import { content, offerings } from "@working-theory/api-client";
24
+
25
+ import { GRID_READ_DEADLINE_MS, gridTable, withinGridDeadline } from "../grid-read";
26
+ import { withGrids } from "../pricing-page";
27
+
28
+ const grid = jest.mocked(content.grid);
29
+
30
+ /** `publicGrid`'s answer for a Capabilities grid: what it left in is all there is. */
31
+ const CAPABILITIES: GridAnswer = {
32
+ kind: "capabilities",
33
+ columns: [
34
+ { key: "pro", ours: true, plan: "pro", name: "Pro" },
35
+ { key: "pro-plus", ours: true, plan: "pro-plus", name: "Pro Plus" },
36
+ ],
37
+ groups: [
38
+ {
39
+ id: "site",
40
+ name: "Site",
41
+ rows: [
42
+ { id: "pages", name: "Pages", note: "Every page a site needs.", cells: { pro: false, "pro-plus": true } },
43
+ { id: "seats", name: "Seats", cells: { pro: { value: "1" }, "pro-plus": { value: "3" } } },
44
+ ],
45
+ summaries: {},
46
+ },
47
+ ],
48
+ factsAsOf: null,
49
+ };
50
+ const ALTERNATIVES: GridAnswer = {
51
+ kind: "alternatives",
52
+ columns: [
53
+ { key: "ours", ours: true, name: "Growth Hub" },
54
+ { key: "wix", ours: false, name: "Wix", what: "A website builder", source: { url: "https://wix.com/pricing" }, checkedOn: "2026-11-01" },
55
+ ],
56
+ groups: [
57
+ {
58
+ id: "build",
59
+ name: "Build",
60
+ rows: [
61
+ {
62
+ id: "r1",
63
+ name: "Drafts",
64
+ cells: {
65
+ ours: { verdict: "yes", note: { code: "from-level", level: "Pro Plus" } },
66
+ wix: { verdict: "partial", words: "Blog only" },
67
+ },
68
+ },
69
+ ],
70
+ summaries: {},
71
+ },
72
+ ],
73
+ factsAsOf: "2026-11-01",
74
+ };
75
+
76
+ let seq = 0;
77
+ beforeEach(() => {
78
+ grid.mockReset();
79
+ jest.mocked(offerings.shown).mockReset();
80
+ seq += 1;
81
+ });
82
+
83
+ /** A block line's grid, parsed by the one grammar. */
84
+ function block(text: string): GridBlock {
85
+ const line = parseBlockLine(text);
86
+ if (line === null || line.tag !== "Grid") throw new Error(`not a grid line: ${text}`);
87
+ return line.block;
88
+ }
89
+ /** A grid-bound section, parsed as a page's sections are. */
90
+ function section(setting: Record<string, unknown>, own: Record<string, unknown> = {}): PageSection {
91
+ return PageSectionsSchema.parse([{ id: "t", type: "comparison-table", data: { grid: setting, ...own } }])[0]!;
92
+ }
93
+
94
+ describe("a grid-bound section and a Grid block line give the same table (AC-3)", () => {
95
+ it.each<[string, GridAnswer, () => [string, Record<string, unknown>]]>([
96
+ [
97
+ "capabilities, with levels",
98
+ CAPABILITIES,
99
+ () => [
100
+ `<Grid kind="capabilities" products="growth-hub-${seq}" levels="pro pro-plus" show="features" />`,
101
+ { kind: "capabilities", products: [`growth-hub-${seq}`], levels: ["pro", "pro-plus"], show: "features" },
102
+ ],
103
+ ],
104
+ [
105
+ "alternatives, with ours, columns and source",
106
+ ALTERNATIVES,
107
+ () => [
108
+ `<Grid kind="alternatives" category="website-platform-${seq}" ours="growth-hub" columns="wix" show="features" source="true" />`,
109
+ { kind: "alternatives", category: `website-platform-${seq}`, ours: "growth-hub", columns: ["wix"], show: "features", source: true },
110
+ ],
111
+ ],
112
+ ])("%s", async (_label, answer, fields) => {
113
+ grid.mockResolvedValue({ ok: true, body: answer });
114
+ const [line, setting] = fields();
115
+ const fromBlock = await gridTable(block(line), "en");
116
+ const [resolved] = await withGrids([section(setting)], "en");
117
+ expect(fromBlock).not.toBeNull();
118
+ expect(resolved!.data).toEqual(fromBlock!.data);
119
+ // The same fields are one read of the hub, shared: the two paths cannot disagree.
120
+ expect(grid).toHaveBeenCalledTimes(1);
121
+ });
122
+
123
+ it("the section's planBar equals a block's price and button, from the same grid data", async () => {
124
+ grid.mockResolvedValue({ ok: true, body: CAPABILITIES });
125
+ const fromBlock = await gridTable(block(`<Grid kind="capabilities" products="g-${seq}" show="features" price="true" button="true" />`), "en");
126
+ const planBar = { pickerLabel: "Plan", price: true, button: true };
127
+ const [resolved] = await withGrids([section({ kind: "capabilities", products: [`g-${seq}`], show: "features" }, { planBar })], "en");
128
+ expect(fromBlock!.data.planBar).toEqual(planBar);
129
+ expect(resolved!.data).toEqual(fromBlock!.data);
130
+ expect(fromBlock!.plans).toEqual(["pro", "pro-plus"]);
131
+ });
132
+ });
133
+
134
+ describe("the section draws exactly what the public grid answers (AC-6, AC-12, AC-13)", () => {
135
+ it("adds, removes and reorders nothing: the answer's rows and columns are the table's", async () => {
136
+ // What `publicGrid` left out — a row not in Stripe yet, an unpublished
137
+ // record, an unapproved or hidden column, an unknown slug — is not in the
138
+ // answer, and the site has no second filter and no second source.
139
+ grid.mockResolvedValue({ ok: true, body: ALTERNATIVES });
140
+ const [resolved] = await withGrids([section({ kind: "alternatives", category: `c-${seq}`, show: "features" })], "en");
141
+ const data = resolved!.data as Extract<PageSection, { type: "comparison-table" }>["data"];
142
+ expect(data.columns.map((c) => c.key)).toEqual(ALTERNATIVES.columns.map((c) => c.key));
143
+ expect(data.groups.map((g) => g.rows.map((r) => r.featureName))).toEqual([["Drafts"]]);
144
+ });
145
+
146
+ it("reads one route — the public grid read — with the grid's own fields and the locale, and nothing else", async () => {
147
+ grid.mockResolvedValue({ ok: true, body: CAPABILITIES });
148
+ await withGrids([section({ kind: "capabilities", products: [`growth-hub-${seq}`, "positionary"], levels: ["pro"], show: "capabilities" })], "de");
149
+ expect(grid.mock.calls).toEqual([
150
+ [{ kind: "capabilities", slug: `growth-hub-${seq} positionary`, show: "capabilities", levels: "pro", locale: "de" }],
151
+ ]);
152
+ // No workspace, organization or shown-set read: the same call in single
153
+ // tenant, multi-tenant and from a spoke with its own client.
154
+ expect(offerings.shown).not.toHaveBeenCalled();
155
+ });
156
+
157
+ it("carries no lookup key, planning id or PRD link: an answer holding one is refused, and a table holds the answer's words alone", async () => {
158
+ // A hub that answered more than the public shape: `GridAnswerSchema` is strict, so no table is drawn.
159
+ grid.mockResolvedValue({
160
+ ok: true,
161
+ body: { ...CAPABILITIES, entitlement: "pack-site", planningId: "FEAT-1", prd: "https://example.com/prd" } as GridAnswer,
162
+ });
163
+ expect(await withGrids([section({ kind: "capabilities", products: [`k-${seq}`], show: "features" })], "en")).toEqual([]);
164
+
165
+ grid.mockResolvedValue({ ok: true, body: CAPABILITIES });
166
+ const [resolved] = await withGrids([section({ kind: "capabilities", products: [`k2-${seq}`], show: "features" })], "en");
167
+ const data = resolved!.data as Record<string, unknown>;
168
+ expect(Object.keys(data).sort()).toEqual(["columns", "groups", "labelHeader"]);
169
+ expect(JSON.stringify(data)).not.toMatch(/entitlement|planningId|prd|pack-/);
170
+ });
171
+ });
172
+
173
+ describe("withinGridDeadline", () => {
174
+ afterEach(() => jest.useRealTimers());
175
+
176
+ it("answers the read when it lands in time, and null for a rejection", async () => {
177
+ expect(await withinGridDeadline(Promise.resolve("table"))).toBe("table");
178
+ expect(await withinGridDeadline(Promise.reject(new Error("down")))).toBeNull();
179
+ });
180
+
181
+ it("answers null once the deadline passes", async () => {
182
+ jest.useFakeTimers();
183
+ const late = withinGridDeadline(new Promise<string>(() => undefined));
184
+ await jest.advanceTimersByTimeAsync(GRID_READ_DEADLINE_MS);
185
+ expect(await late).toBeNull();
186
+ expect(GRID_READ_DEADLINE_MS).toBe(3_000);
187
+ });
188
+ });
189
+
190
+ describe("grid-read.ts imports nothing from in-page-magnet (#12385)", () => {
191
+ // pricing-page → grid-read → in-page-magnet → contact.actions →
192
+ // site-pages.config → pricing-page closed a cycle that stopped `next build`.
193
+ // Every specifier form — static and dynamic import, re-export, require.
194
+ it("names no in-page-magnet module in any import, re-export or require", () => {
195
+ const source = readFileSync(path.join(__dirname, "..", "grid-read.ts"), "utf8");
196
+ const specifiers = [
197
+ ...source.matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)(["'`])([^"'`]+)\1/g),
198
+ ].map((match) => match[2]);
199
+ expect(specifiers.length).toBeGreaterThan(0);
200
+ expect(specifiers.filter((s) => /(^|\/)in-page-magnet(\.tsx?)?$/.test(s!))).toEqual([]);
201
+ });
202
+
203
+ it("reaches the site through hub-read.ts alone, so no other local module can lead back", () => {
204
+ const source = readFileSync(path.join(__dirname, "..", "grid-read.ts"), "utf8");
205
+ const local = [
206
+ ...source.matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)(["'`])([^"'`]+)\1/g),
207
+ ]
208
+ .map((match) => match[2]!)
209
+ .filter((s) => s.startsWith(".") || s.startsWith("@/"));
210
+ expect(local).toEqual(["./hub-read"]);
211
+ });
212
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * lib/hub-read.ts — the shared hub read (#8731), a leaf module since #12385.
3
+ *
4
+ * `grid-read.ts` once imported `sharedHubRead` from `in-page-magnet.ts`, and
5
+ * `pricing-page.ts` → `grid-read.ts` → `in-page-magnet.ts` →
6
+ * `contact.actions.ts` → `site-pages.config.tsx` → `pricing-page.ts` closed a
7
+ * cycle that stopped `next build` collecting page data. The read now lives
8
+ * here, importing no other apps/web module, and `in-page-magnet.ts`
9
+ * re-exports it under the same names.
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+ import path from "node:path";
13
+
14
+ jest.mock("@working-theory/api-client", () => ({
15
+ flows: { get: jest.fn() },
16
+ leads: { captureStatus: jest.fn() },
17
+ }));
18
+ jest.mock("@working-theory/site-pages/pages/contact/contact.actions", () => ({
19
+ captureLeadAction: jest.fn(),
20
+ }));
21
+ // eslint-disable-next-line no-restricted-syntax -- test-seam mock: a "use server" boundary in-page-magnet only binds
22
+ jest.mock("../newsletter.actions", () => ({
23
+ subscribeNewsletterAction: jest.fn(),
24
+ }));
25
+
26
+ import { HUB_READ_TTL_MS, sharedHubRead } from "../hub-read";
27
+ import * as inPageMagnet from "../in-page-magnet";
28
+
29
+ /** Every module specifier a source file names: static and dynamic imports, re-exports and requires. */
30
+ function specifiers(file: string): string[] {
31
+ const source = readFileSync(path.join(__dirname, "..", file), "utf8");
32
+ const found: string[] = [];
33
+ for (const match of source.matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)(["'`])([^"'`]+)\1/g)) {
34
+ found.push(match[2]!);
35
+ }
36
+ return found;
37
+ }
38
+
39
+ describe("hub-read.ts is a leaf (#12385)", () => {
40
+ // No package import either: the #12385 cycle ran through one
41
+ // (`@working-theory/site-pages`' contact actions read `site-pages.config.tsx`).
42
+ it("imports nothing at all", () => {
43
+ expect(specifiers("hub-read.ts")).toEqual([]);
44
+ });
45
+ });
46
+
47
+ describe("in-page-magnet.ts re-exports the shared hub read under the same names (#12385)", () => {
48
+ it("exports the very same sharedHubRead and HUB_READ_TTL_MS", () => {
49
+ expect(inPageMagnet.sharedHubRead).toBe(sharedHubRead);
50
+ expect(inPageMagnet.HUB_READ_TTL_MS).toBe(HUB_READ_TTL_MS);
51
+ expect(HUB_READ_TTL_MS).toBe(15_000);
52
+ });
53
+ });
54
+
55
+ describe("sharedHubRead (#8731)", () => {
56
+ afterEach(() => {
57
+ jest.useRealTimers();
58
+ });
59
+
60
+ it("shares one in-flight read between concurrent calls", async () => {
61
+ const read = jest.fn(async () => "answer");
62
+ const [a, b] = await Promise.all([sharedHubRead("hub-read:concurrent", read), sharedHubRead("hub-read:concurrent", read)]);
63
+ expect([a, b]).toEqual(["answer", "answer"]);
64
+ expect(read).toHaveBeenCalledTimes(1);
65
+ });
66
+
67
+ it("shares a null answer too, so a burst against an unreachable hub is one read", async () => {
68
+ const read = jest.fn(async () => null);
69
+ await sharedHubRead("hub-read:null", read);
70
+ await expect(sharedHubRead("hub-read:null", read)).resolves.toBeNull();
71
+ expect(read).toHaveBeenCalledTimes(1);
72
+ });
73
+
74
+ it("keeps each key's read apart", async () => {
75
+ await expect(sharedHubRead("hub-read:a", async () => "a")).resolves.toBe("a");
76
+ await expect(sharedHubRead("hub-read:b", async () => "b")).resolves.toBe("b");
77
+ });
78
+
79
+ it("reads afresh once HUB_READ_TTL_MS has passed, and not before", async () => {
80
+ jest.useFakeTimers({ now: 1_000_000 });
81
+ const read = jest.fn(async () => "fresh");
82
+ await sharedHubRead("hub-read:ttl", read);
83
+ jest.setSystemTime(1_000_000 + HUB_READ_TTL_MS - 1);
84
+ await sharedHubRead("hub-read:ttl", read);
85
+ expect(read).toHaveBeenCalledTimes(1);
86
+ jest.setSystemTime(1_000_000 + HUB_READ_TTL_MS);
87
+ await sharedHubRead("hub-read:ttl", read);
88
+ expect(read).toHaveBeenCalledTimes(2);
89
+ });
90
+ });