Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(persistence): our own implementation of the #6071 fix (#6071)

time-attacka3c67c582ad6
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 535caa395d..84e906c563 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 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-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-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.md
index 868da8654f..83aedeb6cd 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -529,15 +529,21 @@ intent committed with the page; the `facts-backstop` effect becomes
`dispatched` when its durable worker job is accepted. Extraction availability
is 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. 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
+disabled extraction and dream-generated content do not enqueue work.
+Extraction reads only `compiled_truth`, so a write that leaves it unchanged on
+a live page that was already eligible records
+`facts_backstop: { skipped: "body_unchanged" }` and queues nothing. Title,
+tag, frontmatter and timeline edits fall in this case, as does
+`gbrain repair timeline` writing back rows the database already holds. If an
+extraction of that page is still pending (its effect not yet handed off, or
+its job not yet finished), the write queues anyway, because its new revision
+supersedes the pending one. A page that becomes eligible, or a deleted page
+written again, is extracted even with the same body. A body-preserving write
+does not extract an eligible page that was never extracted; its facts are
+extracted when the 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.
+extract-conversation-facts --dry-run` previews a backfill without model calls,
+and `--max-cost-usd` caps its spend.
Managed jobs retain the committed page request as their authority and publish
through the coordinator. Legacy jobs without that request skip with
`missing_write_authority`; raw queue/fence paths remain unsupported. Activation
diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.ts
index b6f79e094b..19830bd4f6 100644
--- a/src/core/persistence/effect-facts.ts
+++ b/src/core/persistence/effect-facts.ts
@@ -3,6 +3,8 @@ import type { ParsedPage } from '../import-file.ts';
import { isFactsBackstopEligible } from '../facts/eligibility.ts';
import { isFactsExtractionEnabled } from '../facts/extract.ts';
import { MinionQueue } from '../minions/queue.ts';
+import type { MinionJobStatus } from '../minions/types.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
@@ -35,33 +37,51 @@ export async function authorizeFactsBackstop(engine: BrainEngine, row: WriteRequ
}
}
-/** 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;
+/** Job states from which a facts-absorb job can still start, and so can still be superseded by a newer revision. */
+const STARTABLE_JOB_STATES: readonly MinionJobStatus[] = ['waiting', 'delayed', 'paused', 'waiting-children', 'active'];
+
+/**
+ * Whether an extraction bound to this page row has yet to read it: a
+ * facts-backstop effect still in the outbox, or a facts-absorb job that can
+ * still start. Both carry the page id and revision, so the next revision ends
+ * them as `superseded`.
+ */
+async function extractionPendingForPage(engine: BrainEngine, pageId: number): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ pending: boolean }>(
+ `SELECT EXISTS (SELECT 1 FROM persistence_effects
+ WHERE kind = 'facts-backstop' AND state IN ('queued', 'running') AND data->>'page_id' = $1)
+ OR EXISTS (SELECT 1 FROM minion_jobs
+ WHERE name = 'facts-absorb' AND status = ANY($2::text[]) AND data->>'page_id' = $1) AS pending`,
+ [String(pageId), [...STARTABLE_JOB_STATES]]);
+ return row?.pending === true;
+}
+
+/**
+ * #6042: the extractor reads compiled_truth only. When the page was live and
+ * 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.
+ */
+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;
+ return !(await extractionPendingForPage(engine, live.id));
}
/**
* 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.
+ * `before` is the page as this write found it (null for a new page).
*/
-export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage,
- prior?: Pick<ParsedPage, 'type' | 'compiled_truth' | 'frontmatter'>): Promise<FactsBackstopStatus> {
+export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage, before: PageSnapshot | null = null): 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' };
+ if (await bodyAlreadyOffered(engine, row.slug, page, before)) return { skipped: 'body_unchanged' };
return { queued: true };
}
diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.ts
index 4e4ca8fdb7..1a1bdd6c0b 100644
--- a/src/core/persistence/page-advisories.ts
+++ b/src/core/persistence/page-advisories.ts
@@ -3,6 +3,7 @@ import type { ParsedPage } from '../import-file.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { writerLintForPutPage } from '../output/post-write.ts';
import type { WriteRequest } from './model.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
import { prepareFactsBackstop } from './effect-facts.ts';
const LINT_MESSAGES: Record<string,string> = { citation:'Paragraph has no citation marker.',
@@ -16,14 +17,13 @@ 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,
- prior?: Pick<ParsedPage, 'type' | 'compiled_truth' | 'frontmatter'>) {
+export async function preparePageAdvisories(engine: BrainEngine, row: WriteRequest, page: ParsedPage, before: PageSnapshot | null = null) {
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, prior).catch(() => ({ skipped: 'backstop_error' })) : undefined;
+ ? await prepareFactsBackstop(engine, row, page, before).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.ts
index 9c10c1a497..fd2341ff75 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -390,7 +390,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const 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,snapshot?.page.deleted_at == null ? snapshot?.page : undefined);
+ const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage,snapshot);
// 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.ts
index 86bb978bc7..f4682bed7a 100644
--- a/test/persistence-facts-backstop.test.ts
+++ b/test/persistence-facts-backstop.test.ts
@@ -13,6 +13,7 @@ import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { claimPersistenceEffect, publicEffectsForRequest } from '../src/core/persistence/effect-journal.ts';
import { authorizeFactsBackstop, dispatchFactsBackstopEffect, readFactsBackstopJobPage } from '../src/core/persistence/effect-facts.ts';
import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -46,14 +47,6 @@ 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 });
@@ -136,49 +129,93 @@ 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]);
+// #6042: a rewrite that keeps compiled_truth (the only text the extractor reads) of an extracted page.
+const retitled = (title: string) => content.replace('title: Field notes', `title: ${title}`);
+const withTimeline = (body: string) => `${body}\n\n--- timeline ---\n\n- **2026-08-02** | A synthetic dated event.\n`;
+
+/** Hands every pending facts effect to its job, then records the jobs as finished: no extraction of the page is pending. */
+async function finishExtractions() {
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at = now() + interval '1 hour' WHERE kind <> 'facts-backstop'");
+ for (;;) {
+ const effect = await claimPersistenceEffect(engine, localHostId());
+ if (!effect) break;
+ await dispatchFactsBackstopEffect(engine, effect, localHostId());
}
+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE name = 'facts-absorb'");
+}
+/** Publishes `body` against the page's current revision, deleted pages included. */
+async function rewrite(body: string) {
+ const before = (await engine.readPageSnapshot('notes/example', { sourceId: 'default', includeDeleted: true }))!;
+ const input = await prepare({}, { content: body, expected_revision: before.revision });
+ const row = await publishMutation(engine, input.row, input.prepared);
+ expect(row.state).toBe('committed');
+ const effectQueued = (await publicEffectsForRequest(engine, row.id)).some(effect => effect.kind === 'facts-backstop');
+ return { status: row.outcome?.facts_backstop, effectQueued };
+}
+
+test('#6042: title-only and timeline-only rewrites of an extracted page record body_unchanged and queue no effect', () => fixture(async () => {
+ expect((await publish()).outcome?.facts_backstop).toEqual({ queued: true });
+ await finishExtractions();
+ expect(await rewrite(retitled('Renamed once'))).toEqual({ status: { skipped: 'body_unchanged' }, effectQueued: false });
+ expect(await rewrite(withTimeline(retitled('Renamed once')))).toEqual({ status: { skipped: 'body_unchanged' }, effectQueued: false });
+ expect(await jobs()).toHaveLength(1);
+}));
+
+test('#6042 control: a rewrite that changes compiled_truth still queues extraction', () => fixture(async () => {
+ await publish();
+ await finishExtractions();
+ expect(await rewrite(`${content}A further substantive sentence about the project schedule.\n`)).toEqual({ status: { queued: true }, effectQueued: true });
}));
-test('rewriting a deleted page with its old body extracts it again (#6042)', () => fixture(async () => {
+test('#6042: an extraction still in the outbox is superseded by the rewrite, so the rewrite queues in its place', () => fixture(async () => {
await publish();
- await settleFacts();
+ expect(await rewrite(retitled('Renamed before extraction'))).toEqual({ status: { queued: true }, effectQueued: true });
+}));
+
+test.each(['waiting', 'delayed', 'paused', 'waiting-children', 'active'])('#6042: a facts-absorb job that is %s still counts as pending', (status) => fixture(async () => {
+ await publish();
+ await finishExtractions();
+ // A move to active is a claim, which the queue protocol trigger requires to advance claim_generation.
+ await engine.executeRaw(`UPDATE minion_jobs SET status = $1::text,
+ claim_generation = claim_generation + CASE WHEN $1::text = 'active' THEN 1 ELSE 0 END WHERE name = 'facts-absorb'`, [status]);
+ expect(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 () => {
+ await publish();
+ await finishExtractions();
+ await engine.executeRaw("UPDATE minion_jobs SET status = $1 WHERE name = 'facts-absorb'", [status]);
+ expect((await rewrite(retitled('Renamed after the job'))).status).toEqual({ skipped: 'body_unchanged' });
+}));
+
+test('#6042: only an extraction bound to this page row blocks the skip, not one for the same slug elsewhere', () => fixture(async () => {
+ await publish();
+ await finishExtractions();
+ const { page } = (await engine.readPageSnapshot('notes/example', { sourceId: 'default' }))!;
+ await new MinionQueue(engine).add('facts-absorb', { slug: 'notes/example', sourceId: 'elsewhere', page_id: page.id + 1000 }, { queue: 'default' });
+ expect((await rewrite(retitled('Renamed beside a foreign job'))).status).toEqual({ skipped: 'body_unchanged' });
+}));
+
+test('#6042: a page that was ineligible before the write is offered when it becomes eligible with the same body', () => fixture(async () => {
+ await publish();
+ await finishExtractions();
+ const asConcept = content.replace('type: note', 'type: concept');
+ expect((await rewrite(asConcept)).status).toEqual({ skipped: 'kind:concept' });
+ expect(await rewrite(content)).toEqual({ status: { queued: true }, effectQueued: true });
+}));
+
+test('#6042: rewriting a soft-deleted page with its old body queues extraction again', () => fixture(async () => {
+ await publish();
+ await finishExtractions();
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 }]);
+ expect(await rewrite(content)).toEqual({ status: { queued: true }, effectQueued: true });
}));
-test('a maintenance write that keeps the body of a never-extracted eligible page queues nothing (#6042)', () => fixture(async () => {
+test('#6042 accepted tradeoff: a never-extracted eligible page is not extracted by a body-preserving rewrite', () => 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 rewrite(retitled('Renamed after enabling'))).toEqual({ status: { skipped: 'body_unchanged' }, effectQueued: false });
expect(await jobs()).toHaveLength(0);
}));
diff --git a/test/repair-command.test.ts b/test/repair-command.test.ts
index cb8bb49609..2b3376a6dc 100644
--- a/test/repair-command.test.ts
+++ b/test/repair-command.test.ts
@@ -14,8 +14,6 @@ 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';
@@ -74,8 +72,8 @@ async function brain(run: (engine: BrainEngine, sources: string[]) => Promise<vo
}
}
-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() } });
+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() } });
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));
@@ -102,21 +100,27 @@ describe('gbrain repair timeline', () => {
});
}, 120_000);
- test('materializing rows into an eligible page queues no facts extraction (#6042)', async () => {
+ test('#6042: materializing timeline rows into an already-extracted page queues no facts extraction', 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.
+ const body = 'A synthetic field report with enough substantive text that the facts backstop treats it as eligible for extraction.';
+ await submitPageMutation(ctxFor(engine, source), { operation: 'put_page', params: { slug: 'notes/report', content: page(body), request_id: randomUUID() } });
+ await engine.transaction(tx => withCoordinatedWrite(tx, [source], () => tx.executeRaw(
+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-08-02','legacy','A dated event','' FROM pages WHERE source_id=$1 AND slug='notes/report'`,
+ [source]), TEST_WRITE_ATTRIBUTION));
+ // Stand-in for the page's own extraction having run: its outbox entry is settled.
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([]);
+ await engine.executeRaw(`UPDATE persistence_effects SET state='committed' WHERE kind='facts-backstop' AND source_id=$1`, [source]);
+ const receipts = async () => engine.executeRaw<{ id: string; facts: unknown }>(
+ `SELECT id, outcome->'facts_backstop' AS facts FROM persistence_requests
+ WHERE source_id=$1 AND slug='notes/report' AND operation='put_page' AND state='committed' ORDER BY created_at`, [source]);
+ expect((await receipts()).map(r => r.facts)).toEqual([{ queued: true }]);
+ const scope = await resolveRepairScope(engine);
+ const repaired = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });
+ expect(repaired).toMatchObject({ applied: 1, complete: true });
+ expect(await markedPages(engine, source)).toEqual(['notes/report']);
+ const [, repairWrite] = await receipts();
+ expect(repairWrite.facts).toEqual({ skipped: 'body_unchanged' });
+ expect(await engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND kind='facts-backstop'`, [repairWrite.id])).toEqual([]);
});
}, 120_000);