Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): classify every repair item failure through ItemRun (GBRA-130 A-9)
garrytanfe707c1a5ad2
diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex d6c6afddac..e08f55d832 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -27,6 +27,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */export const ISOLATE_SITES = {+ 'repair.apply_items': 'A-9',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;@@ -50,7 +51,7 @@ export const RUN_SCOPED_CODES: ReadonlySet<string> = new Set(['queue_capacity', 'write_quota_exhausted', 'write_capacity_backpressure', 'maintenance_backpressure', 'database_contention','writer_registration_required', 'writer_identity_invalid', 'writer_not_initialized', 'writer_upgrade_required','writer_not_quiesced', 'writer_admin_locked', 'unsupported_mutation_protocol', 'write_claim_lost', 'connection_lost',- 'permission_denied', 'scope_denied', 'config', 'auth', 'connector_holds_exhausted', 'transfer_in_progress', 'disk_full',+ 'permission_denied', 'schema_owner_required', 'scope_denied', 'config', 'auth', 'connector_holds_exhausted', 'transfer_in_progress', 'disk_full',]);/** Item codes that fail the same way until the item changes. Every other item code is transient. */diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 4f316511e7..df6ab7f0d6 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -12,12 +12,22 @@* `op_checkpoints` under a fingerprint of (kind, brain, sources): a rerun with* the same scope resumes after it, and a finished scan clears it.*- * An item whose apply refuses `invalid_params`, `source_changed` or- * `page_body_segmented` is a per-item verdict, not a run failure: it is recorded in `failed[]`, left as- * it was, and the loop continues without a cursor write for it. A later- * success writes a higher cursor, so a resumed run does not retry it; the next- * full scan (a run with no stored cursor, which every completed run leaves- * behind) does, the same way a `revision_conflict` item is retried.+ * Every item failure is classified by `classifyItemFailure` (item-failure.ts,+ * GBRA-130) through one `ItemRun` per run. An accepted, still pending write is+ * progress and is checked first; a held writer stops the run with its writer+ * status; any other run-scoped failure (a lost connection, a failed+ * transaction, an abort) is rethrown. Every item-scoped failure is a per-item+ * verdict: it is recorded in `failed[]` with the kind's preview as its fix,+ * left as it was, and the loop continues without a cursor write for it. A+ * later success writes a higher cursor, so a resumed run does not retry it;+ * the next full scan (a run with no stored cursor, which every completed run+ * leaves behind, and so does a limited run that ended with only item+ * failures) does, the same way a `revision_conflict` item is retried. When+ * most items fail the breaker stops the run with `item_failures_systemic` and+ * the kind's `onItemFailures` hook is not called. An apply bound to an+ * approved preview (`--expect`) is the operator's answer to one exact set:+ * only `REPAIR_ITEM_FAILURE_CODES` continue it, and any other failure is+ * thrown with its own code (a refused choice, a conflict, a crash).*/import { withAdmissionOrigin } from '../persistence/admission-origin.ts';import { randomUUID } from 'node:crypto';@@ -36,6 +46,8 @@ import type { RepairKindSpec } from './registry.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';+import { readFix } from '../ops/op-fix.ts';+import { ItemRun, type ItemFailure } from '../item-failure.ts';export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;export type RepairKind = typeof REPAIR_KINDS[number];@@ -126,6 +138,11 @@ export interface RepairHandler {* of the selected scope). Runs only when the run ended without an exception.*/report?(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions): Promise<Partial<Pick<RepairResult, 'repaired' | 'remaining' | 'verification' | 'stopped'>>>;+ /**+ * The items whose apply threw an item-scoped failure this run, with the classified failure. Called once before the+ * result is reported, never for a run the breaker stopped (`item_failures_systemic`) or one a run-scoped error ended.+ */+ onItemFailures?(ctx: OperationContext, failures: ReadonlyArray<{ item: RepairItem; failure: ItemFailure }>): Promise<void>;}/**@@ -137,13 +154,18 @@ export interface RepairItemOutcome { applied: boolean; outcome: string; reason?:stop?: { reason: string; message: string; fix?: Action } }/**- * Refusal codes that are one item's verdict: the item is recorded in `failed[]` and the run goes on.+ * Refusal codes a kind may treat as one item's verdict inside its own apply (ghost-pages extends them). The core records+ * every item-scoped failure the same way (`classifyItemFailure`); these codes are a subset of that, and the only+ * failures an apply bound to `--expect` continues past.* `page_body_segmented`: the item's page stores its body in segments and the kind rewrites the whole body as one string.*/export const REPAIR_ITEM_FAILURE_CODES: ReadonlySet<string> = new Set(['invalid_params', 'source_changed', 'page_body_segmented']);-/** An item whose apply refused with a per-item code; its page, file and rows are exactly as before. The next full scan retries it. */-export interface RepairFailedItem { item: string; source_id: string; slug: string; reason: string; message: string; retry: 'next_full_scan' }+/**+ * An item whose apply failed item-scoped; its page, file and rows are exactly as before. The next full scan retries it.+ * `fix` previews the kind for the item's source (read-only), which lists the item again with its current state.+ */+export interface RepairFailedItem { item: string; source_id: string; slug: string; reason: string; message: string; retry: 'next_full_scan'; fix?: Action }export interface RepairResult {kind: RepairKind;@@ -162,10 +184,11 @@ export interface RepairResult {resumed_from: RepairCursor | null;applied: number;skipped: number;- /** Items refused per item (`REPAIR_ITEM_FAILURE_CODES`) and left unchanged; `complete` still means every pending item was attempted. */+ /** Items that failed item-scoped and were left unchanged; `complete` still means every pending item was attempted. */failed: RepairFailedItem[];complete: boolean;- stopped?: { reason: string; message: string; fix?: Action };+ /** `code`: with reason `error` (a kind that threw inside a multi-kind loop), the classified error code. */+ stopped?: { reason: string; message: string; fix?: Action; code?: string };/** #6543 (D1): accepted repairs still unpublished when the run stopped; the cursor stays before the first, and a rerun replays the same requests. */pending?: Array<{ item: string; request_id: string }>;apply_command: string;@@ -335,7 +358,10 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,...(plan.scan ? { scan: plan.scan } : {}),};+ const items = new ItemRun('repair.apply_items');+ const failedItems: Array<{ item: RepairItem; failure: ItemFailure }> = [];const finish = async (): Promise<RepairResult> => {+ if (failedItems.length && handler.onItemFailures && result.stopped?.reason !== 'item_failures_systemic') await handler.onItemFailures(ctx, failedItems);if (handler.report) Object.assign(result, await handler.report(ctx, scope, result, planOpts));return result;};@@ -422,6 +448,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(applied.detail ? { detail: applied.detail } : {}), ...(applied.llm_usd ? { llm_usd: applied.llm_usd } : {}) });}}+ items.succeed();if (typeof applied === 'object' ? applied.applied : applied) result.applied++;else result.skipped++;if (typeof applied === 'object' && applied.stop) {@@ -431,17 +458,6 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc} catch (error) {// A page edited since planning is left for the next full scan.if (error instanceof OperationError && error.code === 'revision_conflict') { result.skipped++; continue; }- // A per-item refusal: recorded, nothing written, no cursor for it; the next full scan retries it (PR #6459).- if (error instanceof OperationError && REPAIR_ITEM_FAILURE_CODES.has(error.code)) {- const message = redactConnectionInfo(error.message);- const failedItem = `${item.source_id}:${item.slug}`;- result.failed.push({ item: failedItem, source_id: item.source_id, slug: item.slug, reason: error.code, message, retry: 'next_full_scan' });- result.outcomes = { ...result.outcomes, failed: (result.outcomes?.failed ?? 0) + 1 };- if ((result.outcome_items ??= []).length < (handler.outcomeItemsLimit ?? SAMPLE * 2)) {- result.outcome_items.push({ item: failedItem, outcome: 'failed', reason: error.code, detail: { message } });- }- continue;- }const receipt = acceptedPendingReceipt(error);if (receipt) {// #6543 (D1): an accepted write publishes whether or not this run waits; keep going while a consumer here publishes.@@ -459,9 +475,32 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc+ `Rerun \`${result.apply_command}\` to resume; the same request is replayed.` };return finish();}- if (!writerHeld(error)) throw error;- return stopAfterSettle({ reason: error.code, message: `The canonical writer for source '${item.source_id}' is held (${error.code}). `- + `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` });+ if (writerHeld(error)) {+ return stopAfterSettle({ reason: error.code, message: `The canonical writer for source '${item.source_id}' is held (${error.code}). `+ + `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` });+ }+ // An apply bound to an approved preview (`--expect`) applies that set or answers why not; only the kinds' own refusals continue it.+ if (opts.expect && !(error instanceof OperationError && REPAIR_ITEM_FAILURE_CODES.has(error.code))) throw error;+ let failure: ItemFailure;+ try {+ failure = items.fail(`${item.source_id}:${item.slug}`, error);+ } catch (stop) {+ if (!(stop instanceof OperationError) || stop.code !== 'item_failures_systemic') throw stop;+ return stopAfterSettle({ reason: stop.code, message: redactConnectionInfo(`${stop.message} Fix the shared cause, then rerun \`${result.apply_command}\` to resume.`),+ fix: readFix(`Previews ${handler.kind} again (read-only) to show whether the shared cause is gone.`, { argv: ['gbrain', 'repair', handler.kind, ...(opts.sourceFlag ? ['--source', opts.sourceFlag] : []), '--json'] }) });+ }+ // A per-item failure: recorded, nothing written, no cursor for it; the next full scan retries it (PR #6459, GBRA-130).+ const message = redactConnectionInfo(failure.message);+ const failedItem = `${item.source_id}:${item.slug}`;+ result.failed.push({ item: failedItem, source_id: item.source_id, slug: item.slug, reason: failure.code, message, retry: 'next_full_scan',+ fix: readFix(`Previews ${handler.kind} for source ${item.source_id} (read-only); it lists ${item.slug} again with its current state. A run with no stored cursor retries it.`,+ { argv: ['gbrain', 'repair', handler.kind, '--source', item.source_id, '--json'] }) });+ failedItems.push({ item, failure });+ result.outcomes = { ...result.outcomes, failed: (result.outcomes?.failed ?? 0) + 1 };+ if ((result.outcome_items ??= []).length < (handler.outcomeItemsLimit ?? SAMPLE * 2)) {+ result.outcome_items.push({ item: failedItem, outcome: 'failed', reason: failure.code, detail: { message } });+ }+ continue;}await advance(item.cursor);}@@ -470,7 +509,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, screturn finish();}result.complete = pending.length === plan.items.length;- if (result.complete) await writeCursor(ctx.engine, handler.kind, scope, null, null, opts.expect);+ // A limited run whose attempted items all failed keeps no cursor either: the next run is a full scan, not a resume past them.+ if (result.complete || (latest === null && result.failed.length > 0)) await writeCursor(ctx.engine, handler.kind, scope, null, null, opts.expect);return finish();}diff --git a/test/pathological/a9-repair-core.test.ts b/test/pathological/a9-repair-core.test.tsnew file mode 100644index 0000000000..622db00aa2--- /dev/null+++ b/test/pathological/a9-repair-core.test.ts@@ -0,0 +1,170 @@+/**+ * GBRA-130 A-9: the repair core's per-item catch (src/core/repair/core.ts).+ *+ * Protects: one item whose apply throws anything item-scoped (a terminal+ * `storage_error`, `content_rejected`, a plain `Error`) is recorded in+ * failed[] with retry next_full_scan and a fix naming the kind's preview, and+ * the run goes on; a run-scoped failure (connection lost, 25P02, abort, a held+ * writer) still stops the run and records no failure; most items failing trips+ * item_failures_systemic; a limited run that ends with only item failures+ * clears its cursor so the next run is a full scan.+ * Fails when: the catch goes back to an allowlist (the run throws and the+ * stored cursor re-fails the same item on every rerun), or a run-scoped error+ * is recorded as one item's failure.+ * Why new: test/repair-apply-continue-6459.test.ts covers only the three+ * listed refusal codes with a store-only stub; this drives real pages on both+ * engines through the pathological harness.+ * Seams: none (a stub repair handler, as the registry accepts).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { afterCursor, resolveRepairScope, runRepair, type RepairCursor, type RepairHandler, type RepairItem } from '../../src/core/repair/core.ts';+import type { RepairKindSpec } from '../../src/core/repair/registry.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const SOURCE = 'default';+const slugOf = (n: number) => `notes/p${n}`;++interface Stub { handler: RepairHandler; spec: RepairKindSpec; attempts: string[]; poison: Map<string, () => unknown>; recorded: Array<{ slug: string; code: string; class: string }> }++function stubKind(engine: BrainEngine): Stub {+ const stub = { attempts: [], poison: new Map(), recorded: [] } as unknown as Stub;+ stub.handler = {+ kind: 'timeline', publication: 'projection', embeds: false,+ async plan(_engine, scope, after: RepairCursor | null) {+ const rows = await engine.executeRaw<{ id: number; slug: string }>(+ "SELECT id, slug FROM pages WHERE source_id=ANY($1::text[]) AND deleted_at IS NULL AND compiled_truth LIKE 'needs repair%' ORDER BY id", [scope.source_ids]);+ const items: RepairItem[] = rows.map(row => ({ cursor: { phase: 0, id: Number(row.id) }, source_id: SOURCE, slug: row.slug, chars: 10, action: 'repair' }));+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {} };+ },+ async apply(_ctx, item) {+ stub.attempts.push(item.slug);+ const poison = stub.poison.get(item.slug);+ if (poison) throw poison();+ await engine.putPage(item.slug, { type: 'note', title: item.slug, compiled_truth: `repaired ${item.slug}` }, { sourceId: SOURCE, allowEmptyOverwrite: true });+ return { applied: true, outcome: 'repaired' };+ },+ async onItemFailures(_ctx, failures) {+ for (const { item, failure } of failures) stub.recorded.push({ slug: item.slug, code: failure.code, class: failure.class });+ },+ } as RepairHandler;+ stub.spec = { kind: 'timeline', handler: stub.handler, summary: 'stub', embeds: 'none', checks: [], consent: 'safe' } as unknown as RepairKindSpec;+ return stub;+}++const ctxOf = (engine: BrainEngine) => ({ engine, sourceId: SOURCE, remote: false as const, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } }) as never;++const ITEM_ERRORS: Array<{ name: string; error: () => unknown; code: string }> = [+ { name: 'terminal storage_error', error: () => new OperationError('storage_error', 'The write ended failed: publication refused the page.'), code: 'storage_error' },+ { name: 'content_rejected', error: () => new OperationError('content_rejected', 'The content sanity gate rejected the body.'), code: 'content_rejected' },+ { name: 'plain Error', error: () => new Error('boom: postgres://user:[email protected]/brain'), code: 'internal' },+];++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-9 repair core: one bad item never stops the kind (${backend})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); }, 120_000);+ afterAll(async () => { await close(); });+ beforeEach(async () => {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [SOURCE]);+ for (let n = 1; n <= 6; n++) await engine.putPage(slugOf(n), { type: 'note', title: slugOf(n), compiled_truth: `needs repair ${n}` }, { sourceId: SOURCE });+ });+ const cursorRows = () => engine.executeRaw<{ completed_keys: Array<{ cursor: RepairCursor | null }> }>("SELECT completed_keys FROM op_checkpoints WHERE op='repair'");+ const run = async (stub: Stub, opts: { limit?: number } = {}) => runRepair(ctxOf(engine), stub.handler, await resolveRepairScope(engine), { apply: true, spec: stub.spec, ...opts });++ for (const { name, error, code } of ITEM_ERRORS) {+ test(`item case: an item whose apply throws ${name} is recorded in failed[] and the healthy items are repaired`, async () => {+ const stub = stubKind(engine);+ stub.poison.set(slugOf(3), error);+ const before = await snapshotItems(engine, SOURCE);+ const result = await expectUnitNotAborted(() => run(stub));+ expect(stub.attempts).toEqual([1, 2, 3, 4, 5, 6].map(slugOf));+ expect(result).toMatchObject({ applied: 5, complete: true });+ expect(result.stopped).toBeUndefined();+ expect(result.failed.length).toBe(1);+ expectItemFailure({ ...result.failed[0]!, code: result.failed[0]!.reason }, { key: `${SOURCE}:${slugOf(3)}`, code, fix: /"gbrain","repair","timeline","--source","default"/ });+ expect(result.failed[0]!.retry).toBe('next_full_scan');+ expect(JSON.stringify(result)).not.toContain('secret');+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: [1, 2, 4, 5, 6].map(slugOf), progressFields: ['content_hash'] });+ expect(await cursorRows()).toEqual([]);+ expect(stub.recorded.map(r => r.slug)).toEqual([slugOf(3)]);+ });+ }++ test('recovery case: once the cause clears, the next full scan retries the failed item and it lands', async () => {+ const stub = stubKind(engine);+ stub.poison.set(slugOf(2), ITEM_ERRORS[2]!.error);+ await expectUnitNotAborted(() => run(stub));+ stub.poison.clear();+ stub.attempts.length = 0;+ const before = await snapshotItems(engine, SOURCE);+ const rerun = await expectUnitNotAborted(() => run(stub));+ expect(stub.attempts).toEqual([slugOf(2)]);+ expect(rerun).toMatchObject({ applied: 1, failed: [], complete: true, resumed_from: null });+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: [slugOf(2)], progressFields: ['content_hash'] });+ });++ test('an accepted, still pending write stays a pending stop, never an item failure', async () => {+ const stub = stubKind(engine);+ stub.poison.set(slugOf(2), () => Object.assign(new OperationError('write_pending', 'accepted, pending publication'), { writeRequest: { request_id: 'req-pending-1', state: 'queued' } }));+ const result = await runRepair(ctxOf(engine), stub.handler, await resolveRepairScope(engine), { apply: true, spec: stub.spec,+ publicationOwner: async () => ({ alive: false, owner: 'none (test)' }) });+ expect(result.failed).toEqual([]);+ expect(result.stopped?.reason).toBe('write_pending');+ expect(result.pending).toEqual([{ item: `${SOURCE}:${slugOf(2)}`, request_id: 'req-pending-1' }]);+ });++ for (const { name, error } of runScopedErrors()) {+ test(`run case: a run-scoped ${name} at an item stops the run and records no failure`, async () => {+ const stub = stubKind(engine);+ const injected = error();+ stub.poison.set(slugOf(3), () => injected);+ let thrown: unknown;+ const result = await run(stub).catch(err => { thrown = err; return null; });+ expect(stub.attempts).toEqual([1, 2, 3].map(slugOf));+ if (result) {+ expect(result.stopped?.reason).toBe('owner_unavailable');+ expect(result.stopped?.message).toContain('gbrain sources writer status default');+ expect(result.failed).toEqual([]);+ } else expect(thrown).toBe(injected);+ const rows = await cursorRows();+ expect(rows.length).toBe(1);+ expect(rows[0]!.completed_keys[0]!.cursor?.id).toBeGreaterThan(0);+ expect(stub.recorded).toEqual([]);+ });+ }++ test('breaker case: when most items fail the run stops with item_failures_systemic and records nothing', async () => {+ const stub = stubKind(engine);+ for (let n = 1; n <= 6; n++) stub.poison.set(slugOf(n), () => new Error('the chunker is broken for every page'));+ const result = await expectUnitNotAborted(() => run(stub));+ expect(result.stopped?.reason).toBe('item_failures_systemic');+ expect(result.stopped?.message).toContain('repair.apply_items');+ expect(result.complete).toBe(false);+ expect(stub.recorded).toEqual([]);+ expect((await cursorRows()).length).toBe(1);+ });++ test('a limited run that ends with only item failures clears its cursor, so the next run is a full scan', async () => {+ const stub = stubKind(engine);+ stub.poison.set(slugOf(1), ITEM_ERRORS[2]!.error);+ stub.poison.set(slugOf(3), ITEM_ERRORS[0]!.error);+ const first = await expectUnitNotAborted(() => run(stub, { limit: 2 }));+ expect(first).toMatchObject({ applied: 1, complete: false });+ expect((await cursorRows())[0]!.completed_keys[0]!.cursor).toMatchObject({ id: expect.any(Number) });+ const second = await expectUnitNotAborted(() => run(stub, { limit: 1 }));+ expect(second.failed.map(f => f.slug)).toEqual([slugOf(3)]);+ expect(await cursorRows()).toEqual([]);+ stub.poison.clear();+ stub.attempts.length = 0;+ const full = await expectUnitNotAborted(() => run(stub));+ expect(full.resumed_from).toBeNull();+ expect(stub.attempts).toEqual([1, 3, 4, 5, 6].map(slugOf));+ });+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 038e54eda2..d9df21dd19 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -18,4 +18,5 @@ export interface SiteCases {}export const CATALOGUE: Record<IsolateSite, SiteCases> = {+ 'repair.apply_items': { file: 'test/pathological/a9-repair-core.test.ts', item: 'item case: an item whose apply throws', run: 'run case: a run-scoped' },};diff --git a/test/pathological/item-failure.test.ts b/test/pathological/item-failure.test.tsindex d72ed92e47..bf9991159a 100644--- a/test/pathological/item-failure.test.ts+++ b/test/pathological/item-failure.test.ts@@ -97,3 +97,7 @@ describe('ItemRun breaker', () => {test('RUN_SCOPED_CODES holds item_failures_systemic so a tripped inner loop stops its outer loop', () => {expect(RUN_SCOPED_CODES.has('item_failures_systemic')).toBe(true);});++test('a role that may not create schema objects stops the run: schema_owner_required is run-scoped', () => {+ expect(classifyItemFailure(new OperationError('schema_owner_required', 'This database role may not create query_cache.'))).toMatchObject({ code: 'schema_owner_required', scope: 'run' });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 12e8291655..e9419e0621 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -218,6 +218,7 @@ test/page-prepare-shared-origin-6517.test.tstest/page-purge-batch-sweep-6884.test.tstest/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.ts+test/pathological/a9-repair-core.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.tsdiff --git a/test/repair-apply-continue-6459.test.ts b/test/repair-apply-continue-6459.test.tsindex f9618fd682..45d47b1f75 100644--- a/test/repair-apply-continue-6459.test.ts+++ b/test/repair-apply-continue-6459.test.ts@@ -74,6 +74,10 @@ const FAILURES: Record<number, Failure> = {3: { code: 'source_changed', message: 'file_database_drift: notes/item-3.md differs from the database copy; neither was overwritten' },};+/** GBRA-130: every failed item carries the kind's read-only preview for its source as its fix. */+const PREVIEW_FIX = expect.objectContaining({ argv: ['gbrain', 'repair', 'timeline', '--source', 'default', '--json'], consent: [] });+const LANE_PREVIEW_FIX = expect.objectContaining({ argv: ['gbrain', 'repair', 'fences', '--source', 'default', '--json'], consent: [] });+const cursorRows = () => engine.executeRaw<{ completed_keys: unknown }>("SELECT completed_keys FROM op_checkpoints WHERE op='repair'");describe('repair --apply continues past a per-item invalid_params / source_changed refusal (PR #6459)', () => {@@ -85,8 +89,8 @@ describe('repair --apply continues past a per-item invalid_params / source_changexpect(result).toMatchObject({ applied: 3, skipped: 0, complete: true });expect(result.stopped).toBeUndefined();expect(result.failed).toEqual([- { item: 'default:notes/item-1', source_id: 'default', slug: 'notes/item-1', reason: 'invalid_params', message: expect.stringContaining('not a valid slug'), retry: 'next_full_scan' },- { item: 'default:notes/item-3', source_id: 'default', slug: 'notes/item-3', reason: 'source_changed', message: expect.stringContaining('file_database_drift'), retry: 'next_full_scan' },+ { item: 'default:notes/item-1', source_id: 'default', slug: 'notes/item-1', reason: 'invalid_params', message: expect.stringContaining('not a valid slug'), retry: 'next_full_scan', fix: PREVIEW_FIX },+ { item: 'default:notes/item-3', source_id: 'default', slug: 'notes/item-3', reason: 'source_changed', message: expect.stringContaining('file_database_drift'), retry: 'next_full_scan', fix: PREVIEW_FIX },]);expect(JSON.stringify(result)).not.toContain('secret');expect(result.outcomes).toEqual({ repaired: 3, failed: 2 });@@ -138,7 +142,7 @@ describe('repair --apply continues past a per-item invalid_params / source_changexpect(stub.store.get(1)).toBe('repaired item 1');});- test('other refusals still stop the run as before (write_pending stops; an unexpected error rethrows)', async () => {+ test('other refusals still stop the run as before (write_pending stops; a lost connection rethrows; an unexpected error is one item\'s failure, GBRA-130)', async () => {const stub = stubKind('timeline', 3, {});stub.handler.apply = async (_c, it) => {stub.attempts.push(it.cursor.id);@@ -152,7 +156,12 @@ describe('repair --apply continues past a per-item invalid_params / source_changawait resetPgliteState(engine);const boom = stubKind('timeline', 3, {});boom.handler.apply = async (_c, it) => { if (it.cursor.id === 0) throw new Error('disk on fire'); return { applied: true, outcome: 'repaired' }; };- await expect(runRepair(ctx(), boom.handler, await resolveRepairScope(engine), { apply: true, spec: boom.spec })).rejects.toThrow('disk on fire');+ const isolated = await runRepair(ctx(), boom.handler, await resolveRepairScope(engine), { apply: true, spec: boom.spec });+ expect(isolated).toMatchObject({ applied: 2, complete: true, failed: [{ slug: 'notes/item-0', reason: 'internal', message: 'disk on fire', retry: 'next_full_scan' }] });+ await resetPgliteState(engine);+ const lost = stubKind('timeline', 3, {});+ lost.handler.apply = async (_c, it) => { if (it.cursor.id === 0) throw Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' }); return { applied: true, outcome: 'repaired' }; };+ await expect(runRepair(ctx(), lost.handler, await resolveRepairScope(engine), { apply: true, spec: lost.spec })).rejects.toThrow('Connection terminated');});test('the human output counts the failures, names the slug and the full-scan command; the command exits 1', async () => {@@ -187,8 +196,8 @@ describe('repair --apply continues past a per-item invalid_params / source_changconst lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences'], registry: [stub.spec] });const [result] = lane.results as RepairResult[];expect(result!.failed.map(f => f.slug)).toEqual(['notes/item-1', 'notes/item-3']);- expect(lane.failed).toEqual([{ kind: 'fences', item: 'default:notes/item-1', source_id: 'default', slug: 'notes/item-1', reason: 'invalid_params', message: expect.any(String), retry: 'next_full_scan' },- { kind: 'fences', item: 'default:notes/item-3', source_id: 'default', slug: 'notes/item-3', reason: 'source_changed', message: expect.any(String), retry: 'next_full_scan' }]);+ expect(lane.failed).toEqual([{ kind: 'fences', item: 'default:notes/item-1', source_id: 'default', slug: 'notes/item-1', reason: 'invalid_params', message: expect.any(String), retry: 'next_full_scan', fix: LANE_PREVIEW_FIX },+ { kind: 'fences', item: 'default:notes/item-3', source_id: 'default', slug: 'notes/item-3', reason: 'source_changed', message: expect.any(String), retry: 'next_full_scan', fix: LANE_PREVIEW_FIX }]);expect(lane.stopped).toEqual([]);});});diff --git a/test/repair-apply-pending-6543.test.ts b/test/repair-apply-pending-6543.test.tsindex 35d877d3d1..0456a4eff0 100644--- a/test/repair-apply-pending-6543.test.ts+++ b/test/repair-apply-pending-6543.test.ts@@ -152,7 +152,7 @@ describe('#6543 D1: repair apply continues past accepted-but-pending writes', ()const spec = repairSpec('timeline');let calls = 0;const dying = { ...spec.handler, apply: async (...args: Parameters<typeof spec.handler.apply>) => {- if (++calls === 3) throw new Error('process died');+ if (++calls === 3) throw Object.assign(new Error('process died'), { name: 'AbortError' });return spec.handler.apply(...args);} };slowPublications(1_000);