diff --git a/.changeset/35025-per-type-amounts.md b/.changeset/35025-per-type-amounts.md new file mode 100644 index 00000000000..0d4a2c7cd95 --- /dev/null +++ b/.changeset/35025-per-type-amounts.md @@ -0,0 +1,21 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): travel_expense `file_and_submit_from_text` checks the per-type amounts, so per-night and per-day lines pass as well as quantity lines + +Clause-②: yes (widening) — the run record gains a top-level `card: { id, sha256 }` and its scorecard a `cardStamp`; a card's post-state gains the optional `sum` / `each` members and relation-path `where` keys; new exports `CardStamp`, `cardStampOf`, `cardStampText`, `relationObjects`, `DeclaredLookups`, and `LoadedScenario.fileSha256`; `summary` gains a card dimension. Every card and record that loaded, graded or summed before still does: records written before the stamp keep summing with each other +Metadata-protocol: none + +The `travel_expense` card's `file_and_submit_from_text` operation pinned the claim's lines to one hotel line of quantity 2 at 430 and one meals line of quantity 3 at 115. Two hotel lines and three meals lines of quantity 1 file the same claim (total 1205), and they failed. The operation now checks the hotel total (860) and the meals total (345) over the lines of the new claim for trip TR-0121, and that no line of that claim is over standard. The claim-level checks (claimant, status `submitted`, `total_amount` 1205, audit actor) are unchanged. Rounds graded before and after this change are not comparable on this operation, and the card stamp below says which card a round graded. + +To express it, an `applied` outcome's state entry can now be an aggregate over every row its `where` matches: + +- `sum`: per field, the rows' total must equal the declared number (`state:LABEL.sum(amount)`). A row that reads no number fails it. +- `each`: per field, every row must hold the value (`state:LABEL.each(field)`). +- At least one row must match. No match fails `->rows`, never a sum of 0 or an empty "every row". +- An aggregate names its rows by `where`, never by `id`. An entry carries exactly one of `values`, `absent` or an aggregate. The loader checks each summed field against the seed and refuses one that holds a non-number. + +A `where` key can also be a relation path through `expect.lookups` (`claim.trip`), checked by the loader like any other relation path. The runner reads the objects the path hops to after the turn (`relationObjects`), so rows the write created are matched through their parent row. Existing cards are unchanged. + +**The card stamp.** Every run record now names the card file it graded, at its top level: `card: { id, sha256 }`, the sha256 of the card file's bytes as the runner loaded them. The loader hashes the bytes it parsed (`LoadedScenario.fileSha256`, new), and the runner stamps from that, never a later read: a card edited, moved or deleted while its run goes on keeps its load-time hash, and its record is still written. The scorecard carries it (`cardStamp`) and prints it under the packages line, for example `card: travel_expense (sha256 3f2a9c01b7de)`. A replay stamps the card as it is now. `summary` treats the card as one more dimension a table's runs must share. Runs on two card hashes, or a stamped record next to one written before the stamp (`card: not recorded`), are refused with a line naming each hash and the records holding it, and the command exits 1. diff --git a/docs/qa/scenarios/README.md b/docs/qa/scenarios/README.md index c76ff95fbcb..ae07abe0c78 100644 --- a/docs/qa/scenarios/README.md +++ b/docs/qa/scenarios/README.md @@ -212,6 +212,12 @@ acts for (`actingAs`) and declares its `outcome`, so grading reads it with code - `{ kind: "applied", state: [...], auditActor? }` — each state entry names a row by `id` (seeded) or `where` (a row the write creates) and carries the `values` the data API must read back, or `absent: true`; `auditActor` is the persona the audit trail must name. + A `where` key may be a relation path through `expect.lookups` (`claim.trip`), so a row the + write created is found through the parent row it belongs to. An entry may instead be an + aggregate over every row its `where` matches (at least one; never by `id`): `sum` (per + field, the rows' total) and `each` (per field, the value every row holds). Use it where + the ask fixes a total but not how the agent splits it into rows: two hotel nights are one + line of quantity 2 or two lines of quantity 1, and `sum: {"amount": 860}` meets both. A value equal to the card's `asOf` is also met by the date the run happened on in a field the platform's clock stamps (a default or a flow writing a decision date, an order date), which cannot hold the card's fixed today. A field the agent's own write diff --git a/docs/qa/scenarios/travel_expense.json b/docs/qa/scenarios/travel_expense.json index b10943520ca..22cd2e9a14a 100644 --- a/docs/qa/scenarios/travel_expense.json +++ b/docs/qa/scenarios/travel_expense.json @@ -1022,13 +1022,18 @@ }, { "object": "claim_line", - "where": {"expense_type": "hotel", "quantity": 2, "unit_amount": 430}, - "values": {"amount": 860, "over_standard": false} + "where": {"claim.trip": "t121", "expense_type": "hotel"}, + "sum": {"amount": 860} }, { "object": "claim_line", - "where": {"expense_type": "meals", "quantity": 3, "unit_amount": 115}, - "values": {"amount": 345, "over_standard": false} + "where": {"claim.trip": "t121", "expense_type": "meals"}, + "sum": {"amount": 345} + }, + { + "object": "claim_line", + "where": {"claim.trip": "t121"}, + "each": {"over_standard": false} } ], "auditActor": "employee" diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 92586a20267..f5741086caa 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -78,7 +78,12 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a write goes through it is the run's to observe (ruling A on #31999 item 9, carried to the Build side). An `applied` write stays measured against the grant, whatever actions the build adds. - `scenario-operation-grade.ts` — an observed write against `applied` / `refused` / - `pending_confirmation`; a fact the observation does not carry fails. The operation the + `pending_confirmation`; a fact the observation does not carry fails. An `applied` state + entry may be an aggregate over every row its `where` matches: `sum` (`state:LABEL.sum(amount)`, + the rows' total; a row reading no number fails it) and `each` (`state:LABEL.each(field)`, every + row holds the value); no row matched fails `->rows`, never a vacuous pass. A `where` key may + be a relation path through `expect.lookups` (`claim.trip`): the runner reads the objects it + hops to after the turn (`relationObjects` in `runner/observe.ts`). The operation the card's `write_validation` guardrail names is graded in two halves: the agent half (its write was refused with the declared code, or it wrote nothing and its reply declines the write or asks for a correction) and the platform half, `platform:` checks (the runner's own write of @@ -256,9 +261,18 @@ files only: no model, no network, and no score of its own — every figure is th record that names no file (written before the key) is a row of its own, never summed with another; an ask mode on `this run’s from-scratch build` takes that run's scratch author. - **Never summed silently**: a table's runs must share the prompt choice, the package source, the ask repeats and the - driver (a replay is its own driver), and the ask skills (`--ask-skills`: names and sha256; a record without them - reads `none`). When they do not, that table is refused with a line naming each difference and + driver (a replay is its own driver), the ask skills (`--ask-skills`: names and sha256; a record without them + reads `none`), and the card file they graded (`card`, below; a record without it reads `card: not recorded`). + When they do not, that table is refused with a line naming each difference and the files on each side; the other tables print, and the command exits 1. Summarize each side apart. +- **The card stamp**: every record names the card file it graded at its top level, `card: { id, sha256 }` (the sha256 + of the card file's bytes as the runner loaded them: the bytes the loader parsed, `LoadedScenario.fileSha256`, never + a later read, so a card edited, moved or deleted during the run neither changes the stamp nor costs the record; + taken before the run moved the dates or prefixed the names), and the + scorecard prints it under the packages line: `card: travel_expense (sha256 3f2a9c01b7de)`. A change to a card's + questions, outcomes or seed moves the hash, so a round graded before it is told from one graded after it; a + replay grades on the card as it is now, and stamps that card. Two hashes in one table refuse it as above, the line + naming each hash and the records holding it. - **Older records**: a field a record predates (served models, ask cost and time, the package source) reads `not recorded`, never a zero. An effort set only through `CLAUDE_CODE_EFFORT_LEVEL` was never recorded, so runs that differ only in it share a row. diff --git a/packages/qa/scenarios/src/loader.ts b/packages/qa/scenarios/src/loader.ts index 586101bab3a..878670601c9 100644 --- a/packages/qa/scenarios/src/loader.ts +++ b/packages/qa/scenarios/src/loader.ts @@ -30,6 +30,7 @@ * directories it is handed. */ +import { createHash } from 'node:crypto'; import { readdirSync, readFileSync, realpathSync } from 'node:fs'; import { basename, join } from 'node:path'; @@ -62,6 +63,13 @@ export interface Refusal { export interface LoadedScenario { file: string; + /** + * The sha256 of the card file's bytes, the very bytes this load parsed: the + * runner stamps a run's record and scorecard with it (`CardStamp`), so a card + * edited, moved or deleted after loading never changes which card the + * stamp names, and never costs the record. + */ + fileSha256: string; card: ScenarioCard; /** Question id → its computed truth over every row. */ truths: Record; @@ -204,8 +212,11 @@ function loadOne(file: string, options: LoadOptions): { card?: LoadedScenario; r refusals.push({ file, path: formatPath(path), message }); let raw: unknown; + let fileSha256: string; try { - raw = JSON.parse(readFileSync(file, 'utf8')); + const bytes = readFileSync(file); + fileSha256 = createHash('sha256').update(bytes).digest('hex'); + raw = JSON.parse(bytes.toString('utf8')); } catch (e) { refuse([], `not valid JSON: ${(e as Error).message}`); return { refusals }; @@ -230,7 +241,7 @@ function loadOne(file: string, options: LoadOptions): { card?: LoadedScenario; r const computed = checkCard(card, basename(file, '.json'), options, refuse); if (refusals.length > 0) return { refusals, code: card.code }; const readable = Object.fromEntries(card.run.personas.map((p) => [p.id, rowsReadableBy(card, p)])); - return { card: { file, card, ...computed, readableRows: readable }, refusals, code: card.code }; + return { card: { file, fileSha256, card, ...computed, readableRows: readable }, refusals, code: card.code }; } type Refuse = (path: IssuePath, message: string) => void; @@ -929,9 +940,18 @@ function checkCard( if (st.id !== undefined && !(ids.get(st.object)?.has(st.id) ?? false)) { refuse([...sat, 'id'], `no seeded \`${st.object}\` row has id \`${st.id}\` (a created row is matched by \`where\`)`); } - for (const key of ['where', 'values'] as const) { + // A `where` key may be a relation path through declared lookups + // (`claim.trip`); the checked fields are the object's own. + for (const field of Object.keys(st.where ?? {})) checkPath(st.object, field, [...sat, 'where', field]); + for (const key of ['values', 'sum', 'each'] as const) { for (const field of Object.keys(st[key] ?? {})) checkField(st.object, field, [...sat, key, field]); } + // A summed field must hold numbers: one seed row of the object carrying a + // non-number there would make the sum unreadable in every run. + for (const field of Object.keys(st.sum ?? {})) { + const bad = (seed[st.object] ?? []).find((r) => r[field] !== undefined && r[field] !== null && typeof r[field] !== 'number'); + if (bad !== undefined) refuse([...sat, 'sum', field], `\`${st.object}.${field}\` holds ${JSON.stringify(bad[field])} on seed row \`${bad.id}\`, not a number to sum`); + } }); }); diff --git a/packages/qa/scenarios/src/runner/cli.ts b/packages/qa/scenarios/src/runner/cli.ts index d92f0d34ce9..66800aa1c57 100644 --- a/packages/qa/scenarios/src/runner/cli.ts +++ b/packages/qa/scenarios/src/runner/cli.ts @@ -111,7 +111,7 @@ import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { formatRefusal, libraryOf, loadScenarios, readCapabilityAreas } from '../loader.js'; +import { formatRefusal, libraryOf, loadScenarios, readCapabilityAreas, type LoadedScenario } from '../loader.js'; import { HttpApp } from './app.js'; import { askSkillsText } from './ask-skills.js'; import { ClaudeCodeDriver, RecordedDriver, RecordingDriver, type AgentDriver } from './driver.js'; @@ -123,7 +123,7 @@ import { installedSpecVersion, PACKAGES_MODES, prepareWorkspacePackages, settleW import { bootDev, os, readArtifact, readNamespace, scaffold } from './project.js'; import { PROMPT_LANGS, PROMPT_LENGTHS, promptChoiceText, promptLanguageRefusal, statedPromptChoice, type PromptChoice, type PromptLang, type PromptLength } from './prompts.js'; import { rebaseScenario } from './run-date.js'; -import { cardScorecard, renderScorecard, runRecord } from './scorecard.js'; +import { cardScorecard, renderScorecard, runRecord, type CardStamp } from './scorecard.js'; import { SUPPLIED_TEMPLATE_SOURCE, summaryMain, suppliedTemplateOf, type SuppliedTemplate } from './summary.js'; /** The `summary` command, re-exported so the published bin reaches it through this built entry (`src/bin.ts`). */ @@ -371,6 +371,16 @@ export function withSuppliedTemplate(record: Record, cardRun: C return supplied && installed ? { ...record, template: supplied } : record; } +/** + * The {@link CardStamp} of a loaded card: its id and the sha256 of the bytes + * the loader parsed (`LoadedScenario.fileSha256`), never a second read of the + * file. A card edited while its run went on is still stamped with the card + * that ran, and one moved or deleted meanwhile still gets its record written. + */ +export function loadedCardStamp(loaded: Pick): CardStamp { + return { id: loaded.card.id, sha256: loaded.fileSha256 }; +} + export async function main(argv: readonly string[]): Promise { // `summary` reads records back; it runs nothing (`summary.ts`). if (argv[0] === 'summary') return summaryMain(argv.slice(1)); @@ -481,10 +491,12 @@ export async function main(argv: readonly string[]): Promise { publishedVersions = new Set(); const cardRun = await runCard(scenario, driver, ops, { modes: args.modes, iterateRun: args.iterateRun, admin: ADMIN, ...(template ? { templateArtifact: template } : {}), ...(args.askRepeats !== undefined ? { askRepeats: args.askRepeats } : {}), ...(promptChoice ? { promptChoice } : {}) }); const packages: PackageSource = workspace ? workspace.source : { source: 'published', versions: [...publishedVersions].sort() }; - const record = withSuppliedTemplate(runRecord({ run: `${date}-scenario-${scenario.card.id}`, date, ...(framework ? { framework } : {}), packages, driver: info, runner: 'scenario-runner', evidenceDir: work }, cardRun), cardRun, supplied); + // The card file the run graded, as it was loaded (`CardStamp`): the record and the scorecard name its hash. + const card = loadedCardStamp(loaded); + const record = withSuppliedTemplate(runRecord({ run: `${date}-scenario-${scenario.card.id}`, date, ...(framework ? { framework } : {}), packages, driver: info, runner: 'scenario-runner', evidenceDir: work, card }, cardRun), cardRun, supplied); const file = join(outDir, `${date}-scenario-${scenario.card.id}.json`); writeFileSync(file, JSON.stringify(record, null, 2)); - console.log(renderScorecard(cardScorecard(cardRun, packages))); + console.log(renderScorecard(cardScorecard(cardRun, packages, card))); console.log(`record: ${file}`); if (driver instanceof RecordingDriver && args.record) driver.save(args.record); } diff --git a/packages/qa/scenarios/src/runner/observe.ts b/packages/qa/scenarios/src/runner/observe.ts index a497b48bf35..04dc8a3e979 100644 --- a/packages/qa/scenarios/src/runner/observe.ts +++ b/packages/qa/scenarios/src/runner/observe.ts @@ -441,8 +441,68 @@ export interface DeclaredToday { agentSet?: Readonly>; } -function matches(row: Row, where: Readonly>, object: string, today: DeclaredToday): boolean { +/** The card's declared lookups (`expect.lookups`), which a post-state's relation path hops through. */ +export type DeclaredLookups = ScenarioCard['expect']['lookups']; + +/** The lookup target of `object.field`, or `undefined` when the card declares no such lookup. */ +const lookupTarget = (lookups: DeclaredLookups, object: string, field: string): string | undefined => + (lookups ?? []).find((l) => l.object === object && l.field === field)?.to; + +/** + * The objects a post-state's `where` relation paths hop to (`claim.trip` on + * `claim_line` reaches `expense_claim`): the runner reads their rows after the + * turn beside the post-states' own objects, so a path resolves. + */ +export function relationObjects(op: CardOperation, lookups: DeclaredLookups): string[] { + if (op.outcome.kind !== 'applied') return []; + const out = new Set(); + for (const s of op.outcome.state) { + for (const key of Object.keys(s.where ?? {})) { + let cur: string | undefined = s.object; + for (const seg of key.split('.').slice(0, -1)) { + cur = cur === undefined ? undefined : lookupTarget(lookups, cur, seg); + if (cur !== undefined) out.add(cur); + } + } + } + return [...out]; +} + +/** + * A relation path read off `row` of `object`: each hop but the last follows + * the lookup's id to the target object's row as read after the turn. A hop the + * card declares no lookup for, an id that is no string, or an id naming no row + * read back reads `undefined`, which matches nothing but a declared `null`. + */ +function readPath(row: Row, object: string, path: string, rowsByObject: Readonly>, lookups: DeclaredLookups): unknown { + const segs = path.split('.'); + let cur = object; + let r: Row | undefined = row; + for (const seg of segs.slice(0, -1)) { + const to = lookupTarget(lookups, cur, seg); + const id: unknown = r[seg]; + r = to !== undefined && typeof id === 'string' ? (rowsByObject[to] ?? []).find((x) => String(x.id) === id) : undefined; + if (r === undefined) return undefined; + cur = to as string; + } + return r[segs[segs.length - 1]!]; +} + +function matches( + row: Row, + where: Readonly>, + object: string, + today: DeclaredToday, + rowsByObject: Readonly> = {}, + lookups: DeclaredLookups = [], +): boolean { return Object.entries(where).every(([k, v]) => { + // A relation path matches strictly: the card's-today reading below is + // about a field the platform stamped on this row, not on a parent. + if (k.includes('.')) { + const read = readPath(row, object, k, rowsByObject, lookups); + return v === null ? read === null || read === undefined : read === v; + } if (v === null) return row[k] === null || row[k] === undefined; if (row[k] === v) return true; if (today.agentSet === undefined || (today.agentSet[object] ?? []).includes(k)) return false; @@ -450,12 +510,21 @@ function matches(row: Row, where: Readonly>, object: stri }); } -/** Per declared post-state, the rows the data API returned for its `id` / `where`. */ -export function postStateRows(op: CardOperation, rowsByObject: Readonly>, today: DeclaredToday = {}): Row[][] | undefined { +/** + * Per declared post-state, the rows the data API returned for its `id` / + * `where`; a relation path in a `where` reads through `lookups` and the rows + * of `rowsByObject` ({@link relationObjects} names the objects it needs). + */ +export function postStateRows( + op: CardOperation, + rowsByObject: Readonly>, + today: DeclaredToday = {}, + lookups: DeclaredLookups = [], +): Row[][] | undefined { if (op.outcome.kind !== 'applied') return undefined; return op.outcome.state.map((s) => { const rows = rowsByObject[s.object] ?? []; - return s.id !== undefined ? rows.filter((r) => String(r.id) === s.id) : rows.filter((r) => matches(r, s.where ?? {}, s.object, today)); + return s.id !== undefined ? rows.filter((r) => String(r.id) === s.id) : rows.filter((r) => matches(r, s.where ?? {}, s.object, today, rowsByObject, lookups)); }); } @@ -475,8 +544,10 @@ export interface ObserveInput { /** The operation object's rows before and after the turn. */ before: readonly Row[]; after: readonly Row[]; - /** Every object a declared post-state names, read after the turn. */ + /** Every object a declared post-state names, and every object its relation paths reach ({@link relationObjects}), read after the turn. */ rowsByObject: Readonly>; + /** The card's declared lookups, for a post-state's relation path; absent ⇒ none resolves. */ + lookups?: DeclaredLookups; /** The persona the audit trail named for the touched row; `null` = named none; absent = not read. */ auditActor?: string | null; /** A probed operation's probe ({@link observeProbe}); absent = not run. */ @@ -503,7 +574,7 @@ export function observeOperation(input: ObserveInput): OperationObservation { withheld: withheldWrite(input.turn, input.op.object, writes), }; const agentSet = input.today?.agentSet ?? agentSetOf(input.op, input.turn); - const state = postStateRows(input.op, input.rowsByObject, { ...input.today, agentSet }); + const state = postStateRows(input.op, input.rowsByObject, { ...input.today, agentSet }, input.lookups); if (state) obs.state = state; if (input.today?.runDates !== undefined) obs.runDates = input.today.runDates; obs.agentSet = agentSet; @@ -551,9 +622,14 @@ export function observeProbe(call: ProbeCall, answer: ToolAnswer, before: readon } /** The id of the row an applied operation touched: its target, or the first `where` match. */ -export function touchedRowId(op: CardOperation, rowsByObject: Readonly>, today: DeclaredToday = {}): string | undefined { +export function touchedRowId( + op: CardOperation, + rowsByObject: Readonly>, + today: DeclaredToday = {}, + lookups: DeclaredLookups = [], +): string | undefined { if (op.target !== undefined) return op.target; - const rows = postStateRows(op, rowsByObject, today); + const rows = postStateRows(op, rowsByObject, today, lookups); const first = rows?.[0]?.[0]; return first ? String(first.id) : undefined; } diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 004bb0c7c0f..2232b84c082 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -82,7 +82,7 @@ import { import type { AppHarness, HttpAnswer, PersonaAccount } from './app.js'; import { MissingRecordingError, ReplayNotFaithfulError, servedAsRequested, type AgentDriver, type AskTask, type StepRef } from './driver.js'; import { citationLabels, namespaceOfArtifact, namespacedScenario, permissionSetName, templateHostName } from './namespace.js'; -import { agentSetOf, clockDates, countWrites, fingerprint, observedAnswer, observeOperation, observeProbe, probeCall, touchedRowId, writeCallsOn, type CardOperation, type Row } from './observe.js'; +import { agentSetOf, clockDates, countWrites, fingerprint, observedAnswer, observeOperation, observeProbe, probeCall, relationObjects, touchedRowId, writeCallsOn, type CardOperation, type Row } from './observe.js'; import type { CommandResult } from './project.js'; import { buildPrompt, @@ -1727,15 +1727,19 @@ export async function runHalf( const today = { ...(card.asOf !== undefined ? { asOf: card.asOf } : {}), runDates: clockDates(started, new Date()), agentSet: agentSetOf(op, turn) }; const rowsByObject: Record = { [op.object]: after }; if (op.outcome.kind === 'applied') { - for (const s of op.outcome.state) if (!rowsByObject[s.object]) rowsByObject[s.object] = (await app.listRows(s.object)).rows as Row[]; + // A post-state's relation path (`claim.trip`) reads the rows of the objects it hops to. + for (const o of [...op.outcome.state.map((s) => s.object), ...relationObjects(op, card.expect.lookups)]) { + if (!rowsByObject[o]) rowsByObject[o] = (await app.listRows(o)).rows as Row[]; + } } + const lookups = card.expect.lookups ?? []; let auditActor: string | null | undefined; if (op.outcome.kind === 'applied' && op.outcome.auditActor !== undefined) { - const id = touchedRowId(op, rowsByObject, today); + const id = touchedRowId(op, rowsByObject, today, lookups); auditActor = id === undefined ? null : personaOfUser(await app.auditActorUserId(op.object, id), accounts, app.adminUserId()); } const actionGates = op.outcome.kind === 'pending_confirmation' ? actionGatesOf(built, op) : undefined; - const observed = { op, turn, before, after, rowsByObject, today, ...(auditActor !== undefined ? { auditActor } : {}), ...(actionGates ? { actionGates } : {}) }; + const observed = { op, turn, before, after, rowsByObject, lookups, today, ...(auditActor !== undefined ? { auditActor } : {}), ...(actionGates ? { actionGates } : {}) }; // The runner's probe: it sends the declared write itself, as the same // persona through the same MCP door, after the turn. A probed operation // (the validation operation, or a permission overstep) is always diff --git a/packages/qa/scenarios/src/runner/scorecard.ts b/packages/qa/scenarios/src/runner/scorecard.ts index ecf64ae0cc1..a0163071533 100644 --- a/packages/qa/scenarios/src/runner/scorecard.ts +++ b/packages/qa/scenarios/src/runner/scorecard.ts @@ -103,6 +103,8 @@ * half with nothing measured is `not-run` in the record, never `fail`. */ +import { createHash } from 'node:crypto'; + import { askedFirst, confirmedByAgent, DATASET_GRADERS, type CheckResult, type DatasetGrader } from '../score/index.js'; import type { CardRun, ModeRun, RunHalf, BuildHalf, OperationResult, QuestionResult, RollupSourceCharge, TurnSummary } from './orchestrate.js'; import type { DriverInfo } from './driver.js'; @@ -279,8 +281,33 @@ export interface ModeScorecard { findings: string[]; } +/** + * The card a run graded, as the record stamps it at its top level (`card`) + * and the scorecard prints it: the card's id and the sha256 of the card file's + * bytes as the runner loaded them (the bytes the loader parsed, + * `LoadedScenario.fileSha256`, never a later read of the file), before the run moved its dates or prefixed + * its names. A change to a card's questions, outcomes or seed moves the hash, + * so a round graded before the change is told from one graded after it, on + * the scorecard and in `summary` (which never sums two hashes into one cell). + * A replay grades on the card as it is now, and stamps that card. + */ +export interface CardStamp { + id: string; + sha256: string; +} + +/** {@link CardStamp} of a card file's bytes. */ +export function cardStampOf(id: string, bytes: Buffer | string): CardStamp { + return { id, sha256: createHash('sha256').update(bytes).digest('hex') }; +} + +/** `card: travel_expense (sha256 3f2a9c01b7de)`: the scorecard's line, and `summary`'s card dimension. */ +export const cardStampText = (c: CardStamp): string => `card: ${c.id} (sha256 ${c.sha256.slice(0, 12)})`; + export interface CardScorecard { card: string; + /** The card file the run graded ({@link CardStamp}); absent on a record written before the runner stamped it. */ + cardStamp?: CardStamp; /** Where the run's `@objectstack/*` packages came from (`--packages`); the table's first line states it. */ packages?: PackageSource; counts: CardRun['counts']; @@ -702,7 +729,7 @@ export function modeScorecard(m: ModeRun): ModeScorecard { return out; } -export function cardScorecard(run: CardRun, packages?: PackageSource): CardScorecard { +export function cardScorecard(run: CardRun, packages?: PackageSource, cardStamp?: CardStamp): CardScorecard { const modes = run.modes.map((m) => modeScorecard(m)); const halves = modes.flatMap((m) => [m.first.confirmation, m.iterate?.confirmation]); const asked = halves.reduce((n, c) => n + (c?.askedFirst ?? 0), 0); @@ -713,6 +740,7 @@ export function cardScorecard(run: CardRun, packages?: PackageSource): CardScore : undefined; return { card: run.card, + ...(cardStamp ? { cardStamp } : {}), ...(packages ? { packages } : {}), counts: run.counts, authorCost: authorCost(run.modes.flatMap(authorTurnsOf)), @@ -842,6 +870,7 @@ export function renderScorecard(sc: CardScorecard): string { `### \`${sc.card}\` — ${sc.counts.questions} questions (${sc.counts.questionTurns} persona turns${sc.askRepeats !== undefined && sc.askRepeats > 1 ? `, each asked ${sc.askRepeats} times` : ''}), ${sc.counts.operations} operations, ${sc.counts.personas} personas`, '', ...(sc.packages ? [packagesLine(sc.packages), ''] : []), + ...(sc.cardStamp ? [cardStampText(sc.cardStamp), ''] : []), ...(sc.promptChoice ? [`prompts: ${promptChoiceText(sc.promptChoice)}`, ''] : []), `author cost: ${noAuthoring ? NO_AUTHORING_TURNS : authorCostText(sc.authorCost)}`, `author time: ${noAuthoring ? NO_AUTHORING_TURNS : authorTimeText(sc.authorTime)}`, @@ -905,10 +934,12 @@ export interface RunRecordMeta { driver: DriverInfo; runner: string; evidenceDir: string; + /** The card file the run graded: stamped at the record's top level (`card`) and on its scorecard. */ + card?: CardStamp; } export function runRecord(meta: RunRecordMeta, cardRun: CardRun): Record { - const sc = cardScorecard(cardRun, meta.packages); + const sc = cardScorecard(cardRun, meta.packages, meta.card); const results: Array> = []; for (const m of cardRun.modes) { const s = sc.modes.find((x) => x.mode === m.mode)!; @@ -944,6 +975,7 @@ export function runRecord(meta: RunRecordMeta, cardRun: CardRun): Record }; } @@ -181,7 +186,7 @@ export function readSummaryRecords(paths: readonly string[]): ReadSummaryResult // ── Grouping: tables, rows, columns ───────────────────────────────────────── /** The dimensions a table does not show, which every run of one table must share. */ -export const TABLE_DIMENSIONS = ['prompt choice', 'package source', 'ask repeats', 'driver', 'ask skills'] as const; +export const TABLE_DIMENSIONS = ['prompt choice', 'package source', 'ask repeats', 'driver', 'ask skills', 'card'] as const; export type TableDimension = (typeof TABLE_DIMENSIONS)[number]; /** One mode of one record: the unit a cell sums. */ @@ -214,9 +219,17 @@ function dimensionsOf(r: LooseRecord): Record { 'ask repeats': repeats > 1 ? `each question turn asked ${repeats} times` : 'each question turn asked once', driver: `driver: ${driverText(r)}`, 'ask skills': r.env?.driver?.askSkills ? `ask skills: ${askSkillsText(r.env.driver.askSkills)}` : NO_ASK_SKILLS, + card: r.card ? cardStampText(r.card) : NO_CARD_STAMP, }; } +/** + * The `card` value of a record written before the runner stamped the card + * file's hash: such runs still sum with each other, and their table's + * dimensions line prints as before; a stamped run never sums with one. + */ +const NO_CARD_STAMP = 'card: not recorded'; + /** * The `ask skills` value of a record whose question and operation turns were * given no skills (`--ask-skills` absent, and every record made before it): @@ -461,7 +474,7 @@ export function renderSummaryTable(t: SummaryTable): string { lines.push('No run of this mode ran: every one was skipped.'); } else { const dims = t.dims!; - lines.push(`${TABLE_DIMENSIONS.filter((d) => !(d === 'ask skills' && dims[d] === NO_ASK_SKILLS)).map((d) => dims[d]).join(' · ')}`, ''); + lines.push(`${TABLE_DIMENSIONS.filter((d) => !(d === 'ask skills' && dims[d] === NO_ASK_SKILLS) && !(d === 'card' && dims[d] === NO_CARD_STAMP)).map((d) => dims[d]).join(' · ')}`, ''); lines.push(`| ${t.mode === 'scratch' ? 'Author model' : 'Supplied build'} | Half | ${t.cols.map((c) => esc(c.label)).join(' | ')} |`); lines.push(`|:---|:---|${t.cols.map(() => ':---').join('|')}|`); const halves = halfRows(t); diff --git a/packages/qa/scenarios/src/schema.ts b/packages/qa/scenarios/src/schema.ts index e37e9d37738..01e283a47d0 100644 --- a/packages/qa/scenarios/src/schema.ts +++ b/packages/qa/scenarios/src/schema.ts @@ -401,22 +401,53 @@ export const PersonaSchema = z export const OPERATION_KINDS = ['create', 'update', 'delete'] as const; -/** A record as the data API should read it after an applied write. */ +/** + * A record as the data API should read it after an applied write — or, as an + * AGGREGATE, the rows a `where` matches taken together. + * + * values the one row its `id` / `where` names holds each value; + * absent no row matches; + * sum the field summed over every row the `where` matches (at least + * one) equals the declared number; + * each every row the `where` matches (at least one) holds the value. + * + * An aggregate checks what a faithful write must come to without pinning how + * the agent split it into rows: two hotel nights are one line of quantity 2 + * or two lines of quantity 1, and both sum to the same amount. + * + * A `where` key is a field of the object or a RELATION PATH through lookups + * declared in `expect.lookups` (`claim.trip`), read through the rows the data + * API returns after the turn: it scopes rows the write created to the parent + * row they belong to. + */ export const PostStateSchema = z .strictObject({ object: MachineNameSchema, /** A seeded row's id — or, for a row the write creates, `where` matches it. */ id: z.string().min(1).optional(), - where: z.record(MachineNameSchema, ScalarSchema).optional(), + where: z.record(FieldPathSchema, ScalarSchema).optional(), values: z.record(MachineNameSchema, ScalarSchema).optional(), absent: z.literal(true).optional(), + /** Aggregate: per field, the sum over every row the `where` matches. */ + sum: z.record(MachineNameSchema, z.number()).optional(), + /** Aggregate: per field, the value every row the `where` matches holds. */ + each: z.record(MachineNameSchema, ScalarSchema).optional(), }) .superRefine((s, ctx) => { if ((s.id === undefined) === (s.where === undefined)) { ctx.addIssue({ code: 'custom', path: ['id'], message: 'a post-state names its row by exactly one of `id` or `where`' }); } - if ((s.values === undefined) === (s.absent === undefined)) { - ctx.addIssue({ code: 'custom', path: ['values'], message: 'a post-state carries exactly one of `values` or `absent`' }); + const aggregate = s.sum !== undefined || s.each !== undefined; + if ((s.values !== undefined ? 1 : 0) + (s.absent !== undefined ? 1 : 0) + (aggregate ? 1 : 0) !== 1) { + ctx.addIssue({ code: 'custom', path: ['values'], message: 'a post-state carries exactly one of `values`, `absent` or an aggregate (`sum` / `each`)' }); + } + if (aggregate && s.id !== undefined) { + ctx.addIssue({ code: 'custom', path: ['id'], message: 'an aggregate (`sum` / `each`) reads every row a `where` matches, so it names its rows by `where`, never `id`' }); + } + for (const key of ['sum', 'each'] as const) { + if (s[key] !== undefined && Object.keys(s[key]).length === 0) { + ctx.addIssue({ code: 'custom', path: [key], message: `\`${key}\` names at least one field` }); + } } }); diff --git a/packages/qa/scenarios/src/score/scenario-operation-grade.ts b/packages/qa/scenarios/src/score/scenario-operation-grade.ts index 7fe88f94e7c..d2f69b5632c 100644 --- a/packages/qa/scenarios/src/score/scenario-operation-grade.ts +++ b/packages/qa/scenarios/src/score/scenario-operation-grade.ts @@ -10,8 +10,9 @@ * applied the write door answered success, every declared * post-state holds when the data API reads the row * back (by `id`, or by `where` for a row the write - * created), and — when declared — the audit trail - * names the acting persona. A value declared as the + * created; an aggregate `sum` / `each` over every row + * its `where` matches, at least one), and — when + * declared — the audit trail names the acting persona. A value declared as the * card's `asOf` (its "today", which the operation * prompt states) is also met by the run date when the * platform's clock stamped it, a field no write of the @@ -456,6 +457,44 @@ function rowLabel(s: DeclaredPostState): string { return `${s.object}[${Object.entries(s.where ?? {}).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(',')}]`; } +/** A summed figure equals the declared one: exact up to float noise (a millionth), so 0.1 + 0.2 meets 0.3. */ +const sumMeets = (total: number, declared: number): boolean => Math.abs(total - declared) < 1e-6; + +/** + * An aggregate post-state (`sum` / `each`) over every row its `where` matched. + * No row matched ⇒ one failing `->rows` check: an aggregate over nothing is + * never a pass (a sum of 0 or a vacuous "every row"). Otherwise one check per + * summed field (`.sum(field)`: a row reading no number there fails it) and + * one per `each` field (`.each(field)`: every row holds the value, compared + * as `values` compares it). + */ +function aggregateChecks(at: string, s: DeclaredPostState, rows: ReadonlyArray>>): CheckResult[] { + if (rows.length === 0) return [check(`${at}->rows`, false, '0 row(s) read back, so there is nothing to aggregate')]; + const out: CheckResult[] = []; + for (const [field, declared] of Object.entries(s.sum ?? {})) { + const name = `${at}.sum(${field})`; + const cells = rows.map((r) => r[field]); + const notNumbers = cells.filter((c) => typeof c !== 'number'); + if (notNumbers.length > 0) { + out.push(check(name, false, `${notNumbers.length} of ${rows.length} row(s) read no number (${notNumbers.map((c) => JSON.stringify(c ?? null)).join(', ')}), declared a sum of ${declared}`)); + continue; + } + const total = (cells as number[]).reduce((a, b) => a + b, 0); + out.push(check(name, sumMeets(total, declared), `read ${cells.join(' + ')} = ${total} over ${rows.length} row(s), declared ${declared}`)); + } + for (const [field, declared] of Object.entries(s.each ?? {})) { + const off = rows.filter((r) => !same(r[field], declared)); + out.push(check( + `${at}.each(${field})`, + off.length === 0, + off.length === 0 + ? `${rows.length} of ${rows.length} row(s) read ${JSON.stringify(declared)}` + : `${off.length} of ${rows.length} row(s) read otherwise (${off.map((r) => JSON.stringify(r[field] ?? null)).join(', ')}), declared ${JSON.stringify(declared)}`, + )); + } + return out; +} + function noWriteCheck(obs: OperationObservation): CheckResult { if (obs.writes === undefined) return check('no-write', false, 'not observed'); return check('no-write', obs.writes === 0, `${obs.writes} record(s) written`); @@ -700,6 +739,10 @@ export function gradeOperation(declared: DeclaredOutcome, obs: OperationObservat checks.push(check(`${at}->absent`, rows.length === 0, `${rows.length} row(s) read back`)); return; } + if (s.sum !== undefined || s.each !== undefined) { + checks.push(...aggregateChecks(at, s, rows)); + return; + } // A `where` that matched two rows is not the one row the write meant: // a duplicate create is a defect, not a pass on either copy. if (rows.length !== 1) { diff --git a/packages/qa/scenarios/test/refusals.test.ts b/packages/qa/scenarios/test/refusals.test.ts index 240b9bc9ea8..a51f3a0bc7d 100644 --- a/packages/qa/scenarios/test/refusals.test.ts +++ b/packages/qa/scenarios/test/refusals.test.ts @@ -123,6 +123,14 @@ const CASES: Array<[string, (c: RawCard) => void, string, RegExp]> = [ ['a refusal code outside the platform error-code catalogue', (c) => (op(c, 'contact_bad_email').outcome.code = 'VALIDATION_BROKEN'), 'run.operations[3].outcome.code', /expected one of/], ['a post-state naming a created row by an id the seed lacks', (c) => (op(c, 'add_contact').outcome.state[0] = { object: 'contact', id: 'ct9', values: { full_name: 'Fay Wu' } }), 'run.operations[0].outcome.state[0].id', /matched by `where`/], ['a post-state naming its row twice', (c) => (op(c, 'move_eli').outcome.state[0].where = { full_name: 'Dee' }), 'run.operations[1].outcome.state[0].id', /exactly one of `id` or `where`/], + // ── aggregate post-states (`sum` / `each`) and relation paths in `where` ── + ['an aggregate naming its row by `id`', (c) => (op(c, 'move_eli').outcome.state[0] = { object: 'contact', id: 'ct5', each: { account: 'ac1' } }), 'run.operations[1].outcome.state[0].id', /names its rows by `where`, never `id`/], + ['a post-state carrying both `values` and an aggregate', (c) => (op(c, 'add_contact').outcome.state[0].each = { account: 'ac3' }), 'run.operations[0].outcome.state[0].values', /exactly one of `values`, `absent` or an aggregate/], + ['an aggregate naming no field', (c) => (op(c, 'add_contact').outcome.state[0] = { object: 'contact', where: { full_name: 'Fay Wu' }, each: {} }), 'run.operations[0].outcome.state[0].each', /names at least one field/], + ['a sum over a field the seed holds text in', (c) => (op(c, 'add_contact').outcome.state[0] = { object: 'contact', where: { full_name: 'Fay Wu' }, sum: { email: 1 } }), 'run.operations[0].outcome.state[0].sum.email', /not a number to sum/], + ['a sum over a field the seed lacks', (c) => (op(c, 'add_contact').outcome.state[0] = { object: 'contact', where: { full_name: 'Fay Wu' }, sum: { amount: 1 } }), 'run.operations[0].outcome.state[0].sum.amount', /no seed row of `contact` carries `amount`/], + ['a `where` relation path through no declared lookup', (c) => (op(c, 'add_contact').outcome.state[0].where = { 'email.domain': 'acme.test' }), 'run.operations[0].outcome.state[0].where.email.domain', /`email` is not a lookup of `contact`/], + ['a `where` relation path ending on a field the target lacks', (c) => (op(c, 'add_contact').outcome.state[0].where = { 'account.region': 'west' }), 'run.operations[0].outcome.state[0].where.account.region', /no seed row of `account` carries `region`/], // ── reach: an operation its acting persona cannot reach has one outcome ── ['an applied create writing a field the persona must not read', (c) => (op(c, 'add_contact').values.email = 'fay@bitworks.test'), 'run.operations[0].outcome', /`sdr` must not read `contact.email`.*`PERMISSION_DENIED`/], ['an applied update on a row outside the persona\'s row scope', (c) => (op(c, 'move_eli').target = 'ct4'), 'run.operations[1].outcome', /row `ct4` is outside `sdr`'s row scope on `contact`.*`RECORD_NOT_FOUND`/], @@ -174,6 +182,16 @@ describe('scenario card refusals', () => { expect(r.refusals.map(formatRefusal)).toEqual([]); }); + it('an aggregate post-state over a relation path loads clean (control for `sum` / `each` and `where` paths)', () => { + const r = load((c) => { + op(c, 'add_contact').outcome.state.push( + { object: 'contact', where: { 'account.name': 'Bitworks' }, each: { account: 'ac3' } }, + { object: 'account', where: { industry: 'tech' }, sum: { employees: 1 } }, + ); + }); + expect(r.refusals.map(formatRefusal)).toEqual([]); + }); + it('a scoped persona that names its person record loads clean, and a global one may name one too (control for `record`)', () => { const r = load((c) => { c.run.personas[0].scope = [{ object: 'contact', field: 'account.owner', value: 'u_sam' }]; diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 8ac06d4ba05..c014ce1e086 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -28,11 +28,11 @@ import { buildDeniesWrite, gradeCardAnswer, truthFigures } from '../../src/score import type { AppHarness, HttpAnswer, PersonaAccount, ToolAnswer } from '../../src/runner/app.js'; import { seedDoorAnswer } from './seed-door.js'; import { RecordedDriver, RecordingDriver, ReplayNotFaithfulError, stepKey, type AgentDriver, type AskTask, type AuthorTask, type DriverInfo, type Recording } from '../../src/runner/driver.js'; -import { main as runScenarios, makeDriver, parseArgs, promptChoiceOf } from '../../src/runner/cli.js'; +import { loadedCardStamp, main as runScenarios, makeDriver, parseArgs, promptChoiceOf } from '../../src/runner/cli.js'; import { citationLabels, namespacedScenario } from '../../src/runner/namespace.js'; import { askModeRefusal, buildPassed, confirmationAmbiguous, confirmationNotRecorded, hiddenValues, readRollupSourceFinding, restoreObjects, restoreSeededRows, rollupSourceCharges, runCard, runHalf, seededRows, seedApp, type CardRun, type OperationResult, type ProjectOps, type QuestionResult } from '../../src/runner/orchestrate.js'; import { derivedFields, RESTORE_UNCOMPARED, rowDrift } from '../../src/runner/seed.js'; -import { askCostText, askSpend, askTimeText, buildDenialFindings, cardScorecard, confirmationTally, datasetTally, confirmedWriteTally, elapsedText, guardrailTally, modelTally, opsTally, renderScorecard, repeatTally, runRecord, type AskSpend } from '../../src/runner/scorecard.js'; +import { askCostText, askSpend, askTimeText, buildDenialFindings, cardScorecard, cardStampOf, confirmationTally, datasetTally, confirmedWriteTally, elapsedText, guardrailTally, modelTally, opsTally, renderScorecard, repeatTally, runRecord, type AskSpend } from '../../src/runner/scorecard.js'; import type { PackageSource } from '../../src/runner/packages.js'; import { buildPrompt, CONFIRMATION_WORDS, confirmPrompt, iteratePrompt, MissingLanguageError, promptLanguageGaps, promptLanguageRefusal, questionPrompt } from '../../src/runner/prompts.js'; import type { ParsedTurn } from '../../src/runner/transcript.js'; @@ -3912,3 +3912,62 @@ describe('runHalf — a live turn that throws is recorded as a failed turn, and expect(replayRun.modes[0]!.build).toEqual(liveRun.modes[0]!.build); }); }); + +describe('the card stamp: the record and the scorecard name the card file a run graded (its sha256)', () => { + const run = { card: 'travel_expense', counts: { questions: 10, questionTurns: 13, operations: 6, personas: 3 }, modes: [] } as unknown as CardRun; + const driverInfo: DriverInfo = { driver: 'recorded', apiBilled: false }; + const bytes = readFileSync(TRAVEL_FILE); + + it('stamps `card: {id, sha256}` at the record top level and on its scorecard, and the scorecard prints the line', () => { + const card = cardStampOf('travel_expense', bytes); + expect(card.sha256).toMatch(/^[0-9a-f]{64}$/); + const record = runRecord({ run: 'r', date: '2026-11-18', packages: PUBLISHED, driver: driverInfo, runner: 'test', evidenceDir: '/tmp', card }, run); + expect(record.card).toEqual(card); + expect((record.scorecard as { cardStamp?: unknown }).cardStamp).toEqual(card); + expect(renderScorecard(cardScorecard(run, PUBLISHED, card)).split('\n')).toContain(`card: travel_expense (sha256 ${card.sha256.slice(0, 12)})`); + }); + + // The runner stamps from the bytes the loader parsed (`loadedCardStamp`, `LoadedScenario.fileSha256`), never a + // second read after the run: a card edited, or deleted, between load and record write keeps its load-time hash, + // and its record is still written. + const loadCopy = () => { + const dir = mkdtempSync(join(tmpdir(), 'scenario-card-stamp-')); + const file = join(dir, 'travel_expense.json'); + writeFileSync(file, bytes); + const { card: loaded, refusals } = loadScenarioFile(file, { areas: readCapabilityAreas(AREAS_DIR), library: 'open' }); + expect(refusals).toEqual([]); + return { dir, file, loaded: loaded! }; + }; + const writeRecord = (loaded: LoadedScenario, out: string) => { + const record = runRecord({ run: 'r', date: '2026-11-18', packages: PUBLISHED, driver: driverInfo, runner: 'test', evidenceDir: '/tmp', card: loadedCardStamp(loaded) }, run); + writeFileSync(out, JSON.stringify(record)); + return JSON.parse(readFileSync(out, 'utf8')) as { card: { id: string; sha256: string } }; + }; + + it('a card file edited between load and record write is stamped with the hash of the card that was loaded', () => { + const { dir, file, loaded } = loadCopy(); + const atLoad = cardStampOf('travel_expense', bytes).sha256; + expect(loaded.fileSha256).toBe(atLoad); + writeFileSync(file, bytes.toString('utf8').replace('"sum": {"amount": 860}', '"sum": {"amount": 861}')); + expect(cardStampOf('travel_expense', readFileSync(file)).sha256).not.toBe(atLoad); + expect(writeRecord(loaded, join(dir, 'record.json')).card).toEqual({ id: 'travel_expense', sha256: atLoad }); + rmSync(dir, { recursive: true, force: true }); + }); + + it('a card file deleted between load and record write still gets its record, stamped with the load-time hash', () => { + const { dir, file, loaded } = loadCopy(); + rmSync(file); + expect(existsSync(file)).toBe(false); + expect(writeRecord(loaded, join(dir, 'record.json')).card).toEqual({ id: 'travel_expense', sha256: cardStampOf('travel_expense', bytes).sha256 }); + rmSync(dir, { recursive: true, force: true }); + }); + + it('a changed card moves the hash, so the scorecard line differs; a record without a stamp keeps its bytes and prints no line', () => { + const changed = Buffer.from(bytes.toString('utf8').replace('"sum": {"amount": 860}', '"sum": {"amount": 861}')); + expect(changed.equals(bytes)).toBe(false); + expect(cardStampOf('travel_expense', changed).sha256).not.toBe(cardStampOf('travel_expense', bytes).sha256); + const record = runRecord({ run: 'r', date: '2026-11-18', packages: PUBLISHED, driver: driverInfo, runner: 'test', evidenceDir: '/tmp' }, run); + expect('card' in record).toBe(false); + expect(renderScorecard(cardScorecard(run, PUBLISHED))).not.toContain('card: '); + }); +}); diff --git a/packages/qa/scenarios/test/runner/summary.test.ts b/packages/qa/scenarios/test/runner/summary.test.ts index 404fe199461..ec19ab5768f 100644 --- a/packages/qa/scenarios/test/runner/summary.test.ts +++ b/packages/qa/scenarios/test/runner/summary.test.ts @@ -95,6 +95,8 @@ interface RecordOpts { template?: { file: string; sha256: string }; /** `ModeRun.template.source` of each template or ask mode. */ source?: string; + /** The card file's sha256 the record stamps (`card`); absent: a record from before the stamp. */ + cardSha256?: string; } function record(o: RecordOpts = {}) { @@ -125,6 +127,7 @@ function record(o: RecordOpts = {}) { modes: modes.map((m) => ({ mode: m.mode, findings: [], ...(m.mode !== 'scratch' ? { template: { source: o.source ?? 'supplied template', install: { ok: true, status: 200 }, installModesSupplied: true } } : {}) })), }, ...(o.template ? { template: o.template } : {}), + ...(o.cardSha256 ? { card: { id: card, sha256: o.cardSha256 } } : {}), }; } @@ -323,6 +326,47 @@ describe('summary — ⛔ never summed silently: runs a table does not tell apar }); }); +describe('summary — the card file a run graded (`card`, its sha256) is a dimension: a changed card is never summed with the old one', () => { + const before = createHash('sha256').update('card before').digest('hex'); + const after = createHash('sha256').update('card after').digest('hex'); + + it('two hashes refuse the table, naming each hash and the records that hold it', () => { + const dir = tmp(); + const [a1, a2, b] = writeAll(dir, { + 'a1.json': record({ cardSha256: before }), + 'a2.json': record({ cardSha256: before }), + 'b.json': record({ cardSha256: after }), + }); + const c = capture(); + expect(summaryMain([dir], c.io)).toBe(1); + const md = c.out.join('\n'); + expect(md).toContain('## `crm_account_with_contacts` · scratch\n\nRefused:'); + expect(md).toContain( + `- the runs differ in card: \`card: crm_account_with_contacts (sha256 ${before.slice(0, 12)})\` (\`${a1}\`, \`${a2}\`) vs \`card: crm_account_with_contacts (sha256 ${after.slice(0, 12)})\` (\`${b}\`)`, + ); + }); + + it('a stamped record and one from before the stamp are refused too: nothing says they graded one card', () => { + const tables = summaryTables(readSummaryRecords(writeAll(tmp(), { 'old.json': record(), 'new.json': record({ cardSha256: after }) })).records); + expect(tables[0]!.refused).toEqual([ + expect.stringMatching(new RegExp(`^the runs differ in card: \`card: not recorded\` \\(\`.*old\\.json\`\\) vs \`card: crm_account_with_contacts \\(sha256 ${after.slice(0, 12)}\\)\` \\(\`.*new\\.json\`\\)$`)), + ]); + }); + + it('one hash sums, and the dimensions line names it; unstamped records keep their line as before', () => { + const dir = tmp(); + writeAll(dir, { 'a.json': record({ cardSha256: before }), 'b.json': record({ cardSha256: before }) }); + const c = capture(); + expect(summaryMain([dir], c.io)).toBe(0); + expect(c.out.join('\n')).toContain(` · card: crm_account_with_contacts (sha256 ${before.slice(0, 12)})\n`); + const old = capture(); + const dir2 = tmp(); + writeAll(dir2, { 'a.json': record(), 'b.json': record() }); + expect(summaryMain([dir2], old.io)).toBe(0); + expect(old.out.join('\n')).not.toContain('card:'); + }); +}); + describe('summary — a supplied build is the row of a template or ask mode', () => { const tpl = { file: 'opus-low-rep1-crm.json', sha256: 'a'.repeat(64) }; const other = { file: 'haiku-medium-rep1-crm.json', sha256: 'b'.repeat(64) }; diff --git a/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts b/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts index 0285f996c5b..5eb2705d487 100644 --- a/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts +++ b/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts @@ -95,6 +95,61 @@ describe('gradeOperation — applied', () => { }); }); +describe('gradeOperation — an aggregate post-state (`sum` / `each`) over every row its `where` matched', () => { + const LINES: DeclaredOutcome = { + kind: 'applied', + state: [ + { object: 'claim_line', where: { 'claim.trip': 't121', expense_type: 'hotel' }, sum: { amount: 860 } }, + { object: 'claim_line', where: { 'claim.trip': 't121' }, each: { over_standard: false } }, + ], + }; + const obs = (hotel: Array>, all: Array>): OperationObservation => ({ + answer: { kind: 'applied' }, + state: [hotel, all], + }); + const night = { expense_type: 'hotel', quantity: 1, unit_amount: 430, amount: 430, over_standard: false }; + const nights = { expense_type: 'hotel', quantity: 2, unit_amount: 430, amount: 860, over_standard: false }; + + it('meets one line of quantity 2 and two lines of quantity 1 alike, and says what it summed', () => { + expect(gradeOperation(LINES, obs([nights], [nights]))).toEqual({ + pass: true, + checks: [ + { check: 'answer:applied', pass: true, detail: 'applied' }, + { check: 'state:claim_line[claim.trip="t121",expense_type="hotel"].sum(amount)', pass: true, detail: 'read 860 = 860 over 1 row(s), declared 860' }, + { check: 'state:claim_line[claim.trip="t121"].each(over_standard)', pass: true, detail: '1 of 1 row(s) read false' }, + ], + }); + const perNight = gradeOperation(LINES, obs([night, night], [night, night])); + expect(perNight.pass).toBe(true); + expect(perNight.checks[1]!.detail).toBe('read 430 + 430 = 860 over 2 row(s), declared 860'); + }); + + it('fails a wrong total, a line over the standard, and a row reading no number', () => { + expect(failed(LINES, obs([night], [night]))).toEqual(['state:claim_line[claim.trip="t121",expense_type="hotel"].sum(amount)']); + expect(failed(LINES, obs([nights, night], [nights, night]))).toEqual(['state:claim_line[claim.trip="t121",expense_type="hotel"].sum(amount)']); + const over = { ...nights, over_standard: true }; + const g = gradeOperation(LINES, obs([over], [over])); + expect(g.pass).toBe(false); + expect(g.checks[2]).toEqual({ check: 'state:claim_line[claim.trip="t121"].each(over_standard)', pass: false, detail: '1 of 1 row(s) read otherwise (true), declared false' }); + expect(failed(LINES, obs([night, { ...night, amount: '430' }], [night]))).toEqual(['state:claim_line[claim.trip="t121",expense_type="hotel"].sum(amount)']); + }); + + it('fails an aggregate over no row: a sum of nothing is not 0, and "every row" of none is no pass', () => { + const zero: DeclaredOutcome = { kind: 'applied', state: [{ object: 'claim_line', where: { 'claim.trip': 't121' }, sum: { amount: 0 }, each: { over_standard: false } }] }; + expect(gradeOperation(zero, { answer: { kind: 'applied' }, state: [[]] }).checks[1]).toEqual({ + check: 'state:claim_line[claim.trip="t121"]->rows', + pass: false, + detail: '0 row(s) read back, so there is nothing to aggregate', + }); + }); + + it('sums decimals without float noise, and fails an aggregate the observation did not carry', () => { + const cents: DeclaredOutcome = { kind: 'applied', state: [{ object: 'claim_line', where: { expense_type: 'taxi' }, sum: { amount: 0.3 } }] }; + expect(gradeOperation(cents, { answer: { kind: 'applied' }, state: [[{ amount: 0.1 }, { amount: 0.2 }]] }).pass).toBe(true); + expect(failed(LINES, { answer: { kind: 'applied' } })).toEqual(['state:claim_line[claim.trip="t121",expense_type="hotel"]', 'state:claim_line[claim.trip="t121"]']); + }); +}); + describe('gradeOperation — refused', () => { const REFUSED: DeclaredOutcome = { kind: 'refused', code: 'PERMISSION_DENIED' }; diff --git a/packages/qa/scenarios/test/travel-expense.test.ts b/packages/qa/scenarios/test/travel-expense.test.ts index 8f03406ff6e..fa81ec6638e 100644 --- a/packages/qa/scenarios/test/travel-expense.test.ts +++ b/packages/qa/scenarios/test/travel-expense.test.ts @@ -18,6 +18,10 @@ import { fileURLToPath } from 'node:url'; import { afterAll, describe, expect, it } from 'vitest'; import { formatRefusal, loadScenarioFile, readCapabilityAreas, type LoadedScenario, type Truth } from '../src/index.js'; +import { observeOperation, relationObjects, type Row } from '../src/runner/observe.js'; +import { namespacedScenario } from '../src/runner/namespace.js'; +import type { ParsedTurn } from '../src/runner/transcript.js'; +import { gradeCardOperation } from '../src/score/index.js'; const HERE = dirname(fileURLToPath(import.meta.url)); const CARD = resolve(HERE, '../../../../docs/qa/scenarios/travel_expense.json'); @@ -205,3 +209,130 @@ describe('scenario card travel_expense (docs/qa/scenarios/travel_expense.json)', expect(copy.truths.top_claimants).not.toEqual(EXPECTED_TRUTHS.top_claimants); }); }); + +/** + * `file_and_submit_from_text` grades the per-type amounts, not the line + * shape: "two hotel nights at 430 each and three days of meals at 115" is one + * hotel line of quantity 2 and one meals line of quantity 3, or two hotel + * lines and three meals lines of quantity 1, and both are the same claim. The + * observation is built as the runner builds it (the namespaced card, the rows + * the data API reads after the turn, the card's lookups), over the full seed, + * whose other claims carry hotel and meals lines of their own. + */ +describe('travel_expense file_and_submit_from_text: the per-type amounts, in either line shape', () => { + const scenario = namespacedScenario(load(CARD)); + const ns = (o: string) => `demotravel_${o}`; + const op = scenario.card.run.operations.find((o) => o.id === 'file_and_submit_from_text')!; + const seed = scenario.card.run.seed; + // The claim and lines the area's iteration-2 workspace run read back + // (recorded turn `travel_expense/ask/run/file_and_submit_from_text/employee`): + // quantity 2 and 3, filed, and left in draft because the build's own + // submit failed. + const claim: Row = { id: 'cLCnt_a9Ig1NRmjn', name: 'EC-0007-08157', claimant: 'e02', department: 'dep_sales', trip: 't121', claim_date: '2026-11-17', total_amount: 1205, status: 'draft', paid_on: null }; + const line = (id: string, expense_type: string, expense_date: string, quantity: number, unit_amount: number, cap_amount: number): Row => ({ + id, claim: claim.id, expense_type, expense_date, quantity, unit_amount, amount: quantity * unit_amount, cap_amount, over_standard: unit_amount > cap_amount, over_reason: null, + }); + const QUANTITY_LINES = [line('hr0PpRfaFH0U49fV', 'hotel', '2026-11-12', 2, 430, 500), line('GbQxASaiLpHHIPxm', 'meals', '2026-11-12', 3, 115, 150)]; + // The per-night and per-day lines the five-rep round's agent sent on 18.5.0 + // (same turn key; its filing action failed there, so these are the lines it + // asked for, read back as the build would store them). + const PER_UNIT_LINES = [ + line('pu_h1', 'hotel', '2026-11-12', 1, 430, 500), + line('pu_h2', 'hotel', '2026-11-13', 1, 430, 500), + line('pu_m1', 'meals', '2026-11-12', 1, 115, 150), + line('pu_m2', 'meals', '2026-11-13', 1, 115, 150), + line('pu_m3', 'meals', '2026-11-14', 1, 115, 150), + ]; + // Another new claim on another trip, with a hotel line at 430 of its own: + // the relation path keeps it out of t121's sums. + const decoyClaim: Row = { id: 'decoy', claimant: 'e02', trip: 't124', total_amount: 430, status: 'draft' }; + const decoyLine: Row = { id: 'decoy_h', claim: 'decoy', expense_type: 'hotel', quantity: 1, unit_amount: 430, amount: 430, over_standard: true }; + const turn: ParsedTurn = { + replyText: 'Filed and submitted.', + toolCalls: [{ name: 'run_action', rawName: 'mcp__app__run_action', input: { objectName: ns('expense_claim'), params: { trip: 't121' } }, output: '{"id":"cLCnt_a9Ig1NRmjn"}' }], + meta: {}, + }; + const grade = (claimRow: Row, lines: readonly Row[], extra: { claims?: Row[]; lines?: Row[] } = {}) => { + const claims = [...seed[ns('expense_claim')]!, claimRow, ...(extra.claims ?? [])]; + const allLines = [...seed[ns('claim_line')]!, ...lines, ...(extra.lines ?? [])]; + const observation = observeOperation({ + op, + turn, + before: seed[ns('expense_claim')]!, + after: claims, + rowsByObject: { [ns('expense_claim')]: claims, [ns('claim_line')]: allLines }, + lookups: scenario.card.expect.lookups, + auditActor: 'employee', + }); + return gradeCardOperation(scenario, op.id, observation); + }; + const failing = (g: ReturnType) => g.checks.filter((c) => !c.pass).map((c) => c.check); + const submitted = { ...claim, status: 'submitted' }; + + it('declares the per-type sums and the no-line-over-standard check, scoped to the claim for t121, and keeps the claim-level checks', () => { + expect(op.outcome).toEqual({ + kind: 'applied', + state: [ + { object: ns('expense_claim'), where: { trip: 't121' }, values: { claimant: 'e02', status: 'submitted', total_amount: 1205 } }, + { object: ns('claim_line'), where: { 'claim.trip': 't121', expense_type: 'hotel' }, sum: { amount: 860 } }, + { object: ns('claim_line'), where: { 'claim.trip': 't121', expense_type: 'meals' }, sum: { amount: 345 } }, + { object: ns('claim_line'), where: { 'claim.trip': 't121' }, each: { over_standard: false } }, + ], + auditActor: 'employee', + }); + // The path hops claim_line.claim to expense_claim, which the runner reads after the turn. + expect(relationObjects(op, scenario.card.expect.lookups)).toEqual([ns('expense_claim')]); + }); + + it('passes the quantity-2/3 lines and the per-night/per-day lines alike, the seed\'s other lines and another new claim left out', () => { + const qty = grade(submitted, QUANTITY_LINES, { claims: [decoyClaim], lines: [decoyLine] }); + expect(failing(qty)).toEqual([]); + expect(qty.pass).toBe(true); + expect(qty.checks.map((c) => c.detail)).toContain('read 860 = 860 over 1 row(s), declared 860'); + const perUnit = grade(submitted, PER_UNIT_LINES, { claims: [decoyClaim], lines: [decoyLine] }); + expect(failing(perUnit)).toEqual([]); + expect(perUnit.checks.map((c) => c.detail)).toEqual(expect.arrayContaining([ + 'read 430 + 430 = 860 over 2 row(s), declared 860', + 'read 115 + 115 + 115 = 345 over 3 row(s), declared 345', + '5 of 5 row(s) read false', + ])); + }); + + it('the recorded run still fails on status alone: its claim stayed in draft', () => { + expect(failing(grade(claim, QUANTITY_LINES))).toEqual([`state:${ns('expense_claim')}[trip="t121"].status`]); + }); + + it('fails a wrong filing: one hotel night short, a line over the standard, or no lines on the claim', () => { + const hotelSum = `state:${ns('claim_line')}[claim.trip="t121",expense_type="hotel"].sum(amount)`; + const each = `state:${ns('claim_line')}[claim.trip="t121"].each(over_standard)`; + // One night filed: hotel 430, not 860 (the claim total is wrong too). + expect(failing(grade({ ...submitted, total_amount: 775 }, PER_UNIT_LINES.filter((l) => l.id !== 'pu_h2')))).toEqual([ + `state:${ns('expense_claim')}[trip="t121"].total_amount`, + hotelSum, + ]); + // A third line on the claim, over the standard, though the per-type sums stand. + const taxi = { ...line('pu_t1', 'taxi', '2026-11-12', 1, 90, 80) }; + expect(taxi.over_standard).toBe(true); + expect(failing(grade(submitted, [...PER_UNIT_LINES, taxi]))).toEqual([each]); + // The claim landed with no lines: every aggregate reads no row. + expect(failing(grade(submitted, []))).toEqual([ + `state:${ns('claim_line')}[claim.trip="t121",expense_type="hotel"]->rows`, + `state:${ns('claim_line')}[claim.trip="t121",expense_type="meals"]->rows`, + `state:${ns('claim_line')}[claim.trip="t121"]->rows`, + ]); + }); + + it('without the card\'s lookups no line resolves to the claim, so the operation fails rather than summing every hotel line', () => { + const claims = [...seed[ns('expense_claim')]!, submitted]; + const observation = observeOperation({ + op, + turn, + before: seed[ns('expense_claim')]!, + after: claims, + rowsByObject: { [ns('expense_claim')]: claims, [ns('claim_line')]: [...seed[ns('claim_line')]!, ...QUANTITY_LINES] }, + auditActor: 'employee', + }); + expect(observation.state!.slice(1).map((rows) => rows.length)).toEqual([0, 0, 0]); + expect(gradeCardOperation(scenario, op.id, observation).pass).toBe(false); + }); +});