Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep the projection's statements unchanged and list the new repair everywhere the registry is enumerated

garrytanb0b56eed5585
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 7d157cae0b..6145d4af15 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -1,5 +1,6 @@
# Canonical writer census for issue #5105. Counts include lexical references in comments.
# path write-reference ceiling enforcement boundary review rationale
+src/core/generations/fence-evidence.ts 1 projection #8819: moveKeptRows renumbers kept database-only fact rows whose row number an incoming fence row claims, only inside the fence projection's publication transaction (canonical-projections.ts) or the extract_facts reconcile's page write; it changes row_num only, never claim text or lifecycle.
src/core/persistence/activation.ts 0 coordinator Trusted private administration requires explicit quiescence and durable refusal records before enabling managed canonical writer enforcement.
src/core/persistence/canonical-projections.ts 10 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits; a take whose claim changed in place loses its stored resolution there, and a fence row without resolution cells keeps it.
src/core/persistence/derived-retirement-hold.ts 2 contract retireDerivedPages versions, soft-deletes and stamps retired_by/retired_at on derived pages (unmanaged extract_atoms retirement) inside maintenanceTransaction behind the canonical table trigger; it never revives or rewrites content, and the purge hold it defines only keeps rows longer.
@@ -30,6 +31,7 @@ src/commands/reconcile-links.ts 2 engine_guard Canonical table SQL trigger requi
src/commands/reindex-aliases.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/persistence/twin-merge.ts 10 coordinator The #6948 twin merge (links in every role, link transitions, timeline, raw data, files, user tags, aliases and facts move onto the canonical page; the twin is marked origin_twin and soft-deleted) runs only inside the managed_maintenance_resolve_origin_twin preparer's coordinated transaction on managed brains, or one maintenanceTransaction on unmanaged brains, after the group verdict is rechecked under both page locks; it writes no file, so there is no filesystem ordering to keep.
src/core/repair/origin-twins.ts 1 coordinator gbrain repair origin-twins and the post-sync heal resolve each verified twin as a receipted managed_maintenance_resolve_origin_twin request (submitDatabaseMaintenanceIntent, owner host only) on managed brains and in one maintenanceTransaction on unmanaged brains; the verdict is recomputed inside the write and any drift holds the file instead of merging.
+src/core/repair/unwithdrawn-facts.ts 1 coordinator `gbrain repair unwithdrawn-facts` (#8819) puts the ledger before-state back on preview-approved facts a fact_fence generation retired though no fence held them. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_unwithdrawn_facts publication; unmanaged and repo-less brains run it in one maintenanceTransaction under the page lock after the revision recheck.
src/core/search-vector-backfill.ts 2 projection backfillPageVectors (reindex-search-vector, the fts_cjk_boundary migration) rewrites only pages.search_vector, through the seal's pageSearchVectorSql over the sanitized timeline and guarded by the knowledge revision it read (its read is an UPDATE-to-self of id); canonical fields are untouched and the managed writer guard passes search_vector-only updates.
src/commands/sources-set-path.ts 1 coordinator Managed rebind uses native exclusion, exact manifest verification and a retained source-incarnation receipt; unmanaged pointer repair remains explicit.
src/commands/sources.ts 10 coordinator Managed add/archive/restore/remove/purge/reclone route through source lifecycle; remaining legacy canonical SQL stays fenced.
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 8efcd2df76..e496787204 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -12,7 +12,7 @@ import { eachStoredTimelineRow, extractTimelineFromContent, hasExtractorDetail,
type ExtractedTimelineEntry } from '../timeline-extract.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { sanitizeForJsonb } from '../batch-rows.ts';
-import { bodyUnread } from '../page-body/page-shape.ts';
+import { bodyUnread, isSegmentedPage } from '../page-body/page-shape.ts';
import { bodyBlocks, detachedValue, type BodyBlock } from '../page-body/segment-blocks.ts';
import { TakesFenceScan, takesFromRuns } from '../page-body/segment-takes.ts';
import { openFenceRuns } from '../page-body/segment-facts.ts';
@@ -29,7 +29,7 @@ import { propagateFactLowering } from '../trust/propagation.ts';
import { loadWriteGateConfig } from '../trust/gate-outcomes.ts';
import { fenceOwnerKey, readFenceBlocks, TAKE_FENCE_KIND } from '../generations/fence.ts';
import { projectFactFenceGeneration } from '../generations/adapters/fact-rows.ts';
-import { moveKeptRows, pageFenceRowKeys } from '../generations/fence-evidence.ts';
+import { fenceRowKeys, moveKeptRows, pageFenceRowKeys } from '../generations/fence-evidence.ts';
import { projectTakeFenceGeneration } from '../generations/adapters/take-rows.ts';
import { linksFenceProjectionRows, projectLinksFence } from '../links-fence-projection.ts';
@@ -677,9 +677,12 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
const storedRows = prior ? await storedTimeline(engine, prior.page.id) : [];
const prior_ = prior ? await priorView(engine, prior.page, slug, storedRows) : null;
// #8819: the fence rows of the body this write replaces, read at the observed revision, for the fact generation's evidence.
- const priorFenceKeys = prior && projectFences && (await engine.executeRaw(`SELECT 1 FROM facts WHERE source_id=$1 AND source_markdown_slug=$2
- AND row_num IS NOT NULL AND COALESCE(source,'') NOT LIKE 'cli:extract-conversation-facts%' LIMIT 1`, [sourceId, slug])).length
- ? await pageFenceRowKeys(engine, prior.page, slug, sourceId) : null;
+ // An inline body parses without a statement; a segmented one is read from its segments only when the page has positioned facts.
+ const priorFenceKeys = !prior || !projectFences ? null
+ : !isSegmentedPage(prior.page) ? fenceRowKeys(prior.page, slug, sourceId)
+ : (await engine.executeRaw(`SELECT 1 FROM facts WHERE source_id=$1 AND source_markdown_slug=$2
+ AND row_num IS NOT NULL AND COALESCE(source,'') NOT LIKE 'cli:extract-conversation-facts%' LIMIT 1`, [sourceId, slug])).length
+ ? await pageFenceRowKeys(engine, prior.page, slug, sourceId) : null;
const { timeline, exactIncoming, pinned } = classifyTimeline(storedRows, page, prior_?.rows ?? null, slug, writer, policy);
const deletionRows = pinned.filter(row => row.action === 'delete')
.map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' }));
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index 0d06922ac2..438cdeb2d1 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -48,15 +48,15 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
/** #8819: rows the fence never held, which this write keeps as they are. */ kept?: readonly number[] },
expire: () => Promise<unknown>): Promise<FenceGuard<T>> {
const { sourceId, slug, incoming } = input;
- const guarded = await tx.executeRaw<{ id: number; row_num: number; fact: string; visibility: string; trust_tier: string }>(
+ const guarded = (await tx.executeRaw<{ id: number; row_num: number; fact: string; visibility: string; trust_tier: string }>(
`SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f
WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL
AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%'
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text)
WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility)
- AND ${trustRankSql('f.trust_tier')} > ${WRITER_RANK} AND NOT (f.id = ANY($4::bigint[]))
- ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming, [...(input.kept ?? [])]]);
+ AND ${trustRankSql('f.trust_tier')} > ${WRITER_RANK}
+ ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming])).filter(row => !input.kept?.includes(Number(row.id)));
if (guarded.length) await tx.executeRaw('UPDATE facts SET row_num = NULL WHERE id = ANY($1::bigint[])', [guarded.map(g => Number(g.id))]);
await expire();
// A fence with no rows and nothing guarded has nothing to place or gate (#6007: no reads on a fence-free publish).
diff --git a/test/extract-facts-unfenced-rows.test.ts b/test/extract-facts-unfenced-rows.test.ts
index a0ab5fd87c..8ef1fd4cee 100644
--- a/test/extract-facts-unfenced-rows.test.ts
+++ b/test/extract-facts-unfenced-rows.test.ts
@@ -284,6 +284,8 @@ for (const backend of testBackends()) {
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence, row_num, source_markdown_slug)
VALUES ('default', $1, 'Bob example used to advise Widget co', 'fact', 'world', 'high', '2024-01-01', 'linkedin', 1.0, 9, $1) RETURNING id`, [OTHER]);
staleId = Number(stale.id);
+ await managed.executeRaw(`INSERT INTO page_versions (page_id, compiled_truth, frontmatter) VALUES ($1, $2, '{}'::jsonb)`,
+ [page.id, `# Bob Example\n\n${FENCE_ROW_1.replace('| 1 | Alice example joined Acme example |', '| 9 | Bob example used to advise Widget co |')}`]);
} });
}, 180_000);
diff --git a/test/fence-first-generation-8819.test.ts b/test/fence-first-generation-8819.test.ts
index b56f66571b..86a052a523 100644
--- a/test/fence-first-generation-8819.test.ts
+++ b/test/fence-first-generation-8819.test.ts
@@ -108,6 +108,21 @@ describe('#8819 first managed facts-fence generation', () => {
});
}, 120_000);
+ /*
+ * Coverage pass 2 (/ship 8830 Step 7), generated by Capy.
+ * Value: protects=a kept row more trusted than the writer keeps its moved row_num (guardFenceRows skips kept ids); fails_when=the NOT (f.id = ANY(kept)) guard is dropped; why_new=the kept-row test above uses an untrusted-tier row; seam=none; no_claim=trust proposals for the guarded path
+ */
+ test(`[${backend}] a kept row more trusted than the writer moves past a claiming fence row and keeps its number`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await seedPage(s, FACTS_FENCE(FOUNDED), [[1, 'Alice founded acme-example', 'chat']]);
+ await s.engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug, trust_tier)
+ VALUES ($1, $2, 'Alice plays chess', 'fact', 'private', 'mcp:put_page', 2, $2, 'user_confirmed')`, [s.sourceId, SLUG]);
+ }, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', FACTS_FENCE([FOUNDED, ROW(2, 'Alice speaks Portuguese')].join('\n'))));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice plays chess', 3, true], ['Alice speaks Portuguese', 2, true]]);
+ });
+ }, 120_000);
+
test(`[${backend}] the extract_facts reconcile keeps rows the fence never held and still retires a withdrawn one`, async () => {
await managedSource(databaseUrl, async s => {
await s.put(SLUG, PERSON('Alice Example', FACTS_FENCE([FOUNDED, CHESS, ROW(5, 'Alice ran a marathon')].join('\n'))));
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index 31fd763d85..5ee589718c 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -193,7 +193,7 @@ for (const backend of testBackends()) {
const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;
const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
- const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'extractor-facts': 'gbrain repair extractor-facts',
+ const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'extractor-facts': 'gbrain repair extractor-facts', 'unwithdrawn-facts': 'gbrain repair unwithdrawn-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'agent-session-facts': 'gbrain repair agent-session-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'duplicate-facts': 'gbrain repair duplicate-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'timeline-order': 'gbrain repair timeline-order', 'contact-rows': 'gbrain repair contact-rows', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 5bca3a8cbb..22e15dabbd 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind'];
// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.
const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;
let engine: PGLiteEngine;
@@ -111,7 +111,7 @@ describe('surfaces that list instead of run', () => {
expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),
docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));
}
- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');
+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair extractor-facts; gbrain repair unwithdrawn-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');
});
test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {
diff --git a/test/repair-unwithdrawn-facts-8819.test.ts b/test/repair-unwithdrawn-facts-8819.test.ts
index defcd4efbe..65702bf36b 100644
--- a/test/repair-unwithdrawn-facts-8819.test.ts
+++ b/test/repair-unwithdrawn-facts-8819.test.ts
@@ -138,3 +138,99 @@ describe('gbrain repair unwithdrawn-facts (#8819)', () => {
}, 120_000);
}
});
+
+/*
+ * Coverage pass (/ship 8830 Step 7), generated by Capy.
+ * Value: protects=classify never restores superseded, withdrawn, changed_since_retirement, active_duplicate or duplicate_candidate rows; fails_when=a classify guard is dropped or reordered; why_new=existing tests only reach fence_held and ambiguous; seam=none; no_claim=page_missing (needs a second page's generation; not seeded here)
+ * Value: protects=--apply without --expect is invalid_params, an include_ambiguous mismatch is preview_changed, a taken row_num moves to max+1; fails_when=the expect guard, mismatch check or row_num CASE regresses; why_new=no test applies ambiguous rows or a taken row_num; seam=none; no_claim=managed-brain path of these branches (unmanaged PGLite/Postgres only)
+ */
+describe('gbrain repair unwithdrawn-facts (#8819) coverage pass', () => {
+ async function unmanagedPage(databaseUrl: string | undefined, segmented = false) {
+ const handle = await isolatedSharedSkillsEngine(databaseUrl);
+ await handle.engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await handle.engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: FACTS_FENCE(FOUNDED) }, { sourceId: 'default' });
+ if (segmented) await handle.engine.executeRaw(`INSERT INTO page_versions (page_id, compiled_truth, timeline, body_storage, body_generation)
+ SELECT id, NULL, NULL, 'segmented', 1 FROM pages WHERE source_id='default' AND slug=$1`, [SLUG]);
+ await factRow(handle.engine, 'default', 1, 'Alice founded acme-example', 'chat');
+ return handle;
+ }
+
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] exclusions: superseded, withdrawn, changed, active duplicate and duplicate candidate are listed, never restored`, async () => {
+ const { engine, close } = await unmanagedPage(databaseUrl);
+ try {
+ const s = 'default';
+ const ids = { chess: await factRow(engine, s, 2, 'Alice plays chess'), sailsA: await factRow(engine, s, 3, 'Alice sails'), sailsB: await factRow(engine, s, 4, 'Alice sails'),
+ superseded: await factRow(engine, s, 5, 'Alice owns a boat'), withdrawn: await factRow(engine, s, 6, 'Alice likes jazz'),
+ changed: await factRow(engine, s, 7, 'Alice speaks French'), activeDup: await factRow(engine, s, 8, 'Alice runs') };
+ await prefixRetire(engine, s, Object.values(ids));
+ await factRow(engine, s, 9, 'Alice runs');
+ await engine.executeRaw('UPDATE facts SET superseded_by=$2 WHERE id=$1', [ids.superseded, ids.chess]);
+ await engine.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, fact_hash) SELECT source_id, visibility, gbrain_fact_fingerprint(fact) FROM facts WHERE id=$1", [ids.withdrawn]);
+ await engine.executeRaw("UPDATE facts SET expired_at = expired_at + interval '1 second' WHERE id=$1", [ids.changed]);
+ const preview = await repair(engine, s);
+ expect(preview.listing!.map(row => [row.item, row.class])).toEqual([
+ [`${s}:${SLUG}#${ids.chess}`, 'evidenced'], [`${s}:${SLUG}#${ids.sailsA}`, 'evidenced'], [`${s}:${SLUG}#${ids.sailsB}`, 'excluded:duplicate_candidate'],
+ [`${s}:${SLUG}#${ids.superseded}`, 'excluded:superseded'], [`${s}:${SLUG}#${ids.withdrawn}`, 'excluded:withdrawn'],
+ [`${s}:${SLUG}#${ids.changed}`, 'excluded:changed_since_retirement'], [`${s}:${SLUG}#${ids.activeDup}`, 'excluded:active_duplicate']]);
+ expect((await repair(engine, s, { expect: hashOf(preview) })).applied).toBe(1);
+ const active = (await state(engine, Object.values(ids))).filter(([, , on]) => on).map(([id]) => id);
+ expect(active).toEqual([ids.chess, ids.sailsA]);
+ } finally { await close(); }
+ }, 120_000);
+ }
+
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] --apply needs --expect; a taken row number moves the restored row to max+1`, async () => {
+ const { engine, close } = await unmanagedPage(databaseUrl);
+ try {
+ const chess = await factRow(engine, 'default', 2, 'Alice plays chess');
+ await prefixRetire(engine, 'default', [chess]);
+ await factRow(engine, 'default', 2, 'Alice paints');
+ const scope = await resolveRepairScope(engine, 'default');
+ await expect((await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('unwithdrawn-facts', scope, { explicit: true, sourceFlag: 'default' }))
+ .rejects.toMatchObject({ code: 'invalid_params' });
+ const preview = await repair(engine, 'default');
+ expect((await repair(engine, 'default', { expect: hashOf(preview) })).applied).toBe(1);
+ expect(await state(engine, [chess])).toEqual([[chess, 3, true]]);
+ const [{ n }] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND expired_at IS NULL AND row_num=2", [SLUG]);
+ expect(Number(n)).toBe(1);
+ } finally { await close(); }
+ }, 120_000);
+ }
+
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] --include-ambiguous restores ambiguous rows only under the matching flag`, async () => {
+ const { engine, close } = await unmanagedPage(databaseUrl, true);
+ try {
+ const chess = await factRow(engine, 'default', 2, 'Alice plays chess');
+ await prefixRetire(engine, 'default', [chess]);
+ const preview = await repair(engine, 'default', { includeAmbiguous: true });
+ expect(preview.listing!.map(row => row.class)).toEqual(['ambiguous']);
+ await expect(repair(engine, 'default', { expect: hashOf(preview) })).rejects.toMatchObject({ code: 'preview_changed' });
+ expect(await state(engine, [chess])).toEqual([[chess, null, false]]);
+ expect((await repair(engine, 'default', { expect: hashOf(preview), includeAmbiguous: true })).applied).toBe(1);
+ expect(await state(engine, [chess])).toEqual([[chess, 2, true]]);
+ } finally { await close(); }
+ }, 120_000);
+ }
+ /*
+ * Coverage pass 2 (/ship 8830 Step 7), generated by Capy.
+ * Value: protects=a retirement on a deleted page is excluded:page_missing and a page with a version-history gap is ambiguous; fails_when=the page_missing or history_gap branch of classify is dropped or reordered; why_new=pass 1 left both unseeded; seam=none; no_claim=a page row absent entirely (soft delete stands in)
+ */
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] a deleted page excludes its retirements; a version-history gap makes them ambiguous`, async () => {
+ for (const [column, klass] of [['deleted_at', 'excluded:page_missing'], ['version_history_gap_at', 'ambiguous']] as const) {
+ const { engine, close } = await unmanagedPage(databaseUrl);
+ try {
+ const chess = await factRow(engine, 'default', 2, 'Alice plays chess');
+ await prefixRetire(engine, 'default', [chess]);
+ await engine.executeRaw(`UPDATE pages SET ${column}=now() WHERE source_id='default' AND slug=$1`, [SLUG]);
+ const preview = await repair(engine, 'default');
+ expect(preview.listing!.map(row => row.class)).toEqual([klass]);
+ expect(await state(engine, [chess])).toEqual([[chess, null, false]]);
+ } finally { await close(); }
+ }
+ }, 120_000);
+ }
+});