Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a body-preserving rewrite skips facts extraction only for pages an extraction completed for (#6071)
time-attackf76d5a8a6d37
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 7bbc6d2a79..f32fdb4626 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -32,7 +32,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; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` unless a facts-backstop effect or startable facts-absorb job bound to that page id is still pending (the new revision would supersede it), 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-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, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. 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/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex 81a7f56bf4..8873cec348 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -56,21 +56,12 @@ async function extractionPendingForPage(engine: BrainEngine, pageId: number): Prreturn row?.pending === true;}-/**- * #6071 product switch, pending a maintainer decision. false: a body-preserving- * write skips extraction even for a page no extraction was ever offered for- * (`gbrain extract-conversation-facts` remains the explicit path). true: such a- * write still queues extraction for a page with no facts-backstop or- * facts-absorb record.- */-export const BODY_PRESERVING_WRITES_EXTRACT_NEVER_OFFERED_PAGES = false;--async function extractionEverOffered(engine: BrainEngine, pageId: number): Promise<boolean> {- const [row] = await engine.executeRaw<{ offered: boolean }>(- `SELECT EXISTS (SELECT 1 FROM persistence_effects WHERE kind = 'facts-backstop' AND data->>'page_id' = $1)- OR EXISTS (SELECT 1 FROM minion_jobs WHERE name = 'facts-absorb' AND data->>'page_id' = $1) AS offered`,+async function extractionCompletedForPage(engine: BrainEngine, pageId: number): Promise<boolean> {+ const [row] = await engine.executeRaw<{ done: boolean }>(+ `SELECT EXISTS (SELECT 1 FROM minion_jobs+ WHERE name = 'facts-absorb' AND status = 'completed' AND data->>'page_id' = $1) AS done`,[String(pageId)]);- return row?.offered === true;+ return row?.done === true;}/**@@ -78,14 +69,16 @@ async function extractionEverOffered(engine: BrainEngine, pageId: number): Promi* already eligible before this write and the write keeps its compiled_truth* (a title, tag, frontmatter or timeline change, such as `repair timeline`* writing back rows the database already holds), there is nothing new to- * extract. The exception is an extraction still pending for the page: this- * write supersedes it, so the write must queue in its place.+ * extract, provided an extraction already completed for this page. A page no+ * extraction ever completed for still queues one (#6071, maintainer decision B),+ * and so does a page with an extraction still pending: this write supersedes it,+ * so the write must queue in its place.*/async function bodyAlreadyOffered(engine: BrainEngine, slug: string, page: ParsedPage, before: PageSnapshot | null): Promise<boolean> {const live = before && !before.page.deleted_at ? before.page : null;if (!live || live.compiled_truth !== page.compiled_truth) return false;if (!isFactsBackstopEligible(slug, live).ok) return false;- if (BODY_PRESERVING_WRITES_EXTRACT_NEVER_OFFERED_PAGES && !(await extractionEverOffered(engine, live.id))) return false;+ if (!(await extractionCompletedForPage(engine, live.id))) return false;return !(await extractionPendingForPage(engine, live.id));}diff --git a/test/persistence-facts-backstop.test.ts b/test/persistence-facts-backstop.test.tsindex 216171be20..4274faea9f 100644--- a/test/persistence-facts-backstop.test.ts+++ b/test/persistence-facts-backstop.test.ts@@ -6,7 +6,6 @@ import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';-import { BODY_PRESERVING_WRITES_EXTRACT_NEVER_OFFERED_PAGES } from '../src/core/persistence/effect-facts.ts';import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';@@ -182,10 +181,12 @@ test.each(['waiting', 'delayed', 'paused', 'waiting-children', 'active'])('#6042expect(await rewrite(retitled('Renamed during the job'))).toEqual({ status: { queued: true }, effectQueued: true });}));-test.each(['completed', 'failed', 'dead', 'cancelled'])('#6042: a facts-absorb job that is %s no longer blocks the skip', (status) => fixture(async () => {+test.each(['completed', 'failed', 'dead', 'cancelled'])('#6042: on an extracted page, a later facts-absorb job that is %s no longer blocks the skip', (status) => fixture(async () => {await publish();await finishExtractions();- await engine.executeRaw("UPDATE minion_jobs SET status = $1 WHERE name = 'facts-absorb'", [status]);+ const { page } = (await engine.readPageSnapshot('notes/example', { sourceId: 'default' }))!;+ const later = await new MinionQueue(engine).add('facts-absorb', { slug: 'notes/example', sourceId: 'default', page_id: page.id }, { queue: 'default' });+ await engine.executeRaw('UPDATE minion_jobs SET status = $1 WHERE id = $2', [status, later.id]);expect((await rewrite(retitled('Renamed after the job'))).status).toEqual({ skipped: 'body_unchanged' });}));@@ -212,17 +213,26 @@ test('#6042: rewriting a soft-deleted page with its old body queues extraction aexpect(await rewrite(content)).toEqual({ status: { queued: true }, effectQueued: true });}));-test('#6071 switch: a body-preserving rewrite of a never-extracted eligible page follows BODY_PRESERVING_WRITES_EXTRACT_NEVER_OFFERED_PAGES', () => fixture(async () => {+test('#6071: a body-preserving rewrite of an extracted page queues no extraction', () => fixture(async () => {+ await publish();+ await finishExtractions();+ const before = (await jobs()).length;+ expect(await rewrite(retitled('Renamed after extraction'))).toEqual({ status: { skipped: 'body_unchanged' }, effectQueued: false });+ expect(await jobs()).toHaveLength(before);+}));++test('#6071: a body-preserving rewrite of a never-extracted eligible page still queues extraction', () => 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 result = await rewrite(retitled('Renamed after enabling'));- if (BODY_PRESERVING_WRITES_EXTRACT_NEVER_OFFERED_PAGES) {- expect(result).toEqual({ status: { queued: true }, effectQueued: true });- } else {- expect(result).toEqual({ status: { skipped: 'body_unchanged' }, effectQueued: false });- expect(await jobs()).toHaveLength(0);- }+ expect(await rewrite(retitled('Renamed after enabling'))).toEqual({ status: { queued: true }, effectQueued: true });+}));++test('#6071: an extraction that did not complete does not count as extracted', () => fixture(async () => {+ await publish();+ await finishExtractions();+ await engine.executeRaw("UPDATE minion_jobs SET status = 'failed' WHERE name = 'facts-absorb'");+ expect(await rewrite(retitled('Renamed after a failed extraction'))).toEqual({ status: { queued: true }, effectQueued: true });}));test('a slug-bound writer\'s backstop refusal says the page was written and who widens the grant', async () => {diff --git a/test/repair-command.test.ts b/test/repair-command.test.tsindex 2b3376a6dc..bf7331d608 100644--- a/test/repair-command.test.ts+++ b/test/repair-command.test.ts@@ -23,6 +23,8 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';import { testBackends } from './helpers/test-backends.ts';import { runCli } from './helpers/cli-spawn.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+const backends = testBackends();const engines: BrainEngine[] = [];@@ -110,6 +112,9 @@ describe('gbrain repair timeline', () => {// Stand-in for the page's own extraction having run: its outbox entry is settled.await disposePersistenceConsumer(engine);await engine.executeRaw(`UPDATE persistence_effects SET state='committed' WHERE kind='facts-backstop' AND source_id=$1`, [source]);+ const [{ id: pageId }] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id=$1 AND slug='notes/report'`, [source]);+ const done = await new MinionQueue(engine).add('facts-absorb', { slug: 'notes/report', sourceId: source, page_id: pageId }, { queue: 'default' });+ await engine.executeRaw(`UPDATE minion_jobs SET status='completed', finished_at=now() WHERE id=$1`, [done.id]);const receipts = async () => engine.executeRaw<{ id: string; facts: unknown }>(`SELECT id, outcome->'facts_backstop' AS facts FROM persistence_requestsWHERE source_id=$1 AND slug='notes/report' AND operation='put_page' AND state='committed' ORDER BY created_at`, [source]);