Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): deletion provenance and origin evidence walk a long history once, cached per commit
garrytan526bae52657c
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 2449182668..a122a85f25 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -44,7 +44,7 @@- `src/core/repair/overwritten-edits.ts` — `gbrain repair overwritten-edits`, explicit-only and preview-bound (`--slug` narrows): the preview lists each `high` page with a diff of the live page against the archived edit and saves the set; `--apply --expect <hash>` rechecks the page revision and version digest, then submits `revert_version` with `expected_revision` and `databaseOnly: 'overwrite_restore'` (`page-mutations.ts`: no worktree, receipt `write_through.skipped: overwrite_restore`), so the committed file is never rewritten; when this host owns the checkout and the committed HEAD blob differs from the restored page (`fileMatchesSnapshot`), it writes a `file_drift` hold (`fileDriftHold` + `writeGitHold`, `page_revision` = the restored revision). On another host, or for a file over the read bound, the outcome is `restored_file_unheld` with `next` naming the owner host's `gbrain repair file-drift --prefer database`; an apply whose restore request already committed replays it and writes the hold. Outcomes `restored`, `restored_file_held`, `restored_file_unheld`, `changed_since_preview`. Test: `test/overwritten-edits-6712.test.ts` (PGLite and Postgres).- `src/core/persistence/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone on a brain without managed persistence. `assertRestoreOrigin` (called by `submitPageMutation` for `restore_page`, `publishesFile` = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose `source_path` file `inSyncableTree` does not find (exists and is tracked or untracked-not-ignored, the set sync imports) with `source_changed` / detail `canonical_file_absent`, `retryable: false`, docs `storage-tiering.md#restoring-a-page-whose-file-is-gone` and an `ask_user` fix (`gbrain restore <slug> --source-id <id> --detach`, MCP `restore_page` `detach: true`); `detach: true` with nothing to detach refuses `invalid_params`. `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert in `engine-sql/pages.ts` clears that stamp when a sync writes a `source_path` again. `scanMissingRecordedFiles` (at most `MISSING_FILES_SCAN_LIMIT` live pages per source, `collectSyncableFiles` + `scannerSlugRootMode` path resolution) feeds doctor `missing_recorded_files`. Test: `test/restore-detach-6609.test.ts`.- `src/core/repair/keep-db-policy.ts` — the opt-in `storage.keep_db` policy (#6696 C7), since #6712 PR 4b an admission of the managed sync pass (design v3.2 §4, d1b option C); the consumer's keep_db worker and its 10-minute timer are gone. `readKeepDbPolicy` reads a source's `keep_db` prefixes from the gbrain.yml of its canonical checkout, only when the given host owns the active binding; doctor `maintenance_write_drift` reads it and `keepDbReceiptCost`. `freezeKeepDbReconcile` builds the `--prefer database` artifact (`prepareDriftPage`) for a path the pass classified `keep_db` (row 18) or `db_ahead`/`db_only` under keep_db (row 15), committed mode with `Dp = clean`, under this host's policy on a source that is not mirror-read-only, and refuses (`{ refused }`) unless the artifact's own read matches the frozen page id, revision, file bytes (`sha256` = `preconditions.raw_file_hash`) and path. `admitKeepDbReconcile` (trusted local pass only, `remote: false`) admits it through `admitReconcileArtifact` (`persistence/reconcile.ts`, the core `runReconcileApply` shares) under this installation's own CLI writer registration as a background producer, without waiting for publication; inside the admission transaction it re-reads `sync.admission` (`admission_paused` when not `normal`) and runs the pass's `inTx` fence, whose error rolls back and is rethrown as is. The request id derives from the page revision and frozen bytes (one drift, one request), skipping an id whose request `sync.admission` cancelled or that holds a retained backup but no request; the intent carries `keepDb: { passId }`, and its publication re-reads `sync.admission` and completes `cancelled`/`admission_paused` with nothing written (`reconcile-prepare.ts`, `coordinator.ts` `failureState`). `releaseMatchedDriftSkips` releases the concept drift skips of pages the pass classified `matched`. Tests: `test/keep-db-pass-admission.test.ts` (probes 26, 27, 47, 51; Postgres via `test/e2e/keep-db-pass-admission-postgres.test.ts`), `test/keep-db-consumer-retired.test.ts`, `test/file-drift-bulk-reconcile.test.ts` (PGLite; Postgres via `test/e2e/file-drift-bulk-reconcile-postgres.test.ts`).-- `src/core/persistence/sync-origin-evidence.ts` — #7130: whether a missing file is deletion evidence. `readOriginEvidence(gitRoot, tips, paths)` answers `committed` / `never_committed` / `ignored` / `unknown` per Git-root-relative path from one `git log --literal-pathspecs` over the tips and one `git check-ignore --no-index -z --stdin` per 500-path batch (120 s timeout; a failed read is `unknown`, which the classifier holds). `gitIgnoresUntracked` is the write-through test (`page-prepare.ts` keeps a managed write into an ignored path database-only; classic `sync/full.ts` keeps a stale page whose ignored file is still on disk). Read by `sync-pass.ts` (`reclassifyByOrigin`, delete and delete_drift paths only), `sync-discovery.ts` (tree-absent deletes) and the doctor scanner `src/core/uncommitted-deletions.ts`. Test: `test/sync-uncommitted-origin-7130.test.ts`.+- `src/core/persistence/sync-origin-evidence.ts` — #7130: whether a missing file is deletion evidence. `readOriginEvidence(gitRoot, tips, paths)` answers `committed` / `never_committed` / `ignored` / `unknown` per Git-root-relative path from one cached history walk per tip (`historyIndex`: `git log --full-history --name-status`, extended past a cached ancestor; 600 s) and `git check-ignore --no-index -z --stdin` per 500-path batch; a failed read is `unknown`, which the classifier holds. `readDeletionProvenance` reads the same walk. `gitIgnoresUntracked` is the write-through test (`page-prepare.ts` keeps a managed write into an ignored path database-only; classic `sync/full.ts` keeps a stale page whose ignored file is still on disk). Read by `sync-pass.ts` (`reclassifyByOrigin`, delete and delete_drift paths only), `sync-discovery.ts` (tree-absent deletes) and the doctor scanner `src/core/uncommitted-deletions.ts`. Test: `test/sync-uncommitted-origin-7130.test.ts`.- `src/core/persistence/sync-delete-tombstones.ts` — #7130: the record a `managed_sync_delete` apply writes in its own transaction (op `sync-delete-tombstone`, fingerprint = page id, `deleted_at` equal to the page row's), the `syncDeleteOrigin` SQL predicate (record, or the uncompacted committed receipt) and `readUnreviewedSyncTombstones` (sync tombstones with no live twin by `content_hash`). `purge-deleted.ts` holds that set when `automatic` (cycle purge phase, `purge` job; `blocked` code `sync_delete_unreviewed`) and only counts it for the consented manual purge; `purgeStaleCheckpoints` keeps a record while its tombstone exists. Test: `test/purge-sync-tombstone-hold-7130.test.ts`.- `src/core/uncommitted-deletions.ts` — #7130: the one bounded scanner of tombstones whose recorded file Git never held (ignored, or never committed and absent), sync deletions first; read by doctor `uncommitted_sync_deletions` (`src/commands/doctor/checks/uncommitted-sync-deletions.ts`) and by the repair.- `src/core/repair/uncommitted-deletions.ts` — `gbrain repair uncommitted-deletions --source <id>`: explicit-only, preview-bound (`--apply --expect <hash> --yes`) and consented; restores each page through a database-only `restore_page` with `detach` (`databaseOnly: 'detached'`). Never runs on upgrade, `--all` or maintenance. Tests: `test/repair-uncommitted-deletions-7130.test.ts`, `test/e2e/repair-uncommitted-deletions-7130-postgres.test.ts`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 5c3a64d147..2c91739116 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2179,16 +2179,19 @@ committing the file again clears the hold.<a id="file-drift-provenance"></a>**Provenance: who deleted each gone file.** Every page of a`--held --side deleted --state file_gone` preview names where its file went-(JSON: `details.pages[].provenance`, counted in `details.provenance`), read from-HEAD's full history with `--full-history`, so a deletion on a branch a merge-kept is found (a plain `git log --diff-filter=D -- <path>` simplifies it away):+(JSON: `details.pages[].provenance`, counted in `details.provenance` with every+kind listed, zeros included), read from HEAD's full history with `--full-history`,+so a deletion on a branch a merge kept is found (a plain+`git log --diff-filter=D -- <path>` simplifies it away). The history is walked+once and cached per commit, so a long history costs one walk per preview, and+the preview reports the commits read on stderr while it walks:| Provenance | Meaning ||---|---|| `deleted_by_commit` | The newest commit that deleted the file, with its sha, author, date and subject (a merge only when its resolution dropped the file). || `never_committed` | No commit ever held the file, so the page holds the only copy. |-| `deletion_uncommitted` | HEAD still holds the file; only the worktree lost it. |-| `unknown` | Git could not answer. |+| `deletion_uncommitted` | HEAD still holds the file (even one an older commit deleted and a later one restored); only the worktree lost it. |+| `unknown` | Git could not answer, or the history touched the file without a deletion it can name. |`--provenance <kind>` keeps only the held files of one provenance, so eachpopulation gets its own decision:diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 39ac344787..4a26d2d2b6 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1097,6 +1097,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },// #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.{ since: '0.60.361.0', id: 'applied_watermark_7190', text: '`get_write_request` with `applied: true` (`gbrain write-request <id> --applied`) now returns `applied`, read live: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`), the request `sequence` and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`), and a pending write\'s hint names that read; a write\'s own reply is otherwise unchanged. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },+ // GBRA-133 (deletion provenance and origin evidence at scale). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'A `gbrain repair file-drift --held --side deleted --state file_gone` preview over a long history no longer stalls or answers `unknown` for whole batches: the history is walked once and cached per commit instead of once per 500 files, `details.provenance` lists every kind (zeros included), the preview reports the commits it has read on stderr, and a file HEAD holds again reads `deletion_uncommitted`. The database-only keep (`--provenance never_committed --prefer database --apply`) reuses the walk instead of re-reading the history for every page. A managed sync deciding whether a missing file was ever committed reads the same walk, so on a long history a committed deletion is applied instead of being held when the per-batch read ran out of time.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.tsindex 0f1a48b057..d3c53cbaf5 100644--- a/src/core/persistence/sync-origin-evidence.ts+++ b/src/core/persistence/sync-origin-evidence.ts@@ -5,21 +5,29 @@* (an agent's write-through that landed in a directory `.gitignore` excludes, a copy removed before any commit) left no* history, so its absence proves nothing and the page may hold the only copy of its content: sync holds it instead.*- * Both reads are bounded Git plumbing over the candidate paths alone. A read that fails or times out answers `unknown`- * for every path it covered, which the classifier treats like a missing commit (fail closed: hold, never delete).+ * Both reads come from one walk of the history (`historyIndex`): every path a commit touched, and the newest commit that+ * deleted it. The walk is cached per commit and extended by the commits after a cached one, so a long history is read+ * once per process, not once per path or per batch (a pathspec walk per 500 paths ran past its time limit on a long+ * history and answered `unknown` for every path). A walk that fails or times out answers `unknown` for every path,+ * which the classifier treats like a missing commit (fail closed: hold, never delete).*/import { execFile, spawn } from '../spawn.ts';import { promisify } from 'node:util';import { gitChildEnv } from '../git-env.ts';+import { NulRecordSplitter } from '../hardened-git.ts';const execFileAsync = promisify(execFile);/** `committed`: some commit of the history holds the path. `never_committed`: none does. `ignored`: none does and `.gitignore` excludes it (a commit's evidence wins over a later ignore rule). `unknown`: a read failed. */export type OriginEvidence = 'committed' | 'never_committed' | 'ignored' | 'unknown';-/** Paths per Git invocation (argument-list bound). */+/** Paths per `check-ignore` invocation. */const BATCH = 500;const GIT_TIMEOUT_MS = 120_000;+/** One history walk; the old per-batch walks each had GIT_TIMEOUT_MS. */+const WALK_TIMEOUT_MS = 600_000;+/** Walks kept per Git top level: a newer commit extends and replaces its ancestor's, so two cover a pass's target and a baseline off its line. */+const INDEXES_PER_ROOT = 2;const GIT_MAX_BUFFER = 64 * 1024 ** 2;/** `literal`: the paths are pathspecs read literally (`log`); `check-ignore` takes plain pathnames and refuses the magic. */@@ -59,6 +67,89 @@ export async function gitIgnoresUntracked(root: string, relativePath: string): Preturn (await git(root, ['check-ignore', '-q', '--', relativePath])).code === 0;}+type Deletion = { commit: string; author: string; date: string; subject: string };+/** A path some commit touched, with the newest ordinary commit and the newest merge (against its first parent) that deleted it. */+interface PathHistory { deleted?: Deletion; mergeDeleted?: Deletion }+interface HistoryIndex { tip: string; paths: Map<string, PathHistory> }+const historyIndexes = new Map<string, HistoryIndex[]>();++/** Test seam: forget every cached walk. */+export function __resetHistoryIndexesForTest(): void { historyIndexes.clear(); }++/**+ * Walks `revs` (`--full-history`, every commit, merges against their first parent) and records, per Git-root-relative path,+ * that a commit touched it and the newest commits that deleted it. Null when Git failed or the walk ran out of time.+ */+function walkHistory(gitRoot: string, revs: string[], onCommit?: (commits: number) => void): Promise<Map<string, PathHistory> | null> {+ return new Promise(resolve => {+ const child = spawn('git', ['-c', 'core.quotepath=false', '-C', gitRoot, 'log', '--full-history', '--no-renames', '--diff-merges=first-parent', '-z',+ '--format=%x1e%H%x1f%P%x1f%an%x1f%aI%x1f%s', '--name-status', ...revs, '--'], { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'ignore'] });+ const paths = new Map<string, PathHistory>();+ const splitter = new NulRecordSplitter();+ let commit: { deletion: Deletion; merge: boolean } | null = null, status: string | null = null, commits = 0, settled = false;+ const done = (ok: boolean) => { if (!settled) { settled = true; clearTimeout(timer); resolve(ok && splitter.atRecordBoundary ? paths : null); } };+ const timer = setTimeout(() => { child.kill('SIGKILL'); done(false); }, WALK_TIMEOUT_MS);+ child.stdout.on('data', (chunk: Buffer) => {+ for (const record of splitter.push(chunk)) {+ const raw = record.toString('utf8');+ // A path is taken byte for byte; only a header or a status may carry the newline Git puts after a header.+ const token = status === null ? raw.replace(/^\n+/, '') : raw;+ if (status === null && token.startsWith('\x1e')) {+ const [hash = '', parents = '', author = '', date = '', ...subject] = token.slice(1).split('\x1f');+ commit = { deletion: { commit: hash, author, date, subject: subject.join('\x1f') }, merge: parents.trim().split(' ').length > 1 };+ status = null;+ if (++commits % 1000 === 0) onCommit?.(commits);+ } else if (status === null) status = token;+ else {+ const entry = paths.get(token) ?? {};+ if (status === 'D' && commit) {+ if (commit.merge) entry.mergeDeleted ??= commit.deletion; else entry.deleted ??= commit.deletion;+ }+ paths.set(token, entry);+ status = null;+ }+ }+ });+ child.on('error', () => done(false));+ child.on('close', code => done(code === 0));+ });+}++/** Whether `ancestor` is an ancestor of (or equal to) `commit`. */+async function isAncestor(gitRoot: string, ancestor: string, commit: string): Promise<boolean> {+ return (await git(gitRoot, ['merge-base', '--is-ancestor', ancestor, commit])).code === 0;+}++/**+ * The history of the commit `tip` (a full object id) in the work tree at `gitRoot`: a cached walk, a cached walk of an+ * ancestor extended by the commits after it (those are newer, so their deletions win), or one full walk. Null when Git+ * could not answer.+ */+async function historyIndex(gitRoot: string, tip: string, onCommit?: (commits: number) => void): Promise<HistoryIndex | null> {+ const cached = historyIndexes.get(gitRoot) ?? [];+ const exact = cached.find(index => index.tip === tip);+ if (exact) return exact;+ let base: HistoryIndex | undefined;+ for (const index of cached) if (await isAncestor(gitRoot, index.tip, tip)) { base = index; break; }+ const walked = await walkHistory(gitRoot, base ? [tip, `^${base.tip}`] : [tip], onCommit);+ if (!walked) return null;+ const paths = base ? new Map(base.paths) : walked;+ if (base) for (const [path, newer] of walked) {+ const older = paths.get(path);+ paths.set(path, { ...(newer.deleted ?? older?.deleted ? { deleted: newer.deleted ?? older!.deleted } : {}),+ ...(newer.mergeDeleted ?? older?.mergeDeleted ? { mergeDeleted: newer.mergeDeleted ?? older!.mergeDeleted } : {}) });+ }+ const index = { tip, paths };+ historyIndexes.set(gitRoot, [index, ...cached.filter(other => other !== base)].slice(0, INDEXES_PER_ROOT));+ return index;+}++/** The full object id of `rev`'s commit, or null. */+async function commitId(gitRoot: string, rev: string): Promise<string | null> {+ const read = await git(gitRoot, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]);+ return read.code === 0 ? read.stdout.trim() : null;+}+/*** The evidence for each Git-root-relative path in `gitPaths`, read in the work tree at `gitRoot`. `commits` are the* history tips to search (the pinned target and the pass's baseline); a path any commit reachable from one of them@@ -68,18 +159,29 @@ export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArrayconst evidence = new Map<string, OriginEvidence>();const tips = [...new Set(commits.filter((commit): commit is string => typeof commit === 'string' && commit.length > 0))];const paths = [...new Set(gitPaths)];+ const ids = await Promise.all(tips.map(tip => commitId(gitRoot, tip)));+ let historyKnown = ids.every(id => id !== null);+ // A tip that is an ancestor of another adds no commit to the union (the baseline of a pass is usually one of its target).+ const walked: string[] = [];+ for (const id of new Set(ids.filter((id): id is string => id !== null))) {+ let covered = false;+ for (const other of ids) if (other && other !== id && await isAncestor(gitRoot, id, other)) { covered = true; break; }+ if (!covered) walked.push(id);+ }+ const indexes: HistoryIndex[] = [];+ for (const id of walked) {+ const index = await historyIndex(gitRoot, id);+ if (index) indexes.push(index); else historyKnown = false;+ }for (let i = 0; i < paths.length; i += BATCH) {const batch = paths.slice(i, i + BATCH);- const touched = tips.length ? await git(gitRoot, ['log', ...tips, '--format=', '--name-only', '--no-renames', '-z', '--', ...batch], true) : { code: 0, stdout: '' };- // With an empty format and -z, every name is one NUL-terminated record (no separator between commits): read each byte for byte.- const committed = new Set(touched.stdout.split('\0').filter(Boolean));const ignoredRead = await checkIgnore(gitRoot, batch);const ignored = new Set(ignoredRead.stdout.split('\0').filter(Boolean));// check-ignore exits 1 when no path is ignored; anything else but 0 is a failed read.const ignoreKnown = ignoredRead.code === 0 || ignoredRead.code === 1;for (const path of batch) {- if (touched.code !== 0 || !ignoreKnown) evidence.set(path, 'unknown');- else if (committed.has(path)) evidence.set(path, 'committed');+ if (!historyKnown || !ignoreKnown) evidence.set(path, 'unknown');+ else if (indexes.some(index => index.paths.has(path))) evidence.set(path, 'committed');else evidence.set(path, ignored.has(path) ? 'ignored' : 'never_committed');}}@@ -98,40 +200,33 @@ export type DeletionProvenance =| { kind: 'deletion_uncommitted' } | { kind: 'never_committed' } | { kind: 'unknown' };export const DELETION_PROVENANCES = ['deleted_by_commit', 'deletion_uncommitted', 'never_committed'] as const;-/** Paths relative to `root` (a work tree or a directory inside one), read against HEAD in bounded batches. */-export async function readDeletionProvenance(root: string, paths: readonly string[]): Promise<Map<string, DeletionProvenance>> {+/**+ * Paths relative to `root` (a work tree or a directory inside one), read against HEAD from one history walk; `onCommit`+ * hears every 1,000 commits the walk reads.+ */+export async function readDeletionProvenance(root: string, paths: readonly string[], opts: { onCommit?: (commits: number) => void } = {}): Promise<Map<string, DeletionProvenance>> {const provenance = new Map<string, DeletionProvenance>();const unique = [...new Set(paths)];const head = await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);const unborn = head.code === 1 && (await git(root, ['rev-parse', '--is-inside-work-tree'])).stdout.trim() === 'true';for (const path of unique) provenance.set(path, unborn ? { kind: 'never_committed' } : { kind: 'unknown' });if (head.code !== 0) return provenance;+ const top = await git(root, ['rev-parse', '--show-toplevel']);+ const prefix = await git(root, ['rev-parse', '--show-prefix']);+ if (top.code !== 0 || prefix.code !== 0) return provenance;+ // ls-tree from `root` names the paths HEAD still holds, relative to it.+ const inHead = new Set<string>();for (let i = 0; i < unique.length; i += BATCH) {- const batch = unique.slice(i, i + BATCH);- // A side branch's own deleting commit names who removed the path and why; a merge counts (against its first parent) only- // for a path no ordinary commit deleted, where the merge's resolution dropped it.- for (const merges of [['--no-merges'], ['--merges', '--diff-merges=first-parent']]) {- const open = batch.filter(path => provenance.get(path)?.kind === 'unknown');- if (!open.length) break;- const deleted = await git(root, ['log', '--full-history', '--no-renames', ...merges, '--diff-filter=D', '--relative', '-z',- '--format=%x1e%H%x1f%an%x1f%aI%x1f%s', '--name-only', 'HEAD', '--', ...open], true);- if (deleted.code !== 0) break;- for (const record of deleted.stdout.split('\x1e').slice(1)) {- const [header = '', ...names] = record.split('\0');- const [commit = '', author = '', date = '', subject = ''] = header.trim().split('\x1f');- for (const name of names.map(entry => entry.replace(/^\n+/, '')).filter(Boolean)) {- if (provenance.get(name)?.kind === 'unknown' && open.includes(name)) provenance.set(name, { kind: 'deleted_by_commit', commit, author, date, subject });- }- }- }- const rest = batch.filter(path => provenance.get(path)?.kind === 'unknown');- if (!rest.length) continue;- const listed = await git(root, ['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...rest], true);- const touched = await git(root, ['log', '--full-history', '--no-renames', '--relative', '-z', '--format=', '--name-only', 'HEAD', '--', ...rest], true);- if (listed.code !== 0 || touched.code !== 0) continue;- const inHead = new Set(listed.stdout.split('\0').filter(Boolean));- const seen = new Set(touched.stdout.split('\0').map(entry => entry.replace(/^\n+/, '')).filter(Boolean));- for (const path of rest) provenance.set(path, inHead.has(path) ? { kind: 'deletion_uncommitted' } : seen.has(path) ? { kind: 'unknown' } : { kind: 'never_committed' });+ const listed = await git(root, ['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...unique.slice(i, i + BATCH)], true);+ if (listed.code !== 0) return provenance;+ for (const path of listed.stdout.split('\0')) if (path) inHead.add(path);+ }+ const index = await historyIndex(top.stdout.trim(), head.stdout.trim(), opts.onCommit);+ if (!index) return provenance;+ for (const path of unique) {+ const history = index.paths.get(`${prefix.stdout.trim()}${path}`);+ const deletion = history?.deleted ?? history?.mergeDeleted;+ provenance.set(path, inHead.has(path) ? { kind: 'deletion_uncommitted' } : deletion ? { kind: 'deleted_by_commit', ...deletion } : history ? { kind: 'unknown' } : { kind: 'never_committed' });}return provenance;}diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex 93e677d5de..da3ba97310 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -351,10 +351,16 @@ async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlalet window = selected.filter(target => target.inWindow).map(({ inWindow: _inWindow, ...target }) => target);// GBRA-133: a gone file's provenance (sync-origin-evidence.ts), read for every held file a --provenance selection filters, else for one window.const gone = window.filter(target => target.state === 'file_gone').slice(0, opts.provenance ? undefined : HELD_WINDOW_PAGES);- const provenance: Record<string, number> = {};+ const provenance: Record<string, number> = Object.fromEntries([...DELETION_PROVENANCES, 'unknown'].map(kind => [kind, 0]));if (gone.length) {const binding = await getWorktreeBinding(engine, sourceId);- const read = await readDeletionProvenance(join(binding!.local_path!, binding!.relative_path), gone.map(target => target.hold.path));+ // One walk of the history; a long one takes a while, so the preview says it is reading (stderr).+ opts.progress?.start('repair.file_drift.provenance', gone.length);+ let read: Map<string, DeletionProvenance>;+ try {+ read = await readDeletionProvenance(join(binding!.local_path!, binding!.relative_path), gone.map(target => target.hold.path),+ { onCommit: commits => opts.progress?.heartbeat(`read ${commits} commit(s) of history for ${gone.length} held file(s)`) });+ } finally { opts.progress?.finish(); }for (const target of gone) {target.provenance = read.get(target.hold.path) ?? { kind: 'unknown' };provenance[target.provenance.kind] = (provenance[target.provenance.kind] ?? 0) + 1;diff --git a/test/deletion-provenance-scale-gbra133.test.ts b/test/deletion-provenance-scale-gbra133.test.tsnew file mode 100644index 0000000000..6e17fd1ac3--- /dev/null+++ b/test/deletion-provenance-scale-gbra133.test.ts@@ -0,0 +1,91 @@+/**+ * GBRA-133: deletion provenance and origin evidence read a long history once. Before, each read walked the history once per+ * 500 paths with a pathspec (`git log --full-history -- <500 paths>`); on a history of about 20,000 commits every walk ran+ * past its 120 s limit, so a preview of about 2,000 held files sat silent for many minutes and answered `unknown` for whole+ * batches (a round 1,000), and the database-only keep re-walked the history for every page it applied. Now one walk per+ * commit (`historyIndex`, extended by the commits after a cached one) answers every path, HEAD's own files read+ * `deletion_uncommitted` even when an older commit deleted and re-added them, and the walk reports its progress.+ * Real Git; the long history is written with `git fast-import`.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { execFileSync, spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { readDeletionProvenance, readOriginEvidence } from '../src/core/persistence/sync-origin-evidence.ts';++const dirs: string[] = [];+const scratch = () => { const dir = mkdtempSync(join(tmpdir(), 'gbrain-provenance-scale-')); dirs.push(dir); return dir; };+afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };+const kinds = (read: Map<string, { kind: string }>) => Object.fromEntries([...read].map(([path, found]) => [path, found.kind]));++describe('GBRA-133: one history walk answers every path', () => {+ test('a file HEAD holds again reads deletion_uncommitted; a later deletion names the newer commit; batches past 500 paths', async () => {+ const root = scratch();+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q', '-b', 'main');+ for (let i = 0; i < 1200; i++) writeFileSync(join(root, `notes/n${i}.md`), `${i}\n`);+ writeFileSync(join(root, 'notes/back.md'), 'one\n');+ commit(root, 'init');+ git(root, 'rm', '-q', 'notes/back.md'); git(root, 'commit', '-qm', 'drop back');+ writeFileSync(join(root, 'notes/back.md'), 'two\n'); commit(root, 'restore back');+ git(root, 'rm', '-q', '-r', 'notes/n1*'); git(root, 'commit', '-qm', 'cull n1');+ rmSync(join(root, 'notes/back.md'));+ const paths = ['notes/back.md', ...Array.from({ length: 1200 }, (_, i) => `notes/n${i}.md`).filter(path => path.startsWith('notes/n1')), 'notes/never.md'];+ expect(paths.length).toBeGreaterThan(200);+ const many = Array.from({ length: 700 }, (_, i) => `notes/missing${i}.md`);+ const first = await readDeletionProvenance(root, [...paths, ...many]);+ expect(first.get('notes/back.md')).toEqual({ kind: 'deletion_uncommitted' });+ expect(first.get('notes/n1.md')).toMatchObject({ kind: 'deleted_by_commit', subject: 'cull n1' });+ expect(first.get('notes/never.md')).toEqual({ kind: 'never_committed' });+ expect(new Set(many.map(path => first.get(path)!.kind))).toEqual(new Set(['never_committed']));++ // A newer commit deletes back.md for good: the cached walk is extended, and the newest deleting commit is named.+ git(root, 'rm', '-q', '--cached', 'notes/back.md'); git(root, 'commit', '-qm', 'drop back again');+ const second = await readDeletionProvenance(root, ['notes/back.md', 'notes/n1.md']);+ expect(second.get('notes/back.md')).toMatchObject({ kind: 'deleted_by_commit', subject: 'drop back again', commit: git(root, 'rev-parse', 'HEAD') });+ expect(second.get('notes/n1.md')).toMatchObject({ kind: 'deleted_by_commit', subject: 'cull n1' });++ // Origin evidence: a baseline that is an ancestor of the target adds nothing; a path only a newer commit touched is+ // not committed in an older target's history.+ const old = git(root, 'rev-parse', 'HEAD~3');+ writeFileSync(join(root, 'notes/late.md'), 'late\n'); commit(root, 'late');+ git(root, 'rm', '-q', 'notes/late.md'); git(root, 'commit', '-qm', 'drop late');+ const head = git(root, 'rev-parse', 'HEAD');+ expect(Object.fromEntries(await readOriginEvidence(root, [head, old], ['notes/late.md', 'notes/n1.md', 'notes/never.md'])))+ .toEqual({ 'notes/late.md': 'committed', 'notes/n1.md': 'committed', 'notes/never.md': 'never_committed' });+ expect(Object.fromEntries(await readOriginEvidence(root, [old], ['notes/late.md', 'notes/n1.md'])))+ .toEqual({ 'notes/late.md': 'never_committed', 'notes/n1.md': 'committed' });+ });++ test('about 1,800 held files over a 20,000-commit history resolve in one walk, with progress', async () => {+ const root = scratch();+ spawnSync('git', ['init', '-q', '-b', 'main', root]);+ const COMMITS = 20_000, FILES = 4_000, lines: string[] = [], live = new Set<number>();+ for (let c = 0; c < COMMITS; c++) {+ lines.push('commit refs/heads/main', `mark :${c + 1}`, `committer Example <[email protected]> ${1_700_000_000 + c * 60} +0000`, `data ${`c${c}`.length}`, `c${c}`);+ if (c > 0) lines.push(`from :${c}`);+ for (let k = 0; k < 3; k++) {+ const file = (c * 7 + k * 13) % FILES;+ if (live.has(file) && (c + k) % 5 === 0) { lines.push(`D notes/f${file}.md`); live.delete(file); continue; }+ const body = `v${c}\n`;+ lines.push(`M 100644 inline notes/f${file}.md`, `data ${body.length}`, body); live.add(file);+ }+ lines.push('');+ }+ const imported = spawnSync('git', ['-C', root, 'fast-import', '--quiet'], { input: lines.join('\n') + '\n', maxBuffer: 1 << 30 });+ expect(imported.status).toBe(0);+ git(root, 'checkout', '-q', 'main');+ const gone = Array.from({ length: FILES }, (_, i) => i).filter(i => !live.has(i)).map(i => `notes/f${i}.md`);+ const never = Array.from({ length: 1000 }, (_, i) => `notes/never${i}.md`);+ let heard = 0;+ const read = await readDeletionProvenance(root, [...gone, ...never], { onCommit: commits => { heard = commits; } });+ expect(gone.length).toBeGreaterThan(500);+ expect(new Set(gone.map(path => read.get(path)!.kind))).toEqual(new Set(['deleted_by_commit']));+ expect(new Set(never.map(path => read.get(path)!.kind))).toEqual(new Set(['never_committed']));+ expect(heard).toBeGreaterThanOrEqual(COMMITS - 1000);+ expect(kinds(await readDeletionProvenance(root, [gone[0]!, never[0]!]))).toEqual({ [gone[0]!]: 'deleted_by_commit', [never[0]!]: 'never_committed' });+ }, 120_000);+});diff --git a/test/repair-file-drift-provenance-gbra133.test.ts b/test/repair-file-drift-provenance-gbra133.test.tsindex 915a9dc5be..839d87796f 100644--- a/test/repair-file-drift-provenance-gbra133.test.ts+++ b/test/repair-file-drift-provenance-gbra133.test.ts@@ -108,7 +108,7 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: held goneconst all = await run({ prefer: 'database' });expect(all.preview_hash).toBeTruthy();- expect(all.details!.provenance).toEqual({ deleted_by_commit: 1, never_committed: 1 });+ expect(all.details!.provenance).toEqual({ deleted_by_commit: 1, deletion_uncommitted: 0, never_committed: 1, unknown: 0 });expect(pages(all).map(page => [page.slug, page.provenance?.kind, page.provenance?.subject])).toEqual([['notes/b', 'deleted_by_commit', 'cull b'], ['notes/w', 'never_committed', undefined]]);expect(pages(all).find(page => page.slug === 'notes/b')!.provenance!.commit).toBe(git(root, 'rev-parse', 'HEAD'));expect(all.listing!.find(entry => entry.item === 'default:notes/b')!.detail).toContain(`deleted by commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);