Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#6712 PR 4b lane C): #6865 heal skips sync_unfinished on an open/stopped pass, an open episode or another drainer's lease
garrytan75cf1cdd1015
diff --git a/src/core/repair/slug-autoheal.ts b/src/core/repair/slug-autoheal.tsindex 4f5059d7f1..a27760513c 100644--- a/src/core/repair/slug-autoheal.ts+++ b/src/core/repair/slug-autoheal.ts@@ -11,8 +11,9 @@* - only `absent_page`; a line naming an existing page (file-backed or database-only), another type, or anything the* model would judge is left exactly as held, with nothing recorded, for the maintenance run and a person;* - only the bytes sync held: a file edited since (a newer draft) waits for the next sync to re-screen it;- * - never while the source has an unfinished managed sync cursor (another drainer, or this run's own resumable- * stop), and every write re-reads the busy set at admission, so no file whose publication is in flight is edited;+ * - never while the source has an unfinished managed sync (another drainer, or this run's own resumable stop: an+ * unfinished cursor, or an open, stopped or episode-holding pass), and every write re-reads the busy set at+ * admission, so no file whose publication is in flight is edited;* - only under local authority: a sync a remote job or agent submitted defers to the maintenance run;* - the declared slug is checked again inside the publication: a page, an alias or a file at its path written since* the heal read the source refuses the write;@@ -32,6 +33,9 @@ import { readGitSourceHolds } from '../persistence/sync-holds.ts';import { contentRepairLaneCurrent } from '../persistence/sync-fault-class.ts';import { FENCE_REPAIR_ENABLED_KEY, fenceRepairEnabled } from '../fence-repair/config.ts';import { absentSlugHealRun, healAbsentSlugLine } from './slug-conflicts.ts';+import { inspectLock, syncLockId } from '../db-lock.ts';+import { currentDrainLease } from '../persistence/sync-lease.ts';+import { readLivePassRows } from '../persistence/sync-pass-row.ts';export const SLUG_AUTO_REMOVE_KEY = 'sync.slug_conflicts.auto_remove';/** The longest one sync spends healing; a caller deadline that comes sooner wins. */@@ -73,7 +77,7 @@ function noticeOf(sourceId: string, r: Omit<SlugHealReport, 'notice' | 'preview_if (r.skipped) {const why = r.skipped === 'disabled' ? `${SLUG_AUTO_REMOVE_KEY} is false` : r.skipped === 'lane_paused' ? `content repair is paused (${FENCE_REPAIR_ENABLED_KEY} false)`: r.skipped === 'remote_authority' ? 'this sync runs under a remote job or agent, which may import but not rewrite files'- : r.skipped === 'sync_unfinished' ? 'the source still has an unfinished sync cursor' : 'this host may not write the source checkout';+ : r.skipped === 'sync_unfinished' ? 'the source still has an unfinished sync' : 'this host may not write the source checkout';return `[sync] ${r.pending} held file(s) of source ${sourceId} have a stray frontmatter slug: line; sync left them held because ${why}. `+ `Preview the repair with gbrain repair content --source ${sourceId} --no-llm (read-only); the maintenance run applies it when the lane is on.`;}@@ -82,11 +86,19 @@ function noticeOf(sourceId: string, r: Omit<SlugHealReport, 'notice' | 'preview_+ `${left ? `; ${left} held file(s) need more than that and stay for the content-repair lane` : ''}. Opt out: gbrain config set ${SLUG_AUTO_REMOVE_KEY} false.`;}-/** Whether the source has a managed sync cursor that has not finished (a drain in progress, or a resumable stop). */+/**+ * Whether the source's sync has not finished: a managed sync cursor that has not finished (a company brain's drain in+ * progress, or a resumable stop), or, for a source the live pass syncs (#6712 PR 4b, design v3.2 §9), another drainer+ * holding its drain lease, a newest pass that is still open or ended other than `synced`/`up_to_date`, or an open episode.+ */async function unfinishedCursor(engine: BrainEngine, sourceId: string): Promise<boolean> {const rows = await engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'AND completed_keys->0->>'sourceId'=$1 LIMIT 1`, [sourceId]);- return rows.length > 0;+ if (rows.length > 0) return true;+ const lease = await inspectLock(engine, syncLockId(sourceId));+ if (lease && !lease.ttl_expired && lease.acquisition_token !== currentDrainLease(sourceId)?.token) return true;+ const pass = (await readLivePassRows(engine, [sourceId])).get(sourceId)?.value;+ return !!pass && (!['synced', 'up_to_date'].includes(pass.telemetry.outcome) || !!pass.obligations.episode);}/** The post-sync heal of one managed source; returns the result with the report and the held fields it cleared. Never throws. */diff --git a/test/slug-autoheal-pass-6712.test.ts b/test/slug-autoheal-pass-6712.test.tsnew file mode 100644index 0000000000..65f4c79360--- /dev/null+++ b/test/slug-autoheal-pass-6712.test.ts@@ -0,0 +1,131 @@+/**+ * #6712 PR 4b lane C: the #6865 stray slug: line heal (src/core/repair/slug-autoheal.ts) skips with `sync_unfinished`+ * while the source's sync has not finished. A non-company source syncs by the live pass and keeps no cursor row, so the+ * skip reads the pass row and the drain lease: a newest pass that is open or ended other than `synced`/`up_to_date`, an+ * open episode, or another drainer's live lease. A heal after the pass's own stamp at HEAD runs.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { SyncResult } from '../src/commands/sync.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { syncLockId, tryAcquireDbLock } from '../src/core/db-lock.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { MANAGED_SYNC_PASS_OP, readPassRow, type ManagedSyncPassValue } from '../src/core/persistence/sync-pass-row.ts';+import { healAfterManagedSync, SLUG_AUTO_REMOVE_KEY } from '../src/core/repair/slug-autoheal.ts';+import { withEnv } from './helpers/with-env.ts';++const STRAY = 'investors/fund-a.md';+const STRAY_BYTES = '---\ntitle: "Fund A"\ntype: company\nslug: fund-a\n---\nFund A invests in example companies.\n';+const SYNCED = { status: 'synced', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] } as SyncResult;++let engine: PGLiteEngine;+let home: string;+let root: string;+let incarnation: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ home = mkdtempSync(join(tmpdir(), 'gbrain-slug-autoheal-pass-'));+ root = join(home, 'content');+ await inHome(async () => {+ mkdirSync(root);+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ git('init', '-q'); git('config', 'user.name', 'Example'); git('config', 'user.email', '[email protected]');+ mkdirSync(join(root, 'investors'));+ writeFileSync(join(root, STRAY), STRAY_BYTES);+ git('add', STRAY); git('commit', '-qm', 'fixture');+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n');+ chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);+ await claimWorktree(engine, 'default', root);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await engine.setConfig(SLUG_AUTO_REMOVE_KEY, 'false');+ const first = await sync();+ expect(first.slug_lines_removed).toMatchObject({ skipped: 'disabled', removed: 0, pending: 1 });+ await engine.setConfig(SLUG_AUTO_REMOVE_KEY, 'true');+ });+ [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+}, 180_000);++afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++function inHome<T>(run: () => Promise<T>): Promise<T> {+ return withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, run);+}+function git(...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+const sync = () => performSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true } as never);+const heldPaths = async () => ((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]?.holds ?? []).map(hold => [hold.path, hold.code]);++async function passValue(): Promise<ManagedSyncPassValue> {+ const row = await readPassRow(engine, 'default', incarnation);+ expect(row).not.toBeNull();+ return row!.value;+}+async function writePass(value: ManagedSyncPassValue): Promise<void> {+ await engine.executeRaw('UPDATE op_checkpoints SET completed_keys=jsonb_build_array($3::text::jsonb) WHERE op=$1 AND fingerprint=$2',+ [MANAGED_SYNC_PASS_OP, 'default:' + incarnation, JSON.stringify(value)]);+}++describe('the #6865 heal reads the pass row for a source with no cursor (#6712 PR 4b)', () => {+ test("an unfinished pass, an open episode or another drainer's lease skips the heal with sync_unfinished", () => inHome(async () => {+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op IN ('managed-sync','managed-sync-manifest','managed-sync-slice')")).toEqual([]);+ expect(await heldPaths()).toEqual([[STRAY, 'frontmatter_slug_conflict']]);+ const settled = await passValue();+ expect(['synced', 'up_to_date']).toContain(settled.telemetry.outcome);+ expect(settled.obligations.episode).toBeUndefined();+ const unfinished: Array<[string, ManagedSyncPassValue]> = [+ ['an open pass', { ...settled, telemetry: { ...settled.telemetry, outcome: 'open', ended_at: null, stop_reason: null } }],+ ['a pass that stopped not_converged', { ...settled, telemetry: { ...settled.telemetry, outcome: 'resumable', stop_reason: 'not_converged' } }],+ ['a pass that stopped writer_pending', { ...settled, telemetry: { ...settled.telemetry, outcome: 'resumable', stop_reason: 'writer_pending' } }],+ ['a pass that stopped blocked', { ...settled, telemetry: { ...settled.telemetry, outcome: 'blocked', stop_reason: 'reconcile_read_incomplete' } }],+ ['a scoped pass that synced with its episode still open', { ...settled, telemetry: { ...settled.telemetry, outcome: 'synced', stop_reason: 'selection_scoped' },+ obligations: { ...settled.obligations, episode: { opened_at: new Date().toISOString(), full_id: 'episode-6712-lane-c',+ selection: { exclude: [], includeHidden: [], strategy: 'markdown', srcSubpath: null, mode: 'committed' }, inherited: { noEmbed: true, noExtract: true, noSchemaPack: false, from: 'flag' } } } }],+ ];+ try {+ for (const [label, value] of unfinished) {+ await writePass(value);+ const report = (await healAfterManagedSync(engine, { sourceId: 'default' } as never, SYNCED)).slug_lines_removed;+ expect({ label, report }).toMatchObject({ label, report: { skipped: 'sync_unfinished', removed: 0, pending: 1 } });+ expect(report!.notice).toContain('the source still has an unfinished sync');+ expect(readFileSync(join(root, STRAY), 'utf8')).toBe(STRAY_BYTES);+ }+ await writePass(settled);+ const lease = await tryAcquireDbLock(engine, syncLockId('default'), 2);+ expect(lease).not.toBeNull();+ try {+ expect((await healAfterManagedSync(engine, { sourceId: 'default' } as never, SYNCED)).slug_lines_removed).toMatchObject({ skipped: 'sync_unfinished', removed: 0, pending: 1 });+ } finally { await lease!.release(); }+ expect(readFileSync(join(root, STRAY), 'utf8')).toBe(STRAY_BYTES);+ } finally { await writePass(settled); }+ expect(await heldPaths()).toEqual([[STRAY, 'frontmatter_slug_conflict']]);+ }), 180_000);++ test('a pass left open is finished by the next sync, whose stamp at HEAD lets the heal run', () => inHome(async () => {+ const settled = await passValue();+ await writePass({ ...settled, telemetry: { ...settled.telemetry, outcome: 'open', ended_at: null, stop_reason: null } });+ const head = git('rev-parse', 'HEAD');+ const result = await sync();+ const after = await passValue();+ expect(['synced', 'up_to_date']).toContain(after.telemetry.outcome);+ expect(after.telemetry.pass_id).not.toBe(settled.telemetry.pass_id);+ expect(after.obligations.converged?.target).toBe(head);+ expect(result.slug_lines_removed).toMatchObject({ removed: 1, pending: 0, failed: 0, removed_paths: [STRAY] });+ expect(readFileSync(join(root, STRAY), 'utf8')).toBe(STRAY_BYTES.replace('slug: fund-a\n', ''));+ expect(await heldPaths()).toEqual([]);+ }), 180_000);+});