Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): v0.32.2 verify accepts a duplicate active fence row indexed once (#5814, #5830)

garrytanefbea8f37c89
diff --git a/skills/migrations/v0.32.2.md b/skills/migrations/v0.32.2.md
index 5ad76732c5..872df5f93f 100644
--- a/skills/migrations/v0.32.2.md
+++ b/skills/migrations/v0.32.2.md
@@ -28,10 +28,12 @@ restorable database backup as well as source files.
backups and affected sources, run
`gbrain apply-migrations --migration 0.32.2 --yes`.
2. The orchestrator checks the schema, fences eligible facts, then verifies
- fence row counts. Only live legacy rows with an existing source-scoped
- page and canonical file are eligible. Missing targets are reported as
- `skipped_no_page`; no stub is created. Existing fence and database row
- numbers remain reserved. Count verification is not full content parity.
+ that each page's fence and its indexed facts carry the same row numbers
+ (a duplicate active fence row may be indexed once). Only live legacy
+ rows with an existing source-scoped page and canonical file are
+ eligible. Missing targets are reported as `skipped_no_page`; no stub is
+ created. Existing fence and database row numbers remain reserved.
+ Row-number verification is not full content parity.
`--dry-run` previews the migration plan; there is no `--write` flag.
3. Dirty-tree refusal applies only to the source subtrees receiving writes.
If verification fails, inspect the reported drift before retrying. For a
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 7ea3242f0c..075bacb99b 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -120,7 +120,7 @@
"migrations/v0.27.1.md": "719dd4ebcc7ac81413ee79af20f80de5141577e3860e5049a49fc8f6d09ddf89",
"migrations/v0.28.0.md": "21929a392af2e1f454272e80aade6c58c5f6ccd7253d24344d08c6b53bcdf4f9",
"migrations/v0.29.1.md": "7b85373a62a8500ee8c4238ffc9878318b44ee62543adb8b2462049c6c0cd1f8",
- "migrations/v0.32.2.md": "e32e60cba9179fb2429a1cec38ee91abd66937baf4ab393ab008660e59aaf12a",
+ "migrations/v0.32.2.md": "88069b6ede3933aacb0555480bb730f75ca67602a5ae953f9f2a95a2bf6418a2",
"migrations/v0.32.6.md": "e9438a910afe8a1f7861c5222fd7db04a0f8d8b8283778476b07b7c3d539d3f0",
"migrations/v0.33.0.md": "79febbe39b9518837acd1adc86c989a75b196f9fa5c7a217e64dc2eadc23ea01",
"migrations/v0.33.3.0.md": "3747f72d050bf0d269227af2bf5636238d959fa0508f80470bad4874c725d96e",
diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.ts
index 0aaa4246e5..7b4272be66 100644
--- a/src/commands/migrations/v0_32_2.ts
+++ b/src/commands/migrations/v0_32_2.ts
@@ -11,8 +11,10 @@
* A. Schema — assert migration v51 has run.
* B. Fence facts — backfill DB facts → entity-page fences (dry-run
* by default; explicit --write required).
- * C. Verify — re-parse each fence-owned page, count rows, compare
- * against the DB rows for that page; partial on
+ * C. Verify — re-parse each fence-owned page and compare its fence
+ * row numbers with the DB rows for that page; a
+ * duplicate active fence row may be absent from the
+ * index (extract_facts indexes it once). Partial on
* mismatch. Conversation-miner (`cli:`) facts are not
* fence-owned (extract-conversation-facts writes the
* chat log as source of truth) and are excluded.
@@ -43,6 +45,7 @@ import type { BrainEngine } from '../../core/engine.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
import { formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../../core/facts-fence.ts';
+import { duplicateActiveFenceRows } from '../../core/facts/extract-from-fence.ts';
import { resolvePageWriteTarget } from '../../core/write-through.ts';
import { serializePageToMarkdown } from '../../core/markdown.ts';
import { managedPersistenceEnabled } from '../../core/persistence/ownership.ts';
@@ -455,6 +458,14 @@ function fenceFactsResult(outcome: PhaseBOutcome): OrchestratorPhaseResult {
// ── Phase C — Verify ────────────────────────────────────────
+/** Row numbers a drift detail names per side before it summarizes the rest. */
+const DRIFT_ROWS_SHOWN = 5;
+
+function listDriftRows(rows: number[]): string {
+ const shown = rows.slice(0, DRIFT_ROWS_SHOWN).join(', ');
+ return rows.length > DRIFT_ROWS_SHOWN ? `${shown}, +${rows.length - DRIFT_ROWS_SHOWN} more` : shown;
+}
+
async function phaseCVerify(
engine: BrainEngine | null,
opts: OrchestratorOpts,
@@ -464,7 +475,8 @@ async function phaseCVerify(
try {
// Per touched page (= any page with a fenced row in the DB), re-parse
- // the fence from disk and compare row counts to the DB.
+ // the fence (the canonical file, or the database copy on a managed
+ // brain) and compare its row numbers to the DB's.
const sources = await engine.executeRaw<SourceLookup>(
`SELECT id, local_path FROM sources`,
);
@@ -475,8 +487,8 @@ async function phaseCVerify(
// (chat-log shape is the source of truth). Same cli: exclusion as
// extract_facts reconciliation. Counting them here fails every brain
// that ran extract-conversation-facts.
- const groups = await engine.executeRaw<{ source_id: string; source_markdown_slug: string; n: string }>(
- `SELECT source_id, source_markdown_slug, COUNT(*) AS n
+ const groups = await engine.executeRaw<{ source_id: string; source_markdown_slug: string; row_nums: number[] }>(
+ `SELECT source_id, source_markdown_slug, array_agg(row_num ORDER BY row_num) AS row_nums
FROM facts
WHERE row_num IS NOT NULL
AND COALESCE(source, '') NOT LIKE 'cli:%'
@@ -510,10 +522,20 @@ async function phaseCVerify(
body = readFileSync(target.filePath, 'utf-8');
}
const parsed = parseFactsFence(body);
- const fenceCount = parsed.facts.length;
- const dbCount = parseInt(g.n, 10);
- if (fenceCount !== dbCount) {
- mismatches.push(`${g.source_markdown_slug} (fence=${fenceCount}, db=${dbCount})`);
+ const indexed = new Set(g.row_nums.map(Number));
+ const fenced = new Set(parsed.facts.map(f => f.rowNum));
+ // #5814: a duplicate active row may be absent from the index.
+ // extract_facts indexes it once (#1781) while the managed publication
+ // projection indexes every fence row, so both states are in sync.
+ const duplicates = duplicateActiveFenceRows(parsed.facts);
+ const notIndexed = [...fenced].filter(n => !indexed.has(n) && !duplicates.has(n)).sort((a, b) => a - b);
+ const notInFence = [...indexed].filter(n => !fenced.has(n)).sort((a, b) => a - b);
+ if (notIndexed.length > 0 || notInFence.length > 0) {
+ const missing = [
+ notIndexed.length > 0 ? `not indexed: ${listDriftRows(notIndexed)}` : '',
+ notInFence.length > 0 ? `not in fence: ${listDriftRows(notInFence)}` : '',
+ ].filter(Boolean).join('; ');
+ mismatches.push(`${g.source_markdown_slug} (fence=${parsed.facts.length}, db=${indexed.size}; ${missing})`);
}
pagesChecked += 1;
}
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 30bbb5db75..3bf867fde2 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -66,6 +66,7 @@ import { writeReceipt } from '../extract/receipt-writer.ts';
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';
import {
+ duplicateActiveFenceRows,
extractFactsFromFenceText,
type FenceExtractedFact,
} from '../facts/extract-from-fence.ts';
@@ -711,17 +712,10 @@ export async function runExtractFacts(
// trajectory query against the page returns import dates instead of
// claim dates.
const pageEffectiveDate = page.effective_date ? new Date(page.effective_date) : null;
- // #1781: duplicate ACTIVE rows (same claim and source) index once. A
- // struck history row never collapses with an active row that carries the
- // same text, so a claim that reverts to an earlier value stays active.
- const activeKeys = new Set<string>();
- const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate }).filter(f => {
- if (f.expired_at != null) return true;
- const key = `${f.fact}\u0000${f.source}`;
- if (activeKeys.has(key)) return false;
- activeKeys.add(key);
- return true;
- });
+ // #1781: duplicate ACTIVE rows (same claim and source) index once.
+ const duplicates = duplicateActiveFenceRows(parsed.facts);
+ const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate })
+ .filter(f => !duplicates.has(f.row_num));
if (opts.dryRun) return 'next';
diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.ts
index 85fd863118..941f122b01 100644
--- a/src/core/facts/extract-from-fence.ts
+++ b/src/core/facts/extract-from-fence.ts
@@ -71,6 +71,25 @@ export type FenceExtractedFact = NewFact & {
*/
export const FENCE_SOURCE_DEFAULT = 'fence:reconcile';
+/**
+ * #1781: duplicate ACTIVE fence rows (same claim and source) index once.
+ * Returns the row numbers of the later copies, which extract_facts leaves
+ * out of the index. A struck history row never collapses with an active row
+ * that carries the same text, so a claim that reverts to an earlier value
+ * stays active.
+ */
+export function duplicateActiveFenceRows(facts: ParsedFact[]): Set<number> {
+ const seen = new Set<string>();
+ const duplicates = new Set<number>();
+ for (const f of facts) {
+ if (!f.active) continue;
+ const key = `${f.claim}\u0000${f.source ?? FENCE_SOURCE_DEFAULT}`;
+ if (seen.has(key)) duplicates.add(f.rowNum);
+ else seen.add(key);
+ }
+ return duplicates;
+}
+
function parseValidDate(s: string | undefined): Date | undefined {
if (!s) return undefined;
// Be lenient on date shape — accept 'YYYY-MM-DD' or full ISO.
diff --git a/test/migrations-v0_32_2-managed.test.ts b/test/migrations-v0_32_2-managed.test.ts
index bc151453c3..9e263e691d 100644
--- a/test/migrations-v0_32_2-managed.test.ts
+++ b/test/migrations-v0_32_2-managed.test.ts
@@ -4,22 +4,28 @@
* Protects: on a managed brain the backfill publishes each entity page's
* facts fence through the coordinator and adopts the legacy fact rows in
* place (managed_maintenance_adopt_fact_fence), for file-backed and
- * database-only pages alike.
+ * database-only pages alike, and verify reads a page holding a duplicate
+ * active fence row as in sync whether the publication or extract_facts
+ * indexed it last (#5814).
* Fails when: the phase writes fence files into the managed worktree or
* runs a raw `UPDATE facts` (the managed writer guard refuses it and the
* orchestrator chain wedges), when adoption inserts duplicate rows instead
* of keeping the legacy ids and vectors, or when it expires a
- * conversation-extractor row on the same page.
+ * conversation-extractor row on the same page, or when verify counts every
+ * fence row against the index although extract_facts indexes a duplicate once.
* Seams: none; `managedBrain` and the migration's exported `__testing` phases.
*/
import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { __testing } from '../src/commands/migrations/v0_32_2.ts';
import type { OrchestratorOpts } from '../src/commands/migrations/types.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../src/core/facts-fence.ts';
import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { maintenancePreflight, submitFactFenceAdoption } from '../src/core/persistence/prepared-maintenance.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { LEGACY_DB_ONLY_SLUG, LEGACY_FILE_SLUG, seedLegacyManagedContent, type LegacySeed } from './helpers/managed-legacy-fixture.ts';
@@ -164,4 +170,25 @@ for (const backend of testBackends()) {
VALUES ('archived-example', 'people/erin-example', 'Erin example left Acme example', 'fact', 'world', 'medium', now(), 'mcp:put_page', 0.8)`);
} });
}, 120_000);
+
+ test(`${backend}: a duplicate active fence row reads in sync whichever writer indexed the page last (#5814)`, async () => {
+ await managedBrain(async ({ ctx, engine }) => {
+ const slug = 'people/dana-example';
+ const row = (rowNum: number, claim: string) => ({ rowNum, claim, kind: 'fact' as const, confidence: 1, visibility: 'private' as const,
+ notability: 'medium' as const, validFrom: '2026-01-01', source: 'manual', active: true });
+ const body = replaceOrInsertFactsFence('# Dana Example\n', renderFactsTable([row(1, 'Lives in Paris'), row(2, 'Lives in Paris'), row(3, 'Works at Acme example')]));
+ const receipt = await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),
+ content: `---\ntype: person\ntitle: Dana Example\n---\n\n${body}` } }) as { state: string };
+ expect(receipt.state).toBe('committed');
+ const indexed = async () => (await engine.executeRaw<{ row_num: number }>(
+ 'SELECT row_num FROM facts WHERE source_markdown_slug = $1 AND row_num IS NOT NULL ORDER BY row_num', [slug])).map(r => Number(r.row_num));
+
+ // The publication projects every fence row; extract_facts indexes the duplicate once.
+ expect(await indexed()).toEqual([1, 2, 3]);
+ expect(await __testing.phaseCVerify(engine, OPTS)).toMatchObject({ status: 'complete', detail: 'pages_checked=1' });
+ await runExtractFacts(engine, { sourceId: 'default' });
+ expect(await indexed()).toEqual([1, 3]);
+ expect(await __testing.phaseCVerify(engine, OPTS)).toMatchObject({ status: 'complete', detail: 'pages_checked=1' });
+ }, { databaseUrl });
+ }, 120_000);
}
diff --git a/test/migrations-v0_32_2.test.ts b/test/migrations-v0_32_2.test.ts
index 900b977124..b69f5e8c5c 100644
--- a/test/migrations-v0_32_2.test.ts
+++ b/test/migrations-v0_32_2.test.ts
@@ -18,7 +18,8 @@ import { execFileSync } from 'node:child_process';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { v0_32_2, __setTestEngineOverride, __testing } from '../src/commands/migrations/v0_32_2.ts';
-import { parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, type ParsedFact } from '../src/core/facts-fence.ts';
let engine: PGLiteEngine;
let brainDir: string;
@@ -533,6 +534,59 @@ describe('phaseCVerify', () => {
expect(r.status).toBe('complete');
expect(r.detail).toContain('pages_checked=1');
});
+
+ // #5814: extract_facts indexes a duplicate ACTIVE fence row (same claim and
+ // source) once (#1781), so the fence legitimately holds one row more than
+ // the index. Verify must read that page as in sync, and still catch a fence
+ // row or an indexed row the other side lacks.
+ const SLUG = 'people/alice-example';
+ const fenceRow = (rowNum: number, claim: string): ParsedFact => ({
+ rowNum, claim, kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium',
+ validFrom: '2026-01-01', source: 'manual', active: true,
+ });
+ const DUPLICATE_FENCE = [fenceRow(1, 'Lives in Paris'), fenceRow(2, 'Lives in Paris'), fenceRow(3, 'Works at Acme example')];
+
+ async function writeFencedPage(rows: ParsedFact[]): Promise<void> {
+ const body = replaceOrInsertFactsFence('# Alice Example\n', renderFactsTable(rows));
+ mkdirSync(join(brainDir, 'people'), { recursive: true });
+ writeFileSync(join(brainDir, `${SLUG}.md`), `---\ntype: person\ntitle: Alice Example\n---\n\n${body}`);
+ await engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: body, frontmatter: {} });
+ }
+
+ async function indexedRowNums(): Promise<number[]> {
+ const rows = await engine.executeRaw<{ row_num: number }>(
+ 'SELECT row_num FROM facts WHERE source_markdown_slug = $1 AND row_num IS NOT NULL ORDER BY row_num', [SLUG]);
+ return rows.map(r => Number(r.row_num));
+ }
+
+ test('a duplicate active row that extract_facts indexes once is in sync (#5814)', async () => {
+ await writeFencedPage(DUPLICATE_FENCE);
+ await runExtractFacts(engine, { slugs: [SLUG] });
+ expect(await indexedRowNums()).toEqual([1, 3]);
+
+ expect(await __testing.phaseCVerify(engine, OPTS)).toMatchObject({ status: 'complete', detail: 'pages_checked=1' });
+ });
+
+ test.each([
+ ['a non-duplicate fence row is not indexed', [1, 2], 'not indexed: 3'],
+ ['an indexed row number is not in the fence', [1, 3, 4], 'not in fence: 4'],
+ ['each side holds a row number the other lacks', [1, 4], 'not indexed: 3; not in fence: 4'],
+ ['more row numbers are missing than the detail lists', [1, 3, 4, 5, 6, 7, 8, 9, 10], 'not in fence: 4, 5, 6, 7, 8, +2 more'],
+ ])('reports drift on a page with a duplicate active row when %s (#5814)', async (_case, indexed, missing) => {
+ await writeFencedPage(DUPLICATE_FENCE);
+ for (const rowNum of indexed) {
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability,
+ valid_from, source, confidence, row_num, source_markdown_slug)
+ VALUES ('default', $1, $2, 'fact', 'private', 'medium', now(), 'manual', 1.0, $3, $1)`,
+ [SLUG, DUPLICATE_FENCE[rowNum - 1]?.claim ?? `Visited city ${rowNum}`, rowNum],
+ );
+ }
+
+ const r = await __testing.phaseCVerify(engine, OPTS);
+ expect(r.status).toBe('failed');
+ expect(r.detail).toBe(`1 pages drifted: ${SLUG} (fence=3, db=${indexed.length}; ${missing})`);
+ });
});
describe('orchestrator end-to-end', () => {