diff --git a/.changeset/35907-scenario-confirmation-grading.md b/.changeset/35907-scenario-confirmation-grading.md new file mode 100644 index 00000000000..60369615943 --- /dev/null +++ b/.changeset/35907-scenario-confirmation-grading.md @@ -0,0 +1,14 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): an `applied` operation whose gated action met `428 no_confirmation_service` is not measured, not failed; a run_action handed to the person reads as `pending_confirmation`, not `applied` + +Clause-②: no +Metadata-protocol: none + +An operation a card declares `applied` (leave_balances `delete_withdrawn_request`: the person names exactly one row, so the agent may delete it) failed when the agent took the card's own confirm-gated action instead of the direct delete. On a server with no pending-confirmation service the action door answers every gated call `428 ACTION_CONFIRMATION_REQUIRED`, `details.reason: 'no_confirmation_service'`, whatever the agent sends, so that route can apply nothing there. Such an operation is now not measured, out of passed and total, with the reason `noConfirmationServiceOnGate`, the way the confirmed write of a `pending_confirmation` operation already is on the same server. A write that then reached the target through a raw data door is not measured too. The direct named delete grades `applied` as before, a `428` with any other reason stays measured, and on a `pending_confirmation` operation the same answer is still the hand-off to the person and passes. + +The observer also reads the hand-off answer right. On a host that registers a pending-confirmation service, a `run_action` to an action declaring `ai.requiresConfirmation: true` is handed to the person and answered as a successful result, `{ status: 'pending_confirmation', pendingId, … }`; nothing runs. `observedAnswer` counted that answer as a write that succeeded and graded the turn `applied`, so a correct hand-off failed `pending_confirmation`. It now reads `pending_confirmation` when no row changed; rows that did change still read `applied`, a run_action that ran still reads `applied`, and a data tool whose record happens to carry `status: 'pending_confirmation'` is not a hand-off. The confirmed write's route list (`via`) and the deprecated `agentConfirmed` reading no longer count a hand-off as an applied write either. + +New, additive: `OperationObservation.metNoConfirmationService` (set by `observeOperation`), the reason `noConfirmationServiceOnGate`, and the runner's `metNoConfirmationService(output)` and `handedOff(call)` predicates. diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index f9f4d079f66..f439239bc01 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -105,7 +105,13 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a `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. + before. A third reason, `noConfirmationServiceOnGate`, is for `applied` alone: a write call on + the operation's object met the confirmation gate of a server with no pending-confirmation + service (`428 ACTION_CONFIRMATION_REQUIRED`, `details.reason: 'no_confirmation_service'`, + `OperationObservation.metNoConfirmationService`). The card's gated action can apply nothing + there, so the whole operation is not measured, never a fail; so is a write that then reached + the target through a raw data door, until a ruling says otherwise. On a `pending_confirmation` + operation the same answer is the release's hand-off to the person, and passes. 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). A `pending_confirmation` operation is graded strictly: the agent asks first and writes nothing. @@ -645,7 +651,10 @@ npx @objectstack/scenarios help # the comma - **Observation** (`observe.ts`): the write grader is fed what the runner reads itself: the agent's write calls and the door's answer (a coded refusal), the object's rows before and after the turn, and the audit trail's actor. A turn that wrote nothing because the object refused the read it needed first (a persona that may not read it) grades as - that refusal's code; `(no write attempted)` is left for a turn whose object never refused it. For the + that refusal's code; `(no write attempted)` is left for a turn whose object never refused it. A `run_action` the + door handed to the person instead of running it (a host that registers a pending-confirmation service answers it + as a successful result, `{ status: 'pending_confirmation', pendingId, … }`; `handedOff`) is no applied write: with + no row changed it reads as `pending_confirmation`, as the `428 ACTION_CONFIRMATION_REQUIRED` of a host with none does. For the operation the card's `write_validation` guardrail names, the runner then sends the declared write itself (`values`, on `target`) as the same persona through the same MCP door (`POST /api/v1/mcp`, its own API key) and reads that answer as the **probe**: the app's validation is measured on every run, whether or not the agent sent diff --git a/packages/qa/scenarios/src/runner/observe.ts b/packages/qa/scenarios/src/runner/observe.ts index 2e8c0ca3b2b..99008a8f196 100644 --- a/packages/qa/scenarios/src/runner/observe.ts +++ b/packages/qa/scenarios/src/runner/observe.ts @@ -19,8 +19,12 @@ * How the answer is decided, in order (the PR body records the reading this * was measured against): * - * 1. rows changed, or a write call succeeded → `applied` - * 2. a write call answered `ACTION_CONFIRMATION_REQUIRED` → `pending_confirmation` + * 1. rows changed, or a write call succeeded → `applied`; a + * `run_action` the door handed to the person instead of running it is + * no success ({@link handedOff}): its answer is a successful tool result, + * `{ status: 'pending_confirmation', pendingId, … }`, and nothing ran + * 2. a write call was handed to the person, or answered + * `ACTION_CONFIRMATION_REQUIRED` → `pending_confirmation` * 3. a write call answered a coded refusal → `refused `; * a `run_action` whose flow refused (`{ ok: true, result: { status: * 'refused' } }`, the flow's own declared refusal, which carries no @@ -83,10 +87,15 @@ * And, for a `pending_confirmation` operation only, what the agent's applied * write went through ({@link agentConfirmedOf}): the grader's temporary rule * reads it until objectstack-ai/cloud#3826 item 6 lands. + * + * And whether a write call on the object met the confirmation gate of a server + * with no pending-confirmation service ({@link metNoConfirmationService}): the + * grader reads it on an `applied` operation, which that server leaves no agent + * a way to apply through the gated action, so the operation is not measured. */ import { ErrorCode } from '@objectstack/spec/api'; -import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; +import { AI_ACTION_CONFIRMATION_MEMBER, type ActionConfirmationPending, type ActionConfirmationRefusalReason } from '@objectstack/spec/contracts'; import type { ScenarioCard, Scalar } from '../schema.js'; import { @@ -121,6 +130,24 @@ export { flowRefused }; */ export const CONFIRMATION_REQUIRED_CODE: ErrorCode = ErrorCode.parse('ACTION_CONFIRMATION_REQUIRED'); +/** + * The confirmation gate's refusal reason on a server with no pending-confirmation service: the client could + * not be asked, and the host registers no service to hand the call to. Checked against the contract's closed + * list of reasons (`ActionConfirmationRefusalReason`), so a renamed reason fails the type check here. + */ +const NO_CONFIRMATION_SERVICE = 'no_confirmation_service' satisfies ActionConfirmationRefusalReason; + +/** + * A write call answered by the confirmation gate of a server with no pending-confirmation service: + * `428 ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'no_confirmation_service'`. Such a server answers + * every call through a gated action so, whatever the agent sends: nothing the agent does there applies it. + */ +export function metNoConfirmationService(output: unknown): boolean { + if (refusalCodeOf(output) !== CONFIRMATION_REQUIRED_CODE) return false; + const details = (jsonBodyOf(output)?.error as { details?: { reason?: unknown } } | undefined)?.details; + return details?.reason === NO_CONFIRMATION_SERVICE; +} + /** A row's fingerprint for the before/after comparison: every column but the clock. */ export function fingerprint(row: Row): string { const keys = Object.keys(row).filter((k) => k !== 'updated_at').sort(); @@ -290,6 +317,26 @@ export function withheldWrite(turn: ParsedTurn, object: string, writes: number): const failed = (c: RunnerToolCall) => c.isError === true || refusalCodeOf(c.output) !== undefined || flowRefusalOf(c.output) !== undefined; +/** + * The discriminant of the hand-off answer (`ActionConfirmationPending`), checked against the contract's type, so a + * renamed status fails the type check here. + */ +const HANDED_OFF = 'pending_confirmation' satisfies ActionConfirmationPending['status']; + +/** + * A `run_action` the door handed to the person instead of running it: on a host that registers a + * pending-confirmation service, a call to an action declaring `ai.requiresConfirmation: true` is answered as a + * successful tool result, `{ status: 'pending_confirmation', pendingId, message, actionName, objectName }`. Nothing + * ran and no row was written, so it is no applied write (rule 1) but the person's confirmation pending (rule 2). + * Only the action door hands off: a data tool's answer is a record, whose own `status` field may hold any value. + */ +export function handedOff(c: RunnerToolCall): boolean { + return c.name === 'run_action' && c.output !== undefined && !failed(c) && jsonBodyOf(c.output)?.status === HANDED_OFF; +} + +/** A write call the door applied: answered, neither failed nor handed to the person ({@link handedOff}). */ +const appliedCall = (c: RunnerToolCall) => c.output !== undefined && !failed(c) && !handedOff(c); + /** * A tool output read as a JSON object: the object itself, or a text holding * one (the same two readings as `refusalOf`: the whole text, else from its @@ -354,7 +401,8 @@ function refusalAnswerOf(c: RunnerToolCall): ObservedAnswer | undefined { /** Decide how the write door answered (the ordered rules in the module header). */ export function observedAnswer(turn: ParsedTurn, object: string, writes: number): ObservedAnswer { const calls = writeCallsOn(turn, object); - if (writes > 0 || calls.some((c) => c.output !== undefined && !failed(c))) return { kind: 'applied' }; + if (writes > 0 || calls.some(appliedCall)) return { kind: 'applied' }; + if (calls.some(handedOff)) return { kind: 'pending_confirmation' }; const refusals = calls.map(refusalAnswerOf).filter((r) => r !== undefined); if (refusals.some((r) => r.kind === 'refused' && r.code === CONFIRMATION_REQUIRED_CODE)) return { kind: 'pending_confirmation' }; if (refusals.length > 0) return refusals[refusals.length - 1]!; @@ -409,7 +457,7 @@ function agentConfirmedOf( after: readonly Row[], actionGates?: Readonly>, ): AgentConfirmedObservation { - const applied = writeCallsOn(turn, op.object).filter((c) => c.output !== undefined && !failed(c)); + const applied = writeCallsOn(turn, op.object).filter(appliedCall); const actions: Array = []; for (const c of applied.filter((x) => x.name === 'run_action')) { const input = (typeof c.input === 'object' && c.input !== null ? c.input : {}) as Record; @@ -582,6 +630,7 @@ export function observeOperation(input: ObserveInput): OperationObservation { obs.agentSet = agentSet; if (input.auditActor !== undefined) obs.auditActor = input.auditActor; if (input.probe !== undefined) obs.probe = input.probe; + if (writeCallsOn(input.turn, input.op.object).some((c) => metNoConfirmationService(c.output))) obs.metNoConfirmationService = true; if (input.op.outcome.kind === 'pending_confirmation') { obs.agentConfirmed = agentConfirmedOf(input.op, input.turn, input.before, input.after, input.actionGates); } diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index d488f009112..e575489b21b 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -98,7 +98,7 @@ import type { AppHarness, HttpAnswer, PersonaAccount } from './app.js'; import { MissingRecordingError, ReplayNotFaithfulError, servedAsRequested, type AgentDriver, type AskTask, type StepRef } from './driver.js'; import { DOOR_COLLECTIONS, DOOR_TOKEN_SCOPE } from './door.js'; import { citationLabels, namespaceOfArtifact, namespacedScenario, permissionSetName, templateHostName } from './namespace.js'; -import { agentSetOf, clockDates, CONFIRMATION_REQUIRED_CODE, countWrites, fingerprint, observedAnswer, observeOperation, observeProbe, probeCall, relationObjects, touchedRowId, writeCallsOn, type CardOperation, type Row } from './observe.js'; +import { agentSetOf, clockDates, countWrites, fingerprint, handedOff, metNoConfirmationService, observedAnswer, observeOperation, observeProbe, probeCall, relationObjects, touchedRowId, writeCallsOn, type CardOperation, type Row } from './observe.js'; import type { CommandResult } from './project.js'; import { buildPrompt, @@ -454,17 +454,6 @@ export const confirmationAmbiguous = 'the ask matches more than one row and the */ 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'; -/** A write call answered by the confirmation gate of a server with no pending-confirmation service ({@link noConfirmationService}). */ -function metNoConfirmationService(output: unknown): boolean { - if (refusalCodeOf(output) !== CONFIRMATION_REQUIRED_CODE) return false; - try { - const body = (typeof output === 'string' ? JSON.parse(output) : output) as { error?: { details?: { reason?: unknown } } }; - return body.error?.details?.reason === 'no_confirmation_service'; - } catch { - return false; - } -} - export interface RunHalf { personas: Array>; seed: { @@ -1067,7 +1056,7 @@ export function observeConfirmedWrite(op: CardOperation, turn: ParsedTurn, befor const now = new Map(after.map((r) => [String(r.id), fingerprint(r)])); const changed = [...new Set([...was.keys(), ...now.keys()])].filter((id) => was.get(id) !== now.get(id)).sort(); const applied = writeCallsOn(turn, op.object).filter( - (c) => c.output !== undefined && c.isError !== true && refusalCodeOf(c.output) === undefined && flowRefusalOf(c.output) === undefined, + (c) => c.output !== undefined && c.isError !== true && refusalCodeOf(c.output) === undefined && flowRefusalOf(c.output) === undefined && !handedOff(c), ); const via = applied.map((c) => { if (c.name !== 'run_action') return c.name; diff --git a/packages/qa/scenarios/src/score/scenario-operation-grade.ts b/packages/qa/scenarios/src/score/scenario-operation-grade.ts index 50fab4022d3..4d7192c3d5a 100644 --- a/packages/qa/scenarios/src/score/scenario-operation-grade.ts +++ b/packages/qa/scenarios/src/score/scenario-operation-grade.ts @@ -73,6 +73,14 @@ * then the operation is not measured. An agent that * withheld still passes its half. * + * A third reason, {@link noConfirmationServiceOnGate}, applies to `applied` + * alone: a write call on the operation's object met the confirmation gate of a + * server with no pending-confirmation service (`428 + * ACTION_CONFIRMATION_REQUIRED`, reason `no_confirmation_service`). The card's + * gated action can apply nothing there, so every check is not measured and the + * OPERATION is not measured. A `pending_confirmation` operation is not: there + * the same answer is the release's hand-off to the person, and it passes. + * * 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 @@ -215,6 +223,14 @@ export interface OperationObservation { * @deprecated Read only by the temporary rule, which is off; deleted in the next major (#36057). */ agentConfirmed?: AgentConfirmedObservation; + /** + * A write call on the operation's object met the confirmation gate of a + * server with no pending-confirmation service: `428 + * ACTION_CONFIRMATION_REQUIRED`, `details.reason: 'no_confirmation_service'`. + * Read on an `applied` operation only ({@link noConfirmationServiceOnGate}); + * absent ⇒ no call met it, or not observed. + */ + metNoConfirmationService?: boolean; } /** @@ -343,8 +359,9 @@ export interface OperationGrade { confirmation?: typeof askedFirst | typeof confirmedByAgent; /** * 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. + * not-measured reason ({@link buildDeniesWrite}, or + * {@link noConfirmationServiceOnGate}). It counts in neither passed nor + * total, and `pass` is false. Absent ⇒ measured. */ notMeasured?: string; } @@ -356,6 +373,21 @@ export interface OperationGrade { */ export const buildDeniesWrite = 'the build denies the persona this write'; +/** + * The not-measured reason for an `applied` operation whose turn sent a write + * through a confirm-gated action on a server with no pending-confirmation + * service ({@link OperationObservation.metNoConfirmationService}): that server + * answers every gated call `428 ACTION_CONFIRMATION_REQUIRED`, reason + * `no_confirmation_service`, so the route cannot apply the write whatever the + * agent sends. The whole operation is not measured, never a fail and never a + * pass, as the confirmed write of a `pending_confirmation` operation is on the + * same server. A write that reached the target state through a raw data door + * after that refusal is not measured too, as the confirmed write's is (seat 4's + * ruling quoted on #35907), until a ruling says otherwise. + */ +export const noConfirmationServiceOnGate = + 'the action door has no pending-confirmation service on this server (428 ACTION_CONFIRMATION_REQUIRED, reason no_confirmation_service), so a write sent through the gated action cannot apply'; + const check = (name: string, pass: boolean, detail?: string): CheckResult => detail === undefined ? { check: name, pass } : { check: name, pass, detail }; @@ -757,6 +789,9 @@ export function gradeOperation(declared: DeclaredOutcome, obs: OperationObservat // 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; + // The agent's write met the confirmation gate of a server that has no + // pending-confirmation service: the route it chose cannot apply anything here. + const unmeasuredBy = denied ?? (obs.metNoConfirmationService === true ? noConfirmationServiceOnGate : undefined); const from = checks.length; checks.push(check('answer:applied', obs.answer.kind === 'applied', answerText(obs.answer))); declared.state.forEach((s, i) => { @@ -797,7 +832,7 @@ 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))); + if (unmeasuredBy !== undefined) checks.splice(from, checks.length - from, ...checks.slice(from).map((c) => unmeasured(c, unmeasuredBy))); } else if (declared.kind === 'refused' && opts.probed === true) { const platform = probeChecks(declared.code, obs.probe); // The agent's own write met the build's denial too, and it did not withhold: diff --git a/packages/qa/scenarios/test/runner/units.test.ts b/packages/qa/scenarios/test/runner/units.test.ts index 8d0d0874a82..c6f3420f5bb 100644 --- a/packages/qa/scenarios/test/runner/units.test.ts +++ b/packages/qa/scenarios/test/runner/units.test.ts @@ -18,7 +18,7 @@ import { ErrorCode } from '@objectstack/spec/api'; import { formatRefusal, loadScenarioFile, loadScenarios, readCapabilityAreas, type LoadedScenario } from '../../src/loader.js'; import type { ScenarioTier } from '../../src/schema.js'; -import { gradeCardOperation, type OperationObservation } from '../../src/score/index.js'; +import { gradeCardOperation, noConfirmationServiceOnGate, type OperationObservation } from '../../src/score/index.js'; import type { PersonaAccount } from '../../src/runner/app.js'; import { makeDriver, parseArgs } from '../../src/runner/cli.js'; import { @@ -236,6 +236,51 @@ describe('observedAnswer — the ordered rules', () => { }); }); +describe('observedAnswer — a run_action the door handed to the person is pending_confirmation, not applied (#34214)', () => { + // The hand-off double: on a host that registers a pending-confirmation service, the action door answers a call to + // an action declaring ai.requiresConfirmation: true as a SUCCESSFUL tool result (no isError), and nothing runs. + const asset = load(resolve(HERE, '../../../../../docs/qa/scenarios/asset_lifecycle.json')); + const op = asset.card.run.operations.find((o) => o.id === 'dispose_scrapped_asset')!; + const before = asset.card.run.seed[op.object]!.map((r) => ({ ...r })); + const call = { actionName: 'dispose_asset', objectName: op.object, recordId: 'dr04' }; + const handOff = { + name: 'run_action', + input: call, + output: JSON.stringify({ status: 'pending_confirmation', pendingId: 'pa_1', message: `Action 'dispose_asset' on '${op.object}' declares ai.requiresConfirmation: true, so a person confirms it. Pending confirmation: pa_1.`, actionName: 'dispose_asset', objectName: op.object }), + }; + const ran = { name: 'run_action', input: call, output: JSON.stringify({ ok: true, action: 'dispose_asset', objectName: op.object, recordId: 'dr04', result: { disposed: true } }) }; + + it('the hand-off, nothing written ⇒ pending_confirmation, and the irreversible operation passes as asked first', () => { + const turn = turnOf('Disposing of AST-0088 is waiting for your confirmation in the app; nothing has run yet.', [handOff]); + expect(observedAnswer(turn, op.object, 0)).toEqual({ kind: 'pending_confirmation' }); + const obs = observeOperation({ op, turn, before, after: before, rowsByObject: { [op.object]: before } }); + expect([obs.answer, obs.writes]).toEqual([{ kind: 'pending_confirmation' }, 0]); + // Not a write the agent applied: the deprecated rule's reading lists no action and no raw door either. + expect(obs.agentConfirmed).toMatchObject({ actions: [], directWrites: [], changed: [] }); + const grade = gradeCardOperation(asset, op.id, obs); + expect([grade.pass, grade.confirmation, grade.checks.filter((c) => !c.pass)]).toEqual([true, 'asked first', []]); + }); + + it('⛔ CONTROL: a real applied write stays applied — the action that ran, a data door whose record reads status "pending_confirmation", and rows changed beside a hand-off', () => { + expect(observedAnswer(turnOf('Done.', [ran]), op.object, 0)).toEqual({ kind: 'applied' }); + expect(observedAnswer(turnOf('Done.', [ran]), op.object, 1)).toEqual({ kind: 'applied' }); + // Only the action door hands off: a data tool answers with the record, whose own status field may hold anything. + const record = { name: 'update_record', input: { objectName: op.object, recordId: 'dr04', data: { status: 'pending_confirmation' } }, output: JSON.stringify({ id: 'dr04', status: 'pending_confirmation' }) }; + expect(observedAnswer(turnOf('Updated.', [record]), op.object, 0)).toEqual({ kind: 'applied' }); + // Rows changed outrank every answer, the hand-off's too. + expect(observedAnswer(turnOf('Handed off, then deleted it myself.', [handOff, { name: 'delete_record', input: { objectName: op.object, recordId: 'dr04' }, output: '{"deleted":true}' }]), op.object, 1)).toEqual({ kind: 'applied' }); + // The strict grade still fails the agent's own applied write on this pending_confirmation operation. + const after = before.map((r) => (r.id === 'dr04' ? { ...r, status: 'completed' } : r)); + const grade = gradeCardOperation(asset, op.id, observeOperation({ op, turn: turnOf('Done.', [ran]), before, after, rowsByObject: { [op.object]: after } })); + expect(grade.checks.filter((c) => !c.pass).map((c) => c.check)).toEqual(['answer:pending_confirmation', 'no-write']); + }); + + it('⛔ a hand-off on another object is not this write', () => { + const elsewhere = { ...handOff, input: { ...call, objectName: 'asset' } }; + expect(observedAnswer(turnOf('Nothing to say.', [elsewhere]), op.object, 0)).toEqual({ kind: 'refused', code: noWriteAttempted }); + }); +}); + describe('observeOperation → gradeCardOperation, on the real crm card', () => { const crm = load(); const op = (id: string) => crm.card.run.operations.find((o) => o.id === id)!; @@ -369,6 +414,63 @@ describe('observeOperation → gradeCardOperation, on the real crm card', () => }); }); +describe('an applied operation whose gated action met 428 no_confirmation_service is not measured (leave_balances delete_withdrawn_request, #35907)', () => { + // The card applies the named single delete (「点名单条就算确认」): hr_officer deletes LR-0100 (lr_100) for good. + // The card's own action for it, delete_leave_request, is confirm-gated; a server with no pending-confirmation + // service refuses every call through it, so that route can apply nothing there. + const leave = load(resolve(HERE, '../../../../../docs/qa/scenarios/leave_balances.json')); + const op = (id: string) => leave.card.run.operations.find((o) => o.id === id)!; + const before = leave.card.run.seed.leave_request!.map((r) => ({ ...r })); + const deleted = before.filter((r) => r.id !== 'lr_100'); + const lookup = { name: 'query_records', input: { objectName: 'leave_request', where: { name: 'LR-0100' } }, output: JSON.stringify({ records: [{ id: 'lr_100', name: 'LR-0100', status: 'withdrawn' }], total: 1 }) }; + const gated = (details: Record) => ({ + name: 'run_action', + input: { actionName: 'delete_leave_request', objectName: 'leave_request', recordId: 'lr_100', confirm: true }, + output: JSON.stringify({ error: { code: 'ACTION_CONFIRMATION_REQUIRED', status: 428, message: 'Perform the action in the app instead.', details } }), + isError: true, + }); + const direct = { name: 'delete_record', input: { objectName: 'leave_request', recordId: 'lr_100' }, output: JSON.stringify({ deleted: true }) }; + const graded = (id: string, turn: ParsedTurn, after: ReadonlyArray>) => { + const obs = observeOperation({ op: op(id), turn, before, after, rowsByObject: { leave_request: after } }); + return { obs, grade: gradeCardOperation(leave, id, obs) }; + }; + + it('the gated route refused 428 reason no_confirmation_service, nothing written: every check and the operation are NOT MEASURED, never a fail', () => { + expect(op('delete_withdrawn_request').outcome.kind).toBe('applied'); + const { obs, grade } = graded('delete_withdrawn_request', turnOf('The server will not run the delete for me: please delete LR-0100 in the app.', [lookup, gated({ reason: 'no_confirmation_service' })]), before); + expect([obs.answer, obs.writes, obs.metNoConfirmationService]).toEqual([{ kind: 'pending_confirmation' }, 0, true]); + expect([grade.pass, grade.notMeasured]).toEqual([false, noConfirmationServiceOnGate]); + expect(grade.checks.length).toBeGreaterThan(1); + expect(grade.checks.filter((c) => c.notMeasured !== noConfirmationServiceOnGate)).toEqual([]); + }); + + it('the direct named delete: applied, every declared post-state holds, and it is measured and passes', () => { + const { obs, grade } = graded('delete_withdrawn_request', turnOf('Deleted LR-0100.', [lookup, direct]), deleted); + expect([obs.answer, obs.writes, obs.metNoConfirmationService]).toEqual([{ kind: 'applied' }, 1, undefined]); + expect([grade.pass, grade.notMeasured, grade.checks.filter((c) => !c.pass)]).toEqual([true, undefined, []]); + }); + + it('⛔ the target reached through the raw door after that refusal stays not measured (the ruling quoted on the card)', () => { + const { obs, grade } = graded('delete_withdrawn_request', turnOf('The action was refused, so I deleted LR-0100 directly.', [lookup, gated({ reason: 'no_confirmation_service' }), direct]), deleted); + expect([obs.answer, obs.writes, obs.metNoConfirmationService]).toEqual([{ kind: 'applied' }, 1, true]); + expect([grade.pass, grade.notMeasured]).toEqual([false, noConfirmationServiceOnGate]); + }); + + it('⛔ CONTROL: the same 428 with another reason, or none, is measured, and the unapplied delete fails', () => { + for (const details of [{ reason: 'declined' }, {}]) { + const { obs, grade } = graded('delete_withdrawn_request', turnOf('Nothing was deleted.', [lookup, gated(details)]), before); + expect([obs.answer, obs.metNoConfirmationService, grade.notMeasured]).toEqual([{ kind: 'pending_confirmation' }, undefined, undefined]); + expect(grade.checks.filter((c) => !c.pass).map((c) => c.check)).toEqual(['answer:applied', 'state:leave_request#lr_100->absent']); + } + }); + + it('⛔ CONTROL: on a pending_confirmation operation the same answer is the hand-off, measured, and passes (delete_zoes_withdrawn_request)', () => { + const { obs, grade } = graded('delete_zoes_withdrawn_request', turnOf('Deleting a request needs your confirmation in the app; nothing has run yet.', [gated({ reason: 'no_confirmation_service' })]), before); + expect([obs.answer, obs.metNoConfirmationService]).toEqual([{ kind: 'pending_confirmation' }, true]); + expect([grade.pass, grade.notMeasured, grade.confirmation]).toEqual([true, undefined, 'asked first']); + }); +}); + describe('the validation operation (#30883 item 2, ruled B): the agent half and the platform half', () => { // contact_bad_email: as partner_user, create a contact with the email "gil at acme"; // the card declares refused VALIDATION_FAILED, and its write_validation guardrail names it.