Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: segmented and pruned-history evidence, doctor goldens, bench seed (review round 2)
garrytanf551c284f872
diff --git a/docs/guides/git-canonical.md b/docs/guides/git-canonical.mdindex acf9dc9482..ae35956815 100644--- a/docs/guides/git-canonical.md+++ b/docs/guides/git-canonical.md@@ -108,7 +108,7 @@ recorded):| `adopt_db_moved` | An older version of the page equals the committed file, and no newer state was shared: only the database moved. | adopt || `git_wins_file_moved` | The page equals an older committed blob of its path, and no newer state was shared: only the file moved (a plain `git commit`, for example). | git wins (`file_moved`) || `both_moved` | Both sides moved since the last state they shared. A revert counts as a move: a page reverted to an older state while Git edited the file is `both_moved`, not `git_wins_file_moved`. | discard until decided |-| `no_evidence` | Nothing shared within the depth (no archived version, a path with one blob, a segmented page whose export matches no blob), or the other side's history reached the depth (basis `history_truncated`). | discard until decided |+| `no_evidence` | Nothing shared within the depth (no archived version, a path with one blob, a segmented page whose export matches no blob or that has a version archived after the matching blob), or the other side's history reached the depth or lost versions to pruning (basis `history_truncated`). | discard until decided |A later `updated_at` on the database row changes nothing here. The evidencekind of each page is part of the preview hash, and `gbrain sources git-gapdiff --git a/scripts/bench/sync-pass-memory.ts b/scripts/bench/sync-pass-memory.tsindex 867255c3b5..d1c1981d6a 100644--- a/scripts/bench/sync-pass-memory.ts+++ b/scripts/bench/sync-pass-memory.ts@@ -12,7 +12,7 @@** seed builds a managed Postgres brain whose default source holds --pages committed files written over --commits commits* (with renames and rewrites, then git gc), first-syncs it, makes --ahead of its pages database_ahead with no import- * record (the row changes only type, frontmatter.legacy_type and frontmatter.subtype), adds --dbonly database-only pages,+ * record (each archives its preimage, then the row changes only type, frontmatter.legacy_type and frontmatter.subtype), adds --dbonly database-only pages,* and keeps the result as a template database. run clones the template, resets the checkout to the seeded commit and runs* the conversion apply (convert) or a plain full sync (sync), sampling RSS and heap once a second.*/@@ -133,8 +133,13 @@ async function seed(): Promise<void> {const first = await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });console.error('first sync ' + first.status + ' in ' + Math.round((performance.now() - started) / 1000) + 's');await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ const ahead = "SELECT id FROM pages WHERE source_id='default' ORDER BY slug LIMIT $1";+ // Every real writer archives the preimage first, so the conversion's content evidence reads these pages as database-moved.+ await tx.executeRaw("INSERT INTO page_versions (page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path) "+ + "SELECT p.id,p.compiled_truth,p.frontmatter,p.knowledge_revision,p.timeline,p.title,p.type,(SELECT COALESCE(jsonb_agg(t.tag ORDER BY t.tag),'[]'::jsonb) FROM tags t WHERE t.page_id=p.id),false,p.source_path "+ + "FROM pages p WHERE p.id IN (" + ahead + ") AND COALESCE(p.body_storage,'inline')='inline'", [AHEAD]);const ids = await tx.executeRaw<{ id: string }>("UPDATE pages SET type='concept', frontmatter=frontmatter || jsonb_build_object('type','concept','legacy_type',type,'subtype','imported'), "- + "knowledge_revision=gen_random_uuid(), revision_write_request_id=NULL WHERE source_id='default' AND id IN (SELECT id FROM pages WHERE source_id='default' ORDER BY slug LIMIT $1) RETURNING id::text", [AHEAD]);+ + "knowledge_revision=gen_random_uuid(), revision_write_request_id=NULL WHERE source_id='default' AND id IN (" + ahead + ") RETURNING id::text", [AHEAD]);await tx.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND split_part(fingerprint, ':', 3) = ANY($1::text[])", [ids.map(row => row.id)]);// Pages an older gbrain imported: equal to their files, with no import record.if (LEGACY) await tx.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND split_part(fingerprint, ':', 3) IN (SELECT id::text FROM pages WHERE source_id='default' ORDER BY slug DESC LIMIT $1)", [LEGACY]);diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.tsindex 4a323ff9cb..9a92dcb34a 100644--- a/src/core/persistence/git-conversion.ts+++ b/src/core/persistence/git-conversion.ts@@ -225,7 +225,7 @@ export async function assertOutsideSourceRoots(engine: BrainEngine, file: stringconst inside = relative(fence, path);if (inside !== '' && (inside.startsWith('..') || inside.startsWith(sep) || /^[A-Za-z]:/.test(inside))) continue;throw opError('conversion_file_in_source_root', `${flag} ${file} is inside source ${root.id}'s checkout (${fence}), so it was refused: a review or decisions file names pages and must never be synced or committed.`,- `Pass a path outside every source's checkout, e.g. under ~/.gbrain.`, { docs: DOCS });+ `Pass a path outside ${fence} and every other source checkout, e.g. under ~/.gbrain when your home directory is not inside it.`, { docs: DOCS });}}return real;@@ -831,7 +831,8 @@ async function runConversion(engine: BrainEngine, plan: GitConversionPlan, expeclet holdsCleared = 0;for (const hold of plan.holds) {if (!await engine.transaction(tx => clearGitHold(tx, { sourceId, incarnation: plan.incarnation, path: hold.path, observedAt: hold.observed_at }))) {- throw changedSincePlan(sourceId, new Set([hold.path]), 'mixed');+ throw opError('git_conversion_incomplete', `The hold on ${hold.path} of source ${sourceId} changed or was cleared by another run after the conversion was planned, so the apply stopped before any strict pass, with the source still mixed.`,+ `Preview again with gbrain sources canonical ${sourceId} --to git --dry-run and apply the new hash.`, { docs: DOCS, reason: 'changed_since_preview', detail: 'changed_since_preview', fix: conversionIncompleteFix(sourceId) });}holdsCleared++;recovery.accepted.holds_cleared = holdsCleared;diff --git a/src/core/persistence/git-gap.ts b/src/core/persistence/git-gap.tsindex 9133b329e7..4fa2049f14 100644--- a/src/core/persistence/git-gap.ts+++ b/src/core/persistence/git-gap.ts@@ -387,7 +387,7 @@ export function decideDirection(row: string, head: string | null, versions: Read}type VersionRow = { id: number; page_id: string; compiled_truth: string | null; frontmatter: unknown; timeline: string | null; title: string | null; type: string | null; tags: unknown;- segmented: boolean; is_deleted: boolean | null };+ segmented: boolean; is_deleted: boolean | null; snapshot_at: number | string };const json = <T>(value: unknown, fallback: T): T => value == null ? fallback : typeof value === 'string' ? JSON.parse(value) as T : value as T;/**@@ -428,12 +428,13 @@ export async function readDirectionEvidence(engine: BrainEngine, input: { sourceconst batch = subjects.slice(start, start + EVIDENCE_BATCH);const read = await engine.transaction(async tx => {await tx.executeRaw('SET TRANSACTION READ ONLY');- const live = new Map((await tx.executeRaw<{ id: string; revision: string | null }>(`SELECT id::text, knowledge_revision::text AS revision FROM pages- WHERE id = ANY(string_to_array($1::text, ',')::bigint[]) AND deleted_at IS NULL`, [batch.map(subject => subject.id).join(',')])).map(row => [row.id, row.revision]));+ const rows = await tx.executeRaw<{ id: string; revision: string | null; gap: boolean }>(`SELECT id::text, knowledge_revision::text AS revision, version_history_gap_at IS NOT NULL AS gap+ FROM pages WHERE id = ANY(string_to_array($1::text, ',')::bigint[]) AND deleted_at IS NULL`, [batch.map(subject => subject.id).join(',')]);+ const live = new Map(rows.map(row => [row.id, row.revision])), gaps = new Set(rows.filter(row => row.gap).map(row => row.id));const current = batch.filter(subject => live.has(subject.id) && live.get(subject.id) === subject.revision);const snapshots = await readExportPages(tx, current.map(subject => ({ id: subject.id, source_id: sourceId, slug: subject.slug })), withdrawals);const versions = current.length ? await tx.executeRaw<VersionRow>(`SELECT id, page_id::text AS page_id, compiled_truth, frontmatter, timeline, title, type, tags,- COALESCE(body_storage,'inline')='segmented' AS segmented, is_deleted FROM (SELECT v.*, row_number() OVER (PARTITION BY v.page_id ORDER BY v.id DESC) AS rank FROM page_versions v+ COALESCE(body_storage,'inline')='segmented' AS segmented, is_deleted, EXTRACT(EPOCH FROM snapshot_at)::float8 AS snapshot_at FROM (SELECT v.*, row_number() OVER (PARTITION BY v.page_id ORDER BY v.id DESC) AS rank FROM page_versions vWHERE v.page_id = ANY(string_to_array($1::text, ',')::int[])) ranked WHERE rank <= $2 ORDER BY page_id, id DESC`, [current.map(subject => subject.id).join(','), EVIDENCE_DEPTH]) : [];const segmentedOids = new Map<string, Set<string>>();for (const [i, subject] of current.entries()) {@@ -441,7 +442,7 @@ export async function readDirectionEvidence(engine: BrainEngine, input: { sourceconst sizes = await readBlobSizes(root, older(subject).list.map(entry => entry.oid));segmentedOids.set(subject.id, sizes ? await segmentedExportBlobIds(tx, snapshots[i]!, withdrawals, new Set(sizes.values()), format) : new Set());}- return { current, snapshots, versions, segmentedOids };+ return { current, snapshots, versions, segmentedOids, gaps };});for (const subject of batch) if (!read.current.includes(subject)) out.set(subject.id, none('changed_during_read', older(subject).committed_at));const byPage = new Map<string, VersionRow[]>();@@ -472,8 +473,10 @@ export async function readDirectionEvidence(engine: BrainEngine, input: { sourceconst { list, committed_at, capped } = older(subject);if (subject.segmented) {const match = list.find(entry => read.segmentedOids.get(subject.id)?.has(entry.oid));- out.set(subject.id, match ? { kind: 'git_wins_file_moved', basis: 'row_matches_older_file', blob: match.oid, version: null, versions: 0, blobs: list.length, committed_at }- : { ...none('segmented', committed_at), blobs: list.length });+ const rows = byPage.get(subject.id) ?? [];+ const movedSince = !!match && (read.gaps.has(subject.id) || rows.some(row => Number(row.snapshot_at) > match.at));+ out.set(subject.id, match && !movedSince ? { kind: 'git_wins_file_moved', basis: 'row_matches_older_file', blob: match.oid, version: null, versions: rows.length, blobs: list.length, committed_at }+ : { ...none('segmented', committed_at), blob: match?.oid ?? null, versions: rows.length, blobs: list.length });continue;}const snapshot = read.snapshots[i]!;@@ -481,7 +484,7 @@ export async function readDirectionEvidence(engine: BrainEngine, input: { sourcedigest: digest(reconcileCanonical({ type: (row.type ?? snapshot.page.type) as Page['type'], title: row.title ?? snapshot.page.title, compiled_truth: row.compiled_truth!,timeline: row.timeline ?? '', frontmatter: json(row.frontmatter, {}) }, json<string[]>(row.tags, []))) }));const decided = decideDirection(digest(reconcileCanonical(snapshot.page, snapshot.tags)), fileDigests.get(`${subject.id}:${subject.blob.oid}`) ?? null, versions,- list.map(entry => ({ oid: entry.oid, digest: fileDigests.get(`${subject.id}:${entry.oid}`) ?? null })), { versions: (byPage.get(subject.id)?.length ?? 0) >= EVIDENCE_DEPTH, blobs: capped });+ list.map(entry => ({ oid: entry.oid, digest: fileDigests.get(`${subject.id}:${entry.oid}`) ?? null })), { versions: read.gaps.has(subject.id) || (byPage.get(subject.id)?.length ?? 0) >= EVIDENCE_DEPTH, blobs: capped });out.set(subject.id, { ...decided, versions: versions.length, blobs: list.length, committed_at });}}diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex a25fa26d9a..5e6b57a1b9 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -246,7 +246,7 @@" [INFO] sync_rows_behind_checkpoint: Not applicable: no managed source has a checkout and a sync checkpoint here (a repo-less brain keeps its pages in the database, which is the record)."," [OK] sync_config_keys: No retired sync config key is stored on this brain."," [OK] person_title_duplicates: No title-prefixed person page pairs with an unprefixed page (0 titled page(s) examined).",- " [OK] db_ahead_of_git: Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 equal. Page detail: gbrain sources git-gap <source-id>.",+ " [OK] db_ahead_of_git: Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 live page(s), 5 equal. Page detail: gbrain sources git-gap <source-id>."," [OK] git_index_lag: No source is strict (git-canonical), so no index trails a commit."," [OK] outside_content_fences: No fact, take or link is indexed from a fence on an imported email, calendar, GitHub or transcript page."," [OK] owner_host_stale: No managed write is waiting on an owner host.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 8acd48ed91..95ea66b8a2 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -3728,6 +3728,7 @@"mirror_source": 0,"private": 0},+ "live_pages": 5,"pages": 5,"source_id": "notes","states": {@@ -3753,7 +3754,7 @@"timeout_ms": "<volatile>"},"elapsed_ms": "<volatile>",- "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 equal. Page detail: gbrain sources git-gap <source-id>.",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 live page(s), 5 equal. Page detail: gbrain sources git-gap <source-id>.","name": "db_ahead_of_git","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 7957ca4aa5..d2361445bf 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -3962,6 +3962,7 @@"mirror_source": 0,"private": 0},+ "live_pages": 19,"pages": 19,"source_id": "notes","states": {@@ -3987,7 +3988,7 @@"timeout_ms": "<volatile>"},"elapsed_ms": "<volatile>",- "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 19 live page(s), 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.","name": "db_ahead_of_git","status": "ok"},@@ -8934,6 +8935,7 @@"mirror_source": 0,"private": 0},+ "live_pages": 19,"pages": 19,"source_id": "notes","states": {@@ -8959,7 +8961,7 @@"timeout_ms": "<volatile>"},"elapsed_ms": "<volatile>",- "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 19 live page(s), 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.","name": "db_ahead_of_git","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex c988b3b518..27ebfb2dd1 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -3965,6 +3965,7 @@"mirror_source": 0,"private": 0},+ "live_pages": 19,"pages": 19,"source_id": "notes","states": {@@ -3990,7 +3991,7 @@"timeout_ms": "<volatile>"},"elapsed_ms": "<volatile>",- "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 19 live page(s), 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.","name": "db_ahead_of_git","status": "ok"},@@ -8938,6 +8939,7 @@"mirror_source": 0,"private": 0},+ "live_pages": 19,"pages": 19,"source_id": "notes","states": {@@ -8963,7 +8965,7 @@"timeout_ms": "<volatile>"},"elapsed_ms": "<volatile>",- "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 19 live page(s), 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.","name": "db_ahead_of_git","status": "ok"},diff --git a/test/git-gap-direction-evidence-d4.test.ts b/test/git-gap-direction-evidence-d4.test.tsindex 253d253b7d..48006791ad 100644--- a/test/git-gap-direction-evidence-d4.test.ts+++ b/test/git-gap-direction-evidence-d4.test.ts@@ -6,7 +6,8 @@ import { dirname, join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { PostgresEngine } from '../src/core/postgres-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';-import { inlineExportMarkdown, readExportPage, readExportWithdrawals } from '../src/core/export-snapshot.ts';+import { exportBodyLedger, inlineExportMarkdown, readExportPage, readExportWithdrawals, segmentedExportHead, segmentedExportMarkdown } from '../src/core/export-snapshot.ts';+import { createSegmentedPage } from './helpers/segmented-page.ts';import { decideDirection } from '../src/core/persistence/git-gap.ts';import { readConversionDecisions, writeConversionFile } from '../src/core/persistence/git-conversion.ts';import { censusGitGap, describeGitGap, type GitGapPage } from '../src/commands/sources-git-gap.ts';@@ -171,6 +172,43 @@ for (const backend of testBackends()) describe(`git-gap direction evidence (d4):expect(await writeConversionFile(engine, join(outside, 'review.json'), '--list-out', {})).toBe(join(outside, 'review.json'));}, 120000);+ test('a segmented page: an older blob equal to its export lets Git win only while no version was archived after that blob', async () => {+ const root = tempDir('git-gap-segmented-');+ git(root, 'init', '-q');+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ const { id } = await createSegmentedPage(engine, { slug: 'seg/page', truth: 'Segmented filler line.\n'.repeat(50) });+ const exported = await engine.transaction(async tx => {+ const withdrawals = await readExportWithdrawals(tx, 'default');+ const snapshot = await readExportPage(tx, { id: String(id), source_id: 'default', slug: 'seg/page' }, withdrawals);+ const chunks: Buffer[] = [];+ for await (const piece of segmentedExportMarkdown(tx, snapshot.page, exportBodyLedger(snapshot.page.slug, withdrawals), segmentedExportHead(snapshot))) chunks.push(Buffer.from(piece));+ return Buffer.concat(chunks);+ });+ mkdirSync(join(root, 'seg'), { recursive: true });+ writeFileSync(join(root, 'seg/page.md'), exported);+ commitAll(root, 'first');+ writeFileSync(join(root, 'seg/page.md'), Buffer.concat([exported, Buffer.from('A line Git added.\n')]));+ commitAll(root, 'git edit');+ const evidence = async () => {+ const pages: GitGapPage[] = [];+ await censusGitGap(engine, 'default', { sample: 0, evidence: true, collect: page => { pages.push(page); } });+ return pages.find(page => page.slug === 'seg/page')?.evidence;+ };+ expect(await evidence()).toMatchObject({ kind: 'git_wins_file_moved', basis: 'row_matches_older_file' });+ // A version archived after that blob means the database left that state and came back (a revert): not a one-sided move.+ await engine.executeRaw("INSERT INTO page_versions (page_id, compiled_truth, frontmatter, snapshot_at) VALUES ($1, 'An archived state.', '{}', now() + interval '1 minute')", [id]);+ expect(await evidence()).toMatchObject({ kind: 'no_evidence', basis: 'segmented' });+ }, 120000);++ test('a pruned version history counts as unread: an inline page with a history gap gets no one-sided Git verdict', async () => {+ await fixture();+ await engine.executeRaw("UPDATE pages SET version_history_gap_at = now() WHERE slug = 'notes/file-moved'");+ const pages: GitGapPage[] = [];+ await censusGitGap(engine, 'default', { sample: 0, evidence: true, collect: page => { pages.push(page); } });+ expect(pages.find(page => page.slug === 'notes/file-moved')).toMatchObject({ evidence: { kind: 'no_evidence', basis: 'history_truncated' } });+ expect(pages.find(page => page.slug === 'notes/db-moved')).toMatchObject({ evidence: { kind: 'adopt_db_moved' } });+ }, 120000);+test('repo-less: a source without a checkout reads no evidence (not_applicable) and counts its live pages', async () => {await body('notes/a', 'Only in the database.');const census = await censusGitGap(engine, 'default', { sample: 0, evidence: true });