From 136e4e0c6a8c8d1fa6bb137455951f2e18d0ae65 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 28 Jul 2026 23:46:06 -0400 Subject: [PATCH 1/6] Complete agent assembly Phase 0: catalog schema and recipe backlog. Define schema 0.1.0 types, document the catalog shape, inventory registry gaps, and prioritize synthetic recipe intents for published packages so Phase 1 can compile catalog.json without inventing structure. --- docs/AGENT_ASSEMBLY_PLAN.md | 52 ++++-- docs/catalog/GAP_INVENTORY.md | 93 ++++++++++ docs/catalog/RECIPE_BACKLOG.md | 120 ++++++++++++ docs/catalog/SCHEMA.md | 133 ++++++++++++++ docs/catalog/example-catalog.json | 294 ++++++++++++++++++++++++++++++ src/data/catalog-schema.test.ts | 76 ++++++++ src/data/catalog-schema.ts | 214 ++++++++++++++++++++++ vitest.config.ts | 2 +- 8 files changed, 968 insertions(+), 16 deletions(-) create mode 100644 docs/catalog/GAP_INVENTORY.md create mode 100644 docs/catalog/RECIPE_BACKLOG.md create mode 100644 docs/catalog/SCHEMA.md create mode 100644 docs/catalog/example-catalog.json create mode 100644 src/data/catalog-schema.test.ts create mode 100644 src/data/catalog-schema.ts diff --git a/docs/AGENT_ASSEMBLY_PLAN.md b/docs/AGENT_ASSEMBLY_PLAN.md index 6b3a6dc..7a6fc6a 100644 --- a/docs/AGENT_ASSEMBLY_PLAN.md +++ b/docs/AGENT_ASSEMBLY_PLAN.md @@ -2,11 +2,22 @@ ## Status -**Stage:** Planning. No catalog schema, hosted skill, MCP surface, or recipe -package exists yet. This document is the working plan for closing the gap -between what AI coding agents tend to do (regenerate common backend -functions as bespoke code) and what the Pegma stack already packages -(typed, tested, pin-able components). +**Stage:** Phase 0 complete (schema + gap inventory + recipe backlog). No +compiled `catalog.json`, hosted skill, MCP surface, or recipe fixture package +exists yet. This document is the working plan for closing the gap between what +AI coding agents tend to do (regenerate common backend functions as bespoke +code) and what the Pegma stack already packages (typed, tested, pin-able +components). + +**Phase 0 artifacts:** + +| Artifact | Path | +| --- | --- | +| TypeScript schema | `src/data/catalog-schema.ts` | +| Schema documentation | `docs/catalog/SCHEMA.md` | +| Registry gap inventory | `docs/catalog/GAP_INVENTORY.md` | +| Prioritized recipe backlog | `docs/catalog/RECIPE_BACKLOG.md` | +| Example catalog (illustrative) | `docs/catalog/example-catalog.json` | **Goal:** An agent given a short product description chooses the right `@pegma/*` packages, respects their refusals, and wires them at an explicit @@ -215,7 +226,7 @@ recipe fixture, not a branded product clone. ## Phased delivery -### Phase 0 — Catalog schema and gap inventory ✓-ready to start +### Phase 0 — Catalog schema and gap inventory ✓ complete Define the catalog schema (TypeScript types + example JSON) in this repo or a small public agent-facing package. Inventory current registry fields vs. @@ -226,6 +237,11 @@ rate-limit, authorization-identity, health, logger adapters, audit). **Exit:** schema documented; recipe backlog prioritized; no production architecture disclosure in any recipe intent. +**Done:** schema 0.1.0 in `src/data/catalog-schema.ts` with docs under +`docs/catalog/`; gap inventory maps `PegmaComponent` → catalog fields; recipe +backlog prioritizes P1 `cf-passkey-accounts` and P2 `storage-audit-mail-outbox` +(synthetic intents only); deferred recipes gated on unpublished packages. + ### Phase 1 — Compiled catalog artifact Emit `catalog.json` (and optionally generated markdown) at site build or @@ -343,17 +359,23 @@ Pegma’s scope: ## Open questions -- **Catalog compile home:** site build only vs. small shared package used - by site and MCP. -- **Version authority:** registry snapshot vs. release-projection Store vs. - npm at compile time (or a combination with clear precedence). -- **Recipe repo layout:** monorepo fixtures vs. one examples repository. -- **`plan_composition` input shape:** free text tags vs. structured - capability flags (structured is easier to keep deterministic). +Phase 0 recommendations (not irreversible) are recorded in +`docs/catalog/GAP_INVENTORY.md` under “Decisions locked for Phase 1 compile.” + +- **Catalog compile home:** ~~site build only vs. small shared package~~ → + **prefer site build first**; extract a package only if MCP cannot fetch the + static catalog cleanly. +- **Version authority:** ~~registry prose vs Store vs npm~~ → **precedence:** + release-projection Store when present → npm at compile time → else + `version: null` / unpublished (never parse versions from `now` prose). +- **Recipe repo layout:** monorepo fixtures vs. one examples repository + (still open for Phase 2; backlog citations are layout-agnostic). +- **`plan_composition` input shape:** ~~free text vs structured~~ → + **structured `capabilityTags`** (see schema). - **Skill packaging:** single canonical markdown vs. thin per-tool wrappers - that only differ in install paths. + that only differ in install paths. (Phase 3) - **MCP hosting:** extend `pegma-dev-api` vs. separate Worker to keep the - account API’s privilege surface small. + account API’s privilege surface small. (Phase 4) ## Implementation note diff --git a/docs/catalog/GAP_INVENTORY.md b/docs/catalog/GAP_INVENTORY.md new file mode 100644 index 0000000..3afab4a --- /dev/null +++ b/docs/catalog/GAP_INVENTORY.md @@ -0,0 +1,93 @@ +# Catalog gap inventory + +Compares the human-facing component registry +([`src/data/components.ts`](../../src/data/components.ts)) and related site +surfaces against the composition catalog schema +([`SCHEMA.md`](./SCHEMA.md), [`catalog-schema.ts`](../../src/data/catalog-schema.ts)). + +**Date:** 2026-07-28 · **Schema:** 0.1.0 · **Registry snapshot:** 2026-07-28 (`SNAPSHOT_DATE` in `components.ts`) + +## Registry fields today (`PegmaComponent`) + +| Field | Present | Catalog destination | Gap | +| --- | --- | --- | --- | +| `repo` | yes | `id` + `repo` | No separate stable `id` field (today `repo` is the id) | +| `title` | yes | `title` | — | +| `packages` | yes (`string[]`) | `packages[]` with version/published | No per-package version or publish flag | +| `status` | yes | `status` | No `publishUsability` aggregate | +| `summary` | yes | `summary` | — | +| `owns` | yes | `owns` | — | +| `refuses` | yes | `refuses` | — | +| `now` | yes | `now` | Not structured; versions embedded in prose | +| `plan` | optional path | `links.plan` | No absolute URL; no README/npm link objects | + +## Fields the schema requires that the registry lacks + +| Schema field | Why agents need it | Suggested Phase 1 source | +| --- | --- | --- | +| `packages[].version` | Exact 0.x pins | npm / release projection / registry snapshot with precedence | +| `packages[].published` | Skip unpublished packages | npm existence + hand status | +| `publishUsability` | Fast list filter | Derived from package flags | +| `dependencies` | Correct composition order | Hand edges + package peer/optional deps where honest | +| `adapters` | Cloudflare vs Azure vs memory | Hand table per component (storage already known) | +| `hostMustProvide` | Stop agents from assuming the package owns cookies/DNS/UI | Hand list from READMEs / refuses | +| `capabilityTags` | Deterministic `plan_composition` | Hand tags on compile inputs | +| `recipeIds` | Recipe → component index | Recipe backlog + fixtures | +| `links.githubRepo` / `readme` / `npm` | Progressive disclosure | Convention + npm | +| `stage` | Drift-resistant status | Existing plan aggregation (`live-status` path) | +| `recipes[]` | Named intents with fixture citations | Recipe backlog → fixtures (Phase 2) | + +## Adjacent surfaces (not the catalog) + +| Asset | Role | Gap vs catalog | +| --- | --- | --- | +| `public/llms.txt` | Short agent index | No deps, pins, recipes, or refuses detail; Phase 1 should link to catalog URL only | +| `/stack` | Human component pages | Renders registry + stage; not machine-oriented | +| `/roadmap` | Compiled stage view | Stage only; not composition | +| `/examples` | Skeleton snippets from READMEs | Not recipe-index shaped; no fixture status | +| `worker/src/release-catalog.ts` | Release webhook allowlist / display order | Repo id map only — reuse order, not package facts | +| Component READMEs + conformance | Canonical package truth | Scattered; catalog must summarize and link, not fork | + +## Published vs assembly-usable (registry prose, 2026-07-28) + +Agents must treat **npm publication** as the production gate. Hand status alone +is insufficient when packages remain unpublished. + +| Component | Registry status | Assembly-usable today? | Notes | +| --- | --- | --- | --- | +| spine | published | yes | Pin from registry/npm (e.g. 0.1.1) | +| storage-core | published | yes | Core + azure-tables + cloudflare-d1 | +| authorization-core | published | yes | Multiple `@pegma/authorization-*` packages | +| audit | published | yes | 0.1.0; needs caller storage transaction | +| health | published | yes | | +| sessions | published | yes | | +| mail | published | yes | | +| identity | published | yes | | +| rate-limit | published | yes | | +| logger-adapters | published | yes | | +| support-desk | in development | **no** | Packages unpublished | +| webhooks | in development | **no** | Unpublished (local vendor tarball on this site only) | + +## Decisions locked for Phase 1 compile (from open questions) + +These are Phase 0 recommendations so Phase 1 does not re-litigate shape: + +1. **Compile home:** site build in this repo for the first `catalog.json` + (static publish). Extract a shared package only if the MCP Worker cannot + consume the same static URL cleanly. +2. **Version authority (precedence):** release-projection Store facts when + present → else npm at compile time → else registry `now` parse is + **forbidden**; leave `version: null` and `published: false` rather than + guess from prose. +3. **Recipe layout:** backlog lives in `docs/catalog/`; fixtures decide their + home in Phase 2 (dedicated examples repo vs in-package). Catalog only + stores citations. +4. **`plan_composition` inputs:** structured `capabilityTags` + host + constraints — not free-text LLM classification inside Pegma. + +## What Phase 0 deliberately does not do + +- Emit `catalog.json` or change the site build (Phase 1) +- Add recipe fixture code (Phase 2) +- Publish a skill or MCP tools (Phases 3–4) +- Document commercial host route maps or data models diff --git a/docs/catalog/RECIPE_BACKLOG.md b/docs/catalog/RECIPE_BACKLOG.md new file mode 100644 index 0000000..1d0c669 --- /dev/null +++ b/docs/catalog/RECIPE_BACKLOG.md @@ -0,0 +1,120 @@ +# Synthetic recipe backlog + +Prioritized composition intents for the agent catalog. Every intent is +**synthetic**: a purpose-built product shape for teaching assembly. None +describe a commercial host’s routes, tenancy, or operations. + +**Fixture rule:** catalog and `/examples` may only quote wiring that exists in +a public, CI-tested source (`fixture.status === green`). Until then, recipes +appear as intent metadata only. + +**Publish rule:** recipes whose `requiresPublished` set is not fully usable +must not be offered for production assembly (they may stay in the backlog as +deferred). + +## Priority order (ship fixtures in this order) + +### P1 — `cf-passkey-accounts` (first end-to-end accounts recipe) + +| | | +| --- | --- | +| **Intent** | A small Cloudflare Worker host for a fictional community library (“Northshelf Branch”) offers first-party accounts: passkey sign-in, email one-time codes for enrollment and recovery, server-side sessions, and durable rate limits on expensive auth paths. No passwords. | +| **Packages (published)** | `@pegma/identity`, `@pegma/sessions`, `@pegma/mail`, `@pegma/rate-limit`, `@pegma/authorization-identity`, `@pegma/storage-core`, `@pegma/storage-cloudflare-d1`, `@pegma/spine` | +| **Adapters** | `storage-core/cloudflare-d1`; mail provider chosen by host (e.g. Resend port on consumer pull) | +| **Host must provide** | HTTP routes, cookie/session boundary, WebAuthn origin config, email provider + DNS, secrets, any UI | +| **Non-goals** | Social login, OIDC server for third parties, passwords, multi-tenant orgs | +| **Anti-patterns** | Password table “just for admin”; durable events on Spine’s in-process bus; mail package owning its own outbox store; inventing sessions without `@pegma/sessions` | +| **requiresPublished** | identity, sessions, mail, rate-limit, authorization-core, storage-core, spine | +| **Fixture** | pending — Phase 2 synthetic fixture (not pegma.dev production account routes) | +| **Phase plan exit** | One of two required Phase 2 recipes (“accounts on Cloudflare-shaped host”) | + +### P2 — `storage-audit-mail-outbox` (storage + audit/mail pattern) + +| | | +| --- | --- | +| **Intent** | A fictional equipment checkout service (“Yard Loan”) records inventory mutations in Storage Core and, in the **same** single-partition transaction, appends an audit row and enqueues a transactional mail delivery job. After commit, a worker drains the outbox. | +| **Packages (published)** | `@pegma/storage-core`, `@pegma/audit`, `@pegma/mail`, `@pegma/spine` | +| **Adapters** | memory or cloudflare-d1 / azure-tables for demos; pattern is adapter-agnostic | +| **Host must provide** | Collection declarations, transaction boundary, outbox collection in host storage, mail provider adapter, delivery scheduler | +| **Non-goals** | Mail package owning storage; audit owning a store; cross-partition transactions | +| **Anti-patterns** | Separate “send email” after commit without an outbox job; audit write outside the caller’s `transact`; fake global ordering | +| **requiresPublished** | storage-core, audit, mail, spine | +| **Fixture** | pending — Phase 2; may cite package README/conformance excerpts until a dedicated fixture app exists | +| **Phase plan exit** | Second required Phase 2 recipe (“storage + audit/mail outbox pattern”) | + +### P3 — `durable-auth-rate-limits` + +| | | +| --- | --- | +| **Intent** | A fictional API for appointment holds (“Chair Queue”) applies durable fixed-window rate limits to expensive verification endpoints and an honest in-memory tier only for cheap abuse dampening — never pretending the memory tier is a global quota. | +| **Packages** | `@pegma/rate-limit`, `@pegma/storage-core` (durable tier), `@pegma/spine` | +| **Anti-patterns** | Using only in-memory limits for email-code or passkey verify; calling memory tier a “cluster quota”; expecting rate-limit to stop volumetric DDoS | +| **requiresPublished** | rate-limit, storage-core, spine | +| **Fixture** | pending | + +### P4 — `health-public-liveness` + +| | | +| --- | --- | +| **Intent** | A fictional brochure site’s Worker exposes a public liveness endpoint composed from `@pegma/health` probes (process + optional store ping), with checks registered at an explicit composition root. | +| **Packages** | `@pegma/health`, `@pegma/spine`; optional `@pegma/storage-core` for store ping | +| **Anti-patterns** | Autodiscovery of checks; health package inventing domain collections; treating health as APM | +| **requiresPublished** | health, spine | +| **Fixture** | pending (package README may supply early green citations) | + +### P5 — `logger-tee-composition` + +| | | +| --- | --- | +| **Intent** | A fictional batch importer (“Ledger Drop”) wires Spine’s Logger once at the composition root through `@pegma/logger-tee` into Cloudflare Workers Logs (and optionally a second sink), without growing Spine or inventing a Pegma observability vocabulary. | +| **Packages** | `@pegma/spine`, `@pegma/logger-tee`, `@pegma/logger-cloudflare` (optional other logger adapters) | +| **Anti-patterns** | Putting sink SDKs into Spine; replacing Logger with a custom core; claiming traces/metrics are Pegma’s job | +| **requiresPublished** | spine, logger-adapters | +| **Fixture** | pending | + +### P6 — `static-brochure-minimal` + +| | | +| --- | --- | +| **Intent** | A fictional static museum site (“Glass Wing”) needs no accounts, no durable storage, and no mail — only honest stack awareness (and optional health if a Worker exists). Teaches agents to **select nothing extra**. | +| **Packages** | none required; optional `@pegma/health` if a Worker liveness route exists | +| **Anti-patterns** | Pulling identity/sessions “for later”; inventing a database for a static site | +| **requiresPublished** | (none) | +| **Fixture** | pending — may be skill/eval only with empty composition root | + +## Deferred (unpublished packages) + +Do not offer for production assembly until packages are on npm. + +### D1 — `inbound-webhook-receipts` (when `@pegma/webhooks` is published) + +| | | +| --- | --- | +| **Intent** | A fictional donation platform (“Copper Plate”) records inbound provider webhook receipts with idempotent dedup, poison quarantine, and retention — receipts hold ids and counters, never payloads. | +| **Blocks** | webhooks unpublished | +| **Anti-patterns** | Exactly-once claims; storing full payloads in the receipt ledger; ordering guarantees | + +### D2 — `support-queue-slice` (when Support Desk packages are published) + +| | | +| --- | --- | +| **Intent** | A fictional maker-space helpdesk (“Bench Ticket”) runs a composable support queue for web and email with permission-checked agents and outbox-backed mail. | +| **Blocks** | support-desk packages unpublished | +| **Anti-patterns** | Treating Support Desk as hosted SaaS; AI on ticket bodies before the host documents egress | + +## Explicitly out of backlog (non-goals) + +- Recipes that copy pegma.dev or retiregolden.org route maps, schemas, or ops topology +- Password-based auth “compatibility” recipes (Identity refuses passwords) +- Spine durable-event recipes (Spine refuses durable events on the in-process bus) +- Multi-package monorepo scaffolds that dictate a UI framework + +## Mapping to plan Phase 2 exit + +| Plan requirement | Backlog id | +| --- | --- | +| End-to-end accounts on Cloudflare-shaped host | P1 `cf-passkey-accounts` | +| Storage + audit/mail outbox pattern | P2 `storage-audit-mail-outbox` | + +Ship P1 and P2 fixtures before declaring Phase 2 done. P3–P6 improve coverage; +D1–D2 wait on publication. diff --git a/docs/catalog/SCHEMA.md b/docs/catalog/SCHEMA.md new file mode 100644 index 0000000..c02e801 --- /dev/null +++ b/docs/catalog/SCHEMA.md @@ -0,0 +1,133 @@ +# Composition catalog schema + +Machine-readable facts for agents assembling hosts from `@pegma/*` packages. +This document describes schema **0.1.0** (`CATALOG_SCHEMA_VERSION` in +`src/data/catalog-schema.ts`). + +**Status:** Phase 0 — types and documentation only. Phase 1 emits +`catalog.json` at a stable URL. HTML pages, `llms.txt`, the hosted skill, and +any MCP tools are clients of this catalog (or of artifacts generated from it). + +## Design constraints + +| Rule | Implication | +| --- | --- | +| Catalog is source of truth | Transports do not invent package facts | +| Progressive disclosure | Prefer small list payloads; detail and recipes on demand | +| Exact 0.x pins | `version` is a concrete string or `null` — never a range guess | +| Unpublished is explicit | `published: false` / `publishUsability: "unpublished"` | +| Synthetic recipes | Intents describe purpose-built fixtures, not commercial products | +| Executed examples | Wiring code only when `fixture.status` is `green` and cited | + +## Document shape + +```text +CompositionCatalog +├── schemaVersion, generatedAt, snapshotDate? +├── components[] → CatalogComponent +└── recipes[] → CatalogRecipe +``` + +### `CompositionCatalog` + +| Field | Type | Notes | +| --- | --- | --- | +| `schemaVersion` | string | Catalog schema id (`0.1.0`), not a package version | +| `generatedAt` | string | ISO-8601 compile time | +| `snapshotDate` | string? | Hand registry snapshot date when that is an input | +| `components` | `CatalogComponent[]` | Full component set | +| `recipes` | `CatalogRecipe[]` | Composition intents (may be empty until Phase 2) | + +### `CatalogComponent` + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | string | Stable; usually GitHub repo short name (`spine`, `identity`) | +| `title` | string | Human title | +| `repo` | string | Repo name under `github.com/pegma-dev` | +| `packages` | `CatalogPackage[]` | npm packages with publish flags and pins | +| `status` | enum | `published` \| `in_development` \| `planned` | +| `publishUsability` | enum | `usable` \| `unpublished` \| `partial` | +| `summary` | string | One-line role | +| `owns` | string[] | Load-bearing responsibilities | +| `refuses` | string[] | Hard constraints — part of the contract | +| `dependencies` | `CatalogDependency[]` | Edges to other component ids | +| `adapters` | `CatalogAdapter[]` | Hosting choices (`cloudflare-d1`, `azure-tables`, …) | +| `hostMustProvide` | string[] | Cookies, HTTP boundary, secrets, DNS, UI, … | +| `capabilityTags` | `CapabilityTag[]` | Structured tags for deterministic planning | +| `recipeIds` | string[] | Recipes that include this component | +| `links` | object | `githubRepo` required; plan/readme/npm optional | +| `now` | string? | Plain-language snapshot from the hand registry | +| `stage` | string? | Compiled stage from `PROJECT_PLAN.md` (Phase 1) | + +### `CatalogPackage` + +| Field | Type | Notes | +| --- | --- | --- | +| `name` | string | e.g. `@pegma/spine` | +| `version` | string \| null | Exact pin or null if unknown/unpublished | +| `published` | boolean | Production-assembly gate | +| `npmUrl` | string? | Package page when published | + +### `CatalogDependency` + +| Field | Type | Notes | +| --- | --- | --- | +| `componentId` | string | Target `CatalogComponent.id` | +| `kind` | enum | `requires` \| `optional` \| `composes_with` | +| `note` | string? | Short agent hint | + +### `CatalogAdapter` + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | string | Stable within the component | +| `packageName` | string? | Implementing package | +| `host` | enum | `cloudflare` \| `azure` \| `memory` \| `other` | +| `when` | string | When to choose this adapter | + +### `CatalogRecipe` + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | string | Stable recipe id | +| `intent` | string | Synthetic product shape (one paragraph) | +| `packages` | string[] | Package names (pins appear when fixtures exist) | +| `adapters` | string[] | Selected adapter ids | +| `hostResponsibilities` | string[] | Host-owned work | +| `nonGoals` | string[] | Out of scope for the recipe | +| `antiPatterns` | string[] | What not to invent | +| `fixture` | object | Citation + kind + status | +| `capabilityTags` | tags | Overlap with component tags for planning | +| `requiresPublished` | string[] | Component ids that must be usable | +| `backlogPriority` | number? | Phase 0 ordering only (1 = first) | + +### `RecipeFixtureCitation` + +| Field | Type | Notes | +| --- | --- | --- | +| `kind` | enum | `package_readme` \| `conformance` \| `recipe_package` \| `scaffold` \| `pending` | +| `citation` | string | Public URL or path | +| `status` | enum | `green` \| `pending` \| `none` | + +## Capability tags + +Structured flags (not free text) so `plan_composition` can stay rule-based: + +`accounts`, `passkeys`, `email_codes`, `sessions`, `authorization`, `storage`, +`audit`, `mail_transactional`, `rate_limit_durable`, `rate_limit_memory`, +`webhooks_inbound`, `support_queue`, `health`, `logging`, `events_in_process`, +`cloudflare`, `azure`, `static_host`. + +## TypeScript source + +Canonical types: [`src/data/catalog-schema.ts`](../../src/data/catalog-schema.ts). + +Illustrative (non-authoritative) document: +[`example-catalog.json`](./example-catalog.json) — incomplete sample for shape +checking only; Phase 1 replaces hand examples with a compiled artifact. + +## Gap inventory and recipes + +- Field-by-field registry comparison: [`GAP_INVENTORY.md`](./GAP_INVENTORY.md) +- Prioritized synthetic recipe backlog: [`RECIPE_BACKLOG.md`](./RECIPE_BACKLOG.md) diff --git a/docs/catalog/example-catalog.json b/docs/catalog/example-catalog.json new file mode 100644 index 0000000..557ff78 --- /dev/null +++ b/docs/catalog/example-catalog.json @@ -0,0 +1,294 @@ +{ + "schemaVersion": "0.1.0", + "generatedAt": "2026-07-28T00:00:00.000Z", + "snapshotDate": "2026-07-28", + "components": [ + { + "id": "spine", + "title": "Spine", + "repo": "spine", + "packages": [ + { + "name": "@pegma/spine", + "version": "0.1.1", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@pegma/spine" + } + ], + "status": "published", + "publishUsability": "usable", + "summary": "The small, stable contracts every component shares.", + "owns": [ + "PrincipalId and IsoTimestamp — shared identity and time types", + "Clock — time as an injected, test-replaceable input", + "Logger — a one-method structured logging port", + "Typed event declarations and a best-effort in-process bus" + ], + "refuses": [ + "Durable events — anything that must survive a crash goes to a storage-backed outbox, never the in-process bus", + "Growth — the more spine changes, the more the ecosystem churns" + ], + "dependencies": [], + "adapters": [], + "hostMustProvide": [ + "Composition-root wiring for Clock, Logger, and any in-process bus subscribers" + ], + "capabilityTags": ["logging", "events_in_process"], + "recipeIds": [ + "cf-passkey-accounts", + "storage-audit-mail-outbox", + "health-public-liveness", + "logger-tee-composition" + ], + "links": { + "githubRepo": "https://github.com/pegma-dev/spine", + "readme": "https://github.com/pegma-dev/spine#readme", + "npm": "https://www.npmjs.com/package/@pegma/spine" + }, + "now": "0.1.1 on npm; deliberately close to frozen." + }, + { + "id": "storage-core", + "title": "Storage Core", + "repo": "storage-core", + "packages": [ + { + "name": "@pegma/storage-core", + "version": "0.4.0", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@pegma/storage-core" + }, + { + "name": "@pegma/storage-azure-tables", + "version": "0.4.0", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@pegma/storage-azure-tables" + }, + { + "name": "@pegma/storage-cloudflare-d1", + "version": "0.4.0", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@pegma/storage-cloudflare-d1" + } + ], + "status": "published", + "publishUsability": "usable", + "summary": "Persistence without the component knowing what the database is.", + "owns": [ + "Declared collections with codecs — schema-agnostic on purpose", + "update deciders re-run against fresh state on every conflict", + "Single-collection, single-partition transactions" + ], + "refuses": [ + "Server-side queries and secondary indexes", + "Cross-partition anything" + ], + "dependencies": [ + { + "componentId": "spine", + "kind": "requires", + "note": "Shared contracts and logging port" + } + ], + "adapters": [ + { + "id": "memory", + "packageName": "@pegma/storage-core", + "host": "memory", + "when": "Tests and local sketches; not a production durability claim" + }, + { + "id": "azure-tables", + "packageName": "@pegma/storage-azure-tables", + "host": "azure", + "when": "Azure-hosted apps that want the Tables adapter" + }, + { + "id": "cloudflare-d1", + "packageName": "@pegma/storage-cloudflare-d1", + "host": "cloudflare", + "when": "Cloudflare Workers/Pages with D1" + } + ], + "hostMustProvide": [ + "Chosen adapter binding (e.g. D1 database, Azure connection)", + "Collection declarations and codecs" + ], + "capabilityTags": ["storage", "cloudflare", "azure"], + "recipeIds": [ + "cf-passkey-accounts", + "storage-audit-mail-outbox", + "durable-auth-rate-limits" + ], + "links": { + "githubRepo": "https://github.com/pegma-dev/storage-core", + "readme": "https://github.com/pegma-dev/storage-core#readme", + "npm": "https://www.npmjs.com/package/@pegma/storage-core" + }, + "now": "0.4.0 on npm with Azure Tables and Cloudflare D1 adapters." + }, + { + "id": "webhooks", + "title": "Webhooks", + "repo": "webhooks", + "packages": [ + { + "name": "@pegma/webhooks", + "version": null, + "published": false + } + ], + "status": "in_development", + "publishUsability": "unpublished", + "summary": "Inbound webhook receipts: idempotent dedup, poison quarantine, retention.", + "owns": [ + "One receipt per provider event id", + "Quarantine-then-acknowledge after bounded failures" + ], + "refuses": [ + "Exactly-once delivery", + "Storing payloads — receipts hold ids and counters, never customer data" + ], + "dependencies": [ + { + "componentId": "storage-core", + "kind": "requires" + }, + { + "componentId": "spine", + "kind": "requires" + } + ], + "adapters": [], + "hostMustProvide": [ + "HTTP endpoint and provider signature verification", + "Storage binding for the receipt ledger" + ], + "capabilityTags": ["webhooks_inbound"], + "recipeIds": ["inbound-webhook-receipts"], + "links": { + "githubRepo": "https://github.com/pegma-dev/webhooks", + "plan": "https://github.com/pegma-dev/webhooks/blob/main/docs/PROJECT_PLAN.md" + }, + "now": "Unpublished; not usable for production assembly." + } + ], + "recipes": [ + { + "id": "cf-passkey-accounts", + "intent": "A small Cloudflare Worker host for a fictional community library (Northshelf Branch) offers first-party accounts: passkey sign-in, email one-time codes for enrollment and recovery, server-side sessions, and durable rate limits on expensive auth paths. No passwords.", + "packages": [ + "@pegma/identity", + "@pegma/sessions", + "@pegma/mail", + "@pegma/rate-limit", + "@pegma/authorization-identity", + "@pegma/storage-core", + "@pegma/storage-cloudflare-d1", + "@pegma/spine" + ], + "adapters": ["cloudflare-d1"], + "hostResponsibilities": [ + "HTTP routes and cookie/session boundary", + "WebAuthn relying-party configuration", + "Email provider adapter and DNS", + "Secrets and any account UI" + ], + "nonGoals": [ + "Social login", + "OIDC server for third parties", + "Passwords", + "Multi-tenant organizations" + ], + "antiPatterns": [ + "Password table or reset flow", + "Durable events on Spine in-process bus", + "Mail package owning its own outbox store" + ], + "fixture": { + "kind": "pending", + "citation": "docs/catalog/RECIPE_BACKLOG.md#p1--cf-passkey-accounts-first-end-to-end-accounts-recipe", + "status": "pending" + }, + "capabilityTags": [ + "accounts", + "passkeys", + "email_codes", + "sessions", + "authorization", + "mail_transactional", + "rate_limit_durable", + "storage", + "cloudflare" + ], + "requiresPublished": [ + "identity", + "sessions", + "mail", + "rate-limit", + "authorization-core", + "storage-core", + "spine" + ], + "backlogPriority": 1 + }, + { + "id": "storage-audit-mail-outbox", + "intent": "A fictional equipment checkout service (Yard Loan) records inventory mutations in Storage Core and, in the same single-partition transaction, appends an audit row and enqueues a transactional mail delivery job.", + "packages": [ + "@pegma/storage-core", + "@pegma/audit", + "@pegma/mail", + "@pegma/spine" + ], + "adapters": ["memory"], + "hostResponsibilities": [ + "Collection declarations", + "Transaction boundary", + "Outbox collection in host storage", + "Mail provider and delivery worker schedule" + ], + "nonGoals": [ + "Mail-owned outbox store", + "Audit-owned store", + "Cross-partition transactions" + ], + "antiPatterns": [ + "Send email after commit without an outbox job in the same transaction", + "Audit write outside the caller transact" + ], + "fixture": { + "kind": "pending", + "citation": "docs/catalog/RECIPE_BACKLOG.md#p2--storage-audit-mail-outbox-storage--auditmail-pattern", + "status": "pending" + }, + "capabilityTags": ["storage", "audit", "mail_transactional"], + "requiresPublished": ["storage-core", "audit", "mail", "spine"], + "backlogPriority": 2 + }, + { + "id": "inbound-webhook-receipts", + "intent": "A fictional donation platform (Copper Plate) records inbound provider webhook receipts with idempotent dedup and poison quarantine. Receipts hold ids and counters, never payloads.", + "packages": ["@pegma/webhooks", "@pegma/storage-core", "@pegma/spine"], + "adapters": [], + "hostResponsibilities": [ + "HTTP endpoint", + "Provider signature verification", + "Storage for the receipt ledger" + ], + "nonGoals": ["Exactly-once delivery", "Payload archival in the receipt ledger"], + "antiPatterns": [ + "Claiming exactly-once processing", + "Storing full webhook bodies in receipts" + ], + "fixture": { + "kind": "pending", + "citation": "docs/catalog/RECIPE_BACKLOG.md#d1--inbound-webhook-receipts-when-pegmawebhooks-is-published", + "status": "none" + }, + "capabilityTags": ["webhooks_inbound"], + "requiresPublished": ["webhooks", "storage-core", "spine"], + "backlogPriority": 90 + } + ] +} diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts new file mode 100644 index 0000000..e587e2e --- /dev/null +++ b/src/data/catalog-schema.test.ts @@ -0,0 +1,76 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { + CATALOG_SCHEMA_VERSION, + isPublishUsable, + publishedPackageNames, + type CatalogComponent, + type CompositionCatalog, +} from './catalog-schema'; + +const here = dirname(fileURLToPath(import.meta.url)); +const examplePath = join(here, '../../docs/catalog/example-catalog.json'); + +function loadExample(): CompositionCatalog { + return JSON.parse(readFileSync(examplePath, 'utf8')) as CompositionCatalog; +} + +describe('composition catalog schema', () => { + it('pins schema version 0.1.0', () => { + expect(CATALOG_SCHEMA_VERSION).toBe('0.1.0'); + }); + + it('loads the example catalog with required top-level fields', () => { + const catalog = loadExample(); + expect(catalog.schemaVersion).toBe(CATALOG_SCHEMA_VERSION); + expect(catalog.generatedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + expect(catalog.components.length).toBeGreaterThan(0); + expect(catalog.recipes.length).toBeGreaterThan(0); + }); + + it('marks unpublished packages unusable for production assembly', () => { + const catalog = loadExample(); + const webhooks = catalog.components.find((c) => c.id === 'webhooks'); + expect(webhooks).toBeDefined(); + expect(webhooks!.publishUsability).toBe('unpublished'); + expect(isPublishUsable(webhooks!)).toBe(false); + expect(publishedPackageNames(webhooks!)).toEqual([]); + }); + + it('exposes published package names only when versioned and published', () => { + const storage: CatalogComponent = loadExample().components.find( + (c) => c.id === 'storage-core', + )!; + expect(isPublishUsable(storage)).toBe(true); + expect(publishedPackageNames(storage)).toEqual( + expect.arrayContaining([ + '@pegma/storage-core', + '@pegma/storage-azure-tables', + '@pegma/storage-cloudflare-d1', + ]), + ); + }); + + it('keeps recipe intents synthetic (no commercial host names)', () => { + const catalog = loadExample(); + const banned = [/retiregolden/i, /pegma\.dev\/account/i]; + for (const recipe of catalog.recipes) { + for (const pattern of banned) { + expect(recipe.intent).not.toMatch(pattern); + } + expect(recipe.intent.length).toBeGreaterThan(40); + expect(recipe.requiresPublished.length).toBeGreaterThan(0); + } + }); + + it('orders priority recipes ahead of deferred unpublished ones', () => { + const catalog = loadExample(); + const byId = Object.fromEntries(catalog.recipes.map((r) => [r.id, r])); + expect(byId['cf-passkey-accounts']?.backlogPriority).toBe(1); + expect(byId['storage-audit-mail-outbox']?.backlogPriority).toBe(2); + expect(byId['inbound-webhook-receipts']?.backlogPriority).toBeGreaterThan(2); + expect(byId['inbound-webhook-receipts']?.fixture.status).toBe('none'); + }); +}); diff --git a/src/data/catalog-schema.ts b/src/data/catalog-schema.ts new file mode 100644 index 0000000..d661881 --- /dev/null +++ b/src/data/catalog-schema.ts @@ -0,0 +1,214 @@ +/** + * Composition catalog schema for agent-facing package selection and wiring. + * + * Phase 0 defines types only. Phase 1 emits a concrete `catalog.json` from the + * component registry, plan aggregation, and published version facts. + * + * Design rules (docs/AGENT_ASSEMBLY_PLAN.md): + * - Catalog is the source of truth; HTML, llms.txt, skill, and MCP are clients. + * - Progressive disclosure: list → detail → recipe → fixture citation. + * - Recipes are synthetic and must cite CI-tested fixtures when code is shown. + * - Unpublished packages are unusable for production assembly. + * - Exact 0.x pins when a version is known; never invent versions. + */ + +/** Semver-ish schema id for the catalog document itself (not package versions). */ +export const CATALOG_SCHEMA_VERSION = '0.1.0' as const; + +export type CatalogComponentStatus = + | 'published' + | 'in_development' + | 'planned'; + +/** + * Whether agents may select this package for a production host assembly. + * Distinct from component `status`: a component can be "in development" with + * no npm packages, or published with some packages still missing. + */ +export type PublishUsability = 'usable' | 'unpublished' | 'partial'; + +/** How a dependency relates to another catalog component. */ +export type DependencyKind = + | 'requires' + | 'optional' + | 'composes_with'; + +/** Where a recipe's wiring sketch is allowed to come from. */ +export type RecipeFixtureKind = + | 'package_readme' + | 'conformance' + | 'recipe_package' + | 'scaffold' + | 'pending'; + +export type RecipeFixtureStatus = 'green' | 'pending' | 'none'; + +/** + * Stable capability tags used by `plan_composition` (Phase 4) and the skill. + * Prefer structured flags over free text so recommendations stay deterministic. + */ +export type CapabilityTag = + | 'accounts' + | 'passkeys' + | 'email_codes' + | 'sessions' + | 'authorization' + | 'storage' + | 'audit' + | 'mail_transactional' + | 'rate_limit_durable' + | 'rate_limit_memory' + | 'webhooks_inbound' + | 'support_queue' + | 'health' + | 'logging' + | 'events_in_process' + | 'cloudflare' + | 'azure' + | 'static_host'; + +export interface CatalogPackage { + /** npm package name, e.g. `@pegma/spine` */ + readonly name: string; + /** + * Exact published version when known (e.g. `0.1.1`). + * `null` means not published or version not yet resolved at compile time. + */ + readonly version: string | null; + /** False when the package must not be selected for production assembly. */ + readonly published: boolean; + /** npm package page when published */ + readonly npmUrl?: string; +} + +export interface CatalogDependency { + /** Target component id (same as `CatalogComponent.id`) */ + readonly componentId: string; + readonly kind: DependencyKind; + /** Short note for agents — not a substitute for the README */ + readonly note?: string; +} + +export interface CatalogAdapter { + /** Stable id within the component, e.g. `cloudflare-d1` */ + readonly id: string; + /** Implementing package when it exists */ + readonly packageName?: string; + /** Hosting surface this adapter targets */ + readonly host: 'cloudflare' | 'azure' | 'memory' | 'other'; + /** When an agent should pick this adapter */ + readonly when: string; +} + +export interface CatalogLinks { + readonly githubRepo: string; + readonly plan?: string; + readonly readme?: string; + /** Primary npm package URL when one package is the entry point */ + readonly npm?: string; +} + +/** + * One stack component in the composition catalog. + * Extends the human registry (`PegmaComponent`) with agent-oriented fields. + */ +export interface CatalogComponent { + /** Stable id; matches GitHub repo short name under pegma-dev by convention */ + readonly id: string; + readonly title: string; + readonly repo: string; + readonly packages: readonly CatalogPackage[]; + readonly status: CatalogComponentStatus; + /** + * Aggregate publish signal for production assembly. + * - usable: at least one core package is published with a pin + * - unpublished: nothing agents should depend on yet + * - partial: some packages published, others not (list them in packages[]) + */ + readonly publishUsability: PublishUsability; + readonly summary: string; + readonly owns: readonly string[]; + readonly refuses: readonly string[]; + /** Composition dependencies on other catalog components */ + readonly dependencies: readonly CatalogDependency[]; + /** Hosting adapters and when each applies */ + readonly adapters: readonly CatalogAdapter[]; + /** What the host application must supply (cookies, secrets, DNS, UI, …) */ + readonly hostMustProvide: readonly string[]; + readonly capabilityTags: readonly CapabilityTag[]; + /** Recipe ids that use this component */ + readonly recipeIds: readonly string[]; + readonly links: CatalogLinks; + /** + * Plain-language position from the hand registry / plan snapshot. + * Prefer compiled `stage` from PROJECT_PLAN when Phase 1 has it. + */ + readonly now?: string; + /** Stage paragraph from plan aggregation when available */ + readonly stage?: string; +} + +export interface RecipeFixtureCitation { + readonly kind: RecipeFixtureKind; + /** + * Public path or URL agents can open. Must not point at private hosts + * or commercial product internals. + */ + readonly citation: string; + readonly status: RecipeFixtureStatus; +} + +/** + * A named composition intent. Product shape is synthetic on purpose; + * wiring sketches only appear when `fixture.status === 'green'`. + */ +export interface CatalogRecipe { + readonly id: string; + /** One-paragraph synthetic product shape — never a real commercial product */ + readonly intent: string; + /** Package names (and optional pins once fixtures exist) */ + readonly packages: readonly string[]; + /** Adapter ids selected for this recipe */ + readonly adapters: readonly string[]; + readonly hostResponsibilities: readonly string[]; + readonly nonGoals: readonly string[]; + /** Anti-patterns agents must not invent */ + readonly antiPatterns: readonly string[]; + readonly fixture: RecipeFixtureCitation; + readonly capabilityTags: readonly CapabilityTag[]; + /** + * Component ids that must be publish-usable before this recipe is offered + * for production assembly. + */ + readonly requiresPublished: readonly string[]; + /** + * Priority for the Phase 0 backlog (1 = ship first). + * Omitted or zero in the compiled catalog once fixtures exist. + */ + readonly backlogPriority?: number; +} + +/** + * Top-level machine-readable composition catalog. + * Published at a stable URL in Phase 1 (static `catalog.json`). + */ +export interface CompositionCatalog { + readonly schemaVersion: typeof CATALOG_SCHEMA_VERSION | string; + /** ISO-8601 generation timestamp */ + readonly generatedAt: string; + /** Calendar date of the hand-maintained registry snapshot when used as input */ + readonly snapshotDate?: string; + readonly components: readonly CatalogComponent[]; + readonly recipes: readonly CatalogRecipe[]; +} + +/** Type guard helpers for compile and MCP validation (Phase 1+). */ +export function isPublishUsable(component: CatalogComponent): boolean { + return component.publishUsability === 'usable' || component.publishUsability === 'partial'; +} + +export function publishedPackageNames( + component: CatalogComponent, +): readonly string[] { + return component.packages.filter((p) => p.published && p.version).map((p) => p.name); +} diff --git a/vitest.config.ts b/vitest.config.ts index c085761..4c058b7 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { - include: ['worker/src/**/*.test.ts'], + include: ['worker/src/**/*.test.ts', 'src/**/*.test.ts'], exclude: ['**/node_modules/**', '**/*.d1.test.ts'], testTimeout: 30_000, }, From 2b95fccd538cf508b38c01c77b3f470f71834b0a Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 28 Jul 2026 23:51:01 -0400 Subject: [PATCH 2/6] Address Codex and Copilot review on catalog Phase 0. Quote fixture status literals, align SCHEMA.md types, pin schemaVersion to the 0.1.0 constant, mark hand registry status as a compile gap, and allow empty requiresPublished for brochure-style recipes. --- docs/catalog/GAP_INVENTORY.md | 3 ++- docs/catalog/RECIPE_BACKLOG.md | 2 +- docs/catalog/SCHEMA.md | 2 +- src/data/catalog-schema.test.ts | 7 ++++++- src/data/catalog-schema.ts | 4 ++-- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/catalog/GAP_INVENTORY.md b/docs/catalog/GAP_INVENTORY.md index 3afab4a..ad6d03c 100644 --- a/docs/catalog/GAP_INVENTORY.md +++ b/docs/catalog/GAP_INVENTORY.md @@ -14,7 +14,7 @@ surfaces against the composition catalog schema | `repo` | yes | `id` + `repo` | No separate stable `id` field (today `repo` is the id) | | `title` | yes | `title` | — | | `packages` | yes (`string[]`) | `packages[]` with version/published | No per-package version or publish flag | -| `status` | yes | `status` | No `publishUsability` aggregate | +| `status` | yes | `status` | Hand-maintained only — **do not trust as sole authority** (see below); also no `publishUsability` aggregate | | `summary` | yes | `summary` | — | | `owns` | yes | `owns` | — | | `refuses` | yes | `refuses` | — | @@ -25,6 +25,7 @@ surfaces against the composition catalog schema | Schema field | Why agents need it | Suggested Phase 1 source | | --- | --- | --- | +| `status` | Lifecycle without registry drift | Prefer mapping from each repo’s `PROJECT_PLAN.md` stage (same discipline as the compiled roadmap); hand registry is fallback only when the plan is unreachable | | `packages[].version` | Exact 0.x pins | npm / release projection / registry snapshot with precedence | | `packages[].published` | Skip unpublished packages | npm existence + hand status | | `publishUsability` | Fast list filter | Derived from package flags | diff --git a/docs/catalog/RECIPE_BACKLOG.md b/docs/catalog/RECIPE_BACKLOG.md index 1d0c669..c1f4398 100644 --- a/docs/catalog/RECIPE_BACKLOG.md +++ b/docs/catalog/RECIPE_BACKLOG.md @@ -5,7 +5,7 @@ Prioritized composition intents for the agent catalog. Every intent is describe a commercial host’s routes, tenancy, or operations. **Fixture rule:** catalog and `/examples` may only quote wiring that exists in -a public, CI-tested source (`fixture.status === green`). Until then, recipes +a public, CI-tested source (`fixture.status === 'green'`). Until then, recipes appear as intent metadata only. **Publish rule:** recipes whose `requiresPublished` set is not fully usable diff --git a/docs/catalog/SCHEMA.md b/docs/catalog/SCHEMA.md index c02e801..a7d8fcb 100644 --- a/docs/catalog/SCHEMA.md +++ b/docs/catalog/SCHEMA.md @@ -98,7 +98,7 @@ CompositionCatalog | `nonGoals` | string[] | Out of scope for the recipe | | `antiPatterns` | string[] | What not to invent | | `fixture` | object | Citation + kind + status | -| `capabilityTags` | tags | Overlap with component tags for planning | +| `capabilityTags` | `CapabilityTag[]` | Overlap with component tags for planning | | `requiresPublished` | string[] | Component ids that must be usable | | `backlogPriority` | number? | Phase 0 ordering only (1 = first) | diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts index e587e2e..354be5f 100644 --- a/src/data/catalog-schema.test.ts +++ b/src/data/catalog-schema.test.ts @@ -61,7 +61,12 @@ describe('composition catalog schema', () => { expect(recipe.intent).not.toMatch(pattern); } expect(recipe.intent.length).toBeGreaterThan(40); - expect(recipe.requiresPublished.length).toBeGreaterThan(0); + // Empty requiresPublished is valid (e.g. static-brochure-minimal). + expect(Array.isArray(recipe.requiresPublished)).toBe(true); + for (const id of recipe.requiresPublished) { + expect(typeof id).toBe('string'); + expect(id.length).toBeGreaterThan(0); + } } }); diff --git a/src/data/catalog-schema.ts b/src/data/catalog-schema.ts index d661881..17e18dc 100644 --- a/src/data/catalog-schema.ts +++ b/src/data/catalog-schema.ts @@ -193,7 +193,7 @@ export interface CatalogRecipe { * Published at a stable URL in Phase 1 (static `catalog.json`). */ export interface CompositionCatalog { - readonly schemaVersion: typeof CATALOG_SCHEMA_VERSION | string; + readonly schemaVersion: typeof CATALOG_SCHEMA_VERSION; /** ISO-8601 generation timestamp */ readonly generatedAt: string; /** Calendar date of the hand-maintained registry snapshot when used as input */ @@ -202,7 +202,7 @@ export interface CompositionCatalog { readonly recipes: readonly CatalogRecipe[]; } -/** Type guard helpers for compile and MCP validation (Phase 1+). */ +/** Boolean helpers for compile and MCP validation (Phase 1+). Not type predicates. */ export function isPublishUsable(component: CatalogComponent): boolean { return component.publishUsability === 'usable' || component.publishUsability === 'partial'; } From 9b0cb62243d57a16ad8c071124fdbccec1df9478 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 00:03:30 -0400 Subject: [PATCH 3/6] Tighten Phase 0 publish gates and structural catalog validation. Drop the hand-copied component usability matrix from the gap inventory so status stays compiled. Make isPublishUsable strict, add package-level and recipe package readiness helpers, and parse example-catalog.json as unknown with structural checks. --- docs/catalog/GAP_INVENTORY.md | 32 ++-- src/data/catalog-schema.test.ts | 266 +++++++++++++++++++++++++++++++- src/data/catalog-schema.ts | 36 ++++- 3 files changed, 313 insertions(+), 21 deletions(-) diff --git a/docs/catalog/GAP_INVENTORY.md b/docs/catalog/GAP_INVENTORY.md index ad6d03c..b28066f 100644 --- a/docs/catalog/GAP_INVENTORY.md +++ b/docs/catalog/GAP_INVENTORY.md @@ -49,25 +49,23 @@ surfaces against the composition catalog schema | `worker/src/release-catalog.ts` | Release webhook allowlist / display order | Repo id map only — reuse order, not package facts | | Component READMEs + conformance | Canonical package truth | Scattered; catalog must summarize and link, not fork | -## Published vs assembly-usable (registry prose, 2026-07-28) +## Publish / assembly-usable gate (compiled, not hand-copied) -Agents must treat **npm publication** as the production gate. Hand status alone -is insufficient when packages remain unpublished. +Do **not** maintain a per-component “usable today?” table in this document. +That would duplicate lifecycle facts that AGENTS.md requires to be **compiled** +from component plans (and package-version authority), the same discipline as +the roadmap. -| Component | Registry status | Assembly-usable today? | Notes | -| --- | --- | --- | --- | -| spine | published | yes | Pin from registry/npm (e.g. 0.1.1) | -| storage-core | published | yes | Core + azure-tables + cloudflare-d1 | -| authorization-core | published | yes | Multiple `@pegma/authorization-*` packages | -| audit | published | yes | 0.1.0; needs caller storage transaction | -| health | published | yes | | -| sessions | published | yes | | -| mail | published | yes | | -| identity | published | yes | | -| rate-limit | published | yes | | -| logger-adapters | published | yes | | -| support-desk | in development | **no** | Packages unpublished | -| webhooks | in development | **no** | Unpublished (local vendor tarball on this site only) | +Phase 1 must set each catalog component’s `status`, `publishUsability`, and +`packages[].published` / `packages[].version` from: + +1. Each repo’s `PROJECT_PLAN.md` stage (status / stage prose) +2. Version authority precedence (release-projection Store → npm at compile time) +3. Never from parsing `now` prose in `components.ts` + +Until that compile exists, agents should treat only **npm-published** packages +with exact pins as production-assembly candidates, and treat anything still +unpublished on npm (including local vendor tarballs) as unusable. ## Decisions locked for Phase 1 compile (from open questions) diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts index 354be5f..4af405a 100644 --- a/src/data/catalog-schema.test.ts +++ b/src/data/catalog-schema.test.ts @@ -4,17 +4,209 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { CATALOG_SCHEMA_VERSION, + isPackagePublished, isPublishUsable, publishedPackageNames, + recipePackagesReady, + type CatalogAdapter, type CatalogComponent, + type CatalogComponentStatus, + type CatalogPackage, + type CatalogRecipe, type CompositionCatalog, + type PublishUsability, + type RecipeFixtureStatus, } from './catalog-schema'; const here = dirname(fileURLToPath(import.meta.url)); const examplePath = join(here, '../../docs/catalog/example-catalog.json'); +const COMPONENT_STATUSES = new Set([ + 'published', + 'in_development', + 'planned', +]); +const PUBLISH_USABILITY = new Set([ + 'usable', + 'unpublished', + 'partial', +]); +const FIXTURE_STATUSES = new Set([ + 'green', + 'pending', + 'none', +]); +const ADAPTER_HOSTS = new Set(['cloudflare', 'azure', 'memory', 'other']); + +function assertString(value: unknown, label: string): asserts value is string { + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`${label} must be a non-empty string`); + } +} + +function assertStringArray(value: unknown, label: string): asserts value is string[] { + if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) { + throw new Error(`${label} must be a string array`); + } +} + +function parsePackage(raw: unknown, label: string): CatalogPackage { + if (!raw || typeof raw !== 'object') throw new Error(`${label} must be an object`); + const p = raw as Record; + assertString(p.name, `${label}.name`); + if (!(typeof p.version === 'string' || p.version === null)) { + throw new Error(`${label}.version must be string or null`); + } + if (typeof p.published !== 'boolean') { + throw new Error(`${label}.published must be boolean`); + } + return { + name: p.name, + version: p.version, + published: p.published, + ...(typeof p.npmUrl === 'string' ? { npmUrl: p.npmUrl } : {}), + }; +} + +function parseAdapter(raw: unknown, label: string): CatalogAdapter { + if (!raw || typeof raw !== 'object') throw new Error(`${label} must be an object`); + const a = raw as Record; + assertString(a.id, `${label}.id`); + assertString(a.host, `${label}.host`); + if (!ADAPTER_HOSTS.has(a.host)) throw new Error(`${label}.host invalid`); + assertString(a.when, `${label}.when`); + return { + id: a.id, + host: a.host as CatalogAdapter['host'], + when: a.when, + ...(typeof a.packageName === 'string' ? { packageName: a.packageName } : {}), + }; +} + +function parseComponent(raw: unknown, index: number): CatalogComponent { + if (!raw || typeof raw !== 'object') { + throw new Error(`components[${index}] must be an object`); + } + const c = raw as Record; + assertString(c.id, `components[${index}].id`); + assertString(c.title, `components[${index}].title`); + assertString(c.repo, `components[${index}].repo`); + assertString(c.summary, `components[${index}].summary`); + if (typeof c.status !== 'string' || !COMPONENT_STATUSES.has(c.status as CatalogComponentStatus)) { + throw new Error(`components[${index}].status invalid`); + } + if ( + typeof c.publishUsability !== 'string' || + !PUBLISH_USABILITY.has(c.publishUsability as PublishUsability) + ) { + throw new Error(`components[${index}].publishUsability invalid`); + } + if (!Array.isArray(c.packages)) throw new Error(`components[${index}].packages must be array`); + if (!Array.isArray(c.dependencies)) { + throw new Error(`components[${index}].dependencies must be array`); + } + if (!Array.isArray(c.adapters)) throw new Error(`components[${index}].adapters must be array`); + assertStringArray(c.owns, `components[${index}].owns`); + assertStringArray(c.refuses, `components[${index}].refuses`); + assertStringArray(c.hostMustProvide, `components[${index}].hostMustProvide`); + assertStringArray(c.capabilityTags, `components[${index}].capabilityTags`); + assertStringArray(c.recipeIds, `components[${index}].recipeIds`); + if (!c.links || typeof c.links !== 'object') { + throw new Error(`components[${index}].links must be object`); + } + const links = c.links as Record; + assertString(links.githubRepo, `components[${index}].links.githubRepo`); + + return { + id: c.id, + title: c.title, + repo: c.repo, + packages: c.packages.map((p, i) => parsePackage(p, `components[${index}].packages[${i}]`)), + status: c.status as CatalogComponentStatus, + publishUsability: c.publishUsability as PublishUsability, + summary: c.summary, + owns: c.owns, + refuses: c.refuses, + dependencies: c.dependencies as CatalogComponent['dependencies'], + adapters: c.adapters.map((a, i) => parseAdapter(a, `components[${index}].adapters[${i}]`)), + hostMustProvide: c.hostMustProvide, + capabilityTags: c.capabilityTags as CatalogComponent['capabilityTags'], + recipeIds: c.recipeIds, + links: { + githubRepo: links.githubRepo, + ...(typeof links.plan === 'string' ? { plan: links.plan } : {}), + ...(typeof links.readme === 'string' ? { readme: links.readme } : {}), + ...(typeof links.npm === 'string' ? { npm: links.npm } : {}), + }, + ...(typeof c.now === 'string' ? { now: c.now } : {}), + ...(typeof c.stage === 'string' ? { stage: c.stage } : {}), + }; +} + +function parseRecipe(raw: unknown, index: number): CatalogRecipe { + if (!raw || typeof raw !== 'object') { + throw new Error(`recipes[${index}] must be an object`); + } + const r = raw as Record; + assertString(r.id, `recipes[${index}].id`); + assertString(r.intent, `recipes[${index}].intent`); + assertStringArray(r.packages, `recipes[${index}].packages`); + assertStringArray(r.adapters, `recipes[${index}].adapters`); + assertStringArray(r.hostResponsibilities, `recipes[${index}].hostResponsibilities`); + assertStringArray(r.nonGoals, `recipes[${index}].nonGoals`); + assertStringArray(r.antiPatterns, `recipes[${index}].antiPatterns`); + assertStringArray(r.capabilityTags, `recipes[${index}].capabilityTags`); + assertStringArray(r.requiresPublished, `recipes[${index}].requiresPublished`); + if (!r.fixture || typeof r.fixture !== 'object') { + throw new Error(`recipes[${index}].fixture must be object`); + } + const f = r.fixture as Record; + assertString(f.kind, `recipes[${index}].fixture.kind`); + assertString(f.citation, `recipes[${index}].fixture.citation`); + if (typeof f.status !== 'string' || !FIXTURE_STATUSES.has(f.status as RecipeFixtureStatus)) { + throw new Error(`recipes[${index}].fixture.status invalid`); + } + return { + id: r.id, + intent: r.intent, + packages: r.packages, + adapters: r.adapters, + hostResponsibilities: r.hostResponsibilities, + nonGoals: r.nonGoals, + antiPatterns: r.antiPatterns, + fixture: { + kind: f.kind as CatalogRecipe['fixture']['kind'], + citation: f.citation, + status: f.status as RecipeFixtureStatus, + }, + capabilityTags: r.capabilityTags as CatalogRecipe['capabilityTags'], + requiresPublished: r.requiresPublished, + ...(typeof r.backlogPriority === 'number' ? { backlogPriority: r.backlogPriority } : {}), + }; +} + +/** Structural validation — unknown JSON must match CompositionCatalog shape. */ +export function parseCompositionCatalog(raw: unknown): CompositionCatalog { + if (!raw || typeof raw !== 'object') throw new Error('catalog must be an object'); + const doc = raw as Record; + if (doc.schemaVersion !== CATALOG_SCHEMA_VERSION) { + throw new Error(`schemaVersion must be ${CATALOG_SCHEMA_VERSION}`); + } + assertString(doc.generatedAt, 'generatedAt'); + if (!Array.isArray(doc.components)) throw new Error('components must be an array'); + if (!Array.isArray(doc.recipes)) throw new Error('recipes must be an array'); + return { + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: doc.generatedAt, + ...(typeof doc.snapshotDate === 'string' ? { snapshotDate: doc.snapshotDate } : {}), + components: doc.components.map(parseComponent), + recipes: doc.recipes.map(parseRecipe), + }; +} + function loadExample(): CompositionCatalog { - return JSON.parse(readFileSync(examplePath, 'utf8')) as CompositionCatalog; + const raw: unknown = JSON.parse(readFileSync(examplePath, 'utf8')); + return parseCompositionCatalog(raw); } describe('composition catalog schema', () => { @@ -22,7 +214,7 @@ describe('composition catalog schema', () => { expect(CATALOG_SCHEMA_VERSION).toBe('0.1.0'); }); - it('loads the example catalog with required top-level fields', () => { + it('structurally validates the example catalog', () => { const catalog = loadExample(); expect(catalog.schemaVersion).toBe(CATALOG_SCHEMA_VERSION); expect(catalog.generatedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); @@ -30,6 +222,18 @@ describe('composition catalog schema', () => { expect(catalog.recipes.length).toBeGreaterThan(0); }); + it('rejects example JSON missing required fields', () => { + expect(() => parseCompositionCatalog({ schemaVersion: '0.1.0' })).toThrow(/generatedAt/); + expect(() => + parseCompositionCatalog({ + schemaVersion: '0.2.0', + generatedAt: '2026-07-28T00:00:00.000Z', + components: [], + recipes: [], + }), + ).toThrow(/schemaVersion/); + }); + it('marks unpublished packages unusable for production assembly', () => { const catalog = loadExample(); const webhooks = catalog.components.find((c) => c.id === 'webhooks'); @@ -37,6 +241,7 @@ describe('composition catalog schema', () => { expect(webhooks!.publishUsability).toBe('unpublished'); expect(isPublishUsable(webhooks!)).toBe(false); expect(publishedPackageNames(webhooks!)).toEqual([]); + expect(isPackagePublished(webhooks!, '@pegma/webhooks')).toBe(false); }); it('exposes published package names only when versioned and published', () => { @@ -53,6 +258,63 @@ describe('composition catalog schema', () => { ); }); + it('gates recipe readiness on package pins, not partial components alone', () => { + const catalog = loadExample(); + const inbound = catalog.recipes.find((r) => r.id === 'inbound-webhook-receipts')!; + expect(recipePackagesReady(catalog, inbound)).toBe(false); + + // Partial component with only some packages published must not pass a + // recipe that names an unpublished sibling package. + const partialCatalog: CompositionCatalog = { + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: '2026-07-28T00:00:00.000Z', + components: [ + { + id: 'demo', + title: 'Demo', + repo: 'demo', + packages: [ + { name: '@pegma/demo-core', version: '0.1.0', published: true }, + { name: '@pegma/demo-extra', version: null, published: false }, + ], + status: 'published', + publishUsability: 'partial', + summary: 'partial demo', + owns: [], + refuses: [], + dependencies: [], + adapters: [], + hostMustProvide: [], + capabilityTags: [], + recipeIds: [], + links: { githubRepo: 'https://github.com/pegma-dev/demo' }, + }, + ], + recipes: [ + { + id: 'needs-extra', + intent: 'A fictional partial-package case that asks for the unpublished sibling.', + packages: ['@pegma/demo-core', '@pegma/demo-extra'], + adapters: [], + hostResponsibilities: [], + nonGoals: [], + antiPatterns: [], + fixture: { kind: 'pending', citation: 'n/a', status: 'pending' }, + capabilityTags: [], + requiresPublished: ['demo'], + }, + ], + }; + expect(isPublishUsable(partialCatalog.components[0]!)).toBe(false); + expect(recipePackagesReady(partialCatalog, partialCatalog.recipes[0]!)).toBe(false); + expect( + recipePackagesReady(partialCatalog, { + ...partialCatalog.recipes[0]!, + packages: ['@pegma/demo-core'], + }), + ).toBe(true); + }); + it('keeps recipe intents synthetic (no commercial host names)', () => { const catalog = loadExample(); const banned = [/retiregolden/i, /pegma\.dev\/account/i]; diff --git a/src/data/catalog-schema.ts b/src/data/catalog-schema.ts index 17e18dc..15f5691 100644 --- a/src/data/catalog-schema.ts +++ b/src/data/catalog-schema.ts @@ -202,9 +202,23 @@ export interface CompositionCatalog { readonly recipes: readonly CatalogRecipe[]; } -/** Boolean helpers for compile and MCP validation (Phase 1+). Not type predicates. */ +/** + * Boolean helpers for compile and MCP validation (Phase 1+). Not type predicates. + * + * Component-level `publishUsability === 'partial'` means *some* packages are + * published. Production gates must still check the specific packages a recipe + * names — use `isPackagePublished` / `recipePackagesReady`. + */ export function isPublishUsable(component: CatalogComponent): boolean { - return component.publishUsability === 'usable' || component.publishUsability === 'partial'; + return component.publishUsability === 'usable'; +} + +export function isPackagePublished( + component: CatalogComponent, + packageName: string, +): boolean { + const pkg = component.packages.find((p) => p.name === packageName); + return Boolean(pkg?.published && pkg.version); } export function publishedPackageNames( @@ -212,3 +226,21 @@ export function publishedPackageNames( ): readonly string[] { return component.packages.filter((p) => p.published && p.version).map((p) => p.name); } + +/** + * True when every package named by the recipe is published with a version pin + * somewhere in the catalog. Empty `recipe.packages` is ready (brochure / no-op). + */ +export function recipePackagesReady( + catalog: CompositionCatalog, + recipe: CatalogRecipe, +): boolean { + if (recipe.packages.length === 0) return true; + for (const name of recipe.packages) { + const owner = catalog.components.find((c) => + c.packages.some((p) => p.name === name), + ); + if (!owner || !isPackagePublished(owner, name)) return false; + } + return true; +} From 363f4aaffdd09fd8480a795d7f67956d7023c17d Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 00:07:59 -0400 Subject: [PATCH 4/6] Support name@version recipe pins and validate catalog dependencies. recipePackagesReady parses scoped package specifiers so pinned recipes match catalog package names, and parseCompositionCatalog checks dependency shape and DependencyKind instead of casting. --- docs/catalog/SCHEMA.md | 2 +- src/data/catalog-schema.test.ts | 83 ++++++++++++++++++++++++++++++++- src/data/catalog-schema.ts | 33 ++++++++++++- 3 files changed, 114 insertions(+), 4 deletions(-) diff --git a/docs/catalog/SCHEMA.md b/docs/catalog/SCHEMA.md index a7d8fcb..5ea7a7f 100644 --- a/docs/catalog/SCHEMA.md +++ b/docs/catalog/SCHEMA.md @@ -92,7 +92,7 @@ CompositionCatalog | --- | --- | --- | | `id` | string | Stable recipe id | | `intent` | string | Synthetic product shape (one paragraph) | -| `packages` | string[] | Package names (pins appear when fixtures exist) | +| `packages` | string[] | Package names, optionally pinned as `name@version` | | `adapters` | string[] | Selected adapter ids | | `hostResponsibilities` | string[] | Host-owned work | | `nonGoals` | string[] | Out of scope for the recipe | diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts index 4af405a..d9b0317 100644 --- a/src/data/catalog-schema.test.ts +++ b/src/data/catalog-schema.test.ts @@ -8,12 +8,15 @@ import { isPublishUsable, publishedPackageNames, recipePackagesReady, + parsePackageSpecifier, type CatalogAdapter, type CatalogComponent, type CatalogComponentStatus, + type CatalogDependency, type CatalogPackage, type CatalogRecipe, type CompositionCatalog, + type DependencyKind, type PublishUsability, type RecipeFixtureStatus, } from './catalog-schema'; @@ -37,6 +40,11 @@ const FIXTURE_STATUSES = new Set([ 'none', ]); const ADAPTER_HOSTS = new Set(['cloudflare', 'azure', 'memory', 'other']); +const DEPENDENCY_KINDS = new Set([ + 'requires', + 'optional', + 'composes_with', +]); function assertString(value: unknown, label: string): asserts value is string { if (typeof value !== 'string' || value.length === 0) { @@ -83,6 +91,21 @@ function parseAdapter(raw: unknown, label: string): CatalogAdapter { }; } +function parseDependency(raw: unknown, label: string): CatalogDependency { + if (!raw || typeof raw !== 'object') throw new Error(`${label} must be an object`); + const d = raw as Record; + assertString(d.componentId, `${label}.componentId`); + assertString(d.kind, `${label}.kind`); + if (!DEPENDENCY_KINDS.has(d.kind as DependencyKind)) { + throw new Error(`${label}.kind invalid`); + } + return { + componentId: d.componentId, + kind: d.kind as DependencyKind, + ...(typeof d.note === 'string' ? { note: d.note } : {}), + }; +} + function parseComponent(raw: unknown, index: number): CatalogComponent { if (!raw || typeof raw !== 'object') { throw new Error(`components[${index}] must be an object`); @@ -127,7 +150,9 @@ function parseComponent(raw: unknown, index: number): CatalogComponent { summary: c.summary, owns: c.owns, refuses: c.refuses, - dependencies: c.dependencies as CatalogComponent['dependencies'], + dependencies: c.dependencies.map((d, i) => + parseDependency(d, `components[${index}].dependencies[${i}]`), + ), adapters: c.adapters.map((a, i) => parseAdapter(a, `components[${index}].adapters[${i}]`)), hostMustProvide: c.hostMustProvide, capabilityTags: c.capabilityTags as CatalogComponent['capabilityTags'], @@ -313,6 +338,62 @@ describe('composition catalog schema', () => { packages: ['@pegma/demo-core'], }), ).toBe(true); + expect( + recipePackagesReady(partialCatalog, { + ...partialCatalog.recipes[0]!, + packages: ['@pegma/demo-core@0.1.0'], + }), + ).toBe(true); + expect( + recipePackagesReady(partialCatalog, { + ...partialCatalog.recipes[0]!, + packages: ['@pegma/demo-core@9.9.9'], + }), + ).toBe(false); + }); + + it('parses scoped package@version specifiers', () => { + expect(parsePackageSpecifier('@pegma/spine@0.1.1')).toEqual({ + name: '@pegma/spine', + version: '0.1.1', + }); + expect(parsePackageSpecifier('@pegma/spine')).toEqual({ + name: '@pegma/spine', + version: null, + }); + expect(parsePackageSpecifier('left-pad@1.0.0')).toEqual({ + name: 'left-pad', + version: '1.0.0', + }); + }); + + it('rejects malformed dependency entries', () => { + expect(() => + parseCompositionCatalog({ + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: '2026-07-28T00:00:00.000Z', + components: [ + { + id: 'x', + title: 'X', + repo: 'x', + packages: [], + status: 'published', + publishUsability: 'usable', + summary: 'x', + owns: [], + refuses: [], + dependencies: ['spine'], + adapters: [], + hostMustProvide: [], + capabilityTags: [], + recipeIds: [], + links: { githubRepo: 'https://github.com/pegma-dev/x' }, + }, + ], + recipes: [], + }), + ).toThrow(/dependencies\[0\]/); }); it('keeps recipe intents synthetic (no commercial host names)', () => { diff --git a/src/data/catalog-schema.ts b/src/data/catalog-schema.ts index 15f5691..91bc0f7 100644 --- a/src/data/catalog-schema.ts +++ b/src/data/catalog-schema.ts @@ -166,7 +166,7 @@ export interface CatalogRecipe { readonly id: string; /** One-paragraph synthetic product shape — never a real commercial product */ readonly intent: string; - /** Package names (and optional pins once fixtures exist) */ + /** Package names, optionally pinned as `name@version` once fixtures exist */ readonly packages: readonly string[]; /** Adapter ids selected for this recipe */ readonly adapters: readonly string[]; @@ -227,20 +227,49 @@ export function publishedPackageNames( return component.packages.filter((p) => p.published && p.version).map((p) => p.name); } +/** + * Split a recipe package specifier into name and optional exact version. + * Accepts bare names (`@pegma/spine`) and pinned forms (`@pegma/spine@0.1.1`). + * Scoped packages keep the leading `@`; the last `@` separates the version. + */ +export function parsePackageSpecifier(spec: string): { + readonly name: string; + readonly version: string | null; +} { + if (spec.startsWith('@')) { + const sep = spec.lastIndexOf('@'); + if (sep > 0) { + return { name: spec.slice(0, sep), version: spec.slice(sep + 1) || null }; + } + return { name: spec, version: null }; + } + const sep = spec.indexOf('@'); + if (sep > 0) { + return { name: spec.slice(0, sep), version: spec.slice(sep + 1) || null }; + } + return { name: spec, version: null }; +} + /** * True when every package named by the recipe is published with a version pin * somewhere in the catalog. Empty `recipe.packages` is ready (brochure / no-op). + * Specifiers may be bare names or `name@version` pins. */ export function recipePackagesReady( catalog: CompositionCatalog, recipe: CatalogRecipe, ): boolean { if (recipe.packages.length === 0) return true; - for (const name of recipe.packages) { + for (const spec of recipe.packages) { + const { name, version } = parsePackageSpecifier(spec); const owner = catalog.components.find((c) => c.packages.some((p) => p.name === name), ); if (!owner || !isPackagePublished(owner, name)) return false; + if (version !== null) { + const pkg = owner.packages.find((p) => p.name === name); + if (!pkg || pkg.version !== version) return false; + } } return true; } From 35fc887c92c4d6a2293340ba0d01e50a06b66131 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 00:12:03 -0400 Subject: [PATCH 5/6] Reject empty package pins and green fixtures still marked pending. Trailing name@ is not a bare package. Fixture status green requires a real fixture kind so catalog clients cannot treat backlog citations as proven. --- src/data/catalog-schema.test.ts | 52 +++++++++++++++++++++++++++++++++ src/data/catalog-schema.ts | 8 +++-- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts index d9b0317..576d27d 100644 --- a/src/data/catalog-schema.test.ts +++ b/src/data/catalog-schema.test.ts @@ -191,6 +191,12 @@ function parseRecipe(raw: unknown, index: number): CatalogRecipe { if (typeof f.status !== 'string' || !FIXTURE_STATUSES.has(f.status as RecipeFixtureStatus)) { throw new Error(`recipes[${index}].fixture.status invalid`); } + // Green means CI-proven wiring — pending kind cannot claim green. + if (f.status === 'green' && f.kind === 'pending') { + throw new Error( + `recipes[${index}].fixture: status 'green' cannot use kind 'pending'`, + ); + } return { id: r.id, intent: r.intent, @@ -365,6 +371,52 @@ describe('composition catalog schema', () => { name: 'left-pad', version: '1.0.0', }); + expect(parsePackageSpecifier('@pegma/spine@')).toEqual({ + name: '@pegma/spine', + version: '', + }); + expect( + recipePackagesReady(loadExample(), { + id: 'bad-pin', + intent: 'A fictional recipe with a trailing-@ package specifier that must not pass.', + packages: ['@pegma/spine@'], + adapters: [], + hostResponsibilities: [], + nonGoals: [], + antiPatterns: [], + fixture: { kind: 'pending', citation: 'n/a', status: 'pending' }, + capabilityTags: [], + requiresPublished: ['spine'], + }), + ).toBe(false); + }); + + it('rejects green fixtures that are still pending', () => { + expect(() => + parseCompositionCatalog({ + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: '2026-07-28T00:00:00.000Z', + components: [], + recipes: [ + { + id: 'fake-green', + intent: 'A fictional recipe that claims green without a real fixture source kind.', + packages: [], + adapters: [], + hostResponsibilities: [], + nonGoals: [], + antiPatterns: [], + fixture: { + kind: 'pending', + citation: 'docs/catalog/RECIPE_BACKLOG.md', + status: 'green', + }, + capabilityTags: [], + requiresPublished: [], + }, + ], + }), + ).toThrow(/green.*pending/i); }); it('rejects malformed dependency entries', () => { diff --git a/src/data/catalog-schema.ts b/src/data/catalog-schema.ts index 91bc0f7..2f690bf 100644 --- a/src/data/catalog-schema.ts +++ b/src/data/catalog-schema.ts @@ -234,18 +234,20 @@ export function publishedPackageNames( */ export function parsePackageSpecifier(spec: string): { readonly name: string; + /** Exact version, `null` when bare, or `''` when the specifier is malformed (`name@`). */ readonly version: string | null; } { if (spec.startsWith('@')) { const sep = spec.lastIndexOf('@'); if (sep > 0) { - return { name: spec.slice(0, sep), version: spec.slice(sep + 1) || null }; + // Keep empty suffix as '' so callers can reject `name@` — do not coerce to bare. + return { name: spec.slice(0, sep), version: spec.slice(sep + 1) }; } return { name: spec, version: null }; } const sep = spec.indexOf('@'); if (sep > 0) { - return { name: spec.slice(0, sep), version: spec.slice(sep + 1) || null }; + return { name: spec.slice(0, sep), version: spec.slice(sep + 1) }; } return { name: spec, version: null }; } @@ -262,6 +264,8 @@ export function recipePackagesReady( if (recipe.packages.length === 0) return true; for (const spec of recipe.packages) { const { name, version } = parsePackageSpecifier(spec); + // Empty version suffix (`@pegma/spine@`) is not a bare name and not a pin. + if (version === '') return false; const owner = catalog.components.find((c) => c.packages.some((p) => p.name === name), ); From 49d84942a5cdbc30a08efb9f908ce289e4a2e694 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 00:18:08 -0400 Subject: [PATCH 6/6] Use fictional catalog samples and component-scoped recipe adapters. Replace real Pegma lifecycle facts in example-catalog.json with example-* shape data, require componentId+adapterId on recipe adapters, and validate fixture kinds plus capability tags in structural parsing. --- docs/catalog/SCHEMA.md | 8 +- docs/catalog/example-catalog.json | 261 +++++++++------------------ src/data/catalog-schema.test.ts | 291 ++++++++++++++++++++++-------- src/data/catalog-schema.ts | 13 +- 4 files changed, 311 insertions(+), 262 deletions(-) diff --git a/docs/catalog/SCHEMA.md b/docs/catalog/SCHEMA.md index 5ea7a7f..a2cf7e9 100644 --- a/docs/catalog/SCHEMA.md +++ b/docs/catalog/SCHEMA.md @@ -93,7 +93,7 @@ CompositionCatalog | `id` | string | Stable recipe id | | `intent` | string | Synthetic product shape (one paragraph) | | `packages` | string[] | Package names, optionally pinned as `name@version` | -| `adapters` | string[] | Selected adapter ids | +| `adapters` | `{ componentId, adapterId }[]` | Component-scoped adapter selections | | `hostResponsibilities` | string[] | Host-owned work | | `nonGoals` | string[] | Out of scope for the recipe | | `antiPatterns` | string[] | What not to invent | @@ -124,8 +124,10 @@ Structured flags (not free text) so `plan_composition` can stay rule-based: Canonical types: [`src/data/catalog-schema.ts`](../../src/data/catalog-schema.ts). Illustrative (non-authoritative) document: -[`example-catalog.json`](./example-catalog.json) — incomplete sample for shape -checking only; Phase 1 replaces hand examples with a compiled artifact. +[`example-catalog.json`](./example-catalog.json) — **fictional** component ids and +packages for shape checking only (not Pegma lifecycle facts). Phase 1 emits a +compiled catalog from plans + version authority; do not treat this sample as +roadmap truth. ## Gap inventory and recipes diff --git a/docs/catalog/example-catalog.json b/docs/catalog/example-catalog.json index 557ff78..17b10c1 100644 --- a/docs/catalog/example-catalog.json +++ b/docs/catalog/example-catalog.json @@ -4,207 +4,143 @@ "snapshotDate": "2026-07-28", "components": [ { - "id": "spine", - "title": "Spine", - "repo": "spine", + "id": "example-contracts", + "title": "Example Contracts", + "repo": "example-contracts", "packages": [ { - "name": "@pegma/spine", - "version": "0.1.1", + "name": "@example/contracts", + "version": "0.0.1", "published": true, - "npmUrl": "https://www.npmjs.com/package/@pegma/spine" + "npmUrl": "https://www.npmjs.com/package/@example/contracts" } ], "status": "published", "publishUsability": "usable", - "summary": "The small, stable contracts every component shares.", - "owns": [ - "PrincipalId and IsoTimestamp — shared identity and time types", - "Clock — time as an injected, test-replaceable input", - "Logger — a one-method structured logging port", - "Typed event declarations and a best-effort in-process bus" - ], - "refuses": [ - "Durable events — anything that must survive a crash goes to a storage-backed outbox, never the in-process bus", - "Growth — the more spine changes, the more the ecosystem churns" - ], + "summary": "Fictional shared contracts package for schema shape-checking only.", + "owns": ["Shared demo types and a one-method logger port"], + "refuses": ["Durable cross-process events on an in-process bus"], "dependencies": [], "adapters": [], - "hostMustProvide": [ - "Composition-root wiring for Clock, Logger, and any in-process bus subscribers" - ], + "hostMustProvide": ["Composition-root Clock and Logger wiring"], "capabilityTags": ["logging", "events_in_process"], - "recipeIds": [ - "cf-passkey-accounts", - "storage-audit-mail-outbox", - "health-public-liveness", - "logger-tee-composition" - ], + "recipeIds": ["example-accounts", "example-outbox", "example-deferred"], "links": { - "githubRepo": "https://github.com/pegma-dev/spine", - "readme": "https://github.com/pegma-dev/spine#readme", - "npm": "https://www.npmjs.com/package/@pegma/spine" + "githubRepo": "https://github.com/example/example-contracts", + "readme": "https://github.com/example/example-contracts#readme", + "npm": "https://www.npmjs.com/package/@example/contracts" }, - "now": "0.1.1 on npm; deliberately close to frozen." + "now": "Fictional pin for schema samples — not a Pegma lifecycle fact." }, { - "id": "storage-core", - "title": "Storage Core", - "repo": "storage-core", + "id": "example-store", + "title": "Example Store", + "repo": "example-store", "packages": [ { - "name": "@pegma/storage-core", - "version": "0.4.0", - "published": true, - "npmUrl": "https://www.npmjs.com/package/@pegma/storage-core" - }, - { - "name": "@pegma/storage-azure-tables", - "version": "0.4.0", + "name": "@example/store", + "version": "0.0.1", "published": true, - "npmUrl": "https://www.npmjs.com/package/@pegma/storage-azure-tables" + "npmUrl": "https://www.npmjs.com/package/@example/store" }, { - "name": "@pegma/storage-cloudflare-d1", - "version": "0.4.0", + "name": "@example/store-cloud", + "version": "0.0.1", "published": true, - "npmUrl": "https://www.npmjs.com/package/@pegma/storage-cloudflare-d1" + "npmUrl": "https://www.npmjs.com/package/@example/store-cloud" } ], "status": "published", "publishUsability": "usable", - "summary": "Persistence without the component knowing what the database is.", - "owns": [ - "Declared collections with codecs — schema-agnostic on purpose", - "update deciders re-run against fresh state on every conflict", - "Single-collection, single-partition transactions" - ], - "refuses": [ - "Server-side queries and secondary indexes", - "Cross-partition anything" - ], + "summary": "Fictional persistence port used only to illustrate adapters and deps.", + "owns": ["Declared collections and single-partition transactions"], + "refuses": ["Cross-partition transactions"], "dependencies": [ { - "componentId": "spine", + "componentId": "example-contracts", "kind": "requires", - "note": "Shared contracts and logging port" + "note": "Shared contracts" } ], "adapters": [ { "id": "memory", - "packageName": "@pegma/storage-core", + "packageName": "@example/store", "host": "memory", - "when": "Tests and local sketches; not a production durability claim" - }, - { - "id": "azure-tables", - "packageName": "@pegma/storage-azure-tables", - "host": "azure", - "when": "Azure-hosted apps that want the Tables adapter" + "when": "Tests and local sketches" }, { - "id": "cloudflare-d1", - "packageName": "@pegma/storage-cloudflare-d1", + "id": "cloud-sql", + "packageName": "@example/store-cloud", "host": "cloudflare", - "when": "Cloudflare Workers/Pages with D1" + "when": "Cloudflare-shaped hosts in the sample recipe" } ], - "hostMustProvide": [ - "Chosen adapter binding (e.g. D1 database, Azure connection)", - "Collection declarations and codecs" - ], - "capabilityTags": ["storage", "cloudflare", "azure"], - "recipeIds": [ - "cf-passkey-accounts", - "storage-audit-mail-outbox", - "durable-auth-rate-limits" - ], + "hostMustProvide": ["Chosen adapter binding and collection codecs"], + "capabilityTags": ["storage", "cloudflare"], + "recipeIds": ["example-accounts", "example-outbox"], "links": { - "githubRepo": "https://github.com/pegma-dev/storage-core", - "readme": "https://github.com/pegma-dev/storage-core#readme", - "npm": "https://www.npmjs.com/package/@pegma/storage-core" + "githubRepo": "https://github.com/example/example-store", + "readme": "https://github.com/example/example-store#readme", + "npm": "https://www.npmjs.com/package/@example/store" }, - "now": "0.4.0 on npm with Azure Tables and Cloudflare D1 adapters." + "now": "Fictional pin for schema samples — not a Pegma lifecycle fact." }, { - "id": "webhooks", - "title": "Webhooks", - "repo": "webhooks", + "id": "example-inbox", + "title": "Example Inbox", + "repo": "example-inbox", "packages": [ { - "name": "@pegma/webhooks", + "name": "@example/inbox", "version": null, "published": false } ], "status": "in_development", "publishUsability": "unpublished", - "summary": "Inbound webhook receipts: idempotent dedup, poison quarantine, retention.", - "owns": [ - "One receipt per provider event id", - "Quarantine-then-acknowledge after bounded failures" - ], - "refuses": [ - "Exactly-once delivery", - "Storing payloads — receipts hold ids and counters, never customer data" - ], + "summary": "Fictional unpublished component for unusable-package shape checks.", + "owns": ["Idempotent receipt rows"], + "refuses": ["Storing full provider payloads in the receipt"], "dependencies": [ { - "componentId": "storage-core", + "componentId": "example-store", "kind": "requires" }, { - "componentId": "spine", + "componentId": "example-contracts", "kind": "requires" } ], "adapters": [], - "hostMustProvide": [ - "HTTP endpoint and provider signature verification", - "Storage binding for the receipt ledger" - ], + "hostMustProvide": ["HTTP endpoint and storage binding"], "capabilityTags": ["webhooks_inbound"], - "recipeIds": ["inbound-webhook-receipts"], + "recipeIds": ["example-deferred"], "links": { - "githubRepo": "https://github.com/pegma-dev/webhooks", - "plan": "https://github.com/pegma-dev/webhooks/blob/main/docs/PROJECT_PLAN.md" + "githubRepo": "https://github.com/example/example-inbox", + "plan": "https://github.com/example/example-inbox/blob/main/docs/PROJECT_PLAN.md" }, - "now": "Unpublished; not usable for production assembly." + "now": "Fictional unpublished sample — not a Pegma lifecycle fact." } ], "recipes": [ { - "id": "cf-passkey-accounts", - "intent": "A small Cloudflare Worker host for a fictional community library (Northshelf Branch) offers first-party accounts: passkey sign-in, email one-time codes for enrollment and recovery, server-side sessions, and durable rate limits on expensive auth paths. No passwords.", + "id": "example-accounts", + "intent": "A fictional community library (Northshelf Branch) offers first-party passkey accounts with email codes on a Cloudflare-shaped host. Synthetic shape sample only.", "packages": [ - "@pegma/identity", - "@pegma/sessions", - "@pegma/mail", - "@pegma/rate-limit", - "@pegma/authorization-identity", - "@pegma/storage-core", - "@pegma/storage-cloudflare-d1", - "@pegma/spine" + "@example/contracts", + "@example/store", + "@example/store-cloud" + ], + "adapters": [ + { "componentId": "example-store", "adapterId": "cloud-sql" } ], - "adapters": ["cloudflare-d1"], "hostResponsibilities": [ "HTTP routes and cookie/session boundary", - "WebAuthn relying-party configuration", - "Email provider adapter and DNS", - "Secrets and any account UI" - ], - "nonGoals": [ - "Social login", - "OIDC server for third parties", - "Passwords", - "Multi-tenant organizations" - ], - "antiPatterns": [ - "Password table or reset flow", - "Durable events on Spine in-process bus", - "Mail package owning its own outbox store" + "WebAuthn relying-party configuration" ], + "nonGoals": ["Passwords", "Social login"], + "antiPatterns": ["Password table", "Durable events on an in-process bus"], "fixture": { "kind": "pending", "citation": "docs/catalog/RECIPE_BACKLOG.md#p1--cf-passkey-accounts-first-end-to-end-accounts-recipe", @@ -213,81 +149,52 @@ "capabilityTags": [ "accounts", "passkeys", - "email_codes", - "sessions", - "authorization", - "mail_transactional", - "rate_limit_durable", "storage", "cloudflare" ], "requiresPublished": [ - "identity", - "sessions", - "mail", - "rate-limit", - "authorization-core", - "storage-core", - "spine" + "example-contracts", + "example-store" ], "backlogPriority": 1 }, { - "id": "storage-audit-mail-outbox", - "intent": "A fictional equipment checkout service (Yard Loan) records inventory mutations in Storage Core and, in the same single-partition transaction, appends an audit row and enqueues a transactional mail delivery job.", - "packages": [ - "@pegma/storage-core", - "@pegma/audit", - "@pegma/mail", - "@pegma/spine" + "id": "example-outbox", + "intent": "A fictional equipment checkout service (Yard Loan) commits an audit row and mail outbox job in the same storage transaction.", + "packages": ["@example/store", "@example/contracts"], + "adapters": [ + { "componentId": "example-store", "adapterId": "memory" } ], - "adapters": ["memory"], "hostResponsibilities": [ - "Collection declarations", "Transaction boundary", - "Outbox collection in host storage", - "Mail provider and delivery worker schedule" - ], - "nonGoals": [ - "Mail-owned outbox store", - "Audit-owned store", - "Cross-partition transactions" - ], - "antiPatterns": [ - "Send email after commit without an outbox job in the same transaction", - "Audit write outside the caller transact" + "Outbox collection in host storage" ], + "nonGoals": ["Mail-owned outbox store"], + "antiPatterns": ["Send email after commit without an outbox job"], "fixture": { "kind": "pending", "citation": "docs/catalog/RECIPE_BACKLOG.md#p2--storage-audit-mail-outbox-storage--auditmail-pattern", "status": "pending" }, "capabilityTags": ["storage", "audit", "mail_transactional"], - "requiresPublished": ["storage-core", "audit", "mail", "spine"], + "requiresPublished": ["example-store", "example-contracts"], "backlogPriority": 2 }, { - "id": "inbound-webhook-receipts", - "intent": "A fictional donation platform (Copper Plate) records inbound provider webhook receipts with idempotent dedup and poison quarantine. Receipts hold ids and counters, never payloads.", - "packages": ["@pegma/webhooks", "@pegma/storage-core", "@pegma/spine"], + "id": "example-deferred", + "intent": "A fictional donation platform (Copper Plate) records inbound webhook receipts once the inbox package is published.", + "packages": ["@example/inbox", "@example/store", "@example/contracts"], "adapters": [], - "hostResponsibilities": [ - "HTTP endpoint", - "Provider signature verification", - "Storage for the receipt ledger" - ], - "nonGoals": ["Exactly-once delivery", "Payload archival in the receipt ledger"], - "antiPatterns": [ - "Claiming exactly-once processing", - "Storing full webhook bodies in receipts" - ], + "hostResponsibilities": ["HTTP endpoint", "Provider signature verification"], + "nonGoals": ["Exactly-once delivery"], + "antiPatterns": ["Storing full webhook bodies in receipts"], "fixture": { "kind": "pending", "citation": "docs/catalog/RECIPE_BACKLOG.md#d1--inbound-webhook-receipts-when-pegmawebhooks-is-published", "status": "none" }, "capabilityTags": ["webhooks_inbound"], - "requiresPublished": ["webhooks", "storage-core", "spine"], + "requiresPublished": ["example-inbox", "example-store", "example-contracts"], "backlogPriority": 90 } ] diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts index 576d27d..7acbd0d 100644 --- a/src/data/catalog-schema.test.ts +++ b/src/data/catalog-schema.test.ts @@ -6,18 +6,21 @@ import { CATALOG_SCHEMA_VERSION, isPackagePublished, isPublishUsable, + parsePackageSpecifier, publishedPackageNames, recipePackagesReady, - parsePackageSpecifier, + type CapabilityTag, type CatalogAdapter, type CatalogComponent, type CatalogComponentStatus, type CatalogDependency, type CatalogPackage, type CatalogRecipe, + type CatalogRecipeAdapterRef, type CompositionCatalog, type DependencyKind, type PublishUsability, + type RecipeFixtureKind, type RecipeFixtureStatus, } from './catalog-schema'; @@ -39,6 +42,33 @@ const FIXTURE_STATUSES = new Set([ 'pending', 'none', ]); +const FIXTURE_KINDS = new Set([ + 'package_readme', + 'conformance', + 'recipe_package', + 'scaffold', + 'pending', +]); +const CAPABILITY_TAGS = new Set([ + 'accounts', + 'passkeys', + 'email_codes', + 'sessions', + 'authorization', + 'storage', + 'audit', + 'mail_transactional', + 'rate_limit_durable', + 'rate_limit_memory', + 'webhooks_inbound', + 'support_queue', + 'health', + 'logging', + 'events_in_process', + 'cloudflare', + 'azure', + 'static_host', +]); const ADAPTER_HOSTS = new Set(['cloudflare', 'azure', 'memory', 'other']); const DEPENDENCY_KINDS = new Set([ 'requires', @@ -58,6 +88,18 @@ function assertStringArray(value: unknown, label: string): asserts value is stri } } +function assertCapabilityTags( + value: unknown, + label: string, +): asserts value is CapabilityTag[] { + assertStringArray(value, label); + for (const tag of value) { + if (!CAPABILITY_TAGS.has(tag as CapabilityTag)) { + throw new Error(`${label} has unknown capability tag: ${tag}`); + } + } +} + function parsePackage(raw: unknown, label: string): CatalogPackage { if (!raw || typeof raw !== 'object') throw new Error(`${label} must be an object`); const p = raw as Record; @@ -106,6 +148,14 @@ function parseDependency(raw: unknown, label: string): CatalogDependency { }; } +function parseRecipeAdapterRef(raw: unknown, label: string): CatalogRecipeAdapterRef { + if (!raw || typeof raw !== 'object') throw new Error(`${label} must be an object`); + const a = raw as Record; + assertString(a.componentId, `${label}.componentId`); + assertString(a.adapterId, `${label}.adapterId`); + return { componentId: a.componentId, adapterId: a.adapterId }; +} + function parseComponent(raw: unknown, index: number): CatalogComponent { if (!raw || typeof raw !== 'object') { throw new Error(`components[${index}] must be an object`); @@ -132,7 +182,7 @@ function parseComponent(raw: unknown, index: number): CatalogComponent { assertStringArray(c.owns, `components[${index}].owns`); assertStringArray(c.refuses, `components[${index}].refuses`); assertStringArray(c.hostMustProvide, `components[${index}].hostMustProvide`); - assertStringArray(c.capabilityTags, `components[${index}].capabilityTags`); + assertCapabilityTags(c.capabilityTags, `components[${index}].capabilityTags`); assertStringArray(c.recipeIds, `components[${index}].recipeIds`); if (!c.links || typeof c.links !== 'object') { throw new Error(`components[${index}].links must be object`); @@ -155,7 +205,7 @@ function parseComponent(raw: unknown, index: number): CatalogComponent { ), adapters: c.adapters.map((a, i) => parseAdapter(a, `components[${index}].adapters[${i}]`)), hostMustProvide: c.hostMustProvide, - capabilityTags: c.capabilityTags as CatalogComponent['capabilityTags'], + capabilityTags: c.capabilityTags, recipeIds: c.recipeIds, links: { githubRepo: links.githubRepo, @@ -176,22 +226,26 @@ function parseRecipe(raw: unknown, index: number): CatalogRecipe { assertString(r.id, `recipes[${index}].id`); assertString(r.intent, `recipes[${index}].intent`); assertStringArray(r.packages, `recipes[${index}].packages`); - assertStringArray(r.adapters, `recipes[${index}].adapters`); + if (!Array.isArray(r.adapters)) { + throw new Error(`recipes[${index}].adapters must be an array`); + } assertStringArray(r.hostResponsibilities, `recipes[${index}].hostResponsibilities`); assertStringArray(r.nonGoals, `recipes[${index}].nonGoals`); assertStringArray(r.antiPatterns, `recipes[${index}].antiPatterns`); - assertStringArray(r.capabilityTags, `recipes[${index}].capabilityTags`); + assertCapabilityTags(r.capabilityTags, `recipes[${index}].capabilityTags`); assertStringArray(r.requiresPublished, `recipes[${index}].requiresPublished`); if (!r.fixture || typeof r.fixture !== 'object') { throw new Error(`recipes[${index}].fixture must be object`); } const f = r.fixture as Record; assertString(f.kind, `recipes[${index}].fixture.kind`); + if (!FIXTURE_KINDS.has(f.kind as RecipeFixtureKind)) { + throw new Error(`recipes[${index}].fixture.kind invalid`); + } assertString(f.citation, `recipes[${index}].fixture.citation`); if (typeof f.status !== 'string' || !FIXTURE_STATUSES.has(f.status as RecipeFixtureStatus)) { throw new Error(`recipes[${index}].fixture.status invalid`); } - // Green means CI-proven wiring — pending kind cannot claim green. if (f.status === 'green' && f.kind === 'pending') { throw new Error( `recipes[${index}].fixture: status 'green' cannot use kind 'pending'`, @@ -201,16 +255,18 @@ function parseRecipe(raw: unknown, index: number): CatalogRecipe { id: r.id, intent: r.intent, packages: r.packages, - adapters: r.adapters, + adapters: r.adapters.map((a, i) => + parseRecipeAdapterRef(a, `recipes[${index}].adapters[${i}]`), + ), hostResponsibilities: r.hostResponsibilities, nonGoals: r.nonGoals, antiPatterns: r.antiPatterns, fixture: { - kind: f.kind as CatalogRecipe['fixture']['kind'], + kind: f.kind as RecipeFixtureKind, citation: f.citation, status: f.status as RecipeFixtureStatus, }, - capabilityTags: r.capabilityTags as CatalogRecipe['capabilityTags'], + capabilityTags: r.capabilityTags, requiresPublished: r.requiresPublished, ...(typeof r.backlogPriority === 'number' ? { backlogPriority: r.backlogPriority } : {}), }; @@ -240,17 +296,37 @@ function loadExample(): CompositionCatalog { return parseCompositionCatalog(raw); } +function emptyRecipe( + overrides: Partial & Pick, +): CatalogRecipe { + return { + adapters: [], + hostResponsibilities: [], + nonGoals: [], + antiPatterns: [], + fixture: { kind: 'pending', citation: 'n/a', status: 'pending' }, + capabilityTags: [], + requiresPublished: [], + ...overrides, + }; +} + describe('composition catalog schema', () => { it('pins schema version 0.1.0', () => { expect(CATALOG_SCHEMA_VERSION).toBe('0.1.0'); }); - it('structurally validates the example catalog', () => { + it('structurally validates the fictional example catalog', () => { const catalog = loadExample(); expect(catalog.schemaVersion).toBe(CATALOG_SCHEMA_VERSION); expect(catalog.generatedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); expect(catalog.components.length).toBeGreaterThan(0); expect(catalog.recipes.length).toBeGreaterThan(0); + // Example must not claim real Pegma component lifecycle facts. + for (const c of catalog.components) { + expect(c.id.startsWith('example-')).toBe(true); + expect(c.repo.startsWith('example-')).toBe(true); + } }); it('rejects example JSON missing required fields', () => { @@ -267,35 +343,29 @@ describe('composition catalog schema', () => { it('marks unpublished packages unusable for production assembly', () => { const catalog = loadExample(); - const webhooks = catalog.components.find((c) => c.id === 'webhooks'); - expect(webhooks).toBeDefined(); - expect(webhooks!.publishUsability).toBe('unpublished'); - expect(isPublishUsable(webhooks!)).toBe(false); - expect(publishedPackageNames(webhooks!)).toEqual([]); - expect(isPackagePublished(webhooks!, '@pegma/webhooks')).toBe(false); + const inbox = catalog.components.find((c) => c.id === 'example-inbox'); + expect(inbox).toBeDefined(); + expect(inbox!.publishUsability).toBe('unpublished'); + expect(isPublishUsable(inbox!)).toBe(false); + expect(publishedPackageNames(inbox!)).toEqual([]); + expect(isPackagePublished(inbox!, '@example/inbox')).toBe(false); }); it('exposes published package names only when versioned and published', () => { - const storage: CatalogComponent = loadExample().components.find( - (c) => c.id === 'storage-core', + const store: CatalogComponent = loadExample().components.find( + (c) => c.id === 'example-store', )!; - expect(isPublishUsable(storage)).toBe(true); - expect(publishedPackageNames(storage)).toEqual( - expect.arrayContaining([ - '@pegma/storage-core', - '@pegma/storage-azure-tables', - '@pegma/storage-cloudflare-d1', - ]), + expect(isPublishUsable(store)).toBe(true); + expect(publishedPackageNames(store)).toEqual( + expect.arrayContaining(['@example/store', '@example/store-cloud']), ); }); it('gates recipe readiness on package pins, not partial components alone', () => { const catalog = loadExample(); - const inbound = catalog.recipes.find((r) => r.id === 'inbound-webhook-receipts')!; - expect(recipePackagesReady(catalog, inbound)).toBe(false); + const deferred = catalog.recipes.find((r) => r.id === 'example-deferred')!; + expect(recipePackagesReady(catalog, deferred)).toBe(false); - // Partial component with only some packages published must not pass a - // recipe that names an unpublished sibling package. const partialCatalog: CompositionCatalog = { schemaVersion: CATALOG_SCHEMA_VERSION, generatedAt: '2026-07-28T00:00:00.000Z', @@ -305,8 +375,8 @@ describe('composition catalog schema', () => { title: 'Demo', repo: 'demo', packages: [ - { name: '@pegma/demo-core', version: '0.1.0', published: true }, - { name: '@pegma/demo-extra', version: null, published: false }, + { name: '@example/demo-core', version: '0.1.0', published: true }, + { name: '@example/demo-extra', version: null, published: false }, ], status: 'published', publishUsability: 'partial', @@ -318,76 +388,79 @@ describe('composition catalog schema', () => { hostMustProvide: [], capabilityTags: [], recipeIds: [], - links: { githubRepo: 'https://github.com/pegma-dev/demo' }, + links: { githubRepo: 'https://github.com/example/demo' }, }, ], recipes: [ - { + emptyRecipe({ id: 'needs-extra', intent: 'A fictional partial-package case that asks for the unpublished sibling.', - packages: ['@pegma/demo-core', '@pegma/demo-extra'], - adapters: [], - hostResponsibilities: [], - nonGoals: [], - antiPatterns: [], - fixture: { kind: 'pending', citation: 'n/a', status: 'pending' }, - capabilityTags: [], + packages: ['@example/demo-core', '@example/demo-extra'], requiresPublished: ['demo'], - }, + }), ], }; expect(isPublishUsable(partialCatalog.components[0]!)).toBe(false); expect(recipePackagesReady(partialCatalog, partialCatalog.recipes[0]!)).toBe(false); expect( - recipePackagesReady(partialCatalog, { - ...partialCatalog.recipes[0]!, - packages: ['@pegma/demo-core'], - }), + recipePackagesReady( + partialCatalog, + emptyRecipe({ + id: 'core-only', + intent: 'A fictional recipe that only needs the published core package.', + packages: ['@example/demo-core'], + }), + ), ).toBe(true); expect( - recipePackagesReady(partialCatalog, { - ...partialCatalog.recipes[0]!, - packages: ['@pegma/demo-core@0.1.0'], - }), + recipePackagesReady( + partialCatalog, + emptyRecipe({ + id: 'core-pin', + intent: 'A fictional recipe with an exact pin matching the published version.', + packages: ['@example/demo-core@0.1.0'], + }), + ), ).toBe(true); expect( - recipePackagesReady(partialCatalog, { - ...partialCatalog.recipes[0]!, - packages: ['@pegma/demo-core@9.9.9'], - }), + recipePackagesReady( + partialCatalog, + emptyRecipe({ + id: 'bad-pin', + intent: 'A fictional recipe whose pin does not match the published version.', + packages: ['@example/demo-core@9.9.9'], + }), + ), ).toBe(false); }); it('parses scoped package@version specifiers', () => { - expect(parsePackageSpecifier('@pegma/spine@0.1.1')).toEqual({ - name: '@pegma/spine', - version: '0.1.1', + expect(parsePackageSpecifier('@example/contracts@0.0.1')).toEqual({ + name: '@example/contracts', + version: '0.0.1', }); - expect(parsePackageSpecifier('@pegma/spine')).toEqual({ - name: '@pegma/spine', + expect(parsePackageSpecifier('@example/contracts')).toEqual({ + name: '@example/contracts', version: null, }); expect(parsePackageSpecifier('left-pad@1.0.0')).toEqual({ name: 'left-pad', version: '1.0.0', }); - expect(parsePackageSpecifier('@pegma/spine@')).toEqual({ - name: '@pegma/spine', + expect(parsePackageSpecifier('@example/contracts@')).toEqual({ + name: '@example/contracts', version: '', }); expect( - recipePackagesReady(loadExample(), { - id: 'bad-pin', - intent: 'A fictional recipe with a trailing-@ package specifier that must not pass.', - packages: ['@pegma/spine@'], - adapters: [], - hostResponsibilities: [], - nonGoals: [], - antiPatterns: [], - fixture: { kind: 'pending', citation: 'n/a', status: 'pending' }, - capabilityTags: [], - requiresPublished: ['spine'], - }), + recipePackagesReady( + loadExample(), + emptyRecipe({ + id: 'bad-pin', + intent: 'A fictional recipe with a trailing-@ package specifier that must not pass.', + packages: ['@example/contracts@'], + requiresPublished: ['example-contracts'], + }), + ), ).toBe(false); }); @@ -419,6 +492,61 @@ describe('composition catalog schema', () => { ).toThrow(/green.*pending/i); }); + it('rejects unknown fixture kinds and capability tags', () => { + expect(() => + parseCompositionCatalog({ + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: '2026-07-28T00:00:00.000Z', + components: [], + recipes: [ + { + id: 'bad-kind', + intent: 'A fictional recipe with a typo in fixture kind.', + packages: [], + adapters: [], + hostResponsibilities: [], + nonGoals: [], + antiPatterns: [], + fixture: { + kind: 'not_a_real_kind', + citation: 'n/a', + status: 'green', + }, + capabilityTags: [], + requiresPublished: [], + }, + ], + }), + ).toThrow(/fixture\.kind invalid/); + + expect(() => + parseCompositionCatalog({ + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: '2026-07-28T00:00:00.000Z', + components: [ + { + id: 'example-x', + title: 'X', + repo: 'example-x', + packages: [], + status: 'published', + publishUsability: 'usable', + summary: 'x', + owns: [], + refuses: [], + dependencies: [], + adapters: [], + hostMustProvide: [], + capabilityTags: ['not_a_tag'], + recipeIds: [], + links: { githubRepo: 'https://github.com/example/x' }, + }, + ], + recipes: [], + }), + ).toThrow(/unknown capability tag/); + }); + it('rejects malformed dependency entries', () => { expect(() => parseCompositionCatalog({ @@ -426,9 +554,9 @@ describe('composition catalog schema', () => { generatedAt: '2026-07-28T00:00:00.000Z', components: [ { - id: 'x', + id: 'example-x', title: 'X', - repo: 'x', + repo: 'example-x', packages: [], status: 'published', publishUsability: 'usable', @@ -440,7 +568,7 @@ describe('composition catalog schema', () => { hostMustProvide: [], capabilityTags: [], recipeIds: [], - links: { githubRepo: 'https://github.com/pegma-dev/x' }, + links: { githubRepo: 'https://github.com/example/x' }, }, ], recipes: [], @@ -456,21 +584,24 @@ describe('composition catalog schema', () => { expect(recipe.intent).not.toMatch(pattern); } expect(recipe.intent.length).toBeGreaterThan(40); - // Empty requiresPublished is valid (e.g. static-brochure-minimal). expect(Array.isArray(recipe.requiresPublished)).toBe(true); for (const id of recipe.requiresPublished) { expect(typeof id).toBe('string'); expect(id.length).toBeGreaterThan(0); } + for (const adapter of recipe.adapters) { + expect(adapter.componentId.length).toBeGreaterThan(0); + expect(adapter.adapterId.length).toBeGreaterThan(0); + } } }); it('orders priority recipes ahead of deferred unpublished ones', () => { const catalog = loadExample(); const byId = Object.fromEntries(catalog.recipes.map((r) => [r.id, r])); - expect(byId['cf-passkey-accounts']?.backlogPriority).toBe(1); - expect(byId['storage-audit-mail-outbox']?.backlogPriority).toBe(2); - expect(byId['inbound-webhook-receipts']?.backlogPriority).toBeGreaterThan(2); - expect(byId['inbound-webhook-receipts']?.fixture.status).toBe('none'); + expect(byId['example-accounts']?.backlogPriority).toBe(1); + expect(byId['example-outbox']?.backlogPriority).toBe(2); + expect(byId['example-deferred']?.backlogPriority).toBeGreaterThan(2); + expect(byId['example-deferred']?.fixture.status).toBe('none'); }); }); diff --git a/src/data/catalog-schema.ts b/src/data/catalog-schema.ts index 2f690bf..3649a3d 100644 --- a/src/data/catalog-schema.ts +++ b/src/data/catalog-schema.ts @@ -158,6 +158,15 @@ export interface RecipeFixtureCitation { readonly status: RecipeFixtureStatus; } +/** + * Recipe adapter selection. Adapter ids are only unique within a component, + * so recipes always pair them with `componentId`. + */ +export interface CatalogRecipeAdapterRef { + readonly componentId: string; + readonly adapterId: string; +} + /** * A named composition intent. Product shape is synthetic on purpose; * wiring sketches only appear when `fixture.status === 'green'`. @@ -168,8 +177,8 @@ export interface CatalogRecipe { readonly intent: string; /** Package names, optionally pinned as `name@version` once fixtures exist */ readonly packages: readonly string[]; - /** Adapter ids selected for this recipe */ - readonly adapters: readonly string[]; + /** Adapter selections (component-scoped ids) */ + readonly adapters: readonly CatalogRecipeAdapterRef[]; readonly hostResponsibilities: readonly string[]; readonly nonGoals: readonly string[]; /** Anti-patterns agents must not invent */