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..b28066f --- /dev/null +++ b/docs/catalog/GAP_INVENTORY.md @@ -0,0 +1,92 @@ +# 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` | Hand-maintained only — **do not trust as sole authority** (see below); also 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 | +| --- | --- | --- | +| `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 | +| `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 | + +## Publish / assembly-usable gate (compiled, not hand-copied) + +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. + +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) + +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..c1f4398 --- /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..a2cf7e9 --- /dev/null +++ b/docs/catalog/SCHEMA.md @@ -0,0 +1,135 @@ +# 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, optionally pinned as `name@version` | +| `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 | +| `fixture` | object | Citation + kind + status | +| `capabilityTags` | `CapabilityTag[]` | 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) — **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 + +- 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..17b10c1 --- /dev/null +++ b/docs/catalog/example-catalog.json @@ -0,0 +1,201 @@ +{ + "schemaVersion": "0.1.0", + "generatedAt": "2026-07-28T00:00:00.000Z", + "snapshotDate": "2026-07-28", + "components": [ + { + "id": "example-contracts", + "title": "Example Contracts", + "repo": "example-contracts", + "packages": [ + { + "name": "@example/contracts", + "version": "0.0.1", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@example/contracts" + } + ], + "status": "published", + "publishUsability": "usable", + "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 Clock and Logger wiring"], + "capabilityTags": ["logging", "events_in_process"], + "recipeIds": ["example-accounts", "example-outbox", "example-deferred"], + "links": { + "githubRepo": "https://github.com/example/example-contracts", + "readme": "https://github.com/example/example-contracts#readme", + "npm": "https://www.npmjs.com/package/@example/contracts" + }, + "now": "Fictional pin for schema samples — not a Pegma lifecycle fact." + }, + { + "id": "example-store", + "title": "Example Store", + "repo": "example-store", + "packages": [ + { + "name": "@example/store", + "version": "0.0.1", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@example/store" + }, + { + "name": "@example/store-cloud", + "version": "0.0.1", + "published": true, + "npmUrl": "https://www.npmjs.com/package/@example/store-cloud" + } + ], + "status": "published", + "publishUsability": "usable", + "summary": "Fictional persistence port used only to illustrate adapters and deps.", + "owns": ["Declared collections and single-partition transactions"], + "refuses": ["Cross-partition transactions"], + "dependencies": [ + { + "componentId": "example-contracts", + "kind": "requires", + "note": "Shared contracts" + } + ], + "adapters": [ + { + "id": "memory", + "packageName": "@example/store", + "host": "memory", + "when": "Tests and local sketches" + }, + { + "id": "cloud-sql", + "packageName": "@example/store-cloud", + "host": "cloudflare", + "when": "Cloudflare-shaped hosts in the sample recipe" + } + ], + "hostMustProvide": ["Chosen adapter binding and collection codecs"], + "capabilityTags": ["storage", "cloudflare"], + "recipeIds": ["example-accounts", "example-outbox"], + "links": { + "githubRepo": "https://github.com/example/example-store", + "readme": "https://github.com/example/example-store#readme", + "npm": "https://www.npmjs.com/package/@example/store" + }, + "now": "Fictional pin for schema samples — not a Pegma lifecycle fact." + }, + { + "id": "example-inbox", + "title": "Example Inbox", + "repo": "example-inbox", + "packages": [ + { + "name": "@example/inbox", + "version": null, + "published": false + } + ], + "status": "in_development", + "publishUsability": "unpublished", + "summary": "Fictional unpublished component for unusable-package shape checks.", + "owns": ["Idempotent receipt rows"], + "refuses": ["Storing full provider payloads in the receipt"], + "dependencies": [ + { + "componentId": "example-store", + "kind": "requires" + }, + { + "componentId": "example-contracts", + "kind": "requires" + } + ], + "adapters": [], + "hostMustProvide": ["HTTP endpoint and storage binding"], + "capabilityTags": ["webhooks_inbound"], + "recipeIds": ["example-deferred"], + "links": { + "githubRepo": "https://github.com/example/example-inbox", + "plan": "https://github.com/example/example-inbox/blob/main/docs/PROJECT_PLAN.md" + }, + "now": "Fictional unpublished sample — not a Pegma lifecycle fact." + } + ], + "recipes": [ + { + "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": [ + "@example/contracts", + "@example/store", + "@example/store-cloud" + ], + "adapters": [ + { "componentId": "example-store", "adapterId": "cloud-sql" } + ], + "hostResponsibilities": [ + "HTTP routes and cookie/session boundary", + "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", + "status": "pending" + }, + "capabilityTags": [ + "accounts", + "passkeys", + "storage", + "cloudflare" + ], + "requiresPublished": [ + "example-contracts", + "example-store" + ], + "backlogPriority": 1 + }, + { + "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" } + ], + "hostResponsibilities": [ + "Transaction boundary", + "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": ["example-store", "example-contracts"], + "backlogPriority": 2 + }, + { + "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"], + "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": ["example-inbox", "example-store", "example-contracts"], + "backlogPriority": 90 + } + ] +} diff --git a/src/data/catalog-schema.test.ts b/src/data/catalog-schema.test.ts new file mode 100644 index 0000000..7acbd0d --- /dev/null +++ b/src/data/catalog-schema.test.ts @@ -0,0 +1,607 @@ +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, + isPackagePublished, + isPublishUsable, + parsePackageSpecifier, + publishedPackageNames, + recipePackagesReady, + 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'; + +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 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', + 'optional', + 'composes_with', +]); + +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 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; + 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 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 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`); + } + 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`); + 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`); + } + 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.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, + 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`); + 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`); + 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`); + } + 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, + packages: r.packages, + 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 RecipeFixtureKind, + citation: f.citation, + status: f.status as RecipeFixtureStatus, + }, + capabilityTags: r.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 { + const raw: unknown = JSON.parse(readFileSync(examplePath, 'utf8')); + 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 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', () => { + 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 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 store: CatalogComponent = loadExample().components.find( + (c) => c.id === 'example-store', + )!; + 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 deferred = catalog.recipes.find((r) => r.id === 'example-deferred')!; + expect(recipePackagesReady(catalog, deferred)).toBe(false); + + const partialCatalog: CompositionCatalog = { + schemaVersion: CATALOG_SCHEMA_VERSION, + generatedAt: '2026-07-28T00:00:00.000Z', + components: [ + { + id: 'demo', + title: 'Demo', + repo: 'demo', + packages: [ + { name: '@example/demo-core', version: '0.1.0', published: true }, + { name: '@example/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/example/demo' }, + }, + ], + recipes: [ + emptyRecipe({ + id: 'needs-extra', + intent: 'A fictional partial-package case that asks for the unpublished sibling.', + 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, + emptyRecipe({ + id: 'core-only', + intent: 'A fictional recipe that only needs the published core package.', + packages: ['@example/demo-core'], + }), + ), + ).toBe(true); + expect( + 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, + 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('@example/contracts@0.0.1')).toEqual({ + name: '@example/contracts', + version: '0.0.1', + }); + 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('@example/contracts@')).toEqual({ + name: '@example/contracts', + version: '', + }); + expect( + 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); + }); + + 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 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({ + 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: ['spine'], + adapters: [], + hostMustProvide: [], + capabilityTags: [], + recipeIds: [], + links: { githubRepo: 'https://github.com/example/x' }, + }, + ], + recipes: [], + }), + ).toThrow(/dependencies\[0\]/); + }); + + 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(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['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 new file mode 100644 index 0000000..3649a3d --- /dev/null +++ b/src/data/catalog-schema.ts @@ -0,0 +1,288 @@ +/** + * 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; +} + +/** + * 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'`. + */ +export interface CatalogRecipe { + readonly id: string; + /** One-paragraph synthetic product shape — never a real commercial product */ + readonly intent: string; + /** Package names, optionally pinned as `name@version` once fixtures exist */ + readonly packages: 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 */ + 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; + /** 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[]; +} + +/** + * 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'; +} + +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( + component: CatalogComponent, +): readonly string[] { + 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; + /** 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) { + // 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) }; + } + 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 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), + ); + 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; +} 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, },