229 lines · 9.4 KB · TypeScriptRaw
/** * The MCP tool pairs, held to one written answer on both sides: the Worker's * half of crates/cotton-tools/tests/mcp_goldens.rs, reading the SAME files * (crates/cotton-tools/tests/goldens/*.json). A case under `cases` answers the * same on the phone and here; a case under `differs` is a known difference, * each side's answer written down (`rust`, `worker`) until it is settled. * * Each case runs on a fresh personal object, seeded through the admin import, * its calls made by a read-and-write token; a step's arg that is exactly * `{{n.path}}` is step n's answer at that dotted path. Every answer is normalised before * it is compared, by the rule the Rust file's doc comment states: case-new * UUIDs become <id1>…, RFC 3339 instants <instant>, today's UTC date <today>, * a volatile key's value "<volatile>", and this Worker's undo envelope is left * out unless a step asks for it (`envelope: true`). */import { describe, expect, it } from "vitest";import briefings from "../../../crates/cotton-rules/vectors/memory_briefing.json";import { compileBriefing, type BriefingEntry } from "../src/mcp/tools/memory/briefing.ts";import { mint, NOTES_OPEN, BOOKS_OPEN, FILMS_OPEN, personalObject, put, tool, PEOPLE_OPEN, PHOTOS_OPEN, TODOS_OPEN } from "./personal.ts";const files = import.meta.glob("../../../crates/cotton-tools/tests/goldens/*.json", { eager: true, import: "default" }) as Record<string, Golden>;/** Keys whose values move from run to run on either side (mcp_goldens.rs `VOLATILE_KEYS`). */const VOLATILE_KEYS = new Set(["change_id"]);const SEED_AT = "2026-01-01T00:00:00.000Z";type Expectation = { answer: unknown } | { refusal: string };interface Step { tool: string; args?: Record<string, unknown>; expect?: Expectation; worker?: Expectation; envelope?: boolean;}/** mcp_goldens.rs rule 5: the answer without this Worker's undo envelope (src/changes.ts), which the phone answers no write with. */function withoutEnvelope(answer: unknown): unknown { if (!answer || typeof answer !== "object" || Array.isArray(answer)) return answer; const out = { ...(answer as Record<string, unknown>) }; if ("change_id" in out) delete out.changes; delete out.change_id; delete out.undoable; return out;}interface Case { name: string; seed?: { kind: string; id: string; data: Record<string, unknown>; at?: string }[]; steps: Step[];}interface Golden { pair: string; cases?: Case[]; differs?: Case[]; /** briefing.json: the compiler's goldens are the Rust fixture; this lists the cases the Worker answers otherwise. */ compiler?: { differs: { name: string; worker: BriefingAnswer }[] };}const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;const INSTANT = /\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})/g;class Ids { own: Set<string>; tokens = new Map<string, string>(); constructor(c: Case) { this.own = new Set((c.seed ?? []).map((r) => r.id)); for (const s of c.steps) for (const m of JSON.stringify(s.args ?? {}).matchAll(UUID)) this.own.add(m[0]); } token(id: string): string { if (this.own.has(id)) return id; const known = this.tokens.get(id); if (known) return known; const t = `<id${this.tokens.size + 1}>`; this.tokens.set(id, t); return t; }}function normalisedText(text: string, ids: Ids, today: string): string { return text .replace(UUID, (id) => ids.token(id)) .replace(INSTANT, "<instant>") .replaceAll(today, "<today>");}function normalised(value: unknown, ids: Ids, today: string): unknown { if (typeof value === "string") return normalisedText(value, ids, today); if (Array.isArray(value)) return value.map((v) => normalised(v, ids, today)); if (value && typeof value === "object") { const out: Record<string, unknown> = {}; for (const [k, v] of Object.entries(value)) out[k] = VOLATILE_KEYS.has(k) ? "<volatile>" : normalised(v, ids, today); return out; } return value;}/** A step's args with each `{{n.path}}` replaced by that earlier answer's value, as the tool gave it. */function resolved(args: unknown, answers: unknown[]): unknown { if (typeof args === "string") { const m = /^\{\{(\d+)\.([^}]+)\}\}$/.exec(args); if (!m) return args; let at: unknown = answers[Number(m[1])]; for (const key of m[2]!.split(".")) at = at && typeof at === "object" ? (at as Record<string, unknown>)[key] : undefined; return at ?? null; } if (Array.isArray(args)) return args.map((a) => resolved(a, answers)); if (args && typeof args === "object") return Object.fromEntries(Object.entries(args).map(([k, v]) => [k, resolved(v, answers)])); return args;}let objects = 0;async function run(c: Case): Promise<Expectation[]> { const slug = `golden-${++objects}`; // The todo tables open too: the goldens test the todo tools' mechanics, and since AUDIT C 2-2 create_todo on sealed // todos writes only in a window or sealed at arrival (test/audit-c-assistant-key.test.ts holds that rule). const { credential } = await personalObject(slug, { open: [...NOTES_OPEN.open, ...BOOKS_OPEN.open, ...FILMS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...TODOS_OPEN] }); const token = await mint(slug, credential, "Claude", ["read", "write"]); const seed = c.seed ?? []; if (seed.length) await put(slug, seed.map((r) => ({ verb: "put", table: r.kind, id: r.id, data: r.data, created_at: r.at ?? SEED_AT, updated_at: r.at ?? SEED_AT }))); const ids = new Ids(c); const got: Expectation[] = []; const answers: unknown[] = []; for (const step of c.steps) { const r = await tool(slug, token, step.tool, resolved(step.args ?? {}, answers) as Record<string, unknown>); const today = new Date().toISOString().slice(0, 10); const text = r.content[0]?.text ?? ""; if (r.isError) { answers.push(null); got.push({ refusal: normalisedText(text, ids, today) }); } else { let parsed: unknown; try { parsed = JSON.parse(text); } catch { parsed = text; } answers.push(parsed); got.push({ answer: normalised(step.envelope ? parsed : withoutEnvelope(parsed), ids, today) }); } } return got;}for (const [path, golden] of Object.entries(files)) { const file = path.split("/").pop()!; describe(`${file}: ${golden.pair}`, () => { for (const c of golden.cases ?? []) { it(c.name, async () => { const got = await run(c); expect(got).toEqual(c.steps.map((s) => s.expect)); }); } for (const c of golden.differs ?? []) { it(`differs from the phone: ${c.name}`, async () => { const got = await run(c); expect(got).toEqual(c.steps.map((s) => s.expect ?? s.worker)); }); } });}// ── the briefing compiler: the Rust goldens, read here ───────────────────────interface FixtureEntry { slug: string; title: string; pinned: boolean; position?: number; machine: string | null; createdAt: string;}interface FixtureCase { name: string; input: { ownerName: string | null; generatedAt: string; machine: string | null; projects: { slug: string; name: string; entries: FixtureEntry[] }[]; owner: FixtureEntry[] | null; procedures: { project: string; id: string; title: string; trigger: string }[] | null; budgetTokens: number | null; }; result: BriefingAnswer;}interface BriefingAnswer { markdown: string; tokensEstimate: number; overBudget: boolean; dropped: { entries: number; procedures: number; procedures_cut: number };}const entry = (e: FixtureEntry): BriefingEntry => ({ slug: e.slug, title: e.title, pinned: e.pinned, position: e.position ?? 0, machine: e.machine, created_at: e.createdAt });/** The Worker's compiler on a fixture input, answered in the fixture's shape. */function workerBriefing(input: FixtureCase["input"]): BriefingAnswer { const r = compileBriefing({ generatedAt: input.generatedAt, machine: input.machine, projects: input.projects.map((p) => ({ slug: p.slug, name: p.name, entries: p.entries.map(entry) })), owner: input.owner ? input.owner.map(entry) : null, procedures: input.procedures ?? [], budgetTokens: input.budgetTokens, }); return { markdown: r.markdown, tokensEstimate: r.tokensEstimate, overBudget: r.overBudget, dropped: { entries: r.dropped.entries, procedures: r.dropped.procedures, procedures_cut: r.dropped.proceduresCut } };}/** * crates/cotton-rules/vectors/memory_briefing.json, the Rust compiler's * whole-document goldens. A case naming the owner is the Rust compiler's * alone: the Worker's takes no owner name, and neither tool passes one * (memory.rs `owner_name` is always None), so the served-* cases are the same * inputs with none. */describe("memory_briefing.json: the briefing compiler, on the phone's goldens", () => { const ledger = Object.entries(files).find(([path]) => path.endsWith("/briefing.json"))?.[1].compiler?.differs ?? []; const differs = new Map(ledger.map((d) => [d.name, d.worker])); const served = (briefings as FixtureCase[]).filter((c) => c.input.ownerName === null); it("holds served cases, and every listed difference names one", () => { expect(served.length).toBeGreaterThanOrEqual(8); for (const name of differs.keys()) expect(served.map((c) => c.name)).toContain(name); }); for (const c of served) { const worker = differs.get(c.name); it(worker ? `differs from the phone: ${c.name}` : c.name, () => { expect(workerBriefing(c.input)).toEqual(worker ?? c.result); }); }});