Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): the managed-facts preflight waits up to 1 s for its own writer instead of refusing

garrytan0ee6bc9736cf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f173f63f99..2f2d7010c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -129,6 +129,7 @@ The release also absorbs 62 open community pull requests, each re-checked agains
- **What the agent saves with `remember` is no longer stored a second time by automatic capture (#5888).** The writeback hook, the compaction harvest and the corpus sweep skip a fact only on an exact normalized match (rules above). Capture counts same-entity near duplicates (cosine 0.92 or higher) without dropping them, so a threshold can be measured first. Hot memory and the `context_pack`/`delta` facts show one line per duplicate group. Each skip is logged on stderr and in the hook heartbeat, and `gbrain doctor` (`memory_writeback`) reports `cross_lane_duplicates_7d` and `near_duplicates_shadow_7d`.
- **The maintenance sweep reads whole session transcripts, and a resumed session no longer re-extracts the same head (#5887).** Windows break at turn boundaries and carry their `[user]` or `[assistant]` label, pasted blocks are removed first, and the progress sidecar makes appends and compaction rewrites cost only their new turns. `gbrain sweep --once --json` reports `corpus_files[]` with `windows_done` and `windows_remaining`. Ported from #5897. Contributed by @javieraldape.
+- **A capture right after another managed write no longer refuses as "writer busy".** The managed-facts preflight probed the worktree lock with no wait, while this process's own persistence consumer was still finishing the previous write (its receipt already read committed). A `remember` followed by automatic capture could lose that capture for a whole sweep cycle. The preflight now waits up to 1 s; a writer still busy after that refuses with `writer_lock_unavailable` as before.
- **New explicit repair `gbrain repair captured-facts`** expires facts captured before v0.60.30.0 from gbrain's own claude-cli sessions or from pasted text (doctor `captured_facts_active`; the post-upgrade banner names the preview). Self-capture facts with evidence expire with `--apply --expect <hash>`; paste candidates (a word-overlap heuristic against the retained session corpus) only with `--include-ambiguous`. A claim with a legitimate active copy is kept. Facts are expired, never withdrawn, so `remember` can save the claim again.
#### Search (#5889, #5890, #5892)
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index ee1373f5b3..af629039d6 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -103,6 +103,16 @@ export async function assertManagedFactsEmbedding(engine: BrainEngine, config: G
}
}
+/**
+ * How long the managed-facts preflight waits for the worktree lock. This
+ * process's own persistence consumer holds it while it finishes publishing
+ * the previous write, after that write's receipt already reads committed, so
+ * a capture that follows a `remember` or another capture found it busy and
+ * refused for a whole sweep cycle. A holder still busy after the wait is a
+ * real conflict and still refuses.
+ */
+export const MANAGED_FACTS_WRITER_WAIT_MS = 1000;
+
export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
input: { turnText: string; pageSlug?: string }): Promise<ManagedFactsSession | null> {
const engine = ctx.engine;
@@ -166,7 +176,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
if (writeThrough && binding) {
if (binding.state !== 'active' || !binding.owner_host_id) throw new OperationError('owner_unavailable', 'The canonical fact writer is unavailable; extraction has not started.');
if (binding.owner_host_id === localHostId()) {
- const lock = await acquireWorktree(binding, 0, undefined, engine);
+ const lock = await acquireWorktree(binding, MANAGED_FACTS_WRITER_WAIT_MS, undefined, engine);
if (!lock) throw new OperationError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.');
await lock.release();
}
diff --git a/test/capture-dedup.test.ts b/test/capture-dedup.test.ts
index 112561de48..d6ecd254f1 100644
--- a/test/capture-dedup.test.ts
+++ b/test/capture-dedup.test.ts
@@ -25,14 +25,15 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
import { runFactsPipeline, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { disposePersistenceConsumer, persistenceConsumerStatus } from '../src/core/persistence/service.ts';
+import { MANAGED_FACTS_WRITER_WAIT_MS } from '../src/core/persistence/facts-maintenance.ts';
import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
import { readHeartbeatTail } from '../src/core/context/hook-heartbeat.ts';
import { buildMemoryWritebackCheck } from '../src/commands/doctor/checks/memory-writeback.ts';
@@ -67,12 +68,27 @@ function extracts(facts: Array<{ fact: string; entity: string | null }>) {
usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
}));
}
-function capture(source: FactsBackstopCtx['source'], sessionId: string | null, extra: Partial<FactsBackstopCtx> = {}) {
- return runFactsPipeline(`A synthetic turn ${Math.random()}`, { engine, sourceId, sessionId, source, mode: 'inline', remote: false, ...extra });
+/**
+ * Waits until this engine's persistence consumer has finished every claimed
+ * publication: a receipt reads committed before the publishing task releases
+ * the worktree lock, so the next step must not race that tail.
+ */
+async function settled() {
+ for (const deadline = Date.now() + 10_000; Date.now() < deadline; await new Promise(r => setTimeout(r, 10))) {
+ const s = persistenceConsumerStatus(engine);
+ if (s.active_preparations === 0 && s.active_worktrees === 0) return;
+ }
+ throw new Error('persistence consumer did not settle');
+}
+async function capture(source: FactsBackstopCtx['source'], sessionId: string | null, extra: Partial<FactsBackstopCtx> = {}) {
+ const r = await runFactsPipeline(`A synthetic turn ${Math.random()}`, { engine, sourceId, sessionId, source, mode: 'inline', remote: false, ...extra });
+ await settled();
+ return r;
}
async function remember(fact: string, entity: string) {
const r = await dispatchToolCall(engine, 'remember', { fact, entity, provenance: 'user told me' }, { remote: false, sourceId });
expect(r.isError).toBeFalsy();
+ await settled();
}
async function active() {
return engine.executeRaw<{ id: number; fact: string; entity_slug: string | null; visibility: string; source: string }>(
@@ -84,9 +100,10 @@ async function withGuardPaused(edit: () => Promise<unknown>) {
try { await edit(); } finally { if (enabled) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
}
/** Backdates a fixture row; a managed brain's writer guard is paused for the edit, as the connector fixture does. */
-function age(fact: string, minutes: number) {
- return withGuardPaused(() => engine.executeRaw(`UPDATE facts SET created_at=now()-($3::int * interval '1 minute') WHERE source_id=$1 AND fact=$2`,
+async function age(fact: string, minutes: number) {
+ await withGuardPaused(() => engine.executeRaw(`UPDATE facts SET created_at=now()-($3::int * interval '1 minute') WHERE source_id=$1 AND fact=$2`,
[sourceId, fact, minutes]));
+ await settled();
}
async function hotFacts() {
__resetHotMemoryCacheForTests();
@@ -110,6 +127,7 @@ async function freshSource(mode: 'unmanaged' | 'managed') {
const r = await dispatchToolCall(engine, 'put_page', { slug, content: `---\ntitle: ${title}\ntype: ${type}\n---\n\n${body}\n` }, { remote: false, sourceId });
expect(r.isError).toBeFalsy();
}
+ await settled();
}
for (const backend of testBackends()) describe(`capture dedup on ${backend}`, () => {
@@ -139,6 +157,28 @@ for (const mode of ['unmanaged', 'managed'] as const) {
describe(`capture dedup (${mode})`, () => {
const run = (fn: () => Promise<void>) => withEnv({ GBRAIN_HOME: home }, async () => { await freshSource(mode); await fn(); });
+ if (mode === 'managed') {
+ // The preflight waits up to MANAGED_FACTS_WRITER_WAIT_MS for the worktree
+ // lock: a writer finishing its previous publication is not a conflict.
+ const holdLock = async (ms: number) => {
+ const lock = await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 0, undefined, engine);
+ expect(lock).not.toBeNull();
+ return new Promise<void>(resolve => setTimeout(() => { void lock!.release().then(resolve); }, ms));
+ };
+ test('the fact preflight waits out a writer that releases within the bound', () => run(async () => {
+ const released = holdLock(200);
+ extracts([{ fact: 'Bob Example owns the Acme Example launch checklist', entity: 'people/bob-example' }]);
+ expect(await capture('hook:writeback', 'sess-lock')).toMatchObject({ inserted: 1 });
+ await released;
+ }), 60_000);
+ test('a writer busy past the bound still refuses with writer_lock_unavailable', () => run(async () => {
+ const released = holdLock(MANAGED_FACTS_WRITER_WAIT_MS + 1500);
+ extracts([{ fact: 'Bob Example owns the Acme Example budget review', entity: 'people/bob-example' }]);
+ await expect(capture('hook:writeback', 'sess-lock-2')).rejects.toMatchObject({ code: 'writer_lock_unavailable' });
+ await released;
+ }), 60_000);
+ }
+
test('remember then a writeback of the same claim on another entity ends with one active row and one hot fact', () => run(async () => {
const claim = 'Alice Example will lead the Acme Example renewal in November';
await remember(claim, 'people/alice-example');