Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): held phantoms never use up the pass cap; skip a page whose facts changed after planning; hold ontology provenance phantoms (#6650)

garrytan3600a596f73a
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 8238071424..e32e7532be 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -880,9 +880,15 @@ export async function runExtractFacts(
// #6278: the pass moves rows by their fence position and would strand a
// legacy row (no position) on a deleted phantom. #6650: only the phantoms
// that own legacy rows are held, so one unadoptable row no longer stops
- // the pass for the whole source.
+ // the pass for the whole source. A phantom that is the provenance page of
+ // an ontology observation is held too: the move would rewrite the
+ // observation's subject and expire it.
let phantomResult: PhantomPassResult = emptyPhantomPassResult();
if (opts.brainDir) {
+ const holdSlugs = new Set([...legacySlugs, ...(await engine.executeRaw<{ slug: string }>(
+ `SELECT DISTINCT source_markdown_slug AS slug FROM facts
+ WHERE source_id = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND source_markdown_slug NOT LIKE '%/%'`,
+ [sourceId])).map(row => row.slug)]);
try {
phantomResult = await runPhantomRedirectPass(
engine,
@@ -890,7 +896,7 @@ export async function runExtractFacts(
sourceId,
opts.dryRun ?? false,
opts.signal,
- legacySlugs,
+ holdSlugs,
);
} catch (e) {
// The pass owns its own per-phantom try/catch; reaching this catch
diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.ts
index afe33fa55c..591a03b5f7 100644
--- a/src/core/cycle/phantom-redirect.ts
+++ b/src/core/cycle/phantom-redirect.ts
@@ -85,7 +85,11 @@ export interface PhantomPassResult {
skipped_drift: number;
no_canonical: number;
not_phantom: number;
- /** #6650: phantoms held this pass because they still own legacy (unfenced) fact rows. */
+ /**
+ * #6650: top-level pages held this pass because they own legacy (unfenced)
+ * fact rows: the redirect moves rows by fence position and would strand
+ * them on the deleted phantom. Every other phantom of the source proceeds.
+ */
held_legacy_rows: number;
/** True iff the pass was skipped wholesale because the writer lock was busy. */
lock_busy: boolean;
@@ -686,14 +690,19 @@ export async function runPhantomRedirectPass(
try {
// Find unprefixed phantoms in this source. We over-fetch by 1 so
// `more_pending` reflects whether the cap actually clipped work.
+ // #6650: held phantoms are excluded before the cap, so they never use up
+ // the pass's candidate positions.
+ const held = [...holdSlugs].filter(slug => !slug.includes('/'));
+ result.held_legacy_rows = held.length;
const rows = await engine.executeRaw<{ slug: string }>(
`SELECT slug FROM pages
WHERE source_id = $1
AND deleted_at IS NULL
AND slug NOT LIKE '%/%'
+ AND slug <> ALL($3::text[])
ORDER BY slug ASC
LIMIT $2`,
- [sourceId, limit + 1],
+ [sourceId, limit + 1, held],
);
result.more_pending = rows.length > limit;
@@ -702,10 +711,6 @@ export async function runPhantomRedirectPass(
// #1972: bail between phantoms on abort (each is independently committed).
if (isAborted(signal)) break;
const slug = rows[i].slug;
- // #6650: a phantom that still owns legacy (unfenced) fact rows is held:
- // the redirect moves rows by fence position and would strand them on
- // the deleted phantom. Every other phantom of the source proceeds.
- if (holdSlugs.has(slug)) { result.held_legacy_rows += 1; continue; }
const page = await engine.getPage(slug, { sourceId });
if (!page) continue;
result.scanned += 1;
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index 76a7d523e3..f71b27f79e 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -350,6 +350,22 @@ export async function planFence(engine: BrainEngine, sourceId: string, entitySlu
return { body: rendered, assignments, rejected };
}
+/**
+ * #6650: whether a fact the adoption pins (read just now) no longer renders
+ * as the fence row planned from the earlier read. The pins are the request's
+ * hashes, so publishing such a plan would write the older metadata back over
+ * the newer row; the page is skipped and replanned next run instead.
+ */
+function factsChangedSincePlanning(body: string, assignments: Array<{ id: string; row_num: number }>, pinned: Array<{ id: number; value: Record<string, unknown> }>): boolean {
+ const cells = new Map(parseFactsFence(body).facts.map(f => [f.rowNum, f]));
+ return assignments.some(a => {
+ const cell = cells.get(a.row_num);
+ const now = pinned.find(f => f.id === Number(a.id))?.value as unknown as UnfencedFactRow | undefined;
+ if (!cell || !now || normalizeClaimWhitespace(String(now.fact)) !== normalizeClaimWhitespace(cell.claim)) return true;
+ return renderFactsTable([fenceRowOf(now, cell.rowNum, cell.claim)]) !== renderFactsTable([cell]);
+ });
+}
+
/** Keep the typed records and name the page once in `failed_pages` with the stable token; the rows stay as they are. */
function recordUnadoptable(outcome: UnfencedFactsOutcome, slug: string, records: UnadoptableFactRecord[]): void {
if (records.length === 0) return;
@@ -397,6 +413,10 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi
fact_id: Number(a.id), reason: 'fence_unrenderable' as const, class: 'prior_refusal' as const, request_id: request.prior.request_id }))]);
continue;
}
+ if (factsChangedSincePlanning(fence.body, fence.assignments, request.facts)) {
+ outcome.failed_pages.push(`${entitySlug} (a legacy fact changed after its fence row was planned; nothing was submitted and the next run replans it)`);
+ continue;
+ }
recordUnadoptable(outcome, entitySlug, fence.rejected);
const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
await submitPlannedFactFenceAdoption(engine, authority, entitySlug, request,
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index ff0fd0fcd2..c24efd08c7 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -312,7 +312,7 @@ function deterministicAdoptionRefusal(prior: Pick<WriteRequest, 'error_code' | '
/** What `planFactFenceAdoption` decided: submit (or replay) `requestId`, or skip because this build already refused these inputs. */
export type FactFenceAdoptionPlan =
- | { kind: 'submit'; requestId: string; intent: Record<string, unknown> }
+ | { kind: 'submit'; requestId: string; intent: Record<string, unknown>; facts: FactSnapshot[] }
| { kind: 'suppressed'; prior: WriteRequest };
/**
@@ -332,7 +332,7 @@ export async function planFactFenceAdoption(engine: BrainEngine, authority: Main
for (let attempt = 0; ; attempt++) {
const requestId = maintenanceRequestId({ authority: authority.writer, slug, intent, ...(attempt ? { attempt } : {}) });
const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
- if (!prior || prior.state === 'committed' || !isTerminal(prior)) return { kind: 'submit', requestId, intent };
+ if (!prior || prior.state === 'committed' || !isTerminal(prior)) return { kind: 'submit', requestId, intent, facts: current };
if (prior.state === 'failed' && deterministicAdoptionRefusal(prior)
&& Date.now() - new Date(prior.completed_at ?? prior.updated_at).getTime() < ADOPTION_REFUSAL_HOLD_MS) {
return { kind: 'suppressed', prior };
diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.ts
index e53eae394a..54746edc0e 100644
--- a/test/fact-fence-adoption-exits.test.ts
+++ b/test/fact-fence-adoption-exits.test.ts
@@ -21,7 +21,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { fenceCellReadBackProblem, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../src/core/facts-fence.ts';
-import { planFence, type UnfencedFactRow } from '../src/core/facts/unfenced-facts.ts';
+import { fenceUnfencedFacts, planFence, planUnfencedFacts, type UnfencedFactRow } from '../src/core/facts/unfenced-facts.ts';
import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
import { serializePageToMarkdown } from '../src/core/markdown.ts';
import { FACT_FENCE_PLANNER, maintenancePreflight, submitFactFenceAdoption } from '../src/core/persistence/prepared-maintenance.ts';
@@ -32,6 +32,8 @@ import { LEGACY_FILE_SLUG, seedLegacyManagedContent, type LegacySeed } from './h
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
const SLUG = 'people/alice-example';
const noOccupiedRows = { executeRaw: async () => [] } as unknown as BrainEngine;
@@ -124,6 +126,28 @@ for (const backend of testBackends()) {
expect(await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE slug=$1 AND (intent->>'planner')::int=$2`, [LEGACY_FILE_SLUG, FACT_FENCE_PLANNER])).toHaveLength(2);
}, { databaseUrl, setup: async ({ engine, root }) => { seed = await seedLegacyManagedContent(engine, root); } });
}, 120_000);
+
+ test(`${backend}: a legacy fact that changes after planning is not overwritten by the older plan`, async () => {
+ let seed!: LegacySeed;
+ await managedBrain(async ({ engine }) => {
+ const plan = await planUnfencedFacts(engine, { sourceId: 'default' });
+ const changed = seed.legacyFactIds[0];
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.executeRaw(`UPDATE facts SET kind='belief', confidence=0.25 WHERE id=$1`, [changed]);
+ }, TEST_WRITE_ATTRIBUTION));
+ const outcome = await fenceUnfencedFacts(engine, plan);
+ expect(outcome.failed_pages.some(p => p.startsWith(`${LEGACY_FILE_SLUG} (a legacy fact changed after its fence row was planned`))).toBe(true);
+ const [row] = await engine.executeRaw<{ kind: string; confidence: number; row_num: number | null }>('SELECT kind, confidence, row_num FROM facts WHERE id=$1', [changed]);
+ expect(row).toMatchObject({ kind: 'belief', row_num: null });
+ expect(Number(row.confidence)).toBeCloseTo(0.25);
+ // The next run replans from the current row and adopts it with its current metadata.
+ const again = await fenceUnfencedFacts(engine, await planUnfencedFacts(engine, { sourceId: 'default' }));
+ expect(again.fenced_slugs).toContain(LEGACY_FILE_SLUG);
+ const [adopted] = await engine.executeRaw<{ kind: string; row_num: number | null }>('SELECT kind, row_num FROM facts WHERE id=$1', [changed]);
+ expect(adopted.kind).toBe('belief');
+ expect(adopted.row_num).not.toBeNull();
+ }, { databaseUrl, setup: async ({ engine, root }) => { seed = await seedLegacyManagedContent(engine, root); } });
+ }, 120_000);
}
describe('extract_facts: an unadoptable row holds only its own phantom (#6650)', () => {
@@ -177,6 +201,32 @@ describe('extract_facts: an unadoptable row holds only its own phantom (#6650)',
});
});
+ test('held phantoms do not use up the pass cap: a later phantom still redirects', async () => {
+ await withBrain(async ({ engine, brainDir }) => {
+ await withEnv({ GBRAIN_PHANTOM_REDIRECT_LIMIT: '1' }, async () => {
+ await engine.putPage('aaron', { type: 'person', title: 'aaron', compiled_truth: '# aaron\n', frontmatter: {}, timeline: '' });
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', 'aaron', ' ', 'fact', 'world', 'medium', '2026-03-01', 'mcp:remember', 0.8)`);
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(result.phantomsHeldLegacyRows).toBe(1);
+ expect(result.phantomsRedirected).toBe(1);
+ expect(await alive(engine, 'alice')).toBe(false);
+ expect(await alive(engine, 'aaron')).toBe(true);
+ });
+ });
+ });
+
+ test('a phantom that is the provenance page of an ontology observation is held, so the move never rewrites its subject', async () => {
+ await withBrain(async ({ engine, brainDir }) => {
+ await engine.mergeOntologyFact({ entitySlug: 'people/bob-example', dimension: 'role', value: 'advisor', source: 'alice' });
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(result.phantomsRedirected).toBe(0);
+ expect(await alive(engine, 'alice')).toBe(true);
+ expect(await engine.executeRaw("SELECT entity_slug, source_markdown_slug FROM facts WHERE dimension='role'"))
+ .toEqual([{ entity_slug: 'people/bob-example', source_markdown_slug: 'alice' }]);
+ });
+ });
+
test('a phantom that owns a legacy row is held and keeps its row', async () => {
await withBrain(async ({ engine, brainDir }) => {
await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)