From 204312f19aec53bee4e8b528d75585e041c4ce7c Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 09:08:27 -0400 Subject: [PATCH 1/7] [2] Synthetic recipe fixtures for agent assembly catalog. Add CI-tested Northshelf accounts and Yard Loan outbox compositions under recipes/, mark those catalog entries green, and grow /examples into a recipe index that quotes only fixture and package sources. --- docs/AGENT_ASSEMBLY_PLAN.md | 39 +-- docs/catalog/GAP_INVENTORY.md | 13 +- docs/catalog/RECIPE_BACKLOG.md | 4 +- package-lock.json | 23 ++ package.json | 3 +- public/llms.txt | 5 +- recipes/README.md | 26 ++ .../cf-passkey-accounts/composition.test.ts | 83 ++++++ recipes/cf-passkey-accounts/composition.ts | 194 ++++++++++++++ .../composition.test.ts | 92 +++++++ .../storage-audit-mail-outbox/composition.ts | 244 ++++++++++++++++++ recipes/tsconfig.json | 15 ++ src/data/compile-catalog.test.ts | 23 +- src/data/recipe-backlog.ts | 17 +- src/pages/examples.astro | 137 +++++++++- vitest.config.ts | 6 +- 16 files changed, 877 insertions(+), 47 deletions(-) create mode 100644 recipes/README.md create mode 100644 recipes/cf-passkey-accounts/composition.test.ts create mode 100644 recipes/cf-passkey-accounts/composition.ts create mode 100644 recipes/storage-audit-mail-outbox/composition.test.ts create mode 100644 recipes/storage-audit-mail-outbox/composition.ts create mode 100644 recipes/tsconfig.json diff --git a/docs/AGENT_ASSEMBLY_PLAN.md b/docs/AGENT_ASSEMBLY_PLAN.md index a243ae8..b2e497a 100644 --- a/docs/AGENT_ASSEMBLY_PLAN.md +++ b/docs/AGENT_ASSEMBLY_PLAN.md @@ -2,13 +2,13 @@ ## Status -**Stage:** Phase 1 complete (compiled `catalog.json` at site build). No 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). +**Stage:** Phase 2 complete for required fixtures (P1 + P2 under `recipes/`). +No hosted skill or MCP surface 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–1 artifacts:** +**Phase 0–2 artifacts:** | Artifact | Path | | --- | --- | @@ -19,6 +19,8 @@ already packages (typed, tested, pin-able components). | Example catalog (fictional shape sample) | `docs/catalog/example-catalog.json` | | Catalog compiler | `src/data/compile-catalog.ts` | | Published catalog | `https://pegma.dev/catalog.json` (build emit) | +| P1 fixture (Northshelf accounts) | `recipes/cf-passkey-accounts/` | +| P2 fixture (Yard Loan outbox) | `recipes/storage-audit-mail-outbox/` | **Goal:** An agent given a short product description chooses the right `@pegma/*` packages, respects their refusals, and wires them at an explicit @@ -262,14 +264,11 @@ enrichment + recipe backlog). `public/llms.txt` links the catalog without inlining it. Unpublished packages get `published: false` / `publishUsability: unpublished|partial`. -### Phase 2 — Synthetic recipe fixtures +### Phase 2 — Synthetic recipe fixtures ✓ Create public, CI-tested fixtures for the highest-value published -compositions. Preferred homes (decide at implementation, boring wins): - -- a dedicated public repo (e.g. recipe or examples host under pegma-dev), or -- `packages/recipes` / fixture apps inside component repos where the - composition is local to one package boundary +compositions. Home chosen: `recipes/` in this repository (boring wins over a +second repo until coverage grows). Rules for fixtures: @@ -279,12 +278,18 @@ Rules for fixtures: - Site/catalog may only quote code that exists in those fixtures (or in already-public package README/conformance sources) -Ship at least one end-to-end “accounts on Cloudflare-shaped host” recipe -and one “storage + audit/mail outbox pattern” recipe before declaring the -phase done. +Shipped: + +| Recipe | Path | Catalog fixture | +| --- | --- | --- | +| `cf-passkey-accounts` | `recipes/cf-passkey-accounts/` | green | +| `storage-audit-mail-outbox` | `recipes/storage-audit-mail-outbox/` | green | + +P3–P6 remain pending. Deferred D1–D2 still wait on package publication. -**Exit:** catalog recipe entries resolve to green fixtures; `/examples` -can grow from skeleton to recipe index without inventing code. +**Exit:** catalog recipe entries resolve to green fixtures for P1–P2; +`/examples` indexes those recipes and quotes only fixture (or package +README) sources. ### Phase 3 — Hosted skill diff --git a/docs/catalog/GAP_INVENTORY.md b/docs/catalog/GAP_INVENTORY.md index b28066f..c65d849 100644 --- a/docs/catalog/GAP_INVENTORY.md +++ b/docs/catalog/GAP_INVENTORY.md @@ -45,7 +45,7 @@ surfaces against the composition catalog schema | `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 | +| `/examples` | Recipe index + README snippets | P1–P2 quote `recipes/` fixtures; P3+ still pending | | `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 | @@ -78,15 +78,14 @@ These are Phase 0 recommendations so Phase 1 does not re-litigate shape: 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. +3. **Recipe layout:** backlog lives in `docs/catalog/` + `src/data/recipe-backlog.ts`; + fixtures live under `recipes/` in this repo (Phase 2). Catalog stores citations. 4. **`plan_composition` inputs:** structured `capabilityTags` + host constraints — not free-text LLM classification inside Pegma. -## What Phase 0 deliberately does not do +## What Phase 0 deliberately did not do -- Emit `catalog.json` or change the site build (Phase 1) -- Add recipe fixture code (Phase 2) +- Emit `catalog.json` or change the site build (done in Phase 1) +- Add recipe fixture code (done in Phase 2 for P1–P2 under `recipes/`) - 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 index c1f4398..081a0a2 100644 --- a/docs/catalog/RECIPE_BACKLOG.md +++ b/docs/catalog/RECIPE_BACKLOG.md @@ -25,7 +25,7 @@ deferred). | **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) | +| **Fixture** | green — [`recipes/cf-passkey-accounts/`](../../recipes/cf-passkey-accounts/) (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) @@ -39,7 +39,7 @@ deferred). | **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 | +| **Fixture** | green — [`recipes/storage-audit-mail-outbox/`](../../recipes/storage-audit-mail-outbox/) | | **Phase plan exit** | Second required Phase 2 recipe (“storage + audit/mail outbox pattern”) | ### P3 — `durable-auth-rate-limits` diff --git a/package-lock.json b/package-lock.json index bac9349..cf2f64f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "pegma.dev", "version": "0.1.0", "dependencies": { + "@pegma/audit": "0.1.0", "@pegma/authorization-identity": "0.1.2", "@pegma/health": "^0.1.1", "@pegma/identity": "0.1.0", @@ -2262,6 +2263,28 @@ "node": ">=20.0.0" } }, + "node_modules/@pegma/audit": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pegma/audit/-/audit-0.1.0.tgz", + "integrity": "sha512-L1VGdpZDUeJAKRNBALbaT9lt+tPEQdh7GqgMNo+9TKIU9tg0AFZDN1d0r8RDBHgmigwZaybX8BoK34SJBdsNlQ==", + "license": "MIT", + "dependencies": { + "@pegma/spine": "0.1.1", + "@pegma/storage-core": "0.3.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@pegma/audit/node_modules/@pegma/storage-core": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@pegma/storage-core/-/storage-core-0.3.0.tgz", + "integrity": "sha512-XcSIAxjC1JV+Pt3dpSrLZELSejckO/COWLZ03BfYQv0Hem4QL/7XCq5gb5dxEymKVufQuIqGtuDPZi2UPfqnuQ==", + "license": "MIT", + "engines": { + "node": ">=22" + } + }, "node_modules/@pegma/authorization-contracts": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/@pegma/authorization-contracts/-/authorization-contracts-0.1.2.tgz", diff --git a/package.json b/package.json index cca0f19..988fccc 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "astro dev", "build": "astro build", - "check": "astro check && tsc -p worker/tsconfig.json --noEmit", + "check": "astro check && tsc -p worker/tsconfig.json --noEmit && tsc -p recipes/tsconfig.json --noEmit", "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", @@ -17,6 +17,7 @@ "worker:types": "wrangler types worker/worker-configuration.d.ts -c worker/wrangler.jsonc" }, "dependencies": { + "@pegma/audit": "0.1.0", "@pegma/authorization-identity": "0.1.2", "@pegma/health": "^0.1.1", "@pegma/identity": "0.1.0", diff --git a/public/llms.txt b/public/llms.txt index 77169e5..43e3063 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -80,8 +80,9 @@ status, design decisions, and non-goals. status, links. - [Roadmap](https://pegma.dev/roadmap): the aggregate view; status compiled at build time from the repos' plans. -- [Examples](https://pegma.dev/examples): snippets lifted from real code - only, each citing its source. +- [Examples](https://pegma.dev/examples): composition recipes with CI-tested + fixtures under recipes/ (P1 accounts, P2 audit/mail outbox) plus snippets + lifted from package READMEs; each block cites its source. - [Account](https://pegma.dev/account): the static shell for pegma.dev's D1-backed first-party Identity reference consumer. The Worker pins the exact Identity, Authorization adapter, Sessions, Mail, rate-limit, and storage diff --git a/recipes/README.md b/recipes/README.md new file mode 100644 index 0000000..794de54 --- /dev/null +++ b/recipes/README.md @@ -0,0 +1,26 @@ +# Synthetic recipe fixtures + +CI-tested composition sketches for agents. Product names and domains are +**fictional on purpose** — they teach assembly, not commercial architecture. + +| Recipe id | Intent (short) | Path | +| --- | --- | --- | +| `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/) | + +## Rules + +1. **Synthetic only.** No routes, schemas, or ops topology from production hosts. +2. **Executed.** Every recipe has a `*.test.ts` included in `npm test`. +3. **Catalog citation.** `/catalog.json` and `/examples` may quote wiring only + from files under this tree (or from already-public package README/conformance + sources). `fixture.status` is `green` only when CI covers the fixture. +4. **Composition root is the map.** Fixtures wire packages explicitly; no + autodiscovery story. + +## Production vs test adapters + +Fixtures use `@pegma/storage-core` **memory** stores in tests so CI stays +fast and free of cloud credentials. Recipe metadata and comments name the +production adapter the host should choose (for example Cloudflare D1 for +`cf-passkey-accounts`). Memory is never a durability claim. diff --git a/recipes/cf-passkey-accounts/composition.test.ts b/recipes/cf-passkey-accounts/composition.test.ts new file mode 100644 index 0000000..9c8b33c --- /dev/null +++ b/recipes/cf-passkey-accounts/composition.test.ts @@ -0,0 +1,83 @@ +import type { PrincipalId } from '@pegma/spine'; +import { describe, expect, it } from 'vitest'; +import { + createNorthshelfComposition, + openNorthshelfSession, + NORTHSHELF_RP, +} from './composition'; + +/** Deterministic 32-byte secret, base64 — tests only. */ +const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); + +describe('cf-passkey-accounts (Northshelf Branch)', () => { + it('wires Identity, Sessions, durable rate limits, and claims projection', async () => { + const composition = createNorthshelfComposition({ + emailCodeSecretBase64: TEST_SECRET, + }); + + const user = await composition.identity.provisionVerifiedUser({ + principalId: 'prn_northshelf_patron' as PrincipalId, + email: 'patron@northshelf.example', + }); + + const claims = await composition.identity.claimsFor(user.principalId); + expect(claims).toMatchObject({ + issuer: NORTHSHELF_RP.issuer, + subject: user.principalId, + emailVerified: true, + }); + + const link = composition.identityLinkFromClaims(claims); + expect(link.issuer).toBe(NORTHSHELF_RP.issuer); + expect(link.subject).toBe(user.principalId); + + const sessionId = 'n'.repeat(43); + await openNorthshelfSession( + composition, + sessionId, + user.principalId, + claims, + ); + const session = await composition.sessions.get(sessionId); + expect(session?.principalId).toBe(user.principalId); + expect(session?.data).toContain('authorizationLink'); + }); + + it('starts passkey registration for an existing user (ceremony is host/browser)', async () => { + const composition = createNorthshelfComposition({ + emailCodeSecretBase64: TEST_SECRET, + }); + const user = await composition.identity.provisionVerifiedUser({ + principalId: 'prn_northshelf_staff' as PrincipalId, + email: 'staff@northshelf.example', + }); + + const start = await composition.identity.beginPasskeyRegistration( + user.principalId, + '203.0.113.10', + ); + expect(start.options.rp.id).toBe(NORTHSHELF_RP.rpID); + expect(start.options.rp.name).toBe(NORTHSHELF_RP.rpName); + expect(typeof start.challengeHandle).toBe('string'); + }); + + it('starts email-code account creation without passwords', async () => { + const composition = createNorthshelfComposition({ + emailCodeSecretBase64: TEST_SECRET, + }); + + const started = await composition.identity.beginAccountCreation( + 'new.patron@northshelf.example', + '203.0.113.20', + ); + expect(typeof started.codeHandle).toBe('string'); + expect(started.codeHandle.length).toBeGreaterThan(8); + expect(typeof started.expiresAt).toBe('string'); + }); + + it('refuses an unconfigured email-code secret', () => { + expect(() => + createNorthshelfComposition({ emailCodeSecretBase64: 'short' }), + ).toThrow(/email-code secret/); + }); +}); diff --git a/recipes/cf-passkey-accounts/composition.ts b/recipes/cf-passkey-accounts/composition.ts new file mode 100644 index 0000000..75b2c58 --- /dev/null +++ b/recipes/cf-passkey-accounts/composition.ts @@ -0,0 +1,194 @@ +/** + * Recipe: cf-passkey-accounts + * + * Synthetic host: Northshelf Branch — a fictional community library. + * Teaches first-party accounts on a Cloudflare-shaped Worker host: + * Identity (passkeys + email codes, no passwords), Sessions, durable + * rate limits, Authorization claims projection, and Storage Core. + * + * Tests use the memory store. Production Workers should inject + * `@pegma/storage-cloudflare-d1` with the same composition shape. + * + * This is not pegma.dev’s production account API. Do not copy commercial + * route maps or cookie names from any live product. + */ + +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { + createHmacEmailCodeProtector, + createIdentity, + type Identity, + type VerifiedIdentityClaims, +} from '@pegma/identity'; +import { + createDurableLimiter, + defineRateLimitPolicy, + type DurableRateLimiter, +} from '@pegma/rate-limit'; +import { createSessionStore, type SessionStore } from '@pegma/sessions'; +import { fixedClock, type Clock, type Logger, type PrincipalId } from '@pegma/spine'; +import { createMemoryStore, type Store } from '@pegma/storage-core'; + +/** Fictional relying-party surface for the Northshelf Branch library. */ +export const NORTHSHELF_RP = { + issuer: 'https://accounts.northshelf.example', + rpName: 'Northshelf Branch', + rpID: 'northshelf.example', + origins: ['https://northshelf.example'] as const, +} as const; + +export interface NorthshelfCompositionOptions { + /** Injected store. Production: D1 adapter. Tests: memory. */ + readonly store?: Store; + /** + * Base64-encoded email-code HMAC secret (≥32 raw bytes). + * Host-managed; never generated at process start in production. + */ + readonly emailCodeSecretBase64: string; + readonly clock?: Clock; + readonly logger?: Logger; +} + +export interface NorthshelfComposition { + readonly store: Store; + readonly identity: Identity; + readonly sessions: SessionStore; + readonly registrationLimiter: DurableRateLimiter; + readonly authenticationLimiter: DurableRateLimiter; + readonly emailCodeRequestLimiter: DurableRateLimiter; + readonly emailCodeVerificationLimiter: DurableRateLimiter; + readonly emailCodeProtector: ReturnType; + readonly clock: Clock; + /** Project already-verified Identity claims into Authorization Core link keys. */ + readonly identityLinkFromClaims: ( + claims: VerifiedIdentityClaims, + ) => ReturnType; +} + +function decodeEmailCodeSecret(value: string): Uint8Array { + if ( + value.length < 44 || + value.length > 172 || + !/^[A-Za-z0-9+/]+={0,2}$/u.test(value) + ) { + throw new Error('Northshelf email-code secret is not configured.'); + } + let binary: string; + try { + binary = atob(value); + } catch { + throw new Error('Northshelf email-code secret is invalid.'); + } + if (binary.length < 32 || binary.length > 128) { + throw new Error('Northshelf email-code secret is invalid.'); + } + return Uint8Array.from(binary, (c) => c.charCodeAt(0)); +} + +function durableLimiter( + store: Store, + name: string, + limit: number, + windowMs: number, +): DurableRateLimiter { + return createDurableLimiter( + defineRateLimitPolicy({ name, limit, windowMs }), + store, + ); +} + +/** + * Explicit composition root for the Northshelf Branch accounts recipe. + * + * Wire once. Hosts still own HTTP routes, cookies, WebAuthn ceremony + * completion in the browser, email provider/DNS, and any UI. + */ +export function createNorthshelfComposition( + options: NorthshelfCompositionOptions, +): NorthshelfComposition { + const store = options.store ?? createMemoryStore(); + const clock = options.clock ?? fixedClock('2026-07-29T12:00:00.000Z'); + const emailCodeProtector = createHmacEmailCodeProtector( + decodeEmailCodeSecret(options.emailCodeSecretBase64), + ); + + const registrationLimiter = durableLimiter( + store, + 'northshelf-passkey-registration', + 10, + 5 * 60_000, + ); + const authenticationLimiter = durableLimiter( + store, + 'northshelf-passkey-authentication', + 30, + 5 * 60_000, + ); + const emailCodeRequestLimiter = durableLimiter( + store, + 'northshelf-email-code-request', + 5, + 10 * 60_000, + ); + const emailCodeVerificationLimiter = durableLimiter( + store, + 'northshelf-email-code-verification', + 10, + 10 * 60_000, + ); + + const identity = createIdentity({ + store, + issuer: NORTHSHELF_RP.issuer, + rpName: NORTHSHELF_RP.rpName, + rpID: NORTHSHELF_RP.rpID, + origins: [...NORTHSHELF_RP.origins], + registrationLimiter, + authenticationLimiter, + emailCodeProtector, + emailCodeRequestLimiter, + emailCodeVerificationLimiter, + clock, + }); + + const sessions = createSessionStore(store, { + clock, + ...(options.logger === undefined ? {} : { logger: options.logger }), + }); + + return Object.freeze({ + store, + identity, + sessions, + registrationLimiter, + authenticationLimiter, + emailCodeRequestLimiter, + emailCodeVerificationLimiter, + emailCodeProtector, + clock, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); +} + +/** + * Host sketch: after Identity verifies a principal, open a server-side + * session. Session `data` is opaque to `@pegma/sessions` — never put IdP + * access tokens or other re-presentable credentials here. + */ +export async function openNorthshelfSession( + composition: NorthshelfComposition, + sessionId: string, + principalId: PrincipalId, + claims: VerifiedIdentityClaims, +): Promise { + const link = composition.identityLinkFromClaims(claims); + await composition.sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + issuer: claims.issuer, + subject: claims.subject, + authorizationLink: link, + }), + }); +} diff --git a/recipes/storage-audit-mail-outbox/composition.test.ts b/recipes/storage-audit-mail-outbox/composition.test.ts new file mode 100644 index 0000000..afe39f7 --- /dev/null +++ b/recipes/storage-audit-mail-outbox/composition.test.ts @@ -0,0 +1,92 @@ +import type { PrincipalId } from '@pegma/spine'; +import { describe, expect, it } from 'vitest'; +import { + checkoutEquipment, + createYardLoanComposition, + yardLoanPartition, +} from './composition'; + +const DESK = 'desk_main'; +const PARTITION = yardLoanPartition(DESK); +const WHEN = '2026-07-29T15:00:00.000Z'; + +describe('storage-audit-mail-outbox (Yard Loan)', () => { + it('commits loan, audit, and mail job in one single-partition transaction', async () => { + const composition = createYardLoanComposition(DESK); + + const result = await checkoutEquipment(composition, { + itemId: 'ladder-12ft', + borrowerPrincipalId: 'prn_borrower' as PrincipalId, + actorPrincipalId: 'prn_clerk' as PrincipalId, + auditEventId: 'evt_checkout_1', + mailJobId: 'mail_checkout_1', + occurredAt: WHEN, + }); + + expect(result.committed).toBe(true); + + const loan = await composition.records.get({ + partition: PARTITION, + id: 'loan|ladder-12ft', + }); + expect(loan).toMatchObject({ + kind: 'loan', + status: 'checked_out', + borrowerPrincipalId: 'prn_borrower', + }); + + const history = await composition.audit.history( + composition.records, + PARTITION, + { subject: 'ladder-12ft' }, + ); + expect(history).toHaveLength(1); + expect(history[0]?.action).toBe('yard_loan.item.checked_out'); + + const mailRow = await composition.records.get({ + partition: PARTITION, + id: 'mail|mail_checkout_1', + }); + expect(mailRow?.kind).toBe('mail'); + if (mailRow?.kind === 'mail') { + expect(mailRow.job.status).toBe('pending'); + expect(mailRow.job.recipientRef).toBe('prn_borrower'); + expect(mailRow.callerMetadata).toBe('yard-loan-checkout-notice'); + } + }); + + it('leaves no orphan audit or mail when the transaction rolls back', async () => { + const composition = createYardLoanComposition(DESK); + + // Seed an existing loan so a second insert of the same item is refused. + await composition.records.put({ + kind: 'loan', + deskId: DESK, + itemId: 'drill-set', + borrowerPrincipalId: 'prn_existing' as PrincipalId, + status: 'checked_out', + }); + + const result = await checkoutEquipment(composition, { + itemId: 'drill-set', + borrowerPrincipalId: 'prn_other' as PrincipalId, + actorPrincipalId: 'prn_clerk' as PrincipalId, + auditEventId: 'evt_orphan', + mailJobId: 'mail_orphan', + occurredAt: WHEN, + }); + + expect(result.committed).toBe(false); + expect(result.reason).toBe('exists'); + + expect( + await composition.audit.history(composition.records, PARTITION), + ).toEqual([]); + expect( + await composition.records.get({ + partition: PARTITION, + id: 'mail|mail_orphan', + }), + ).toBeNull(); + }); +}); diff --git a/recipes/storage-audit-mail-outbox/composition.ts b/recipes/storage-audit-mail-outbox/composition.ts new file mode 100644 index 0000000..4768190 --- /dev/null +++ b/recipes/storage-audit-mail-outbox/composition.ts @@ -0,0 +1,244 @@ +/** + * Recipe: storage-audit-mail-outbox + * + * Synthetic host: Yard Loan — a fictional equipment checkout desk. + * Teaches the pattern every durable notification and audit trail needs: + * + * state change + audit row + mail outbox job + * commit together in one storage-core single-partition `transact` + * + * Audit and Mail own no store. The host collection holds inventory rows, + * audit events, and mail jobs in one partition so atomicity is real. + * + * Tests use the memory store. Production hosts pick a durable adapter + * (Cloudflare D1 or Azure Tables) for the same collection shape. + */ + +import { + auditRecordId, + decodeAuditEvent, + defineAudit, + encodeAuditEvent, + type AuditEvent, + type AuditLog, +} from '@pegma/audit'; +import { + defineMail, + type Mail, + type MailJob, +} from '@pegma/mail'; +import type { IsoTimestamp, PrincipalId } from '@pegma/spine'; +import { + createMemoryStore, + defineCollection, + type CollectionStore, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; + +/** One collection, one partition per loan — the only atomic scope. */ +export type YardLoanRecord = + | { + readonly kind: 'loan'; + readonly deskId: string; + readonly itemId: string; + readonly borrowerPrincipalId: PrincipalId; + readonly status: 'checked_out' | 'returned'; + } + | { + readonly kind: 'audit'; + readonly deskId: string; + readonly event: AuditEvent; + } + | { + readonly kind: 'mail'; + readonly deskId: string; + readonly job: MailJob; + /** Host-owned metadata preserved across mail worker transitions. */ + readonly callerMetadata: string; + }; + +export const yardLoanPartition = (deskId: string): string => `desk|${deskId}`; + +export const yardLoanRecords = defineCollection({ + name: 'yard_loan_records', + key: (record) => ({ + partition: yardLoanPartition(record.deskId), + id: + record.kind === 'loan' + ? `loan|${record.itemId}` + : record.kind === 'audit' + ? auditRecordId(record.event.id) + : `mail|${record.job.id}`, + }), + codec: { + encode: (record): StoredRecord => { + if (record.kind === 'loan') { + return { + kind: 'loan', + deskId: record.deskId, + itemId: record.itemId, + borrowerPrincipalId: record.borrowerPrincipalId, + status: record.status, + }; + } + if (record.kind === 'audit') { + return { + kind: 'audit', + deskId: record.deskId, + ...encodeAuditEvent(record.event), + }; + } + return { + kind: 'mail', + deskId: record.deskId, + jobId: record.job.id, + callerMetadata: record.callerMetadata, + job: JSON.stringify(record.job), + }; + }, + decode: (raw): YardLoanRecord => { + const kind = String(raw['kind'] ?? ''); + if (kind === 'loan') { + return { + kind: 'loan', + deskId: String(raw['deskId']), + itemId: String(raw['itemId']), + borrowerPrincipalId: String(raw['borrowerPrincipalId']) as PrincipalId, + status: String(raw['status']) as 'checked_out' | 'returned', + }; + } + if (kind === 'audit') { + return { + kind: 'audit', + deskId: String(raw['deskId']), + event: decodeAuditEvent(raw), + }; + } + if (kind === 'mail') { + const jobJson = raw['job']; + if (typeof jobJson !== 'string') { + throw new TypeError('yard loan mail row missing job payload'); + } + return { + kind: 'mail', + deskId: String(raw['deskId']), + job: JSON.parse(jobJson) as MailJob, + callerMetadata: String(raw['callerMetadata'] ?? ''), + }; + } + throw new TypeError(`unknown yard loan record kind: ${kind}`); + }, + }, +}); + +export interface YardLoanComposition { + readonly store: Store; + readonly records: CollectionStore; + readonly audit: AuditLog; + readonly mail: Mail; + readonly deskId: string; + readonly partition: string; +} + +export interface CheckoutInput { + readonly itemId: string; + readonly borrowerPrincipalId: PrincipalId; + readonly actorPrincipalId: PrincipalId; + readonly auditEventId: string; + readonly mailJobId: string; + readonly occurredAt: IsoTimestamp; +} + +/** + * Explicit composition root for one Yard Loan desk partition. + */ +export function createYardLoanComposition( + deskId: string, + store: Store = createMemoryStore(), +): YardLoanComposition { + const partition = yardLoanPartition(deskId); + const records = store.collection(yardLoanRecords); + + const audit = defineAudit({ + collection: yardLoanRecords, + toRecord: (event) => ({ kind: 'audit', deskId, event }), + toEvent: (record) => (record.kind === 'audit' ? record.event : null), + }); + + const mail = defineMail({ + collection: yardLoanRecords, + key: ({ partition: p, jobId }) => ({ + partition: p, + id: `mail|${jobId}`, + }), + toRecord: (job, previous) => + previous?.kind === 'mail' + ? { ...previous, job } + : { + kind: 'mail', + deskId, + job, + callerMetadata: 'yard-loan-checkout-notice', + }, + toJob: (record) => (record.kind === 'mail' ? record.job : null), + }); + + return Object.freeze({ + store, + records, + audit, + mail, + deskId, + partition, + }); +} + +/** + * Checkout: inventory row + audit event + mail outbox job in one transact. + * If the transaction refuses, there is no orphan audit or pending mail. + */ +export async function checkoutEquipment( + composition: YardLoanComposition, + input: CheckoutInput, +): Promise<{ readonly committed: boolean; readonly reason?: string }> { + const { deskId, partition, records, audit, mail } = composition; + + const outcome = await records.transact(partition, [ + { + action: 'insert', + value: { + kind: 'loan', + deskId, + itemId: input.itemId, + borrowerPrincipalId: input.borrowerPrincipalId, + status: 'checked_out', + }, + }, + audit.action({ + id: input.auditEventId, + occurredAt: input.occurredAt, + actor: { + kind: 'principal', + principalId: input.actorPrincipalId, + }, + action: 'yard_loan.item.checked_out', + subject: input.itemId, + details: { + borrower: input.borrowerPrincipalId, + }, + }), + mail.action({ + partition, + id: input.mailJobId, + recipientRef: input.borrowerPrincipalId, + contentRef: `yard_loan.checkout:${input.itemId}`, + createdAt: input.occurredAt, + }), + ]); + + if (!outcome.committed) { + return { committed: false, reason: outcome.reason }; + } + return { committed: true }; +} diff --git a/recipes/tsconfig.json b/recipes/tsconfig.json new file mode 100644 index 0000000..d7c2677 --- /dev/null +++ b/recipes/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022"], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "types": ["node"] + }, + "include": ["./**/*.ts"] +} diff --git a/src/data/compile-catalog.test.ts b/src/data/compile-catalog.test.ts index 3b3adf2..1f1103b 100644 --- a/src/data/compile-catalog.test.ts +++ b/src/data/compile-catalog.test.ts @@ -79,12 +79,16 @@ describe('compileCompositionCatalog', () => { expect(storage.packages.filter((p) => p.published)).toHaveLength(1); }); - it('includes recipe intents without inventing green fixtures', async () => { + it('includes recipe intents with green fixtures only for CI-tested recipes', async () => { clearNpmVersionCache(); const catalog = await compile({}); const accounts = catalog.recipes.find((r) => r.id === 'cf-passkey-accounts')!; expect(accounts.backlogPriority).toBe(1); - expect(accounts.fixture.status).toBe('pending'); + expect(accounts.fixture).toMatchObject({ + kind: 'recipe_package', + status: 'green', + }); + expect(accounts.fixture.citation).toContain('recipes/cf-passkey-accounts'); expect(accounts.adapters[0]).toEqual({ componentId: 'storage-core', adapterId: 'cloudflare-d1', @@ -92,8 +96,23 @@ describe('compileCompositionCatalog', () => { const outbox = catalog.recipes.find((r) => r.id === 'storage-audit-mail-outbox')!; // Durable pattern: host picks adapter; memory must not be the recipe default. expect(outbox.adapters).toEqual([]); + expect(outbox.fixture).toMatchObject({ + kind: 'recipe_package', + status: 'green', + }); + expect(outbox.fixture.citation).toContain( + 'recipes/storage-audit-mail-outbox', + ); for (const recipe of catalog.recipes) { expect(recipe.intent).not.toMatch(/retiregolden/i); + } + // 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', + ); + for (const recipe of pendingOrNone) { expect(recipe.fixture.status).not.toBe('green'); } }); diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index ca39e29..da82d0c 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -2,12 +2,13 @@ * Prioritized synthetic recipe intents for the compiled catalog. * Source narrative: docs/catalog/RECIPE_BACKLOG.md * - * Fixtures are pending until Phase 2; wiring code must not be invented here. + * Wiring code may only be quoted when fixture.status is `green` and the + * citation points at a CI-tested path under recipes/. */ import type { CatalogRecipe } from './catalog-schema'; -/** Recipes included in catalog.json (intent metadata; fixtures still pending). */ +/** Recipes included in catalog.json. */ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ { id: 'cf-passkey-accounts', @@ -42,10 +43,10 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 'Mail package owning its own outbox store', ], fixture: { - kind: 'pending', + kind: 'recipe_package', citation: - 'docs/catalog/RECIPE_BACKLOG.md#p1--cf-passkey-accounts-first-end-to-end-accounts-recipe', - status: 'pending', + 'https://github.com/pegma-dev/pegma.dev/tree/main/recipes/cf-passkey-accounts', + status: 'green', }, capabilityTags: [ 'accounts', @@ -94,10 +95,10 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 'Audit write outside the caller transact', ], fixture: { - kind: 'pending', + kind: 'recipe_package', citation: - 'docs/catalog/RECIPE_BACKLOG.md#p2--storage-audit-mail-outbox-storage--auditmail-pattern', - status: 'pending', + 'https://github.com/pegma-dev/pegma.dev/tree/main/recipes/storage-audit-mail-outbox', + status: 'green', }, capabilityTags: ['storage', 'audit', 'mail_transactional'], requiresPublished: ['storage-core', 'audit', 'mail', 'spine'], diff --git a/src/pages/examples.astro b/src/pages/examples.astro index 4fed87c..216c425 100644 --- a/src/pages/examples.astro +++ b/src/pages/examples.astro @@ -1,5 +1,8 @@ --- import Base from '../layouts/Base.astro'; +import { RECIPE_BACKLOG } from '../data/recipe-backlog'; +import northshelfComposition from '../../recipes/cf-passkey-accounts/composition.ts?raw'; +import yardLoanComposition from '../../recipes/storage-audit-mail-outbox/composition.ts?raw'; /* Examples are LIFTED FROM REAL CODE, per the site's hard rule — each block cites its source. Do not invent example code for this page. */ @@ -51,23 +54,125 @@ const bus = createEventBus(); bus.subscribe(AccountCreated, (envelope) => { welcomeCache.invalidate(envelope.payload.principalId); });`; + +/** Excerpt the createNorthshelfComposition function for the page (full file is long). */ +function excerptFunction(source: string, name: string, maxLines = 55): string { + const lines = source.replace(/\r\n/g, '\n').split('\n'); + const start = lines.findIndex((l) => l.includes(`function ${name}`)); + if (start < 0) return source.slice(0, 1200); + const slice = lines.slice(start, start + maxLines); + // Trim trailing incomplete block noise if we hit the cap mid-function. + return slice.join('\n').trimEnd() + (slice.length >= maxLines ? '\n // …' : ''); +} + +const northshelfExcerpt = excerptFunction( + northshelfComposition, + 'createNorthshelfComposition', + 60, +); +const yardLoanExcerpt = excerptFunction( + yardLoanComposition, + 'checkoutEquipment', + 45, +); + +const greenRecipes = RECIPE_BACKLOG.filter((r) => r.fixture.status === 'green'); +const pendingRecipes = RECIPE_BACKLOG.filter( + (r) => r.fixture.status === 'pending' || r.fixture.status === 'none', +); ---

