Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): slug-conflicts rotates past a poison candidate and counts its attempts (GBRA-130 A-44)

garrytane6635f2e52c9
diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.ts
index d437064a28..a611d52b4b 100644
--- a/src/core/repair/fences.ts
+++ b/src/core/repair/fences.ts
@@ -65,6 +65,7 @@ import { analyzeFences, attemptCandidate, runTier3, tier3Estimate, tier3Memo, ty
import type { FenceFix, FenceIssue, FencePage, FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';
import { lineDiff } from './frontmatter.ts';
import type { RepairHandler, RepairItem, RepairItemOutcome, RepairListing, RepairPlan, RepairPlanOptions, RepairResult, RepairScope } from './core.ts';
+import { rotate, rotationAfter, rotationBrain, rotationKeyOf, saveRotation } from './rotation.ts';
/** The fences result's `verification` (report hook): what the run did and what is left, for the CLI and the cycle phase report. */
export interface FenceRepairVerification {
@@ -207,17 +208,7 @@ function selected(cand: FenceCandidate, selection: Selection): boolean {
return (!!cand.path && selection.only.includes(cand.path)) || selection.slugs.includes(cand.key);
}
-async function rotationAfter(engine: BrainEngine, brainId: string): Promise<string | null> {
- const [row] = await engine.executeRaw<{ last: string | null }>("SELECT completed_keys->0->>'last' AS last FROM op_checkpoints WHERE op=$1 AND fingerprint=$2", [ROTATION_OP, brainId]);
- return row?.last ?? null;
-}
-
-async function saveRotation(engine: BrainEngine, brainId: string, last: string): Promise<void> {
- await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
- ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [ROTATION_OP, brainId, JSON.stringify([{ last }])]);
-}
-
-const rotationKey = (entry: Pick<ApprovedFence, 'source_id' | 'key'>) => `${entry.source_id}\u0000${entry.key}`;
+const rotationKey = (entry: Pick<ApprovedFence, 'source_id' | 'key'>) => rotationKeyOf(entry.source_id, entry.key);
function item(entry: ApprovedFence, index: number, hash: string | null, last: boolean, partial: boolean): FenceItem {
return { cursor: { phase: 1, id: index + 1 }, source_id: entry.source_id, slug: entry.slug, chars: 0, action: `${entry.tier}:${entry.path ?? entry.slug}`,
@@ -262,9 +253,8 @@ export const fencesRepair: RepairHandler = {
for (const id of scope.source_ids) sources.set(id, await loadFenceSource(engine, id, { remote: opts?.remote !== false }));
const found = await listFenceCandidates(engine, scope.source_ids);
const { extra, unknown } = await extraCandidates(engine, scope, selection, found, sources);
- let candidates = [...found, ...extra].filter(cand => selected(cand, selection));
- const rotation = opts?.apply ? await rotationAfter(engine, scope.brain_id) : null;
- if (rotation) candidates = [...candidates.filter(c => rotationKey({ source_id: c.source_id, key: c.key }) > rotation), ...candidates.filter(c => rotationKey({ source_id: c.source_id, key: c.key }) <= rotation)];
+ const candidates = rotate([...found, ...extra].filter(cand => selected(cand, selection)), c => rotationKey({ source_id: c.source_id, key: c.key }),
+ opts?.apply ? await rotationAfter(engine, ROTATION_OP, scope.brain_id) : null);
const s = await settings(engine, opts ?? { noLlm: false });
const store = attemptStore(engine);
const residuals: Record<string, number> = {};
@@ -391,10 +381,7 @@ export const fencesRepair: RepairHandler = {
return await applyFence(ctx, entry, { embed: opts?.embed === true, expect: hash, allowanceUsd: opts?.llmAllowanceUsd, deadline: opts?.deadline, noLlm: opts?.noLlm === true });
} finally {
if (hash && last) await clearApprovedSet(ctx.engine, { command: 'fences', hash });
- if (!hash) {
- const [brain] = await ctx.engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);
- await saveRotation(ctx.engine, brain?.brain_id ?? 'host', rotationKey(entry)).catch(() => undefined);
- }
+ if (!hash) await saveRotation(ctx.engine, ROTATION_OP, await rotationBrain(ctx.engine), rotationKey(entry)).catch(() => undefined);
}
},
render(details, opts) {
diff --git a/src/core/repair/rotation.ts b/src/core/repair/rotation.ts
new file mode 100644
index 0000000000..60ed6fd8de
--- /dev/null
+++ b/src/core/repair/rotation.ts
@@ -0,0 +1,37 @@
+/**
+ * Rotation for repair kinds whose candidates come back in the same order every
+ * run (fences, slug-conflicts): a bare apply saves the key of each candidate it
+ * attempts, and the next bare apply starts after it, so a candidate that keeps
+ * failing (or a run that keeps stopping on a budget) cannot hold the rest back.
+ * Stored in op_checkpoints under the kind's own op, keyed by brain.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export async function rotationAfter(engine: BrainEngine, op: string, brainId: string): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ last: string | null }>("SELECT completed_keys->0->>'last' AS last FROM op_checkpoints WHERE op=$1 AND fingerprint=$2", [op, brainId]);
+ return row?.last ?? null;
+}
+
+export async function saveRotation(engine: BrainEngine, op: string, brainId: string, last: string): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [op, brainId, JSON.stringify([{ last }])]);
+}
+
+/** The candidates after `rotation` first, then the rest, each part in its original order. */
+export function rotate<T>(items: readonly T[], key: (item: T) => string, rotation: string | null): T[] {
+ return rotation ? [...items.filter(item => key(item) > rotation), ...items.filter(item => key(item) <= rotation)] : [...items];
+}
+
+/**
+ * A candidate's rotation key: source, then the kind's key, ordered by source first. U+0001 separates them because jsonb
+ * refuses U+0000, which made every saved rotation fail before GBRA-130.
+ */
+export function rotationKeyOf(sourceId: string, key: string): string {
+ return `${sourceId}\u0001${key}`;
+}
+
+/** The brain id a handler's apply stores its rotation under. */
+export async function rotationBrain(engine: BrainEngine): Promise<string> {
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);
+ return brain?.brain_id ?? 'host';
+}
diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.ts
index 3f9e462605..e4c7bdd175 100644
--- a/src/core/repair/slug-conflicts.ts
+++ b/src/core/repair/slug-conflicts.ts
@@ -67,7 +67,8 @@ import { pricingSetCommand } from '../budget/no-pricing.ts';
import type { CapSource } from '../consent.ts';
import { sha256 } from '../persistence/digest.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
-import { clearGitHold, readGitHold, readGitSourceHolds, recordContentHoldRepair, type ContentHoldRepairState, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { clearGitHold, readGitHold, readGitSourceHolds, recordContentHoldRepair, recordHoldAttempt, type ContentHoldRepairState, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { rotate, rotationAfter, rotationBrain, rotationKeyOf, saveRotation } from './rotation.ts';
import { confinedRepairTarget, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
import { repairBusy, repairBusyMessage } from '../persistence/repair-busy.ts';
import { frozenImportScreenInput, loadSyncScreenRun, screenFrozenContent } from '../persistence/sync-screen.ts';
@@ -144,6 +145,8 @@ const TRANSIENT: ReadonlySet<string> = new Set(['llm_unavailable', 'ledger_unava
const STOPWORDS: ReadonlySet<string> = new Set(['a', 'an', 'the', 'of', 'and', 'or', 'for', 'to', 'in', 'on', 'at', 'by', 'with', 'from', 'inc', 'llc', 'ltd', 'co', 'corp', 'company', 'mr', 'ms', 'dr']);
const itemName = (entry: Pick<ApprovedConflict, 'source_id' | 'path'>) => `${entry.source_id}:${entry.path}`;
+const ROTATION_OP = 'slug-conflict-repair-rotation';
+const rotationKey = (entry: Pick<ApprovedConflict, 'source_id' | 'path'>) => rotationKeyOf(entry.source_id, entry.path);
const isImport = (entry: Pick<ApprovedConflict, 'rule'>) => entry.rule === 'already_clean' || entry.rule === 'already_exempt';
function previewArgv(scope: RepairScope, selection: Selection): string[] {
@@ -498,6 +501,8 @@ export const slugConflictsRepair: RepairHandler = {
llmItems.push({ item: name, named: cand.namedSlug, estimate_usd: estimate.usd });
}
}
+ // GBRA-130 A-44: a bare apply starts after the candidate the last one attempted (the fences rotation).
+ if (opts?.apply) approved.splice(0, approved.length, ...rotate(approved, rotationKey, await rotationAfter(engine, ROTATION_OP, scope.brain_id)));
let waiting = 0;
for (const entry of [...approved].reverse()) { if (entry.tier === 'llm') waiting++; entry.llm_waiting = entry.tier === 'llm' ? waiting : 0; }
const sourcesRows = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);
@@ -528,6 +533,16 @@ export const slugConflictsRepair: RepairHandler = {
return await applyConflict(ctx, entry, { embed: opts?.embed === true, expect: hash, allowanceUsd: opts?.llmAllowanceUsd, deadline: opts?.deadline, noLlm: opts?.noLlm === true });
} finally {
if (hash && last) await clearApprovedSet(ctx.engine, { command: 'slug-conflicts', hash });
+ if (!hash) await saveRotation(ctx.engine, ROTATION_OP, await rotationBrain(ctx.engine), rotationKey(entry)).catch(() => undefined);
+ }
+ },
+ /** GBRA-130 A-44: a candidate whose apply failed item-scoped counts a failed attempt on its hold, so HOLD_ATTEMPTS_NEEDS_HUMAN escalates it. */
+ async onItemFailures(ctx, failures) {
+ for (const { item } of failures) {
+ const { entry } = item as ConflictItem;
+ const [source] = await ctx.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [entry.source_id]);
+ if (!source) continue;
+ await recordHoldAttempt(ctx.engine, { sourceId: entry.source_id, incarnation: source.incarnation, path: entry.path, code: CONTENT_REPAIR_HOLD_CODE });
}
},
render(details, opts) {
diff --git a/test/pathological/a44-slug-conflicts-rotation.test.ts b/test/pathological/a44-slug-conflicts-rotation.test.ts
new file mode 100644
index 0000000000..f17006dde3
--- /dev/null
+++ b/test/pathological/a44-slug-conflicts-rotation.test.ts
@@ -0,0 +1,143 @@
+/**
+ * GBRA-130 A-44: \`gbrain repair slug-conflicts\` (src/core/repair/slug-conflicts.ts),
+ * run by \`gbrain repair content\`, the cycle's content_repair phase and
+ * \`sync unblock --apply\`, on a managed source with real
+ * \`frontmatter_slug_conflict\` holds written by sync.
+ *
+ * Protects: a candidate whose repair fails item-scoped is recorded in
+ * \`failed[]\`, a failed attempt is recorded on its hold (so
+ * HOLD_ATTEMPTS_NEEDS_HUMAN escalates it), its file is untouched and the other
+ * candidates are repaired; a bare apply starts after the candidate the last
+ * one attempted (the fences rotation), so a poison candidate cannot sit first
+ * forever; a run-scoped failure stops the run and records no attempt; a
+ * systemic run (most candidates failing) records no attempt either.
+ * Fails when: slug-conflicts loses the rotation (a limited run re-attempts the
+ * same poison candidate every time) or records attempts from a run-scoped or
+ * systemic stop.
+ * Why new: test/repair-slug-conflicts.test.ts covers healthy candidates on PGLite only.
+ * Seams: a test-only trigger on pages builds the poison candidate (its
+ * publication fails); run-scoped errors are injected at the engine inside the
+ * kind's apply.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { resolveRepairScope } from '../../src/core/repair/core.ts';
+import { rotationAfter, rotationKeyOf, saveRotation } from '../../src/core/repair/rotation.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const SOURCE = 'default';
+const quiet = { info() {}, warn() {}, error() {} };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();
+const file = (name: string) => '---\ntitle: Note ' + name + '\ntype: note\nslug: ghost-' + name + '\n---\nBody of ' + name + '.\n';
+
+async function refusePages(engine: BrainEngine, slugs: string[]) {
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION pathological_refuse_page() RETURNS trigger LANGUAGE plpgsql AS $fn$
+ BEGIN IF NEW.slug = ANY(ARRAY[${slugs.map(s => "'" + s + "'").join(',')}]::text[]) THEN RAISE EXCEPTION 'pathological: page refused' USING ERRCODE = 'check_violation'; END IF; RETURN NEW; END $fn$`);
+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_page ON pages');
+ await engine.executeRaw('CREATE TRIGGER pathological_refuse_page BEFORE INSERT OR UPDATE ON pages FOR EACH ROW EXECUTE FUNCTION pathological_refuse_page()');
+}
+
+function failingInApply(engine: BrainEngine, injected: unknown): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ const value = Reflect.get(target, prop);
+ if (prop === 'executeRaw' && typeof value === 'function') {
+ return (...args: unknown[]) => new Error().stack?.includes('applyConflict') ? Promise.reject(injected) : (value as Function).apply(target, args);
+ }
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+}
+
+/** A managed source whose \`notes/<name>.md\` files each declare a slug no page or file has: sync holds them \`frontmatter_slug_conflict\`. */
+function withConflicts(names: string[], databaseUrl: string | undefined, run: (b: { engine: BrainEngine; root: string; attempts: () => Promise<Record<string, number>>;
+ repair: (opts?: { limit?: number; engine?: BrainEngine }) => Promise<import('../../src/core/repair/core.ts').RepairResult> }) => Promise<void>) {
+ return managedBrain(async ({ engine, root }) => {
+ await performManagedSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, noExtract: true });
+ const attempts = async () => Object.fromEntries(((await readGitSourceHolds(engine, { sourceIds: [SOURCE] }))[0]?.holds ?? [])
+ .filter(h => h.code === 'frontmatter_slug_conflict').map(h => [h.path, h.meta.attempts ?? 1]));
+ expect(Object.keys(await attempts()).sort()).toEqual(names.map(n => 'notes/' + n + '.md'));
+ const repair = async (opts: { limit?: number; engine?: BrainEngine } = {}) => {
+ const runner = await repairRunner(opts.engine ?? engine, { apply: true, noEmbed: true, logger: quiet });
+ return runner.run('slug-conflicts', await resolveRepairScope(engine, SOURCE), { explicit: true, sourceFlag: SOURCE, limit: opts.limit });
+ };
+ await run({ engine, root, attempts, repair });
+ }, { databaseUrl, setup: ({ root }) => {
+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ for (const name of names) writeFileSync(join(root, 'notes', name + '.md'), file(name));
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'fixture');
+ } });
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe('A-44 slug-conflicts: a poison candidate is rotated past and its hold counts the attempt (' + backend + ')', () => {
+ test('item case: the poison candidate is recorded in failed[] with a hold attempt and the other candidates are repaired', () => withConflicts(['a', 'b', 'c'], databaseUrl, async ({ engine, root, attempts, repair }) => {
+ await refusePages(engine, ['notes/a']);
+ const before = await snapshotItems(engine, SOURCE);
+ const result = await expectUnitNotAborted(() => repair());
+ expect(result).toMatchObject({ applied: 2, complete: true });
+ expect(result.failed.length).toBe(1);
+ expectItemFailure({ key: result.failed[0]!.item, code: result.failed[0]!.reason, fix: result.failed[0]!.fix }, { key: SOURCE + ':notes/a.md', code: 'storage_error', fix: /"gbrain","repair","slug-conflicts","--source","default"/ });
+ expect(await attempts()).toEqual({ 'notes/a.md': 2 });
+ expect(readFileSync(join(root, 'notes', 'a.md'), 'utf8')).toBe(file('a'));
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: ['notes/b', 'notes/c'] });
+ }), 120_000);
+
+ test('rotation: a limited bare apply starts after the candidate the last one attempted', () => withConflicts(['a', 'b', 'c'], databaseUrl, async ({ engine, repair }) => {
+ await refusePages(engine, ['notes/a']);
+ const first = await expectUnitNotAborted(() => repair({ limit: 1 }));
+ expect(first.failed.map(f => f.slug)).toEqual(['notes/a.md']);
+ const second = await expectUnitNotAborted(() => repair({ limit: 1 }));
+ expect(second.failed).toEqual([]);
+ expect(second.outcome_items?.map(o => o.item)).toEqual([SOURCE + ':notes/b.md']);
+ }), 120_000);
+
+ test('the rotation key round-trips through op_checkpoints (jsonb refuses the NUL separator fences used, so no rotation was ever saved)', () => managedBrain(async ({ engine }) => {
+ for (const op of ['fence-repair-rotation', 'slug-conflict-repair-rotation']) {
+ await saveRotation(engine, op, 'brain-example', rotationKeyOf(SOURCE, 'notes/a.md'));
+ expect(await rotationAfter(engine, op, 'brain-example')).toBe(rotationKeyOf(SOURCE, 'notes/a.md'));
+ }
+ expect(rotationKeyOf('a', 'z') < rotationKeyOf('b', 'a')).toBe(true);
+ }, { databaseUrl }), 120_000);
+
+ test('recovery case: once the cause clears, the next run repairs the poison candidate and its hold clears', () => withConflicts(['a', 'b', 'c'], databaseUrl, async ({ engine, attempts, repair }) => {
+ await refusePages(engine, ['notes/a']);
+ await expectUnitNotAborted(() => repair());
+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_page ON pages');
+ const before = await snapshotItems(engine, SOURCE);
+ const result = await expectUnitNotAborted(() => repair());
+ expect(result).toMatchObject({ applied: 1, failed: [] });
+ expect(await attempts()).toEqual({});
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: ['notes/a'] });
+ }), 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test('run case: a run-scoped ' + name + ' in a candidate\'s apply stops the run and records no attempt', () => withConflicts(['a', 'b', 'c'], databaseUrl, async ({ engine, attempts, repair }) => {
+ const injected = error();
+ const before = await snapshotItems(engine, SOURCE);
+ const was = await attempts();
+ let thrown: unknown;
+ const result = await repair({ engine: failingInApply(engine, injected) }).catch(err => { thrown = err; return null; });
+ if (result) {
+ expect(result.stopped?.reason).toBe('owner_unavailable');
+ expect(result.failed).toEqual([]);
+ } else expect(thrown).toBe(injected);
+ expect(await attempts()).toEqual(was);
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE));
+ }), 120_000);
+ }
+
+ test('breaker case: when most candidates fail the run stops item_failures_systemic and records no attempt', () => withConflicts(['a', 'b', 'c', 'd', 'e', 'f'], databaseUrl, async ({ engine, attempts, repair }) => {
+ await refusePages(engine, ['notes/a', 'notes/b', 'notes/c', 'notes/d', 'notes/e', 'notes/f']);
+ const was = await attempts();
+ const result = await expectUnitNotAborted(() => repair());
+ expect(result.stopped?.reason).toBe('item_failures_systemic');
+ expect(await attempts()).toEqual(was);
+ }), 180_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 18c712560f..cac2fce508 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -220,6 +220,7 @@ test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
test/pathological/a26-safe-chunks-reseal.test.ts
test/pathological/a27-credential-reseal.test.ts
+test/pathological/a44-slug-conflicts-rotation.test.ts
test/pathological/a45-repair-all-kinds.test.ts
test/pathological/a46-content-lane-kinds.test.ts
test/pathological/a9-repair-core.test.ts