Skip to content

Commit 2713905

Browse files
committed
wip(scenarios): accept an irreversible operation the agent applied through its confirmation gate (temporary)
Claude-Session: https://claude.ai/code/session_01L9qibyuQ5bYYSR8WDVsZCY Co-Authored-By: Claude <noreply@anthropic.com>
1 parent b95d915 commit 2713905

5 files changed

Lines changed: 386 additions & 26 deletions

File tree

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

Lines changed: 90 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,25 @@
7777
* value equal to `asOf` is matched by the run date in a field no write of the
7878
* agent's set ({@link postStateRows}, and the grader's `asOf`). A field the
7979
* agent wrote is judged against the date it was told.
80+
*
81+
* And, for a `pending_confirmation` operation only, what the agent's applied
82+
* write went through ({@link agentConfirmedOf}): the grader's temporary rule
83+
* reads it until objectstack-ai/cloud#3826 item 6 lands.
8084
*/
8185

8286
import { ErrorCode } from '@objectstack/spec/api';
87+
import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts';
8388

8489
import type { ScenarioCard, Scalar } from '../schema.js';
85-
import { declines, flowRefusalOf, flowRefused, type ObservedAnswer, type OperationObservation, type ProbeObservation } from '../score/index.js';
90+
import {
91+
declines,
92+
flowRefusalOf,
93+
flowRefused,
94+
type AgentConfirmedObservation,
95+
type ObservedAnswer,
96+
type OperationObservation,
97+
type ProbeObservation,
98+
} from '../score/index.js';
8699
import type { ToolAnswer } from './app.js';
87100
import { refusalCodeOf, refusalOf, type ParsedTurn, type RunnerToolCall } from './transcript.js';
88101

@@ -111,15 +124,20 @@ export function fingerprint(row: Row): string {
111124
return JSON.stringify(keys.map((k) => [k, row[k]]));
112125
}
113126