Examples

- Every snippet here is lifted from real, maintained sources — component READMEs, conformance - tests, or production consumers — and cites where it lives. An example that was never executed - is documentation that lies. + Every snippet here is lifted from real, maintained sources — synthetic recipe + fixtures under recipes/, component READMEs, or conformance tests — + and cites where it lives. An example that was never executed is documentation + that lies.

- This page is a skeleton on purpose: it grows as components publish, and full composition - recipes ("a site with accounts", "a support queue") arrive with the consumers they are lifted - from. + Full composition recipes are synthetic on purpose (fictional product shapes). + Machine-readable metadata lives in + catalog.json. Agents should fetch the + catalog rather than inventing package sets. +

+
+ +
+

Recipe index

+

+ Recipes with green fixtures are CI-tested and safe to quote. + Pending intents stay metadata-only until a fixture lands. +

+
    + { + greenRecipes.map((recipe) => ( +
  • + + {recipe.id} + + — green fixture + source +

    {recipe.intent}

    +
  • + )) + } +
+ { + pendingRecipes.length > 0 && ( +
+ Pending / deferred recipe intents +
    + {pendingRecipes.map((recipe) => ( +
  • + {recipe.id} — {recipe.fixture.status} + {recipe.backlogPriority !== undefined && + recipe.backlogPriority >= 90 + ? ' (awaits package publication)' + : ''} +
  • + ))} +
+
+ ) + } +
+ +
+

