Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: a file_gone hold clears when its page is soft-deleted; a stamping pass releases deleted-side holds whose page and file are both gone

garrytaneddb2fe56496
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 2a59c219aa..5675fc6ed3 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -438,6 +438,17 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnat
return true;
}
+/**
+ * GBRA-133: clears the deleted-side `file_drift` hold at `path` (a page whose file is gone, a tombstone whose file was
+ * edited, a purged page whose file came back) once the page is soft-deleted, the decision it waited for. False when the
+ * path has no such hold.
+ */
+export async function clearDeletionHold(tx: Exec, input: { sourceId: string; incarnation: string; path: string }): Promise<boolean> {
+ const hold = await readRow(tx, input.sourceId, input.incarnation, input.path);
+ if (!hold || hold.code !== 'file_drift' || fileDriftSide(hold.meta) !== 'deleted') return false;
+ return clearGitHold(tx, { ...input, observedAt: hold.observed_at });
+}
+
/** #5984: which of these paths have a hold row (one indexed read), so a batched waiver run clears only those. */
export async function heldGitPaths(tx: Exec, sourceId: string, incarnation: string, paths: readonly string[]): Promise<Set<string>> {
if (!paths.length) return new Set();
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 521880dc5d..e90dd7580e 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -32,7 +32,7 @@ import { sourceMirrorReadOnly } from './mirror-read-only.ts';
import { colonFileRefusal, COLON_REFUSAL_MESSAGES, readSyncFile, resolveManagedSyncContext, syncExcludePatterns, syncGitAsync, type ManagedSyncContext, type SyncFileRefusal } from './sync-discovery.ts';
import { isWindowsColonTarget } from './native-file-target.ts';
import { confirmedSyncDelta } from '../sync-rename-identity.ts';
-import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportParser, syncImportParsers,
+import { fileDriftSide, holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportParser, syncImportParsers,
type GitHoldRecord, type SyncImportParser, type SyncImportProvenance } from './sync-holds.ts';
import { movedDriftHolds, sameParser } from './sync-prescreen.ts';
import { sameSyncOrigin, selectOriginClaimant, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
@@ -894,7 +894,11 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
}
return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,
heldRenames: holds.flatMap(hold => hold.meta.rename_from ? [{ path: toGit(hold.path), rename: hold.meta.rename_from }] : []),
- releasableHolds: holds.filter(hold => !domain.has(toGit(hold.path))).map(hold => hold.path),
+ releasableHolds: holds.filter(hold => {
+ const path = toGit(hold.path), at = byOrigin.get(path);
+ return !domain.has(path) || deletionSettled(hold, tree.has(path) || (mode === 'working' && (untracked.has(path) || index.has(path))),
+ at !== undefined && !pages.deleted(at), () => readPresent(root, path, scope));
+ }).map(hold => hold.path),
paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3,
...(confirm ? { confirm: narrow ? { ...confirm, narrow: narrow === 'taken' && !reuse ? 'classified' : narrow } : confirm } : {}), ...(reuse ? { reused } : {}), ...(treeReuse ? { treeReuse } : {}), pack: pack?.identity ?? null,
selection: { exclude: [...exclude].sort(), includeHidden: [...includeHidden].sort(), strategy, srcSubpath: scope || null, mode },
@@ -1159,6 +1163,14 @@ function readPresent(root: string, gitPath: string, scope: string): boolean {
try { return readSyncFile(root, path) !== null; } catch { return true; }
}
+/**
+ * GBRA-133: a deleted-side `file_drift` hold whose two sides agree again (no file at `L` or on disk, no live page at the
+ * origin) waits for nothing: a soft delete, a purge or the file's removal decided it, so the stamp releases it.
+ */
+function deletionSettled(hold: GitHoldRecord, inLevel: boolean, live: boolean, present: () => boolean): boolean {
+ return hold.code === 'file_drift' && fileDriftSide(hold.meta) === 'deleted' && !inLevel && !live && !present();
+}
+
/** Whether a hold still describes the path at level `L`, in the hold's own domain (a pinned blob, working bytes, or a deletion). */
function holdAtLevel(hold: GitHoldRecord, level: string | null, diskSha256: string | null): boolean {
if (hold.meta.deleted) return level === null;
diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index d82b7f7a12..83eb52fe00 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -47,7 +47,7 @@ import { authorizeWrite } from '../persistence/authority.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
-import { readSyncImportProvenance } from '../persistence/sync-holds.ts';
+import { clearDeletionHold, readSyncImportProvenance } from '../persistence/sync-holds.ts';
import { readRevisionAttestations } from '../persistence/sync-pass.ts';
import { readDeletionProvenance } from '../persistence/sync-origin-evidence.ts';
import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
@@ -315,5 +315,10 @@ export async function prepareGhostPageRetirement(engine: BrainEngine, row: Write
const page = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
if (!page.file || relative(page.file.root, page.file.path).split(sep).join('/') !== ghost.path) throw refuse(changed('its canonical file target moved'));
if (page.file.expectedBeforeHash !== null) throw refuse(restored(ghost));
- return { ...page, validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); } };
+ return { ...page, validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); },
+ // GBRA-133: the soft delete is the decision a held deletion of this file waited for, so its hold clears with it.
+ apply: async (tx, preimage) => {
+ const outcome = await page.apply(tx, preimage);
+ return await clearDeletionHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: ghost.path }) ? { ...outcome, hold_cleared: true } : outcome;
+ } };
}
diff --git a/test/file-drift-soft-delete-hold-release-gbra133.test.ts b/test/file-drift-soft-delete-hold-release-gbra133.test.ts
new file mode 100644
index 0000000000..83ff1402e4
--- /dev/null
+++ b/test/file-drift-soft-delete-hold-release-gbra133.test.ts
@@ -0,0 +1,88 @@
+/**
+ * GBRA-133: `gbrain repair file-drift --held --side deleted --state file_gone --prefer file` soft-deleted the page but left
+ * its `file_drift` hold, and no later sync released it, not even `--full`: the pass found the hold "at its level" (no file)
+ * and kept it. The soft delete is the decision the hold waited for, so the ghost retirement now clears it in the same
+ * publication. A hold an earlier version left behind (its page already deleted, its file gone) is released by the next
+ * pass that stamps; a held deletion whose page is still live stays held.
+ */
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const SLUGS = ['notes/gone', 'notes/live', 'notes/other'];
+const logger = { info() {}, warn() {}, error() {} };
+
+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; meta: { side?: string; state?: string } } }>(
+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code} ${r.meta.side ?? ''} ${r.meta.state ?? ''}`.trim());
+const deleted = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ d: boolean }>(
+ "SELECT deleted_at IS NOT NULL AS d FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]?.d;
+
+/** Older imports of notes/gone and notes/live (no import record, no write request), whose files one commit then deletes: two held file_gone deletions. */
+async function heldDeletions(engine: BrainEngine, root: string): Promise<void> {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const coordinated = (sql: string, params: unknown[] = []) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
+ await coordinated(`DELETE FROM op_checkpoints WHERE op='sync-import-provenance'
+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug IN ('notes/gone', 'notes/live'))`);
+ for (const slug of ['notes/gone', 'notes/live']) await coordinated(`UPDATE pages SET knowledge_revision = $1::uuid, revision_write_request_id = NULL,
+ updated_at = now() - interval '1 hour' WHERE source_id='default' AND slug=$2`, [randomUUID(), slug]);
+ git(root, 'rm', '-q', 'notes/gone.md', 'notes/live.md'); git(root, 'commit', '-qm', 'remove gone and live');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/gone.md file_drift deleted file_gone', 'notes/live.md file_drift deleted file_gone']);
+}
+
+/** A commit that touches only notes/other, so the next pass stamps. */
+function unrelatedCommit(root: string): void {
+ writeFileSync(join(root, 'notes/other.md'), note('notes/other', `Edited ${randomUUID()}.`)); git(root, 'commit', '-qam', 'edit other');
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of SLUGS) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');
+ };
+
+ test(`GBRA-133 [${backend}]: repair file-drift --prefer file soft-deletes a file_gone page and clears its hold in the same publication`, () => managedBrain(async ({ engine, root }) => {
+ await heldDeletions(engine, root);
+ const run = async (expect?: string) => withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () =>
+ (await repairRunner(engine, { apply: expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),
+ { explicit: true, sourceFlag: 'default', held: true, prefer: 'file', side: 'deleted', state: 'file_gone', only: ['notes/gone.md'], ...(expect ? { expect } : {}) }));
+ const preview = await run();
+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/gone', action: 'soft_delete' })]);
+ expect((await run(preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });
+ expect(await deleted(engine, 'notes/gone')).toBe(true);
+ expect(await holds(engine)).toEqual(['notes/live.md file_drift deleted file_gone']);
+ unrelatedCommit(root);
+ await performManagedSync(engine, OPTS);
+ await performManagedSync(engine, { ...OPTS, full: true });
+ expect(await holds(engine)).toEqual(['notes/live.md file_drift deleted file_gone']);
+ }, { databaseUrl, setup }), 180_000);
+
+ test(`GBRA-133 [${backend}]: a hold left on a page deleted since is released by the next stamping pass; a held page still live stays held`, () => managedBrain(async ({ engine, root }) => {
+ await heldDeletions(engine, root);
+ // The soft delete an earlier version's repair made, which left the hold.
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.softDeletePage('notes/gone', { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ expect(await deleted(engine, 'notes/gone')).toBe(true);
+ expect(await holds(engine)).toEqual(['notes/gone.md file_drift deleted file_gone', 'notes/live.md file_drift deleted file_gone']);
+ unrelatedCommit(root);
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/live.md file_drift deleted file_gone']);
+ expect(await deleted(engine, 'notes/live')).toBe(false);
+ }, { databaseUrl, setup }), 180_000);
+}