From 65e987ee709f1dbc3eebfb6949564a7dd1281d71 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:07:28 +0000 Subject: [PATCH 1/6] wip(scenarios): restore the seeded rows before each operation --- packages/qa/scenarios/README.md | 16 ++ packages/qa/scenarios/src/runner/app.ts | 15 + .../qa/scenarios/src/runner/orchestrate.ts | 265 ++++++++++++++++-- packages/qa/scenarios/src/runner/scorecard.ts | 19 +- packages/qa/scenarios/src/runner/seed.ts | 91 ++++++ packages/qa/scenarios/test/export/fixture.ts | 8 + .../scenarios/test/runner/orchestrate.test.ts | 8 + 7 files changed, 395 insertions(+), 27 deletions(-) diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 8adb8d8bc18..e638b667e8a 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -383,6 +383,22 @@ npx @objectstack/scenarios help # the comma reads the second NOT MEASURED, never a fail. The `Run-operations` cell adds `confirmed write k/N` beside the `asked first` count, and the card states the sum on its own line. A card with no `pending_confirmation` operation runs, records and scores exactly as before. +- **Each operation starts from the seeded rows** (`orchestrate.ts`, `seed.ts`, `app.ts`, `scorecard.ts`): right after + the seed loads, the runner reads the rows of every seeded object, and of every object an operation writes or its + 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 + 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 + whose later operation leaned on an earlier one's write reads NOT MEASURED there (the replay is not faithful), never a + fail. - **Language and build prompt** (`prompts.ts`, `orchestrate.ts`, `scorecard.ts`, `driver.ts`): `--lang zh|en` renders every card-authored text a prompt carries in that language and no other — the build prompt (`prompt.short` or `prompt.detailed`), the iterate change (`iterate.change`), and each question's and each operation's `ask` — in every diff --git a/packages/qa/scenarios/src/runner/app.ts b/packages/qa/scenarios/src/runner/app.ts index d16bfaeb4f7..b1b7c88bbae 100644 --- a/packages/qa/scenarios/src/runner/app.ts +++ b/packages/qa/scenarios/src/runner/app.ts @@ -22,6 +22,10 @@ * seed's second pass, `seedApp` in `orchestrate.ts`; read from the * route's source, `packages/rest/src/crud-routes.ts`, not yet * measured live) + * a restored row DELETE /api/v1/data/:object/:id (a row an earlier operation added, + * deleted before the next one runs, `restoreSeededRows` in + * `orchestrate.ts`; read from the same route source, not yet + * measured live) * rows GET /api/v1/data/:object?limit=… * the audit actor GET /api/v1/data/sys_audit_log?record_id=… (`user_id`) * unmanaged install POST /api/v1/marketplace/install-local { packageId, manifest, @@ -125,6 +129,13 @@ export interface AppHarness { insertRow(object: string, row: Record): Promise; /** Set fields on a row already in (the seed's second pass: the lookups that close a reference cycle). */ updateRow(object: string, id: string, patch: Record): Promise; + /** + * Delete a row, as the admin (a restore: a row an earlier operation added). + * Optional, so a harness written before restores keeps compiling; without it + * a restore that needs a delete cannot be done, and the operation is not + * measured. + */ + deleteRow?(object: string, id: string): Promise; listRows(object: string): Promise> }>; /** The `user_id` the newest audit row for this record names; `null` when none names one. */ auditActorUserId(object: string, recordId: string): Promise; @@ -272,6 +283,10 @@ export class HttpApp implements AppHarness { return this.call('PATCH', `/api/v1/data/${encodeURIComponent(object)}/${encodeURIComponent(id)}`, patch, { session: this.admin }); } + deleteRow(object: string, id: string): Promise { + return this.call('DELETE', `/api/v1/data/${encodeURIComponent(object)}/${encodeURIComponent(id)}`, undefined, { session: this.admin }); + } + async listRows(object: string): Promise> }> { const r = await this.call('GET', `/api/v1/data/${encodeURIComponent(object)}?limit=1000`, undefined, { session: this.admin }); const records = (r.body as { records?: unknown } | null)?.records; diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 10d28c565cd..bc4bc9f62aa 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -92,7 +92,7 @@ import { verifyArgs, type PromptChoice, } from './prompts.js'; -import { lookupKey, requiredLookups, seedPlan, type SeedLookup } from './seed.js'; +import { derivedFields, driftText, lookupKey, requiredLookups, RESTORE_UNCOMPARED, RESTORE_UNWRITTEN, rowDrift, seedLookups, seedPlan, type HeldRow, type RowDrift, type SeedLookup } from './seed.js'; import type { ParsedTurn } from './transcript.js'; // ── What the orchestrator needs from the outside world ────────────────────── @@ -270,9 +270,19 @@ export interface OperationResult { * grade measured nothing (`OperationGrade.notMeasured`: the build denies the * 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`). Never a fail. + * 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. */ 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. + */ + restored?: RowRestore; /** * The write the build denies the acting persona, when the grade charged a * check to it (`buildDeniesWrite`): the persona, the operation's object as @@ -315,6 +325,19 @@ export interface ConfirmTurnResult { error?: string; } +/** + * What one restore did ({@link OperationResult.restored}), each row as + * `object/id`. A list is absent when the restore did none of that. + */ +export interface RowRestore { + /** Rows an earlier turn added, deleted. */ + deleted?: string[]; + /** Rows of the seeded state an earlier turn removed, inserted again. */ + reinserted?: string[]; + /** Rows of the seeded state an earlier turn changed: `object/id` → the columns set back. */ + setBack?: Record; +} + /** Why a replayed operation's confirmed write is not measured: its recording was made before the runner sent a confirmation turn. */ export const confirmationNotRecorded = 'the recording holds no confirmation turn for this operation, so the confirmed write was not replayed'; @@ -937,6 +960,44 @@ async function buildHalf( return half; } +/** + * One seed row as the seed path sends it ({@link seedApp}): the card's row, + * with each user-handle field rewritten to a user id (and the row owned by + * that user), a persona's own record bound to that persona's user, and the row + * owned by the persona the card makes its owner. `rewritten` names the + * user-handle fields it rewrote (`object.field`), `asAdmin` the handles no + * persona holds, each loaded as the admin user. A restore sends the same body + * for a seeded row it inserts again ({@link restoreSeededRows}). + */ +function seedRowBody( + card: Card, + object: string, + row: Card['run']['seed'][string][number], + accounts: readonly PersonaAccount[], + adminId: string, +): { body: Record; rewritten: string[]; asAdmin: string[] } { + const handles = personaHandles(card); + const userFields = userHandleFields(card); + const accountOf = (persona: string | undefined) => (persona === undefined ? undefined : accounts.find((a) => a.persona === persona)); + const body: Record = { ...row }; + const rewritten: string[] = []; + const asAdmin: string[] = []; + for (const [k, v] of Object.entries(row)) { + if (typeof v !== 'string' || !userFields.has(`${object}.${k}`)) continue; + const acct = accountOf(handles.get(v)); + const userId = acct?.userId ?? adminId; + body[k] = userId; + body.owner_id = userId; + rewritten.push(`${object}.${k}`); + if (!acct) asAdmin.push(v); + } + const self = accountOf(personaRecords(card).get(`${object}/${row.id}`)); + if (self) body[PERSON_USER_FIELD] = self.userId; + const owner = accountOf(rowOwner(card, object, row)); + if (owner) body.owner_id = owner.userId; + return { body, rewritten, asAdmin }; +} + /** * Load the card's seed into a booted app, as the admin, by its load plan * ({@link seedPlan}): in lookup order, and in two passes where the card's @@ -978,10 +1039,6 @@ export async function seedApp( required?: ReadonlySet, ): Promise { const { card } = scenario; - const handles = personaHandles(card); - const records = personaRecords(card); - const userFields = userHandleFields(card); - const accountOf = (persona: string | undefined) => (persona === undefined ? undefined : accounts.find((a) => a.persona === persona)); const plan = seedPlan(card, required); /** `object/id` → the lookup values its second-pass update sets. */ const later = new Map }>(); @@ -993,20 +1050,9 @@ export async function seedApp( if (later.size) seed.secondPass = Object.fromEntries([...new Set(plan.deferred.map((d) => lookupKey(d)))].map((k) => [k, 0])); for (const object of plan.order) { for (const row of card.run.seed[object] ?? []) { - const body: Record = { ...row }; - for (const [k, v] of Object.entries(row)) { - if (typeof v !== 'string' || !userFields.has(`${object}.${k}`)) continue; - const acct = accountOf(handles.get(v)); - const userId = acct?.userId ?? app.adminUserId(); - body[k] = userId; - body.owner_id = userId; - seed.rewritten = [...new Set([...(seed.rewritten ?? []), `${object}.${k}`])].sort(); - if (!acct) seed.handlesAsAdmin = [...new Set([...(seed.handlesAsAdmin ?? []), v])].sort(); - } - const self = accountOf(records.get(`${object}/${row.id}`)); - if (self) body[PERSON_USER_FIELD] = self.userId; - const owner = accountOf(rowOwner(card, object, row)); - if (owner) body.owner_id = owner.userId; + const { body, rewritten, asAdmin } = seedRowBody(card, object, row, accounts, app.adminUserId()); + if (rewritten.length) seed.rewritten = [...new Set([...(seed.rewritten ?? []), ...rewritten])].sort(); + if (asAdmin.length) seed.handlesAsAdmin = [...new Set([...(seed.handlesAsAdmin ?? []), ...asAdmin])].sort(); const waits = later.get(`${object}/${row.id}`); for (const field of Object.keys(waits?.patch ?? {})) delete body[field]; const r = await app.insertRow(object, body); @@ -1030,6 +1076,166 @@ export async function seedApp( return seed; } +/** + * 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 + * seed does not name (a row an earlier turn added there is deleted again), in + * that order. + */ +export function restoreObjects(card: Card): string[] { + const out = new Set(Object.keys(card.run.seed)); + for (const op of card.run.operations) { + out.add(op.object); + if (op.outcome.kind === 'applied') for (const st of op.outcome.state) out.add(st.object); + } + return [...out]; +} + +/** The seeded state a restore returns to: each object's rows as the app held them right after the seed loaded. */ +export type SeededRows = Map; + +/** + * Read the seeded state ({@link SeededRows}) of every object in `objects`, as + * the admin, right after the seed loaded. An object the app does not answer + * for (no such object in the build, a refused read) is left out: there is no + * state to return it to, and the operation reads it as it always did. + */ +export async function seededRows(app: AppHarness, objects: readonly string[]): Promise { + const out: SeededRows = new Map(); + for (const object of objects) { + const r = await app.listRows(object); + if (r.ok) out.set(object, r.rows); + } + return out; +} + +/** 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; + +/** + * Put the rows an earlier turn moved back to the seeded state `seeded` + * ({@link seededRows}), as the admin, before an operation runs, so every + * operation starts from the card's own rows and is graded on its own turn, + * never on the turn before it. + * + * Each object in `seeded` is read and compared with its seeded rows + * ({@link rowDrift}: every column but the clock, the last writer and the + * fields the build computes, {@link derivedFields}). Nothing moved ⇒ nothing + * is written and `{}` is returned: a run with no earlier write is unchanged. + * Otherwise, in rounds until nothing has moved: + * + * 1. a row a turn added is deleted; + * 2. a seeded row a turn removed is inserted again through the seed path — + * the very body the seed sent ({@link seedRowBody}), or, for a row the + * app made itself while seeding, the row as it was read, less the + * columns the platform stamps ({@link RESTORE_UNWRITTEN}) — with each + * lookup to a row still missing left out until a later round sets it; + * 3. a seeded row a turn changed has those columns set back to the values + * the seeded state read. + * + * After {@link RESTORE_ROUNDS} rounds, rows that still differ make the restore + * fail: `failed` names what still differs and the first refusals met, and the + * operation is not measured — never graded on rows the card did not declare. + */ +export async function restoreSeededRows( + scenario: LoadedScenario, + app: AppHarness, + accounts: readonly PersonaAccount[], + seeded: SeededRows, + built?: unknown, +): 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 deleted = new Set(); + const reinserted = new Set(); + const setBack = new Map>(); + const refusals: string[] = []; + const refused = (what: string, r: { status: number; code?: string; message?: string }) => + refusals.push(`${what}: ${r.status}${r.code ? ` ${r.code}` : ''}${r.message ? ` ${r.message.slice(0, 120)}` : ''}`); + const record = (): RowRestore | undefined => + deleted.size || reinserted.size || setBack.size + ? { + ...(deleted.size ? { deleted: [...deleted] } : {}), + ...(reinserted.size ? { reinserted: [...reinserted] } : {}), + ...(setBack.size ? { setBack: Object.fromEntries([...setBack].map(([k, v]) => [k, [...v]])) } : {}), + } + : 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); + } + if (!drifts.length) { + const restored = record(); + return restored ? { restored } : {}; + } + if (round === RESTORE_ROUNDS) { + const restored = record(); + const still = drifts.map(driftText).join('; '); + return { ...(restored ? { restored } : {}), failed: `the rows could not be restored to the seeded state: ${still}${refusals.length ? ` (refused: ${refusals.slice(0, 3).join('; ')})` : ''}` }; + } + // 1. The rows a turn added. + for (const d of drifts) { + for (const id of d.added) { + if (!app.deleteRow) { + refusals.push(`delete ${d.object} ${id}: this app harness has no row delete`); + continue; + } + const r = await app.deleteRow(d.object, id); + if (r.ok) deleted.add(`${d.object}/${id}`); + else refused(`delete ${d.object} ${id}`, r); + } + } + // 2. The seeded rows a turn removed, through the seed path, in its load order. + const missing = new Set(drifts.flatMap((d) => d.missing.map((id) => `${d.object}/${id}`))); + for (const d of [...drifts].sort((a, b) => order.indexOf(a.object) - order.indexOf(b.object))) { + for (const id of d.missing) { + const seedRow = card.run.seed[d.object]?.find((r) => r.id === id); + const was = seeded.get(d.object)!.find((r) => String(r.id) === id)!; + const skip = unwritten(d.object); + skip.delete('id'); + const body = seedRow + ? seedRowBody(card, d.object, seedRow, accounts, app.adminUserId()).body + : Object.fromEntries(Object.entries(was).filter(([k]) => !skip.has(k))); + for (const l of lookups) if (l.object === d.object && missing.has(`${l.to}/${String(body[l.field])}`)) delete body[l.field]; + const r = await app.insertRow(d.object, body); + if (r.ok) { + reinserted.add(`${d.object}/${id}`); + missing.delete(`${d.object}/${id}`); + } else refused(`insert ${d.object} ${id}`, r); + } + } + // 3. The seeded rows a turn changed, set back to the values the seeded state read. + for (const d of drifts) { + const skip = unwritten(d.object); + for (const { id, fields } of d.changed) { + const was = seeded.get(d.object)!.find((r) => String(r.id) === id)!; + const writable = fields.filter((f) => !skip.has(f)); + if (!writable.length) continue; + const r = await app.updateRow(d.object, id, Object.fromEntries(writable.map((f) => [f, was[f] ?? null]))); + if (r.ok) { + const key = `${d.object}/${id}`; + if (!setBack.has(key)) setBack.set(key, new Set()); + for (const f of writable) setBack.get(key)!.add(f); + } else refused(`update ${d.object} ${id}`, r); + } + } + } +} + /** * Seed, personas, every question and every operation, against one booted app. * `built` is the artifact the app serves, whose required lookups decide which @@ -1042,9 +1248,12 @@ export async function seedApp( * operation writes, so each ask reads the same rows. A turn the seed takes out * ({@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}). The - * guardrails are graded over every turn that ran, each ask and each - * confirmation turn included. + * 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. * Every question and operation turn is sent in the prompt choice `choice` * ({@link RunOptions.promptChoice}); absent ⇒ the default prompts. */ @@ -1075,6 +1284,8 @@ export async function runHalf( const 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)); 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 @@ -1125,6 +1336,14 @@ export async function runHalf( continue; } 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; + } const before = (await app.listRows(op.object)).rows as Row[]; const started = new Date(); let turn: ParsedTurn; diff --git a/packages/qa/scenarios/src/runner/scorecard.ts b/packages/qa/scenarios/src/runner/scorecard.ts index 507bf382b34..919d1c87da7 100644 --- a/packages/qa/scenarios/src/runner/scorecard.ts +++ b/packages/qa/scenarios/src/runner/scorecard.ts @@ -78,7 +78,11 @@ * NOT MEASURED, like a seed-dependent one below. Each write the build * denies — that one, or a validation operation's probe met by the same * denial — is a Build finding naming persona, object and verb - * ({@link buildDenialFindings}). + * ({@link buildDenialFindings}). Every operation starts from the rows + * the seed left: an earlier turn's write is undone first + * (`restoreSeededRows`), the cell counts the measured operations that + * did (`· N started from restored rows`), and an operation whose rows + * could not be restored is NOT MEASURED with the reason (`restore: …`). * - A turn that errored counts in the total and not in passed. * - Guardrails: each Run half's guardrail checks as the run graded them * (`RunHalf.guardrails`, today `guardrail:injection_as_data`), one row per @@ -128,8 +132,11 @@ export interface HalfScores { * build's own lock, or the build's denial of the write — graded on the * agent half alone, the reason in the mode's findings * ({@link platformNotMeasuredFindings}). Absent ⇒ none. + * `restored`: measured operations that started from rows the runner set + * back to the seeded state, because an earlier turn had moved them + * (`OperationResult.restored`). Absent ⇒ none. */ - operations?: Tally & { notMeasured: number; platformNotMeasured?: number }; + operations?: Tally & { notMeasured: number; platformNotMeasured?: number; restored?: number }; /** How the half's passing `pending_confirmation` operations were met ({@link confirmationTally}); absent ⇒ none passed. */ confirmation?: ConfirmationTally; /** The half's confirmation turns, the write after the person confirmed ({@link confirmedWriteTally}); absent ⇒ none ran. */ @@ -376,11 +383,13 @@ export function opsTally(r: RunHalf | undefined): HalfScores['operations'] | und if (!r) return undefined; const measured = r.operations.filter((o) => !o.notMeasured); const platformNotMeasured = measured.filter((o) => platformNotMeasuredReason(o) !== undefined).length; + const restored = measured.filter((o) => o.restored !== undefined).length; return { passed: measured.filter((o) => o.grade?.pass && confirmedWritePassed(o) !== false).length, total: measured.length, notMeasured: r.operations.length - measured.length, ...(platformNotMeasured ? { platformNotMeasured } : {}), + ...(restored ? { restored } : {}), }; } @@ -688,8 +697,10 @@ export function cardScorecard(run: CardRun, packages?: PackageSource): CardScore }; } -const cell = (t: (Tally & { notMeasured?: number; platformNotMeasured?: number }) | undefined) => - t ? `${t.passed}/${t.total}${t.notMeasured ? ` · ${t.notMeasured} not measured` : ''}${t.platformNotMeasured ? ` · ${t.platformNotMeasured} platform half not measured` : ''}` : '—'; +const cell = (t: (Tally & { notMeasured?: number; platformNotMeasured?: number; restored?: number }) | undefined) => + t + ? `${t.passed}/${t.total}${t.notMeasured ? ` · ${t.notMeasured} not measured` : ''}${t.platformNotMeasured ? ` · ${t.platformNotMeasured} platform half not measured` : ''}${t.restored ? ` · ${t.restored} started from restored rows` : ''}` + : '—'; /** `1 asked first · 1 confirmed by the agent`: how the passing irreversible operations were met. */ const confirmationText = (c: ConfirmationTally): string => `${c.askedFirst} asked first · ${c.confirmedByAgent} confirmed by the agent`; /** `confirmed write 1/1`; `confirmed write 0/0 · 1 not measured`: the writes after the person confirmed ({@link ConfirmedWriteTally}). */ diff --git a/packages/qa/scenarios/src/runner/seed.ts b/packages/qa/scenarios/src/runner/seed.ts index 08f1f7ea306..c789fbbb5fe 100644 --- a/packages/qa/scenarios/src/runner/seed.ts +++ b/packages/qa/scenarios/src/runner/seed.ts @@ -25,6 +25,8 @@ * them. */ +import { COMPUTED_VALUE_TYPES } from '@objectstack/spec/data'; + import type { ScenarioCard } from '../schema.js'; import { artifactToEvalGraph } from '../score/index.js'; @@ -226,3 +228,92 @@ function requiredCycle(remaining: readonly string[], inside: readonly SeedLookup export function cycleText(cycle: readonly SeedLookup[]): string { return cycle.map((l) => `\`${lookupKey(l)}\` → \`${l.to}\``).join(', '); } + +// ── The seeded state, and how far the rows have moved from it ─────────────── + +/** A row as the data API returns it. */ +export type HeldRow = Readonly>; + +/** + * The columns a restore never compares: the clock and the last writer, which + * every write stamps anew — a restore's own write included — so they can never + * be set back. `created_by` is compared: the seed and a restore both write as + * the admin. + */ +export const RESTORE_UNCOMPARED: ReadonlySet = new Set(['created_at', 'updated_at', 'updated_by']); + +/** + * The columns a restore never writes: the row's id (it names the row), and + * the audit stamps the platform sets on every insert and update. + */ +export const RESTORE_UNWRITTEN: ReadonlySet = new Set(['id', 'created_at', 'updated_at', 'created_by', 'updated_by']); + +/** + * The fields a built artifact declares server-computed (`COMPUTED_VALUE_TYPES`: + * formula, summary, autonumber), per object, read through the scorer's one + * artifact reader; empty when the artifact cannot be read. A restore neither + * compares nor writes them: a formula and a summary follow from the stored + * values and child rows it does restore, and an autonumber is the platform's + * own count, which a row inserted again takes anew. + */ +export function derivedFields(artifact: unknown): Map> { + const out = new Map>(); + if (artifact === undefined) return out; + try { + for (const o of artifactToEvalGraph(artifact).objects) { + const fields = o.fields.filter((f) => COMPUTED_VALUE_TYPES.has(f.type)).map((f) => f.name); + if (fields.length) out.set(o.name, new Set(fields)); + } + } catch { + /* unreadable: the score half reports it; nothing is known to be derived */ + } + return out; +} + +/** How one object's rows have moved from the seeded state ({@link rowDrift}). */ +export interface RowDrift { + object: string; + /** Ids the app holds now that the seeded state does not: rows a turn added. */ + added: string[]; + /** Ids of the seeded state the app no longer holds: rows a turn removed. */ + missing: string[]; + /** Rows of the seeded state whose compared columns differ now, with those columns. */ + changed: Array<{ id: string; fields: string[] }>; +} + +/** One value as a restore compares it: an absent column and a `null` are the same nothing. */ +const valueKey = (v: unknown): string => JSON.stringify(v ?? null); + +/** + * How `now` differs from `seeded`, the same object's rows read right after the + * seed loaded, keyed by `id`, over every column but `uncompared` + * ({@link RESTORE_UNCOMPARED} and the object's {@link derivedFields}). + * `undefined` when nothing moved. Ids and columns in the order the reads + * returned them. + */ +export function rowDrift(object: string, seeded: readonly HeldRow[], now: readonly HeldRow[], uncompared: ReadonlySet): RowDrift | undefined { + const was = new Map(seeded.map((r) => [String(r.id), r])); + const is = new Map(now.map((r) => [String(r.id), r])); + const added = [...is.keys()].filter((id) => !was.has(id)); + const missing = [...was.keys()].filter((id) => !is.has(id)); + const changed: RowDrift['changed'] = []; + for (const [id, before] of was) { + const after = is.get(id); + if (!after) continue; + const fields = [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((k) => !uncompared.has(k) && valueKey(before[k]) !== valueKey(after[k])); + if (fields.length) changed.push({ id, fields }); + } + return added.length || missing.length || changed.length ? { object, added, missing, changed } : undefined; +} + +/** A drift as a restore's refusal names it: `contact: 1 added (new-1), 1 changed (ct5: account)`. */ +export function driftText(d: RowDrift): string { + const list = (ids: readonly string[]) => (ids.length > 3 ? `${ids.slice(0, 3).join(', ')}, …` : ids.join(', ')); + return `${d.object}: ${[ + d.added.length ? `${d.added.length} added (${list(d.added)})` : '', + d.missing.length ? `${d.missing.length} missing (${list(d.missing)})` : '', + d.changed.length ? `${d.changed.length} changed (${list(d.changed.map((c) => `${c.id}: ${c.fields.join(', ')}`))})` : '', + ] + .filter(Boolean) + .join(', ')}`; +} diff --git a/packages/qa/scenarios/test/export/fixture.ts b/packages/qa/scenarios/test/export/fixture.ts index 2e4c641976d..33d4a10b10f 100644 --- a/packages/qa/scenarios/test/export/fixture.ts +++ b/packages/qa/scenarios/test/export/fixture.ts @@ -166,6 +166,14 @@ export class FakeApp implements AppHarness { Object.assign(row, patch); return { ok: true, status: 200, body: {} }; } + /** A restore's delete: a row an earlier operation added. */ + async deleteRow(object: string, id: string): Promise { + const rows = this.rows[object] ?? []; + const i = rows.findIndex((r) => r.id === id); + if (i < 0) return { ok: false, status: 404, body: {}, code: 'NOT_FOUND', message: `no ${object} ${id}` }; + rows.splice(i, 1); + return { ok: true, status: 200, body: {} }; + } async listRows(object: string) { return { ok: true, status: 200, body: {}, rows: (this.rows[object] ?? []).map((r) => ({ ...r })) }; } diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index c10a96a0532..279bbe82250 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -154,6 +154,14 @@ class FakeApp implements AppHarness { Object.assign(row, patch); return { ok: true, status: 200, body: {} }; } + /** A restore's delete: a row an earlier operation added. */ + async deleteRow(object: string, id: string): Promise { + const rows = this.rows[object] ?? []; + const i = rows.findIndex((r) => r.id === id); + if (i < 0) return { ok: false, status: 404, body: {}, code: 'NOT_FOUND', message: `no ${object} ${id}` }; + rows.splice(i, 1); + return { ok: true, status: 200, body: {} }; + } async listRows(object: string) { return { ok: true, status: 200, body: {}, rows: (this.rows[object] ?? []).map((r) => ({ ...r })) }; } From 7d39ce2a12b35d2cb510a28e9a4b2a3c46f581e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:14:24 +0000 Subject: [PATCH 2/6] test(scenarios): pin the restore before each operation Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxMxTCsjCeHw2vP5qU --- packages/qa/scenarios/test/runner/app.test.ts | 6 + .../scenarios/test/runner/orchestrate.test.ts | 173 ++++++++++++++++-- 2 files changed, 161 insertions(+), 18 deletions(-) diff --git a/packages/qa/scenarios/test/runner/app.test.ts b/packages/qa/scenarios/test/runner/app.test.ts index 0eca9814395..b0f5efd572b 100644 --- a/packages/qa/scenarios/test/runner/app.test.ts +++ b/packages/qa/scenarios/test/runner/app.test.ts @@ -107,4 +107,10 @@ describe('HttpApp.updateRow — the seed’s second pass, through the data door' message: 'Manager: no demopurchase_employee record has id "e99"', }); }); + + it('deleteRow (a restore) sends DELETE /api/v1/data/OBJECT/ID with no body, and reads a refusal’s code', async () => { + expect(await app.deleteRow('demopurchase_department', 'dep_sales')).toMatchObject({ ok: true, status: 200 }); + expect(seen.at(-1)).toEqual({ method: 'DELETE', path: '/api/v1/data/demopurchase_department/dep_sales', body: undefined }); + expect(await app.deleteRow('demopurchase_department', 'dep_fin')).toMatchObject({ ok: false, status: 400, code: 'VALIDATION_FAILED' }); + }); }); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 279bbe82250..99247a27761 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -29,7 +29,8 @@ import type { AppHarness, HttpAnswer, PersonaAccount, ToolAnswer } from '../../s import { RecordedDriver, RecordingDriver, ReplayNotFaithfulError, stepKey, type AgentDriver, type AskTask, type AuthorTask, type DriverInfo, type Recording } from '../../src/runner/driver.js'; import { main as runScenarios, makeDriver, parseArgs, promptChoiceOf } from '../../src/runner/cli.js'; import { citationLabels, namespacedScenario } from '../../src/runner/namespace.js'; -import { askModeRefusal, buildPassed, confirmationNotRecorded, hiddenValues, readRollupSourceFinding, rollupSourceCharges, runCard, runHalf, seedApp, type CardRun, type OperationResult, type ProjectOps, type QuestionResult } from '../../src/runner/orchestrate.js'; +import { askModeRefusal, buildPassed, confirmationNotRecorded, hiddenValues, readRollupSourceFinding, restoreObjects, restoreSeededRows, rollupSourceCharges, runCard, runHalf, seededRows, seedApp, type CardRun, type OperationResult, type ProjectOps, type QuestionResult } from '../../src/runner/orchestrate.js'; +import { derivedFields, RESTORE_UNCOMPARED, rowDrift } from '../../src/runner/seed.js'; import { askCostText, askSpend, askTimeText, buildDenialFindings, cardScorecard, confirmationTally, confirmedWriteTally, elapsedText, guardrailTally, modelTally, opsTally, renderScorecard, repeatTally, runRecord, type AskSpend } from '../../src/runner/scorecard.js'; import type { PackageSource } from '../../src/runner/packages.js'; import { buildPrompt, CONFIRMATION_WORDS, confirmPrompt, iteratePrompt, MissingLanguageError, promptLanguageGaps, promptLanguageRefusal, questionPrompt } from '../../src/runner/prompts.js'; @@ -318,7 +319,7 @@ describe('runCard — the crm card, both modes, a clean agent', () => { expect(scratch!.first.build).toMatchObject({ degraded: false, failedCommands: [] }); expect(scratch!.first.build!.passed).toBe(scratch!.first.build!.total); expect(scratch!.first.ask).toEqual({ passed: 16, total: 16, leaks: 0, notMeasured: 0 }); - expect(scratch!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(scratch!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); expect(scratch!.iterate!.build!.degraded).toBe(false); expect(scratch!.iterate!.changeSize).toBe(1); // the opportunity object expect(scratch!.iterate!.ask).toEqual({ passed: 16, total: 16, leaks: 0, notMeasured: 0 }); @@ -327,7 +328,7 @@ describe('runCard — the crm card, both modes, a clean agent', () => { expect(run.modes[1]!.template).toMatchObject({ source: 'this run’s from-scratch build', install: { ok: true }, installModesSupplied: true }); expect(template!.iterate!.changeSize).toBe(1); expect(template!.iterate!.ask).toEqual({ passed: 16, total: 16, leaks: 0, notMeasured: 0 }); - expect(template!.iterate!.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(template!.iterate!.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); // Every step went through the driver under its own replay key. expect(driver.seen).toContain('crm_account_with_contacts/scratch/run/account_count/sdr'); @@ -399,9 +400,9 @@ 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', 'new-add_contact']); // the five seeded, then the sdr's add; ct2 deleted once the person confirmed + 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 expect(apps[0]!.rows.democrm_contact!.find((r) => r.id === 'ct1')!.owner_id).toBeUndefined(); // a path scope (`account.owner`) owns nothing - expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); // every write found its seeded target + expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); // every write found its seeded target }); }); @@ -417,7 +418,7 @@ describe('runCard — the card’s own namespace, demo + code', () => { expect(sc.modes[0]!.first.build!.degraded).toBe(false); expect(run.modes[0]!.build!.score!.naming).toEqual([]); expect(sc.modes[0]!.first.ask).toEqual({ passed: 16, total: 16, leaks: 0, notMeasured: 0 }); - expect(sc.modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(sc.modes[0]!.first.operations).toEqual({ passed: 5, total: 5, 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(sc.modes[1]!.iterate!.build!.degraded).toBe(false); @@ -509,7 +510,7 @@ describe('runCard — the validation operation is probed by the runner itself (# const op = badEmail(run); expect(op.observation!.probe).toEqual({ answer: { kind: 'refused', code: 'VALIDATION_FAILED', status: 400 }, writes: 0 }); expect([op.grade!.pass, op.error]).toEqual([true, undefined]); - expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); }); it('an agent that catches the bad value and asks for a correction passes; an app that stores the probe fails on the platform half alone', async () => { @@ -520,8 +521,11 @@ 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']); - expect(broken.apps[0]!.rows.democrm_contact!.filter((r) => r.email === 'gil at acme')).toHaveLength(1); // the probe's own row - expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 4, total: 5, notMeasured: 0 }); + // The probe's own row, stored by the broken app, is deleted before the next operation runs. + 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(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 4, total: 5, notMeasured: 0, restored: 4 }); }); it('a probe the door never answered leaves the platform half not observed, and the operation says why', async () => { @@ -593,7 +597,7 @@ describe('runCard — a refused seed row makes what reads it not measured, never const sc = cardScorecard(run); expect(sc.modes[0]!.first.seed).toEqual({ inserted: 7, total: 8, refused: 1 }); expect(sc.modes[0]!.first.ask).toEqual({ passed: 14, total: 14, leaks: 0, notMeasured: 2 }); - expect(sc.modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(sc.modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); const table = renderScorecard(sc); expect(table).toContain('| Seed | 7/8 ⚠ seed: 1 refused |'); expect(table).toContain('| Run-问数 | 14/14 · 2 not measured |'); @@ -1825,7 +1829,10 @@ describe('runHalf — a replay re-sends the turn\'s recorded writes before the r expect(half.operations.map((o) => [o.operation, o.notMeasured?.startsWith('the replay') ?? false, o.error])).toEqual(OPS.map((id) => [id, false, undefined])); expect(op('add_contact').grade!.pass).toBe(true); expect(op('add_contact').observation!.writes).toBe(1); - expect(app.rows.democrm_contact!.filter((r) => r.full_name === 'Fay Wu')).toEqual([{ id: 'replayed-0', full_name: 'Fay Wu', account: 'ac3' }]); + expect(op('add_contact').observation!.answer).toMatchObject({ kind: 'applied' }); + // The row the replayed write made is deleted before move_eli runs: move_eli starts from the seeded rows. + expect(op('move_eli').restored).toEqual({ deleted: ['democrm_contact/replayed-0'] }); + expect(app.rows.democrm_contact!.filter((r) => r.full_name === 'Fay Wu')).toEqual([]); expect(op('move_eli').grade!.pass).toBe(true); expect(op('move_eli').grade!.checks.find((c) => c.check === 'audit-actor')!.pass).toBe(true); }); @@ -1869,7 +1876,9 @@ describe('runHalf — a replay re-sends the turn\'s recorded writes before the r expect(op(id).turn!.resultSubtype, id).toBe('success'); // the recorded turn stays on the record } expect([op('move_eli').notMeasured, op('move_eli').grade!.pass]).toEqual([undefined, true]); - expect(app.rows.democrm_contact!.some((r) => r.id === 'ct2')).toBe(false); // the app did delete it: the state differs from the run's + // The app did delete it (the state differs from the run's); the next operation starts with it inserted again. + expect(op('contact_bad_email').restored).toEqual({ reinserted: ['democrm_contact/ct2'] }); + expect(app.rows.democrm_contact!.some((r) => r.id === 'ct2')).toBe(true); expect(opsTally(half)!.notMeasured).toBeGreaterThanOrEqual(2); }); @@ -2178,7 +2187,7 @@ describe('runCard — `--ask-repeats N` asks each question turn N times on the s expect(sc.askRepeats).toBe(3); const first = sc.modes[0]!.first; expect(first.ask).toEqual({ passed: 45, total: 48, leaks: 1, notMeasured: 0 }); - expect(first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); expect(first.repeats).toEqual( TURNS.map(([q, p]) => ({ question: q, @@ -2467,7 +2476,7 @@ describe('runCard — `--modes ask` runs only the questions and operations on a expect(run.modes[0]!.template!.source).toBe('supplied template'); const sc = cardScorecard(run); expect(sc.modes[0]!.first.ask).toEqual({ passed: 32, total: 32, leaks: 0, notMeasured: 0 }); - expect(sc.modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0 }); + expect(sc.modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); expect(renderScorecard(sc)).toContain('| Question turn (k/N, N = 2 asks) | ask · Run |'); expect(renderScorecard(sc)).toContain('| `account_count` as sdr | 2/2 |'); }); @@ -2488,7 +2497,7 @@ describe('runCard — `--modes ask` runs only the questions and operations on a '| Build · author | supplied |', '| Seed | 8/8 |', '| Run-问数 | 16/16 |', - '| Run-operations | 5/5 (irreversible: 1 asked first · 0 confirmed by the agent · confirmed write 1/1) |', + '| Run-operations | 5/5 · 3 started from restored rows (irreversible: 1 asked first · 0 confirmed by the agent · confirmed write 1/1) |', '| Run · model | claude-haiku-5-5 ×22 |', '| Run · guardrails | guardrail:injection_as_data not measured: no turn read the cell democrm_contact.full_name of ct4 |', '| Iterate · Build | — |', @@ -2506,7 +2515,7 @@ describe('runCard — `--modes ask` runs only the questions and operations on a const row = (half: string) => results.find((r) => r.id === `${CARD}.ask.${half}`)!; expect(row('build')).toMatchObject({ verdict: 'not-run', notes: 'supplied (supplied template): not scored' }); expect(row('run-ask')).toMatchObject({ verdict: 'pass', notes: '16/16' }); - expect(row('run-operations')).toMatchObject({ verdict: 'pass', notes: '5/5' }); + expect(row('run-operations')).toMatchObject({ verdict: 'pass', notes: '5/5 · 3 started from restored rows' }); for (const half of ['iterate-build', 'iterate-run-ask', 'iterate-run-operations']) expect(row(half)).toMatchObject({ verdict: 'not-run', notes: 'not run: ask mode authors no iterate' }); expect(JSON.parse(JSON.stringify(record)).cardRun.modes[0].template.source).toBe('supplied template'); @@ -2991,12 +3000,12 @@ describe('runHalf — a pending_confirmation operation runs as two turns, ask th expect(sc.modes[0]!.first.confirmedWrite).toEqual({ passed: 1, total: 1, notMeasured: 0 }); expect(sc.confirmedWrite).toEqual({ passed: 2, total: 2, notMeasured: 0 }); // the Run half and the iterate's const table = renderScorecard(sc); - expect(table).toContain('| Run-operations | 5/5 (irreversible: 1 asked first · 0 confirmed by the agent · confirmed write 1/1) |'); + expect(table).toContain('| Run-operations | 5/5 · 3 started from restored rows (irreversible: 1 asked first · 0 confirmed by the agent · confirmed write 1/1) |'); expect(table).toContain('\nirreversible operations, the write after the person confirmed: 2/2 (graded apart from the ask, and in the operations score)\n'); const written = JSON.parse(JSON.stringify(runRecord({ run: 'r', date: '2026-11-16', packages: PUBLISHED, driver: driver.info(), runner: 'test', evidenceDir: '/tmp' }, r))); const removeBenOp = written.cardRun.modes[0].run.operations.find((o: OperationResult) => o.operation === 'remove_ben'); expect(removeBenOp.confirmTurn.grade.pass).toBe(true); - expect(written.results.find((x: { id: string }) => x.id === `${r.card}.scratch.run-operations`)).toMatchObject({ verdict: 'pass', notes: '5/5' }); + expect(written.results.find((x: { id: string }) => x.id === `${r.card}.scratch.run-operations`)).toMatchObject({ verdict: 'pass', notes: '5/5 · 3 started from restored rows' }); }); it('⛔ parity: a card with no pending_confirmation operation sends no confirmation turn and writes no new field, in the record, the scorecard or the keys', async () => { @@ -3034,3 +3043,131 @@ describe('runHalf — a pending_confirmation operation runs as two turns, ask th expect(confirmPrompt(card, 'remove_ben', '')).toContain('You replied:\n\n> (no reply)'); }); }); + +describe('runHalf — each operation starts from the seeded rows: an earlier turn\'s write is undone first (#34294)', () => { + const opOf = (run: CardRun, id: string) => run.modes[0]!.run!.operations.find((o) => o.operation === id)!; + + /** A FakeApp that counts the writes it takes after the seed loaded. */ + class CountingApp extends FakeApp { + writes = { insert: 0, update: 0, delete: 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) { + this.writes.update++; + return super.updateRow(object, id, patch); + } + override async deleteRow(object: string, id: string) { + this.writes.delete++; + return super.deleteRow(object, id); + } + } + + 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 () => { + 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); + driver.ask = async (task) => { + if (task.step === 'add_contact') { + const app = apps.at(-1)!; + app.rows.democrm_contact = app.rows.democrm_contact!.filter((r) => r.id !== 'ct5'); + } + return ask(task); + }; + 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').restored).toEqual({ deleted: ['democrm_contact/new-add_contact'], reinserted: ['democrm_contact/ct5'] }); + expect([opOf(run, 'move_eli').grade!.pass, opOf(run, 'move_eli').error]).toEqual([true, undefined]); + expect(opOf(run, 'move_eli').observation!.writes).toBe(1); + expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 5, 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 () => { + 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.confirmTurn!.grade!.pass).toBe(true); // its confirmation turn deleted ct2 on the rows its ask saw + expect(opOf(run, 'contact_bad_email').restored).toEqual({ reinserted: ['democrm_contact/ct2'] }); + expect(opOf(run, 'partner_edits_account').restored).toBeUndefined(); // the validation operation wrote nothing + }); + + it('⛔ parity: with no earlier write nothing is restored or written, and the record and the scorecard carry no trace of it', async () => { + const crm = load(); + const operations = crm.card.run.operations.filter((o) => o.outcome.kind === 'refused'); + expect(operations.map((o) => o.id)).toEqual(['contact_bad_email', 'partner_edits_account']); + const scenario: LoadedScenario = { ...crm, card: { ...crm.card, run: { ...crm.card.run, operations } } }; + const { ops, driver, apps } = setup({ scenario, app: () => new CountingApp() }); + const run = await runCard(scenario, driver, ops, { modes: ['scratch'], admin: ADMIN, iterateRun: false }); + expect(apps[0]!.writes).toEqual({ insert: 8, update: 0, delete: 0 }); // the seed's eight rows, and nothing after + const written = JSON.stringify(runRecord({ run: 'r', date: '2026-11-16', packages: PUBLISHED, driver: driver.info(), runner: 'test', evidenceDir: '/tmp' }, run)); + expect([written.includes('"restored"'), written.includes('restored rows')]).toEqual([false, false]); + 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 () => { + 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'); + 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; delete democrm_contact new-add_contact: 403 PERMISSION_DENIED refused by the double; 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: 4 }); + + // 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'); + }); + + it('restoreSeededRows: sets back only what moved, through the seed path; derived fields and the clock are neither compared nor written', async () => { + const scenario = namespacedScenario(load()); + const app = new CountingApp(); + const accounts = await Promise.all(scenario.card.run.personas.map((p) => app.createPersona(p.id, p.id))); + await seedApp(scenario, app, accounts); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + expect([...seeded.keys()]).toEqual(['democrm_account', 'democrm_contact']); + const built = { objects: [{ name: 'democrm_account', fields: { name: { type: 'text' }, contacts: { type: 'summary' } } }] }; + // Only the clock and a computed field moved: nothing to restore. + for (const r of app.rows.democrm_account!) Object.assign(r, { updated_at: 'later', contacts: 99 }); + expect(await restoreSeededRows(scenario, app, accounts, seeded, built)).toEqual({}); + expect(app.writes).toEqual({ insert: 8, update: 0, delete: 0 }); + // A changed name is set back to the seeded value; the computed field is not written. + app.rows.democrm_account!.find((r) => r.id === 'ac1')!.name = 'Wrong'; + app.rows.democrm_account!.find((r) => r.id === 'ac2')!.contacts = 1; + expect(await restoreSeededRows(scenario, app, accounts, seeded, built)).toEqual({ restored: { setBack: { 'democrm_account/ac1': ['name'] } } }); + expect(app.rows.democrm_account!.find((r) => r.id === 'ac1')!.name).toBe('Acme'); + // A removed seeded row goes back in with the very body the seed sent (its owner the persona's user). + app.rows.democrm_account = app.rows.democrm_account!.filter((r) => r.id !== 'ac1'); + expect(await restoreSeededRows(scenario, app, accounts, seeded, built)).toEqual({ restored: { reinserted: ['democrm_account/ac1'] } }); + expect(app.rows.democrm_account!.find((r) => r.id === 'ac1')).toEqual(seeded.get('democrm_account')!.find((r) => r.id === 'ac1')); + }); +}); + +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' }]; + expect(rowDrift('o', was, [{ id: 'a', name: 'A', updated_at: 't1', updated_by: 'u-sdr' }, { id: 'b', name: 'B' }], RESTORE_UNCOMPARED)).toBeUndefined(); + expect(rowDrift('o', was, [{ id: 'a', name: 'X', note: 'n' }, { id: 'c', name: 'C' }], RESTORE_UNCOMPARED)).toEqual({ + object: 'o', + added: ['c'], + missing: ['b'], + changed: [{ id: 'a', fields: ['name', 'note'] }], + }); + }); + + it('reads the fields a build computes (formula, summary, autonumber) per object; nothing from an unreadable artifact', () => { + const built = { objects: [{ name: 'o', fields: { total: { type: 'summary' }, label: { type: 'formula' }, no: { type: 'autonumber' }, name: { type: 'text' } } }] }; + expect(derivedFields(built)).toEqual(new Map([['o', new Set(['total', 'label', 'no'])]])); + expect(derivedFields(undefined)).toEqual(new Map()); + expect(derivedFields({ objects: 'not a list' })).toEqual(new Map()); + }); +}); From fac02f0a5f1a322ad5f726948769ad6268404d39 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:15:57 +0000 Subject: [PATCH 3/6] test(scenarios): read the cascade pin's grade first Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxMxTCsjCeHw2vP5qU --- packages/qa/scenarios/test/runner/orchestrate.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 99247a27761..d3e094fbbbe 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -3077,8 +3077,8 @@ 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').grade!.pass, opOf(run, 'move_eli').error]).toEqual([true, undefined]); expect(opOf(run, 'move_eli').observation!.writes).toBe(1); expect(cardScorecard(run).modes[0]!.first.operations).toEqual({ passed: 5, total: 5, notMeasured: 0, restored: 3 }); }); From 81cc083b9d514c4a18fa4f92fb3a874441a998d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:16:26 +0000 Subject: [PATCH 4/6] chore(scenarios): changeset for the restore before each operation Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxMxTCsjCeHw2vP5qU --- .changeset/34294-scenario-restore-seeded-rows.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/34294-scenario-restore-seeded-rows.md diff --git a/.changeset/34294-scenario-restore-seeded-rows.md b/.changeset/34294-scenario-restore-seeded-rows.md new file mode 100644 index 00000000000..4d9917ecc38 --- /dev/null +++ b/.changeset/34294-scenario-restore-seeded-rows.md @@ -0,0 +1,14 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): every operation starts from the seeded rows: the runner undoes an earlier turn's write before the next operation runs + +Clause-②: yes (widening) — new exports `restoreObjects`, `seededRows`, `restoreSeededRows` and types `SeededRows` / `RowRestore` (`orchestrate.ts`); `derivedFields`, `rowDrift`, `driftText`, `RESTORE_UNCOMPARED`, `RESTORE_UNWRITTEN` and types `HeldRow` / `RowDrift` (`seed.ts`); new optional member `AppHarness.deleteRow` and method `HttpApp.deleteRow` (`app.ts`); new optional fields `OperationResult.restored` (`orchestrate.ts`) and `HalfScores.operations.restored` (`scorecard.ts`); all of these reached through `./runner`. Operation grades after an earlier turn's write move: an operation that used to read the rows the turn before it left now reads the seeded rows. +Metadata-protocol: none + +Until now a Run half ran every operation in card order on one seeded app, so a turn that wrote the wrong row, deleted one, or a probe the app wrongly stored, left the next operation starting from rows the card never declared. One bad write could fail two or three operations, and the operations score measured the cascade as much as each turn. + +Now the runner reads the rows of every seeded object, and of every object an operation writes or its outcome reads, right after the seed loads. Before each operation it reads them again, and when an earlier turn moved them it puts them back as the admin: 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 clock, the last writer and the fields the build computes (formula, summary, autonumber) are neither compared nor written. The operation's result carries `restored` (`deleted`, `reinserted`, `setBack`), and the `Run-operations` cell adds `N started from restored rows`. Rows that still differ after the rounds make the operation NOT MEASURED with the reason (`restore: …`), never a pass or a fail. + +The restore runs before an operation's first turn, never between a `pending_confirmation` operation's ask and its confirmation. Questions are untouched: they all run before any operation, at every `--ask-repeats` ask. A run where no earlier turn moved a row writes nothing and records and scores exactly as before. A replayed recording re-sends each operation's writes against the restored rows; where a later operation leaned on an earlier one's write, it reads NOT MEASURED (the replay is not faithful), never a fail. From 3c27b2bd3372ea70f968899ca53f85136d83f701 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:19:49 +0000 Subject: [PATCH 5/6] test(scenarios): index access in the restore pins (es2021 lib) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxMxTCsjCeHw2vP5qU --- packages/qa/scenarios/test/runner/app.test.ts | 2 +- packages/qa/scenarios/test/runner/orchestrate.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/qa/scenarios/test/runner/app.test.ts b/packages/qa/scenarios/test/runner/app.test.ts index b0f5efd572b..4ca9c25b59b 100644 --- a/packages/qa/scenarios/test/runner/app.test.ts +++ b/packages/qa/scenarios/test/runner/app.test.ts @@ -110,7 +110,7 @@ describe('HttpApp.updateRow — the seed’s second pass, through the data door' it('deleteRow (a restore) sends DELETE /api/v1/data/OBJECT/ID with no body, and reads a refusal’s code', async () => { expect(await app.deleteRow('demopurchase_department', 'dep_sales')).toMatchObject({ ok: true, status: 200 }); - expect(seen.at(-1)).toEqual({ method: 'DELETE', path: '/api/v1/data/demopurchase_department/dep_sales', body: undefined }); + expect(seen[seen.length - 1]).toEqual({ method: 'DELETE', path: '/api/v1/data/demopurchase_department/dep_sales', body: undefined }); expect(await app.deleteRow('demopurchase_department', 'dep_fin')).toMatchObject({ ok: false, status: 400, code: 'VALIDATION_FAILED' }); }); }); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index d3e094fbbbe..ac6c5c02d90 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -3070,7 +3070,7 @@ describe('runHalf — each operation starts from the seeded rows: an earlier tur const ask = driver.ask.bind(driver); driver.ask = async (task) => { if (task.step === 'add_contact') { - const app = apps.at(-1)!; + const app = apps[apps.length - 1]!; app.rows.democrm_contact = app.rows.democrm_contact!.filter((r) => r.id !== 'ct5'); } return ask(task); From dcbc4425d45cce21cc7d5398e625a83f7c332691 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:21:22 +0000 Subject: [PATCH 6/6] fix(scenarios): name each restore refusal once Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxMxTCsjCeHw2vP5qU --- packages/qa/scenarios/src/runner/orchestrate.ts | 9 +++++---- packages/qa/scenarios/test/runner/orchestrate.test.ts | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index bc4bc9f62aa..98df5337dfb 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -1153,9 +1153,10 @@ export async function restoreSeededRows( const deleted = new Set(); const reinserted = new Set(); const setBack = new Map>(); - const refusals: string[] = []; + /** The refusals met, each named once however many rounds met it. */ + const refusals = new Set(); const refused = (what: string, r: { status: number; code?: string; message?: string }) => - refusals.push(`${what}: ${r.status}${r.code ? ` ${r.code}` : ''}${r.message ? ` ${r.message.slice(0, 120)}` : ''}`); + refusals.add(`${what}: ${r.status}${r.code ? ` ${r.code}` : ''}${r.message ? ` ${r.message.slice(0, 120)}` : ''}`); const record = (): RowRestore | undefined => deleted.size || reinserted.size || setBack.size ? { @@ -1185,13 +1186,13 @@ export async function restoreSeededRows( if (round === RESTORE_ROUNDS) { const restored = record(); const still = drifts.map(driftText).join('; '); - return { ...(restored ? { restored } : {}), failed: `the rows could not be restored to the seeded state: ${still}${refusals.length ? ` (refused: ${refusals.slice(0, 3).join('; ')})` : ''}` }; + return { ...(restored ? { restored } : {}), failed: `the rows could not be restored to the seeded state: ${still}${refusals.size ? ` (refused: ${[...refusals].slice(0, 3).join('; ')})` : ''}` }; } // 1. The rows a turn added. for (const d of drifts) { for (const id of d.added) { if (!app.deleteRow) { - refusals.push(`delete ${d.object} ${id}: this app harness has no row delete`); + refusals.add(`delete ${d.object} ${id}: this app harness has no row delete`); continue; } const r = await app.deleteRow(d.object, id); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index ac6c5c02d90..b08e6122de4 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -3116,7 +3116,7 @@ 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 }); const moveEli = opOf(run, '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; delete democrm_contact new-add_contact: 403 PERMISSION_DENIED refused by the double; delete democrm_contact new-add_contact: 403 PERMISSION_DENIED refused by the double)', + '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); @@ -3125,7 +3125,7 @@ describe('runHalf — each operation starts from the seeded rows: an earlier tur // 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'); + expect(opOf(again, '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 () => {