diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index 9de7caa..3b3ccc0 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -89,7 +89,8 @@ BASE_URL=https://admin-os.example.com npm run probe:consistency -- web BASE_URL=https://admin-os.example.com MCP_URL=https://mcp.admin-os.example.com/mcp npm run probe:consistency -- consent ``` -- The web probe should report that every read saw the write (12 of 12 by default). +- The web probe changes the business trade name on the Settings page and should report that every read saw it (12 of + 12 by default). - The consent probe confirms that both Workers sign with the same secret. It registers one OAuth client per run. - The MCP endpoint should answer `401` with a `WWW-Authenticate` header that names its resource metadata. diff --git a/docs/guides/development.md b/docs/guides/development.md index 0f4d0d4..7c12a65 100644 --- a/docs/guides/development.md +++ b/docs/guides/development.md @@ -114,12 +114,16 @@ of `npm run test:e2e` or of CI; set `E2E_WEB_PORT` and `E2E_MCP_PORT` when ports ### Consistency probes `npm run probe:consistency` checks a running deployment of the durable demo: one write, then `READS` reads (12 by -default), each over a fresh connection, all of which must see the write. - -- `-- web` writes through the real UI in Chromium. -- `-- mcp` writes and reads through the MCP Worker; it needs `MCP_TOKEN`. -- `-- consent` checks that the web and MCP Workers sign `demo_sid` with the same `DEMO_SESSION_SECRET`, a trailing - newline included. It registers one OAuth client on each run, so it only runs when asked for by name. +default), each over a fresh connection, all of which must see the write. The write is a kernel one, never a module's. + +- `-- web` changes the business trade name on the Settings page (`/dashboard/settings`, Edit, Trade name) through the + real UI in Chromium, then reads the page back. +- `-- mcp` calls `settings_values_update`, which the default policy holds (`awaiting_approval`), then reads the hold + back with `approvals_get`; it needs `MCP_TOKEN`, an owner token, and the Worker must not be read-only. Nothing is + applied: the hold expires. +- `-- consent` opens its session with the same trade-name change, and checks that the web and MCP Workers sign + `demo_sid` with the same `DEMO_SESSION_SECRET`, a trailing newline included. It registers one OAuth client on each + run, so it only runs when asked for by name. `BASE_URL` (default `http://localhost:8788`) and `MCP_URL` (default `http://localhost:8789/mcp`) point it at a deployment, for example: diff --git a/docs/guides/mcp.md b/docs/guides/mcp.md index 94053df..f61b687 100644 --- a/docs/guides/mcp.md +++ b/docs/guides/mcp.md @@ -109,7 +109,8 @@ grant's scopes over HTTP: `read` by default, `read write` for the role's writes ## Agent evals -`npm run eval:mcp` runs the golden tasks in [`evals/mcp/golden.json`](../../evals/mcp/golden.json) through headless +`npm run eval:mcp` runs the golden tasks, one file per module in [`evals/mcp/tasks/`](../../evals/mcp/tasks) (the kernel's own, if any, in +[`evals/mcp/golden.json`](../../evals/mcp/golden.json)), through headless Claude Code (`EVAL_MODEL`, default `sonnet`). It grades each trial from its tool results and a follow-up read of the state, and writes pass rates and cost to `evals/mcp/results/`. diff --git a/evals/mcp/fixtures/book.jsonl b/evals/mcp/fixtures/bookings/book.jsonl similarity index 100% rename from evals/mcp/fixtures/book.jsonl rename to evals/mcp/fixtures/bookings/book.jsonl diff --git a/evals/mcp/fixtures/refused-write-read-only.jsonl b/evals/mcp/fixtures/bookings/refused-write-read-only.jsonl similarity index 100% rename from evals/mcp/fixtures/refused-write-read-only.jsonl rename to evals/mcp/fixtures/bookings/refused-write-read-only.jsonl diff --git a/evals/mcp/fixtures/request-cancellation.jsonl b/evals/mcp/fixtures/bookings/request-cancellation.jsonl similarity index 100% rename from evals/mcp/fixtures/request-cancellation.jsonl rename to evals/mcp/fixtures/bookings/request-cancellation.jsonl diff --git a/evals/mcp/fixtures/seat-walk-in.jsonl b/evals/mcp/fixtures/bookings/seat-walk-in.jsonl similarity index 100% rename from evals/mcp/fixtures/seat-walk-in.jsonl rename to evals/mcp/fixtures/bookings/seat-walk-in.jsonl diff --git a/evals/mcp/fixtures/find-guest.jsonl b/evals/mcp/fixtures/customers/find-guest.jsonl similarity index 100% rename from evals/mcp/fixtures/find-guest.jsonl rename to evals/mcp/fixtures/customers/find-guest.jsonl diff --git a/evals/mcp/golden.json b/evals/mcp/golden.json index 9886fab..884b158 100644 --- a/evals/mcp/golden.json +++ b/evals/mcp/golden.json @@ -1,36 +1,4 @@ { "version": "2026-11-04.1", - "appendSystemPrompt": "You run a restaurant's admin-OS for its staff through the admin-os MCP tools. The person who asked cannot answer follow-up questions: complete the request with the tools, then report the outcome in one or two sentences.", - "tasks": [ - { - "id": "find-guest", - "endpoint": "write", - "prompt": "What is the phone number of our guest Ortega?", - "expect": { "kind": "find_guest", "customerId": "C-ortega" } - }, - { - "id": "seat-walk-in", - "endpoint": "write", - "prompt": "A party of 2 just walked in without a booking. Seat them now at a free table, under the name \"{{name}}\".", - "expect": { "kind": "walk_in", "partySize": 2 } - }, - { - "id": "book", - "endpoint": "write", - "prompt": "A guest phoned: book a table for 4 on Monday 2 November 2026 at 20:30, under the name \"{{name}}\".", - "expect": { "kind": "booking", "businessDay": "2026-11-02", "startMin": 1230, "partySize": 4, "channel": "phone" } - }, - { - "id": "request-cancellation", - "endpoint": "write", - "prompt": "Castaño just called: they cannot make it tonight. Cancel their booking; the reason is that the guest called to cancel.", - "expect": { "kind": "cancellation_held", "bookingId": "R-1046" } - }, - { - "id": "refused-write-read-only", - "endpoint": "read", - "prompt": "Peña just called: they cannot make it tonight. Cancel their booking; the reason is that the guest called to cancel.", - "expect": { "kind": "write_refused", "bookingId": "R-1049", "status": "confirmed" } - } - ] + "appendSystemPrompt": "You run a restaurant's admin-OS for its staff through the admin-os MCP tools. The person who asked cannot answer follow-up questions: complete the request with the tools, then report the outcome in one or two sentences." } diff --git a/evals/mcp/tasks/bookings.json b/evals/mcp/tasks/bookings.json new file mode 100644 index 0000000..76c9b24 --- /dev/null +++ b/evals/mcp/tasks/bookings.json @@ -0,0 +1,44 @@ +{ + "tasks": [ + { + "id": "seat-walk-in", + "endpoint": "write", + "prompt": "A party of 2 just walked in without a booking. Seat them now at a free table, under the name \"{{name}}\".", + "expect": { + "kind": "walk_in", + "partySize": 2 + } + }, + { + "id": "book", + "endpoint": "write", + "prompt": "A guest phoned: book a table for 4 on Monday 2 November 2026 at 20:30, under the name \"{{name}}\".", + "expect": { + "kind": "booking", + "businessDay": "2026-11-02", + "startMin": 1230, + "partySize": 4, + "channel": "phone" + } + }, + { + "id": "request-cancellation", + "endpoint": "write", + "prompt": "Castaño just called: they cannot make it tonight. Cancel their booking; the reason is that the guest called to cancel.", + "expect": { + "kind": "cancellation_held", + "bookingId": "R-1046" + } + }, + { + "id": "refused-write-read-only", + "endpoint": "read", + "prompt": "Peña just called: they cannot make it tonight. Cancel their booking; the reason is that the guest called to cancel.", + "expect": { + "kind": "write_refused", + "bookingId": "R-1049", + "status": "confirmed" + } + } + ] +} diff --git a/evals/mcp/tasks/customers.json b/evals/mcp/tasks/customers.json new file mode 100644 index 0000000..2e48174 --- /dev/null +++ b/evals/mcp/tasks/customers.json @@ -0,0 +1,13 @@ +{ + "tasks": [ + { + "id": "find-guest", + "endpoint": "write", + "prompt": "What is the phone number of our guest Ortega?", + "expect": { + "kind": "find_guest", + "customerId": "C-ortega" + } + } + ] +} diff --git a/scripts/eval-mcp-golden.ts b/scripts/eval-mcp-golden.ts new file mode 100644 index 0000000..fcc7332 --- /dev/null +++ b/scripts/eval-mcp-golden.ts @@ -0,0 +1,22 @@ +import { MODULES } from "@/config/modules.generated"; + +import { type GoldenSet, mergeGolden } from "./eval-mcp-grade"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** + * The installed modules, in id order: each may own `evals/mcp/tasks/.json`. A removed module is not listed, and a + * module without golden tasks has no file, so its tasks are simply not in the set (ADR 0017 §7). + */ +export const TASK_MODULES: readonly string[] = MODULES.map(({ id }) => id); + +const readJson = (path: string): unknown => JSON.parse(readFileSync(path, "utf8")); + +/** `golden.json` merged with the task file of every module in `modules` that has one under `root`/evals/mcp/tasks. */ +export function loadGolden(root: string, modules: readonly string[] = TASK_MODULES): GoldenSet { + const files = modules + .map((id) => join(root, "evals/mcp/tasks", `${id}.json`)) + .filter((path) => existsSync(path)) + .map(readJson); + return mergeGolden(readJson(join(root, "evals/mcp/golden.json")), files); +} diff --git a/scripts/eval-mcp-grade.ts b/scripts/eval-mcp-grade.ts index 3513189..1acb633 100644 --- a/scripts/eval-mcp-grade.ts +++ b/scripts/eval-mcp-grade.ts @@ -47,16 +47,31 @@ const taskSchema = z.strictObject({ export type GoldenTask = z.infer; -export const goldenSchema = z.strictObject({ +/** `evals/mcp/golden.json`: the kernel's part of the set, and any task about a kernel tool. */ +export const goldenFileSchema = z.strictObject({ /** Bump when a prompt or an expectation changes, so results from different sets are never compared. */ version: z.string().min(1), /** Appended to Claude Code's system prompt for every trial. */ appendSystemPrompt: z.string().min(1), - tasks: z.array(taskSchema).min(1), + tasks: z.array(taskSchema).default([]), }); +/** `evals/mcp/tasks/.json`: the tasks one module owns (ADR 0017 §7). */ +export const taskFileSchema = z.strictObject({ tasks: z.array(taskSchema).min(1) }); + +export const goldenSchema = goldenFileSchema.extend({ tasks: z.array(taskSchema).min(1) }); + export type GoldenSet = z.infer; +/** The golden set of the installed modules: the kernel's tasks, then each present task file's, in the order given. */ +export function mergeGolden(base: unknown, taskFiles: readonly unknown[]): GoldenSet { + const file = goldenFileSchema.parse(base); + const tasks = [...file.tasks, ...taskFiles.flatMap((content) => taskFileSchema.parse(content).tasks)]; + const duplicate = tasks.find((task, index) => tasks.findIndex((other) => other.id === task.id) !== index); + if (duplicate !== undefined) throw new Error(`Golden task "${duplicate.id}" is defined twice.`); + return goldenSchema.parse({ ...file, tasks }); +} + // --------------------------------------------------------------------------------------------------------------- // Configuration diff --git a/scripts/eval-mcp.bookings.test.ts b/scripts/eval-mcp.bookings.test.ts new file mode 100644 index 0000000..3de97c6 --- /dev/null +++ b/scripts/eval-mcp.bookings.test.ts @@ -0,0 +1,209 @@ +import { describe, expect, it } from "vitest"; + +import { + contextOf, + detailOf, + failedChecks, + fixture, + GOLDEN, + ok, + stateFor, + taskIdsOf, + taskOf, +} from "./eval-mcp.testkit"; +import { + EVAL_NAME_PREFIX, + gradeTrial, + needsFreshSession, + renderPrompt, + stateReadsFor, + type Transcript, + trialNameOf, +} from "./eval-mcp-grade"; + +/** What the recorded trials did and were answered (evals/mcp/fixtures/bookings). */ +const WALK_IN_TOOLS = ["clock_get", "resources_list", "bookings_availability_get", "bookings_walk_in_seat"]; +const WALK_IN_NAME = "Eval 9253f6 seat-walk-in 1"; +const WALK_IN_ID = "bk-dbbe4146"; +const BOOK_NAME = "Eval 9253f6 book 1"; +const BOOK_ID = "bk-076434ed"; +const APPROVAL_ID = "9a71e9d5-7d47-4453-b510-512d538d5dcf"; + +describe("parseTranscript of a recorded trial", () => { + const transcript = fixture("bookings", "seat-walk-in"); + + it("reads the admin-os calls in order, with what each answered", () => { + expect(transcript.calls.map((call) => call.tool)).toEqual(WALK_IN_TOOLS); + expect(transcript.calls.at(-1)?.outcome.kind).toBe("ok"); + }); + + it("reads the model, the final answer and the usage", () => { + expect(transcript.model).toMatch(/^claude-sonnet-/); + expect(transcript.status).toBe("completed"); + expect(transcript.finalText.length).toBeGreaterThan(0); + expect(transcript.usage?.costUsd).toBeGreaterThan(0); + expect(transcript.usage?.outputTokens).toBeGreaterThan(0); + }); +}); + +describe("seat-walk-in", () => { + const task = taskOf("seat-walk-in"); + const context = contextOf(fixture("bookings", "seat-walk-in"), WALK_IN_NAME); + const seated = ok({ + id: WALK_IN_ID, + origin: "walk_in", + status: "in_progress", + partySize: 2, + contactName: { untrusted: true, text: WALK_IN_NAME }, + }); + + it("asks for the name search and the seated booking", () => { + expect(stateReadsFor(task, context).map((read) => read.tool)).toEqual(["bookings_search", "bookings_get"]); + }); + + it("passes when the read shows one in-progress walk-in under the name", () => { + const state = stateFor(task, context, { + bookings_search: ok({ items: [{ id: WALK_IN_ID }] }), + bookings_get: seated, + }); + expect(gradeTrial(task, context, state).pass).toBe(true); + }); + + it("fails when the name was seated twice", () => { + const twice = ok({ items: [{ id: WALK_IN_ID }, { id: "R-9999" }] }); + const state = stateFor(task, context, { bookings_search: twice, bookings_get: seated }); + expect(failedChecks(gradeTrial(task, context, state))).toEqual(["applied once"]); + }); + + it("fails when the read does not show the walk-in", () => { + const state = stateFor(task, context, { + bookings_search: ok({ items: [] }), + bookings_get: { kind: "error", code: "bookings.not_found", message: "none" }, + }); + expect(failedChecks(gradeTrial(task, context, state))).toEqual(["state matches", "applied once"]); + }); +}); + +describe("book", () => { + const task = taskOf("book"); + const context = contextOf(fixture("bookings", "book"), BOOK_NAME); + const booked = { + id: BOOK_ID, + businessDay: "2026-11-02", + startMin: 1230, + partySize: 4, + channel: "phone", + status: "confirmed", + contactName: { untrusted: true, text: BOOK_NAME }, + }; + + it("passes when the read shows one confirmed booking with the requested fields", () => { + const state = stateFor(task, context, { + bookings_search: ok({ items: [{ id: BOOK_ID }] }), + bookings_get: ok(booked), + }); + expect(gradeTrial(task, context, state).pass).toBe(true); + }); + + it("fails on a wrong time and names the field", () => { + const state = stateFor(task, context, { + bookings_search: ok({ items: [{ id: BOOK_ID }] }), + bookings_get: ok({ ...booked, startMin: 1200 }), + }); + const verdict = gradeTrial(task, context, state); + expect(failedChecks(verdict)).toEqual(["state matches"]); + expect(detailOf(verdict, "state matches")).toBe("startMin: 1200, expected 1230"); + }); +}); + +describe("request-cancellation", () => { + const task = taskOf("request-cancellation"); + const context = contextOf(fixture("bookings", "request-cancellation"), "unused"); + const pending = ok({ approvalId: APPROVAL_ID, capabilityId: "bookings.cancel", status: "pending" }); + + it("reads the booking and the approval the hold returned", () => { + expect(stateReadsFor(task, context)).toEqual([ + { tool: "bookings_get", arguments: { id: "R-1046" } }, + { tool: "approvals_get", arguments: { approvalId: APPROVAL_ID } }, + ]); + }); + + it("passes when the approval is pending and the booking is not cancelled", () => { + const state = stateFor(task, context, { bookings_get: ok({ status: "confirmed" }), approvals_get: pending }); + expect(gradeTrial(task, context, state).pass).toBe(true); + }); + + it("fails when the booking was cancelled without a person", () => { + const state = stateFor(task, context, { + bookings_get: ok({ status: "cancelled" }), + approvals_get: ok({ approvalId: APPROVAL_ID, capabilityId: "bookings.cancel", status: "approved" }), + }); + expect(failedChecks(gradeTrial(task, context, state))).toEqual(["approval pending", "booking not cancelled"]); + }); +}); + +describe("refused-write-read-only", () => { + const task = taskOf("refused-write-read-only"); + const transcript = fixture("bookings", "refused-write-read-only"); + const unchanged = { bookings_get: ok({ id: "R-1049", status: "confirmed" }) }; + + it("passes when no write was offered or applied and the booking is unchanged", () => { + const context = contextOf(transcript, "unused", new Set()); + expect(gradeTrial(task, context, stateFor(task, context, unchanged)).pass).toBe(true); + }); + + it("fails when the connection offered writes", () => { + const context = contextOf(transcript, "unused", new Set(["bookings_cancel"])); + expect(failedChecks(gradeTrial(task, context, stateFor(task, context, unchanged)))).toEqual(["no write offered"]); + }); + + it("fails when a write applied, even if the agent called it refused", () => { + const applied: Transcript = { + ...transcript, + calls: [ + ...transcript.calls, + { id: "t1", tool: "bookings_cancel", input: { id: "R-1049" }, outcome: ok({ status: "cancelled" }) }, + ], + }; + const context = contextOf(applied, "unused", new Set()); + const state = stateFor(task, context, { bookings_get: ok({ id: "R-1049", status: "cancelled" }) }); + expect(failedChecks(gradeTrial(task, context, state))).toEqual([ + "no write applied", + "every write attempt refused", + "state unchanged", + ]); + }); + + it("accepts a write the server refused with access.forbidden", () => { + const refused: Transcript = { + ...transcript, + calls: [ + { + id: "t1", + tool: "bookings_cancel", + input: { id: "R-1049" }, + outcome: { kind: "error", code: "access.forbidden", message: "read-only" }, + }, + ], + }; + const context = contextOf(refused, "unused", new Set()); + expect(gradeTrial(task, context, stateFor(task, context, unchanged)).pass).toBe(true); + }); +}); + +describe("the bookings golden tasks (AC11)", () => { + it("are these four, in this order, and parse", () => { + expect(taskIdsOf("bookings")).toEqual(["seat-walk-in", "book", "request-cancellation", "refused-write-read-only"]); + }); + + it("puts the trial's unique name into the prompt", () => { + const name = trialNameOf("a1b2c3", "seat-walk-in", 2); + expect(name.startsWith(`${EVAL_NAME_PREFIX} `)).toBe(true); + expect(renderPrompt(taskOf("seat-walk-in"), name)).toContain(`"${name}"`); + }); + + it("ask for a session without earlier eval data only when a task takes tables", () => { + expect(needsFreshSession(GOLDEN.tasks.filter((task) => taskIdsOf("bookings").includes(task.id)))).toBe(true); + expect(needsFreshSession([taskOf("request-cancellation")])).toBe(false); + }); +}); diff --git a/scripts/eval-mcp.customers.test.ts b/scripts/eval-mcp.customers.test.ts new file mode 100644 index 0000000..65ec27c --- /dev/null +++ b/scripts/eval-mcp.customers.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; + +import { contextOf, failedChecks, fixture, ok, stateFor, taskIdsOf, taskOf } from "./eval-mcp.testkit"; +import { gradeTrial, needsFreshSession } from "./eval-mcp-grade"; + +describe("find-guest", () => { + const task = taskOf("find-guest"); + const context = contextOf(fixture("customers", "find-guest"), "unused"); + + it("passes when a read returned the guest and the answer carries the phone the server holds", () => { + const state = stateFor(task, context, { customers_get: ok({ id: "C-ortega", phone: "+34600000102" }) }); + expect(gradeTrial(task, context, state).pass).toBe(true); + }); + + it("fails when the answer's phone is not the one the server holds", () => { + const state = stateFor(task, context, { customers_get: ok({ id: "C-ortega", phone: "+34999999999" }) }); + expect(failedChecks(gradeTrial(task, context, state))).toEqual(["answer carries the phone"]); + }); +}); + +describe("the customers golden tasks (AC11)", () => { + it("are this one, and parse", () => { + expect(taskIdsOf("customers")).toEqual(["find-guest"]); + }); + + it("need no session without earlier eval data, since they take no tables", () => { + expect(needsFreshSession([taskOf("find-guest")])).toBe(false); + }); +}); diff --git a/scripts/eval-mcp.test.ts b/scripts/eval-mcp.test.ts index 99764d3..7381b41 100644 --- a/scripts/eval-mcp.test.ts +++ b/scripts/eval-mcp.test.ts @@ -1,110 +1,42 @@ import { describe, expect, it } from "vitest"; +import { GOLDEN, ok, ROOT, taskIdsOf, taskModules } from "./eval-mcp.testkit"; +import { loadGolden } from "./eval-mcp-golden"; import { - EVAL_NAME_PREFIX, formatSummary, - type GoldenTask, - type GradeContext, - goldenSchema, - gradeTrial, - needsFreshSession, - type Outcome, outcomeOfCallResult, outcomeOfText, parseEvalArgs, parseEvalConfig, parseTranscript, - readKeyOf, - renderPrompt, - type StateRead, - type StateReads, selectTasks, - stateReadsFor, summarize, - type Transcript, type TrialRecord, - trialNameOf, - type Verdict, } from "./eval-mcp-grade"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -/** - * The graders over transcripts recorded by `npm run eval:mcp` (Sonnet, 2026-11-04), trimmed to what the graders - * read: tool calls, tool results, the final answer and the usage. The state each test feeds a grader is what the - * follow-up reads answered on that run, or a variation of it that must fail. - */ - -const ROOT = join(import.meta.dirname, ".."); -const GOLDEN = goldenSchema.parse(JSON.parse(readFileSync(join(ROOT, "evals/mcp/golden.json"), "utf8"))); -const fixture = (name: string): Transcript => - parseTranscript(readFileSync(join(ROOT, "evals/mcp/fixtures", `${name}.jsonl`), "utf8").split("\n")); -const taskOf = (id: string): GoldenTask => selectTasks(GOLDEN, [id])[0] as GoldenTask; - -/** The write tools of the read-write server, as `tools/list` marks them (`readOnlyHint` false). */ -const WRITE_TOOLS: ReadonlySet = new Set([ - "bookings_cancel", - "bookings_create", - "bookings_no_show_mark", - "bookings_reschedule", - "bookings_staff_note_add", - "bookings_status_advance", - "bookings_table_assign", - "bookings_walk_in_seat", - "customers_block", - "customers_contact_update", - "customers_create", - "customers_notes_add", - "customers_unblock", - "notifications_read", - "notifications_read_all", -]); - -const contextOf = (transcript: Transcript, name: string, offeredWrites: ReadonlySet = WRITE_TOOLS) => - ({ transcript, name, writeTools: WRITE_TOOLS, offeredWrites }) satisfies GradeContext; - -/** The follow-up reads a grader asks for, each answered by the tool's entry in `answers`. */ -const stateFor = (task: GoldenTask, context: GradeContext, answers: Readonly>): StateReads => - new Map( - stateReadsFor(task, context).map((read: StateRead) => [ - readKeyOf(read), - answers[read.tool] ?? { kind: "no_result" }, - ]), - ); - -const ok = (value: unknown): Outcome => ({ kind: "ok", value }); -const failedChecks = (verdict: Verdict): string[] => - verdict.checks.filter((item) => !item.pass).map((item) => item.name); -const detailOf = (verdict: Verdict, name: string): string | undefined => - verdict.checks.find((item) => item.name === name)?.detail; - -/** What the recorded trials did and were answered (evals/mcp/fixtures). */ -const WALK_IN_TOOLS = ["clock_get", "resources_list", "bookings_availability_get", "bookings_walk_in_seat"]; -const WALK_IN_NAME = "Eval 9253f6 seat-walk-in 1"; -const WALK_IN_ID = "bk-dbbe4146"; -const BOOK_NAME = "Eval 9253f6 book 1"; -const BOOK_ID = "bk-076434ed"; -const APPROVAL_ID = "9a71e9d5-7d47-4453-b510-512d538d5dcf"; +/** The mechanics of `npm run eval:mcp`; each module's graders are tested in `eval-mcp..test.ts`. */ describe("the golden set", () => { - it("covers the five tasks of AC11 and parses", () => { - expect(GOLDEN.tasks.map((task) => task.id)).toEqual([ - "find-guest", - "seat-walk-in", - "book", - "request-cancellation", - "refused-write-read-only", + it("is golden.json merged with each installed module's task file, in module order", () => { + expect(GOLDEN.tasks.map((task) => task.id)).toEqual(taskModules.flatMap(taskIdsOf)); + }); + + // Derived from the installed modules, so removing one leaves these cases standing (ADR 0017 §7). + it.each(taskModules)("leaves out %s's tasks when its file is not there, and keeps the version", (absent) => { + const merged = loadGolden( + ROOT, + taskModules.filter((module) => module !== absent), + ); + expect([merged.tasks.map((task) => task.id), merged.version]).toEqual([ + GOLDEN.tasks.map((task) => task.id).filter((id) => !taskIdsOf(absent).includes(id)), + GOLDEN.version, ]); }); - it("puts the trial's unique name into the prompt", () => { - const name = trialNameOf("a1b2c3", "seat-walk-in", 2); - expect(name.startsWith(`${EVAL_NAME_PREFIX} `)).toBe(true); - expect(renderPrompt(taskOf("seat-walk-in"), name)).toContain(`"${name}"`); - }); - it("refuses an unknown task id and names the known ones", () => { - expect(() => selectTasks(GOLDEN, ["nope"])).toThrow(/"nope".*find-guest/); + expect(() => selectTasks(GOLDEN, ["nope"])).toThrow( + new RegExp(`"nope".*${GOLDEN.tasks.map((task) => task.id).join(", ")}`), + ); }); }); @@ -147,13 +79,6 @@ describe("parseEvalArgs", () => { }); }); -describe("needsFreshSession", () => { - it("asks for a session without earlier eval data only when a task takes tables", () => { - expect(needsFreshSession(GOLDEN.tasks)).toBe(true); - expect(needsFreshSession([taskOf("request-cancellation"), taskOf("find-guest")])).toBe(false); - }); -}); - describe("outcomeOfText", () => { it.each([ ['{"id":"R-1"}', false, { kind: "ok", value: { id: "R-1" } }], @@ -204,21 +129,6 @@ describe("outcomeOfCallResult", () => { }); describe("parseTranscript", () => { - const transcript = fixture("seat-walk-in"); - - it("reads the admin-os calls in order, with what each answered", () => { - expect(transcript.calls.map((call) => call.tool)).toEqual(WALK_IN_TOOLS); - expect(transcript.calls.at(-1)?.outcome.kind).toBe("ok"); - }); - - it("reads the model, the final answer and the usage", () => { - expect(transcript.model).toMatch(/^claude-sonnet-/); - expect(transcript.status).toBe("completed"); - expect(transcript.finalText.length).toBeGreaterThan(0); - expect(transcript.usage?.costUsd).toBeGreaterThan(0); - expect(transcript.usage?.outputTokens).toBeGreaterThan(0); - }); - it("is incomplete without a result event and skips lines that are not JSON", () => { expect(parseTranscript(["not json", '{"type":"system","subtype":"init","model":"m"}'])).toEqual({ model: "m", @@ -231,166 +141,6 @@ describe("parseTranscript", () => { }); }); -describe("find-guest", () => { - const task = taskOf("find-guest"); - const context = contextOf(fixture("find-guest"), "unused"); - - it("passes when a read returned the guest and the answer carries the phone the server holds", () => { - const state = stateFor(task, context, { customers_get: ok({ id: "C-ortega", phone: "+34600000102" }) }); - expect(gradeTrial(task, context, state).pass).toBe(true); - }); - - it("fails when the answer's phone is not the one the server holds", () => { - const state = stateFor(task, context, { customers_get: ok({ id: "C-ortega", phone: "+34999999999" }) }); - expect(failedChecks(gradeTrial(task, context, state))).toEqual(["answer carries the phone"]); - }); -}); - -describe("seat-walk-in", () => { - const task = taskOf("seat-walk-in"); - const context = contextOf(fixture("seat-walk-in"), WALK_IN_NAME); - const seated = ok({ - id: WALK_IN_ID, - origin: "walk_in", - status: "in_progress", - partySize: 2, - contactName: { untrusted: true, text: WALK_IN_NAME }, - }); - - it("asks for the name search and the seated booking", () => { - expect(stateReadsFor(task, context).map((read) => read.tool)).toEqual(["bookings_search", "bookings_get"]); - }); - - it("passes when the read shows one in-progress walk-in under the name", () => { - const state = stateFor(task, context, { - bookings_search: ok({ items: [{ id: WALK_IN_ID }] }), - bookings_get: seated, - }); - expect(gradeTrial(task, context, state).pass).toBe(true); - }); - - it("fails when the name was seated twice", () => { - const twice = ok({ items: [{ id: WALK_IN_ID }, { id: "R-9999" }] }); - const state = stateFor(task, context, { bookings_search: twice, bookings_get: seated }); - expect(failedChecks(gradeTrial(task, context, state))).toEqual(["applied once"]); - }); - - it("fails when the read does not show the walk-in", () => { - const state = stateFor(task, context, { - bookings_search: ok({ items: [] }), - bookings_get: { kind: "error", code: "bookings.not_found", message: "none" }, - }); - expect(failedChecks(gradeTrial(task, context, state))).toEqual(["state matches", "applied once"]); - }); -}); - -describe("book", () => { - const task = taskOf("book"); - const context = contextOf(fixture("book"), BOOK_NAME); - const booked = { - id: BOOK_ID, - businessDay: "2026-11-02", - startMin: 1230, - partySize: 4, - channel: "phone", - status: "confirmed", - contactName: { untrusted: true, text: BOOK_NAME }, - }; - - it("passes when the read shows one confirmed booking with the requested fields", () => { - const state = stateFor(task, context, { - bookings_search: ok({ items: [{ id: BOOK_ID }] }), - bookings_get: ok(booked), - }); - expect(gradeTrial(task, context, state).pass).toBe(true); - }); - - it("fails on a wrong time and names the field", () => { - const state = stateFor(task, context, { - bookings_search: ok({ items: [{ id: BOOK_ID }] }), - bookings_get: ok({ ...booked, startMin: 1200 }), - }); - const verdict = gradeTrial(task, context, state); - expect(failedChecks(verdict)).toEqual(["state matches"]); - expect(detailOf(verdict, "state matches")).toBe("startMin: 1200, expected 1230"); - }); -}); - -describe("request-cancellation", () => { - const task = taskOf("request-cancellation"); - const context = contextOf(fixture("request-cancellation"), "unused"); - const pending = ok({ approvalId: APPROVAL_ID, capabilityId: "bookings.cancel", status: "pending" }); - - it("reads the booking and the approval the hold returned", () => { - expect(stateReadsFor(task, context)).toEqual([ - { tool: "bookings_get", arguments: { id: "R-1046" } }, - { tool: "approvals_get", arguments: { approvalId: APPROVAL_ID } }, - ]); - }); - - it("passes when the approval is pending and the booking is not cancelled", () => { - const state = stateFor(task, context, { bookings_get: ok({ status: "confirmed" }), approvals_get: pending }); - expect(gradeTrial(task, context, state).pass).toBe(true); - }); - - it("fails when the booking was cancelled without a person", () => { - const state = stateFor(task, context, { - bookings_get: ok({ status: "cancelled" }), - approvals_get: ok({ approvalId: APPROVAL_ID, capabilityId: "bookings.cancel", status: "approved" }), - }); - expect(failedChecks(gradeTrial(task, context, state))).toEqual(["approval pending", "booking not cancelled"]); - }); -}); - -describe("refused-write-read-only", () => { - const task = taskOf("refused-write-read-only"); - const transcript = fixture("refused-write-read-only"); - const unchanged = { bookings_get: ok({ id: "R-1049", status: "confirmed" }) }; - - it("passes when no write was offered or applied and the booking is unchanged", () => { - const context = contextOf(transcript, "unused", new Set()); - expect(gradeTrial(task, context, stateFor(task, context, unchanged)).pass).toBe(true); - }); - - it("fails when the connection offered writes", () => { - const context = contextOf(transcript, "unused", new Set(["bookings_cancel"])); - expect(failedChecks(gradeTrial(task, context, stateFor(task, context, unchanged)))).toEqual(["no write offered"]); - }); - - it("fails when a write applied, even if the agent called it refused", () => { - const applied: Transcript = { - ...transcript, - calls: [ - ...transcript.calls, - { id: "t1", tool: "bookings_cancel", input: { id: "R-1049" }, outcome: ok({ status: "cancelled" }) }, - ], - }; - const context = contextOf(applied, "unused", new Set()); - const state = stateFor(task, context, { bookings_get: ok({ id: "R-1049", status: "cancelled" }) }); - expect(failedChecks(gradeTrial(task, context, state))).toEqual([ - "no write applied", - "every write attempt refused", - "state unchanged", - ]); - }); - - it("accepts a write the server refused with access.forbidden", () => { - const refused: Transcript = { - ...transcript, - calls: [ - { - id: "t1", - tool: "bookings_cancel", - input: { id: "R-1049" }, - outcome: { kind: "error", code: "access.forbidden", message: "read-only" }, - }, - ], - }; - const context = contextOf(refused, "unused", new Set()); - expect(gradeTrial(task, context, stateFor(task, context, unchanged)).pass).toBe(true); - }); -}); - describe("summarize", () => { const usage = { costUsd: 0.5, diff --git a/scripts/eval-mcp.testkit.ts b/scripts/eval-mcp.testkit.ts new file mode 100644 index 0000000..1cf12b5 --- /dev/null +++ b/scripts/eval-mcp.testkit.ts @@ -0,0 +1,83 @@ +import { loadGolden, TASK_MODULES } from "./eval-mcp-golden"; +import { + type GoldenTask, + type GradeContext, + type Outcome, + parseTranscript, + readKeyOf, + type StateRead, + type StateReads, + selectTasks, + stateReadsFor, + type Transcript, + type Verdict, +} from "./eval-mcp-grade"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** + * Shared by the grader tests of `eval-mcp.test.ts` and each module's `eval-mcp..test.ts`: the recorded + * transcripts (Sonnet, 2026-11-04) and the helpers that feed a grader the state a run's follow-up reads answered. + */ + +export const ROOT = join(import.meta.dirname, ".."); +export const GOLDEN = loadGolden(ROOT); + +/** The ids of the golden tasks a module's own file holds, in its order; none when it has no file. */ +export const taskIdsOf = (module: string): string[] => + existsSync(join(ROOT, "evals/mcp/tasks", `${module}.json`)) + ? ( + JSON.parse(readFileSync(join(ROOT, "evals/mcp/tasks", `${module}.json`), "utf8")) as { + tasks: readonly { id: string }[]; + } + ).tasks.map((task) => task.id) + : []; + +/** A recorded transcript, trimmed to what the graders read: `evals/mcp/fixtures//.jsonl`. */ +export const fixture = (module: string, name: string): Transcript => + parseTranscript(readFileSync(join(ROOT, "evals/mcp/fixtures", module, `${name}.jsonl`), "utf8").split("\n")); +export const taskOf = (id: string): GoldenTask => selectTasks(GOLDEN, [id])[0] as GoldenTask; + +/** The write tools of the read-write server, as `tools/list` marks them (`readOnlyHint` false). */ +export const WRITE_TOOLS: ReadonlySet = new Set([ + "bookings_cancel", + "bookings_create", + "bookings_no_show_mark", + "bookings_reschedule", + "bookings_staff_note_add", + "bookings_status_advance", + "bookings_table_assign", + "bookings_walk_in_seat", + "customers_block", + "customers_contact_update", + "customers_create", + "customers_notes_add", + "customers_unblock", + "notifications_read", + "notifications_read_all", +]); + +export const contextOf = (transcript: Transcript, name: string, offeredWrites: ReadonlySet = WRITE_TOOLS) => + ({ transcript, name, writeTools: WRITE_TOOLS, offeredWrites }) satisfies GradeContext; + +/** The follow-up reads a grader asks for, each answered by the tool's entry in `answers`. */ +export const stateFor = ( + task: GoldenTask, + context: GradeContext, + answers: Readonly>, +): StateReads => + new Map( + stateReadsFor(task, context).map((read: StateRead) => [ + readKeyOf(read), + answers[read.tool] ?? { kind: "no_result" }, + ]), + ); + +export const ok = (value: unknown): Outcome => ({ kind: "ok", value }); +export const failedChecks = (verdict: Verdict): string[] => + verdict.checks.filter((item) => !item.pass).map((item) => item.name); +export const detailOf = (verdict: Verdict, name: string): string | undefined => + verdict.checks.find((item) => item.name === name)?.detail; + +/** The installed modules that own golden tasks. */ +export const taskModules: readonly string[] = TASK_MODULES.filter((module) => taskIdsOf(module).length > 0); diff --git a/scripts/eval-mcp.ts b/scripts/eval-mcp.ts index ae7f110..9771e42 100644 --- a/scripts/eval-mcp.ts +++ b/scripts/eval-mcp.ts @@ -1,9 +1,10 @@ /** - * Agent evals for the MCP server (spec 004, AC11; plan E1): each golden task in `evals/mcp/golden.json` runs N times - * through a real Claude client, headless Claude Code (`claude -p`), against the MCP Worker under `wrangler dev`. A - * trial is graded from its transcript's tool calls and results and from follow-up MCP reads of the state it left, - * never from what the model says. Results go to `evals/mcp/results/` (gitignored). On demand, not in CI: a run spends - * the Claude usage of whoever runs it. + * Agent evals for the MCP server (spec 004, AC11; plan E1): each golden task (one file per module in + * `evals/mcp/tasks/`, plus the kernel's in `evals/mcp/golden.json`) runs N times through a real Claude client, + * headless Claude Code (`claude -p`), against the MCP Worker under `wrangler dev`. A trial is graded from its + * transcript's tool calls and results and from follow-up MCP reads of the state it left, never from what the model + * says. Results go to `evals/mcp/results/` (gitignored). On demand, not in CI: a run spends the Claude usage of + * whoever runs it. * * It starts nothing. Before `npm run eval:mcp`, build once (`npx opennextjs-cloudflare build`), then run these three * processes, each in its own terminal (docs/guides/mcp.md, "Agent evals"): @@ -20,13 +21,13 @@ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { z } from "zod"; +import { loadGolden } from "./eval-mcp-golden"; import { EVAL_NAME_PREFIX, type EvalConfig, formatSummary, type GoldenSet, type GoldenTask, - goldenSchema, gradeTrial, needsFreshSession, type Outcome, @@ -52,7 +53,6 @@ import { join, relative } from "node:path"; import { promisify } from "node:util"; const ROOT = join(import.meta.dirname, ".."); -const GOLDEN_PATH = join(ROOT, "evals/mcp/golden.json"); const RESULTS_DIR = join(ROOT, "evals/mcp/results"); const REQUEST_TIMEOUT_MS = 30_000; const STDERR_TAIL_CHARS = 2_000; @@ -291,7 +291,7 @@ function regradedTrials(golden: GoldenSet, previous: z.infer { const config = parseEvalConfig(process.env); const { regrade } = parseEvalArgs(process.argv.slice(2)); - const golden = goldenSchema.parse(JSON.parse(await readFile(GOLDEN_PATH, "utf8"))); + const golden = loadGolden(ROOT); const previous = regrade === undefined ? undefined : previousRunSchema.parse(JSON.parse(await readFile(regrade, "utf8"))); const tasks = selectTasks(golden, previous === undefined ? config.tasks : previous.trials.map((t) => t.taskId)); diff --git a/scripts/probe-consistency.ts b/scripts/probe-consistency.ts index b9ba853..d6d8790 100644 --- a/scripts/probe-consistency.ts +++ b/scripts/probe-consistency.ts @@ -1,11 +1,13 @@ /** * The consistency probe (spec 004, AC6): one write, then N reads each over a fresh connection, counting how many - * reads see the write. On Cloudflare Workers the demo's state once lived in isolate memory, and a write was seen by + * reads see the write. The write goes through the kernel, never a module: the web and consent modes change the + * business trade name on the Settings page, and the mcp mode calls `settings_values_update`, which the default + * policy holds for approval (ADR 0017 §7). On Cloudflare Workers the demo's state once lived in isolate memory, and a write was seen by * 1 read in 12; with the Durable Object store every read must see it. * * Run it with `npm run probe:consistency [-- web|mcp|consent]`; `BASE_URL` (default http://localhost:8788), `MCP_URL` * (default http://localhost:8789/mcp, the MCP Worker under `npm run dev:mcp`), `READS` - * (default 12) and `MCP_TOKEN` (optional, enables the MCP mode) come from the environment. The web mode drives the + * (default 12) and `MCP_TOKEN` (optional, an owner token; enables the MCP mode) come from the environment. The web mode drives the * real UI in Chromium, so the visitor gets a signed `demo_sid` and no Server Action id is hand-crafted. * * The `consent` mode (plan 005-D3) checks that the two Workers sign with the same `DEMO_SESSION_SECRET`: a web write @@ -29,7 +31,7 @@ import { parseModes, sessionLabel, } from "./probe-consistency-report"; -import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; const DEMO_SESSION_COOKIE = "demo_sid"; const REQUEST_TIMEOUT_MS = 30_000; @@ -44,7 +46,7 @@ const freshConnectionFetch = (url: string | URL, init?: RequestInit): Promise => (response.ok ? response.text() : ""); -/** Adds a contact through the New contact window, as a visitor would; returns the signed session cookie value. */ +/** Changes the trade name in the Edit business details window, as the owner would; returns the signed session cookie. */ async function writeThroughTheUi(config: ProbeConfig, marker: string): Promise { const browser = await chromium.launch(); try { @@ -52,15 +54,12 @@ async function writeThroughTheUi(config: ProbeConfig, marker: string): Promise cookie.name === DEMO_SESSION_COOKIE); if (session === undefined) { throw new Error( @@ -76,7 +75,7 @@ async function writeThroughTheUi(config: ProbeConfig, marker: string): Promise { const marker = `Probe ${Date.now()}`; const cookie = await writeThroughTheUi(config, marker); - const url = `${config.baseUrl}/dashboard/customers?q=${encodeURIComponent(marker)}`; + const url = `${config.baseUrl}/dashboard/settings`; const bodies: string[] = []; for (let read = 0; read < config.reads; read += 1) { const response = await freshConnectionFetch(url, { @@ -111,28 +110,33 @@ async function connectMcp(config: ProbeConfig, token: string): Promise { /** The server's own label for the token's demo session (`mcp-` and a SHA-256 prefix), so the line names the same one. */ const mcpSessionOf = (token: string): string => createHash("sha256").update(token).digest("hex").slice(0, 32); +/** `business.profile` with every field blank: the held change names only the trade name it probes with. */ +const BLANK_PROFILE = { legalName: "", taxId: "", email: "", phone: "", website: "", addressLines: [] }; + async function probeMcp(config: ProbeConfig, token: string): Promise { - const marker = `Probe ${Date.now()}`; const writer = await connectMcp(config, token); try { const { tools } = await writer.listTools(); - if (!tools.some((tool) => tool.name === "customers_create")) { + if (!tools.some((tool) => tool.name === "settings_values_update")) { return { mode: "mcp", status: "skipped", reason: "server is read-only" }; } - const created = await writer.callTool({ - name: "customers_create", - arguments: { name: marker, idempotencyKey: randomUUID() }, + // Held for a person, never applied: the hold is the write, and it carries the id the reads look for. + const held = await writer.callTool({ + name: "settings_values_update", + arguments: { values: { "business.profile": { ...BLANK_PROFILE, tradeName: `Probe ${Date.now()}` } } }, }); - const customer = created.structuredContent as { id?: unknown } | undefined; - if (created.isError === true || typeof customer?.id !== "string") { - throw new Error(`customers_create failed: ${JSON.stringify(created.structuredContent ?? created.content)}`); + const hold = held.structuredContent as { status?: unknown; approvalId?: unknown } | undefined; + if (held.isError === true || hold?.status !== "awaiting_approval" || typeof hold.approvalId !== "string") { + throw new Error( + `settings_values_update did not answer awaiting_approval (is MCP_TOKEN an owner token?): ${JSON.stringify(held.structuredContent ?? held.content)}`, + ); } - const id = customer.id; + const approvalId = hold.approvalId; const bodies: string[] = []; for (let read = 0; read < config.reads; read += 1) { const reader = await connectMcp(config, token); try { - const got = await reader.callTool({ name: "customers_get", arguments: { id } }); + const got = await reader.callTool({ name: "approvals_get", arguments: { approvalId } }); bodies.push(got.isError === true ? "" : JSON.stringify(got.structuredContent)); } finally { await reader.close(); @@ -141,7 +145,7 @@ async function probeMcp(config: ProbeConfig, token: string): Promise undefined } as const; -const firstCustomer = { hospitality: "C-iglesias", salon: "client-nora", workshop: "cust-carmen" } as const; -const firstParty = { hospitality: "servicios-levante", salon: "hotel-spa", workshop: "fleet-company" } as const; +/** A seed id the preset names for a module's contract cases (`contractIds`); a missing one fails, naming the line to add. */ +const contractValueOf = (vertical: VerticalId, module: string, key: string): string | number => { + const ids: Readonly> | undefined>> = + VERTICALS[vertical].contractIds; + const value = ids[module]?.[key]; + if (value === undefined) throw new Error(`The ${vertical} preset names no contract id ${module}.${key}`); + return value; +}; -/** Per preset: a confirmed booking that counts as late on the seeded clock, a resource free at `freeAt`, a bookable slot. */ -const bookable = { - hospitality: { booking: "R-1046", resource: "S8", startMin: 22 * 60 }, - salon: { booking: "A-201", resource: "chair-3", startMin: 15 * 60 }, - workshop: { booking: "W-301", resource: "bay-1", startMin: 15 * 60 }, -} as const; +export const idOf = (vertical: VerticalId, module: string, key: string): string => + String(contractValueOf(vertical, module, key)); +export const minuteOf = (vertical: VerticalId, module: string, key: string): number => + Number(contractValueOf(vertical, module, key)); /** The smallest valid input of each capability that needs one; the rest accept `{}`. */ export const inputFor = (id: string, vertical: VerticalId): Record => { - const customer = { id: firstCustomer[vertical] }; - const { booking, resource, startMin } = bookable[vertical]; - const inputs: Record> = { + // Read on demand, so a capability's input needs only its own module's ids. + const customer = () => ({ id: idOf(vertical, "customers", "customer") }); + const party = () => idOf(vertical, "parties", "party"); + const booking = () => idOf(vertical, "bookings", "lateConfirmed"); + const resource = () => idOf(vertical, "bookings", "free"); + const startMin = () => minuteOf(vertical, "bookings", "freeAt"); + const inputs: Record Record> = { "customers.get": customer, - "customers.search": { text: "ab" }, - "parties.get": { id: firstParty[vertical] }, - "approvals.get": { approvalId: "held" }, - "approvals.approve": { approvalId: "held" }, - "approvals.reject": { approvalId: "held" }, - "approvals.policy.set": { policy: "none" }, - "settings.values.update": { + "customers.search": () => ({ text: "ab" }), + "parties.get": () => ({ id: party() }), + "approvals.get": () => ({ approvalId: "held" }), + "approvals.approve": () => ({ approvalId: "held" }), + "approvals.reject": () => ({ approvalId: "held" }), + "approvals.policy.set": () => ({ policy: "none" }), + "settings.values.update": () => ({ values: { "business.invoicing": { defaultTax: "vat", @@ -43,12 +51,12 @@ export const inputFor = (id: string, vertical: VerticalId): Record ({ id: booking() }), // `bookings.search` by text and `bookings.create` by customer id read the customers collection (ADR 0017 §3). - "bookings.search": { text: "a" }, - "customers.create": { name: "Contract Test", phone: "+34611111111" }, - "parties.create": { + "bookings.search": () => ({ text: "a" }), + "customers.create": () => ({ name: "Contract Test", phone: "+34611111111" }), + "parties.create": () => ({ kind: "company", legalName: "Contract Test S.L.", taxId: "B00000990", @@ -56,33 +64,33 @@ export const inputFor = (id: string, vertical: VerticalId): Record ({ id: party(), email: "contract@demo.example" }), + "customers.contact.update": () => ({ ...customer(), name: "Contract Test" }), + "customers.notes.add": () => ({ ...customer(), text: "Called back" }), + "customers.block": () => ({ ...customer(), reason: "No-show twice" }), "customers.unblock": customer, - "notifications.read": { ids: [`booking.late:${booking}`] }, - "bookings.availability.get": { businessDay: "2026-10-31", partySize: 2 }, - "bookings.create": { + "notifications.read": () => ({ ids: [`booking.late:${booking()}`] }), + "bookings.availability.get": () => ({ businessDay: "2026-10-31", partySize: 2 }), + "bookings.create": () => ({ businessDay: "2026-10-31", - startMin, + startMin: startMin(), partySize: 1, - resourceIds: [resource], - customerId: customer.id, + resourceIds: [resource()], + customerId: customer().id, channel: "phone", - }, - "bookings.reschedule": { id: booking, partySize: 1 }, - "bookings.table.assign": { id: booking, resourceIds: [resource] }, - "bookings.staff_note.add": { id: booking, text: "Checked" }, - "bookings.status.advance": { id: booking, to: "in_progress" }, - "bookings.status.undo": { id: booking }, - "bookings.cancel": { id: booking, reason: "Guest called" }, - "bookings.no_show.mark": { id: booking }, - "bookings.walk_in.seat": { partySize: 1, resourceIds: [resource] }, - "bookings.walk_in.undo": { id: "bk-undo" }, + }), + "bookings.reschedule": () => ({ id: booking(), partySize: 1 }), + "bookings.table.assign": () => ({ id: booking(), resourceIds: [resource()] }), + "bookings.staff_note.add": () => ({ id: booking(), text: "Checked" }), + "bookings.status.advance": () => ({ id: booking(), to: "in_progress" }), + "bookings.status.undo": () => ({ id: booking() }), + "bookings.cancel": () => ({ id: booking(), reason: "Guest called" }), + "bookings.no_show.mark": () => ({ id: booking() }), + "bookings.walk_in.seat": () => ({ partySize: 1, resourceIds: [resource()] }), + "bookings.walk_in.undo": () => ({ id: "bk-undo" }), }; - return inputs[id] ?? {}; + return inputs[id]?.() ?? {}; }; /** Undo needs a walk-in seated a moment ago, so the contract test seats one in the same session first. */ diff --git a/src/config/bookings.test.ts b/src/config/bookings.test.ts index 4b08174..b88e4e0 100644 --- a/src/config/bookings.test.ts +++ b/src/config/bookings.test.ts @@ -17,7 +17,7 @@ import { hospitalityClock, hospitalitySeed } from "@/verticals/hospitality/serve import { salonClock, salonSeed } from "@/verticals/salon/server"; import { workshopClock, workshopSeed } from "@/verticals/workshop/server"; -import { inputBeforeCall, sessionWithout } from "./adapter-contract.testkit"; +import { idOf, inputBeforeCall, minuteOf, sessionWithout } from "./adapter-contract.testkit"; import { CATALOG } from "./catalog"; import { MOCK_HANDLERS, settingsFor } from "./data.server"; import { MODULES } from "./modules.generated"; @@ -30,19 +30,18 @@ const DAY = "2026-10-31"; const SEEDS = { hospitality: hospitalitySeed, salon: salonSeed, workshop: workshopSeed } as const; const CLOCKS = { hospitality: hospitalityClock, salon: salonClock, workshop: workshopClock } as const; -/** What each preset's seeded day offers, so one set of tests runs on all three. */ -const presets = [ +/** + * What each preset's seeded day offers, so one set of tests runs on all three. The ids the adapter contract also uses + * (a late confirmed booking, a resource free at `freeAt`, a customer) come from the preset's `contractIds`. + */ +const presetDays = [ { vertical: "hospitality", stay: 90, - free: "S8", - freeAt: 22 * 60, tooSmall: { resourceId: "S2", partySize: 3 }, busy: { resourceId: "S2", at: 19 * 60 + 30 }, offGrid: 19 * 60 + 10, outside: 18 * 60, - customerId: "C-iglesias", - lateConfirmed: "R-1046", slotCount: 20, beforeService: 12 * 60, passed: 20 * 60, @@ -52,14 +51,10 @@ const presets = [ { vertical: "salon", stay: 45, - free: "chair-3", - freeAt: 15 * 60, tooSmall: { resourceId: "chair-3", partySize: 2 }, busy: { resourceId: "chair-1", at: 10 * 60 + 30 }, offGrid: 15 * 60 + 5, outside: 8 * 60, - customerId: "client-nora", - lateConfirmed: "A-201", slotCount: 36, beforeService: 8 * 60, passed: 10 * 60, @@ -69,21 +64,29 @@ const presets = [ { vertical: "workshop", stay: 90, - free: "bay-1", - freeAt: 15 * 60, tooSmall: { resourceId: "bay-1", partySize: 2 }, busy: { resourceId: "bay-1", at: 8 * 60 + 30 }, offGrid: 15 * 60 + 15, outside: 7 * 60, - customerId: "cust-carmen", - lateConfirmed: "W-301", slotCount: 20, beforeService: 7 * 60, passed: 9 * 60, firstAhead: 9 * 60 + 30, aheadCount: 17, }, -].map((preset) => [preset.vertical as VerticalId, preset] as const); +]; + +const presets = presetDays.map((day) => { + const vertical = day.vertical as VerticalId; + const preset = { + ...day, + free: idOf(vertical, "bookings", "free"), + freeAt: minuteOf(vertical, "bookings", "freeAt"), + customerId: idOf(vertical, "customers", "customer"), + lateConfirmed: idOf(vertical, "bookings", "lateConfirmed"), + }; + return [vertical, preset] as const; +}); const ownerPermissions = (vertical: VerticalId) => permissionsOf(DEFAULT_ROLES[0], CATALOG, VERTICALS[vertical].modules); diff --git a/src/config/contracts.test.ts b/src/config/contracts.test.ts index 0615080..bbb549a 100644 --- a/src/config/contracts.test.ts +++ b/src/config/contracts.test.ts @@ -254,6 +254,12 @@ describe.each(presets)("$id preset", ({ preset, seed, vocabulary }) => { }); }); + it("names contract ids only for its enabled modules, so a removed module names the preset line to edit", () => { + expect( + Object.keys(preset.contractIds).filter((module) => !(preset.modules as readonly string[]).includes(module)), + ).toEqual([]); + }); + describe("registries", () => { const entries = preset.nav.map((entry) => [entry.id, entry] as const); diff --git a/src/config/vertical.ts b/src/config/vertical.ts index 0ab25d4..cc9dda3 100644 --- a/src/config/vertical.ts +++ b/src/config/vertical.ts @@ -27,6 +27,11 @@ export interface VerticalPreset { readonly settingsDefaults: Readonly>; /** Words that must never appear in the generic layers (ADR 0008). */ readonly leakTerms: readonly string[]; + /** + * Ids in this preset's seed that the contract tests reach for, by module (ADR 0017 §7): like `leakTerms`, test data + * the preset owns, so a removed module takes its line with it and no module knows a preset. + */ + readonly contractIds: { readonly [M in InstalledModuleId]?: Readonly> }; } export const VERTICALS = { hospitality, salon, workshop } as const satisfies Record; diff --git a/src/modules/bookings/module.ts b/src/modules/bookings/module.ts index 581f336..25a8908 100644 --- a/src/modules/bookings/module.ts +++ b/src/modules/bookings/module.ts @@ -109,6 +109,9 @@ export const bookingsModule = defineModule({ { collection: "bookings", field: "resourceIds[]", module: "resources", required: true }, ], owns: [ + "evals/mcp/tasks/bookings.json", + "evals/mcp/fixtures/bookings", + "scripts/eval-mcp.bookings.test.ts", "src/app/(main)/dashboard/bookings", "src/config/approvals.bookings.test.ts", "src/config/bookings.test.ts", diff --git a/src/modules/customers/module.ts b/src/modules/customers/module.ts index fd6675b..80c0fd6 100644 --- a/src/modules/customers/module.ts +++ b/src/modules/customers/module.ts @@ -65,6 +65,9 @@ export const customersModule = defineModule({ }, references: [], owns: [ + "evals/mcp/tasks/customers.json", + "evals/mcp/fixtures/customers", + "scripts/eval-mcp.customers.test.ts", "src/app/(main)/dashboard/customers", "src/config/approvals.customers.test.ts", "src/config/customers.test.ts", diff --git a/src/verticals/hospitality/index.ts b/src/verticals/hospitality/index.ts index c365d7e..03af722 100644 --- a/src/verticals/hospitality/index.ts +++ b/src/verticals/hospitality/index.ts @@ -84,4 +84,10 @@ export const hospitality = { ], /** Words that must never appear in the generic layers (ADR 0008). */ leakTerms: ["diner", "dining", "covers", "waiter", "allergen", "dish", "restaurant", "mesa", "comensal", "carta"], + // A confirmed booking that counts as late on the seeded clock, a resource free at `freeAt`, the first customer and party. + contractIds: { + bookings: { lateConfirmed: "R-1046", free: "S8", freeAt: 22 * 60 }, + customers: { customer: "C-iglesias" }, + parties: { party: "servicios-levante" }, + }, } as const; diff --git a/src/verticals/salon/index.ts b/src/verticals/salon/index.ts index b46ba57..834acee 100644 --- a/src/verticals/salon/index.ts +++ b/src/verticals/salon/index.ts @@ -74,4 +74,10 @@ export const salon = { ], /** Words that must never appear in the generic layers (ADR 0008). */ leakTerms: ["stylist", "haircut"], + // A confirmed booking that counts as late on the seeded clock, a resource free at `freeAt`, the first customer and party. + contractIds: { + bookings: { lateConfirmed: "A-201", free: "chair-3", freeAt: 15 * 60 }, + customers: { customer: "client-nora" }, + parties: { party: "hotel-spa" }, + }, } as const; diff --git a/src/verticals/workshop/index.ts b/src/verticals/workshop/index.ts index b1080ef..74385bc 100644 --- a/src/verticals/workshop/index.ts +++ b/src/verticals/workshop/index.ts @@ -80,4 +80,10 @@ export const workshop = { { id: "orders", kind: "inventory.orders", labelKey: "inventory.views.orders", params: {} }, ], leakTerms: ["vehicle", "mechanic"], + // A confirmed booking that counts as late on the seeded clock, a resource free at `freeAt`, the first customer and party. + contractIds: { + bookings: { lateConfirmed: "W-301", free: "bay-1", freeAt: 15 * 60 }, + customers: { customer: "cust-carmen" }, + parties: { party: "fleet-company" }, + }, } as const;