Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 22 additions & 17 deletions docs/AGENT_ASSEMBLY_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --- | --- |
Expand All @@ -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
Expand Down Expand Up @@ -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:

Expand All @@ -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

Expand Down
13 changes: 6 additions & 7 deletions docs/catalog/GAP_INVENTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down Expand Up @@ -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
4 changes: 2 additions & 2 deletions docs/catalog/RECIPE_BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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`
Expand Down
23 changes: 23 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
5 changes: 3 additions & 2 deletions public/llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions recipes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 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

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.
138 changes: 138 additions & 0 deletions recipes/cf-passkey-accounts/composition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { fixedClock, type PrincipalId } from '@pegma/spine';
import { createMemoryStore } from '@pegma/storage-core';
import { describe, expect, it } from 'vitest';
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)));

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, claims projection, and mail worker', async () => {
const { composition } = makeComposition();

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, claims);
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 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 and drains delivery through the mail worker', async () => {
const { composition, mail } = makeComposition();

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');

// 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', () => {
expect(() =>
createNorthshelfComposition({
store: createMemoryStore(),
emailCodeSecretBase64: 'short',
mailDelivery: recordingMailDelivery(),
}),
).toThrow(/missing or invalid/);
});
});
Loading
Loading