Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): skip the facts backstop when a write keeps an eligible page's body (#6071)
time-attack7f8ddaf0542d
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 96496db7fe..cf073be357 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -30,7 +30,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.-- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.+- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live page that was already eligible skips with `body_unchanged`, so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.- `src/core/persistence/effect-recovery-scan.ts` — bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations. `test/persistence-effect-recovery-fairness.test.ts` holds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex fb7dfdedad..903e47b712 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -526,7 +526,15 @@ intent committed with the page; the `facts-backstop` effect becomes`dispatched` when its durable worker job is accepted. Extraction availabilityis checked by that worker. The handoff is idempotent and rechecks the source,page revision and current writer grant. Confined writers, unchanged pages,-disabled extraction and dream-generated content do not enqueue work.+disabled extraction and dream-generated content do not enqueue work. Neither+does a write that keeps the body (`compiled_truth`, the only text extraction+reads) of a page that was already eligible: a frontmatter or timeline change,+or `gbrain repair timeline` writing back rows the database already holds,+records `facts_backstop: { skipped: "body_unchanged" }`. Such a page's facts+are extracted when its body next changes. For conversation-shaped pages+(`conversation`, `meeting`, `slack`, `email`, `imessage`), `gbrain+extract-conversation-facts --dry-run` shows what a backfill would process+without model calls, and `--max-cost-usd` caps the run's spend.Managed jobs retain the committed page request as their authority and publishthrough the coordinator. Legacy jobs without that request skip with`missing_write_authority`; raw queue/fence paths remain unsupported. Activationdiff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex 9397fca4c1..b6f79e094b 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -35,13 +35,33 @@ export async function authorizeFactsBackstop(engine: BrainEngine, row: WriteRequ}}-/** Provider availability belongs to the durable job's execution process. */-export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage): Promise<FactsBackstopStatus> {+/** An extraction of the page that has not finished; a write moves the revision it is bound to, so it would end `superseded`. */+async function factsExtractionInFlight(engine: BrainEngine, sourceId: string, slug: string): Promise<boolean> {+ const rows = await engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE kind='facts-backstop' AND state IN ('queued','running')+ AND source_id=$1 AND data->>'slug'=$2+ UNION ALL SELECT 1 FROM minion_jobs WHERE name='facts-absorb' AND status IN ('waiting','active','delayed','paused','waiting-children')+ AND data->>'sourceId'=$1 AND data->>'slug'=$2 LIMIT 1`, [sourceId, slug]);+ return rows.length > 0;+}++/**+ * Provider availability belongs to the durable job's execution process.+ * `prior` is the live page before this write. Extraction reads only+ * compiled_truth, so a write that keeps the body of a page that was already+ * eligible (a frontmatter or timeline change, or `repair timeline`+ * materializing rows the database already holds) has nothing new to extract+ * (#6042), unless it supersedes an unfinished extraction of the page: then it+ * queues one in that extraction's place.+ */+export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage,+ prior?: Pick<ParsedPage, 'type' | 'compiled_truth' | 'frontmatter'>): Promise<FactsBackstopStatus> {const confined = derivedExtractionSkip(row.authority);if (confined) return { skipped: confined };if (!(await isFactsExtractionEnabled(engine))) return { skipped: 'extraction_disabled' };const eligible = isFactsBackstopEligible(row.slug, page);if (!eligible.ok) return { skipped: eligible.reason };+ if (prior && prior.compiled_truth === page.compiled_truth && isFactsBackstopEligible(row.slug, prior).ok+ && !(await factsExtractionInFlight(engine, row.source_id, row.slug))) return { skipped: 'body_unchanged' };return { queued: true };}diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.tsindex 43e0ac5ffd..4e4ca8fdb7 100644--- a/src/core/persistence/page-advisories.ts+++ b/src/core/persistence/page-advisories.ts@@ -16,13 +16,14 @@ export function pageNoopAdvisories(row: WriteRequest): Record<string, unknown> {return { ...remoteLinkHint(row), ...(['put_page', 'capture', 'edit_page'].includes(row.operation) ? { facts_backstop: { skipped: 'not_imported' } } : {}) };}/** Optional lint reads are outside publication locks; its bounded result is retained in the receipt. */-export async function preparePageAdvisories(engine: BrainEngine, row: WriteRequest, page: ParsedPage) {+export async function preparePageAdvisories(engine: BrainEngine, row: WriteRequest, page: ParsedPage,+ prior?: Pick<ParsedPage, 'type' | 'compiled_truth' | 'frontmatter'>) {const visible = row.authority.remote ? { ...page, compiled_truth: sanitizeRemoteBody(page.compiled_truth),timeline: sanitizeRemoteBody(page.timeline ?? '') } : page;const lint = await writerLintForPutPage(engine, row.slug, { sourceId: row.source_id, noLog: true, page: visible });const sanitized = lint && 'top_findings' in lint ? { ...lint,top_findings: lint.top_findings.map(finding => ({ ...finding, message: LINT_MESSAGES[finding.validator] ?? `${finding.validator} validation finding.` })) } : lint;const facts = ['put_page', 'capture', 'edit_page'].includes(row.operation)- ? await prepareFactsBackstop(engine, row, page).catch(() => ({ skipped: 'backstop_error' })) : undefined;+ ? await prepareFactsBackstop(engine, row, page, prior).catch(() => ({ skipped: 'backstop_error' })) : undefined;return { ...remoteLinkHint(row), ...(sanitized ? { writer_lint: sanitized } : {}), ...(facts ? { facts_backstop: facts } : {}) };}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex b68222cb5f..aebb6c5159 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -389,7 +389,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst noop = logicalNoop && (snapshot?.page.deleted_at != null) === targetDeleted;const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined;const ordinaryPage = ['put_page','capture','restore_page','revert_version','edit_page'].includes(row.operation);- const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage);+ const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage,snapshot?.page.deleted_at == null ? snapshot?.page : undefined);// A managed maintenance page (e.g. the dream write-back after grounding// quarantine) republishes a body; its automatic links follow that body.const autoLinkedPage = ordinaryPage || p.kind === 'managed_maintenance_page';diff --git a/test/persistence-facts-backstop.test.ts b/test/persistence-facts-backstop.test.tsindex c8067bde6d..86bb978bc7 100644--- a/test/persistence-facts-backstop.test.ts+++ b/test/persistence-facts-backstop.test.ts@@ -32,7 +32,7 @@ async function prepare(overrides: Partial<OperationContext> = {}, params: Recordconst ctx: OperationContext = { engine, config, dryRun: false, remote: false, sourceId: 'default', logger: { info() {}, warn() {}, error() {} }, ...overrides };const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, 'notes/example');const intent = { content, ...params };- const current = await engine.readPageSnapshot('notes/example', { sourceId: 'default' });+ const current = await engine.readPageSnapshot('notes/example', { sourceId: 'default', includeDeleted: true });await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',sourceIncarnation: source.incarnation, slug: 'notes/example', pageId: current?.page.id ?? null, requestId: randomUUID(), callerIntent: intent, intent });const row = (await claimNextWrite(engine, localHostId()))!;@@ -46,6 +46,14 @@ async function claimFacts(row: WriteRequest) {return effect;}async function jobs() { return engine.executeRaw<{ id: number; data: Record<string, unknown>; idempotency_key: string }>("SELECT id,data,idempotency_key FROM minion_jobs WHERE name='facts-absorb'"); }+/** Hand every queued facts effect to its job and finish the jobs, so no extraction of the page is in flight. */+async function settleFacts() {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE kind<>'facts-backstop'");+ for (let effect = await claimPersistenceEffect(engine, localHostId()); effect; effect = await claimPersistenceEffect(engine, localHostId())) {+ await dispatchFactsBackstopEffect(engine, effect, localHostId());+ }+ await engine.executeRaw("UPDATE minion_jobs SET status='completed' WHERE name='facts-absorb'");+}test('page receipt and bounded extraction debt commit together; durable handoff rolls back and replays once', () => fixture(async () => {const row = await publish(); expect(row.outcome?.facts_backstop).toEqual({ queued: true });@@ -128,6 +136,52 @@ test('confined writers and disabled extraction never receive a queued claim', ()expect(disabled.outcome?.facts_backstop).toEqual({ skipped: 'extraction_disabled' });}));+test('a write that leaves the page body unchanged records no extraction debt; a body change does (#6042)', () => fixture(async () => {+ expect((await publish()).outcome?.facts_backstop).toEqual({ queued: true });+ const titled = (title: string, rest = '') => `${content.replace('title: Field notes', `title: ${title}`)}${rest}`;+ const timeline = '\n\n<!-- timeline -->\n- **2026-07-01** | A synthetic dated event.';+ const concept = titled('Revised notes', timeline).replace('type: note', 'type: concept');+ for (const [change, next, expected, settled] of [+ // The first write's extraction has not run; this write supersedes it, so it queues in its place.+ ['title only, extraction in flight', titled('Renamed notes'), { queued: true }, false],+ ['title only', titled('Revised notes'), { skipped: 'body_unchanged' }, true],+ ['timeline only', titled('Revised notes', timeline), { skipped: 'body_unchanged' }, true],+ ['retyped ineligible', concept, { skipped: 'kind:concept' }, true],+ // The body was never offered while the page was a concept, so becoming eligible extracts it.+ ['retyped eligible', titled('Revised notes', timeline), { queued: true }, true],+ ['body', titled('Revised notes', ` One more substantive sentence about the project.${timeline}`), { queued: true }, true],+ ] as const) {+ if (settled) await settleFacts();+ const current = (await engine.readPageSnapshot('notes/example', { sourceId: 'default' }))!;+ const input = await prepare({}, { content: next, expected_revision: current.revision });+ const row = await publishMutation(engine, input.row, input.prepared);+ expect([change, row.state, row.outcome?.facts_backstop]).toEqual([change, 'committed', expected]);+ expect([change, (await publicEffectsForRequest(engine, row.id)).some(effect => effect.kind === 'facts-backstop')]).toEqual([change, 'queued' in expected]);+ }+}));++test('rewriting a deleted page with its old body extracts it again (#6042)', () => fixture(async () => {+ await publish();+ await settleFacts();+ await engine.softDeletePage('notes/example', { sourceId: 'default' });+ const deleted = (await engine.readPageSnapshot('notes/example', { sourceId: 'default', includeDeleted: true }))!;+ const input = await prepare({}, { expected_revision: deleted.revision });+ const restored = await publishMutation(engine, input.row, input.prepared);+ expect([restored.state, restored.outcome?.facts_backstop]).toEqual(['committed', { queued: true }]);+}));++test('a maintenance write that keeps the body of a never-extracted eligible page queues nothing (#6042)', () => fixture(async () => {+ await engine.setConfig('facts.extraction_enabled', 'false');+ expect((await publish()).outcome?.facts_backstop).toEqual({ skipped: 'extraction_disabled' });+ await engine.setConfig('facts.extraction_enabled', 'true');+ const current = (await engine.readPageSnapshot('notes/example', { sourceId: 'default' }))!;+ const input = await prepare({}, { content: content.replace('title: Field notes', 'title: Retitled notes'), expected_revision: current.revision });+ const row = await publishMutation(engine, input.row, input.prepared);+ expect([row.state, row.outcome?.facts_backstop]).toEqual(['committed', { skipped: 'body_unchanged' }]);+ expect((await publicEffectsForRequest(engine, row.id)).some(effect => effect.kind === 'facts-backstop')).toBe(false);+ expect(await jobs()).toHaveLength(0);+}));+test('a slug-bound writer\'s backstop refusal says the page was written and who widens the grant', async () => {const row = { slug: 'notes/a', authority: { slugPrefixes: ['notes/'] } } as unknown as WriteRequest;await expect(authorizeFactsBackstop(engine, row)).rejects.toMatchObject({ code: 'permission_denied',diff --git a/test/repair-command.test.ts b/test/repair-command.test.tsindex 25460f6186..cb8bb49609 100644--- a/test/repair-command.test.ts+++ b/test/repair-command.test.ts@@ -14,6 +14,8 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { localHostId } from '../src/core/persistence/identity.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';import { timelineRepair } from '../src/core/repair/timeline.ts';@@ -72,8 +74,8 @@ async function brain(run: (engine: BrainEngine, sources: string[]) => Promise<vo}}-async function pageWithHistory(engine: BrainEngine, sourceId: string, slug: string) {- await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, content: page(`Body of ${slug}.`), request_id: randomUUID() } });+async function pageWithHistory(engine: BrainEngine, sourceId: string, slug: string, body = `Body of ${slug}.`) {+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, content: page(body), request_id: randomUUID() } });await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy',$3,'' FROM pages WHERE source_id=$1 AND slug=$2`,[sourceId, slug, `History of ${slug}`]), TEST_WRITE_ATTRIBUTION));@@ -100,6 +102,24 @@ describe('gbrain repair timeline', () => {});}, 120_000);+ test('materializing rows into an eligible page queues no facts extraction (#6042)', async () => {+ await brain(async (engine, [source]) => {+ await pageWithHistory(engine, source, 'notes/a', 'A synthetic newsletter body, long enough that the facts backstop would extract from it.');+ // The page's own extraction has finished, as it had for the pages #6042 rewrote.+ await disposePersistenceConsumer(engine);+ for (let pass = 0; pass < 20 && await runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 }); pass++);+ await engine.executeRaw("UPDATE minion_jobs SET status='completed' WHERE name='facts-absorb' AND data->>'sourceId'=$1", [source]);+ const applied = await runRepair(ctxFor(engine, source), timelineRepair, await resolveRepairScope(engine), { apply: true });+ expect(applied).toMatchObject({ applied: 1, complete: true });+ expect(await markedPages(engine, source)).toEqual(['notes/a']);+ const writes = await engine.executeRaw<{ id: string; outcome: { facts_backstop?: unknown } }>(`SELECT id,outcome FROM persistence_requests+ WHERE source_id=$1 AND slug='notes/a' AND operation='put_page' AND state='committed' ORDER BY created_at`, [source]);+ // The page's own write extracts; the repair republishes the same body, so it does not.+ expect(writes.map(write => write.outcome.facts_backstop)).toEqual([{ queued: true }, { skipped: 'body_unchanged' }]);+ expect(await engine.executeRaw("SELECT id FROM persistence_effects WHERE request_id=$1::uuid AND kind='facts-backstop'", [writes[1].id])).toEqual([]);+ });+ }, 120_000);+test('--limit stops after n items and a rerun resumes from the scope-bound checkpoint', async () => {await brain(async (engine, [source]) => {for (const slug of ['notes/a', 'notes/b', 'notes/c']) await pageWithHistory(engine, source, slug);