From cfac59225b5f8f0ce03525c296cbd61e8ac1749f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:04:21 +0000 Subject: [PATCH 1/4] fix(scenarios): an operation an earlier write would meet runs on a fresh seeded copy of the app, not on rows written back through its doors Claude-Session: https://claude.ai/code/session_01ADHkmP1FQBBcaufj5VXUcV Co-authored-by: Claude --- .../qa/scenarios/src/runner/orchestrate.ts | 231 ++++++++++++++---- 1 file changed, 190 insertions(+), 41 deletions(-) diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 4b0f3cb2f73..f92b76b517f 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -119,6 +119,29 @@ export interface ProjectOps { namespace?(dir: string): string | undefined; } +/** + * Another copy of the app a Run half runs on: booted anew from the same + * project, with the same build installed the same way, holding no rows of + * the card's yet ({@link runHalf} seeds it). `release` stops it. A half that + * has one starts an operation an earlier turn's write would otherwise meet on + * a copy of its own instead of writing the rows back + * ({@link restoreSeededRows}). + */ +export type FreshCopy = () => Promise<{ app: AppHarness; release(): Promise }>; + +/** A {@link FreshCopy} of the project in `dir`: `ops.boot` again, and nothing installed (the project is the build). */ +function freshBoot(ops: Pick, dir: string): FreshCopy { + return async () => { + const booted = await ops.boot(dir); + try { + return { app: ops.harness(booted.url), release: () => booted.stop() }; + } catch (e) { + await booted.stop(); + throw e; + } + }; +} + export interface RunOptions { modes: ReadonlyArray<'scratch' | 'template' | 'ask'>; /** Re-run the Run half after the iterate (scratch mode). Default true. */ @@ -272,16 +295,18 @@ export interface OperationResult { * persona the write the card gives it, `buildDeniesWrite`); or it was * replayed and the app did not answer its re-sent writes as it answered the * recorded run (`ReplayNotFaithfulError`); or it was not run, because the - * rows an earlier turn moved could not be restored to the seeded state - * (`restore: …`, {@link restoreSeededRows}). Never a fail. + * rows an earlier turn moved could not be restored to the seeded state, or + * no fresh copy of the app could be seeded for it (`restore: …`, + * {@link runHalf}). Never a fail. */ notMeasured?: string; /** - * The rows the runner set back to the seeded state before this operation - * ran, because an earlier turn had moved them ({@link restoreSeededRows}): - * the operation started from the card's own rows, as if it ran first. - * Absent when nothing had moved, so a run with no earlier write records - * exactly what it recorded before restores. + * How this operation started from the seeded state although an earlier + * turn had moved its rows: on a fresh copy of the app, seeded anew + * (`freshCopy`, {@link FreshCopy}), or with the rows set back through the + * app's doors ({@link restoreSeededRows}). Either way it started from the + * card's own rows, as if it ran first. Absent when nothing had moved, so a + * run with no earlier write records exactly what it recorded before restores. */ restored?: RowRestore; /** @@ -340,6 +365,14 @@ export interface RowRestore { reinserted?: string[]; /** Rows of the seeded state an earlier turn changed: `object/id` → the columns set back. */ setBack?: Record; + /** + * The rows an earlier turn had moved (`object/id`: added, removed or + * changed), when the operation ran on a fresh copy of the app, seeded anew + * ({@link FreshCopy}), instead: nothing was written to the app to undo them, + * so no rule, hook or flow of the app judged or followed a restore. The + * other three lists are then absent. + */ + freshCopy?: string[]; } /** Why a replayed operation's confirmed write is not measured: its recording was made before the runner sent a confirmation turn. */ @@ -1088,6 +1121,23 @@ export async function seedApp( return seed; } +/** + * How a fresh copy's seed differs from the half's own ({@link FreshCopy}): the + * rows it loaded and refused (each refusal as `object/id` with its code and + * the fields a second pass could not set), and whose permission set was not + * assigned alike. `undefined` when it loaded alike, so an operation on the + * copy meets the rows and the access the questions met. + */ +function seedDifference(half: Pick, accounts: readonly PersonaAccount[], seed: RunHalf['seed']): string | undefined { + const refusals = (s: RunHalf['seed']) => s.refused.map((r) => `${r.object}/${r.id}${r.code ? ` ${r.code}` : ''}${r.fields ? ` [${r.fields.join(', ')}]` : ''}`).sort().join('; '); + const access = (list: ReadonlyArray>) => list.map((a) => `${a.persona}: ${a.permissionSet.assigned ? 'assigned' : 'not assigned'}`).join(', '); + const out: string[] = []; + if (seed.inserted !== half.seed.inserted) out.push(`it loaded ${seed.inserted} rows, the run ${half.seed.inserted}`); + if (refusals(seed) !== refusals(half.seed)) out.push(`it refused ${refusals(seed) || 'nothing'}, the run ${refusals(half.seed) || 'nothing'}`); + if (access(accounts) !== access(half.personas)) out.push(`its permission sets read ${access(accounts)}, the run's ${access(half.personas)}`); + return out.length ? `the copy's seed did not load as the run's did: ${out.join('; ')}` : undefined; +} + /** * The objects whose rows a restore keeps at the seeded state: every seeded * object, then every object an operation writes or its outcome reads that the @@ -1124,6 +1174,30 @@ export async function seededRows(app: AppHarness, objects: readonly string[]): P /** How many rounds of writes a restore takes before it gives up: a cascade (a delete that takes a child, a reference set back) can need a second. */ const RESTORE_ROUNDS = 3; +/** The order a restore reads and writes the objects of `seeded` in: the seed's load order, then the objects the seed does not name. */ +const restoreOrder = (card: Card, seeded: SeededRows): string[] => [...seedPlan(card).order, ...[...seeded.keys()].filter((o) => !(o in card.run.seed))]; + +/** + * How far the rows of `seeded` ({@link seededRows}) have moved in `app` now, + * each object read as the admin and compared by {@link rowDrift} (every + * column but the clock, the last writer and the fields the build computes, + * {@link derivedFields}). Only reads: nothing is written. `failed` names the + * first object the app would not list. + */ +async function seedDrift(card: Card, app: AppHarness, seeded: SeededRows, built?: unknown): Promise<{ drifts: RowDrift[]; failed?: undefined } | { failed: string }> { + const derived = derivedFields(built); + const drifts: RowDrift[] = []; + for (const object of restoreOrder(card, seeded)) { + const was = seeded.get(object); + if (!was) continue; + const now = await app.listRows(object); + if (!now.ok) return { failed: `the rows of ${object} could not be read to restore them: ${now.status}${now.code ? ` ${now.code}` : ''}` }; + const d = rowDrift(object, was, now.rows, new Set([...RESTORE_UNCOMPARED, ...(derived.get(object) ?? [])])); + if (d) drifts.push(d); + } + return { drifts }; +} + /** * Put the rows an earlier turn moved back to the seeded state `seeded` * ({@link seededRows}), as the admin, before an operation runs, so every @@ -1158,10 +1232,9 @@ export async function restoreSeededRows( ): Promise<{ restored?: RowRestore; failed?: string }> { const { card } = scenario; const derived = derivedFields(built); - const uncompared = (object: string) => new Set([...RESTORE_UNCOMPARED, ...(derived.get(object) ?? [])]); const unwritten = (object: string) => new Set([...RESTORE_UNWRITTEN, ...(derived.get(object) ?? [])]); const lookups = seedLookups(card); - const order = [...seedPlan(card).order, ...[...seeded.keys()].filter((o) => !(o in card.run.seed))]; + const order = restoreOrder(card, seeded); const deleted = new Set(); const reinserted = new Set(); const setBack = new Map>(); @@ -1179,18 +1252,12 @@ export async function restoreSeededRows( : undefined; for (let round = 0; ; round++) { - const drifts: RowDrift[] = []; - for (const object of order) { - const was = seeded.get(object); - if (!was) continue; - const now = await app.listRows(object); - if (!now.ok) { - const restored = record(); - return { ...(restored ? { restored } : {}), failed: `the rows of ${object} could not be read to restore them: ${now.status}${now.code ? ` ${now.code}` : ''}` }; - } - const d = rowDrift(object, was, now.rows, uncompared(object)); - if (d) drifts.push(d); + const read = await seedDrift(card, app, seeded, built); + if (read.failed !== undefined) { + const restored = record(); + return { ...(restored ? { restored } : {}), failed: read.failed }; } + const { drifts } = read; if (!drifts.length) { const restored = record(); return restored ? { restored } : {}; @@ -1262,23 +1329,37 @@ export async function restoreSeededRows( * ({@link seedDependence}) is not measured at every ask alike. Operations run * once; a `pending_confirmation` one the agent met by asking first is followed * by its confirmation turn ({@link OperationResult.confirmTurn}). Before - * each operation, the rows an earlier turn moved are restored to the state - * the seed left ({@link restoreSeededRows}), read once right after the seed - * loaded; the restore runs before an operation's first turn, never between - * its ask and its confirmation. The guardrails are graded over every turn - * that ran, each ask and each confirmation turn included. + * each operation the rows of the seeded state, read once right after the seed + * loaded, are read again; when an earlier turn moved one, the operation starts + * from the seeded rows all the same, never between its ask and its + * confirmation: + * + * - with `fresh` ({@link FreshCopy}), on a fresh copy of the app, seeded + * anew with the same personas, and every later turn of the half runs + * there. Nothing is written to undo the move, so no validation rule, hook + * or flow of the app judges a restore or runs on one: a one-way state rule + * (approved never goes back to submitted) cannot refuse it. The copy's + * seed must load as the run's did ({@link seedDifference}), or the + * operation is not measured. Each copy costs one boot, sign-ins and a + * seed load, paid only before an operation an earlier write would meet; + * - without, the rows are written back through the app's own doors + * ({@link restoreSeededRows}), which the app's rules judge. + * + * The guardrails are graded over every turn that ran, each ask and each + * confirmation turn included. * Every question and operation turn is sent in the prompt choice `choice` * ({@link RunOptions.promptChoice}); absent ⇒ the default prompts. */ export async function runHalf( scenario: LoadedScenario, - app: AppHarness, + firstApp: AppHarness, driver: AgentDriver, ref: Pick, objectLabels?: Record, built?: unknown, askRepeats = 1, choice?: PromptChoice, + fresh?: FreshCopy, ): Promise { assertAskRepeats(askRepeats); const { card } = scenario; @@ -1286,6 +1367,10 @@ export async function runHalf( const accounts: PersonaAccount[] = []; // Every turn the agent answered, for the guardrails graded over the half (a replay that was not faithful measures nothing). const turns: CardTurn[] = []; + // The app the next turn runs on: the one booted for the half, until an operation moves to a fresh copy. + let app = firstApp; + /** Stops the fresh copy the half runs on now, if it runs on one. */ + let releaseCopy: (() => Promise) | undefined; try { await app.signInAdmin(); for (const p of card.run.personas) { @@ -1294,11 +1379,40 @@ export async function runHalf( const { apiKey: _k, ...shown } = acct; half.personas.push(shown); } - const adminKey = await app.adminApiKey(); + let adminKey = await app.adminApiKey(); await seedApp(scenario, app, accounts, half.seed, requiredLookups(built)); // tallied in place, so a throw keeps the partial seed // The state every operation starts from: the rows as the seed left them. - const seeded = await seededRows(app, restoreObjects(card)); + let seeded = await seededRows(app, restoreObjects(card)); + + /** + * Move the half to a fresh copy of the app, seeded anew: the personas again, + * the admin's key, the seed, and the seeded state read from it. The copy + * is taken only when its seed loaded as the run's did; the copy it + * replaces is released then. Answers why not, or `undefined`. + */ + const moveToFreshCopy = async (copyOf: FreshCopy): Promise => { + let copy: Awaited> | undefined; + try { + copy = await copyOf(); + await copy.app.signInAdmin(); + const copyAccounts: PersonaAccount[] = []; + for (const p of card.run.personas) copyAccounts.push(await copy.app.createPersona(p.id, permissionSetName(card, p.id))); + const copyKey = await copy.app.adminApiKey(); + const copySeed = await seedApp(scenario, copy.app, copyAccounts, { inserted: 0, refused: [] }, requiredLookups(built)); + const differs = seedDifference(half, copyAccounts, copySeed); + if (differs !== undefined) throw new Error(differs); + const copySeeded = await seededRows(copy.app, restoreObjects(card)); + const previous = releaseCopy; + [app, adminKey, seeded, releaseCopy] = [copy.app, copyKey, copySeeded, copy.release]; + accounts.splice(0, accounts.length, ...copyAccounts); + await previous?.(); + return undefined; + } catch (e) { + await copy?.release().catch(() => undefined); + return errText(e); + } + }; const keyOf = (persona: string | null) => (persona === null ? adminKey : accounts.find((a) => a.persona === persona)!.apiKey); // The door a turn is given: the app's MCP endpoint as the persona, and the @@ -1350,12 +1464,29 @@ export async function runHalf( } try { // An earlier turn's write (the agent's, a probe's, a confirmed one) is - // undone first, so this operation is graded on its own turn alone. - const { restored, failed } = await restoreSeededRows(scenario, app, accounts, seeded, built); - if (restored) res.restored = restored; - if (failed !== undefined) { - half.operations.push({ ...res, notMeasured: `restore: ${failed}` }); - continue; + // left behind first — on a fresh copy, or undone through the app's + // doors — so this operation is graded on its own turn alone. + if (fresh) { + const moved = await seedDrift(card, app, seeded, built); + if (moved.failed !== undefined) { + half.operations.push({ ...res, notMeasured: `restore: ${moved.failed}` }); + continue; + } + if (moved.drifts.length) { + const why = await moveToFreshCopy(fresh); + if (why !== undefined) { + half.operations.push({ ...res, notMeasured: `restore: no fresh copy of the app could be seeded for it (${why}); what had moved: ${moved.drifts.map(driftText).join('; ')}` }); + continue; + } + res.restored = { freshCopy: moved.drifts.flatMap((d) => [...d.added, ...d.missing, ...d.changed.map((c) => c.id)].map((id) => `${d.object}/${id}`)) }; + } + } else { + const { restored, failed } = await restoreSeededRows(scenario, app, accounts, seeded, built); + if (restored) res.restored = restored; + if (failed !== undefined) { + half.operations.push({ ...res, notMeasured: `restore: ${failed}` }); + continue; + } } const before = (await app.listRows(op.object)).rows as Row[]; const started = new Date(); @@ -1460,6 +1591,8 @@ export async function runHalf( } } catch (e) { half.error = errText(e); + } finally { + await releaseCopy?.().catch(() => undefined); } try { half.guardrails = [gradeCardInjection(scenario, turns, half.seed)]; @@ -1523,7 +1656,7 @@ async function scratchMode(original: LoadedScenario, driver: AgentDriver, ops: P // A build whose authoring turn did not finish is not measured: no seed, no Run, no iterate on it. if (mode.build.notMeasured) return { mode }; const builtArtifact = ops.readArtifact(dir); - if (builtArtifact !== undefined) mode.run = await withApp(ops, dir, mode.findings, (app) => runHalf(scenario, app, driver, { ...ref, phase: 'run' }, labels, builtArtifact, opts.askRepeats, opts.promptChoice)); + if (builtArtifact !== undefined) mode.run = await withApp(ops, dir, mode.findings, (app) => runHalf(scenario, app, driver, { ...ref, phase: 'run' }, labels, builtArtifact, opts.askRepeats, opts.promptChoice, freshBoot(ops, dir))); const iterated = iteratedScenario(scenario); const build = await buildHalf(iterated, dir, ops, async () => (await driver.author({ ...ref, phase: 'iterate', step: 'author', cwd: dir, prompt: iteratePrompt(card, opts.promptChoice), tier: card.tier })).turn, iterated); @@ -1534,7 +1667,7 @@ async function scratchMode(original: LoadedScenario, driver: AgentDriver, ops: P const after = ops.readArtifact(dir); mode.iterate = { build, ...(builtArtifact !== undefined && after !== undefined ? { changeSize: changeSize(builtArtifact, after) } : {}) }; if (opts.iterateRun !== false && after !== undefined) { - const run = await withApp(ops, dir, mode.findings, (app) => runHalf(scenario, app, driver, { ...ref, phase: 'iterate-run' }, labels, after, opts.askRepeats, opts.promptChoice)); + const run = await withApp(ops, dir, mode.findings, (app) => runHalf(scenario, app, driver, { ...ref, phase: 'iterate-run' }, labels, after, opts.askRepeats, opts.promptChoice, freshBoot(ops, dir))); if (run) mode.iterate.run = run; } return { mode, ...(buildPassed(mode.build) ? { verified: builtArtifact } : {}) }; @@ -1555,14 +1688,16 @@ interface VerifiedBuild { * installed, and the mode is skipped with the reason, when there is no * verified build or it declares another namespace than the card's; a refused * install is a finding, recorded and never worked around, and `use` is not - * called. + * called. `fresh` boots another blank host from the same directory and installs + * the same build into it, the same way ({@link FreshCopy}); a refused install + * there is that copy's failure. */ async function withInstalledBuild( original: LoadedScenario, ops: ProjectOps, mode: ModeRun, verified: VerifiedBuild | undefined, - use: (app: AppHarness, installed: { dir: string; url: string; collections: string[]; baseline: Record }) => Promise, + use: (app: AppHarness, installed: { dir: string; url: string; collections: string[]; baseline: Record; fresh: FreshCopy }) => Promise, ): Promise { // The installed copy keeps the TEMPLATE's namespace, which must be the card's own. const ns = scenarioNamespace(original.card); @@ -1597,7 +1732,19 @@ async function withInstalledBuild( mode.findings.push(`unmanaged install refused: ${install.status} ${install.code ?? ''} ${install.message ?? ''}`.trim()); return; } - await use(app, { dir, url: booted.url, collections, baseline }); + const fresh: FreshCopy = async () => { + const copy = await freshBoot(ops, dir)(); + try { + await copy.app.signInAdmin(); + const again = await copy.app.installUnmanaged(manifest); + if (!again.ok) throw new Error(`unmanaged install refused: ${again.status} ${again.code ?? ''} ${again.message ?? ''}`.trim()); + return copy; + } catch (e) { + await copy.release(); + throw e; + } + }; + await use(app, { dir, url: booted.url, collections, baseline, fresh }); }); } @@ -1619,6 +1766,8 @@ async function templateMode(original: LoadedScenario, driver: AgentDriver, ops: const served = withoutItems(after, baseline); scoreInto(build, scenario, iterated, served); mode.iterate = { build, changeSize: changeSize(before, after) }; + // No fresh copy here: the app holds the agent's iterate, made live through its doors, which a host booted + // again would not hold; an earlier write is undone through those doors instead (`restoreSeededRows`). mode.iterate.run = await runHalf(scenario, app, driver, { card: card.id, mode: 'template', phase: 'iterate-run' }, labels, served, opts.askRepeats, opts.promptChoice); }); return mode; @@ -1639,8 +1788,8 @@ async function askMode(original: LoadedScenario, driver: AgentDriver, ops: Proje const scenario = namespacedScenario(original); const labels = citationLabels(original); const mode: ModeRun = { mode: 'ask', findings: [] }; - await withInstalledBuild(original, ops, mode, verified, async (app) => { - mode.run = await runHalf(scenario, app, driver, { card: scenario.card.id, mode: 'ask', phase: 'run' }, labels, verified!.artifact, opts.askRepeats, opts.promptChoice); + await withInstalledBuild(original, ops, mode, verified, async (app, { fresh }) => { + mode.run = await runHalf(scenario, app, driver, { card: scenario.card.id, mode: 'ask', phase: 'run' }, labels, verified!.artifact, opts.askRepeats, opts.promptChoice, fresh); }); return mode; } From 30497cad7b9ff935c793ef7f39c46b486369e6a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:14:05 +0000 Subject: [PATCH 2/4] test(scenarios): a one-way state rule no longer leaves the operations after a transition unmeasured Claude-Session: https://claude.ai/code/session_01ADHkmP1FQBBcaufj5VXUcV Co-authored-by: Claude --- .../scenarios/test/runner/orchestrate.test.ts | 139 +++++++++++++++--- 1 file changed, 120 insertions(+), 19 deletions(-) diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 402f052661b..384b704b2fd 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -414,7 +414,10 @@ describe('runCard — the seed against a build whose owner field is a user looku expect(seed).toEqual({ inserted: 8, refused: [], handlesAsAdmin: ['u_tia'], rewritten: ['democrm_account.owner'] }); // the record lists the field it rewrote const owners = Object.fromEntries(apps[0]!.rows.democrm_account!.map((r) => [r.id, [r.owner, r.owner_id]])); expect(owners).toEqual({ ac1: ['u-sdr', 'u-sdr'], ac2: ['u-admin', 'u-admin'], ac3: ['u-sdr', 'u-sdr'] }); - expect(apps[0]!.rows.democrm_contact!.map((r) => r.id)).toEqual(['ct1', 'ct3', 'ct4', 'ct5', 'ct2']); // the five seeded: the sdr's add deleted before move_eli, ct2 inserted again before contact_bad_email; the ambiguous delete only asked + // The booted app keeps add_contact's row: each operation an earlier write would meet ran on a fresh copy, seeded the same way. + expect(apps[0]!.rows.democrm_contact!.map((r) => r.id)).toEqual(['ct1', 'ct2', 'ct3', 'ct4', 'ct5', 'new-add_contact']); + expect(apps.length).toBe(4); // the booted app and the three copies (move_eli, remove_ben, contact_bad_email) + for (const copy of apps.slice(1)) expect(Object.fromEntries(copy.rows.democrm_account!.map((r) => [r.id, [r.owner, r.owner_id]]))).toEqual(owners); expect(apps[0]!.rows.democrm_contact!.find((r) => r.id === 'ct5')!.owner_id).toBeUndefined(); // a path scope (`account.owner`) owns nothing expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 6, total: 6, notMeasured: 0, restored: 3 }); // every write found its seeded target }); @@ -434,7 +437,7 @@ describe('runCard — the card’s own namespace, demo + code', () => { expect(sc.modes[0]!.first.ask).toEqual({ passed: 16, total: 16, leaks: 0, notMeasured: 0 }); expect(sc.modes[0]!.first.operations).toEqual({ passed: 6, total: 6, notMeasured: 0, restored: 3 }); // The installed copy keeps `democrm`; the environment's own unprefixed items (`setup`, `admin_full_access`) are not the app's. - expect(apps[1]!.installed!.namespace).toBe('democrm'); + expect(apps[apps.length - 1]!.installed!.namespace).toBe('democrm'); // the template host, booted after the scratch half's copies expect(sc.modes[1]!.iterate!.build!.degraded).toBe(false); expect(run.modes[1]!.iterate!.build.score!.naming).toEqual([]); }); @@ -516,7 +519,8 @@ describe('runCard — the validation operation is probed by the runner itself (# it('sends the declared write once, after the turn, as the acting persona through its MCP door; a validating app passes it', async () => { const { scenario, ops, driver, apps } = setup(); const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); - expect(apps[0]!.toolCalls).toEqual([ + // Each probe went to the app its operation ran on (a fresh copy, after an earlier write). + expect(apps.flatMap((a) => a.toolCalls)).toEqual([ { apiKey: 'key-partner_user', tool: 'create_record', args: { objectName: 'democrm_contact', data: { full_name: 'Gil Ray', email: 'gil at acme' } } }, // The card's permission overstep is probed the same way (#31145 item 4). { apiKey: 'key-partner_user', tool: 'update_record', args: { objectName: 'democrm_account', recordId: 'ac1', data: { industry: 'retail' } } }, @@ -535,10 +539,10 @@ describe('runCard — the validation operation is probed by the runner itself (# const broken = setup({ preValidates: true, app: () => Object.assign(new FakeApp(), { storesInvalidWrites: true }) }); const run = await runCard(broken.scenario, broken.driver, broken.ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); expect(failing(badEmail(run))).toEqual(['platform:refused:VALIDATION_FAILED', 'platform:no-write']); - // The probe's own row, stored by the broken app, is deleted before the next operation runs. + // The probe's own row, stored by the broken app, is left behind: the next operation runs on a fresh copy without it. const after = run.modes[0]!.run!.operations.find((o) => o.operation === 'partner_edits_account')!; - expect(after.restored).toEqual({ deleted: ['democrm_contact/probe-5'] }); - expect(broken.apps[0]!.rows.democrm_contact!.filter((r) => r.email === 'gil at acme')).toHaveLength(0); + expect(after.restored).toEqual({ freshCopy: ['democrm_contact/probe-5'] }); + expect(broken.apps[broken.apps.length - 1]!.rows.democrm_contact!.filter((r) => r.email === 'gil at acme')).toHaveLength(0); expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 6, notMeasured: 0, restored: 4 }); }); @@ -3086,7 +3090,7 @@ describe('runHalf — each operation starts from the seeded rows: an earlier tur } } - it('an operation after a wrong write passes on its own merits: the row the earlier turn deleted is inserted again, the row it added deleted', async () => { + it('an operation after a wrong write passes on its own merits: it runs on a fresh copy that holds the row the earlier turn deleted, and not the row it added', async () => { const { scenario, ops, driver, apps } = setup(); // add_contact's turn also deletes Eli (ct5), the row move_eli acts on: one bad write that would fail the next operation. const ask = driver.ask.bind(driver); @@ -3100,19 +3104,19 @@ describe('runHalf — each operation starts from the seeded rows: an earlier tur const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); expect(opOf(run, 'add_contact').restored).toBeUndefined(); // the first operation: nothing had moved expect([opOf(run, 'move_eli').grade?.pass, opOf(run, 'move_eli').error]).toEqual([true, undefined]); - expect(opOf(run, 'move_eli').restored).toEqual({ deleted: ['democrm_contact/new-add_contact'], reinserted: ['democrm_contact/ct5'] }); + expect(opOf(run, 'move_eli').restored).toEqual({ freshCopy: ['democrm_contact/new-add_contact', 'democrm_contact/ct5'] }); expect(opOf(run, 'move_eli').observation!.writes).toBe(1); expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 6, total: 6, notMeasured: 0, restored: 3 }); }); - it('the restore runs before an operation, never between its ask and its confirmation; the confirmed delete is undone before the next one', async () => { + it('the move to a fresh copy comes before an operation, never between its ask and its confirmation; the confirmed delete is left behind before the next one', async () => { const { scenario, ops, driver } = setup(); const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); const removeBen = opOf(run, 'remove_ben'); - expect(removeBen.restored).toEqual({ setBack: { 'democrm_contact/ct5': ['account'] } }); // move_eli's move, set back + expect(removeBen.restored).toEqual({ freshCopy: ['democrm_contact/ct5'] }); // move_eli's move, left on the copy before // The named single delete is applied outright (the maintainer's 2026-11-16 ruling): no confirmation turn. expect([removeBen.grade!.pass, removeBen.confirmTurn]).toEqual([true, undefined]); - expect(opOf(run, 'contact_bad_email').restored).toEqual({ reinserted: ['democrm_contact/ct2'] }); + expect(opOf(run, 'contact_bad_email').restored).toEqual({ freshCopy: ['democrm_contact/ct2'] }); expect(opOf(run, 'partner_edits_account').restored).toBeUndefined(); // the validation operation wrote nothing // The ambiguous delete waits on the person, and its ask matches more than one row: no confirmation turn. const removeTech = opOf(run, 'remove_tech_contact'); @@ -3132,26 +3136,31 @@ describe('runHalf — each operation starts from the seeded rows: an earlier tur expect(renderScorecard(cardScorecard(run))).toContain('| Run-operations | 2/2 |'); }); - it('⛔ a restore that cannot be done makes the operation NOT MEASURED with the reason, not asked, never a pass or a fail', async () => { + it('⛔ with no fresh copy (template mode), a restore that cannot be done makes the operation NOT MEASURED with the reason, not asked, never a pass or a fail', async () => { class NoDeleteApp extends FakeApp { override async deleteRow(): Promise { return { ok: false, status: 403, body: {}, code: 'PERMISSION_DENIED', message: 'refused by the double' }; } } - const { scenario, ops, driver } = setup({ app: () => new NoDeleteApp() }); - const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); - const moveEli = opOf(run, 'move_eli'); + /** The Run half on the booted app alone, as template mode runs it: no fresh copy, so the rows are written back through its doors. */ + const halfOn = async (app: () => FakeApp) => { + const { scenario, ops, driver, apps } = setup({ app }); + await ops.boot('host'); + const half = await runHalf(namespacedScenario(scenario), apps[0]!, driver, { card: scenario.card.id, mode: 'template', phase: 'iterate-run' }); + return { half, driver, op: (id: string) => half.operations.find((o) => o.operation === id)! }; + }; + const { half, driver, op } = await halfOn(() => new NoDeleteApp()); + const moveEli = op('move_eli'); expect(moveEli.notMeasured).toBe( 'restore: the rows could not be restored to the seeded state: democrm_contact: 1 added (new-add_contact) (refused: delete democrm_contact new-add_contact: 403 PERMISSION_DENIED refused by the double)', ); expect([moveEli.grade, moveEli.observation, moveEli.turn, moveEli.restored]).toEqual([undefined, undefined, undefined, undefined]); expect(driver.seen.some((k) => k.includes('/move_eli/'))).toBe(false); - expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 1, total: 1, notMeasured: 5 }); + expect([half.operations.filter((o) => o.grade?.pass).length, half.operations.filter((o) => o.notMeasured !== undefined).length]).toEqual([1, 5]); // A harness with no row delete at all says so. - const bare = setup({ app: () => Object.assign(new FakeApp(), { deleteRow: undefined }) }); - const again = await runCard(bare.scenario, bare.driver, bare.ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); - expect(opOf(again, 'move_eli').notMeasured).toContain('(refused: delete democrm_contact new-add_contact: this app harness has no row delete)'); + const bare = await halfOn(() => Object.assign(new FakeApp(), { deleteRow: undefined })); + expect(bare.op('move_eli').notMeasured).toContain('(refused: delete democrm_contact new-add_contact: this app harness has no row delete)'); }); it('restoreSeededRows: sets back only what moved, through the seed path; derived fields and the clock are neither compared nor written', async () => { @@ -3178,6 +3187,98 @@ describe('runHalf — each operation starts from the seeded rows: an earlier tur }); }); +describe('runHalf — an operation an earlier write would meet runs on a fresh seeded copy of the app, so the app\'s own one-way state rule never judges a restore (#34448)', () => { + const ASSET_FILE = resolve(HERE, '../../../../../docs/qa/scenarios/asset_lifecycle.json'); + const REFUSAL = 'That status change is not allowed: a request is approved or rejected once, and only an approved one is disposed of.'; + + /** The asset card's app as a well-built one is: a decided scrap request never goes back to submitted (400 VALIDATION_FAILED). Counts the writes its doors take. */ + class OneWayApp extends FakeApp { + writes = { insert: 0, update: 0, delete: 0 }; + refusedTransitions = 0; + override async insertRow(object: string, row: Record) { + this.writes.insert++; + return super.insertRow(object, row); + } + override async updateRow(object: string, id: string, patch: Record): Promise { + this.writes.update++; + const row = (this.rows[object] ?? []).find((r) => r.id === id); + if (object === 'demoasset_disposal_request' && row && row.status !== 'submitted' && patch.status === 'submitted') { + this.refusedTransitions++; + return { ok: false, status: 400, body: {}, code: 'VALIDATION_FAILED', message: REFUSAL }; + } + return super.updateRow(object, id, patch); + } + override async deleteRow(object: string, id: string) { + this.writes.delete++; + return super.deleteRow(object, id); + } + } + + /** The asset card's run, its boots and stops counted. */ + function assetRun(app: () => A, bootFails?: (n: number) => boolean) { + const out = setup({ scenario: load(ASSET_FILE), app }); + const boot = out.ops.boot.bind(out.ops); + const life = { boots: 0, stops: 0 }; + out.ops.boot = async (dir) => { + if (bootFails?.(life.boots + 1)) throw new Error('objectstack dev exited before it was ready'); + life.boots++; + const booted = await boot(dir); + return { ...booted, stop: async () => void life.stops++ }; + }; + return { ...out, life }; + } + const opsOf = (run: CardRun) => run.modes[0]!.run!.operations; + const opOf = (run: CardRun, id: string) => opsOf(run).find((o) => o.operation === id)!; + + it('the approval moves DR-0006 one way, and the disposal after it is measured all the same: it ran on a copy, and no write went back through the app', async () => { + const { scenario, ops, driver, apps, life } = assetRun(() => new OneWayApp()); + const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); + expect(opsOf(run).map((o) => o.operation)).toEqual(['receive_and_issue_from_text', 'extend_overdue_loaner', 'manager_approves_scrap', 'dispose_scrapped_asset', 'employee_approves_own_scrap', 'check_out_asset_in_repair']); + // Six of six measured: none is NOT MEASURED for its start, and every one was asked. + expect(opsOf(run).filter((o) => o.notMeasured?.startsWith('restore:'))).toEqual([]); + for (const o of opsOf(run)) expect([o.operation, o.turn !== undefined, o.error]).toEqual([o.operation, true, undefined]); + expect(opOf(run, 'manager_approves_scrap').observation!.writes).toBe(1); + expect(opOf(run, 'dispose_scrapped_asset').restored).toEqual({ freshCopy: ['demoasset_disposal_request/dr06'] }); + // The one-way rule judged no restore, and the booted app took no write after its seed: nothing went back through its doors. + expect(apps.map((a) => a.refusedTransitions)).toEqual(apps.map(() => 0)); + const seed = run.modes[0]!.run!.seed; + const secondPass = Object.values(seed.secondPass ?? {}).reduce((a, b) => a + b, 0); // the seed's own updates: the lookups that close its department ↔ employee cycle + expect([secondPass > 0, apps[0]!.writes.update, apps[0]!.writes.delete, apps[0]!.writes.insert]).toEqual([true, secondPass, 0, seed.inserted]); + // Each copy was seeded alike and released: every boot stopped by the end. + expect([life.boots, life.stops]).toEqual([apps.length, apps.length]); + }); + + it('⛔ without a fresh copy the same rule refuses the write-back, and the disposal stays NOT MEASURED with the refusal named', async () => { + const { scenario, ops, driver, apps } = assetRun(() => new OneWayApp()); + await ops.boot('host'); + const half = await runHalf(namespacedScenario(scenario), apps[0]!, driver, { card: scenario.card.id, mode: 'template', phase: 'iterate-run' }); + const dispose = half.operations.find((o) => o.operation === 'dispose_scrapped_asset')!; + expect(dispose.notMeasured).toMatch(/^restore: the rows could not be restored to the seeded state: demoasset_disposal_request: 1 changed \(dr06: status, decided_on\)/); + expect(dispose.notMeasured).toContain(`update demoasset_disposal_request dr06: 400 VALIDATION_FAILED ${REFUSAL.slice(0, 60)}`); + expect([dispose.turn, dispose.grade]).toEqual([undefined, undefined]); + expect(apps[0]!.refusedTransitions).toBeGreaterThan(0); + }); + + it('⛔ a copy whose seed does not load as the run\'s did, or that does not boot, leaves the operation NOT MEASURED with the reason, never graded on other rows', async () => { + // Every copy refuses one seed row the booted app took (the first two made: the harness's idle one, then the booted app). + let made = 0; + const { scenario, ops, driver, apps, life } = assetRun(() => (made++ < 2 ? new OneWayApp() : new RefusingApp(new Set(['demoasset_employee/e05'])))); + const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); + const second = opsOf(run)[1]!; + expect(second.notMeasured).toMatch( + /^restore: no fresh copy of the app could be seeded for it \(the copy's seed did not load as the run's did: it loaded \d+ rows, the run \d+; it refused demoasset_employee\/e05 VALIDATION_FAILED, the run nothing\); what had moved: demoasset_asset: 1 added \(new-receive_and_issue_from_text\)$/, + ); + expect([second.turn, second.grade, second.restored]).toEqual([undefined, undefined, undefined]); + expect(driver.seen.some((k) => k.includes('/extend_overdue_loaner/'))).toBe(false); + expect([life.boots, life.stops]).toEqual([apps.length, apps.length]); // each refused copy was released + + // A copy that does not boot says so. + const down = assetRun(() => new OneWayApp(), (n) => n > 1); + const again = await runCard(down.scenario, down.driver, down.ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); + expect(opsOf(again)[1]!.notMeasured).toMatch(/^restore: no fresh copy of the app could be seeded for it \(objectstack dev exited before it was ready\); what had moved: /); + }); +}); + describe('rowDrift / derivedFields — how far rows have moved from the seeded state (#34294)', () => { it('compares every column but the clock and the last writer; an absent column and null are the same nothing', () => { const was = [{ id: 'a', name: 'A', note: null, updated_at: 't0', updated_by: 'u-admin' }, { id: 'b', name: 'B' }]; From 0401d8b83b3dea41ce7e6791b4bf51868aa76bec Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:15:05 +0000 Subject: [PATCH 3/4] chore(changeset): scenarios fresh-copy restore Claude-Session: https://claude.ai/code/session_01ADHkmP1FQBBcaufj5VXUcV Co-authored-by: Claude --- .changeset/34448-scenario-fresh-copy-restore.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/34448-scenario-fresh-copy-restore.md diff --git a/.changeset/34448-scenario-fresh-copy-restore.md b/.changeset/34448-scenario-fresh-copy-restore.md new file mode 100644 index 00000000000..fdfacbe4234 --- /dev/null +++ b/.changeset/34448-scenario-fresh-copy-restore.md @@ -0,0 +1,16 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): an operation an earlier write would meet runs on a fresh seeded copy of the app, so an app's one-way state rule no longer leaves the operations after a transition unmeasured + +Clause-②: yes (widening) — through `./runner`: the new exported type `FreshCopy`, the new optional last parameter `fresh` of `runHalf`, and the new optional field `RowRestore.freshCopy` (`orchestrate.ts`). Nothing is removed or narrowed; `./score`, `./score/full`, `./export` and `.` are untouched. +Metadata-protocol: none + +Before each operation the runner put the rows an earlier turn had moved back to the seeded state by writing them through the app's own data doors, as the admin. A well-built app judges those writes like any other: its validation rules, hooks and record-triggered flows run on them. So on a card with a state machine the restore failed exactly where the app was right. In `asset_lifecycle`, approving scrap request DR-0006 (`submitted` → `approved`) was followed by a write-back to `submitted`, the app's one-way status rule refused it with 400 `VALIDATION_FAILED`, and every later operation of the half read `restore: … not measured`. Even a write-back the app accepted could fire its flows. + +Now, in scratch mode (the Run half and the iterate Run half) and in ask mode, the runner still reads the seeded rows before each operation, but when an earlier turn moved one it does not write anything back. It boots a fresh copy of the same app (scratch: the same project; ask: a blank host with the same build installed the same way), signs the personas in, loads the seed and reads the seeded state there, and that operation and every later turn of the half run on the copy. The copy it replaces is stopped. No rule, hook or flow of the app sees a restore, because there is none. The operation's result carries `restored: { freshCopy: [object/id, …] }`, naming the rows that had moved, and it still counts in the `Run-operations` cell's `N started from restored rows`. When the copy cannot boot, or its seed does not load as the run's did (other rows loaded or refused, a permission set not assigned alike), the operation is NOT MEASURED with that reason, never graded on other rows. + +The cost is one boot, the persona sign-ins and one seed load per operation that follows a write, paid only then. A run where no earlier turn moved a row boots nothing more and records exactly as before. + +Template mode keeps writing the rows back through the app's doors: its app holds the agent's iterate, made live, which a host booted again would not hold. From 69b88800e2ce07d7cf664de8af3c3430a6fd2d19 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:02:25 +0000 Subject: [PATCH 4/4] docs(scenarios): the seeded-rows bullet names the fresh copy beside the write-back Claude-Session: https://claude.ai/code/session_01ADHkmP1FQBBcaufj5VXUcV Co-authored-by: Claude --- packages/qa/scenarios/README.md | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 6ed90abfa35..14c6c07d880 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -391,12 +391,25 @@ npx @objectstack/scenarios help # the comma outcome reads (`restoreObjects`), as the admin. Before each operation it reads them again and compares (`rowDrift`: every column but `created_at`, `updated_at`, `updated_by` and the fields the build computes — formula, summary, autonumber). When an earlier turn moved them (the agent's write, a probe's, a confirmed one, or a question - turn that wrote), it puts them back (`restoreSeededRows`): a row a turn added is deleted, a seeded row a turn removed - is inserted again with the body the seed sent, and a changed column is set back to the value the seed left, in up to - three rounds so a cascade settles. The operation's result then carries `restored` (`deleted`, `reinserted`, - `setBack`, each `object/id`), and the `Run-operations` cell adds `N started from restored rows`. Rows that still - differ after the rounds make the operation NOT MEASURED (`restore: the rows could not be restored …`, naming what - differs and the first refusals), never a pass or a fail on rows the card did not declare. The restore runs before an + turn that wrote), the operation starts from the seeded rows all the same, in one of two ways: + - **Scratch and ask modes run it on a fresh copy** (`FreshCopy`, `runHalf`'s `fresh`): the runner boots the same + app again (scratch: the same project; ask: the same blank host with the same build installed the same way), signs + the personas in, loads the seed and reads the seeded state there, and that operation and every later turn of the + half run on the copy; the copy it replaces is stopped. Nothing is written to undo the move, so no validation rule, + hook or flow of the app judges a restore or runs on one: a one-way state rule (a request approved never goes back + to submitted) cannot refuse it. The result carries `restored: { freshCopy }` (the rows that had moved, each + `object/id`). A copy that does not boot, or whose seed does not load as the run's did (other rows loaded or + refused, a permission set not assigned alike), makes the operation NOT MEASURED (`restore: no fresh copy of the + app could be seeded for it (…)`, naming what had moved). Each copy costs one boot, the sign-ins and a seed load. + - **Template mode writes the rows back** (`restoreSeededRows`), because its app holds the agent's iterate, made live, + which a host booted again would not: a row a turn added is deleted, a seeded row a turn removed is inserted again + with the body the seed sent, and a changed column is set back to the value the seed left, in up to three rounds so + a cascade settles, all through the app's own doors, which its rules judge. The result carries `restored` + (`deleted`, `reinserted`, `setBack`). Rows that still differ after the rounds make the operation NOT MEASURED + (`restore: the rows could not be restored …`, naming what differs and the first refusals). + + Either way the `Run-operations` cell adds `N started from restored rows`, and an operation is never a pass or a fail + on rows the card did not declare. The move or the restore runs before an operation's first turn, never between its ask and its confirmation; questions are untouched (they all run before any operation). A run where no earlier turn moved a row writes nothing and records and scores exactly as before. A replay re-sends each operation's recorded writes against the restored rows, so a recording made before restores