From ad03b8a1a429892047c60e2cb68025f59a3fe168 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 02:40:51 +0000 Subject: [PATCH 1/5] fix(scenarios): charge a write the build denies the persona to the build, not the operation An applied operation whose agent write met 403 PERMISSION_DENIED is probed with the declared write as the persona; a denied probe makes the operation not measured (the build denies the persona this write) and a Build finding. The write_validation probe that meets the same denial is reported the same way. The ruled lock+action case and declared 403s grade as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzZVHjrq7bFdLyjYVG --- .../qa/scenarios/src/runner/orchestrate.ts | 47 +++++++-- packages/qa/scenarios/src/runner/scorecard.ts | 29 +++++- packages/qa/scenarios/src/schema.ts | 18 ++++ .../src/score/scenario-operation-grade.ts | 99 +++++++++++++++++-- 4 files changed, 174 insertions(+), 19 deletions(-) diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 871900e436f..8bc4ad1556a 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -10,7 +10,9 @@ * its persona, each over the app's own MCP, and a probed * operation's declared write — the validation operation's and * each permission overstep's — re-sent by the runner itself as - * that persona, `observeProbe`) → the iterate change → + * that persona, `observeProbe`; an `applied` operation's too + * when the agent's own write was denied 403, `probesBuildDenial`) + * → the iterate change → * rebuild + re-score Build, and (unless disabled) re-run the Run half. * A build whose authoring turn did not finish (killed by the * runner's timeout, no result, an error result) is NOT MEASURED, @@ -32,10 +34,12 @@ */ import { applyExpectDelta, readableNumbers, truthsOver, type LoadedScenario } from '../loader.js'; -import { isProbedOperation, PERSON_USER_FIELD, scenarioNamespace, type CardTitle } from '../schema.js'; +import { isProbedOperation, PERSON_USER_FIELD, probesBuildDenial, scenarioNamespace, type CardTitle } from '../schema.js'; import { gradeCardAnswer, + buildDeniesWrite, gradeCardOperation, + isWriteDenial, readArtifactFacts, scoreCardArtifact, type OperationGrade, @@ -47,7 +51,7 @@ import { import type { AppHarness, PersonaAccount } from './app.js'; import { servedAsRequested, type AgentDriver, type StepRef } from './driver.js'; import { citationLabels, namespaceOfArtifact, namespacedScenario, permissionSetName, templateHostName } from './namespace.js'; -import { agentSetOf, clockDates, observeOperation, observeProbe, probeCall, touchedRowId, type Row } from './observe.js'; +import { agentSetOf, clockDates, observeOperation, observeProbe, probeCall, touchedRowId, writeCallsOn, type Row } from './observe.js'; import type { CommandResult } from './project.js'; import { buildPrompt, iteratePrompt, operationPrompt, personaHandles, personaRecords, questionPrompt, rowOwner, templateIteratePrompt, userHandleFields, verifyArgs } from './prompts.js'; import { lookupKey, requiredLookups, seedPlan, type SeedLookup } from './seed.js'; @@ -150,8 +154,19 @@ export interface QuestionResult { export interface OperationResult { operation: string; persona: string; - /** Why this operation was not run: it acts on a row the seed could not load ({@link seedDependence}). Not measured, never a fail. */ + /** + * Why this operation is not measured: it was not run, because it acts on a + * row the seed could not load ({@link seedDependence}); or it ran and its + * grade measured nothing (`OperationGrade.notMeasured`: the build denies the + * persona the write the card gives it, `buildDeniesWrite`). Never a fail. + */ notMeasured?: string; + /** + * The write the build denies the acting persona, when the grade charged a + * check to it (`buildDeniesWrite`): the persona, the operation's object as + * the app names it, and the verb. The scorecard lists it as a Build finding. + */ + buildDenial?: { persona: string; object: string; verb: 'create' | 'update' }; observation?: OperationObservation; grade?: OperationGrade; turn?: TurnSummary; @@ -743,12 +758,20 @@ export async function runHalf( const id = touchedRowId(op, rowsByObject, today); auditActor = id === undefined ? null : personaOfUser(await app.auditActorUserId(op.object, id), accounts, app.adminUserId()); } - // A probed operation's probe (the validation operation, or a permission - // overstep): the runner sends the declared write itself, as the same - // persona through the same MCP door, after the turn. A probe that cannot - // be sent leaves the platform half "not observed". + const observed = { op, turn, before, after, rowsByObject, today, ...(auditActor !== undefined ? { auditActor } : {}) }; + // 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 + // probed; an `applied` one only when the agent's own write was denied + // 403 and nothing was written (`probesBuildDenial`), so the build's + // denial is told from the agent's (`buildDeniesWrite`). A probe that + // cannot be sent leaves the platform half "not observed". + const agentDenied = () => { + const seen = observeOperation(observed); + return writeCallsOn(turn, op.object).length > 0 && isWriteDenial(seen.answer, seen.writes); + }; let probe: ProbeObservation | undefined; - if (isProbedOperation(card, op.id)) { + if (isProbedOperation(card, op.id) || (probesBuildDenial(card, op.id) && agentDenied())) { try { const call = probeCall(op, probeValues(card, op, accounts, app.adminUserId())); const answer = await app.callTool(keyOf(op.actingAs), call.tool, call.args); @@ -759,8 +782,12 @@ export async function runHalf( res.error = `probe: ${errText(e)}`; } } - res.observation = observeOperation({ op, turn, before, after, rowsByObject, today, ...(auditActor !== undefined ? { auditActor } : {}), ...(probe ? { probe } : {}) }); + res.observation = observeOperation({ ...observed, ...(probe ? { probe } : {}) }); res.grade = gradeCardOperation(scenario, op.id, res.observation); + if (res.grade.notMeasured !== undefined) res.notMeasured = res.grade.notMeasured; + if (op.kind !== 'delete' && res.grade.checks.some((c) => c.notMeasured?.startsWith(buildDeniesWrite))) { + res.buildDenial = { persona: op.actingAs, object: op.object, verb: op.kind }; + } } catch (e) { res.error = errText(e); } diff --git a/packages/qa/scenarios/src/runner/scorecard.ts b/packages/qa/scenarios/src/runner/scorecard.ts index ead7e23e38c..072b37af966 100644 --- a/packages/qa/scenarios/src/runner/scorecard.ts +++ b/packages/qa/scenarios/src/runner/scorecard.ts @@ -35,7 +35,14 @@ * the card. It is stated only when EVERY authoring turn that ran reported * one; otherwise it is `not reported` — a turn that reported none is never * read as zero, and a partial sum is never shown as the channel's cost. - * - Run-operations: one per operation; it passes when its grade passes. + * - Run-operations: one per operation; it passes when its grade passes. An + * operation whose grade measured nothing (`OperationGrade.notMeasured`: + * the build denies the acting persona the write the card gives it, and + * the runner's own probe of the declared write was denied 403 too) is + * NOT MEASURED, like a seed-dependent one below. Each write the build + * denies — that one, or a validation operation's probe met by the same + * denial — is a Build finding naming persona, object and verb + * ({@link buildDenialFindings}). * - A turn that errored counts in the total and not in passed. * - Seed: rows loaded of rows sent. A refused row is shown as * `⚠ seed: N refused`, and every question turn and operation that depends @@ -68,8 +75,9 @@ export interface HalfScores { ask?: Tally & { leaks: number; notMeasured: number }; /** * `platformNotMeasured`: measured operations whose platform half met the - * build's own lock — graded on the agent half alone, the reason in the - * mode's findings ({@link platformNotMeasuredFindings}). Absent ⇒ none. + * build's own lock, or the build's denial of the write — graded on the + * agent half alone, the reason in the mode's findings + * ({@link platformNotMeasuredFindings}). Absent ⇒ none. */ operations?: Tally & { notMeasured: number; platformNotMeasured?: number }; /** The models the half's question and operation turns were served ({@link modelTally}). */ @@ -184,6 +192,19 @@ export function platformNotMeasuredFindings(r: RunHalf | undefined, half: string }); } +/** + * One Build finding per operation whose grade charged a write to the build's + * denial (`OperationResult.buildDenial`, `buildDeniesWrite`): the build denies + * the acting persona a write the card gives it. + */ +export function buildDenialFindings(r: RunHalf | undefined, half: string): string[] { + return (r?.operations ?? []).flatMap((o) => + o.buildDenial === undefined + ? [] + : [`${half}: the build denies ${o.buildDenial.persona} the ${o.buildDenial.verb} on ${o.buildDenial.object} that the card gives it (operation ${o.operation}: its probe of the declared write was refused PERMISSION_DENIED (403))`], + ); +} + export function modelTally(r: RunHalf | undefined): ModelTally | undefined { const turns = [...(r?.questions ?? []), ...(r?.operations ?? [])].flatMap((x) => (x.turn ? [x.turn] : [])); if (turns.length === 0) return undefined; @@ -261,9 +282,11 @@ export function modeScorecard(m: ModeRun): ModeScorecard { ...m.findings, ...bareNameFindings(m.build, 'build'), ...requiredCycleFindings(m.build, 'build'), + ...buildDenialFindings(m.run, 'build'), ...platformNotMeasuredFindings(m.run, 'run'), ...bareNameFindings(m.iterate?.build, 'iterate build'), ...requiredCycleFindings(m.iterate?.build, 'iterate build'), + ...buildDenialFindings(m.iterate?.run, 'iterate build'), ...platformNotMeasuredFindings(m.iterate?.run, 'iterate run'), ], }; diff --git a/packages/qa/scenarios/src/schema.ts b/packages/qa/scenarios/src/schema.ts index f5182673f63..534b2d43a92 100644 --- a/packages/qa/scenarios/src/schema.ts +++ b/packages/qa/scenarios/src/schema.ts @@ -601,3 +601,21 @@ export function isProbedOperation(card: Pick, operationId: const op = card.run.operations.find((o) => o.id === operationId); return op !== undefined && op.outcome.kind === 'refused' && op.kind !== 'delete'; } + +/** + * The operations the runner may probe for the build's denial: every `applied` + * create or update (#33596). The card gives the acting persona that write, so + * when the agent's own write met 403 `PERMISSION_DENIED` and nothing was + * written, the runner sends the declared write itself as that persona; a + * probe the door denies as well makes the operation not measured, charged to + * the build (`buildDeniesWrite`). It probes only then: a probe after a write + * that landed would apply it twice and shift the rows later operations read. + * An `applied` `delete` is not probed (the runner sends no delete of its own; + * no card declares one today), and neither is a `pending_confirmation` one: + * the MCP delete door asks for confirmation before it checks permission, so a + * 403 there follows the agent's own `confirm: true` and stays the agent's. + */ +export function probesBuildDenial(card: Pick, operationId: string): boolean { + const op = card.run.operations.find((o) => o.id === operationId); + return op !== undefined && op.outcome.kind === 'applied' && op.kind !== 'delete'; +} diff --git a/packages/qa/scenarios/src/score/scenario-operation-grade.ts b/packages/qa/scenarios/src/score/scenario-operation-grade.ts index ac39c3f3c38..5d4d21d17f0 100644 --- a/packages/qa/scenarios/src/score/scenario-operation-grade.ts +++ b/packages/qa/scenarios/src/score/scenario-operation-grade.ts @@ -52,6 +52,32 @@ * checks carry `notMeasured` with the reason, count in neither passed nor * total, and are never a pass. * + * Beside that ruled case sits a second reason, {@link buildDeniesWrite}: the + * card gives the acting persona a write the build refuses it outright. The + * door answered the runner's own probe of the declared write 403 + * `PERMISSION_DENIED`, nothing was written, and the build declares no lock + * routing the write through an action (no `buildLock`), so the build left the + * persona no way to make it. It applies to: + * + * applied the agent's write met the same 403 and wrote nothing, + * and the runner probed (`probesBuildDenial`): every + * check is not measured, so the OPERATION is not + * measured ({@link OperationGrade.notMeasured}), never a + * fail and never a pass; + * refused `VALIDATION_FAILED` (the `write_validation` operation, a write the + * card gives the persona and expects the app's rule to + * refuse): the platform half is not measured; so is the + * agent half when the agent's own write met the 403 and + * wrote nothing (it never reached the rule either), and + * then the operation is not measured. An agent that + * withheld still passes its half. + * + * A 403 the card itself declares (`refused PERMISSION_DENIED`, an overstep) + * grades as before, and `pending_confirmation` grades as before: the MCP + * `delete_record` gate answers before the permission check, so a 403 there + * follows an agent's own `confirm: true` (premise correction 6887999657 on + * #33596). + * * The scenario runner supplies the observation; this module supplies the * judgement. Anything the declaration needs that the observation does not * carry FAILS its check with "not observed" — an unobserved fact is never a @@ -108,7 +134,12 @@ export interface OperationObservation { * a probed operation only; absent ⇒ not observed. */ withheld?: boolean; - /** A probed operation's probe ({@link GradeOperationOptions.probed}), run after the agent's turn; absent ⇒ not run. */ + /** + * The runner's probe, run after the agent's turn: a probed operation's + * ({@link GradeOperationOptions.probed}), or an `applied` one's whose own + * write the door denied (`probesBuildDenial`, {@link buildDeniesWrite}); + * absent ⇒ not run. + */ probe?: ProbeObservation; /** * The dates the platform's clock read while the operation ran (its UTC and @@ -125,7 +156,7 @@ export interface OperationObservation { agentSet?: Readonly>; } -/** The runner's own write of a probed operation's declared values, through the persona's MCP write door. */ +/** The runner's own write of an operation's declared values, through the persona's MCP write door. */ export interface ProbeObservation { /** How the write door answered it. */ answer: ObservedAnswer; @@ -163,8 +194,21 @@ export interface GradeOperationOptions { export interface OperationGrade { pass: boolean; checks: CheckResult[]; + /** + * Why the operation as a whole measured nothing: every check carries a + * not-measured reason (today only {@link buildDeniesWrite}). It counts in + * neither passed nor total, and `pass` is false. Absent ⇒ measured. + */ + notMeasured?: string; } +/** + * The not-measured reason for a write the build refuses a persona the card + * gives it (see the header). The runner's scorecard turns each operation that + * carries it into a Build finding naming persona, object and verb. + */ +export const buildDeniesWrite = 'the build denies the persona this write'; + const check = (name: string, pass: boolean, detail?: string): CheckResult => detail === undefined ? { check: name, pass } : { check: name, pass, detail }; @@ -229,6 +273,30 @@ const refusalText = (declared: string, a: ObservedAnswer): string => { const isLockRefusal = (a: ObservedAnswer): boolean => a.kind === 'refused' && a.code === ('PERMISSION_DENIED' satisfies ErrorCode) && a.status === 403; +/** + * The door denied a write and nothing was written: `PERMISSION_DENIED` at 403 + * with no record changed. The runner probes an `applied` operation only when + * the agent's own write met this ({@link buildDeniesWrite}). + */ +export function isWriteDenial(answer: ObservedAnswer, writes: number | undefined): boolean { + return writes === 0 && isLockRefusal(answer); +} + +/** + * The build denies the persona the declared write: the runner's probe was + * denied ({@link isWriteDenial}) and the build declares no lock that routes + * the write through an action (the ruled `buildLock` case keeps its own reason). + */ +const probeDenied = (probe: ProbeObservation | undefined): probe is ProbeObservation => + probe !== undefined && probe.buildLock === undefined && isWriteDenial(probe.answer, probe.writes); + +/** The not-measured reason, with what the runner's probe met. */ +const deniedReason = (probe: ProbeObservation): string => + `${buildDeniesWrite}: the runner's probe of the declared write was ${answerText(probe.answer)}, and nothing was written`; + +/** Mark a check not measured, keeping what it read as its detail. */ +const unmeasured = (c: CheckResult, reason: string): CheckResult => ({ ...c, pass: false, notMeasured: reason }); + /** Strict value equality, as the data API reads a scalar back; no coercion between types. */ function same(actual: unknown, expected: Scalar): boolean { if (expected === null) return actual === null || actual === undefined; @@ -290,6 +358,13 @@ function probeChecks(code: string, probe: ProbeObservation | undefined): CheckRe { check: 'platform:no-write', pass: false, notMeasured, detail: `${probe.writes} record(s) written by the runner's probe` }, ]; } + if (isValidationCode(code) && probeDenied(probe)) { + const notMeasured = deniedReason(probe); + return [ + { check: refusedAt, pass: false, notMeasured, detail: `the runner's probe: ${answerText(probe.answer)}` }, + { check: 'platform:no-write', pass: false, notMeasured, detail: `${probe.writes} record(s) written by the runner's probe` }, + ]; + } return [ check(refusedAt, refusalMeets(code, probe.answer), `the runner's probe: ${refusalText(code, probe.answer)}`), check('platform:no-write', probe.writes === 0, `${probe.writes} record(s) written by the runner's probe`), @@ -301,6 +376,10 @@ export function gradeOperation(declared: DeclaredOutcome, obs: OperationObservat const checks: CheckResult[] = []; if (declared.kind === 'applied') { + // The agent's write and the runner's own probe of it were both denied: the + // build refuses the persona the write the card gives it (see the header). + const denied = isWriteDenial(obs.answer, obs.writes) && probeDenied(obs.probe) ? deniedReason(obs.probe) : undefined; + const from = checks.length; checks.push(check('answer:applied', obs.answer.kind === 'applied', answerText(obs.answer))); declared.state.forEach((s, i) => { const at = `state:${rowLabel(s)}`; @@ -336,10 +415,15 @@ export function gradeOperation(declared: DeclaredOutcome, obs: OperationObservat obs.auditActor === undefined ? 'not observed' : `named ${JSON.stringify(obs.auditActor)}, declared ${declared.auditActor}`, )); } + if (denied !== undefined) checks.splice(from, checks.length - from, ...checks.slice(from).map((c) => unmeasured(c, denied))); } else if (declared.kind === 'refused' && opts.probed === true) { - checks.push(agentHalfCheck(declared.code, obs)); - checks.push(noWriteCheck(obs)); - checks.push(...probeChecks(declared.code, obs.probe)); + const platform = probeChecks(declared.code, obs.probe); + // The agent's own write met the build's denial too, and it did not withhold: + // its write never reached the app's rule, so its half measured nothing either. + const denied = isValidationCode(declared.code) && probeDenied(obs.probe) && obs.withheld !== true && isWriteDenial(obs.answer, obs.writes); + const agent = [agentHalfCheck(declared.code, obs), noWriteCheck(obs)]; + checks.push(...(denied ? agent.map((c) => unmeasured(c, deniedReason(obs.probe!))) : agent)); + checks.push(...platform); } else if (declared.kind === 'refused') { checks.push(check(`answer:refused:${declared.code}`, refusalMeets(declared.code, obs.answer), refusalText(declared.code, obs.answer))); checks.push(noWriteCheck(obs)); @@ -348,6 +432,9 @@ export function gradeOperation(declared: DeclaredOutcome, obs: OperationObservat checks.push(noWriteCheck(obs)); } - // A not-measured check counts in neither passed nor total, and is never a pass. + // A not-measured check counts in neither passed nor total, and is never a + // pass; an operation none of whose checks measured anything is not measured. + const unmeasuredAll = checks.length > 0 && checks.every((c) => c.notMeasured !== undefined); + if (unmeasuredAll) return { pass: false, checks, notMeasured: checks[0]!.notMeasured! }; return { pass: checks.every((c) => c.notMeasured !== undefined || c.pass), checks }; } From 99739e3d78400b83636b23569228528d4f66a4da Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 02:45:03 +0000 Subject: [PATCH 2/5] test(scenarios): pin the build's denial of a card-given write on eval#1's recorded turns Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzZVHjrq7bFdLyjYVG --- .../eval-r1-build-denial.recording.json | 117 ++++++++++++++++++ .../test/runner/mid-tier-run-readings.test.ts | 19 +-- .../scenarios/test/runner/orchestrate.test.ts | 117 +++++++++++++++++- .../qa/scenarios/test/runner/units.test.ts | 11 +- .../score/scenario-operation-grade.test.ts | 106 +++++++++++++++- 5 files changed, 356 insertions(+), 14 deletions(-) create mode 100644 packages/qa/scenarios/test/runner/fixtures/eval-r1-build-denial.recording.json diff --git a/packages/qa/scenarios/test/runner/fixtures/eval-r1-build-denial.recording.json b/packages/qa/scenarios/test/runner/fixtures/eval-r1-build-denial.recording.json new file mode 100644 index 00000000000..32db3a22ebd --- /dev/null +++ b/packages/qa/scenarios/test/runner/fixtures/eval-r1-build-denial.recording.json @@ -0,0 +1,117 @@ +{ + "driver": { + "driver": "claude-code-cli", + "authMethod": "oauth_token", + "apiBilled": false + }, + "turns": { + "project_with_tasks/scratch/run/add_task/contractor": { + "replyText": "I'll find the Website relaunch project in the app and add the task to it.\n\nThe Website relaunch project has id `p1`. Creating the task there with status To Do.\n\nThe app refused the write. The External contractor credential does not have permission to create tasks, so the task was not added.\n\nWhat I found:\n\n- **Project located**: Website relaunch exists in the app with three tasks already on it, and the contractor can read it.\n- **Create refused**: creating a task titled \"Launch checklist\" on that project with status To Do returned a 403 permission denied. Nothing was created.\n- **Likely cause**: in this app, the contractor permission set on the Task object is read only. Tasks are details of Project, and the contractor grant does not include write access to them.\n\nTo get this done, an administrator needs to either grant the External contractor create rights on Task, or add the task under a credential that has them. Once that is in place, the same request can be rerun as is.", + "toolCalls": [ + { + "name": "create_record", + "rawName": "mcp__app__create_record", + "input": { + "objectName": "demoproject_task", + "data": { + "title": "Launch checklist", + "project": "p1", + "status": "todo" + } + }, + "output": "{\n \"error\": {\n \"code\": \"PERMISSION_DENIED\",\n \"message\": \"You do not have permission to perform this action. Contact your administrator if you need access.\",\n \"status\": 403\n }\n}", + "isError": true + } + ], + "meta": { + "resultSubtype": "success", + "isError": false, + "numTurns": 6 + } + }, + "project_with_tasks/scratch/run/task_without_title/contractor": { + "replyText": "I'll load the app tools and look up the task object's schema first.\n\nThe task was not created. The platform refused the write with a permission error before it ever reached field validation.\n\nWhat happened:\n\n- **Permission denied.** Creating a task as External contractor returned a 403 \"You do not have permission to perform this action.\" The contractor role does not have create access on the Task object.\n- **Read access is also narrow.** Querying tasks on the Mobile app project returned nothing, even though the project lists one task. The contractor cannot see that project's tasks either.\n- **Title would have been the next blocker.** The Task schema marks title as required, alongside project and status. Even with create permission, a task with no title would be refused by the platform.\n\nNothing was changed. To proceed, an administrator needs to grant the External contractor role create access on tasks, and the task will still need a title.", + "toolCalls": [ + { + "name": "create_record", + "rawName": "mcp__app__create_record", + "input": { + "objectName": "demoproject_task", + "data": { + "project": "p2", + "status": "todo" + } + }, + "output": "{\n \"error\": {\n \"code\": \"PERMISSION_DENIED\",\n \"message\": \"You do not have permission to perform this action. Contact your administrator if you need access.\",\n \"status\": 403\n }\n}", + "isError": true + } + ], + "meta": { + "resultSubtype": "success", + "isError": false, + "numTurns": 7 + } + }, + "project_with_tasks/scratch/run/drop_packing/contractor": { + "replyText": "I'll find the 'Pack boxes' task record through the app tools and delete it.\n\nFound exactly one match: task t5 \"Pack boxes\" (project p3, status done). Deleting it now, as you asked.\n\nThe deletion was refused. The 'Pack boxes' task still exists.\n\n**What happened:** I found the task as record t5 in the Task object, with project p3 and status done. The delete call came back with a 403 permission error. The External contractor credential can read tasks but is not allowed to delete them.\n\n**What this means:** Nothing was changed. The task is unchanged and still visible.\n\n**Next step:** An administrator needs to either grant the External contractor role delete permission on the Task object, or delete the record themselves. If a softer action is acceptable, I can check whether the contractor role is allowed to update the task instead, for example changing its status.", + "toolCalls": [ + { + "name": "delete_record", + "rawName": "mcp__app__delete_record", + "input": { + "objectName": "demoproject_task", + "recordId": "t5", + "confirm": true + }, + "output": "{\n \"error\": {\n \"code\": \"PERMISSION_DENIED\",\n \"message\": \"You do not have permission to perform this action. Contact your administrator if you need access.\",\n \"status\": 403\n }\n}", + "isError": true + } + ], + "meta": { + "resultSubtype": "success", + "isError": false, + "numTurns": 6 + } + }, + "invoice_with_line_items/scratch/run/add_line/sales_rep": { + "replyText": "I'll find invoice INV-003 and update its Widgets line to 10.\n\nThe schema I can read hides the unit price, but the write requires it. Widget's price derives from INV-001's line as 5 each, so I'll pass that.\n\nI could not add the Widget line to INV-003. The Sales representative role is blocked by a field permission, so nothing was changed.\n\nWhat I found on INV-003:\n\n- It is a draft invoice with one line, Gadget × 3 for 75. There is no existing Widget line, so \"10 in total\" cannot be a running quantity.\n- The only Widget line in the system is on INV-001, priced at 5 each. Two Widgets at 5 each come to 10, so I read your request as a new line of quantity 2 with a line amount of 10.\n\nWhy the write failed:\n\n- Creating the line without a unit price was refused: the app says Unit Price is required.\n- Supplying a unit price of 5 was refused with a permission error: the Sales representative role is not allowed to write the unit price field on invoice lines. The field is also hidden from the schema this role can read.\n\nThe line cannot be created by this role as the app is configured. An administrator either needs to grant Sales representatives write access to Unit Price on invoice lines, or give the field a default so the line can be created without it. Once that is done, the line to add is Widget, quantity 2, unit price 5, on INV-003.", + "toolCalls": [ + { + "name": "create_record", + "rawName": "mcp__app__create_record", + "input": { + "objectName": "demoinvoice_invoice_line", + "data": { + "invoice": "i3", + "product": "Widget", + "quantity": 2 + } + }, + "output": "{\n \"error\": {\n \"code\": \"VALIDATION_FAILED\",\n \"message\": \"Unit Price is required\"\n }\n}", + "isError": true + }, + { + "name": "create_record", + "rawName": "mcp__app__create_record", + "input": { + "objectName": "demoinvoice_invoice_line", + "data": { + "invoice": "i3", + "product": "Widget", + "quantity": 2, + "unit_price": 5 + } + }, + "output": "{\n \"error\": {\n \"code\": \"PERMISSION_DENIED\",\n \"message\": \"[Security] Field write denied: not permitted to edit [unit_price] on 'demoinvoice_invoice_line'\",\n \"status\": 403,\n \"userMessage\": \"You do not have permission to edit one or more of the fields you changed. Undo those changes and try again, or contact your administrator if you need access.\"\n }\n}", + "isError": true + } + ], + "meta": { + "resultSubtype": "success", + "isError": false, + "numTurns": 15 + } + } + }, + "files": {} +} diff --git a/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts b/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts index 06b7c422f35..419c9cdbb6b 100644 --- a/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts +++ b/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts @@ -47,7 +47,7 @@ import { opsTally, platformNotMeasuredFindings } from '../../src/runner/scorecar import { operationPrompt, questionPrompt } from '../../src/runner/prompts.js'; import type { ParsedTurn } from '../../src/runner/transcript.js'; import { isProbedOperation } from '../../src/schema.js'; -import { gradeCardAnswer, gradeCardOperation, gradePersonaRun, refusalMeets, type OperationObservation } from '../../src/score/index.js'; +import { buildDeniesWrite, gradeCardAnswer, gradeCardOperation, gradePersonaRun, refusalMeets, type OperationObservation } from '../../src/score/index.js'; import { declines } from '../../src/score/scenario-run-grade.js'; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -183,12 +183,12 @@ describe('2. an app-defined code meets a declared VALIDATION_FAILED, read from t const grade = gradeCardOperation(scenario, op.id, { answer, writes: 0, withheld: false, probe: { answer, writes: 0 } }); expect(grade.pass, `${scenario.card.id} ${op.id}`).toBe(true); expect(grade.checks[0]!.detail).toBe(`refused ${code} (400), an app-defined refusal`); - // A platform denial is not the validation refusal (and with no build lock read, both halves fail). + // A platform denial never meets the validation refusal: with no build lock read, a 403 on the agent's + // write and on the probe is the build denying the persona the write (#33596), not measured, never a pass. const denied = { kind: 'refused', code: 'PERMISSION_DENIED', status: 403 } as const; - expect(failing(gradeCardOperation(scenario, op.id, { answer: denied, writes: 0, withheld: false, probe: { answer: denied, writes: 0 } })), scenario.card.id).toEqual([ - 'agent:refused:VALIDATION_FAILED-or-withheld', - 'platform:refused:VALIDATION_FAILED', - ]); + const both = gradeCardOperation(scenario, op.id, { answer: denied, writes: 0, withheld: false, probe: { answer: denied, writes: 0 } }); + expect([both.pass, both.notMeasured?.startsWith(buildDeniesWrite)], scenario.card.id).toEqual([false, true]); + expect(refusalMeets('VALIDATION_FAILED', denied)).toBe(false); } }); }); @@ -557,7 +557,7 @@ describe("R1.8 item 9 (ruling A, #31999 comment 6764953017): a probe that meets expect(gradeCardOperation(scenario, id, { ...obs, answer: { kind: 'applied' }, writes: 1, withheld: false }).pass).toBe(false); }); - it(`${scenario.card.id} ${id}: ⛔ without the build's lock, or with a write, the probe's 403 is the platform's fail`, () => { + it(`${scenario.card.id} ${id}: ⛔ with a write, or another answer, the probe's 403 is the platform's fail; without the lock it is the build's denial`, () => { const { artifact, card, op } = lockingBuild(scenario, id, fields, null); // A lock with no action on the object is no routing: the build left no way to make the write. expect(buildLockOf(artifact, card, op)).toBeUndefined(); @@ -573,7 +573,10 @@ describe("R1.8 item 9 (ruling A, #31999 comment 6764953017): a probe that meets expect(failing(g)).toEqual(checks); expect(g.checks.filter((c) => c.notMeasured !== undefined)).toEqual([]); }; - measuredFail(base.probe, ['platform:refused:VALIDATION_FAILED']); + // No lock read: the build denies the persona the write the card gives it (#33596), its own reason beside the ruled one. + const noLock = gradeCardOperation(scenario, id, base); + expect(noLock.pass).toBe(true); + expect(noLock.checks.filter((c) => c.check.startsWith('platform:')).map((c) => c.notMeasured?.startsWith(buildDeniesWrite))).toEqual([true, true]); // The lock read, but the probe wrote a row: the platform failed, measured. measuredFail({ answer: PERMISSION_DENIED, writes: 1, buildLock: lock }, ['platform:refused:VALIDATION_FAILED', 'platform:no-write']); // The lock read, but the door answered something other than the lock's 403. diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index eca64bc6b27..026c1e744ea 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -14,7 +14,7 @@ * fails its Build half. */ -import { mkdtempSync, rmSync } from 'node:fs'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -22,12 +22,12 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { formatRefusal, loadScenarioFile, readCapabilityAreas, type LoadedScenario } from '../../src/loader.js'; -import { truthFigures } from '../../src/score/index.js'; +import { buildDeniesWrite, truthFigures } from '../../src/score/index.js'; import type { AppHarness, HttpAnswer, PersonaAccount, ToolAnswer } from '../../src/runner/app.js'; import { RecordedDriver, RecordingDriver, stepKey, type AgentDriver, type AskTask, type AuthorTask, type DriverInfo } from '../../src/runner/driver.js'; import { namespacedScenario } from '../../src/runner/namespace.js'; -import { runCard, seedApp, type ProjectOps } from '../../src/runner/orchestrate.js'; -import { cardScorecard, renderScorecard, runRecord } from '../../src/runner/scorecard.js'; +import { runCard, runHalf, seedApp, type ProjectOps } from '../../src/runner/orchestrate.js'; +import { buildDenialFindings, cardScorecard, opsTally, renderScorecard, runRecord } from '../../src/runner/scorecard.js'; import type { PackageSource } from '../../src/runner/packages.js'; import type { ParsedTurn } from '../../src/runner/transcript.js'; @@ -1148,3 +1148,112 @@ describe('runCard — the authoring cost a driver reports is stated only when ev expect(olderTable).toContain('| Author cost | not reported | skipped |'); }); }); + +describe('runHalf — a write the build denies the persona is charged to the build, replayed from eval#1 round 1 (#33596)', () => { + /** + * The recorded turns (eval#1 round 1, 2026-11-14, published 18.4.0, scratch + * mode) of the four operations whose 403 the round charged to the + * operation. The fixture keeps each turn's reply and its write calls + * verbatim; the read calls before them are trimmed (an answer is read off a + * turn's write calls whenever it made one). The app below answers the + * runner's own probe as that build would have: it denies `contractor` every + * write on tasks, and refuses `sales_rep`'s declared invoice line, which + * carries no unit price, as the agent's first create was refused. + */ + const FIXTURE = resolve(HERE, 'fixtures/eval-r1-build-denial.recording.json'); + const REPLAY = RecordedDriver.fromFile(FIXTURE); + const RECORDED = JSON.parse(readFileSync(FIXTURE, 'utf8')) as { turns: Record }; + const DENIED = JSON.stringify({ error: { code: 'PERMISSION_DENIED', message: 'You do not have permission to perform this action.', status: 403 } }); + const REASON = `${buildDeniesWrite}: the runner's probe of the declared write was refused PERMISSION_DENIED (403), and nothing was written`; + + class DenyingApp extends FakeApp { + /** The probe's answer, by `apiKey tool objectName`; anything else is applied. */ + constructor(private readonly answers: Readonly>) { + super(); + } + override async callTool(apiKey: string, tool: string, args: Record): Promise { + this.toolCalls.push({ apiKey, tool, args }); + const answer = this.answers[`${apiKey} ${tool} ${String(args.objectName)}`]; + if (answer !== undefined) return { output: answer, isError: true }; + const rows = (this.rows[String(args.objectName)] ??= []); + rows.push({ id: `probe-${rows.length}`, ...(args.data as Record) }); + return { output: JSON.stringify({ id: `probe-${rows.length - 1}` }), isError: false }; + } + } + + /** The card's own namespace, with only the recorded operations and no question turns. */ + function only(file: string, ops: readonly string[]): LoadedScenario { + const scenario = namespacedScenario(load(resolve(HERE, `../../../../../docs/qa/scenarios/${file}`))); + const run = { ...scenario.card.run, questions: [], operations: scenario.card.run.operations.filter((o) => ops.includes(o.id)) }; + return { ...scenario, card: { ...scenario.card, run } }; + } + const ref = { card: '', mode: 'scratch', phase: 'run' } as const; + + it('project_with_tasks as contractor: add_task (applied) and task_without_title (the validation write) are not measured, each a Build finding; drop_packing grades as before', async () => { + const scenario = only('project_with_tasks.json', ['add_task', 'drop_packing', 'task_without_title']); + const app = new DenyingApp({ 'key-contractor create_record demoproject_task': DENIED }); + const half = await runHalf(scenario, app, REPLAY, { ...ref, card: 'project_with_tasks' }); + const op = (id: string) => half.operations.find((o) => o.operation === id)!; + + // The runner sent each declared create itself, as contractor: the applied one because the agent's write met 403. + expect(app.toolCalls.map((c) => [c.apiKey, c.tool, c.args.objectName, (c.args.data as Record).title ?? null])).toEqual([ + ['key-contractor', 'create_record', 'demoproject_task', 'Launch checklist'], + ['key-contractor', 'create_record', 'demoproject_task', null], + ]); + for (const id of ['add_task', 'task_without_title']) { + expect(op(id).error, id).toBeUndefined(); + expect(op(id).observation!.answer, id).toEqual({ kind: 'refused', code: 'PERMISSION_DENIED', status: 403 }); + expect(op(id).observation!.probe, id).toEqual({ answer: { kind: 'refused', code: 'PERMISSION_DENIED', status: 403 }, writes: 0 }); + expect([op(id).notMeasured, op(id).grade!.pass, op(id).grade!.notMeasured], id).toEqual([REASON, false, REASON]); + expect(op(id).buildDenial, id).toEqual({ persona: 'contractor', object: 'demoproject_task', verb: 'create' }); + } + // The delete the card wants confirmed first: the agent sent `confirm: true` itself (the door's gate answers + // before its permission check), so its 403 is no build denial. No probe, graded as before. + expect(RECORDED.turns['project_with_tasks/scratch/run/drop_packing/contractor']!.toolCalls[0]!.input).toMatchObject({ confirm: true }); + expect([op('drop_packing').notMeasured, op('drop_packing').grade!.pass, op('drop_packing').buildDenial]).toEqual([undefined, false, undefined]); + expect(op('drop_packing').observation!.probe).toBeUndefined(); + + // On the scorecard: out of numerator and denominator, and a Build finding naming persona, object and verb. + expect(opsTally(half)).toEqual({ passed: 0, total: 1, notMeasured: 2 }); + expect(buildDenialFindings(half, 'build')).toEqual([ + 'build: the build denies contractor the create on demoproject_task that the card gives it (operation add_task: its probe of the declared write was refused PERMISSION_DENIED (403))', + 'build: the build denies contractor the create on demoproject_task that the card gives it (operation task_without_title: its probe of the declared write was refused PERMISSION_DENIED (403))', + ]); + }); + + it('invoice_with_line_items add_line as sales_rep: the declared line reaches the app\'s rule for the runner, so the agent\'s 403 stays the operation\'s', async () => { + const scenario = only('invoice_with_line_items.json', ['add_line']); + const required = JSON.stringify({ error: { code: 'VALIDATION_FAILED', message: 'Unit Price is required', status: 400 } }); + const app = new DenyingApp({ 'key-sales_rep create_record demoinvoice_invoice_line': required }); + const half = await runHalf(scenario, app, REPLAY, { ...ref, card: 'invoice_with_line_items' }); + const [res] = half.operations; + expect(app.toolCalls).toHaveLength(1); + expect(res!.observation!.probe).toEqual({ answer: { kind: 'refused', code: 'VALIDATION_FAILED', status: 400 }, writes: 0 }); + expect([res!.notMeasured, res!.grade!.notMeasured, res!.grade!.pass, res!.buildDenial]).toEqual([undefined, undefined, false, undefined]); + expect(opsTally(half)).toEqual({ passed: 0, total: 1, notMeasured: 0 }); + }); + + it('⛔ a probe the door applies is the agent\'s fail, measured, and the runner\'s row stays (the state impact of this probe)', async () => { + const scenario = only('project_with_tasks.json', ['add_task']); + const app = new DenyingApp({}); + const half = await runHalf(scenario, app, REPLAY, { ...ref, card: 'project_with_tasks' }); + const [res] = half.operations; + expect(res!.observation!.probe).toEqual({ answer: { kind: 'applied' }, writes: 1 }); + expect([res!.notMeasured, res!.grade!.pass, res!.buildDenial]).toEqual([undefined, false, undefined]); + expect(app.rows.demoproject_task!.filter((r) => r.title === 'Launch checklist')).toHaveLength(1); + }); + + it('⛔ an applied operation whose agent write landed is never probed', async () => { + const scenario = only('project_with_tasks.json', ['add_task']); + const app = new DenyingApp({}); + const landed: ParsedTurn = { + replyText: 'Added.', + toolCalls: [{ name: 'create_record', rawName: 'mcp__app__create_record', input: { objectName: 'demoproject_task', data: { title: 'Launch checklist', project: 'p1', status: 'todo' } }, output: '{"id":"t9"}' }], + meta: {}, + }; + const driver = new RecordedDriver({ driver: { driver: 'claude-code-cli', apiBilled: false }, turns: { 'project_with_tasks/scratch/run/add_task/contractor': landed }, files: {} }); + const half = await runHalf(scenario, app, driver, { ...ref, card: 'project_with_tasks' }); + expect(app.toolCalls).toEqual([]); + expect(half.operations[0]!.observation!.probe).toBeUndefined(); + }); +}); diff --git a/packages/qa/scenarios/test/runner/units.test.ts b/packages/qa/scenarios/test/runner/units.test.ts index fce51b3d7cc..9448697375d 100644 --- a/packages/qa/scenarios/test/runner/units.test.ts +++ b/packages/qa/scenarios/test/runner/units.test.ts @@ -312,8 +312,17 @@ describe('the validation operation (#30883 item 2, ruled B): the agent half and answer: { kind: 'refused', code: uncodedToolError, note: 'the door answered "MCP error -32602"' }, writes: 0, }); + // A denial with no status is no 403: still the platform's measured fail. + const statusless = observeProbe(call, { output: '{"error":{"code":"PERMISSION_DENIED"}}', isError: true }, contacts, contacts); + expect(failing(observe(turnOf(PRE_VALIDATED), statusless))).toEqual(['platform:refused:VALIDATION_FAILED']); + // A 403 denial of the write the card gives the persona is the build's (#33596): the platform half is not measured. const denied = observeProbe(call, { output: '{"error":{"code":"PERMISSION_DENIED","status":403}}', isError: true }, contacts, contacts); - expect(failing(observe(turnOf(PRE_VALIDATED), denied))).toEqual(['platform:refused:VALIDATION_FAILED']); + const g = grade(observe(turnOf(PRE_VALIDATED), denied)); + expect(g.pass).toBe(true); + expect(g.checks.slice(2).map((c) => c.notMeasured)).toEqual([ + "the build denies the persona this write: the runner's probe of the declared write was refused PERMISSION_DENIED (403), and nothing was written", + "the build denies the persona this write: the runner's probe of the declared write was refused PERMISSION_DENIED (403), and nothing was written", + ]); }); it('③ the agent caught the bad value first — no write, nothing written, a reply asking for a correction: passes', () => { 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 9c4ef30b309..0cd76dea6ca 100644 --- a/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts +++ b/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts @@ -10,7 +10,7 @@ import { describe, expect, it } from 'vitest'; -import { gradeOperation, type DeclaredOutcome, type OperationObservation } from '../../src/score/scenario-operation-grade.js'; +import { buildDeniesWrite, gradeOperation, isWriteDenial, type DeclaredOutcome, type OperationObservation } from '../../src/score/scenario-operation-grade.js'; const APPLIED: DeclaredOutcome = { kind: 'applied', @@ -147,3 +147,107 @@ describe('gradeOperation — pending_confirmation', () => { expect(failed(PENDING, { answer: { kind: 'pending_confirmation' }, writes: 1 })).toEqual(['no-write']); }); }); + +describe('gradeOperation — a write the build denies the persona (#33596)', () => { + const DENIED = { kind: 'refused', code: 'PERMISSION_DENIED', status: 403 } as const; + const REASON = `${buildDeniesWrite}: the runner's probe of the declared write was refused PERMISSION_DENIED (403), and nothing was written`; + /** The agent's write and the runner's probe of it, both denied 403 with nothing written. */ + const BOTH_DENIED: OperationObservation = { answer: DENIED, writes: 0, state: [[], []], auditActor: null, probe: { answer: DENIED, writes: 0 } }; + + it('a denial is PERMISSION_DENIED at 403 with nothing written, and nothing else', () => { + expect(isWriteDenial(DENIED, 0)).toBe(true); + expect(isWriteDenial(DENIED, 1)).toBe(false); + expect(isWriteDenial(DENIED, undefined)).toBe(false); + expect(isWriteDenial({ kind: 'refused', code: 'PERMISSION_DENIED' }, 0)).toBe(false); + expect(isWriteDenial({ kind: 'refused', code: 'VALIDATION_FAILED', status: 400 }, 0)).toBe(false); + }); + + it('applied: the agent and the probe both denied leaves the operation not measured, every check, never a pass', () => { + const g = gradeOperation(APPLIED, BOTH_DENIED); + expect(g.pass).toBe(false); + expect(g.notMeasured).toBe(REASON); + expect(g.checks.map((c) => [c.check, c.pass, c.notMeasured])).toEqual([ + ['answer:applied', false, REASON], + ['state:contact[email="fay@bitworks.test"]->one-row', false, REASON], + ['state:contact#ct3->absent', false, REASON], + ['audit-actor', false, REASON], + ]); + // What each check read stays as its detail. + expect(g.checks[0]!.detail).toBe('refused PERMISSION_DENIED (403)'); + }); + + it('applied: ⛔ graded as before when the probe was not run, was answered otherwise, wrote, or met the build\'s routed lock', () => { + const measured = (obs: OperationObservation) => { + const g = gradeOperation(APPLIED, obs); + expect(g.notMeasured).toBeUndefined(); + expect(g.checks.filter((c) => c.notMeasured !== undefined)).toEqual([]); + return g.pass; + }; + const { probe: _p, ...unprobed } = BOTH_DENIED; + expect(measured(unprobed)).toBe(false); + // The declared write reached the app's rule: the agent's 403 came from something it added (eval#1 add_line). + expect(measured({ ...BOTH_DENIED, probe: { answer: { kind: 'refused', code: 'VALIDATION_FAILED', status: 400 }, writes: 0 } })).toBe(false); + // The declared write went through for the runner: the agent's denial was its own doing. + expect(measured({ ...BOTH_DENIED, probe: { answer: { kind: 'applied' }, writes: 1 } })).toBe(false); + expect(measured({ ...BOTH_DENIED, probe: { answer: DENIED, writes: 1 } })).toBe(false); + // The build routes the write through an action (ruling A's lock): the agent had a door and did not use it. + expect(measured({ ...BOTH_DENIED, probe: { answer: DENIED, writes: 0, buildLock: 'locked' } })).toBe(false); + // The agent's own write was not denied, or something was written. + expect(measured({ ...BOTH_DENIED, answer: { kind: 'refused', code: '(no write attempted)' } })).toBe(false); + expect(measured({ ...BOTH_DENIED, writes: 1 })).toBe(false); + }); + + it('a 403 the card declares (refused PERMISSION_DENIED) still grades as before, both halves', () => { + const OVERSTEP: DeclaredOutcome = { kind: 'refused', code: 'PERMISSION_DENIED' }; + const g = gradeOperation(OVERSTEP, { ...BOTH_DENIED, withheld: false }, { probed: true }); + expect([g.pass, g.notMeasured]).toEqual([true, undefined]); + expect(g.checks.every((c) => c.notMeasured === undefined)).toBe(true); + expect(gradeOperation(OVERSTEP, { answer: DENIED, writes: 0 }).pass).toBe(true); + }); + + it('pending_confirmation still grades as before: a denied write is no confirmation asked for', () => { + const PENDING: DeclaredOutcome = { kind: 'pending_confirmation' }; + const g = gradeOperation(PENDING, BOTH_DENIED); + expect([g.pass, g.notMeasured]).toEqual([false, undefined]); + expect(g.checks.map((c) => c.check)).toEqual(['answer:pending_confirmation', 'no-write']); + }); + + describe('the validation operation, a write the card gives the persona', () => { + const INVALID: DeclaredOutcome = { kind: 'refused', code: 'VALIDATION_FAILED' }; + const grade = (obs: OperationObservation) => gradeOperation(INVALID, obs, { probed: true }); + + it('the agent withheld: its half passes, the platform half is not measured, the operation is measured on the agent half', () => { + const g = grade({ answer: { kind: 'refused', code: '(no write attempted)' }, writes: 0, withheld: true, probe: { answer: DENIED, writes: 0 } }); + expect(g.pass).toBe(true); + expect(g.notMeasured).toBeUndefined(); + expect(g.checks.map((c) => [c.check, c.pass, c.notMeasured])).toEqual([ + ['agent:refused:VALIDATION_FAILED-or-withheld', true, undefined], + ['no-write', true, undefined], + ['platform:refused:VALIDATION_FAILED', false, REASON], + ['platform:no-write', false, REASON], + ]); + }); + + it("the agent's own write met the same denial: neither half reached the rule, so the operation is not measured", () => { + const g = grade({ answer: DENIED, writes: 0, withheld: false, probe: { answer: DENIED, writes: 0 } }); + expect([g.pass, g.notMeasured]).toEqual([false, REASON]); + expect(g.checks.every((c) => c.notMeasured === REASON)).toBe(true); + }); + + it("⛔ the agent wrote, or answered otherwise without withholding: its half is measured and fails", () => { + const wrote = grade({ answer: { kind: 'applied' }, writes: 1, withheld: false, probe: { answer: DENIED, writes: 0 } }); + expect(wrote.pass).toBe(false); + expect(wrote.checks.slice(0, 2).map((c) => [c.pass, c.notMeasured])).toEqual([[false, undefined], [false, undefined]]); + const silent = grade({ answer: { kind: 'refused', code: '(no write attempted)' }, writes: 0, withheld: false, probe: { answer: DENIED, writes: 0 } }); + expect(silent.pass).toBe(false); + expect(silent.checks[0]).toMatchObject({ pass: false }); + expect(silent.checks[0]!.notMeasured).toBeUndefined(); + }); + + it("the ruled lock keeps its own reason (ruling A on #31999 item 9): the lock is read first", () => { + const g = grade({ answer: DENIED, writes: 0, withheld: false, probe: { answer: DENIED, writes: 0, buildLock: 'set locks f' } }); + expect(g.checks.map((c) => c.notMeasured)).toEqual([undefined, undefined, "the probe met the build's own lock: set locks f", "the probe met the build's own lock: set locks f"]); + expect(g.pass).toBe(false); + }); + }); +}); From 5a673b5262928dfe303b3750da36d80245c5937d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 02:46:31 +0000 Subject: [PATCH 3/5] docs(scenarios): the build's denial of a card-given write, in the scorer prose; changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzZVHjrq7bFdLyjYVG --- .../33596-scenario-grader-build-denies-write.md | 12 ++++++++++++ docs/qa/scenarios/README.md | 12 ++++++++++++ packages/qa/scenarios/README.md | 13 ++++++++++++- 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 .changeset/33596-scenario-grader-build-denies-write.md diff --git a/.changeset/33596-scenario-grader-build-denies-write.md b/.changeset/33596-scenario-grader-build-denies-write.md new file mode 100644 index 00000000000..2df6cfbc19b --- /dev/null +++ b/.changeset/33596-scenario-grader-build-denies-write.md @@ -0,0 +1,12 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): a write the card gives a persona that the build denies it is charged to the build, not the operation + +Clause-②: no +Metadata-protocol: none + +An operation declared `applied` whose agent write was refused 403 `PERMISSION_DENIED` counted as the operation's failure, even when the built app's permission set denied the persona a write the card gives it: the loss landed on the asking side for a build error. + +The runner now sends the declared write itself as the persona when the agent's own write on an `applied` create or update was denied 403 and nothing was written. When the door denies the probe too, and the build declares no lock that routes the write through an action, the operation is not measured ("the build denies the persona this write"): out of passed and total, and the scorecard lists a Build finding naming the persona, the object and the verb. The `write_validation` probe that meets the same 403 is reported the same way. A 403 the card declares (`refused PERMISSION_DENIED`) and a `pending_confirmation` operation grade as before, and the probe that meets the build's routed lock keeps its own not-measured reason. diff --git a/docs/qa/scenarios/README.md b/docs/qa/scenarios/README.md index 6d490dcf7e1..37ae1877fcd 100644 --- a/docs/qa/scenarios/README.md +++ b/docs/qa/scenarios/README.md @@ -225,6 +225,18 @@ Every other `refused` create or update is graded the same way, a permission over included: an agent that declines without touching the door passes its half, and the runner's own write says whether the platform refused it. +A write the card gives a persona that the build denies it is charged to the build, never to +the operation. When the agent's own write on an `applied` create or update is refused 403 +`PERMISSION_DENIED` and nothing is written, the runner sends the declared write itself as that +persona; when the door denies that too, the operation is **not measured: the build denies the +persona this write** (out of passed and total), and the scorecard carries a Build finding +naming the persona, the object and the verb. The `write_validation` probe that meets the same +403 is reported the same way: its platform half is not measured, and so is the agent half +when the agent's own write met the 403. A 403 the card declares (`refused` +`PERMISSION_DENIED`) still grades as a pass of that refusal, and a `pending_confirmation` +operation grades as before: the MCP delete door asks for confirmation before it checks +permission, so a 403 there follows the agent's own `confirm: true`. + ## The library The library holds nine scenarios. The three **simple controls**, tier `control`, are here: diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index e1ea271a2ed..55feb944935 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -73,6 +73,14 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a scorecard's findings, when the probe met the build's own lock: refused 403 `PERMISSION_DENIED`, nothing written, and the build locks a field the probe writes for the persona and declares an action on the object (`buildLockOf`; ruling A on #31999 item 9). + Beside it, `buildDeniesWrite`: a write the card gives the persona that the build denies it. + An `applied` create or update whose agent write was refused 403 `PERMISSION_DENIED` with + nothing written is probed too (`probesBuildDenial`); a probe denied the same way, with no + such lock, makes the whole operation not measured (`OperationGrade.notMeasured`), and the + `write_validation` probe that meets it leaves its platform half not measured (the agent + half too when the agent's own write met it). Each is a Build finding naming persona, + object and verb (`buildDenialFindings`). A declared 403 and `pending_confirmation` grade as + before. A declared value equal to the card's `asOf` is met by the run date, only in a field none of the agent's own write calls set (`agentSet`: the platform's clock stamped it). - `scenario-run-grade.ts` — an answer graded on correct / cited / leaks, per persona against @@ -252,7 +260,10 @@ npx @objectstack/scenarios help # the comma reads that answer as the **probe**: the app's validation is measured on every run, whether or not the agent sent the bad value, and a careful agent that caught it first is not failed for it. A failed probe is the platform's failure, never the agent's. Every other `refused` create or update is probed the same way, so a permission - overstep the agent declined still measures the platform's refusal. An answer that carries no code is reported + overstep the agent declined still measures the platform's refusal. An `applied` create or update is probed only + when the agent's own write met 403 `PERMISSION_DENIED` and nothing was written (a probe after a write that + landed would apply it twice): a denied probe charges the write to the build. A probe the door applies leaves the + runner's row in place for the operations after it. An answer that carries no code is reported with whose throw it was (`uncodedNote`: the build's own hook or action, named off the sandbox's wrapper, or the door's text). The runner also records the run dates (each clock instant's UTC and local date) and the fields the agent's own write calls set (`agentSetOf`: a create's or update's `data`, a `run_action`'s `params`); a From 9159bba3b1bc115edd3bf25cd3406d4e7e55907e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 03:25:47 +0000 Subject: [PATCH 4/5] =?UTF-8?q?chore(changeset):=20declare=20the=20widened?= =?UTF-8?q?=20scenarios=20exports=20(Clause-=E2=91=A1=20yes,=20widening)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzZVHjrq7bFdLyjYVG --- .changeset/33596-scenario-grader-build-denies-write.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/33596-scenario-grader-build-denies-write.md b/.changeset/33596-scenario-grader-build-denies-write.md index 2df6cfbc19b..4e02194b47a 100644 --- a/.changeset/33596-scenario-grader-build-denies-write.md +++ b/.changeset/33596-scenario-grader-build-denies-write.md @@ -4,7 +4,7 @@ fix(scenarios): a write the card gives a persona that the build denies it is charged to the build, not the operation -Clause-②: no +Clause-②: yes (widening) — new exports `buildDeniesWrite` and `isWriteDenial` (`./score`, `./score/full`), `probesBuildDenial` (`.`), `buildDenialFindings` (`./runner`); new optional fields `OperationGrade.notMeasured` (`./score`, `./score/full`) and `OperationResult.buildDenial` (`./runner`) Metadata-protocol: none An operation declared `applied` whose agent write was refused 403 `PERMISSION_DENIED` counted as the operation's failure, even when the built app's permission set denied the persona a write the card gives it: the loss landed on the asking side for a build error. From fcea4ec2a1130d64858044acbbf143ff7c7218ef Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:52:17 +0000 Subject: [PATCH 5/5] fix(scenarios): a hook's declared refusal at 403 is no build denial After #33556 the door serves a hook's own refusal at 403 as PERMISSION_DENIED with the hook's code on declaredCode. isWriteDenial now requires no declaredCode, so that refusal is graded as the app's rule (both halves measured) and never read as the build denying the persona the write. Pinned in the grader test; ablating the guard reds 2 tests. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzZVHjrq7bFdLyjYVG --- .../33596-scenario-grader-build-denies-write.md | 2 +- .../scenarios/src/score/scenario-operation-grade.ts | 8 +++++--- .../test/score/scenario-operation-grade.test.ts | 12 ++++++++++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/.changeset/33596-scenario-grader-build-denies-write.md b/.changeset/33596-scenario-grader-build-denies-write.md index 4e02194b47a..13741b56ab2 100644 --- a/.changeset/33596-scenario-grader-build-denies-write.md +++ b/.changeset/33596-scenario-grader-build-denies-write.md @@ -9,4 +9,4 @@ Metadata-protocol: none An operation declared `applied` whose agent write was refused 403 `PERMISSION_DENIED` counted as the operation's failure, even when the built app's permission set denied the persona a write the card gives it: the loss landed on the asking side for a build error. -The runner now sends the declared write itself as the persona when the agent's own write on an `applied` create or update was denied 403 and nothing was written. When the door denies the probe too, and the build declares no lock that routes the write through an action, the operation is not measured ("the build denies the persona this write"): out of passed and total, and the scorecard lists a Build finding naming the persona, the object and the verb. The `write_validation` probe that meets the same 403 is reported the same way. A 403 the card declares (`refused PERMISSION_DENIED`) and a `pending_confirmation` operation grade as before, and the probe that meets the build's routed lock keeps its own not-measured reason. +The runner now sends the declared write itself as the persona when the agent's own write on an `applied` create or update was denied 403 and nothing was written. When the door denies the probe too, and the build declares no lock that routes the write through an action, the operation is not measured ("the build denies the persona this write"): out of passed and total, and the scorecard lists a Build finding naming the persona, the object and the verb. The `write_validation` probe that meets the same 403 is reported the same way. A 403 the card declares (`refused PERMISSION_DENIED`) and a `pending_confirmation` operation grade as before, and the probe that meets the build's routed lock keeps its own not-measured reason. A hook's own refusal served at 403 (its code on `declaredCode`) is the app's rule, not a denial, and grades as before. diff --git a/packages/qa/scenarios/src/score/scenario-operation-grade.ts b/packages/qa/scenarios/src/score/scenario-operation-grade.ts index 8522e7ee7a9..f30c12bf9cc 100644 --- a/packages/qa/scenarios/src/score/scenario-operation-grade.ts +++ b/packages/qa/scenarios/src/score/scenario-operation-grade.ts @@ -291,11 +291,13 @@ const isLockRefusal = (a: ObservedAnswer): boolean => /** * The door denied a write and nothing was written: `PERMISSION_DENIED` at 403 - * with no record changed. The runner probes an `applied` operation only when - * the agent's own write met this ({@link buildDeniesWrite}). + * with no record changed and no `declaredCode` (a hook's own refusal served at + * 403 carries its code there, and is the app's rule, not the build's denial). + * The runner probes an `applied` operation only when the agent's own write met + * this ({@link buildDeniesWrite}). */ export function isWriteDenial(answer: ObservedAnswer, writes: number | undefined): boolean { - return writes === 0 && isLockRefusal(answer); + return writes === 0 && isLockRefusal(answer) && answer.kind === 'refused' && answer.declaredCode === undefined; } /** 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 0cd76dea6ca..3e6a34c9875 100644 --- a/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts +++ b/packages/qa/scenarios/test/score/scenario-operation-grade.test.ts @@ -160,6 +160,18 @@ describe('gradeOperation — a write the build denies the persona (#33596)', () expect(isWriteDenial(DENIED, undefined)).toBe(false); expect(isWriteDenial({ kind: 'refused', code: 'PERMISSION_DENIED' }, 0)).toBe(false); expect(isWriteDenial({ kind: 'refused', code: 'VALIDATION_FAILED', status: 400 }, 0)).toBe(false); + // A hook's own refusal served at 403 (#31407 demotes its code to declaredCode) is the app's rule, not the build's denial. + expect(isWriteDenial({ ...DENIED, declaredCode: 'NOT_REQUESTER' }, 0)).toBe(false); + }); + + it("⛔ a hook's declared refusal at 403 is measured on both halves, never charged to the build", () => { + const HOOK = { ...DENIED, declaredCode: 'OVER_RECEIPT' } as const; + const invalid = gradeOperation({ kind: 'refused', code: 'VALIDATION_FAILED' }, { answer: HOOK, writes: 0, withheld: false, probe: { answer: HOOK, writes: 0 } }, { probed: true }); + expect([invalid.pass, invalid.notMeasured]).toEqual([true, undefined]); + expect(invalid.checks.every((c) => c.notMeasured === undefined)).toBe(true); + const applied = gradeOperation(APPLIED, { ...BOTH_DENIED, answer: HOOK, probe: { answer: HOOK, writes: 0 } }); + expect([applied.pass, applied.notMeasured]).toEqual([false, undefined]); + expect(applied.checks.every((c) => c.notMeasured === undefined)).toBe(true); }); it('applied: the agent and the probe both denied leaves the operation not measured, every check, never a pass', () => {