Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): withdrawal scans move past metafile and locally edited pages (#5396)

garrytan66b73939096e
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 18df314b08..6053cb0767 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -51,7 +51,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 33e947cfeb..ddb120cbdb 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -3,6 +3,7 @@ import type { WithdrawalTarget } from '../facts/withdrawal-discovery.ts';
export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop';
export interface ParkedTarget { slug?: string; error_code: string }
+export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' }
/** A Git or withdrawal target parks after this many consecutive execution failures. */
export const PARK_AFTER_FAILURES = 5;
export interface EffectRecovery {
@@ -39,7 +40,9 @@ export interface PersistenceEffect {
/** Parked scan targets an explicit retry authorized for one more attempt. */
retry_slugs?: string[];
/** Explicit retry authorizations granted to this effect's parked targets. */
- retried?: number };
+ retried?: number;
+ /** #5396: scan targets passed without a file publication (a sync-skip metafile, or a file with an uncoordinated local edit). */
+ skipped?: SkippedTarget[] };
state: 'queued' | 'running' | 'committed' | 'failed';
execution_token: string | null;
claim_expires_at: string | Date | null;
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 29f22a83d8..6798f7cd64 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';
import { existsSync, statSync } from 'node:fs';
-import { join, relative, sep } from 'node:path';
+import { basename, join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import type { GBrainConfig } from '../config.ts';
@@ -30,7 +30,8 @@ import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } fr
import { commitGitTargets, publishGitEffect, pushGitRoot } from './effect-git.ts';
import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
import { dispatchFactsBackstopEffect } from './effect-facts.ts';
-import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect } from './effect-model.ts';
+import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
+import { SYNC_SKIP_FILES } from '../sync.ts';
import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
@@ -77,7 +78,8 @@ async function finishPage(engine: BrainEngine, effect: PersistenceEffect, snapsh
}
/** Missing physical files never prevent the authoritative withdrawal from materializing. */
-async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot, hostId: string): Promise<void> {
+async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot, hostId: string,
+ skipped?: SkippedTarget['reason']): Promise<void> {
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
await guardEffectSource(tx, effect, hostId);
@@ -85,10 +87,32 @@ async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEff
const current = await tx.readPageSnapshot(snapshot.page.slug, { sourceId: effect.source_id, includeDeleted: true });
if (current?.revision !== snapshot.revision || current.page.id !== snapshot.page.id) throw new OperationError('revision_conflict', 'The withdrawal page changed during preparation.');
await materializePageSnapshot(tx, current);
+ if (skipped) await recordSkippedTarget(tx, effect, { slug: current.page.slug, reason: skipped });
await finishPage(tx, effect, current);
});
}
+/** At most this many skipped scan targets are recorded on one effect. */
+const SKIPPED_TARGET_LIMIT = 100;
+
+async function recordSkippedTarget(engine: BrainEngine, effect: PersistenceEffect, target: SkippedTarget): Promise<void> {
+ await engine.executeRaw(`UPDATE persistence_effects SET data=jsonb_set(data,'{skipped}',COALESCE(data->'skipped','[]'::jsonb)||$3::text::jsonb)
+ WHERE id=$1 AND execution_token=$2::uuid AND jsonb_array_length(COALESCE(data->'skipped','[]'::jsonb))<$4`,
+ [effect.id, effect.execution_token, JSON.stringify([target]), SKIPPED_TARGET_LIMIT]);
+}
+
+/**
+ * #5396: sync never imports a metafile (RESOLVER.md carries the managed durability block by design),
+ * so its legacy page and file diverge; a scan never publishes either one to the other.
+ */
+function isMetafilePage(snapshot: PageSnapshot): boolean {
+ return !!snapshot.page.source_path && (SYNC_SKIP_FILES as readonly string[]).includes(basename(snapshot.page.source_path));
+}
+
+function isFileDatabaseDrift(error: unknown): boolean {
+ return error instanceof OperationError && error.code === 'source_changed' && error.detail === 'file_database_drift';
+}
+
/** The target a failing attempt was working on; unset means the failure is effect-wide. */
interface EffectAttempt { target?: string }
@@ -97,8 +121,16 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
if (!snapshot) { await completeEffect(engine, effect); return; }
attempt.target = snapshot.page.slug;
if (snapshot.sourceIncarnation !== effect.source_incarnation) throw new OperationError('source_changed', 'The mirror source was replaced.');
+ if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }
const content = serializePageToMarkdown(snapshot.page, snapshot.tags);
- const file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;
+ let file: Awaited<ReturnType<typeof prepareFileTarget>>;
+ try {
+ file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;
+ } catch (error) {
+ if (!isFileDatabaseDrift(error)) throw error;
+ await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'file_database_drift');
+ return;
+ }
if (!file || snapshot.page.deleted_at || !existsSync(file.path)) {
// A withdrawal cannot resurrect a deleted or missing physical page.
await materializeAndAdvance(engine, effect, snapshot, opts.hostId);
@@ -152,8 +184,20 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
const snapshot = await selectedEffectPage(engine, effect);
if (!snapshot) { await completeEffect(engine, effect); return; }
attempt.target = snapshot.page.slug;
- const file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,
- snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });
+ const skip = async (reason: SkippedTarget['reason']) => engine.transaction(async tx => {
+ await recordSkippedTarget(tx, effect, { slug: snapshot.page.slug, reason });
+ await finishPage(tx, effect, snapshot);
+ });
+ if (isMetafilePage(snapshot)) { await skip('metafile'); return; }
+ let file: Awaited<ReturnType<typeof prepareFileTarget>>;
+ try {
+ file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,
+ snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });
+ } catch (error) {
+ if (!isFileDatabaseDrift(error)) throw error;
+ await skip('file_database_drift');
+ return;
+ }
if (!file) throw new OperationError('source_changed', 'The Git binding changed.');
const path = file.path;
if (!existsSync(path)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId); return; }
diff --git a/test/persistence-effects.test.ts b/test/persistence-effects.test.ts
index fd060cbc42..22f708a855 100644
--- a/test/persistence-effects.test.ts
+++ b/test/persistence-effects.test.ts
@@ -216,6 +216,35 @@ test('a parked withdrawal mirror target retries through physical publication wit
for (const file of [f.file, laterFile]) expect(parseFactsFence(readFileSync(file, 'utf8')).facts.filter(fact => fact.active)).toHaveLength(0);
});
+test('a divergent RESOLVER.md page and a locally edited page no longer block the withdrawal request\'s git and embedding effects (#5396)', async () => {
+ const f = await fixture(body());
+ await engine.putPage('resolver', page(body()), { sourceId: f.sourceId });
+ await engine.executeRaw("UPDATE pages SET source_path='RESOLVER.md' WHERE source_id=$1 AND slug='resolver'", [f.sourceId]);
+ const resolver = (await engine.readPageSnapshot('resolver', { sourceId: f.sourceId }))!;
+ const resolverFile = join(f.root, 'RESOLVER.md');
+ const durable = `${serializePageToMarkdown(resolver.page, resolver.tags)}\n<!-- BEGIN gbrain-brain-durability (managed; do not edit between markers) -->\nCommit every page.\n<!-- END gbrain-brain-durability -->\n`;
+ writeFileSync(resolverFile, durable);
+ await engine.putPage('notes/drifted', page(body()), { sourceId: f.sourceId });
+ const drifted = (await engine.readPageSnapshot('notes/drifted', { sourceId: f.sourceId }))!;
+ const driftedFile = join(f.root, 'notes/drifted.md'); mkdirSync(dirname(driftedFile), { recursive: true });
+ const localEdit = `${serializePageToMarkdown(drifted.page, drifted.tags)}\nA local edit nobody imported.\n`;
+ writeFileSync(driftedFile, localEdit);
+ const row = await withdraw(f, { subjectless: true });
+ for (let pass = 0; pass < 4; pass++) {
+ await onlyEffects(row.id);
+ await runPersistenceEffects(engine, config, { hostId, limit: 10 });
+ }
+ const effects = await engine.executeRaw<{ kind: string; state: string; attempts: number; data: Record<string, unknown> }>(
+ 'SELECT kind,state,attempts,data FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind', [row.id]);
+ expect(effects.map(effect => [effect.kind, effect.state])).toEqual([['embedding', 'queued'], ['git', 'committed'], ['withdrawal-mirror', 'committed']]);
+ expect(effects.find(effect => effect.kind === 'embedding')!.attempts).toBeGreaterThan(0);
+ expect(effects.find(effect => effect.kind === 'withdrawal-mirror')!.data.skipped).toEqual([
+ { slug: 'notes/drifted', reason: 'file_database_drift' }, { slug: 'resolver', reason: 'metafile' }]);
+ expect(readFileSync(resolverFile, 'utf8')).toBe(durable);
+ expect(readFileSync(driftedFile, 'utf8')).toBe(localEdit);
+ expect(parseFactsFence(readFileSync(f.file, 'utf8')).facts.filter(fact => fact.active)).toHaveLength(0);
+});
+
test('configured recovery capacity refuses file mutation without undoing withdrawal', async () => {
const f = await fixture(body()); const original = readFileSync(f.file, 'utf8'); const row = await withdraw(f); await onlyEffects(row.id);
await engine.setConfig('persistence.limits.worktree_recovery_bytes', '1');