diff --git a/docs/AGENT_ASSEMBLY_PLAN.md b/docs/AGENT_ASSEMBLY_PLAN.md index 27d4735..8a4586f 100644 --- a/docs/AGENT_ASSEMBLY_PLAN.md +++ b/docs/AGENT_ASSEMBLY_PLAN.md @@ -2,8 +2,8 @@ ## Status -**Stage:** Phase 4 complete (public catalog MCP). Phase 5 (scaffold + eval) -remains open. +**Stage:** Phase 5 complete (scaffold + offline assembly eval). Implementable +agent-assembly plan work is done. 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 @@ -26,6 +26,8 @@ what the Pegma stack already packages (typed, tested, pin-able components). | Skill install notes | `https://pegma.dev/skill` (`src/pages/skill.astro`) | | Catalog tool logic | `src/data/mcp-tools.ts` | | MCP Worker surface | `worker/src/mcp-server.ts` → `https://pegma.dev/api/mcp` | +| Minimal CF scaffold | `recipes/scaffold-cf-minimal/` | +| Offline assembly eval | `evals/assembly-eval.ts` (`npm run eval:assembly`) | **Goal:** An agent given a short product description chooses the right `@pegma/*` packages, respects their refusals, and wires them at an explicit @@ -343,7 +345,7 @@ no private data plane. and `llms.txt`; `plan_composition` is rule-based over structured `capabilityTags`. -### Phase 5 — Scaffold and eval harness +### Phase 5 — Scaffold and eval harness ✓ Public synthetic starter template with pinned known-good versions and an empty-ish composition root. Small offline or CI eval set of prompts @@ -351,8 +353,33 @@ empty-ish composition root. Small offline or CI eval set of prompts only”, “do not use passwords”) scored on package selection and refusal compliance — not on UI polish. -**Exit:** measured improvement when skill + catalog (+ MCP if present) are -enabled vs. baseline agent with only web search. +Shipped: + +| Surface | Path | +| --- | --- | +| Scaffold fixture | `recipes/scaffold-cf-minimal/` (Glass Wing) | +| Catalog recipe | `static-brochure-minimal` (green scaffold citation) | +| Eval cases | `evals/assembly-cases.ts` | +| Eval runner | `evals/assembly-eval.ts` | +| CI coverage | `evals/assembly-eval.test.ts` via `npm test` / `npm run eval:assembly` | + +The offline harness scores `plan_composition` over the **compiled** catalog +against the prompt set. Offline baseline is a **no-catalog** empty plan +(agent never fetches catalog facts): same package/refusal assertions, scored +honestly. Catalog mode must beat that pass rate. That is the automated gate; +full multi-agent LLM A/B (web search vs skill+catalog+MCP) remains optional +outside CI and is not claimed by the unit harness alone. + +**Exit (automated):** offline compiled-catalog planner pass rate strictly +greater than the offline **no-catalog** baseline on the four Phase 5 prompts; +scaffold fixture green and catalog-cited. + +**Exit (optional, out of band):** full multi-agent LLM A/B (web search only vs +skill + catalog + MCP) remains available for human/operator measurement and is +not required for the CI gate. + +**Done:** automated exit met — compiled-catalog pass rate > no-catalog baseline +on the four prompts; scaffold fixture is green and cited from the catalog. ## Non-goals diff --git a/docs/catalog/RECIPE_BACKLOG.md b/docs/catalog/RECIPE_BACKLOG.md index 081a0a2..03e098f 100644 --- a/docs/catalog/RECIPE_BACKLOG.md +++ b/docs/catalog/RECIPE_BACKLOG.md @@ -72,15 +72,17 @@ deferred). | **requiresPublished** | spine, logger-adapters | | **Fixture** | pending | -### P6 — `static-brochure-minimal` +### P6 — `static-brochure-minimal` (scaffold) | | | | --- | --- | -| **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 | +| **Intent** | A fictional static museum site (“Glass Wing”) needs no accounts, no durable storage, and no mail — only honest stack awareness. Teaches agents to **select nothing extra**. Optional Worker health is host-owned (`withHealth`), not a required catalog capability. | +| **Packages (pinned)** | `@pegma/spine@0.1.1` only (fixture does not import `@pegma/health`; host may add health from the catalog) | +| **Host must provide** | Static hosting / optional Worker fetch; explicit empty-ish composition root | | **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 | +| **requiresPublished** | spine | +| **capabilityTags** | `static_host` only (not bare `cloudflare` — host-tag alone must not select this scaffold) | +| **Fixture** | green — [`recipes/scaffold-cf-minimal/`](../../recipes/scaffold-cf-minimal/) | ## Deferred (unpublished packages) diff --git a/evals/assembly-cases.ts b/evals/assembly-cases.ts new file mode 100644 index 0000000..cb96023 --- /dev/null +++ b/evals/assembly-cases.ts @@ -0,0 +1,84 @@ +/** + * Offline assembly eval cases for Phase 5. + * + * Prompts are scored by mapping them to structured capabilityTags and + * running plan_composition over the **compiled** catalog (same path as + * catalog.json). This measures package selection and refusal compliance + * without hosting an LLM in Pegma. + * + * Offline “no-catalog” baseline: empty package set and no refuse notes + * (agent never fetched catalog facts). Same assertions as catalog mode. + * This is not a full web-search LLM A/B — it measures the planner gate + * against a no-catalog agent. Live multi-agent eval remains out of band. + */ + +import type { CapabilityTag } from '../src/data/catalog-schema'; + +export interface AssemblyEvalCase { + readonly id: string; + /** Short product prompt (synthetic). */ + readonly prompt: string; + /** Structured tags an agent should pass to plan_composition. */ + readonly capabilityTags: readonly CapabilityTag[]; + readonly host?: 'cloudflare' | 'azure' | 'memory' | 'other'; + /** Package name substrings that must appear in the plan. */ + readonly mustIncludePackageNames?: readonly string[]; + /** Package name substrings that must not appear. */ + readonly mustNotIncludePackageNames?: readonly string[]; + /** Substrings that must appear in combined refuses notes / component refuses. */ + readonly mustSurfaceRefusalSubstrings?: readonly string[]; + /** Substrings that must not appear in recommended package names. */ + readonly mustNotRecommendSubstrings?: readonly string[]; + /** Primary recipe id that must be selected (catalog mode). */ + readonly mustPrimaryRecipeId?: string; + /** Primary recipe id that must not be selected (catalog mode). */ + readonly mustNotPrimaryRecipeId?: string; +} + +/** + * Plan Phase 5 prompt set: static brochure, passkeys on Workers, health only, + * and password refusal compliance. + */ +export const ASSEMBLY_EVAL_CASES: readonly AssemblyEvalCase[] = [ + { + id: 'static-brochure', + prompt: + 'Static brochure museum site (Glass Wing). No accounts, no durable storage, no mail.', + capabilityTags: ['static_host'], + mustPrimaryRecipeId: 'static-brochure-minimal', + mustNotIncludePackageNames: [ + '@pegma/identity', + '@pegma/sessions', + '@pegma/mail', + '@pegma/storage-core', + ], + }, + { + id: 'passkey-accounts-workers', + prompt: + 'Passkey accounts on Cloudflare Workers with email-code fallback. No passwords.', + capabilityTags: ['accounts', 'passkeys', 'email_codes', 'cloudflare'], + host: 'cloudflare', + mustIncludePackageNames: ['@pegma/identity'], + mustNotRecommendSubstrings: ['password'], + mustSurfaceRefusalSubstrings: ['password'], + }, + { + id: 'health-endpoint-only', + prompt: 'Public liveness health endpoint only on a small Worker.', + capabilityTags: ['health'], + mustIncludePackageNames: ['@pegma/health'], + mustNotIncludePackageNames: ['@pegma/identity', '@pegma/mail'], + // Do not send agents to the static museum scaffold for a health-only plan. + mustNotPrimaryRecipeId: 'static-brochure-minimal', + }, + { + id: 'no-passwords', + prompt: + 'First-party accounts for a club site. Passkeys preferred. Do not use passwords.', + capabilityTags: ['accounts', 'passkeys'], + mustIncludePackageNames: ['@pegma/identity'], + mustNotRecommendSubstrings: ['password'], + mustSurfaceRefusalSubstrings: ['password'], + }, +]; diff --git a/evals/assembly-eval.test.ts b/evals/assembly-eval.test.ts new file mode 100644 index 0000000..5ebc61f --- /dev/null +++ b/evals/assembly-eval.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it, beforeAll } from 'vitest'; +import { + clearNpmVersionCache, + compileCompositionCatalog, +} from '../src/data/compile-catalog'; +import { components } from '../src/data/components'; +import type { CompositionCatalog } from '../src/data/catalog-schema'; +import { runAssemblyEval } from './assembly-eval'; +import { ASSEMBLY_EVAL_CASES } from './assembly-cases'; + +const FIXED_AT = '2026-07-29T12:00:00.000Z'; +const NO_STAGES: Record = Object.fromEntries( + components.map((c) => [c.repo, null]), +); + +/** + * Deterministic npm pins matching known-good published versions used by + * recipe backlog pins and the site worker. Never hits the network. + */ +const EVAL_NPM: Record = { + '@pegma/spine': '0.1.1', + '@pegma/storage-core': '0.4.0', + '@pegma/storage-azure-tables': '0.4.0', + '@pegma/storage-cloudflare-d1': '0.4.0', + '@pegma/storage-blobs': '0.1.0', + '@pegma/storage-azure-blob': '0.1.0', + '@pegma/storage-cloudflare-r2': '0.1.0', + '@pegma/storage-s3': '0.1.0', + '@pegma/authorization-contracts': '0.1.2', + '@pegma/authorization-core': '0.1.2', + '@pegma/authorization-policy': '0.1.2', + '@pegma/authorization-auth0': '0.1.2', + '@pegma/authorization-stripe': '0.1.2', + '@pegma/authorization-storage': '0.1.2', + '@pegma/authorization-tokens': '0.1.2', + '@pegma/authorization-identity': '0.1.2', + '@pegma/audit': '0.1.0', + '@pegma/support-desk-contracts': '0.1.0', + '@pegma/support-desk-core': '0.1.0', + '@pegma/support-desk-application': '0.1.0', + '@pegma/support-desk-templates': '0.1.0', + '@pegma/webhooks': null, // unpublished for production assembly + '@pegma/sessions': '0.1.0', + '@pegma/mail': '0.1.0', + '@pegma/billing-core': null, + '@pegma/identity': '0.1.0', + '@pegma/rate-limit': '0.1.0', + '@pegma/logger-tee': '0.1.1', + '@pegma/logger-applicationinsights': '0.1.1', + '@pegma/logger-cloudflare': '0.1.1', + '@pegma/logger-datadog': '0.1.1', + '@pegma/health': '0.1.1', +}; + +async function compileEvalCatalog(): Promise { + clearNpmVersionCache(); + return compileCompositionCatalog({ + generatedAt: FIXED_AT, + stageByRepo: NO_STAGES, + npmLookup: async (name) => + Object.prototype.hasOwnProperty.call(EVAL_NPM, name) + ? EVAL_NPM[name]! + : null, + }); +} + +describe('assembly eval harness (Phase 5)', () => { + let catalog: CompositionCatalog; + + beforeAll(async () => { + catalog = await compileEvalCatalog(); + }); + + it('defines the plan prompt set', () => { + expect(ASSEMBLY_EVAL_CASES.map((c) => c.id).sort()).toEqual( + [ + 'health-endpoint-only', + 'no-passwords', + 'passkey-accounts-workers', + 'static-brochure', + ].sort(), + ); + }); + + it('compiles the real catalog artifact (not a hand-built twin)', () => { + expect(catalog.schemaVersion).toBe('0.1.0'); + expect(catalog.components.length).toBe(components.length); + const scaffold = catalog.recipes.find((r) => r.id === 'static-brochure-minimal'); + expect(scaffold?.fixture.status).toBe('green'); + expect(scaffold?.fixture.citation).toContain('scaffold-cf-minimal'); + expect(scaffold?.capabilityTags).toEqual(['static_host']); + expect(scaffold?.capabilityTags).not.toContain('health'); + expect(scaffold?.capabilityTags).not.toContain('cloudflare'); + }); + + it('baseline scores assertions against an empty plan (not forced all-fail)', () => { + const report = runAssemblyEval(null, 'baseline'); + // Static brochure may pass (must-not-include only); include cases fail. + const byId = Object.fromEntries(report.cases.map((c) => [c.id, c])); + expect(byId['static-brochure']?.pass).toBe(true); + expect(byId['passkey-accounts-workers']?.pass).toBe(false); + expect(byId['health-endpoint-only']?.pass).toBe(false); + expect(byId['no-passwords']?.pass).toBe(false); + expect(report.passRate).toBeGreaterThan(0); + expect(report.passRate).toBeLessThan(1); + }); + + it('catalog planner improves pass rate over baseline on compiled catalog', () => { + const baseline = runAssemblyEval(null, 'baseline'); + const withCatalog = runAssemblyEval(catalog, 'catalog'); + expect(withCatalog.passRate).toBeGreaterThan(baseline.passRate); + for (const c of withCatalog.cases) { + expect(c.pass, `${c.id}: ${JSON.stringify(c.checks)}`).toBe(true); + } + expect(withCatalog.passRate).toBe(1); + + const staticCase = withCatalog.cases.find((c) => c.id === 'static-brochure')!; + expect(staticCase.primaryRecipeId).toBe('static-brochure-minimal'); + + const healthCase = withCatalog.cases.find((c) => c.id === 'health-endpoint-only')!; + expect(healthCase.primaryRecipeId).not.toBe('static-brochure-minimal'); + expect(healthCase.packageNames.some((p) => p.includes('@pegma/health'))).toBe( + true, + ); + }); +}); diff --git a/evals/assembly-eval.ts b/evals/assembly-eval.ts new file mode 100644 index 0000000..2d654b9 --- /dev/null +++ b/evals/assembly-eval.ts @@ -0,0 +1,191 @@ +/** + * Offline eval runner: score plan_composition against ASSEMBLY_EVAL_CASES. + * + * - catalog mode: planComposition over a CompositionCatalog + * - baseline mode (“no-catalog”): empty package set + no refuse notes. + * Same assertions as catalog mode — not a forced all-fail, and not a + * simulated web-search LLM. Live multi-agent A/B remains out of band. + */ + +import type { CompositionCatalog } from '../src/data/catalog-schema'; +import { planComposition } from '../src/data/mcp-tools'; +import { + ASSEMBLY_EVAL_CASES, + type AssemblyEvalCase, +} from './assembly-cases'; + +export interface CaseScore { + readonly id: string; + readonly pass: boolean; + readonly checks: readonly { + readonly name: string; + readonly pass: boolean; + readonly detail?: string; + }[]; + readonly packageNames: readonly string[]; + readonly primaryRecipeId: string | null; +} + +export interface EvalReport { + readonly schema: 'pegma.assembly_eval.v1'; + readonly mode: 'baseline' | 'catalog'; + readonly total: number; + readonly passed: number; + readonly passRate: number; + readonly cases: readonly CaseScore[]; +} + +function primaryRecipeIdFromNotes(notes: readonly string[]): string | null { + for (const n of notes) { + const m = /^primary recipe:\s*([^\s;]+)/.exec(n); + if (m) return m[1] ?? null; + } + return null; +} + +function scoreAssertions( + c: AssemblyEvalCase, + packageNames: readonly string[], + refuseBlob: string, + primaryRecipeId: string | null, + mode: 'baseline' | 'catalog', +): CaseScore['checks'][number][] { + const checks: CaseScore['checks'][number][] = []; + + for (const name of c.mustIncludePackageNames ?? []) { + const pass = packageNames.some((p) => p.includes(name) || p === name); + checks.push({ + name: `must_include:${name}`, + pass, + detail: pass ? undefined : `packages=${packageNames.join(',')}`, + }); + } + + for (const name of c.mustNotIncludePackageNames ?? []) { + const pass = !packageNames.some((p) => p.includes(name) || p === name); + checks.push({ + name: `must_not_include:${name}`, + pass, + detail: pass ? undefined : `found in ${packageNames.join(',')}`, + }); + } + + for (const sub of c.mustNotRecommendSubstrings ?? []) { + const lower = sub.toLowerCase(); + const pass = !packageNames.some((p) => p.toLowerCase().includes(lower)); + checks.push({ + name: `must_not_recommend_substring:${sub}`, + pass, + }); + } + + for (const sub of c.mustSurfaceRefusalSubstrings ?? []) { + const pass = refuseBlob.toLowerCase().includes(sub.toLowerCase()); + checks.push({ + name: `must_surface_refusal:${sub}`, + pass, + detail: pass ? undefined : 'refusal not found in notes/component refuses', + }); + } + + // Recipe identity checks only apply when a catalog plan exists. + if (mode === 'catalog' && c.mustPrimaryRecipeId) { + const pass = primaryRecipeId === c.mustPrimaryRecipeId; + checks.push({ + name: `must_primary_recipe:${c.mustPrimaryRecipeId}`, + pass, + detail: pass ? undefined : `primary=${primaryRecipeId ?? 'none'}`, + }); + } + + if (mode === 'catalog' && c.mustNotPrimaryRecipeId) { + const pass = primaryRecipeId !== c.mustNotPrimaryRecipeId; + checks.push({ + name: `must_not_primary_recipe:${c.mustNotPrimaryRecipeId}`, + pass, + detail: pass ? undefined : `primary=${primaryRecipeId}`, + }); + } + + if (checks.length === 0) { + checks.push({ name: 'no_assertions', pass: true }); + } + + return checks; +} + +function scoreCase( + catalog: CompositionCatalog | null, + c: AssemblyEvalCase, + mode: 'baseline' | 'catalog', +): CaseScore { + if (mode === 'baseline' || !catalog) { + // Agent never fetched catalog facts: empty install set, no refuse notes. + const packageNames: string[] = []; + const refuseBlob = ''; + const primaryRecipeId = null; + const checks = scoreAssertions( + c, + packageNames, + refuseBlob, + primaryRecipeId, + 'baseline', + ); + return { + id: c.id, + pass: checks.every((x) => x.pass), + checks, + packageNames, + primaryRecipeId, + }; + } + + const plan = planComposition(catalog, { + capabilityTags: c.capabilityTags, + host: c.host, + productionOnly: true, + }); + const packageNames = plan.packages.map((p) => p.name); + const refuseBlob = [ + ...plan.notes, + ...plan.components.flatMap((comp) => { + const full = catalog.components.find((x) => x.id === comp.id); + return full?.refuses ?? []; + }), + ].join(' | '); + const primaryRecipeId = + plan.recipes[0]?.id ?? primaryRecipeIdFromNotes(plan.notes); + + const checks = scoreAssertions( + c, + packageNames, + refuseBlob, + primaryRecipeId, + 'catalog', + ); + + return { + id: c.id, + pass: checks.every((x) => x.pass), + checks, + packageNames, + primaryRecipeId, + }; +} + +export function runAssemblyEval( + catalog: CompositionCatalog | null, + mode: 'baseline' | 'catalog', + cases: readonly AssemblyEvalCase[] = ASSEMBLY_EVAL_CASES, +): EvalReport { + const scored = cases.map((c) => scoreCase(catalog, c, mode)); + const passed = scored.filter((s) => s.pass).length; + return { + schema: 'pegma.assembly_eval.v1', + mode, + total: scored.length, + passed, + passRate: scored.length === 0 ? 0 : passed / scored.length, + cases: scored, + }; +} diff --git a/package.json b/package.json index 6b91daf..fd821b9 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "test": "vitest run --config vitest.config.ts && vitest run --config vitest.d1.config.ts", "test:node": "vitest run --config vitest.config.ts", "test:d1": "vitest run --config vitest.d1.config.ts", + "eval:assembly": "vitest run --config vitest.config.ts evals/assembly-eval.test.ts", "preview": "astro preview", "worker:dev": "wrangler dev -c worker/wrangler.jsonc", "worker:deploy": "wrangler deploy -c worker/wrangler.jsonc", diff --git a/public/llms.txt b/public/llms.txt index 78c402d..783cdb5 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -97,6 +97,12 @@ status, design decisions, and non-goals. `get_recipe`, `plan_composition`. Public catalog facts only; no private data plane; no auth for reads. Config notes: https://pegma.dev/skill +## Scaffold (agents) + +- Minimal Cloudflare-shaped composition root (Glass Wing synthetic scaffold): + https://github.com/pegma-dev/pegma.dev/tree/main/recipes/scaffold-cf-minimal + Empty-ish root with optional health; pin versions from catalog.json. + ## Site - [The stack](https://pegma.dev/stack): every component — owns, refuses, diff --git a/recipes/README.md b/recipes/README.md index 926ef9e..80f12a5 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -7,6 +7,7 @@ CI-tested composition sketches for agents. Product names and domains are | --- | --- | --- | | `cf-passkey-accounts` | Northshelf Branch — passkey + email-code accounts on a Cloudflare-shaped host | [`cf-passkey-accounts/`](./cf-passkey-accounts/) | | `storage-audit-mail-outbox` | Yard Loan — inventory mutation + audit + mail job in one transaction | [`storage-audit-mail-outbox/`](./storage-audit-mail-outbox/) | +| `static-brochure-minimal` (scaffold) | Glass Wing — empty-ish CF composition root; optional health is host-owned | [`scaffold-cf-minimal/`](./scaffold-cf-minimal/) | ## Rules @@ -20,8 +21,13 @@ CI-tested composition sketches for agents. Product names and domains are ## Production vs test adapters -Composition roots **require** an injected `Store`. Tests pass +Fixtures that use Storage Core (`cf-passkey-accounts`, +`storage-audit-mail-outbox`) **require** an injected `Store`. Tests pass `createMemoryStore()` explicitly so CI stays fast and free of cloud credentials; production hosts inject a durable adapter (for example Cloudflare D1 for `cf-passkey-accounts`). Memory is never a silent default and never a durability claim. + +The static scaffold (`scaffold-cf-minimal` / `static-brochure-minimal`) is +**Store-free** by design — empty-ish until the agent adds features from the +catalog. diff --git a/recipes/scaffold-cf-minimal/composition.test.ts b/recipes/scaffold-cf-minimal/composition.test.ts new file mode 100644 index 0000000..232a991 --- /dev/null +++ b/recipes/scaffold-cf-minimal/composition.test.ts @@ -0,0 +1,38 @@ +import { fixedClock } from '@pegma/spine'; +import { describe, expect, it } from 'vitest'; +import { createGlassWingComposition, GLASS_WING } from './composition'; + +describe('scaffold-cf-minimal (Glass Wing)', () => { + it('builds an empty-ish composition root without health', () => { + const composition = createGlassWingComposition({ + clock: fixedClock('2026-07-29T00:00:00.000Z'), + }); + expect(composition.withHealth).toBe(false); + expect(composition.health).toBeUndefined(); + expect(composition.clock.now()).toBe('2026-07-29T00:00:00.000Z'); + }); + + it('optionally exposes a host-owned liveness handler without @pegma/health', async () => { + const composition = createGlassWingComposition({ + clock: fixedClock('2026-07-29T00:00:00.000Z'), + withHealth: true, + }); + expect(composition.withHealth).toBe(true); + expect(composition.health).toBeTypeOf('function'); + const res = await composition.health!(); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + service: GLASS_WING.service, + status: 'ok', + scaffold: true, + }); + }); + + it('does not invent accounts, storage, or mail wiring', () => { + const composition = createGlassWingComposition({ withHealth: true }); + expect(composition).not.toHaveProperty('identity'); + expect(composition).not.toHaveProperty('sessions'); + expect(composition).not.toHaveProperty('store'); + expect(composition).not.toHaveProperty('mailWorker'); + }); +}); diff --git a/recipes/scaffold-cf-minimal/composition.ts b/recipes/scaffold-cf-minimal/composition.ts new file mode 100644 index 0000000..93e1fec --- /dev/null +++ b/recipes/scaffold-cf-minimal/composition.ts @@ -0,0 +1,89 @@ +/** + * Recipe / scaffold: scaffold-cf-minimal + * + * Synthetic starter: “Glass Wing” — a fictional static museum site Worker + * with an explicit composition root. Empty-ish on purpose: agents modify + * this skeleton instead of inventing composition from scratch. + * + * Known-good pins (align with catalog.json / recipe packages): + * @pegma/spine@0.1.1 + * + * Optional health: host may add @pegma/health later; this fixture does not + * import it so the catalog package list (spine only) stays honest. + * + * Not a branded product clone. No accounts, storage, or mail unless the + * agent deliberately adds them from the catalog. + */ + +import { + systemClock, + type Clock, + type Logger, +} from '@pegma/spine'; + +/** Fictional museum static site. */ +export const GLASS_WING = { + service: 'glass-wing-site', + siteOrigin: 'https://glasswing.example', +} as const; + +export interface GlassWingCompositionOptions { + readonly clock?: Clock; + readonly logger?: Logger; + /** + * When true, expose a minimal host-owned liveness handler that does **not** + * depend on @pegma/health — teaches the composition-root shape only. + * For production probes, prefer composing @pegma/health at the host. + */ + readonly withHealth?: boolean; +} + +export interface GlassWingComposition { + readonly clock: Clock; + readonly logger: Logger | undefined; + readonly withHealth: boolean; + /** + * Optional liveness handler. Present only when `withHealth` is true. + * Host wires this to GET /health (or equivalent). + */ + readonly health?: () => Promise<{ + readonly status: number; + readonly body: unknown; + }>; +} + +/** + * Explicit composition root for a minimal Cloudflare-shaped Worker host. + * Wire packages here — do not autodiscover. + */ +export function createGlassWingComposition( + options: GlassWingCompositionOptions = {}, +): GlassWingComposition { + const clock = options.clock ?? systemClock; + const logger = options.logger; + const withHealth = options.withHealth === true; + + if (!withHealth) { + return { clock, logger, withHealth: false }; + } + + return { + clock, + logger, + withHealth: true, + health: async () => { + // Minimal host-owned probe — not @pegma/health. Agents that want + // composable probes should install and wire @pegma/health from the catalog. + return { + status: 200, + body: { + service: GLASS_WING.service, + status: 'ok', + scaffold: true, + site: GLASS_WING.siteOrigin, + now: clock.now(), + }, + }; + }, + }; +} diff --git a/src/data/compile-catalog.test.ts b/src/data/compile-catalog.test.ts index 1f1103b..73cc519 100644 --- a/src/data/compile-catalog.test.ts +++ b/src/data/compile-catalog.test.ts @@ -106,12 +106,19 @@ describe('compileCompositionCatalog', () => { for (const recipe of catalog.recipes) { expect(recipe.intent).not.toMatch(/retiregolden/i); } + const scaffold = catalog.recipes.find((r) => r.id === 'static-brochure-minimal')!; + expect(scaffold.fixture).toMatchObject({ + kind: 'scaffold', + status: 'green', + }); + expect(scaffold.fixture.citation).toContain('recipes/scaffold-cf-minimal'); // Unshipped backlog recipes remain non-green (no invented wiring). - const pendingOrNone = catalog.recipes.filter( - (r) => - r.id !== 'cf-passkey-accounts' && - r.id !== 'storage-audit-mail-outbox', - ); + const greenIds = new Set([ + 'cf-passkey-accounts', + 'storage-audit-mail-outbox', + 'static-brochure-minimal', + ]); + const pendingOrNone = catalog.recipes.filter((r) => !greenIds.has(r.id)); for (const recipe of pendingOrNone) { expect(recipe.fixture.status).not.toBe('green'); } diff --git a/src/data/mcp-tools.test.ts b/src/data/mcp-tools.test.ts index db6c183..e81163f 100644 --- a/src/data/mcp-tools.test.ts +++ b/src/data/mcp-tools.test.ts @@ -111,6 +111,75 @@ describe('plan_composition', () => { ).toBe(true); }); + it('does not let host-ambient-only recipes win when core tags are requested', () => { + const catalog = { + ...exampleCatalog, + recipes: [ + ...exampleCatalog.recipes, + { + id: 'ambient-scaffold', + intent: 'Ambient-only scaffold', + packages: ['@example/contracts'], + adapters: [], + hostResponsibilities: [], + nonGoals: [], + antiPatterns: [], + fixture: { + kind: 'scaffold' as const, + citation: 'recipes/x', + status: 'green' as const, + }, + capabilityTags: ['static_host', 'cloudflare'] as const, + requiresPublished: ['example-contracts'], + backlogPriority: 1, + }, + ], + }; + const plan = planComposition(catalog, { + capabilityTags: ['storage', 'cloudflare'], + productionOnly: false, + }); + expect(plan.recipes.map((r) => r.id)).not.toContain('ambient-scaffold'); + }); + + it('keeps explicitly requested logging on mixed core+ambient plans', () => { + const catalog = { + ...exampleCatalog, + components: [ + ...exampleCatalog.components, + { + id: 'logger-adapters', + title: 'Logger Adapters', + repo: 'logger-adapters', + packages: [ + { + name: '@example/logger-tee', + version: '0.0.1', + published: true, + }, + ], + status: 'published' as const, + publishUsability: 'usable' as const, + summary: 'Logger sinks', + owns: ['Logger adapters'], + refuses: ['APM'], + dependencies: [], + adapters: [], + hostMustProvide: ['Composition root Logger'], + capabilityTags: ['logging'] as const, + recipeIds: [], + links: { githubRepo: 'https://github.com/example/logger-adapters' }, + }, + ], + }; + const plan = planComposition(catalog, { + capabilityTags: ['storage', 'logging'], + productionOnly: false, + }); + expect(plan.components.some((c) => c.id === 'logger-adapters')).toBe(true); + expect(plan.packages.map((p) => p.name)).toContain('@example/logger-tee'); + }); + it('filters adapter packages by host', () => { const plan = planComposition(exampleCatalog, { capabilityTags: ['storage', 'cloudflare'], diff --git a/src/data/mcp-tools.ts b/src/data/mcp-tools.ts index 19cc917..1583d1b 100644 --- a/src/data/mcp-tools.ts +++ b/src/data/mcp-tools.ts @@ -132,6 +132,25 @@ function meaningfulCoverage( const itemCore = coreTags(itemTags); const reqCore = coreTags(requested); if (itemCore.length === 0) { + // Ambient-only items (logger-adapters, static scaffold, spine, …). + const hostAmbient = new Set([ + 'cloudflare', + 'azure', + 'static_host', + ]); + const requestedNonHostAmbient = requested.filter( + (t) => AMBIENT_TAGS.has(t) && !hostAmbient.has(t), + ); + if (reqCore.length > 0) { + // Mixed request: admit ambient-only items only when a non-host ambient + // capability was explicitly requested (e.g. logging + accounts). + // Host tags alone (cloudflare) must not select the static scaffold. + return ( + tagOverlap(itemTags, requestedNonHostAmbient) > 0 && + tagOverlap(itemTags, requested) > 0 + ); + } + // Ambient-only request: any overlapping ambient tag is enough. return tagOverlap(itemTags, requested) > 0; } const overlap = tagOverlap(itemCore, reqCore.length > 0 ? reqCore : requested); diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index 6545993..1d98331 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -185,22 +185,29 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ { id: 'static-brochure-minimal', intent: - 'A fictional static museum site (Glass Wing) needs no accounts, no durable storage, and no mail — teaching agents to select nothing extra.', - packages: [], + 'A fictional static museum site (Glass Wing) needs no accounts, no durable storage, and no mail — teaching agents to select nothing extra. Optional Worker health probe is host-owned (withHealth), not a required composition capability.', + packages: ['@pegma/spine@0.1.1'], adapters: [], - hostResponsibilities: ['Static hosting only'], + hostResponsibilities: [ + 'Static hosting and optional Worker fetch route', + 'Explicit composition root (empty-ish until features are added)', + 'Optional @pegma/health probe when a public liveness route is desired', + ], nonGoals: ['Accounts, sessions, databases'], antiPatterns: [ 'Pulling identity/sessions for later', 'Inventing a database for a static site', ], fixture: { - kind: 'pending', - citation: 'docs/catalog/RECIPE_BACKLOG.md#p6--static-brochure-minimal', - status: 'pending', + kind: 'scaffold', + citation: + 'https://github.com/pegma-dev/pegma.dev/tree/main/recipes/scaffold-cf-minimal', + status: 'green', }, + // Only static_host (not bare cloudflare) so host-tag-only plans do not + // select the Glass Wing scaffold. Do not attach `health` here. capabilityTags: ['static_host'], - requiresPublished: [], + requiresPublished: ['spine'], backlogPriority: 6, }, { diff --git a/vitest.config.ts b/vitest.config.ts index 25705b2..c65b2af 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,6 +6,7 @@ export default defineConfig({ 'worker/src/**/*.test.ts', 'src/**/*.test.ts', 'recipes/**/*.test.ts', + 'evals/**/*.test.ts', ], exclude: ['**/node_modules/**', '**/*.d1.test.ts'], testTimeout: 30_000,