Accounts on a Cloudflare-shaped host

+

+ Northshelf Branch (synthetic): first-party Identity with + passkeys and email codes, Sessions, durable rate limits, and Authorization + claims projection. Production hosts inject + @pegma/storage-cloudflare-d1; the fixture tests with memory. +

+
{northshelfExcerpt}
+

+ Source:{' '} + recipes/cf-passkey-accounts/composition.ts +

+
+ +
+

Storage + audit + mail outbox in one transaction

+

+ Yard Loan (synthetic): inventory mutation, audit row, and + mail job commit together in a single-partition transact. Audit + and Mail own no store — the host collection is the atomic boundary. +

+
{yardLoanExcerpt}
+

+ Source:{' '} + recipes/storage-audit-mail-outbox/composition.ts

@@ -112,3 +217,21 @@ bus.subscribe(AccountCreated, (envelope) => {

+ + diff --git a/vitest.config.ts b/vitest.config.ts index 4c058b7..25705b2 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,7 +2,11 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { - include: ['worker/src/**/*.test.ts', 'src/**/*.test.ts'], + include: [ + 'worker/src/**/*.test.ts', + 'src/**/*.test.ts', + 'recipes/**/*.test.ts', + ], exclude: ['**/node_modules/**', '**/*.d1.test.ts'], testTimeout: 30_000, }, From 4f0e396cf03038e27208308d6477a6784239661f Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 09:19:54 -0400 Subject: [PATCH 2/7] [2] Address review: live clock default and complete examples excerpts. Use systemClock by default in the Northshelf composition (tests inject fixedClock), clarify secret validation errors, and excerpt whole fixture functions on /examples. --- .../cf-passkey-accounts/composition.test.ts | 26 +++++----- recipes/cf-passkey-accounts/composition.ts | 18 +++++-- src/pages/examples.astro | 48 +++++++++++++++---- 3 files changed, 65 insertions(+), 27 deletions(-) diff --git a/recipes/cf-passkey-accounts/composition.test.ts b/recipes/cf-passkey-accounts/composition.test.ts index 9c8b33c..47ad43a 100644 --- a/recipes/cf-passkey-accounts/composition.test.ts +++ b/recipes/cf-passkey-accounts/composition.test.ts @@ -1,4 +1,4 @@ -import type { PrincipalId } from '@pegma/spine'; +import { fixedClock, type PrincipalId } from '@pegma/spine'; import { describe, expect, it } from 'vitest'; import { createNorthshelfComposition, @@ -9,11 +9,17 @@ import { /** Deterministic 32-byte secret, base64 — tests only. */ const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); +/** Inject a fixed clock so expiry math stays deterministic in tests. */ +function makeComposition() { + return createNorthshelfComposition({ + emailCodeSecretBase64: TEST_SECRET, + clock: fixedClock('2026-07-29T12:00:00.000Z'), + }); +} + describe('cf-passkey-accounts (Northshelf Branch)', () => { it('wires Identity, Sessions, durable rate limits, and claims projection', async () => { - const composition = createNorthshelfComposition({ - emailCodeSecretBase64: TEST_SECRET, - }); + const composition = makeComposition(); const user = await composition.identity.provisionVerifiedUser({ principalId: 'prn_northshelf_patron' as PrincipalId, @@ -44,9 +50,7 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { }); it('starts passkey registration for an existing user (ceremony is host/browser)', async () => { - const composition = createNorthshelfComposition({ - emailCodeSecretBase64: TEST_SECRET, - }); + const composition = makeComposition(); const user = await composition.identity.provisionVerifiedUser({ principalId: 'prn_northshelf_staff' as PrincipalId, email: 'staff@northshelf.example', @@ -62,9 +66,7 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { }); it('starts email-code account creation without passwords', async () => { - const composition = createNorthshelfComposition({ - emailCodeSecretBase64: TEST_SECRET, - }); + const composition = makeComposition(); const started = await composition.identity.beginAccountCreation( 'new.patron@northshelf.example', @@ -75,9 +77,9 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { expect(typeof started.expiresAt).toBe('string'); }); - it('refuses an unconfigured email-code secret', () => { + it('refuses a missing or invalid email-code secret', () => { expect(() => createNorthshelfComposition({ emailCodeSecretBase64: 'short' }), - ).toThrow(/email-code secret/); + ).toThrow(/missing or invalid/); }); }); diff --git a/recipes/cf-passkey-accounts/composition.ts b/recipes/cf-passkey-accounts/composition.ts index 75b2c58..b48b823 100644 --- a/recipes/cf-passkey-accounts/composition.ts +++ b/recipes/cf-passkey-accounts/composition.ts @@ -26,7 +26,7 @@ import { type DurableRateLimiter, } from '@pegma/rate-limit'; import { createSessionStore, type SessionStore } from '@pegma/sessions'; -import { fixedClock, type Clock, type Logger, type PrincipalId } from '@pegma/spine'; +import { systemClock, type Clock, type Logger, type PrincipalId } from '@pegma/spine'; import { createMemoryStore, type Store } from '@pegma/storage-core'; /** Fictional relying-party surface for the Northshelf Branch library. */ @@ -71,16 +71,22 @@ function decodeEmailCodeSecret(value: string): Uint8Array { value.length > 172 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(value) ) { - throw new Error('Northshelf email-code secret is not configured.'); + throw new Error( + 'Northshelf email-code secret is missing or invalid (expected base64 of 32–128 raw bytes).', + ); } let binary: string; try { binary = atob(value); } catch { - throw new Error('Northshelf email-code secret is invalid.'); + throw new Error( + 'Northshelf email-code secret is missing or invalid (expected base64 of 32–128 raw bytes).', + ); } if (binary.length < 32 || binary.length > 128) { - throw new Error('Northshelf email-code secret is invalid.'); + throw new Error( + 'Northshelf email-code secret is missing or invalid (expected base64 of 32–128 raw bytes).', + ); } return Uint8Array.from(binary, (c) => c.charCodeAt(0)); } @@ -107,7 +113,9 @@ export function createNorthshelfComposition( options: NorthshelfCompositionOptions, ): NorthshelfComposition { const store = options.store ?? createMemoryStore(); - const clock = options.clock ?? fixedClock('2026-07-29T12:00:00.000Z'); + // Live clock by default so production-shaped hosts expire challenges/sessions. + // Tests inject fixedClock when they need deterministic timestamps. + const clock = options.clock ?? systemClock; const emailCodeProtector = createHmacEmailCodeProtector( decodeEmailCodeSecret(options.emailCodeSecretBase64), ); diff --git a/src/pages/examples.astro b/src/pages/examples.astro index 216c425..d1eb6fc 100644 --- a/src/pages/examples.astro +++ b/src/pages/examples.astro @@ -55,25 +55,53 @@ bus.subscribe(AccountCreated, (envelope) => { welcomeCache.invalidate(envelope.payload.principalId); });`; -/** Excerpt the createNorthshelfComposition function for the page (full file is long). */ -function excerptFunction(source: string, name: string, maxLines = 55): string { - const lines = source.replace(/\r\n/g, '\n').split('\n'); - const start = lines.findIndex((l) => l.includes(`function ${name}`)); - if (start < 0) return source.slice(0, 1200); - const slice = lines.slice(start, start + maxLines); - // Trim trailing incomplete block noise if we hit the cap mid-function. - return slice.join('\n').trimEnd() + (slice.length >= maxLines ? '\n // …' : ''); +/** + * Extract a complete top-level function by brace matching so the page never + * quotes truncated, non-compiling TypeScript (AGENTS.md examples rule). + */ +function excerptFunction(source: string, name: string): string { + const text = source.replace(/\r\n/g, '\n'); + const marker = `function ${name}`; + const start = text.indexOf(marker); + if (start < 0) { + throw new Error(`examples.astro: function ${name} not found in fixture`); + } + // Walk back to include a leading doc comment if present. + let from = start; + const before = text.slice(0, start); + const doc = before.lastIndexOf('\n/**'); + if (doc >= 0 && !before.slice(doc).includes('\nexport ') && !before.slice(doc).includes('\nfunction ')) { + from = doc + 1; + } else { + const lineStart = before.lastIndexOf('\n'); + from = lineStart < 0 ? 0 : lineStart + 1; + } + + let i = text.indexOf('{', start); + if (i < 0) { + throw new Error(`examples.astro: no body for function ${name}`); + } + let depth = 0; + for (; i < text.length; i++) { + const ch = text[i]; + if (ch === '{') depth++; + else if (ch === '}') { + depth--; + if (depth === 0) { + return text.slice(from, i + 1).trimEnd(); + } + } + } + throw new Error(`examples.astro: unclosed function ${name}`); } const northshelfExcerpt = excerptFunction( northshelfComposition, 'createNorthshelfComposition', - 60, ); const yardLoanExcerpt = excerptFunction( yardLoanComposition, 'checkoutEquipment', - 45, ); const greenRecipes = RECIPE_BACKLOG.filter((r) => r.fixture.status === 'green'); From 9df6a11f0086f3506ed891ce71161866d19c817a Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 09:31:15 -0400 Subject: [PATCH 3/7] [2] Derive Northshelf session principal from verified claims. openNorthshelfSession no longer accepts a separate principalId argument that could disagree with claims.subject and create a cross-account session. --- recipes/cf-passkey-accounts/composition.test.ts | 7 +------ recipes/cf-passkey-accounts/composition.ts | 5 ++++- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/recipes/cf-passkey-accounts/composition.test.ts b/recipes/cf-passkey-accounts/composition.test.ts index 47ad43a..e998edf 100644 --- a/recipes/cf-passkey-accounts/composition.test.ts +++ b/recipes/cf-passkey-accounts/composition.test.ts @@ -38,12 +38,7 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { expect(link.subject).toBe(user.principalId); const sessionId = 'n'.repeat(43); - await openNorthshelfSession( - composition, - sessionId, - user.principalId, - claims, - ); + await openNorthshelfSession(composition, sessionId, claims); const session = await composition.sessions.get(sessionId); expect(session?.principalId).toBe(user.principalId); expect(session?.data).toContain('authorizationLink'); diff --git a/recipes/cf-passkey-accounts/composition.ts b/recipes/cf-passkey-accounts/composition.ts index b48b823..d1086e0 100644 --- a/recipes/cf-passkey-accounts/composition.ts +++ b/recipes/cf-passkey-accounts/composition.ts @@ -182,13 +182,16 @@ export function createNorthshelfComposition( * Host sketch: after Identity verifies a principal, open a server-side * session. Session `data` is opaque to `@pegma/sessions` — never put IdP * access tokens or other re-presentable credentials here. + * + * The session principal is always `claims.subject` so a mismatched caller + * argument cannot create a cross-account session. */ export async function openNorthshelfSession( composition: NorthshelfComposition, sessionId: string, - principalId: PrincipalId, claims: VerifiedIdentityClaims, ): Promise { + const principalId = claims.subject as PrincipalId; const link = composition.identityLinkFromClaims(claims); await composition.sessions.create(sessionId, { principalId, From 304ecce610d86f412458677f150ec48972e089b0 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 09:44:16 -0400 Subject: [PATCH 4/7] [2] Fix Yard Loan excerpt: named CheckoutResult and clean body extract. Return object-literal types broke brace matching on /examples; use CheckoutResult and skip the parameter list before locating the function body brace. --- .../storage-audit-mail-outbox/composition.ts | 7 +++- src/pages/examples.astro | 36 ++++++++++++++++--- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/recipes/storage-audit-mail-outbox/composition.ts b/recipes/storage-audit-mail-outbox/composition.ts index 4768190..97e4e12 100644 --- a/recipes/storage-audit-mail-outbox/composition.ts +++ b/recipes/storage-audit-mail-outbox/composition.ts @@ -194,6 +194,11 @@ export function createYardLoanComposition( }); } +export interface CheckoutResult { + readonly committed: boolean; + readonly reason?: string; +} + /** * Checkout: inventory row + audit event + mail outbox job in one transact. * If the transaction refuses, there is no orphan audit or pending mail. @@ -201,7 +206,7 @@ export function createYardLoanComposition( export async function checkoutEquipment( composition: YardLoanComposition, input: CheckoutInput, -): Promise<{ readonly committed: boolean; readonly reason?: string }> { +): Promise { const { deskId, partition, records, audit, mail } = composition; const outcome = await records.transact(partition, [ diff --git a/src/pages/examples.astro b/src/pages/examples.astro index d1eb6fc..a4989d3 100644 --- a/src/pages/examples.astro +++ b/src/pages/examples.astro @@ -56,8 +56,12 @@ bus.subscribe(AccountCreated, (envelope) => { });`; /** - * Extract a complete top-level function by brace matching so the page never - * quotes truncated, non-compiling TypeScript (AGENTS.md examples rule). + * Extract a complete top-level function so the page never quotes truncated, + * non-compiling TypeScript (AGENTS.md examples rule). + * + * Skips the parameter list first, then takes the next `{` as the body. + * Fixture return types must not embed object-literal braces in the signature + * (use a named interface such as CheckoutResult) so the body brace is unambiguous. */ function excerptFunction(source: string, name: string): string { const text = source.replace(/\r\n/g, '\n'); @@ -66,21 +70,43 @@ function excerptFunction(source: string, name: string): string { if (start < 0) { throw new Error(`examples.astro: function ${name} not found in fixture`); } - // Walk back to include a leading doc comment if present. + let from = start; const before = text.slice(0, start); const doc = before.lastIndexOf('\n/**'); - if (doc >= 0 && !before.slice(doc).includes('\nexport ') && !before.slice(doc).includes('\nfunction ')) { + if ( + doc >= 0 && + !before.slice(doc).includes('\nexport ') && + !before.slice(doc).includes('\nfunction ') + ) { from = doc + 1; } else { const lineStart = before.lastIndexOf('\n'); from = lineStart < 0 ? 0 : lineStart + 1; } - let i = text.indexOf('{', start); + const nameEnd = start + marker.length; + let i = text.indexOf('(', nameEnd); if (i < 0) { + throw new Error(`examples.astro: no parameter list for function ${name}`); + } + let paren = 0; + for (; i < text.length; i++) { + if (text[i] === '(') paren++; + else if (text[i] === ')') { + paren--; + if (paren === 0) { + i++; + break; + } + } + } + + while (i < text.length && text[i] !== '{') i++; + if (text[i] !== '{') { throw new Error(`examples.astro: no body for function ${name}`); } + let depth = 0; for (; i < text.length; i++) { const ch = text[i]; From 706c38959ae77b992aac688a392f3f677c38bb37 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 09:55:16 -0400 Subject: [PATCH 5/7] [2] Require explicit Store injection in recipe composition roots. Memory is no longer a silent default for Northshelf or Yard Loan; tests pass createMemoryStore() and production hosts must inject a durable adapter. --- recipes/README.md | 9 +++++---- recipes/cf-passkey-accounts/composition.test.ts | 9 +++++++-- recipes/cf-passkey-accounts/composition.ts | 12 ++++++++---- .../storage-audit-mail-outbox/composition.test.ts | 10 ++++++++-- recipes/storage-audit-mail-outbox/composition.ts | 6 ++++-- 5 files changed, 32 insertions(+), 14 deletions(-) diff --git a/recipes/README.md b/recipes/README.md index 794de54..926ef9e 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -20,7 +20,8 @@ CI-tested composition sketches for agents. Product names and domains are ## Production vs test adapters -Fixtures use `@pegma/storage-core` **memory** stores in tests so CI stays -fast and free of cloud credentials. Recipe metadata and comments name the -production adapter the host should choose (for example Cloudflare D1 for -`cf-passkey-accounts`). Memory is never a durability claim. +Composition roots **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. diff --git a/recipes/cf-passkey-accounts/composition.test.ts b/recipes/cf-passkey-accounts/composition.test.ts index e998edf..a706031 100644 --- a/recipes/cf-passkey-accounts/composition.test.ts +++ b/recipes/cf-passkey-accounts/composition.test.ts @@ -1,4 +1,5 @@ import { fixedClock, type PrincipalId } from '@pegma/spine'; +import { createMemoryStore } from '@pegma/storage-core'; import { describe, expect, it } from 'vitest'; import { createNorthshelfComposition, @@ -9,9 +10,10 @@ import { /** Deterministic 32-byte secret, base64 — tests only. */ const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); -/** Inject a fixed clock so expiry math stays deterministic in tests. */ +/** Explicit memory store + fixed clock — never a silent production default. */ function makeComposition() { return createNorthshelfComposition({ + store: createMemoryStore(), emailCodeSecretBase64: TEST_SECRET, clock: fixedClock('2026-07-29T12:00:00.000Z'), }); @@ -74,7 +76,10 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { it('refuses a missing or invalid email-code secret', () => { expect(() => - createNorthshelfComposition({ emailCodeSecretBase64: 'short' }), + createNorthshelfComposition({ + store: createMemoryStore(), + emailCodeSecretBase64: 'short', + }), ).toThrow(/missing or invalid/); }); }); diff --git a/recipes/cf-passkey-accounts/composition.ts b/recipes/cf-passkey-accounts/composition.ts index d1086e0..8891453 100644 --- a/recipes/cf-passkey-accounts/composition.ts +++ b/recipes/cf-passkey-accounts/composition.ts @@ -27,7 +27,7 @@ import { } from '@pegma/rate-limit'; import { createSessionStore, type SessionStore } from '@pegma/sessions'; import { systemClock, type Clock, type Logger, type PrincipalId } from '@pegma/spine'; -import { createMemoryStore, type Store } from '@pegma/storage-core'; +import type { Store } from '@pegma/storage-core'; /** Fictional relying-party surface for the Northshelf Branch library. */ export const NORTHSHELF_RP = { @@ -38,8 +38,12 @@ export const NORTHSHELF_RP = { } as const; export interface NorthshelfCompositionOptions { - /** Injected store. Production: D1 adapter. Tests: memory. */ - readonly store?: Store; + /** + * Required injected store. Production hosts pass a durable adapter + * (e.g. Cloudflare D1). Tests pass `createMemoryStore()` explicitly — + * memory is never the silent default. + */ + readonly store: Store; /** * Base64-encoded email-code HMAC secret (≥32 raw bytes). * Host-managed; never generated at process start in production. @@ -112,7 +116,7 @@ function durableLimiter( export function createNorthshelfComposition( options: NorthshelfCompositionOptions, ): NorthshelfComposition { - const store = options.store ?? createMemoryStore(); + const store = options.store; // Live clock by default so production-shaped hosts expire challenges/sessions. // Tests inject fixedClock when they need deterministic timestamps. const clock = options.clock ?? systemClock; diff --git a/recipes/storage-audit-mail-outbox/composition.test.ts b/recipes/storage-audit-mail-outbox/composition.test.ts index afe39f7..b62de62 100644 --- a/recipes/storage-audit-mail-outbox/composition.test.ts +++ b/recipes/storage-audit-mail-outbox/composition.test.ts @@ -1,4 +1,5 @@ import type { PrincipalId } from '@pegma/spine'; +import { createMemoryStore } from '@pegma/storage-core'; import { describe, expect, it } from 'vitest'; import { checkoutEquipment, @@ -10,9 +11,14 @@ const DESK = 'desk_main'; const PARTITION = yardLoanPartition(DESK); const WHEN = '2026-07-29T15:00:00.000Z'; +/** Explicit memory store for tests — production injects a durable adapter. */ +function makeComposition() { + return createYardLoanComposition(DESK, createMemoryStore()); +} + describe('storage-audit-mail-outbox (Yard Loan)', () => { it('commits loan, audit, and mail job in one single-partition transaction', async () => { - const composition = createYardLoanComposition(DESK); + const composition = makeComposition(); const result = await checkoutEquipment(composition, { itemId: 'ladder-12ft', @@ -56,7 +62,7 @@ describe('storage-audit-mail-outbox (Yard Loan)', () => { }); it('leaves no orphan audit or mail when the transaction rolls back', async () => { - const composition = createYardLoanComposition(DESK); + const composition = makeComposition(); // Seed an existing loan so a second insert of the same item is refused. await composition.records.put({ diff --git a/recipes/storage-audit-mail-outbox/composition.ts b/recipes/storage-audit-mail-outbox/composition.ts index 97e4e12..78538dd 100644 --- a/recipes/storage-audit-mail-outbox/composition.ts +++ b/recipes/storage-audit-mail-outbox/composition.ts @@ -29,7 +29,6 @@ import { } from '@pegma/mail'; import type { IsoTimestamp, PrincipalId } from '@pegma/spine'; import { - createMemoryStore, defineCollection, type CollectionStore, type Store, @@ -152,10 +151,13 @@ export interface CheckoutInput { /** * Explicit composition root for one Yard Loan desk partition. + * + * `store` is required. Production hosts inject a durable adapter; tests pass + * `createMemoryStore()` explicitly so memory is never a silent default. */ export function createYardLoanComposition( deskId: string, - store: Store = createMemoryStore(), + store: Store, ): YardLoanComposition { const partition = yardLoanPartition(deskId); const records = store.collection(yardLoanRecords); From 26145bfd6b00428d55f48bf14ad97e5edb949993 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 10:07:13 -0400 Subject: [PATCH 6/7] [2] Wire Identity mail worker and pin green recipe package versions. Northshelf composition requires host mail ports and exposes createMailWorker; tests drain a recording provider. Catalog green recipes publish name@version pins matching the fixture lockfile. --- .../cf-passkey-accounts/composition.test.ts | 77 ++++++++++++++++--- recipes/cf-passkey-accounts/composition.ts | 29 +++++++ src/data/recipe-backlog.ts | 23 +++--- 3 files changed, 108 insertions(+), 21 deletions(-) diff --git a/recipes/cf-passkey-accounts/composition.test.ts b/recipes/cf-passkey-accounts/composition.test.ts index a706031..aa4df8c 100644 --- a/recipes/cf-passkey-accounts/composition.test.ts +++ b/recipes/cf-passkey-accounts/composition.test.ts @@ -5,23 +5,68 @@ import { createNorthshelfComposition, openNorthshelfSession, NORTHSHELF_RP, + type NorthshelfMailDelivery, } from './composition'; /** Deterministic 32-byte secret, base64 — tests only. */ const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); -/** Explicit memory store + fixed clock — never a silent production default. */ -function makeComposition() { - return createNorthshelfComposition({ - store: createMemoryStore(), - emailCodeSecretBase64: TEST_SECRET, - clock: fixedClock('2026-07-29T12:00:00.000Z'), - }); +function recordingMailDelivery(): NorthshelfMailDelivery & { + readonly sent: { readonly recipient: string; readonly subject: string }[]; +} { + const sent: { recipient: string; subject: string }[] = []; + return { + sent, + provider: { + async send(request) { + sent.push({ + recipient: request.mail.recipient, + subject: request.mail.subject, + }); + return { providerMessageRef: `stub-${sent.length}` }; + }, + }, + reconciliation: { + async reconcile() { + return { status: 'delivered' as const }; + }, + }, + renderer: { + async render(content) { + if (content.expired) { + throw new Error('code expired'); + } + if (content.purpose === 'email_changed') { + return { + subject: 'Northshelf email changed', + text: `Changed to ${content.newEmail ?? ''}`, + }; + } + return { + subject: 'Northshelf sign-in code', + text: `Your code is ${content.code ?? 'unknown'}`, + }; + }, + }, + }; +} + +/** Explicit memory store + fixed clock + recording mail — never silent defaults. */ +function makeComposition(mail = recordingMailDelivery()) { + return { + composition: createNorthshelfComposition({ + store: createMemoryStore(), + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: mail, + clock: fixedClock('2026-07-29T12:00:00.000Z'), + }), + mail, + }; } describe('cf-passkey-accounts (Northshelf Branch)', () => { - it('wires Identity, Sessions, durable rate limits, and claims projection', async () => { - const composition = makeComposition(); + it('wires Identity, Sessions, durable rate limits, claims projection, and mail worker', async () => { + const { composition } = makeComposition(); const user = await composition.identity.provisionVerifiedUser({ principalId: 'prn_northshelf_patron' as PrincipalId, @@ -44,10 +89,11 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { const session = await composition.sessions.get(sessionId); expect(session?.principalId).toBe(user.principalId); expect(session?.data).toContain('authorizationLink'); + expect(composition.mailWorker).toBeDefined(); }); it('starts passkey registration for an existing user (ceremony is host/browser)', async () => { - const composition = makeComposition(); + const { composition } = makeComposition(); const user = await composition.identity.provisionVerifiedUser({ principalId: 'prn_northshelf_staff' as PrincipalId, email: 'staff@northshelf.example', @@ -62,8 +108,8 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { expect(typeof start.challengeHandle).toBe('string'); }); - it('starts email-code account creation without passwords', async () => { - const composition = makeComposition(); + it('starts email-code account creation and drains delivery through the mail worker', async () => { + const { composition, mail } = makeComposition(); const started = await composition.identity.beginAccountCreation( 'new.patron@northshelf.example', @@ -72,6 +118,12 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { expect(typeof started.codeHandle).toBe('string'); expect(started.codeHandle.length).toBeGreaterThan(8); expect(typeof started.expiresAt).toBe('string'); + + // Host schedule: drain Identity mail outbox after begin* commits a job. + const page = await composition.mailWorker.runSendPage({ limit: 20 }); + expect(page.examined).toBeGreaterThan(0); + expect(mail.sent.length).toBeGreaterThan(0); + expect(mail.sent[0]?.subject).toMatch(/code/i); }); it('refuses a missing or invalid email-code secret', () => { @@ -79,6 +131,7 @@ describe('cf-passkey-accounts (Northshelf Branch)', () => { createNorthshelfComposition({ store: createMemoryStore(), emailCodeSecretBase64: 'short', + mailDelivery: recordingMailDelivery(), }), ).toThrow(/missing or invalid/); }); diff --git a/recipes/cf-passkey-accounts/composition.ts b/recipes/cf-passkey-accounts/composition.ts index 8891453..04aa9cf 100644 --- a/recipes/cf-passkey-accounts/composition.ts +++ b/recipes/cf-passkey-accounts/composition.ts @@ -18,6 +18,10 @@ import { createHmacEmailCodeProtector, createIdentity, type Identity, + type IdentityMailRenderer, + type MailProvider, + type MailReconciliationPort, + type MailWorker, type VerifiedIdentityClaims, } from '@pegma/identity'; import { @@ -37,6 +41,14 @@ export const NORTHSHELF_RP = { origins: ['https://northshelf.example'] as const, } as const; +/** Host-owned mail delivery ports — required for email-code account flows. */ +export interface NorthshelfMailDelivery { + readonly provider: MailProvider; + readonly reconciliation: MailReconciliationPort; + readonly renderer: IdentityMailRenderer; + readonly workerId?: string; +} + export interface NorthshelfCompositionOptions { /** * Required injected store. Production hosts pass a durable adapter @@ -49,6 +61,11 @@ export interface NorthshelfCompositionOptions { * Host-managed; never generated at process start in production. */ readonly emailCodeSecretBase64: string; + /** + * Required mail ports so email-code account creation can be drained. + * Production: real provider (e.g. Resend). Tests: recording stubs. + */ + readonly mailDelivery: NorthshelfMailDelivery; readonly clock?: Clock; readonly logger?: Logger; } @@ -57,6 +74,8 @@ export interface NorthshelfComposition { readonly store: Store; readonly identity: Identity; readonly sessions: SessionStore; + /** Drains Identity mail outbox jobs (email codes, notices). */ + readonly mailWorker: MailWorker; readonly registrationLimiter: DurableRateLimiter; readonly authenticationLimiter: DurableRateLimiter; readonly emailCodeRequestLimiter: DurableRateLimiter; @@ -168,10 +187,20 @@ export function createNorthshelfComposition( ...(options.logger === undefined ? {} : { logger: options.logger }), }); + const mailWorker = identity.createMailWorker({ + workerId: options.mailDelivery.workerId ?? 'northshelf-identity-mail', + provider: options.mailDelivery.provider, + reconciliation: options.mailDelivery.reconciliation, + renderer: options.mailDelivery.renderer, + leaseMilliseconds: 30_000, + acceptedCallbackMilliseconds: 5 * 60_000, + }); + return Object.freeze({ store, identity, sessions, + mailWorker, registrationLimiter, authenticationLimiter, emailCodeRequestLimiter, diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index da82d0c..6545993 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -15,14 +15,14 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 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', + '@pegma/identity@0.1.0', + '@pegma/sessions@0.1.0', + '@pegma/mail@0.1.0', + '@pegma/rate-limit@0.1.0', + '@pegma/authorization-identity@0.1.2', + '@pegma/storage-core@0.4.0', + '@pegma/storage-cloudflare-d1@0.4.0', + '@pegma/spine@0.1.1', ], adapters: [{ componentId: 'storage-core', adapterId: 'cloudflare-d1' }], hostResponsibilities: [ @@ -74,7 +74,12 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 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'], + packages: [ + '@pegma/storage-core@0.4.0', + '@pegma/audit@0.1.0', + '@pegma/mail@0.1.0', + '@pegma/spine@0.1.1', + ], // Host chooses a durable storage-core adapter (cloudflare-d1 or azure-tables). // Do not pin memory here — the recipe needs durable inventory/audit/outbox rows. adapters: [], From 67d502706ac77fb68655bfb833d93874294d17f3 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 10:17:48 -0400 Subject: [PATCH 7/7] [2] Correct Yard Loan partition comment to desk-scoped atomicity. The fixture partitions by desk, not per loan; the type comment now matches storage-core single-partition transaction scope. --- recipes/storage-audit-mail-outbox/composition.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/recipes/storage-audit-mail-outbox/composition.ts b/recipes/storage-audit-mail-outbox/composition.ts index 78538dd..ee8d7d1 100644 --- a/recipes/storage-audit-mail-outbox/composition.ts +++ b/recipes/storage-audit-mail-outbox/composition.ts @@ -35,7 +35,11 @@ import { type StoredRecord, } from '@pegma/storage-core'; -/** One collection, one partition per loan — the only atomic scope. */ +/** + * One collection, one partition per desk (`desk|{deskId}`). + * All loan, audit, and mail rows for that desk share the only atomic scope + * Storage Core offers (single collection + single partition). + */ export type YardLoanRecord = | { readonly kind: 'loan';