Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): file wins warns to commit appended files; page-body-readers rows
garrytan774337393f5c
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 54ce8b6f7c..28c0b9d6d8 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -435,6 +435,8 @@ src/core/persistence/facts-maintenance.ts prepareManagedFactsSession field METAsrc/core/persistence/facts-prepare.ts prepareManagedFactsMutation call:serializePageToMarkdown SEGW assertInlineBody firstsrc/core/persistence/facts-prepare.ts prepareManagedFactsMutation field SEGW assertInlineBody on the entity snapshot before the fence writesrc/core/persistence/file-repair.ts canonicalRepairFields field META+src/core/persistence/file-wins-content.ts appendedParts field INLINE compares the parsed canonical file with the reconcile result (ParsedPage strings readReconcileState builds through wholeBodySnapshot: a segmented page up to 24 MiB is read whole, a larger one refuses first); no page row is read+src/core/persistence/file-wins-content.ts fileWinsContent field INLINE compares the parsed canonical file with the reconcile result (ParsedPage strings readReconcileState builds through wholeBodySnapshot: a segmented page up to 24 MiB is read whole, a larger one refuses first); no page row is readsrc/core/persistence/import-prepare.ts prepareManagedImportMutation call:serializePageToMarkdown SEGWsrc/core/persistence/large-page-guard.ts assertLargePageAdmission sql META stored size = body_bytes for a segmented page, octet_length of the columns for an inline pagesrc/core/persistence/links-maintenance.ts extractManagedStaleLinks field NONE not the page body: result.timeline counterdiff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex a3ef4bc78d..c02c054daf 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -102,7 +102,9 @@ interface DriftItem extends RepairItem { page: ApprovedPage; hash: string; last:/** One page's prepared resolution: the ready reconcile preview its apply submits, and where it departs from the preferred side. */export interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftClass; adopt_slug_path: boolean; exceptions: DriftException[]; result: ParsedPage; preview: ReconcileArtifact;/** #6712 wave: the canonical file is gone from the last commit and the apply recreates it from the page. */- file_gone?: true }+ file_gone?: true;+ /** GBRA-133: file wins appends protected keys or timeline rows to the canonical file (`fileWinsContent`). */+ file_appended?: true }/** #6712 wave: a page whose canonical file is gone from the last commit, resolved `--prefer file`: soft-delete exactly that page. */export interface SoftDeletePage { slug: string; prefer: 'file'; exceptions: DriftException[]; soft_delete: { ghost: GhostPage; owner: GhostOwner } }/**@@ -499,13 +501,14 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slif (prepared.conflicts.length || !prepared.ready) throw opError('invalid_params', 'Some paths still need a decision.',`Preview ${slug} with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview --out <file> and resolve it there.`);// GBRA-133: file wins keeps the file's bytes and only appends protected parts; a result that needs a re-render refuses here.- if (prefer === 'file' && !opts.fileGone) fileWinsContent(state.raw.toString('utf8'), state.file, prepared.result, text => readCanonicalFileText(state, slug, text), { sourceId, slug });+ const raw = state.raw.toString('utf8');+ const appends = prefer === 'file' && !opts.fileGone && fileWinsContent(raw, state.file, prepared.result, text => readCanonicalFileText(state, slug, text), { sourceId, slug }) !== raw;const preview: ReconcileArtifact = { format_version: 1, preview_id: randomUUID(), preconditions: state.pins,preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };await assertReconcileSize(engine, preview);return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview,- ...(opts.fileGone ? { file_gone: true as const } : {}) };+ ...(opts.fileGone ? { file_gone: true as const } : {}), ...(appends ? { file_appended: true as const } : {}) };}/**@@ -818,6 +821,7 @@ export const fileDriftRepair: RepairHandler = {: [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });// #6712 wave: a recreated file stays only once committed; without Git durability the next sync imports the committed deletion again.const recreated = pages.flatMap(page => 'preview' in page && page.file_gone ? [page.preview.preconditions.relative_path] : []);+ const appended = pages.flatMap(page => 'preview' in page && page.file_appended ? [page.preview.preconditions.relative_path] : []);// #6712 PR 4b: a removed file is gone only once its deletion is committed; without Git durability the next sync finds the committed file held again.const removed = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);let warnings: string[] = nextCommand ? [`This preview covered ${previewed} of the ${held!.targets.length} selected held pages${opts.cursor ? ' after its cursor' : ''} (one window stops at ${HELD_WINDOW_PAGES} pages or ${HELD_WINDOW_BUDGET_MS / 1000} s); its hash and apply command cover only these. `@@ -825,13 +829,14 @@ export const fileDriftRepair: RepairHandler = {const releases = pages.filter(page => 'release_hold' in page).length;if (releases) warnings.push(`The apply only schedules a re-screen of ${releases} held file(s) whose page and file agree; the next sync (gbrain sync --source ${sourceId}) releases each that still agrees.`);let undoneBySync: { recreated: number; removed: number } | null = null;- if (recreated.length || removed.length) {+ if (recreated.length || removed.length || appended.length) {const binding = await getWorktreeBinding(engine, sourceId);const root = join(binding!.local_path!, binding!.relative_path);if (!(await gitDurabilityPolicy(binding, root).catch(() => ({ durable: false }))).durable) {if (removed.length) warnings.unshift(`The next sync undoes this repair unless the removals are committed: Git durability is off for ${sourceId}, so the apply leaves each removed file's deletion uncommitted (${removed.length} file(s)) and the next sync holds the committed file again. Commit them right after the apply: ${commitPushCommand(root, removed, [`gbrain: repair file drift in ${sourceId}`])}`);+ if (appended.length) warnings.unshift(`Commit the appended files right after the apply: Git durability is off for ${sourceId}, so the apply leaves the protected parts it appends to each file uncommitted (${appended.length} file(s)), and the next sync holds an uncommitted file it cannot import as is. ${commitPushCommand(root, appended, [`gbrain: repair file drift in ${sourceId}`])}`);if (recreated.length) warnings.unshift(`The next sync undoes this repair unless the recreated files are committed: Git durability is off for ${sourceId}, so the apply leaves each recreated file uncommitted (${recreated.length} file(s)) and the next sync imports their committed deletion again. Commit them right after the apply: ${commitPushCommand(root, recreated, [`gbrain: repair file drift in ${sourceId}`])}`);- undoneBySync = { recreated: recreated.length, removed: removed.length };+ if (recreated.length || removed.length) undoneBySync = { recreated: recreated.length, removed: removed.length };}}const provenanceOf = new Map((held?.targets ?? []).flatMap(target => target.provenance && target.hold.slug ? [[target.hold.slug, target.provenance] as const] : []));diff --git a/test/sync-holds-wave-gbra133.test.ts b/test/sync-holds-wave-gbra133.test.tsindex 3dc2537883..df19f15cd3 100644--- a/test/sync-holds-wave-gbra133.test.ts+++ b/test/sync-holds-wave-gbra133.test.ts@@ -76,17 +76,23 @@ async function heldUnknownPage(engine: BrainEngine, root: string): Promise<void>const HAND_WRITTEN = '---\ntitle: Alpha Example\ntype: concept\naliases:\n - alpha-one\n - alpha-two\nstatus: active\n---\n\n'+ 'Intro paragraph.\n\nSection text above a rule\n---\n\nAfter the rule.\n\n## Timeline\n\n- 2026-01-01: First event.\n';+/** Quoted values, an unsorted inline tag list, stacked rules with the last one the timeline separator, the timeline at the end. */+const STACKED_RULES = '---\ntitle: "Beta Example"\ntype: concept\ncreated: 2026-01-01\ntags: [zeta-tag, alpha-tag, mid-tag]\nsource_label: \'quoted value\'\n---\n\n'+ + 'Intro paragraph.\n\n---\n\n---\n\n---\n\n## Timeline\n\n- 2026-01-01: First event.\n';+/** notes/alpha as an older gbrain left it, with a database-only timeline row and protected key, then a commit edits its file: held unknown. */-async function heldProtectedPage(engine: BrainEngine, root: string): Promise<void> {- writeFileSync(join(root, 'notes/alpha.md'), HAND_WRITTEN); commitAll(root, 'alpha');+async function heldProtectedPage(engine: BrainEngine, root: string, file = HAND_WRITTEN, dbKeys: Record<string, unknown> = { embed_skip: true },+ events = ['A database-only event.'], dbTruthEdit = false): Promise<void> {+ writeFileSync(join(root, 'notes/alpha.md'), file); commitAll(root, 'alpha');expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');await coordinated(engine, `DELETE FROM op_checkpoints WHERE op='sync-import-provenance'AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug='notes/alpha')`);- await coordinated(engine, `UPDATE pages SET frontmatter = frontmatter || '{"embed_skip": true}'::jsonb, knowledge_revision=$1::uuid, revision_write_request_id=NULL- WHERE source_id='default' AND slug='notes/alpha'`, [randomUUID()]);- await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.addTimelineEntry('notes/alpha',- { date: '2026-02-01', summary: 'A database-only event.', source: 'example', detail: '' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));- writeFileSync(join(root, 'notes/alpha.md'), HAND_WRITTEN.replace('Intro paragraph.', 'Intro paragraph, edited.')); commitAll(root, 'edit alpha');+ await coordinated(engine, `UPDATE pages SET frontmatter = frontmatter || $2::text::jsonb, knowledge_revision=$1::uuid, revision_write_request_id=NULL+ WHERE source_id='default' AND slug='notes/alpha'`, [randomUUID(), JSON.stringify(dbKeys)]);+ if (dbTruthEdit) await coordinated(engine, "UPDATE pages SET compiled_truth = 'An older database body.' WHERE source_id='default' AND slug='notes/alpha'");+ for (const [i, summary] of events.entries()) await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.addTimelineEntry('notes/alpha',+ { date: `2026-02-0${i + 1}`, summary, source: 'example', detail: '' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));+ writeFileSync(join(root, 'notes/alpha.md'), file.replace('Intro paragraph.', 'Intro paragraph, edited.')); commitAll(root, 'edit alpha');await performManagedSync(engine, OPTS);expect(await holds(engine)).toEqual(['notes/alpha.md file_drift unknown']);}@@ -188,4 +194,21 @@ for (const backend of testBackends()) {expect(readFileSync(join(root, 'notes/alpha.md'), 'utf8')).toBe(before);expect(await holds(engine)).toEqual(['notes/alpha.md file_drift unknown']);}, { databaseUrl, setup }), 180_000);++ test(`GBRA-133 [${backend}]: file wins on a file with quoted values, an unsorted inline tag list, stacked rules and a grandfather stamp only in the database appends only the two database-only timeline rows`, () => managedBrain(async ({ engine, root }) => {+ await heldProtectedPage(engine, root, STACKED_RULES, { validate: false }, ['A database-only event.', 'A second database-only event.'], true);+ const before = readFileSync(join(root, 'notes/alpha.md'), 'utf8');+ const preview = await heldPreview(engine, 'file');+ expect(listing(preview)).toEqual(['default:notes/alpha prefer_file']);+ expect(preview.warnings?.some(warning => warning.startsWith('Commit the appended files right after the apply') && warning.includes('notes/alpha.md'))).toBe(true);+ expect((await heldPreview(engine, 'file', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });+ const after = readFileSync(join(root, 'notes/alpha.md'), 'utf8');+ expect(after.slice(0, before.length)).toBe(before);+ expect(after.slice(before.length)).toMatch(/^<!-- gbrain:materialized v1 [0-9a-f]+ -->\n- \*\*2026-02-01\*\* \| example — A database-only event\.\n(<!-- gbrain:materialized v1 [0-9a-f]+ -->\n)?- \*\*2026-02-02\*\* \| example — A second database-only event\.\n$/);+ // Git durability is off in this checkout, so the preview says to commit the appended file; committed, the next sync imports it as is.+ commitAll(root, 'repair');+ await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual([]);+ expect(readFileSync(join(root, 'notes/alpha.md'), 'utf8')).toBe(after);+ }, { databaseUrl, setup }), 180_000);}