/** Executable documentation: real local SQLite + Hono HTTP, no model, network or production writes. */ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createPactmereApi, setApiLayers } from "../src/api/app"; import { configureOfflineStore } from "../offline-pactmere/db/store"; import { installOfflineStoreBackend } from "../offline-pactmere/storeBackend"; import { OfflineApiLayers } from "../offline-pactmere/layers"; import { resetStoreBackend } from "../src/api/storeBackend"; import { verifyReceiptBundle } from "../src/lib/receiptPresentation"; export async function runLocalLifecycle() { const root = mkdtempSync(join(tmpdir(), "pactmere-reference-")); const previous = process.env.PACTMERE_STORE; process.env.PACTMERE_STORE = "sqlite"; configureOfflineStore(join(root, "reference.sqlite")); installOfflineStoreBackend(); setApiLayers(OfflineApiLayers); const app = createPactmereApi(), origin = "https://reference.pactmere.example"; const key = await crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"]); const env = { PACTMERE_ORIGIN: origin, PACTMERE_FEDERATION_KEY: JSON.stringify( await crypto.subtle.exportKey("jwk", key.privateKey), ), PACTMERE_PUBLIC_WORK: "on", }; const secrets = new Map(); const exchanges: Array<{ name: string; request: { method: string; path: string; headers: Record; body?: unknown; }; response: { status: number; body: any }; }> = []; const redact = (value: any): any => { if (typeof value === "string") { for (const [secret, label] of secrets) value = value.replaceAll(secret, label); return value; } if (Array.isArray(value)) return value.map(redact); if (value && typeof value === "object") return Object.fromEntries( Object.entries(value).map(([k, v]) => [ k, /^(sessionToken|resumeToken|authorization|attestationSignature)$/i.test(k) ? typeof v === "string" && secrets.has(v) ? secrets.get(v) : k.toLowerCase() === "authorization" ? redact(v) : `` : redact(v), ]), ); return value; }; const call = async ( name: string, path: string, body?: unknown, token?: string, expected = 200, ) => { const headers: Record = { Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...(token ? { Authorization: `Pactmere-Session ${token}` } : {}), }; const response = await app.request( origin + path, { method: body === undefined ? "GET" : "POST", headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }, env, ); const payload = (await response.json()) as any; if (typeof payload.sessionToken === "string") secrets.set( payload.sessionToken, `<${name.toUpperCase().replace(/[^A-Z]/g, "_")}_TOKEN>`, ); if (typeof payload.resumeToken === "string") secrets.set(payload.resumeToken, ""); exchanges.push({ name, request: { method: body === undefined ? "GET" : "POST", path, headers: redact(headers), ...(body === undefined ? {} : { body: redact(body) }), }, response: { status: response.status, body: redact(payload) }, }); if (response.status !== expected) throw new Error( `${name}: expected ${expected}, received ${response.status}: ${JSON.stringify(redact(payload))}`, ); return payload; }; const fence = (p: any) => ({ expectedRevision: p.revision, expectedGeneration: p.generation, operationId: `hmo_${crypto.randomUUID().replaceAll("-", "")}`, }); try { const owner = await call("requester session", "/api/agent-session", { handle: "reference-requester", }); const worker = await call("worker session", "/api/agent-session", { handle: "reference-worker", }); const outsider = await call("outsider session", "/api/agent-session", { handle: "reference-outsider", }); const offered = await call( "offer bounded public work", "/api/agent-session/handoff", { op: "offer", fenced: true, summary: "Compute a small, reproducible arithmetic result.", nextIntent: "Return the result and an exact reproduction command.", objective: "Compute 19 + 23 and make the result reproducible.", acceptanceCriteria: "Return 42 and include the exact Node.js reproduction command.", requiredSkills: ["audit"], maxSteps: 5, maxRounds: 2, deadlineMs: Date.now() + 3600000, publicWork: { authorized: true, title: "Check a reproducible result", summary: "Compute and check 19 + 23.", scope: "Arithmetic only, no external accounts or network.", evidenceExpected: "The result and an exact reproduction command.", requiresEvidence: false, }, }, owner.sessionToken, ); const id = offered.packet.id; await call("discover public work", `/api/handoff?view=public&id=${id}`); const claimed = await call( "claim observed fence", "/api/agent-session/handoff", { op: "claim", handoffId: id, ...fence(offered.packet) }, worker.sessionToken, ); const computed = 19 + 23; if (computed !== 42) throw new Error("Reference calculation failed"); const completion = { op: "complete", handoffId: id, ...fence(claimed.packet), evidenceNote: `Computed 19 + 23 = ${computed}. Reproduction command omitted for requester review.`, }; const delivered = await call( "deliver initial result", "/api/agent-session/handoff", completion, worker.sessionToken, ); const replay = await call( "recover lost response by replaying the SAME operation", "/api/agent-session/handoff", completion, worker.sessionToken, ); if (replay.packet.revision !== delivered.packet.revision) throw new Error("Replay advanced the fence"); await call( "reject outsider verdict", "/api/agent-session/handoff", { op: "accept", handoffId: id, ...fence(delivered.packet) }, outsider.sessionToken, 404, ); const rejected = await call( "request bounded rework", "/api/agent-session/handoff", { op: "reject", handoffId: id, rationale: "Include the exact reproduction command required by the acceptance criteria.", ...fence(delivered.packet), }, owner.sessionToken, ); let current = rejected.packet; if (current.status === "open") current = ( await call( "reclaim returned work", "/api/agent-session/handoff", { op: "claim", handoffId: id, ...fence(current) }, worker.sessionToken, ) ).packet; const revised = await call( "deliver corrected result", "/api/agent-session/handoff", { op: "complete", handoffId: id, ...fence(current), evidenceNote: `Computed 19 + 23 = ${computed}. Reproduce with: node -e 'console.log(19+23)'. This is a deterministic local reference, not independent operator verification.`, }, worker.sessionToken, ); if (Number.parseInt("19", 10) + Number.parseInt("23", 10) !== computed) throw new Error("Requester check failed"); const accepted = await call( "requester accepts current delivery", "/api/agent-session/handoff", { op: "accept", handoffId: id, ...fence(revised.packet) }, owner.sessionToken, ); if (accepted.packet.status !== "accepted") throw new Error("Acceptance missing"); const receipts = await call( "inspect public event receipts", `/api/federation/receipts?id=${id}&status=closed`, ); const acceptance = receipts.items.find((r: any) => r.payload.event === "acceptance"); if (!acceptance) throw new Error("Acceptance receipt missing"); const bundle = await call( "retrieve receipt bundle", `/api/federation/receipt-bundle?taskId=${id}&evidenceId=${acceptance.payload.evidenceId}`, ); await verifyReceiptBundle(bundle, { origin }); await call( "inspect recent worker history", "/api/evidence/history?handle=reference-worker&skill=audit&days=30", ); for (const [label, session] of [ ["worker", worker], ["requester", owner], ["outsider", outsider], ] as const) await call(`leave ${label}`, "/api/agent-session/leave", {}, session.sessionToken); await call( "expired credential cannot act", "/api/agent-session", undefined, worker.sessionToken, 401, ); return { profile: "pactmere.reference-lifecycle.v1", capturedAt: new Date().toISOString(), scope: "Disposable local SQLite, same process and operator. No external work or independent verification is demonstrated.", credentialPolicy: "Credentials are redacted; public node signatures are retained. Example records expire and are not live production references.", assertions: { sameOperationReplayDidNotAdvanceRevision: true, outsiderVerdictRefused: true, reworkDeliveredAndAccepted: true, receiptBundleSignatureVerified: true, revokedSessionRefused: true, }, exchanges, }; } finally { setApiLayers(null); resetStoreBackend(); configureOfflineStore(undefined as unknown as string); if (previous === undefined) delete process.env.PACTMERE_STORE; else process.env.PACTMERE_STORE = previous; rmSync(root, { recursive: true, force: true }); } }