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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/35025-per-type-amounts.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions docs/qa/scenarios/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 9 additions & 4 deletions docs/qa/scenarios/travel_expense.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
20 changes: 17 additions & 3 deletions packages/qa/scenarios/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 23 additions & 3 deletions packages/qa/scenarios/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<string, Truth>;
Expand Down Expand Up @@ -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 };
Expand All @@ -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;
Expand Down Expand Up @@ -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`);
}
});
});

Expand Down
20 changes: 16 additions & 4 deletions packages/qa/scenarios/src/runner/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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`). */
Expand Down Expand Up @@ -371,6 +371,16 @@ export function withSuppliedTemplate(record: Record<string, unknown>, 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<LoadedScenario, 'fileSha256' | 'card'>): CardStamp {
return { id: loaded.card.id, sha256: loaded.fileSha256 };
}

export async function main(argv: readonly string[]): Promise<number> {
// `summary` reads records back; it runs nothing (`summary.ts`).
if (argv[0] === 'summary') return summaryMain(argv.slice(1));
Expand Down Expand Up @@ -481,10 +491,12 @@ export async function main(argv: readonly string[]): Promise<number> {
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);
}
Expand Down
Loading
Loading