Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): one throwing kind never stops repair --all or the content lane (GBRA-130 A-45, A-46)
garrytan58f39d35d870
diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 72d02ef10d..9a8b4639f4 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -24,11 +24,13 @@ import { readFix } from '../core/ops/op-fix.ts';import { shellQuote } from '../core/agent-output.ts';import { OLDER_THAN_RE } from '../cli/strict-args.ts';import { parseSince } from '../core/since.ts';-import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';+import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult, type RepairScope } from '../core/repair/core.ts';import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,- repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';+ repairPreviewCommand, repairRunner, repairSpec, type RepairKindSpec } from '../core/repair/registry.ts';import { CONTENT_REPAIR_KINDS } from '../core/repair/content-lane.ts';+import { kindErrorResult } from '../core/remediation/repairs.ts';+import { ItemRun } from '../core/item-failure.ts';/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */export const CONTENT_LANE = 'content';@@ -374,18 +376,13 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proif (!auth) return;}const runner = await repairRunner(engine, { apply, noEmbed });- const results: Array<RepairResult & { paid: boolean }> = [];- for (const k of kinds) {- const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,- ...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),- ...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),- ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since } : {}),- ...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),- ...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),- ...(k === kind && k === 'rename-identity' ? { from, close } : {}) });- results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });- if (result.stopped) break;- }+ const results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,+ ...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),+ ...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),+ ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since } : {}),+ ...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),+ ...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),+ ...(k === kind && k === 'rename-identity' ? { from, close } : {}) }));if (apply) clearHealthMemo(engine);const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {@@ -409,6 +406,33 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proif (repairExitVerdict(results) !== 0) setCliExitVerdict(1);}+/**+ * Runs each kind in order; a kind that stops (capacity, a held writer, a pending write) ends the loop. A kind whose plan+ * or apply throws item-scoped (GBRA-130 A-45) is reported as a result stopped with reason `error` and the loop goes on;+ * a run-scoped error, or most kinds failing (`item_failures_systemic`), stops the command. `named`: the operator named+ * one kind, whose error is the command's error. `registry`: the kinds' specs (tests pass stubs).+ */+export async function runRepairKinds(kinds: readonly RepairKind[], scope: RepairScope, opts: { apply: boolean; source?: string; noEmbed: boolean; named: boolean; registry?: readonly RepairKindSpec[] },+ run: (kind: RepairKind) => Promise<RepairResult>): Promise<Array<RepairResult & { paid: boolean }>> {+ const results: Array<RepairResult & { paid: boolean }> = [];+ const kindRun = new ItemRun('repair.all_kinds');+ for (const k of kinds) {+ let result: RepairResult;+ try {+ result = await run(k);+ kindRun.succeed();+ } catch (error) {+ if (opts.named) throw error;+ kindRun.fail(k, error);+ results.push({ ...kindErrorResult(k, scope, { apply: opts.apply, error, source: opts.source }), paid: false });+ continue;+ }+ results.push({ ...result, paid: repairMaySpend(repairSpec(k, opts.registry), opts.noEmbed) });+ if (result.stopped) break;+ }+ return results;+}+/** Exit 1 when any kind stopped early or refused an item; 0 only when every pending item was attempted and applied or skipped. */export function repairExitVerdict(results: ReadonlyArray<Pick<RepairResult, 'stopped' | 'failed'>>): 0 | 1 {return results.some(r => r.stopped || r.failed.length > 0) ? 1 : 0;diff --git a/src/core/cycle/content-repair.ts b/src/core/cycle/content-repair.tsindex 09763359a0..2bd8a727d6 100644--- a/src/core/cycle/content-repair.ts+++ b/src/core/cycle/content-repair.ts@@ -81,7 +81,7 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Colet lane: ContentLaneResult;try {lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: !opts.dryRun, kinds, deadline: start + timeBudgetMs,- logger: { info() {}, warn: console.warn, error: console.error }, ...(opts.registry ? { registry: opts.registry } : {}) });+ logger: { info() {}, warn: console.warn, error: console.error }, ...(opts.registry ? { registry: opts.registry } : {}), ...(opts.signal ? { signal: opts.signal } : {}) });} catch (error) {if (isUncontainedPhaseError(error, opts.signal)) throw error;const rawCode = (error as { code?: unknown } | null)?.code;@@ -109,6 +109,9 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Coconst oldest = kindsRun.map(k => k.oldest_hold_at).filter((at): at is string => !!at).sort()[0] ?? null;const oldestHoldAgeHours = oldest ? Math.max(0, Math.round((now() - Date.parse(oldest)) / 3_600_000)) : null;const hardStop = lane.stopped.find(stop => stop.reason !== 'time_budget');+ // A kind that threw (reason `error`, GBRA-130 A-46) is reported by its code: the phase report never carries an error's message.+ const kindError = hardStop?.reason === 'error' ? hardStop : undefined;+ const stopped = lane.stopped.map(stop => stop.reason === 'error' ? { kind: stop.kind, reason: stop.reason, code: stop.code ?? 'internal', message: `${stop.kind} raised ${stop.code ?? 'an error'}`, ...(stop.fix ? { fix: stop.fix } : {}) } : stop);const timeStop = lane.stopped.find(stop => stop.reason === 'time_budget');const failed = lane.failed.length;const usd = `$${lane.cost.llm_usd.toFixed(4)}`;@@ -121,7 +124,8 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Co].filter(Boolean).join('; ');const notes = [timeStop ? `Stopped at the phase time budget (${Math.round(timeBudgetMs / 1000)} s) in ${timeStop.kind}; the next maintenance run resumes.` : '',- hardStop ? `Stopped (${hardStop.kind}: ${hardStop.reason}): ${hardStop.message}` : '',+ kindError ? `${kindError.kind} stopped on an error (${kindError.code ?? 'internal'}) and the next maintenance run retries; the other kinds ran. Run \`${preview}\` on the brain host to see the plan and the error; ask the user if it keeps failing.`+ : hardStop ? `Stopped (${hardStop.kind}: ${hardStop.reason}): ${hardStop.message}` : '',failed ? `${failed} item(s) refused and left unchanged (first: ${lane.failed[0]!.kind} ${lane.failed[0]!.item}, ${lane.failed[0]!.reason}); the next full scan retries them.` : '',needsHuman ? `${needsHuman} wait for a person: gbrain sync status --source <id> --json names each with its paragraph.` : '',].filter(Boolean);@@ -135,7 +139,7 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Comode: lane.mode, kinds: lane.kinds, candidates, repaired, failed, held_by_reason: heldTotals, by_kind: byKind,llm_usd: lane.cost.llm_usd, oldest_hold_at: oldest, oldest_hold_age_hours: oldestHoldAgeHours,complete: lane.results.every(result => result.complete), time_budget_ms: timeBudgetMs, stopped_reason: hardStop?.reason ?? timeStop?.reason ?? null,- ...(lane.stopped.length ? { stopped: lane.stopped } : {}), ...(fix ? { fix } : {}),+ ...(kindError ? { reason: 'error', code: kindError.code ?? 'internal' } : {}), ...(lane.stopped.length ? { stopped } : {}), ...(fix ? { fix } : {}),},};}diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex e08f55d832..c9fe68794a 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -28,6 +28,8 @@ 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',+ 'repair.all_kinds': 'A-45',+ 'repair.content_lane_kinds': 'A-46',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.tsindex 32d37e22eb..1253cb7962 100644--- a/src/core/remediation/repairs.ts+++ b/src/core/remediation/repairs.ts@@ -20,13 +20,14 @@*/import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';-import { resolveRepairScope, type RepairKind } from '../repair/core.ts';+import { resolveRepairScope, type RepairKind, type RepairResult, type RepairScope } from '../repair/core.ts';import { AUTO_REPAIR_REGISTRY, explicitKindRequired, repairApplyCommand, repairMayEmbed, repairRunner, repairSpec, type RepairKindSpec } from '../repair/registry.ts';import { cliRenderContext, renderAction, type RenderedAction } from '../agent-output.ts';import { readFix } from '../ops/op-fix.ts';import { isStatementTimeoutError } from '../retry-matcher.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import { withAdmissionOrigin } from '../persistence/admission-origin.ts';+import { classifyItemFailure } from '../item-failure.ts';export interface RepairPlanStep {step: number;@@ -74,7 +75,7 @@ export interface RepairPlanReport { steps: RepairPlanStep[]; previewFailures: Reconst PREVIEW_ERROR_MAX_CHARS = 300;/** Redact before truncating, so a cut can never split a credential the redactor would have matched. */-function describePreviewFailure(kind: RepairKind, error: unknown): RepairPreviewFailure {+export function describePreviewFailure(kind: RepairKind, error: unknown): RepairPreviewFailure {const timedOut = isStatementTimeoutError(error);const detail = redactConnectionInfo(error instanceof Error ? error.message : String(error));const cause = timedOut ? 'hit the database statement timeout (GBRAIN_STATEMENT_TIMEOUT)' : 'raised an error';@@ -90,6 +91,21 @@ function describePreviewFailure(kind: RepairKind, error: unknown): RepairPreview};}+/**+ * GBRA-130 (A-45, A-46): a kind whose plan or apply threw an item-scoped error inside a multi-kind loop (`gbrain repair`,+ * `--all`, the content lane), as an empty result that stops with reason `error`, the redacted message and the kind's+ * read-only preview as its fix, so the loop reports it and runs the next kind.+ */+export function kindErrorResult(kind: RepairKind, scope: RepairScope, opts: { apply: boolean; error: unknown; source?: string }): RepairResult {+ const { message } = describePreviewFailure(kind, opts.error);+ const preview = ['gbrain', 'repair', kind, ...(opts.source ? ['--source', opts.source] : [])];+ return { kind, mode: opts.apply ? 'apply' : 'dry_run', scope, affected: 0, sample: [], residuals: {},+ cost: { lifetime_ids: 0, receipt_bytes: 0, embedding_pages: 0, embedding_usd: 0 }, capacity: [], resumed_from: null, applied: 0, skipped: 0, failed: [], complete: false,+ apply_command: repairApplyCommand(kind, { source: opts.source }),+ stopped: { reason: 'error', code: classifyItemFailure(opts.error).code, message: `The ${kind} ${opts.apply ? 'repair' : 'preview'} raised an error, so ${kind} did not finish; every other kind ran. ${message}`,+ fix: readFix(`Repeats the ${kind} preview on the brain host to show the error; it writes nothing.`, { argv: [...preview, '--json'] }) } };+}+/** `{ repair_preview_failures }` when any preview failed, else nothing, so a healthy plan's JSON is unchanged. */export function previewFailureField(failures: readonly RepairPreviewFailure[]): { repair_preview_failures?: RepairPreviewFailure[] } {return failures.length === 0 ? {} : { repair_preview_failures: [...failures] };diff --git a/src/core/repair/content-lane.ts b/src/core/repair/content-lane.tsindex 0b7bc34e1f..54bae3242b 100644--- a/src/core/repair/content-lane.ts+++ b/src/core/repair/content-lane.ts@@ -42,6 +42,8 @@ import type { GitHoldRecord } from '../persistence/sync-holds.ts';import { contentRepairLaneCurrent } from '../persistence/sync-fault-class.ts';import type { RepairFailedItem, RepairKind, RepairResult, RepairScope } from './core.ts';import { repairRunner, type RepairKindSpec } from './registry.ts';+import { kindErrorResult } from '../remediation/repairs.ts';+import { ItemRun } from '../item-failure.ts';/** The lane, in run order: fences first (a merged or closed fence can change what a slug conflict's page looks like), then slug conflicts. */export const CONTENT_REPAIR_KINDS: readonly RepairKind[] = ['fences', 'slug-conflicts'];@@ -110,6 +112,9 @@ export interface ContentLaneOptions {sourceFlag?: string;/** Replaces the registered kinds (tests pass stub specs). */registry?: readonly RepairKindSpec[];+ /** The caller's cancellation: a kind that throws after it fired is rethrown, never recorded as that kind's error.+ * A kind bound to its `--expect` hash is rethrown too: the operator approved that set, so a refusal answers the command. */+ signal?: AbortSignal;logger?: OperationContext['logger'];}@@ -123,7 +128,7 @@ export interface ContentLaneResult {preview_hashes: Partial<Record<RepairKind, string | null>>;/** Paid-model spend across the lane: the estimate on a dry run, the actual spend on an apply; the allowance left under `maxLlmUsd` (null: no run cap). */cost: { llm_usd: number; llm_allowance_remaining_usd: number | null };- /** Every kind that stopped, with its reason (`time_budget` ends the lane; the rest let the next kind run). */+ /** Every kind that stopped, with its reason (`time_budget` ends the lane; the rest let the next kind run). A kind whose plan or apply threw item-scoped stops with reason `error` and its preview as the fix (GBRA-130); a run-scoped error is thrown. */stopped: Array<{ kind: RepairKind } & NonNullable<RepairResult['stopped']>>;/** Every item a kind refused per item and left unchanged (the kinds' `failed[]`, with the kind); the next full scan retries them. */failed: Array<{ kind: RepairKind } & RepairFailedItem>;@@ -162,10 +167,19 @@ export async function runContentLane(engine: BrainEngine, scope: RepairScope, opconst results: RepairResult[] = [];let spent = 0;const allowance = () => opts.maxLlmUsd === undefined ? undefined : Math.max(0, opts.maxLlmUsd - spent);+ const kindRun = new ItemRun('repair.content_lane_kinds');for (const [index, kind] of kinds.entries()) {const expect = opts.expect?.[index];- const result = await runner.run(kind, scope, { explicit: true, limit: opts.limit, sourceFlag: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm,- maxLlmUsd: allowance(), deadline: opts.deadline, ...(expect ? { expect } : {}) });+ let result: RepairResult;+ try {+ result = await runner.run(kind, scope, { explicit: true, limit: opts.limit, sourceFlag: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm,+ maxLlmUsd: allowance(), deadline: opts.deadline, ...(expect ? { expect } : {}) });+ kindRun.succeed();+ } catch (error) {+ if (opts.signal?.aborted || expect) throw error;+ kindRun.fail(kind, error);+ result = kindErrorResult(kind, scope, { apply: opts.apply, error, source: opts.sourceFlag });+ }hashes[kind] = expect ?? result.preview_hash ?? null;spent += result.cost.llm_usd ?? 0;results.push(result);diff --git a/test/pathological/a45-repair-all-kinds.test.ts b/test/pathological/a45-repair-all-kinds.test.tsnew file mode 100644index 0000000000..187e28404b--- /dev/null+++ b/test/pathological/a45-repair-all-kinds.test.ts@@ -0,0 +1,117 @@+/**+ * GBRA-130 A-45: \`gbrain repair\` (the no-kind preview) and \`gbrain repair --all+ * [--apply]\` run every automatic kind in one loop (src/commands/repair.ts+ * runRepairKinds).+ *+ * Protects: a kind whose plan or apply throws item-scoped is reported as a+ * result that stops with reason \`error\`, its message and the kind's preview+ * as the fix, and every later kind still runs; the exit verdict stays 1. A+ * run-scoped failure still stops the whole command, and when most kinds fail+ * the breaker stops it with \`item_failures_systemic\`.+ * Fails when: the loop loses its per-kind catch (the first throwing kind+ * aborts every later kind and the preview of all kinds), or a run-scoped+ * error is reported as one kind's failure.+ * Why new: \`doctor --remediation-plan\` isolates kinds (remediation/repairs.ts);+ * the CLI loop had no owner.+ * Seams: stub kind specs passed as the registry, as repairRunner 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, type RepairCursor, type RepairHandler, type RepairItem, type RepairKind } from '../../src/core/repair/core.ts';+import { repairRunner, type RepairKindSpec } from '../../src/core/repair/registry.ts';+import { repairExitVerdict, runRepairKinds } from '../../src/commands/repair.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const SOURCE = 'default';+const quiet = { info() {}, warn() {}, error() {} };++interface StubKind { spec: RepairKindSpec; fail: { plan?: () => unknown } }++/** A projection kind over the pages under \`<kind>/\`: each pending page is rewritten, so progress shows in its content hash. */+function stubKind(engine: BrainEngine, kind: RepairKind): StubKind {+ const stub = { fail: {} } as StubKind;+ const handler: RepairHandler = {+ kind, publication: 'projection', embeds: false,+ async plan(_engine, scope, after: RepairCursor | null) {+ if (stub.fail.plan) throw stub.fail.plan();+ const rows = await engine.executeRaw<{ id: number; slug: string }>(+ "SELECT id, slug FROM pages WHERE source_id=ANY($1::text[]) AND slug LIKE $2 AND compiled_truth LIKE 'needs repair%' AND deleted_at IS NULL ORDER BY id", [scope.source_ids, kind + '/%']);+ const items: RepairItem[] = rows.map(row => ({ cursor: { phase: 0, id: Number(row.id) }, source_id: SOURCE, slug: row.slug, chars: 1, action: 'repair' }));+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {} };+ },+ async apply(_ctx, item) {+ await engine.putPage(item.slug, { type: 'note', title: item.slug, compiled_truth: 'repaired ' + item.slug }, { sourceId: SOURCE, allowEmptyOverwrite: true });+ return true;+ },+ };+ stub.spec = { kind, handler, summary: 'stub', embeds: 'none', checks: [], consent: 'safe' } as unknown as RepairKindSpec;+ return stub;+}++async function seed(engine: BrainEngine, kinds: readonly string[]) {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [SOURCE]);+ for (const kind of kinds) for (const n of [1, 2]) await engine.putPage(kind + '/p' + n, { type: 'note', title: kind + ' ' + n, compiled_truth: 'needs repair ' + n }, { sourceId: SOURCE });+}+const slugsOf = (kinds: readonly string[]) => kinds.flatMap(kind => [kind + '/p1', kind + '/p2']);++const KINDS: RepairKind[] = ['timeline', 'visibility', 'safe-chunks'];++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe('A-45 repair --all: one throwing kind never stops the later kinds (' + backend + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); }, 120_000);+ afterAll(async () => { await close(); });+ beforeEach(async () => { await seed(engine, KINDS); });++ async function runAll(stubs: StubKind[], apply: boolean) {+ const registry = stubs.map(stub => stub.spec);+ const scope = await resolveRepairScope(engine);+ const runner = await repairRunner(engine, { apply, noEmbed: true, logger: quiet, registry });+ return runRepairKinds(registry.map(spec => spec.kind), scope, { apply, noEmbed: true, named: false, registry }, kind => runner.run(kind, scope));+ }++ for (const apply of [true, false]) {+ test('item case: a kind whose plan throws is listed with reason error and its preview, and the later kinds still run (' + (apply ? '--all --apply' : 'no-kind preview') + ')', async () => {+ const stubs = KINDS.map(kind => stubKind(engine, kind));+ stubs[1]!.fail.plan = () => new Error('visibility plan exploded on one row: postgres://user:[email protected]/brain');+ const before = await snapshotItems(engine, SOURCE);+ const results = await expectUnitNotAborted(() => runAll(stubs, apply));+ expect(results.map(r => r.kind)).toEqual(KINDS);+ const failed = results[1]!;+ expectItemFailure({ key: failed.kind, code: failed.stopped?.reason, fix: failed.stopped?.fix }, { key: 'visibility', code: 'error', fix: /"gbrain","repair","visibility"/ });+ expect(failed.stopped?.message).toContain('visibility plan exploded');+ expect(JSON.stringify(results)).not.toContain('secret');+ expect(results[2]!.affected).toBe(2);+ expect(repairExitVerdict(results)).toBe(1);+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), apply ? { expectProgress: slugsOf(['timeline', 'safe-chunks']), progressFields: ['content_hash'] } : {});+ });+ }++ for (const { name, error } of runScopedErrors()) {+ test('run case: a run-scoped ' + name + ' in one kind stops the whole command', async () => {+ const stubs = KINDS.map(kind => stubKind(engine, kind));+ const injected = error();+ stubs[1]!.fail.plan = () => injected;+ const before = await snapshotItems(engine, SOURCE);+ await expect(runAll(stubs, true)).rejects.toBe(injected);+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { changed: slugsOf(['timeline']) });+ expect((await snapshotItems(engine, SOURCE)).get('safe-chunks/p1')).toEqual(before.get('safe-chunks/p1'));+ });+ }++ test('breaker case: when most kinds fail the command stops with item_failures_systemic', async () => {+ const kinds: RepairKind[] = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'request-indexes', 'orphan-bindings'];+ await seed(engine, kinds);+ const stubs = kinds.map(kind => stubKind(engine, kind));+ for (const stub of stubs) stub.fail.plan = () => new OperationError('invalid_data', 'every plan reads the same broken row');+ const error = await runAll(stubs, false).then(() => null, (err: unknown) => err);+ expect(error).toBeInstanceOf(OperationError);+ expect((error as OperationError).code).toBe('item_failures_systemic');+ expect((error as OperationError).message).toContain('repair.all_kinds');+ });+ });+}diff --git a/test/pathological/a46-content-lane-kinds.test.ts b/test/pathological/a46-content-lane-kinds.test.tsnew file mode 100644index 0000000000..d5754bd259--- /dev/null+++ b/test/pathological/a46-content-lane-kinds.test.ts@@ -0,0 +1,93 @@+/**+ * GBRA-130 A-46: the content-repair lane runs fences, then slug-conflicts+ * (src/core/repair/content-lane.ts runContentLane), for \`gbrain repair+ * content\`, the cycle's content_repair phase and \`sync unblock --apply\`.+ *+ * Protects: a kind whose plan or apply throws item-scoped is recorded in the+ * lane's \`stopped[]\` with reason \`error\`, its message and the kind's preview,+ * and the next kind still runs and reports its own result; a run-scoped+ * failure still stops the lane.+ * Fails when: the lane loses its per-kind catch (a throw in fences means+ * slug-conflicts never runs and every outcome of the lane is lost).+ * Why new: test/repair-apply-continue-6459.test.ts covers per-item failures+ * inside one kind, not a kind that throws.+ * Seams: stub kind specs passed as the lane's registry (ContentLaneOptions.registry).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { afterCursor, resolveRepairScope, type RepairCursor, type RepairHandler, type RepairItem, type RepairKind, type RepairResult } from '../../src/core/repair/core.ts';+import type { RepairKindSpec } from '../../src/core/repair/registry.ts';+import { runContentLane } from '../../src/core/repair/content-lane.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const SOURCE = 'default';+const quiet = { info() {}, warn() {}, error() {} };++interface StubKind { spec: RepairKindSpec; fail: { plan?: () => unknown } }++/** A projection kind over the pages under \`<kind>/\`: each pending page is rewritten, so progress shows in its content hash. */+function stubKind(engine: BrainEngine, kind: RepairKind): StubKind {+ const stub = { fail: {} } as StubKind;+ const handler: RepairHandler = {+ kind, publication: 'projection', embeds: false,+ async plan(_engine, scope, after: RepairCursor | null) {+ if (stub.fail.plan) throw stub.fail.plan();+ const rows = await engine.executeRaw<{ id: number; slug: string }>(+ "SELECT id, slug FROM pages WHERE source_id=ANY($1::text[]) AND slug LIKE $2 AND compiled_truth LIKE 'needs repair%' AND deleted_at IS NULL ORDER BY id", [scope.source_ids, kind + '/%']);+ const items: RepairItem[] = rows.map(row => ({ cursor: { phase: 0, id: Number(row.id) }, source_id: SOURCE, slug: row.slug, chars: 1, action: 'repair' }));+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {} };+ },+ async apply(_ctx, item) {+ await engine.putPage(item.slug, { type: 'note', title: item.slug, compiled_truth: 'repaired ' + item.slug }, { sourceId: SOURCE, allowEmptyOverwrite: true });+ return true;+ },+ };+ stub.spec = { kind, handler, summary: 'stub', embeds: 'none', checks: [], consent: 'safe' } as unknown as RepairKindSpec;+ return stub;+}++async function seed(engine: BrainEngine, kinds: readonly string[]) {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [SOURCE]);+ for (const kind of kinds) for (const n of [1, 2]) await engine.putPage(kind + '/p' + n, { type: 'note', title: kind + ' ' + n, compiled_truth: 'needs repair ' + n }, { sourceId: SOURCE });+}+const slugsOf = (kinds: readonly string[]) => kinds.flatMap(kind => [kind + '/p1', kind + '/p2']);++const KINDS: RepairKind[] = ['fences', 'slug-conflicts'];++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe('A-46 content lane: one throwing kind never stops the next 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 seed(engine, KINDS); });+ const lane = async (stubs: StubKind[]) => runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: KINDS, registry: stubs.map(stub => stub.spec), logger: quiet });++ test('item case: fences throwing is recorded in stopped[] and slug-conflicts still runs and reports its result', async () => {+ const stubs = KINDS.map(kind => stubKind(engine, kind));+ stubs[0]!.fail.plan = () => new Error('fence census refused one file');+ const before = await snapshotItems(engine, SOURCE);+ const result = await expectUnitNotAborted(() => lane(stubs));+ expect(result.stopped.length).toBe(1);+ const stopped = result.stopped[0]!;+ expectItemFailure({ key: stopped.kind, code: stopped.reason, fix: stopped.fix }, { key: 'fences', code: 'error', fix: /"gbrain","repair","fences"/ });+ expect(stopped.message).toContain('fence census refused one file');+ expect(result.results.map((r: RepairResult) => r.kind)).toEqual(KINDS);+ expect(result.results[1]).toMatchObject({ kind: 'slug-conflicts', applied: 2, complete: true });+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: slugsOf(['slug-conflicts']), progressFields: ['content_hash'] });+ });++ for (const { name, error } of runScopedErrors()) {+ test('run case: a run-scoped ' + name + ' in fences stops the lane before slug-conflicts', async () => {+ const stubs = KINDS.map(kind => stubKind(engine, kind));+ const injected = error();+ stubs[0]!.fail.plan = () => injected;+ const before = await snapshotItems(engine, SOURCE);+ await expect(lane(stubs)).rejects.toBe(injected);+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE));+ });+ }+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex d9df21dd19..ac589e7120 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -19,4 +19,6 @@ 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' },+ 'repair.all_kinds': { file: 'test/pathological/a45-repair-all-kinds.test.ts', item: 'item case: a kind whose plan throws', run: 'run case: a run-scoped' },+ 'repair.content_lane_kinds': { file: 'test/pathological/a46-content-lane-kinds.test.ts', item: 'item case: fences throwing is recorded', run: 'run case: a run-scoped' },};diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex e9419e0621..5af32080a8 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -218,6 +218,8 @@ 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/a45-repair-all-kinds.test.ts+test/pathological/a46-content-lane-kinds.test.tstest/pathological/a9-repair-core.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.ts