Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#6712 PR 4b): Git provenance with L absent is delete, never kept (master #5459); restore master's 5459 row 2
garrytanfe307610d74d
diff --git a/scripts/bench/sync-convergence-seeded.ts b/scripts/bench/sync-convergence-seeded.tsindex 7f699eb3dd..d1756cd89f 100644--- a/scripts/bench/sync-convergence-seeded.ts+++ b/scripts/bench/sync-convergence-seeded.ts@@ -71,6 +71,8 @@ export const FINDINGS = {text: 'frontmatter_slug_conflict and legacy_slug_conflict holds are always rescreen-due, so row 1 never holds them; with no page and an unchanged file they fall to row 10 legacy_same (settled, none) while the hold row still exists, so the class contradicts the hold that status shows.' },dirtyGlossary: { kind: 'b', ref: 'v3.2 §9 class glossary; sync-classify.ts syncClassAction',text: 'Row 11 dirty is settled when absorbed or published, but the glossary gives a class one action and 4a tags every dirty path repair, so a settled write-through publication waiting for its commit reads as needing a person.' },+ gitTruth: { kind: 'b', ref: 'master #5459 (keptWorkingTreePages); v3.2 §2.3 row 4 ("any provenance")',+ text: 'master #5459: Git is the truth for tracked paths; row 4 is keptWorkingTreePages. A page Git imported whose file left Git is row 5 delete (row 6 delete_drift without proof) even when a copy lingers untracked; only a working-tree (or unknown-provenance) import is kept. Design row 4 says any provenance, so the shadow follows master, not the table.' },twinInvisible: { kind: 'b', ref: 'v3.2 §2.3 domain (pages with a recorded origin only)',text: 'A #6885 legacy twin (source_path NULL) is outside the domain: the pair reads as one matched path and nothing in convergence counts it, so PR 4 can neither report nor converge already-forked pairs.' },} as const satisfies Record<string, Finding>;@@ -143,7 +145,8 @@ export function mixCases(): SeededCase[] {c('deleted_same: deleted marker', 'mix/purged-marker-same.md', { key: 'deleted_same', ...settledNone }, 'row 8', 'sync, delete_page purge (writes the marker)'),c('deleted_edited: deleted marker', 'mix/purged-marker-differs.md', { key: 'deleted_edited', action: 'hold', settled: false, side: 'deleted', state: 'purged_differs' }, 'row 9', 'sync, delete_page purge, raw SQL (marker), git commit'),c('legacy_same: legacy marker', 'mix/legacy-marker.md', { key: 'legacy_same', ...settledNone }, 'row 10', 'sync, delete_page purge, raw SQL (the legacy marker PR 4b writes)'),- c('kept: live page, file left T, still on disk', 'mix/kept-file.md', { key: 'kept', ...settledNone }, 'row 4', 'sync, git rm --cached and commit'),+ c('delete: Git-imported page, file left T, still on disk (#5459)', 'mix/kept-file.md', { key: 'delete', action: 'delete', settled: false }, 'row 5 (master #5459)', 'sync, git rm --cached and commit', FINDINGS.gitTruth),+ c('kept: working-tree import, never in T, still on disk', 'mix/kept-working.md', { key: 'kept', ...settledNone }, 'row 4 (keptWorkingTreePages)', 'sync --working-tree of an untracked file'),c('dirty: committed edit under an uncommitted one', 'mix/dirty-held.md', { key: 'dirty', action: 'hold', settled: false }, 'row 11', 'sync, git commit, uncommitted edit'),c('dirty: uncommitted edit of a synced file (absorbed)', 'mix/dirty-absorbed.md', { key: 'matched', action: 'none', settled: true }, 'row 12: Dp is read for candidates only (rulings b3)', 'sync, uncommitted edit', FINDINGS.dirtyAbsorbed),c('dirty: write-through publication not committed (published)', 'mix/dirty-published.md', { key: 'dirty', action: 'none', settled: true }, 'row 11 (settled: published)', 'sync, put_page (write-through)', FINDINGS.dirtyGlossary),@@ -195,6 +198,11 @@ export async function seedMix(brain: MixBrain): Promise<SeededCase[]> {if (first.status !== 'first_sync') throw new Error(`the first sync ended ${first.status}`);const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ // Stage 1b: a working-tree sync imports an untracked file (provenance working), which stays on disk and never enters T.+ write(root, 'mix/kept-working.md', note('kept-working', 'An untracked working-tree note.'));+ const working = await performManagedSync(engine, { ...SYNC, workingTree: true });+ if (working.status !== 'synced') throw new Error(`the working-tree sync ended ${working.status}`);+// Stage 2: a second sync writes the holds master writes itself.await withoutTrigger(() => engine.executeRaw("INSERT INTO pages(source_id,slug,type,page_kind,title,compiled_truth) VALUES('default','mix/Legacy Name','note','markdown','Legacy Name','A legacy page.')"));write(root, 'mix/held-dirty.md', note('held-dirty', 'Synthetic held-dirty two.'));@@ -313,12 +321,12 @@ export function seedSpelling(root: string, cases: SeededCase[]): SeededCase[] {return [...cases, ...mixCases().filter(entry => SPELLING.includes(entry.path))];}-/** Phase B: a mass removal that trips #2828's valve (mass/* plus the single delete of the mix). */+/** Phase B: a mass removal that trips #2828's valve (mass/* plus the mix's two single deletes). */export function seedMassDelete(root: string, cases: SeededCase[]): SeededCase[] {gitIn(root, ['rm', '-q', '-r', '--', 'mass']);commitStaged(root, 'mass removal');- return cases.map(entry => entry.path.startsWith('mass/') || entry.path === 'mix/delete-proof.md'- ? { ...entry, category: entry.path.startsWith('mass/') ? 'deletes_withheld (mass removal)' : 'deletes_withheld (the single delete, same trip)', row: '§2.6 valve on row 5',+ return cases.map(entry => entry.path.startsWith('mass/') || entry.path === 'mix/delete-proof.md' || entry.path === 'mix/kept-file.md'+ ? { ...entry, category: entry.path.startsWith('mass/') ? 'deletes_withheld (mass removal)' : 'deletes_withheld (a single delete of the mix, same trip)', row: '§2.6 valve on row 5',seed: `${entry.seed}, git rm and commit (mass)`, expect: { key: 'deletes_withheld', action: 'delete', settled: true } }: entry);}@@ -549,7 +557,7 @@ const SCALE_EXPECT: Record<ScaleKind, { expect: Expected; row: string; finding?:drift_both: { expect: { key: 'drift', action: 'hold', side: 'both' }, row: 'row 19' }, drift_unknown: { expect: { key: 'drift', action: 'hold', side: 'unknown' }, row: 'row 19' },delete: { expect: { key: 'delete', action: 'delete' }, row: 'row 5' }, delete_drift: { expect: { key: 'delete_drift', action: 'hold' }, row: 'row 6' },tombstone_same: { expect: { key: 'deleted_same', action: 'none' }, row: 'row 8' }, tombstone_edited: { expect: { key: 'deleted_edited', action: 'hold' }, row: 'row 9' },- tombstone_untracked: { expect: { key: 'untracked', action: 'none' }, row: 'row 3' }, kept: { expect: { key: 'kept', action: 'none' }, row: 'row 4' },+ tombstone_untracked: { expect: { key: 'untracked', action: 'none' }, row: 'row 3' }, kept: { expect: { key: 'kept', action: 'none' }, row: 'row 4 (keptWorkingTreePages)' },dirty: { expect: { key: 'dirty', action: 'hold' }, row: 'row 11' },dirty_absorbed: { expect: { key: 'matched', action: 'none' }, row: 'row 12: Dp is read for candidates only (rulings b3)', finding: FINDINGS.dirtyAbsorbed },held_invalid_frontmatter: { expect: { key: 'held', action: 'none' }, row: 'row 1' }, legacy_unverified: { expect: { key: 'legacy_unverified', action: 'none' }, row: 'row 17' },@@ -581,6 +589,8 @@ export async function seedScale(engine: BrainEngine, fixture: Fixture, input: {await recordSql(of('reparse_parser'), `jsonb_set(completed_keys->0, '{parser,parser_version}', '"import=0"')`);await recordSql(of('reparse_origin'), `jsonb_set(completed_keys->0, '{origin}', to_jsonb('elsewhere/' || (completed_keys->0->>'origin')))`);await recordSql(of('unproven', 'drift_unknown'), "(completed_keys->0) - 'revision'");+ // Row 4 is keptWorkingTreePages (#5459): the kept picks leave T below, so their records say a working-tree import.+ await recordSql(of('kept'), `jsonb_set(completed_keys->0, '{working}', 'true')`);await recordSql(of('legacy_unverified'), "(completed_keys->0) - 'revision' - 'disk_blob_oid' - 'parser' - 'blob_oid'");// A database-only edit: the page's revision moves off its record's, with no request (so no attestation).await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE source_id=$1 AND id=ANY($2::int[])', [sourceId, idsOf(of('db_only', 'unproven', 'drift_both', 'drift_unknown', 'delete_drift'))]);diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex fb1d84f32b..115d026645 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -28,7 +28,7 @@ export interface SyncPathState {tree: string | null;/** `L(p)`: committed mode `T[p]`; working mode the physical bytes' blob id (CRLF-folded / LFS-resolved to `T[p]` when clean); null = absent. */level: string | null;- /** `workingTreeFilePresent`. */+ /** `workingTreeFilePresent`; committed mode, `L = absent`: false for a page whose import provenance is the Git blob (`keptWorkingTreePages`). */present: boolean;/** Committed mode, `p ∈ T`: the candidate dirtiness; null when the pass did not probe it (only paths settled without it). */dirty: SyncDirtiness | null;diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 0bb83b4f9f..2ad00e4551 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -462,7 +462,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr};const identityDowngrades: DowngradedRename[] = [];const fileRefusals = new Map<string, SyncFileRefusal>();- const keptCount = () => lastLevel?.paths.filter(entry => entry.result.cls === 'kept' && !entry.gitProvenance).length ?? 0;+ const keptCount = () => lastLevel?.paths.filter(entry => entry.result.cls === 'kept').length ?? 0;const result = (status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult => ({ status, fromCommit: remote ? null : context.source.last_commit, toCommit: remote ? '' : head,added: counts.added, modified: counts.modified, deleted: counts.deleted, renamed: counts.renamed, chunksCreated: counts.chunks, embedded: 0, pagesAffected: [],filesImported: sliceBase.pages, bankedFiles: sliceBase.pages, waived: { imports: counts.waivedImports, deletes: counts.waivedDeletes }, prescreened: 0,diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex da8f3bb171..9bd831e6ad 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -74,9 +74,7 @@ export interface ShadowPath { path: string; slug: string | null; pageId: number/** A page-less path unchanged since the baseline whose page a committed request deleted: the bootstrap writes it a `legacy` marker (`legacy_pageless`). */legacyPageless?: true;/** #6517 (`selectOriginClaimant`): several live pages, or no live page and several tombstones, record this origin. */- ambiguousOrigin?: { kind: 'several_live' | 'several_tombstones'; slugs: string[] };- /** The page's import record names the pinned Git blob as its bytes (`working: false`, or a blob id on a record from before the stamp). */- gitProvenance?: true }+ ambiguousOrigin?: { kind: 'several_live' | 'several_tombstones'; slugs: string[] } }export interface ShadowLevel {sourceId: string; incarnation: string; root: string; gitRoot: string; scope: string; slugMode: 'git-root' | 'source-root';@@ -441,13 +439,16 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st}const fp = (path: string) => syncImportParserFor(sourceRelative(path), pack?.identity ?? null);- const stateOf = async (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): Promise<{ state: SyncPathState; row?: PageRow; legacyPageless?: true; gitProvenance?: true }> => {+ const stateOf = async (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): Promise<{ state: SyncPathState; row?: PageRow; legacyPageless?: true }> => {const committed = tree.get(path) ?? null;const row = byOrigin.get(path);const level = levelOf(path, probe);// Presence decides only rows 4-6 (a level of absent); a committed path in T is not read here (Dp covers it).const record = row?.record ?? null;- const presentNow = mode === 'working' ? level !== null : level === null ? readPresent(root, path, scope) : true;+ // #5459 (`keptWorkingTreePages`): a page whose import provenance is the pinned Git blob follows Git, so a lingering+ // untracked copy of its file does not keep it.+ const fromGit = record?.working === false || (record?.working === undefined && !!record?.blob_oid);+ const presentNow = mode === 'working' ? level !== null : level === null ? !fromGit && readPresent(root, path, scope) : true;const recordBlobOids = recordOids(record);const attested = row && (row.arm1 || row.attested_hash) ? { hash: row.attested_hash ?? null, arm1: row.arm1 === true } : null;const hold = holdByGitPath.get(path);@@ -471,9 +472,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stkeepDb: !mirror && keepDbPrefixes.length > 0 && !!row && isKeepDbSlug(row.slug, keepDbPrefixes),openWork: !!row && open.pageIds.has(Number(row.id)) || open.origins.has(originOf(path)),};- // #5459: `working_tree_kept` counts the kept pages whose import provenance is the working tree or unknown, never the Git blob.- const gitProvenance = record?.working === false || (record?.working === undefined && !!record?.blob_oid);- return { state, ...(row ? { row } : {}), ...(legacyPageless ? { legacyPageless } : {}), ...(gitProvenance ? { gitProvenance } : {}) };+ return { state, ...(row ? { row } : {}), ...(legacyPageless ? { legacyPageless } : {}) };};// Bootstrap (the incarnation's first pass; for a read-only level, no pass row yet): page-less paths at their baseline blob@@ -500,7 +499,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst settledBeforeDirtiness = new Set(['held', 'spelling', 'untracked', 'kept', 'delete', 'delete_drift', 'gone', 'deleted_same', 'deleted_edited', 'legacy_same', 'matched']);for (const path of [...domain].sort()) {const probe = probes.get(path);- const { state, row, legacyPageless, gitProvenance } = await stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);+ const { state, row, legacyPageless } = await stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);const result = classifySyncPath(state);// Rows 1-10 precede row 11 and `matched` settles either way, so only the rest are Dp candidates (design v3.2 §2.1).const staged = mode === 'committed' && tree.has(path) && (index.get(path)?.oid !== tree.get(path)!.oid || (index.get(path)?.stage ?? 0) !== 0);@@ -508,7 +507,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst claimed = claimants.get(path) ?? [];const { ambiguous } = claimed.length > 1 ? selectOriginClaimant(claimed.map(page => ({ ...page, deleted_at: page.deleted ? true : null }))) : { ambiguous: null };const ambiguousOrigin = ambiguous ? { kind: ambiguous, slugs: claimed.filter(page => ambiguous === 'several_tombstones' || !page.deleted).map(page => page.slug) } : undefined;- paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}), ...(ambiguousOrigin ? { ambiguousOrigin } : {}), ...(gitProvenance ? { gitProvenance } : {}) });+ paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}), ...(ambiguousOrigin ? { ambiguousOrigin } : {}) });}timings.classify = t();if (candidates.length) {diff --git a/test/sync-convergence-seeded-6712.test.ts b/test/sync-convergence-seeded-6712.test.tsindex b77aca05fa..c6951eb598 100644--- a/test/sync-convergence-seeded-6712.test.ts+++ b/test/sync-convergence-seeded-6712.test.ts@@ -82,7 +82,8 @@ for (const backend of testBackends()) {const before = await footprint(engine);const committed = await evaluate(engine, mix, { label: 'committed' });expectRun(committed);- expect(committed.receipt.deletes).toMatchObject({ count: 1, verdict: 'apply' });+ // delete-proof and kept-file (#5459: a Git-imported page whose file left Git is a delete even with a lingering copy).+ expect(committed.receipt.deletes).toMatchObject({ count: 2, verdict: 'apply' });expect(committed.receipt.db_ahead).toMatchObject({ pending: 1, db_only: 2, unproven: 1 });expect(committed.receipt).toMatchObject({ keep_db_admitted: 2, legacy_unverified: 1, legacy_pageless: 1, decisions: { both: 0, unknown: 0, deleted: 3 } });@@ -112,8 +113,8 @@ for (const backend of testBackends()) {const mass = await evaluate(engine, seedMassDelete(root, cases), { label: 'mass' });expectRun(mass);- expect(mass.receipt.deletes).toMatchObject({ count: 61, verdict: 'withheld' });- expect(mass.receipt.deletes_withheld).toMatchObject({ count: 61, set_hash: expect.stringMatching(/^[0-9a-f]{64}$/) });+ expect(mass.receipt.deletes).toMatchObject({ count: 62, verdict: 'withheld' });+ expect(mass.receipt.deletes_withheld).toMatchObject({ count: 62, set_hash: expect.stringMatching(/^[0-9a-f]{64}$/) });expect(await footprint(engine)).toBe(before);}, mixSetup), 600_000);diff --git a/test/sync-full-untracked-import-5459.test.ts b/test/sync-full-untracked-import-5459.test.tsindex a928020853..f30ae49ce5 100644--- a/test/sync-full-untracked-import-5459.test.ts+++ b/test/sync-full-untracked-import-5459.test.ts@@ -116,7 +116,7 @@ describe('--full tree walk keeps pages imported from untracked working-tree file}}), 300_000);- test('a Git-imported page whose file left Git but lingers untracked is kept, not counted as a working-tree import', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ test('an explicit tracked Git deletion is applied even when a copy of the file lingers untracked (Git is the truth for tracked paths)', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {const { r, id, live, page, incarnation, full } = await managedSource(engine);r.write('tracked'); r.commit('add tracked');@@ -126,17 +126,10 @@ describe('--full tree walk keeps pages imported from untracked working-tree filer.git('rm', '-q', '--cached', 'notes/tracked.md'); r.commitStaged('stop tracking');// The bytes are still on disk, untracked.expect(r.git('status', '--porcelain')).toContain('?? notes/tracked.md');- // #6712 PR 4b (design v3.2 §2.3 row 4, `kept`): a live page whose file left T but is still on disk is kept in committed- // mode, whatever its provenance; only a page imported from the working tree (or of unknown provenance) is counted.const result = await full();- expect(await live()).toEqual(['notes/base', 'notes/tracked']);- expect((await page('notes/tracked'))!.deleted_at).toBeNull();- expect(result.working_tree_kept).toBeUndefined();- // Removing the lingering copy as well is the deletion: nothing keeps the page any more.- r.remove('tracked');- await full();expect(await live()).toEqual(['notes/base']);expect((await page('notes/tracked'))!.deleted_at).not.toBeNull();+ expect(result.working_tree_kept).toBeUndefined();expect(await readSyncImportProvenance(engine, id, incarnation, tracked.id)).toMatchObject({ working: false });}}), 300_000);