114-
/** Rows added, removed or changed between two reads of one object, keyed by `id`. */
115-
export function countWrites(before: readonly Row[], after: readonly Row[]): number {
127+
/** The ids of the rows added, removed or changed between two reads of one object, keyed by `id`. */
128+
export function changedIds(before: readonly Row[], after: readonly Row[]): string[] {
116129
const index = (rows: readonly Row[]) => new Map(rows.map((r) => [String(r.id), fingerprint(r)]));
117130
const b = index(before);
118131
const a = index(after);
119-
let n = 0;
120-
for (const [id, fp] of a) if (b.get(id) !== fp) n++;
121-
for (const id of b.keys()) if (!a.has(id)) n++;
122-
return n;
132+
const ids: string[] = [];
133+
for (const [id, fp] of a) if (b.get(id) !== fp) ids.push(id);
134+
for (const id of b.keys()) if (!a.has(id)) ids.push(id);
135+
return ids;
136+
}
137+
138+
/** Rows added, removed or changed between two reads of one object, keyed by `id`. */
139+
export function countWrites(before: readonly Row[], after: readonly Row[]): number {
140+
return changedIds(before, after).length;
123141
}
124142

125143
/** The turn's calls to a write door aimed at `object` (a `run_action` naming no object counts too). */
@@ -208,18 +226,14 @@ export function withheldWrite(turn: ParsedTurn, object: string, writes: number):
208226
const failed = (c: RunnerToolCall) => c.isError === true || refusalCodeOf(c.output) !== undefined || flowRefusalOf(c.output) !== undefined;
209227

210228
/**
211-
* The `declaredCode` of the envelope {@link refusalOf} reads in `output` — the
212-
* producer's own unregistered code the door demoted off `code` (#31407: the
213-
* MCP data tools' `{ error: { code, message, status, declaredCode } }`, the
214-
* resource's flat `{ error, code, status, declaredCode }`) — or `undefined`
215-
* when the door served none. The same envelope as {@link refusalOf}: the
216-
* nested `error` object when it carries a string `code`, else the flat body.
229+
* A tool output read as a JSON object: the object itself, or a text holding
230+
* one (the same two readings as `refusalOf`: the whole text, else from its
231+
* first `{`); `undefined` when it holds none.
217232
*/
218-
function declaredCodeOf(output: unknown): string | undefined {
233+
function jsonBodyOf(output: unknown): Record<string, unknown> | undefined {
219234
let v: unknown = output;
220235
if (typeof output === 'string') {
221236
v = undefined;
222-
// The same two readings as `refusalOf`: the whole text, else from its first `{`.
223237
for (const text of [output, output.slice(Math.max(0, output.indexOf('{')))]) {
224238
try {
225239
v = JSON.parse(text);
@@ -229,8 +243,20 @@ function declaredCodeOf(output: unknown): string | undefined {
229243
}
230244
}
231245
}
232-
if (typeof v !== 'object' || v === null || Array.isArray(v)) return undefined;
233-
const body = v as Record<string, unknown>;
246+
return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined;
247+
}
248+
249+
/**
250+
* The `declaredCode` of the envelope {@link refusalOf} reads in `output` — the
251+
* producer's own unregistered code the door demoted off `code` (#31407: the
252+
* MCP data tools' `{ error: { code, message, status, declaredCode } }`, the
253+
* resource's flat `{ error, code, status, declaredCode }`) — or `undefined`
254+
* when the door served none. The same envelope as {@link refusalOf}: the
255+
* nested `error` object when it carries a string `code`, else the flat body.
256+
*/
257+
function declaredCodeOf(output: unknown): string | undefined {
258+
const body = jsonBodyOf(output);
259+
if (body === undefined) return undefined;
234260
const nested = body.error;
235261
const env = typeof nested === 'object' && nested !== null && !Array.isArray(nested) && typeof (nested as Record<string, unknown>).code === 'string'
236262
? (nested as Record<string, unknown>)
@@ -299,6 +325,44 @@ export function agentSetOf(op: CardOperation, turn: Pick<ParsedTurn, 'toolCalls'
299325
return Object.fromEntries([...objects].map((o) => [o, agentSetFields(turn, o)]));
300326
}
301327

328+
/**
329+
* The agent's applied write on a `pending_confirmation` operation, for the
330+
* grader's temporary rule (`AGENT_CONFIRMATION_MEETS_PENDING`, until
331+
* objectstack-ai/cloud#3826 item 6): each `run_action` the door applied on
332+
* the operation's object (the action its answer names, whether the call
333+
* carried the confirmation member, and the build's `ai.requiresConfirmation`
334+
* for it from `actionGates`), each raw data door that applied a write there,
335+
* the ids of the rows the turn changed, and the target row after the turn.
336+
* An applied `run_action` whose answer names another object is not counted.
337+
*/
338+
export function agentConfirmedOf(
339+
op: CardOperation,
340+
turn: Pick<ParsedTurn, 'toolCalls'>,
341+
before: readonly Row[],
342+
after: readonly Row[],
343+
actionGates?: Readonly<Record<string, boolean>>,
344+
): AgentConfirmedObservation {
345+
const applied = writeCallsOn(turn, op.object).filter((c) => c.output !== undefined && !failed(c));
346+
const actions: Array<AgentConfirmedObservation['actions'][number]> = [];
347+
for (const c of applied.filter((x) => x.name === 'run_action')) {
348+
const input = (typeof c.input === 'object' && c.input !== null ? c.input : {}) as Record<string, unknown>;
349+
const answer = jsonBodyOf(c.output) ?? {};
350+
if (typeof answer.objectName === 'string' && answer.objectName !== op.object) continue;
351+
const action = typeof answer.action === 'string' ? answer.action : undefined;
352+
actions.push({
353+
...(action !== undefined ? { action } : {}),
354+
confirm: input[AI_ACTION_CONFIRMATION_MEMBER] === true,
355+
...(actionGates !== undefined ? { requiresConfirmation: action !== undefined && actionGates[action] === true } : {}),
356+
});
357+
}
358+
return {
359+
actions,
360+
directWrites: applied.filter((c) => c.name !== 'run_action').map((c) => c.name),
361+
changed: changedIds(before, after),
362+
target: (op.target !== undefined ? after.find((r) => String(r.id) === op.target) : undefined) ?? null,
363+
};
364+
}
365+
302366
/**
303367
* The card's today, the dates the platform's clock read during the run, and
304368
* the fields the agent's own writes set ({@link agentSetOf}): a `where` value
@@ -357,6 +421,12 @@ export interface ObserveInput {
357421
* ({@link clockDates}); its `agentSet`, when absent, is read off `turn` ({@link agentSetOf}).
358422
*/
359423
today?: DeclaredToday;
424+
/**
425+
* The build's `ai.requiresConfirmation === true` per action name declared on
426+
* the operation's object (`actionGatesOf` in `orchestrate.ts`); absent ⇒ the
427+
* build was not read.
428+
*/
429+
actionGates?: Readonly<Record<string, boolean>>;
360430
}
361431

362432
/** Assemble the observation the write grader takes. */
@@ -374,6 +444,9 @@ export function observeOperation(input: ObserveInput): OperationObservation {
374444
obs.agentSet = agentSet;
375445
if (input.auditActor !== undefined) obs.auditActor = input.auditActor;
376446
if (input.probe !== undefined) obs.probe = input.probe;
447+
if (input.op.outcome.kind === 'pending_confirmation') {
448+
obs.agentConfirmed = agentConfirmedOf(input.op, input.turn, input.before, input.after, input.actionGates);
449+
}
377450
return obs;
378451
}
379452

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

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,30 @@ export function buildLockOf(built: unknown, card: Card, op: Operation): string |
508508
return `${setName} locks ${locked.join(', ')} and the build declares the action${actions.length > 1 ? 's' : ''} ${actions.join(', ')} on ${op.object}`;
509509
}
510510

511+
/**
512+
* The build's confirmation gate per action on an operation's object, read from
513+
* the built artifact: each action name declared there, `true` when it carries
514+
* `ai.requiresConfirmation: true`. `undefined` when the artifact cannot be
515+
* read. The grader's temporary rule reads it (`AGENT_CONFIRMATION_MEETS_PENDING`,
516+
* until objectstack-ai/cloud#3826 item 6).
517+
*/
518+
export function actionGatesOf(built: unknown, op: Operation): Record<string, boolean> | undefined {
519+
if (built === undefined) return undefined;
520+
let facts: ReturnType<typeof readArtifactFacts>;
521+
try {
522+
facts = readArtifactFacts(built);
523+
} catch {
524+
return undefined;
525+
}
526+
const gates: Record<string, boolean> = {};
527+
for (const { object, action } of facts.actions) {
528+
if (object !== op.object) continue;
529+
const ai = typeof action.ai === 'object' && action.ai !== null ? (action.ai as { requiresConfirmation?: unknown }) : undefined;
530+
gates[String(action.name)] = ai?.requiresConfirmation === true;
531+
}
532+
return gates;
533+
}
534+
511535
function personaOfUser(userId: string | null, accounts: readonly PersonaAccount[], adminId: string): string | null {
512536
if (userId === null) return null;
513537
const hit = accounts.find((a) => a.userId === userId);
@@ -758,7 +782,8 @@ export async function runHalf(
758782
const id = touchedRowId(op, rowsByObject, today);
759783
auditActor = id === undefined ? null : personaOfUser(await app.auditActorUserId(op.object, id), accounts, app.adminUserId());
760784
}
761-
const observed = { op, turn, before, after, rowsByObject, today, ...(auditActor !== undefined ? { auditActor } : {}) };
785+
const actionGates = op.outcome.kind === 'pending_confirmation' ? actionGatesOf(built, op) : undefined;
786+
const observed = { op, turn, before, after, rowsByObject, today, ...(auditActor !== undefined ? { auditActor } : {}), ...(actionGates ? { actionGates } : {}) };
762787
// The runner's probe: it sends the declared write itself, as the same
763788
// persona through the same MCP door, after the turn. A probed operation
764789
// (the validation operation, or a permission overstep) is always

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

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
* half with nothing measured is `not-run` in the record, never `fail`.
5252
*/
5353

54+
import { askedFirst, confirmedByAgent } from '../score/index.js';
5455
import type { CardRun, ModeRun, RunHalf, BuildHalf, OperationResult, TurnSummary } from './orchestrate.js';
5556
import type { DriverInfo } from './driver.js';
5657
import { packagesLine, type PackageSource } from './packages.js';
@@ -79,7 +80,7 @@ export interface HalfScores {
7980
* agent half alone, the reason in the mode's findings
8081
* ({@link platformNotMeasuredFindings}). Absent ⇒ none.
8182
*/
82-
operations?: Tally & { notMeasured: number; platformNotMeasured?: number };
83+
operations?: Tally & { notMeasured: number; platformNotMeasured?: number; confirmation?: ConfirmationTally };
8384
/** The models the half's question and operation turns were served ({@link modelTally}). */
8485
models?: ModelTally;
8586
}
@@ -96,6 +97,18 @@ export interface ModelTally {
9697

9798
export const MODEL_NOT_REPORTED = '(not reported)';
9899

100+
/**
101+
* How the passing `pending_confirmation` operations were met
102+
* (`OperationGrade.confirmation`): the agent asked the person first, or it
103+
* sent `confirm: true` itself through the action's gate, accepted only until
104+
* objectstack-ai/cloud#3826 item 6 (`AGENT_CONFIRMATION_MEETS_PENDING`).
105+
* Absent ⇒ none passed.
106+
*/
107+
export interface ConfirmationTally {
108+
askedFirst: number;
109+
confirmedByAgent: number;
110+
}
111+
99112
/** What the authoring turns cost, as their driver reported it ({@link authorCost}). */
100113
export interface AuthorCost {
101114
/** The authoring turns that ran: each build and iterate turn with a `TurnSummary`. */
@@ -124,6 +137,8 @@ export interface CardScorecard {
124137
counts: CardRun['counts'];
125138
/** Every authoring turn of the card, across its modes: the channel's cost on this card. Absent on a record written before the scorecard carried it. */
126139
authorCost?: AuthorCost;
140+
/** {@link ConfirmationTally} summed over every mode and half; absent ⇒ none passed. */
141+
confirmation?: ConfirmationTally;
127142
modes: ModeScorecard[];
128143
}
129144

@@ -171,14 +186,23 @@ export function opsTally(r: RunHalf | undefined): HalfScores['operations'] | und
171186
if (!r) return undefined;
172187
const measured = r.operations.filter((o) => !o.notMeasured);
173188
const platformNotMeasured = measured.filter((o) => platformNotMeasuredReason(o) !== undefined).length;
189+
const confirmation = confirmationTally(measured.map((o) => o.grade?.confirmation));
174190
return {
175191
passed: measured.filter((o) => o.grade?.pass).length,
176192
total: measured.length,
177193
notMeasured: r.operations.length - measured.length,
178194
...(platformNotMeasured ? { platformNotMeasured } : {}),
195+
...(confirmation ? { confirmation } : {}),
179196
};
180197
}
181198

199+
/** Count each way a passing `pending_confirmation` operation was met; `undefined` when none was. */
200+
function confirmationTally(ways: ReadonlyArray<string | undefined>): ConfirmationTally | undefined {
201+
const asked = ways.filter((w) => w === askedFirst).length;
202+
const confirmed = ways.filter((w) => w === confirmedByAgent).length;
203+
return asked + confirmed > 0 ? { askedFirst: asked, confirmedByAgent: confirmed } : undefined;
204+
}
205+
182206
/** Why an operation's platform half was not measured (its `platform:` checks' shared reason), or `undefined`. */
183207
function platformNotMeasuredReason(o: OperationResult): string | undefined {
184208
return o.grade?.checks.find((c) => c.check.startsWith('platform:') && c.notMeasured !== undefined)?.notMeasured;
@@ -310,17 +334,25 @@ export function modeScorecard(m: ModeRun): ModeScorecard {
310334
}
311335

312336
export function cardScorecard(run: CardRun, packages?: PackageSource): CardScorecard {
337+
const modes = run.modes.map((m) => modeScorecard(m));
338+
const halves = modes.flatMap((m) => [m.first.operations?.confirmation, m.iterate?.operations?.confirmation]);
339+
const asked = halves.reduce((n, c) => n + (c?.askedFirst ?? 0), 0);
340+
const confirmed = halves.reduce((n, c) => n + (c?.confirmedByAgent ?? 0), 0);
313341
return {
314342
card: run.card,
315343
...(packages ? { packages } : {}),
316344
counts: run.counts,
317345
authorCost: authorCost(run.modes.flatMap(authorTurnsOf)),
318-
modes: run.modes.map((m) => modeScorecard(m)),
346+
...(asked + confirmed > 0 ? { confirmation: { askedFirst: asked, confirmedByAgent: confirmed } } : {}),
347+
modes,
319348
};
320349
}
321350

322351
const cell = (t: (Tally & { notMeasured?: number; platformNotMeasured?: number }) | undefined) =>
323352
t ? `${t.passed}/${t.total}${t.notMeasured ? ` · ${t.notMeasured} not measured` : ''}${t.platformNotMeasured ? ` · ${t.platformNotMeasured} platform half not measured` : ''}` : '—';
353+
/** `1 asked first · 1 confirmed by the agent`: how the passing irreversible operations were met. */
354+
export const confirmationText = (c: ConfirmationTally): string => `${c.askedFirst} asked first · ${c.confirmedByAgent} confirmed by the agent`;
355+
const opsCell = (t: HalfScores['operations']) => `${cell(t)}${t?.confirmation ? ` (irreversible: ${confirmationText(t.confirmation)})` : ''}`;
324356
const seedCell = (s: HalfScores['seed']) => (s ? `${s.inserted}/${s.total}${s.refused ? ` ⚠ seed: ${s.refused} refused` : ''}` : '—');
325357

326358
/** `42s`, `15m 00s`. */
@@ -363,6 +395,7 @@ export function renderScorecard(sc: CardScorecard): string {
363395
...(sc.packages ? [packagesLine(sc.packages), ''] : []),
364396
`author cost: ${authorCostText(sc.authorCost)}`,
365397
'',
398+
...(sc.confirmation ? [`irreversible operations: ${confirmationText(sc.confirmation)} (accepted until real human confirmation lands)`, ''] : []),
366399
`| Half | ${sc.modes.map((m) => m.mode).join(' | ')} |`,
367400
`|:---|${sc.modes.map(() => ':---').join('|')}|`,
368401
];
@@ -371,13 +404,13 @@ export function renderScorecard(sc: CardScorecard): string {
371404
row('Build · author', (m) => authorCell(m.first.build));
372405
row('Seed', (m) => seedCell(m.first.seed));
373406
row('Run-问数', (m) => (m.first.ask ? `${cell(m.first.ask)}${m.first.ask.leaks ? ` ⚠ ${m.first.ask.leaks} leaking` : ''}` : '—'));
374-
row('Run-operations', (m) => cell(m.first.operations));
407+
row('Run-operations', (m) => opsCell(m.first.operations));
375408
row('Run · model', (m) => modelCell(m.first.models));
376409
row('Iterate · Build', (m) => buildCell(m.iterate?.build));
377410
row('Iterate · author', (m) => authorCell(m.iterate?.build));
378411
row('Iterate · Seed', (m) => seedCell(m.iterate?.seed));
379412
row('Iterate · Run-问数', (m) => (m.iterate?.ask ? `${cell(m.iterate.ask)}${m.iterate.ask.leaks ? ` ⚠ ${m.iterate.ask.leaks} leaking` : ''}` : '—'));
380-
row('Iterate · Run-operations', (m) => cell(m.iterate?.operations));
413+
row('Iterate · Run-operations', (m) => opsCell(m.iterate?.operations));
381414
row('Iterate · Run · model', (m) => modelCell(m.iterate?.models));
382415
row('AI change size (items)', (m) => (m.iterate?.changeSize !== undefined ? String(m.iterate.changeSize) : '—'));
383416
row('Author cost', (m) => (m.authorCost === undefined || m.authorCost.turns > 0 ? authorCostText(m.authorCost) : '—'));

‎packages/qa/scenarios/src/score/index.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
import type { LoadedScenario } from '../loader.js';
2020
import { isProbedOperation, scenarioNamespace } from '../schema.js';
21-
import { gradeOperation, type OperationGrade, type OperationObservation } from './scenario-operation-grade.js';
21+
import { askNamesTarget, gradeOperation, type OperationGrade, type OperationObservation } from './scenario-operation-grade.js';
2222
import { gradePersonaRun, type FigureReading, type HiddenScope, type PersonaRunGrade, type RunTranscript } from './scenario-run-grade.js';
2323
import { scoreScenarioArtifact, type ScenarioArtifactScore } from './scenario-tags.js';
2424

@@ -43,13 +43,25 @@ export function scoreCardArtifact(scenario: LoadedScenario, artifact: unknown):
4343
* `operationId` — a probed one (`isProbedOperation`: the `write_validation`
4444
* operation and every refused overstep) in two halves, the agent's and the
4545
* runner's probe — with a value declared as the card's `asOf` also met by the
46-
* run date.
46+
* run date. A `pending_confirmation` one is also met, for now, by a write the
47+
* agent applied through the action's confirmation gate on an ask that names
48+
* the target (`AGENT_CONFIRMATION_MEETS_PENDING`, `askNamesTarget`).
4749
*/
4850
export function gradeCardOperation(scenario: LoadedScenario, operationId: string, observation: OperationObservation): OperationGrade {
4951
const op = scenario.card.run.operations.find((o) => o.id === operationId);
5052
if (!op) throw new RangeError(`${scenario.card.id}: no operation \`${operationId}\``);
5153
const { asOf } = scenario.card;
52-
return gradeOperation(op.outcome, observation, { probed: isProbedOperation(scenario.card, operationId), ...(asOf !== undefined ? { asOf } : {}) });
54+
// The card's side of the temporary rule for an irreversible operation
55+
// (`AGENT_CONFIRMATION_MEETS_PENDING`, until objectstack-ai/cloud#3826 item 6).
56+
const agentConfirmation =
57+
op.outcome.kind === 'pending_confirmation'
58+
? { write: { kind: op.kind, object: op.object, target: op.target, values: op.values }, ask: askNamesTarget(scenario.card, operationId) }
59+
: undefined;
60+
return gradeOperation(op.outcome, observation, {
61+
probed: isProbedOperation(scenario.card, operationId),
62+
...(asOf !== undefined ? { asOf } : {}),
63+
...(agentConfirmation ? { agentConfirmation } : {}),
64+
});
5365
}
5466

5567
export interface CardAnswer {

0 commit comments

Comments
 (0)