Skip to content

Commit bd22740

Browse files
fix(scenarios): scorer and card defects from the 18.6.0 gallery refresh (#36320)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9JpRoUZGqtwqMU5k7b4C58D)_ Part of #36206 (items 1, 4, 5, 6, 7, 8 and the operand-shown half of item 2 land here; item 3 and the column-total half of item 2 wait on a decision, see Acceptance notes). Clause-②: yes (widening) — new exports `confirmTurnMetNoConfirmationService` and `SEED_POSTURE` on the `./runner` entry Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:评测席位跑场景卡时,三类本不该扣的分不再扣,四张卡的数据和提示词更正,其余用户无感。 - 为什么做:场景库专题(画廊刷新)中,模型做对了却被判错或被判"无法测量",分数里混进了评分器和卡片自己的错。 - 出错会怎样:最坏是某次评测把一个本该判错的回答判成"未测"或判对,只影响评测分数,改动可直接撤回。 - 要你做什么:审批步骤走卡片自带动作时是否算作有效授权,以及拒答里能否写出某一列的合计,两件需要你拍板。 ## What changes One commit per item; each conclusion below is against `origin/main` 4ab1218. | Item | Conclusion | |:--|:--| | 1. confirm turn after a first-turn `428 no_confirmation_service` | **changed** — `confirmTurnMetNoConfirmationService` (`src/runner/orchestrate.ts`): the confirmed write is not measured when the confirm turn's own write met that 428 (as before) OR the first turn's write met it and the confirm turn sent no write on the object. A confirm turn that does write is graded as any other. PR #36140 (merged for #35907) covered only the first leg: its diff marks not-measured from `writeCallsOn(second, ...)` alone. | | 2. decline graded "a figure the data cannot support" for derived numbers | **changed, half** — `supportedNumbers` (`src/score/scenario-run-grade.ts`): a number in an `unanswerable` decline is supported when it is the sum or difference of two OTHER numbers the reply writes that the turn's outputs carry (54.5 = 45.5 + 9; 229 = 249 - 20). Operands must stand in the reply, one step only, a zero from two equal figures supports nothing. The column-total half ($125,190) is **not** changed: it contradicts a pinned case in the same suite ("an amount summed from the rows still fails: a sum is not a count"), so it is an open question. | | 3. `persona-grant:dept_manager:*_approval_step:update` vs the card's own `decide_approval_step` | **not changed — needs a decision.** The check treats only a card action with `confirm: true` as a designed route; the suite pins the opposite case on purpose ("The card's action without `confirm` is no designed route: the check is measured", and `start_qa` stays measured beside `set_task_status`). Accepting `decide_approval_step` reverses that pin. | | 4. requisition_to_receipt `supplier.rating` seeded `A`/`B`/`C` | **changed** — seeded `grade_a`/`grade_b`/`grade_c` (no truth reads the field). New library guard: every seed value of a card's `selectFields` field parses as a `SelectOptionSchema` value. | | 5. travel_expense `as_118_2.decided_on` after `asOf` | **changed** — `2026-11-02` to `2026-10-31` (no truth reads step dates). New library guard: per card, the seed fields dated after `asOf` are pinned (all are plans: due, start, end, expected). | | 6. service_desk `urgent_high_last_30_days` off by one | **changed (card data)** — TK-0091 and its three comments move one day later, so no urgent or high ticket sits on 2026-10-01, the day the platform's `last_30_days` preset (`['30_days_ago', 'tomorrow')`, `packages/core/src/utils/analytics-date-range.ts`) counts and the card's 30-day window does not; truth 8 to 9, seed rule `$comment` names the exception. The card's `last_days` semantics are untouched. New library guard: no `last_days` truth changes when its window is widened by the preset's extra day. | | 7. service_desk Build two checks short | **changed** — the detailed prompt (en + zh) now asks for a report of tickets by agent group and priority, and names a computed value (days to resolve, from the opened and resolved dates). New library guard: every card tagged `dashboards.report` asks for a report in both languages. | | 8. data contract says rows load "through the data API" | **changed (contract text only)** — `SEED_POSTURE` in `src/runner/prompts.ts`: rows load through the platform's seed path as established facts, no record-triggered flow fires, so a derived field must be a formula or a write-time expression; a loaded row is already counted in stored totals. Seeding behaviour is unchanged. | Read first (by risk): `src/score/scenario-run-grade.ts` `supportedNumbers` (the grader widening), `src/runner/orchestrate.ts` `confirmTurnMetNoConfirmationService`, `docs/qa/scenarios/service_desk.json` (seed move + prompt). Two-minute check: `pnpm --filter @objectstack/scenarios exec vitest run --maxWorkers=2 test/library.test.ts` shows 19 passed, including the four new guards. ## Tests - New: item 1, three cases in `test/runner/orchestrate.test.ts` (first-turn 428 + no write: not measured; + a write: graded; other-reason 428 + no write: measured fail). Item 2, five cases in `test/score/scenario-run-grade.test.ts`. Items 4-7, four guards in `test/library.test.ts`. Item 8, one case in `test/runner/units.test.ts`. Item 6, the service_desk truth pin 8 to 9. - Whole package at the final head: `typecheck` clean, `test` 42/42 files and 1293 tests passing across two runs (the first run's 14 skips are the two build files' tests, which pass once the package is built) — see Verification. ## Acceptance notes - **Item 2, column totals (open question).** Options: (A) accept a whole-column sum of one returned list as served, and rewrite the pinned "a sum is not a count" case; (B) keep it refused and have the cards say a decline may only quote figures as served; (C) leave both. The recorded replies are not in the repository, so whether the three flagged replies wrote their operands (and so pass under this change) is NOT MEASURED; the tests use replies modeled on the card's description. - **Item 3 (open question).** Options: (A) any card-declared agent action on the object routes an `applied` write too (reverses the pinned `confirm`-only rule); (B) keep the rule, and the leave_balances / requisition_to_receipt prompts tell the build to grant the manager `update` on `approval_step`; (C) a card-schema opt-in naming the operation's route action, so only operations the card designs through an action leave the check to the run. - **Same family as item 6, outside this card's files:** order_to_cash `collected_by_team_last_30_days` has PAY-0044 on 2026-10-01. The new guard enumerates it as the one remaining position, so fixing it turns that pin red by design. ## Verification <details><summary>Item 1 ablation (orchestrate.ts, fix committed first)</summary> `node scripts/ablation-replace.mjs --file packages/qa/scenarios/src/runner/orchestrate.ts --anchor ' || (firstMet && writes.length === 0)' --delete -- ... vitest run test/runner/orchestrate.test.ts -t 'two turns'`: mutation landed (anchor 1 to 0, blob f58c077 to c72e3bd35891); the new not-measured case failed (1 failed, 14 passed); restored, blob == HEAD, `git diff HEAD` empty. </details> <details><summary>Item 2 ablation (scenario-run-grade.ts)</summary> First attempt was a no-op refused by the tool (replacement text was a substring of the anchor, rise 0); rerun with `--anchor ' || values.some((n) => derived(n, at))' --delete`: mutation landed (blob 9a3cb9e to 78d0020365c7); the sum and difference cases failed (2 failed, 3 passed); restored, blob == HEAD, `git diff HEAD` empty. </details> <details><summary>Items 4-6 reverse verification (base card data)</summary> With the three cards restored from 4ab1218 (tree only), `test/library.test.ts`: 3 failed, 15 passed — the select-value guard listed six `supplier.rating` values, the asOf guard and the window guard (`service_desk/urgent_high_last_30_days`) went red; `git checkout HEAD -- docs/qa/scenarios/` then `git diff HEAD` empty and status clean. </details> <details><summary>Package suite and derived gates at c621cbb</summary> - `pnpm --filter @objectstack/scenarios typecheck`: clean. `pnpm --filter @objectstack/scenarios test`: 40/42 files on the first run, the two `test/build/*` files refusing for a missing own `dist/`; after `pnpm --filter @objectstack/scenarios build` both pass (2/2 files, 14 tests). Total 42/42 files, 1279 + 14 = 1293 tests passed. - `node scripts/pm/dispatch-gates.mjs --commands` derived 69 commands; all run, exit codes captured before any pipe; `--ran` reconciliation: 69 accounted, 67 run, 2 NOT MEASURED (exit 3, prerequisite): `check-plugin-teardown-shape.mjs --self-test` (positive control pinned to a commit this shallow checkout cannot reach) and `check:dual-build-cjs-loads` (needs every package's `dist/`). Both are left to CI. - `test:repo` and the full lint farm are CI's. ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-adr-links.mjs :: exit 0 node scripts/check-adr-links.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 3 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:cli-command-ids :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 3 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:settings-bind-window :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY)_ <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRY38EZf38Yy3zthbY --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2b57044 commit bd22740

12 files changed

Lines changed: 260 additions & 26 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
fix(scenarios): scorer and card fixes from the 18.6.0 gallery refresh
6+
7+
Clause-②: yes (widening) — new exports `confirmTurnMetNoConfirmationService` and `SEED_POSTURE` on the `./runner` entry
8+
Metadata-protocol: none
9+
10+
- The confirmed write of a `pending_confirmation` operation is not measured, never failed, when the first turn's write already met `428 ACTION_CONFIRMATION_REQUIRED` with `reason: no_confirmation_service` and the confirmation turn sends no write on the object: the agent remembered that the route cannot apply on that server. A confirmation turn that does write is graded as before. New export: `confirmTurnMetNoConfirmationService(firstMet, turn, object)`.
11+
- A decline of an `unanswerable` question may state the sum or the difference of two figures the turn's tool outputs carry, when the reply writes both of them too ("45.5 + 9 = 54.5 days", "249 comments, 20 internal, so 229"). A derived figure whose operands the reply leaves out, a product, a figure derived from a derived figure and a zero from two equal figures still fail.
12+
- Card data: requisition_to_receipt seeds `supplier.rating` as `grade_a` / `grade_b` / `grade_c` (a single-choice value is a lowercase identifier, so `A` / `B` / `C` refused every supplier row and the purchase orders, lines and receipts beneath them); travel_expense's step `as_118_2` is decided on the card's `asOf` (2026-10-31), not after it; service_desk's TK-0091 opens on 2026-10-02, so no urgent or high ticket sits on the day the platform's `last_30_days` preset counts and the card's 30-day window does not (`urgent_high_last_30_days` is now 9); and service_desk's prompt asks for the report and the computed value its Build half grades.
13+
- The build prompt's data contract says how the seed loads: through the platform's seed path as established facts, where every validation rule and hook but the state machine's entry check runs and no record-triggered flow fires, so a derived field must be a formula or an expression computed when written. New export: `SEED_POSTURE`.

‎docs/qa/scenarios/requisition_to_receipt.json‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,12 @@
105105
{"id": "e18", "name": "Adam Wright", "department": "dep_exec", "title": "General manager", "email": "adam.wright@example.com"}
106106
],
107107
"supplier": [
108-
{"id": "s01", "name": "Bluepeak Electronics", "category": "it_hardware", "rating": "A", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0101"},
109-
{"id": "s02", "name": "Cedar Office Supply", "category": "office_supplies", "rating": "B", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0102"},
110-
{"id": "s03", "name": "Harbor Facilities Co.", "category": "facilities", "rating": "A", "payment_terms": "net_60", "bank_account": "6217 0000 0000 0103"},
111-
{"id": "s04", "name": "Summit Advisory Group", "category": "services", "rating": "B", "payment_terms": "net_60", "bank_account": "6217 0000 0000 0104"},
112-
{"id": "s05", "name": "Granite Systems", "category": "it_hardware", "rating": "A", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0105"},
113-
{"id": "s06", "name": "Maple Print Works", "category": "office_supplies", "rating": "C", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0106"}
108+
{"id": "s01", "name": "Bluepeak Electronics", "category": "it_hardware", "rating": "grade_a", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0101"},
109+
{"id": "s02", "name": "Cedar Office Supply", "category": "office_supplies", "rating": "grade_b", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0102"},
110+
{"id": "s03", "name": "Harbor Facilities Co.", "category": "facilities", "rating": "grade_a", "payment_terms": "net_60", "bank_account": "6217 0000 0000 0103"},
111+
{"id": "s04", "name": "Summit Advisory Group", "category": "services", "rating": "grade_b", "payment_terms": "net_60", "bank_account": "6217 0000 0000 0104"},
112+
{"id": "s05", "name": "Granite Systems", "category": "it_hardware", "rating": "grade_a", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0105"},
113+
{"id": "s06", "name": "Maple Print Works", "category": "office_supplies", "rating": "grade_c", "payment_terms": "net_30", "bank_account": "6217 0000 0000 0106"}
114114
],
115115
"purchase_requisition": [
116116
{"id": "r001", "name": "PR-0001", "requester": "e01", "request_date": "2026-07-01", "category": "office_supplies", "description": "Printer paper for the office", "total_amount": 1200, "approval_levels": 1, "status": "received"},

‎docs/qa/scenarios/service_desk.json‎

Lines changed: 7 additions & 7 deletions
Large diffs are not rendered by default.

‎docs/qa/scenarios/travel_expense.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -867,7 +867,7 @@
867867
{"id": "as_116_2", "claim": "c116", "step": 2, "approver": "e13", "decision": "pending", "decided_on": null, "comment": null},
868868
{"id": "as_117_1", "claim": "c117", "step": 1, "approver": "e14", "decision": "rejected", "decided_on": "2026-10-29", "comment": "Trip purpose does not match the approved request."},
869869
{"id": "as_118_1", "claim": "c118", "step": 1, "approver": "e09", "decision": "approved", "decided_on": "2026-10-30", "comment": null},
870-
{"id": "as_118_2", "claim": "c118", "step": 2, "approver": "e13", "decision": "approved", "decided_on": "2026-11-02", "comment": null}
870+
{"id": "as_118_2", "claim": "c118", "step": 2, "approver": "e13", "decision": "approved", "decided_on": "2026-10-31", "comment": null}
871871
]
872872
},
873873
"questions": [

‎packages/qa/scenarios/src/runner/orchestrate.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,9 +461,28 @@ export const confirmationAmbiguous = 'the ask matches more than one row and the
461461
* Why a confirmed write is not measured on a server with no pending-confirmation service: the action door answered
462462
* the turn's confirm-gated call `428 ACTION_CONFIRMATION_REQUIRED`, `details.reason: 'no_confirmation_service'`, and
463463
* on such a server it answers every such call so, whatever the agent sends. The ask (the first turn) is graded as before.
464+
* The same holds when the FIRST turn's call met that answer and the confirmation turn sent no write on the object: the
465+
* agent already learned the route cannot apply, so not retrying it is no failure ({@link confirmTurnMetNoConfirmationService}).
464466
*/
465467
const noConfirmationService = 'the action door has no pending-confirmation service on this server (428 ACTION_CONFIRMATION_REQUIRED, reason no_confirmation_service), so no agent can apply the confirmed write';
466468

469+
/**
470+
* Whether the confirmation turn of a `pending_confirmation` operation meets the server with no pending-confirmation
471+
* service ({@link noConfirmationService}), so its confirmed write is not measured. Either:
472+
*
473+
* - a write call on the operation's object in the confirmation turn met `428 ACTION_CONFIRMATION_REQUIRED`,
474+
* reason `no_confirmation_service`; or
475+
* - the first turn's write call met that answer (`firstMet`, the first turn's
476+
* `OperationObservation.metNoConfirmationService`) and the confirmation turn sent no write call on the
477+
* object at all: the agent remembered the route cannot apply here and did not retry it.
478+
*
479+
* A confirmation turn that does write after a first-turn 428 is graded on its own, as any other.
480+
*/
481+
export function confirmTurnMetNoConfirmationService(firstMet: boolean, second: Pick<ParsedTurn, 'toolCalls'>, object: string): boolean {
482+
const writes = writeCallsOn(second, object);
483+
return writes.some((c) => metNoConfirmationService(c.output)) || (firstMet && writes.length === 0);
484+
}
485+
467486
export interface RunHalf {
468487
personas: Array<Omit<PersonaAccount, 'apiKey'>>;
469488
seed: {
@@ -1967,7 +1986,7 @@ export async function runHalf(
19671986
const afterConfirm = (await app.listRows(op.object)).rows as Row[];
19681987
confirmed.observation = observeConfirmedWrite(op, second, beforeConfirm, afterConfirm, clockDates(startedConfirm, new Date()));
19691988
confirmed.grade = gradeConfirmedWrite(op, confirmed.observation, card.asOf !== undefined ? { asOf: card.asOf } : {});
1970-
if (writeCallsOn(second, op.object).some((c) => metNoConfirmationService(c.output))) confirmed.notMeasured = noConfirmationService;
1989+
if (confirmTurnMetNoConfirmationService(res.observation.metNoConfirmationService === true, second, op.object)) confirmed.notMeasured = noConfirmationService;
19711990
}
19721991
} catch (e) {
19731992
confirmed.error = errText(e);

‎packages/qa/scenarios/src/runner/prompts.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,17 +443,38 @@ const CONFIRM_FIRST_LOCK =
443443
'so a plain record update cannot make that change while those people’s other changes to the same fields still land; ' +
444444
'an action that deletes its row locks nothing, and those people keep their delete right';
445445

446+
/**
447+
* How the runner loads the seed, as the build must expect it: through the
448+
* platform's own seed path (`seedApp` in `orchestrate.ts`), not the data API a
449+
* person writes through. The rows are established facts: the state machine's
450+
* entry check is skipped, every other validation rule and hook judges each
451+
* row, and no record-triggered flow fires on it. So a field a build derives
452+
* with an after-save flow stays empty on every loaded row (asset_lifecycle's
453+
* department scoping fields left a manager seeing none of the department's
454+
* rows), and a rule that judges a row against a total the loaded rows already
455+
* count (a payment against its invoice's balance) refuses the history.
456+
*/
457+
export const SEED_POSTURE =
458+
'The rows are loaded through the platform’s seed path as established facts, not as new records entering their lifecycle: ' +
459+
'each row is still judged by every validation rule and hook except the state machine’s entry check, and no record-triggered flow fires on it. ' +
460+
'So a value derived from other fields or rows (a department copied from a related row to scope access, an amount, a flag) must be a formula or a field computed by an expression when written, ' +
461+
'never set by a record-triggered flow, or every loaded row keeps it empty. ' +
462+
'And a loaded row is already counted in the stored totals of the rows it relates to (a payment in its invoice’s balance), ' +
463+
'so a validation rule must not refuse it by comparing it with such a total.';
464+
446465
/** The runner's contract, appended to every build prompt. */
447466
export function dataContract(card: Card): string {
448467
const lines: string[] = [];
449468
lines.push('## What the app will be loaded with and used by');
450469
lines.push('');
451470
lines.push(
452-
'After you finish, a test runner loads the rows below through the data API and signs each person in. ' +
471+
'After you finish, a test runner loads the rows below and signs each person in. ' +
453472
'Use these object and field machine names exactly (lookup values are the `id` of the referenced row), ' +
454473
'and make every value shown valid for its field. The object names already carry this app’s namespace prefix.',
455474
);
456475
lines.push('');
476+
lines.push(SEED_POSTURE);
477+
lines.push('');
457478
lines.push(namingRule(card));
458479
lines.push('');
459480
lines.push('```json');

‎packages/qa/scenarios/src/score/scenario-run-grade.ts‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,29 @@ function rowCounts(calls: readonly RunToolCall[]): Set<number> {
343343
return out;
344344
}
345345

346+
/**
347+
* Which of the numbers `written` (as {@link writtenNumbers} reads a reply) the
348+
* data supports: each one some value in `served` holds, or the sum or the
349+
* difference of two OTHER numbers the same reply writes that `served` holds
350+
* ("45.5 days of annual leave and 9 unpaid, 54.5 in all"; "249 tickets, 20
351+
* with no reply, so 229"). The operands must stand in the reply itself, so a
352+
* derived figure is one a reader can check against the served ones, never a
353+
* number that merely happens to equal the sum of two values somewhere in the
354+
* outputs. A difference of two equal figures (a zero) supports nothing: the reply
355+
* writing one figure twice derives no zero from the data. One step only: a figure
356+
* derived from a derived figure is not supported,
357+
* and neither is a product, a ratio or a sum of a column the reply does not write
358+
* out. The cost: an invented figure that happens to equal the sum or difference
359+
* of two served figures the reply writes is not caught.
360+
*/
361+
function supportedNumbers(written: readonly number[][], served: ReadonlySet<number>): boolean[] {
362+
const operands = written.map((values) => values.filter((n) => served.has(n)));
363+
const same = (a: number, b: number) => Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(b));
364+
const derived = (n: number, at: number) =>
365+
operands.some((as, i) => i !== at && as.some((a) => operands.some((bs, j) => j !== at && j !== i && bs.some((b) => same(a + b, n) || (!same(a, b) && same(a - b, n))))));
366+
return written.map((values, at) => operands[at]!.length > 0 || values.some((n) => derived(n, at)));
367+
}
368+
346369
function isBag(v: unknown): v is Record<string, unknown> {
347370
return typeof v === 'object' && v !== null && !Array.isArray(v);
348371
}
@@ -949,10 +972,12 @@ const USER_ACCOUNTS = /\b(?:user|login|sign-in) accounts?\b|用户账[号户]/i;
949972
* - An `unanswerable` truth: `correct` is a decline that states no figure
950973
* the data cannot support — every number the reply writes is one some
951974
* tool output of the turn carries ({@link carriedNumbers}; a unit number
952-
* is carried when either of its readings is), or a count of the rows
953-
* one returned, overall or per field value ({@link rowCounts}). So a
975+
* is carried when either of its readings is), a count of the rows
976+
* one returned, overall or per field value ({@link rowCounts}), or the
977+
* sum or difference of two such numbers the reply also writes
978+
* ({@link supportedNumbers}). So a
954979
* decline that shows the rows it checked ("no tax rate field; INV-002
955-
* totals 120", "30 laptops, 23 in use") is correct, and one that guesses
980+
* totals 120", "30 laptops, 23 in use", "45.5 + 9 = 54.5 days") is correct, and one that guesses
956981
* ("it is probably 13%", "about 12 expire under a 3-year term") is not,
957982
* in any wording. The cost: an invented figure equal to a number some
958983
* tool output happens to carry or count (0, 1 and small counts are
@@ -1008,7 +1033,7 @@ export function gradePersonaRun(input: PersonaRunInput, turn: RunTranscript): Pe
10081033
const declined = declines(turn.replyText) || refusedWithoutFigure(turn);
10091034
if (input.personaTruth.kind === 'unanswerable') {
10101035
const carried = new Set([...carriedNumbers(turn.toolCalls), ...rowCounts(turn.toolCalls)]);
1011-
const supported = writtenNumbers(turn.replyText).every((values) => values.some((n) => carried.has(n)));
1036+
const supported = supportedNumbers(writtenNumbers(turn.replyText), carried).every(Boolean);
10121037
return {
10131038
correct: declined && supported,
10141039
cited: true,

‎packages/qa/scenarios/test/library.test.ts‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import { dirname, resolve } from 'node:path';
1414
import { fileURLToPath } from 'node:url';
1515
import { describe, expect, it } from 'vitest';
1616

17-
import { formatRefusal, loadScenarios, readCapabilityAreas, type Truth } from '../src/index.js';
17+
import { SelectOptionSchema } from '@objectstack/spec/data';
18+
19+
import { formatRefusal, loadScenarios, readCapabilityAreas, truthsOver, type Truth } from '../src/index.js';
1820
import { promptLanguageGaps } from '../src/runner/prompts.js';
1921

2022
const HERE = dirname(fileURLToPath(import.meta.url));
@@ -160,6 +162,83 @@ describe('the open scenario library (docs/qa/scenarios)', () => {
160162
});
161163
}
162164

165+
it('every seed value of a single-choice field the card asks for is a valid option value', () => {
166+
// An option value is a lowercase machine identifier (`SelectOptionSchema.value`), so a build
167+
// can only declare options the platform accepts; a seed value no option can hold is refused,
168+
// with every row that looks it up (requisition_to_receipt's `supplier.rating` "A"/"B"/"C").
169+
const invalid: string[] = [];
170+
for (const { card } of result.cards) {
171+
for (const { object, field } of card.expect.selectFields ?? []) {
172+
for (const row of card.run.seed[object] ?? []) {
173+
const v = row[field];
174+
if (v === null || v === undefined) continue;
175+
if (!SelectOptionSchema.safeParse({ label: String(v), value: v }).success) invalid.push(`${card.id}: ${object}.${field} = ${JSON.stringify(v)}`);
176+
}
177+
}
178+
}
179+
expect(invalid).toEqual([]);
180+
});
181+
182+
it('a seed row dated after the card\'s asOf is a plan (a due, start, end or expected date), never a fact the card treats as done', () => {
183+
// travel_expense's step `as_118_2` was decided 2026-11-02, after its asOf 2026-10-31: the agent
184+
// rightly refused to pay a claim over a future-dated approval. Each card's future-dated fields, pinned.
185+
const future: Record<string, string[]> = {};
186+
for (const { card } of result.cards) {
187+
if (card.asOf === undefined) continue;
188+
const fields = new Set<string>();
189+
for (const [object, rows] of Object.entries(card.run.seed)) {
190+
for (const row of rows) {
191+
for (const [field, v] of Object.entries(row)) {
192+
if (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v) && v.slice(0, 10) > card.asOf) fields.add(`${object}.${field}`);
193+
}
194+
}
195+
}
196+
if (fields.size > 0) future[card.id] = [...fields].sort();
197+
}
198+
expect(future).toEqual({
199+
asset_lifecycle: ['checkout.due_on'],
200+
leave_balances: ['leave_day.leave_date', 'leave_request.end_date', 'leave_request.start_date'],
201+
order_to_cash: ['invoice.due_date'],
202+
requisition_to_receipt: ['purchase_order.expected_date'],
203+
travel_expense: ['trip_request.end_date', 'trip_request.start_date'],
204+
});
205+
});
206+
207+
it('a last-N-days truth counts no row on the extra day the platform\'s preset adds (last_30_days spans 31 days ending on asOf)', () => {
208+
// The card's `last_days` window is the N days ending on asOf; the platform's
209+
// `last_N_days` preset runs from N days before asOf, one day more. A row on that
210+
// day makes an app that uses the preset answer differently from the card.
211+
const ambiguous: string[] = [];
212+
for (const loaded of result.cards) {
213+
const widened = structuredClone(loaded.card);
214+
const ids: string[] = [];
215+
for (const q of widened.run.questions) {
216+
for (const f of 'filter' in q.truth ? (q.truth.filter ?? []) : []) {
217+
if (f.op === 'in_window' && typeof f.value === 'object' && f.value !== null && 'kind' in f.value && f.value.kind === 'last_days') {
218+
f.value = { kind: 'last_days', days: f.value.days + 1 };
219+
ids.push(q.id);
220+
}
221+
}
222+
}
223+
if (ids.length === 0) continue;
224+
const wide = truthsOver(widened, loaded.card.run.seed);
225+
for (const id of [...new Set(ids)]) {
226+
if (JSON.stringify([wide.truths[id], wide.personaTruths[id]]) !== JSON.stringify([loaded.truths[id], loaded.personaTruths[id]])) ambiguous.push(`${loaded.card.id}/${id}`);
227+
}
228+
}
229+
// order_to_cash's PAY-0044 (2026-10-01) is the one left: the same defect, outside this change's cards.
230+
expect(ambiguous).toEqual(['order_to_cash/collected_by_team_last_30_days']);
231+
});
232+
233+
it('every card tagged for a report asks for one in its detailed prompt, in both languages', () => {
234+
// The Build check `dashboards.report` grades a report the prompt never asked for otherwise.
235+
const silent = result.cards
236+
.filter(({ card }) => card.capabilities.includes('dashboards.report'))
237+
.filter(({ card }) => !/\breport\b/i.test(card.prompt.detailed.en ?? '') || !/报表/.test(card.prompt.detailed.zh ?? ''))
238+
.map(({ card }) => card.id);
239+
expect(silent).toEqual([]);
240+
});
241+
163242
it('reads the capability areas from the checklist tree', () => {
164243
// A closed set read from disk, not a list kept here: the assertion is only
165244
// that it is non-trivial and holds an area every seed card uses.

0 commit comments

Comments
 (0)