Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: evidence ordering, nested-source history, held binding and conversion file fences (review round 1)
garrytandae985057fe2
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex e4f2d2aeaf..84df69aaab 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1074,7 +1074,7 @@ More: [docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes](../../do| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A conversion review list, decisions file or approval was refused because its path is inside a source's checkout. | Those files name pages and paths. Written or read only outside every registered source root (mode 0600), they can never be synced, imported or committed. | Pass a path outside every source checkout, e.g. under ~/.gbrain. | agent | `repeat the read that failed` | 1 | no |+| A conversion review list, decisions file or approval was refused because its path is inside a source's checkout. | Those files name pages and paths. Written or read only outside every registered source root and the Git working tree holding it (mode 0600), they can never be synced, imported or committed. | Pass a path outside every source checkout, e.g. under ~/.gbrain. | agent | `repeat the read that failed` | 1 | no |More: [docs/guides/git-canonical.md#review-list-and-decisions](../../docs/guides/git-canonical.md#review-list-and-decisions)diff --git a/docs/guides/git-canonical.md b/docs/guides/git-canonical.mdindex 4ed30388cf..acf9dc9482 100644--- a/docs/guides/git-canonical.md+++ b/docs/guides/git-canonical.md@@ -105,10 +105,10 @@ recorded):| Evidence | Meaning | Category ||---|---|---|-| `adopt_db_moved` | An older version of the page equals the committed file: only the database moved. | adopt |-| `git_wins_file_moved` | The page equals an older committed blob of its path: 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. | 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). | discard until decided |+| `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 |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-gap@@ -135,7 +135,8 @@ A decision names the page at its revision, blob and evidence: once the pagemoves again it is counted `stale` and not applied, and the page waits for a newdecision. The file is bound into the preview hash. Review lists, decision filesand approvals hold page names, so gbrain writes them owner-only (mode 0600) and-refuses any path inside a source's checkout (`conversion_file_in_source_root`).+refuses any path inside a source's checkout or the Git working tree that holds+it, including a symlink into one (`conversion_file_in_source_root`).### Approval across timediff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 841e148957..f42620a8e5 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -380,7 +380,7 @@ export const CODES = {git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'held_drift_unknown_differs', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database', 'ignore_status_unknown', 'no_record_both_moved', 'no_record_no_evidence'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; no_record_both_moved and no_record_no_evidence, a page with no import record whose content history shows both sides moved, or shows nothing, until the owner's --decisions file decides it; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted; ignore_status_unknown, a target whose ignore status Git cannot read (beyond a symlink, outside the checkout, a timed-out check). There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },git_conversion_delta: { class: 'consent', actor: 'user', summary: "An approved conversion found pages that changed since the approval, or decisions it did not approve, so only the unchanged pages were applied and the source stays mixed.", why: "gbrain sources canonical --to git --apply --approved applies only the pages whose slug, revision, committed blob, evidence and action are the ones the owner approved. A page that changed since, a new page, a database edit the plan would now discard, and any decision the approval did not hold stay unapplied and are listed (delta) with counts; nothing outside the approved set is applied without a new decision.", docs: 'docs/guides/git-canonical.md#approval-across-time', suggestion: 'Relay the delta list and its counts to the owner; once they decide, preview again with --approval-out and apply the new approval.' },- conversion_file_in_source_root: { class: 'caller', summary: "A conversion review list, decisions file or approval was refused because its path is inside a source's checkout.", why: "Those files name pages and paths. Written or read only outside every registered source root (mode 0600), they can never be synced, imported or committed.", docs: 'docs/guides/git-canonical.md#review-list-and-decisions', suggestion: 'Pass a path outside every source checkout, e.g. under ~/.gbrain.' },+ conversion_file_in_source_root: { class: 'caller', summary: "A conversion review list, decisions file or approval was refused because its path is inside a source's checkout.", why: "Those files name pages and paths. Written or read only outside every registered source root and the Git working tree holding it (mode 0600), they can never be synced, imported or committed.", docs: 'docs/guides/git-canonical.md#review-list-and-decisions', suggestion: 'Pass a path outside every source checkout, e.g. under ~/.gbrain.' },git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet.", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.tsindex c03c8346b1..4a323ff9cb 100644--- a/src/core/persistence/git-conversion.ts+++ b/src/core/persistence/git-conversion.ts@@ -54,7 +54,7 @@ import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { inlineExportMarkdown, readExportPage, readExportPages, readExportWithdrawals, type ExportSnapshot } from '../export-snapshot.ts';import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';import { censusGitGap, type GitGapCensus, type GitGapPage } from '../../commands/sources-git-gap.ts';-import { compareInlineExportFile, DIRECTION_EVIDENCE, ignoredPaths, readBlobs, type DeclaredClass, type DirectionEvidence, type Evidence, type ExportFileComparison } from './git-gap.ts';+import { compareInlineExportFile, DIRECTION_EVIDENCE, gitTopLevel, ignoredPaths, readBlobs, type DeclaredClass, type DirectionEvidence, type Evidence, type ExportFileComparison } from './git-gap.ts';import { commitThroughDoor } from './git-door.ts';import { gitRootAhead, pushGitRoot } from './effect-git.ts';import { DURABILITY_NOT_ENABLED_REASON, gitDurabilityPolicy } from './git-durability-policy.ts';@@ -204,22 +204,27 @@ const DECISION_VALUES = ['adopt', 'git_wins'] as const;/*** The review list and decision files hold page names and paths: each is written owner-only (0600) and refused anywhere- * under a registered source's root, so no sync or commit ever picks one up. Checked on the real path of the file's directory.+ * under a registered source's root or the Git working tree that holds it, so no sync or commit ever picks one up. Checked+ * on the native real path of the file's directory and, when the file exists, of the file itself (a symlink into a checkout).*/export async function assertOutsideSourceRoots(engine: BrainEngine, file: string, flag: string): Promise<string> {const target = resolve(file);let directory: string;- try { directory = realpathSync(dirname(target)); } catch {+ try { directory = realpathSync.native(dirname(target)); } catch {throw opError('invalid_params', `${flag} ${file}: its directory does not exist.`, `Pass a path in an existing directory outside every source's checkout, e.g. under ~/.gbrain.`);}const real = join(directory, target.slice(dirname(target).length + 1));+ let linked = real;+ try { linked = realpathSync.native(real); } catch { /* not written yet */ }const roots = await engine.executeRaw<{ id: string; local_path: string }>('SELECT id, local_path FROM sources WHERE local_path IS NOT NULL');for (const root of roots) {let base: string;- try { base = realpathSync(root.local_path); } catch { base = resolve(root.local_path); }- const inside = relative(base, real);- if (inside === '' || (!inside.startsWith('..') && !inside.startsWith(sep) && !/^[A-Za-z]:/.test(inside))) {- throw opError('conversion_file_in_source_root', `${flag} ${file} is inside source ${root.id}'s root (${root.local_path}), so it was refused: a review or decisions file names pages and must never be synced or committed.`,+ try { base = realpathSync.native(root.local_path); } catch { base = resolve(root.local_path); }+ const top = gitTopLevel(base);+ for (const fence of new Set([base, ...(top ? [top] : [])])) for (const path of new Set([real, linked])) {+ const 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 });}}@@ -245,9 +250,14 @@ export async function readConversionDecisions(engine: BrainEngine, file: string,if (parsed?.kind !== DECISIONS_KIND || parsed.version !== 1) throw bad(`it is not a ${DECISIONS_KIND} file (version 1).`);if (parsed.source_id !== sourceId) throw bad(`it is for source ${String(parsed.source_id)}, not ${sourceId}.`);if (!Array.isArray(parsed.pages)) throw bad('it has no pages list.');+ return decisionEntries(parsed.pages, bad);+}++/** The decided entries of a decisions list (null decisions skipped), each checked for its fields and decided once. */+function decisionEntries(pages: unknown[], bad: (why: string) => OperationError): ConversionDecision[] {const out: ConversionDecision[] = [];const seen = new Set<string>();- for (const entry of parsed.pages as Array<Record<string, unknown>>) {+ for (const entry of pages as Array<Record<string, unknown>>) {if (entry?.decision == null) continue;const { slug, revision, blob, evidence, decision } = entry;if (typeof slug !== 'string' || !(DECISION_VALUES as readonly unknown[]).includes(decision) || !(DIRECTION_EVIDENCE as readonly unknown[]).includes(evidence)@@ -730,7 +740,7 @@ export async function readConversionApproval(engine: BrainEngine, file: string,try { parsed = JSON.parse(readFileSync(real, 'utf8')); } catch { throw bad('it is not JSON.'); }if (parsed?.kind !== APPROVAL_KIND || parsed.version !== 1 || typeof parsed.items !== 'object' || !Array.isArray(parsed.decisions)) throw bad(`it is not a ${APPROVAL_KIND} file (version 1).`);if (parsed.source_id !== sourceId) throw bad(`it is for source ${String(parsed.source_id)}, not ${sourceId}.`);- return parsed;+ return { ...parsed, decisions: decisionEntries(parsed.decisions, bad) };}/** One item of an approved apply that stays unapplied: changed or new since the approval, a discard, or a decision the approval did not hold. */@@ -760,10 +770,17 @@ export async function applyApprovedConversion(engine: BrainEngine, sourceId: strconst progress: ConversionProgress = { phase: 'adopt', groups_committed: 0, scanned: 0, total: partial.adopt.length };const report: ConversionReporter = patch => { Object.assign(progress, patch); opts.onProgress?.({ ...progress }); };const previewCommand = `gbrain sources canonical ${sourceId} --to git --dry-run --approval-out <file>`;- const committed = await adoptGroups(engine, partial, previewCommand, report);- report({ phase: 'withhold', scanned: 0, total: partial.withhold.length });- const withheld = await withholdGroups(engine, partial, previewCommand, groups => report({ scanned: progress.scanned + groups.pages, groups_committed: committed.groups + groups.commits }));- const push = await pushConversion(engine, plan.context);+ const recovery: ConversionRecovery = { mode: plan.preview.strict ? 'git' : 'mixed', phase: 'adopt', commits: [], push: null,+ accepted: { adopted: 0, withheld: 0, holds_cleared: 0, pass_writes: 0 }, reclassified: [], rollback: [] };+ let committed: GitConversionResult['committed'], withheld: GitConversionResult['withheld'], push: ConversionPush;+ try {+ committed = await adoptGroups(engine, partial, previewCommand, report, recovery.commits);+ recovery.accepted.adopted = committed.pages;+ report({ phase: 'withhold', scanned: 0, total: partial.withhold.length });+ withheld = await withholdGroups(engine, partial, previewCommand, groups => report({ scanned: progress.scanned + groups.pages, groups_committed: committed.groups + groups.commits }), recovery.commits);+ recovery.accepted.withheld = withheld.pages;+ push = await pushConversion(engine, plan.context);+ } catch (error) { throw await withRecovery(engine, sourceId, error, recovery, progress); }const by: Record<string, number> = {};for (const item of delta) by[item.reason] = (by[item.reason] ?? 0) + (item.reason.startsWith('discard:') ? plan.preview.discard.by[item.reason.slice(8) as DiscardCategory] : 1);return { status: 'delta', source_id: sourceId, head: plan.preview.head, committed, withheld, holds_cleared: 0, parked: { retried: 0, reclassified: 0 }, push, closing_passes: 0,@@ -813,7 +830,10 @@ async function runConversion(engine: BrainEngine, plan: GitConversionPlan, expecreport({ phase: 'holds', scanned: 0, total: plan.holds.length }); recovery.phase = 'holds';let 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 }))) holdsCleared++;+ 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');+ }+ holdsCleared++;recovery.accepted.holds_cleared = holdsCleared;report({ scanned: progress.scanned + 1 });}@@ -844,16 +864,18 @@ async function runConversion(engine: BrainEngine, plan: GitConversionPlan, expec}return { status: after.remaining === 0 && !binding.reclassified.size ? 'converted' : 'incomplete', source_id: sourceId, head: after.head, committed, withheld, holds_cleared: holdsCleared, parked, push,closing_passes: closing, after, reclassified: [...binding.reclassified].sort() };- } catch (error) {- if (error && typeof error === 'object') {- recovery.phase = progress.phase;- recovery.mode = (await engine.executeRaw<{ strict: boolean }>("SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1", [sourceId]).catch(() => []))[0]?.strict ? 'git' : recovery.mode;- recovery.push ??= progress.push ?? null;- recovery.rollback = conversionRollback(sourceId, recovery.mode);- Object.defineProperty(error, RECOVERY, { value: recovery, configurable: true });- }- throw error;- }+ } catch (error) { throw await withRecovery(engine, sourceId, error, recovery, progress); }+}++/** A failed apply's error with its recovery report attached: where it stopped, the mode it left, its commits and the rollback. */+async function withRecovery(engine: BrainEngine, sourceId: string, error: unknown, recovery: ConversionRecovery, progress: ConversionProgress): Promise<unknown> {+ if (!error || typeof error !== 'object') return error;+ recovery.phase = progress.phase;+ recovery.mode = (await engine.executeRaw<{ strict: boolean }>("SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1", [sourceId]).catch(() => []))[0]?.strict ? 'git' : recovery.mode;+ recovery.push ??= progress.push ?? null;+ recovery.rollback = conversionRollback(sourceId, recovery.mode);+ Object.defineProperty(error, RECOVERY, { value: recovery, configurable: true });+ return error;}/**diff --git a/src/core/persistence/git-gap.ts b/src/core/persistence/git-gap.tsindex 6c9bded850..9133b329e7 100644--- a/src/core/persistence/git-gap.ts+++ b/src/core/persistence/git-gap.ts@@ -186,9 +186,14 @@ function gitLine(root: string, args: string[]): string | null {return result.ok ? result.stdout.toString('utf8').replace(/\n$/, '') : null;}-/** Whether `root` is inside a Git working tree (hardened `rev-parse --show-toplevel`). */+/** The top level of the Git working tree `root` is inside (hardened `rev-parse --show-toplevel`); null outside one. */+export function gitTopLevel(root: string): string | null {+ return gitLine(root, ['rev-parse', '--show-toplevel']);+}++/** Whether `root` is inside a Git working tree. */export function isGitCheckout(root: string): boolean {- return gitLine(root, ['rev-parse', '--show-toplevel']) !== null;+ return gitTopLevel(root) !== null;}/**@@ -285,7 +290,7 @@ export async function worktreeBlobOid(path: string, format: ObjectFormat): Promiexport const DIRECTION_EVIDENCE = ['adopt_db_moved', 'git_wins_file_moved', 'both_moved', 'no_evidence'] as const;export type DirectionEvidence = typeof DIRECTION_EVIDENCE[number];export type EvidenceBasis = 'older_version_matches_file' | 'row_matches_older_file' | 'conflicting_history' | 'shared_older_state' | 'no_shared_state'- | 'segmented' | 'history_unreadable' | 'changed_during_read';+ | 'segmented' | 'history_unreadable' | 'changed_during_read' | 'history_truncated';/** Versions and blobs compared per page, newest first. */export const EVIDENCE_DEPTH = 32;/** Pages whose versions, export views and blobs one evidence read holds at a time. */@@ -352,15 +357,28 @@ export async function readBlobSizes(root: string, oids: readonly string[]): Prom/*** The direction pure decision: `row` and `head` are the canonical digests of the page's export view and of its file at* the tip (null when the file does not parse), `versions` the page's older versions and `blobs` the path's older blobs- * (the tip's excluded), each newest first with its digest (null when it does not parse).+ * (the tip's excluded), each newest first with its digest (null when it does not parse); `capped` says a list reached+ * EVIDENCE_DEPTH, so older entries exist that were not read.+ *+ * A one-sided verdict needs the matched state to be the newest state both sides shared. The row equals an older blob+ * (only the file moved) unless a state newer than that blob was shared with an older version that differs from the row:+ * then the database left it too (a revert to the row's content is a move). The mirror holds for the file equal to an+ * older version. When the other side's list is capped, a newer shared state may lie past it, so the verdict is no_evidence.*/export function decideDirection(row: string, head: string | null, versions: ReadonlyArray<{ id: number; digest: string }>,- blobs: ReadonlyArray<{ oid: string; digest: string | null }>): Pick<Evidence, 'kind' | 'basis' | 'blob' | 'version'> {- const fileMoved = blobs.find(blob => blob.digest === row);- const databaseMoved = head === null ? undefined : versions.find(version => version.digest === head);- if (fileMoved && databaseMoved) return { kind: 'both_moved', basis: 'conflicting_history', blob: fileMoved.oid, version: databaseMoved.id };- if (fileMoved) return { kind: 'git_wins_file_moved', basis: 'row_matches_older_file', blob: fileMoved.oid, version: null };- if (databaseMoved) return { kind: 'adopt_db_moved', basis: 'older_version_matches_file', blob: null, version: databaseMoved.id };+ blobs: ReadonlyArray<{ oid: string; digest: string | null }>, capped: { versions: boolean; blobs: boolean } = { versions: false, blobs: false }): Pick<Evidence, 'kind' | 'basis' | 'blob' | 'version'> {+ const fileAt = blobs.findIndex(blob => blob.digest === row);+ const databaseAt = head === null ? -1 : versions.findIndex(version => version.digest === head);+ const fileMoved = fileAt >= 0 ? blobs[fileAt]! : undefined, databaseMoved = databaseAt >= 0 ? versions[databaseAt]! : undefined;+ const sharedNewerThanBlob = fileAt >= 0 && blobs.slice(0, fileAt).some(blob => blob.digest !== null && blob.digest !== row && versions.some(version => version.digest === blob.digest));+ const sharedNewerThanVersion = databaseAt >= 0 && versions.slice(0, databaseAt).some(version => version.digest !== head && blobs.some(blob => blob.digest === version.digest));+ if ((fileMoved && databaseMoved) || sharedNewerThanBlob || sharedNewerThanVersion) {+ return { kind: 'both_moved', basis: 'conflicting_history', blob: fileMoved?.oid ?? null, version: databaseMoved?.id ?? null };+ }+ if (fileMoved) return capped.versions ? { kind: 'no_evidence', basis: 'history_truncated', blob: fileMoved.oid, version: null }+ : { kind: 'git_wins_file_moved', basis: 'row_matches_older_file', blob: fileMoved.oid, version: null };+ if (databaseMoved) return capped.blobs ? { kind: 'no_evidence', basis: 'history_truncated', blob: null, version: databaseMoved.id }+ : { kind: 'adopt_db_moved', basis: 'older_version_matches_file', blob: null, version: databaseMoved.id };const digests = new Map<string, string>();for (const blob of blobs) if (blob.digest !== null && !digests.has(blob.digest)) digests.set(blob.digest, blob.oid);const shared = versions.find(version => digests.has(version.digest));@@ -396,14 +414,14 @@ export async function readDirectionEvidence(engine: BrainEngine, input: { sourceif (!rel.startsWith('../') && target.startsWith(root + sep)) paths.get(origin.page_id)?.add(gitPath(rel));} catch (error) { if (!(error instanceof RestoreTargetError)) throw error; }}- const history = await readPathHistory(root, tip, scope, new Set([...paths.values()].flatMap(set => [...set])));+ const history = await readPathHistory(input.gitRoot, tip, scope, new Set([...paths.values()].flatMap(set => [...set])));const none = (basis: EvidenceBasis, committed_at: number | null = null): Evidence => ({ kind: 'no_evidence', basis, blob: null, version: null, versions: 0, blobs: 0, committed_at });if (!history) { for (const subject of subjects) out.set(subject.id, none('history_unreadable')); return out; }const older = (subject: EvidenceSubject) => {const merged = [...paths.get(subject.id)!].flatMap(path => history.get(path) ?? []).sort((a, b) => a.seq - b.seq);const seen = new Set<string>([subject.blob.oid]), list: HistoryEntry[] = [];for (const entry of merged) if (!seen.has(entry.oid) && list.length < EVIDENCE_DEPTH) { seen.add(entry.oid); list.push(entry); }- return { list, committed_at: merged[0]?.at ?? null };+ return { list, committed_at: merged[0]?.at ?? null, capped: list.length >= EVIDENCE_DEPTH || [...paths.get(subject.id)!].some(path => (history.get(path)?.length ?? 0) > EVIDENCE_DEPTH) };};const withdrawals = await readExportWithdrawals(engine, sourceId);for (let start = 0; start < subjects.length; start += EVIDENCE_BATCH) {@@ -451,7 +469,7 @@ export async function readDirectionEvidence(engine: BrainEngine, input: { sourcefrom = to;}for (const [i, subject] of read.current.entries()) {- const { list, committed_at } = older(subject);+ const { 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 }@@ -463,7 +481,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 })));+ 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 });out.set(subject.id, { ...decided, versions: versions.length, blobs: list.length, committed_at });}}diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 00296f85dd..bf8d3a277c 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -1087,7 +1087,8 @@ async function confirmPages(exec: Exec, input: { kind: 'postgres' | 'pglite'; sofunction bindConversion(paths: ShadowPath[], scope: string, binding: ConversionBinding): void {for (const [i, entry] of paths.entries()) {const r = entry.result;- if (!r.gitWins || r.settled || r.inFlight || (r.action !== 'import' && r.action !== 'delete')) continue;+ const gitWins = r.gitWins ?? (r.cls === 'held' && r.action === 'import' ? classifySyncPath({ ...entry.state, hold: null }, { strict: true }).gitWins : undefined);+ if (!gitWins || r.settled || r.inFlight || (r.action !== 'import' && r.action !== 'delete')) continue;const path = scope && entry.path.startsWith(`${scope}/`) ? entry.path.slice(scope.length + 1) : entry.path;const expected = binding.expect.get(path);if (expected && String(entry.pageId) === expected.id && (entry.revision ?? null) === expected.revision && (expected.blob === undefined || (entry.state.level ?? null) === expected.blob)) continue;diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex e82a42ae81..1f692fdccd 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6832,7 +6832,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/git-canonical-conversion-evidence-d4.test.ts b/test/git-canonical-conversion-evidence-d4.test.tsindex 9ceda3f016..f33a4a880e 100644--- a/test/git-canonical-conversion-evidence-d4.test.ts+++ b/test/git-canonical-conversion-evidence-d4.test.ts@@ -13,6 +13,7 @@ import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { applyApprovedConversion, applyGitConversion, applyMixedConversion, conversionApproval, conversionRecovery, conversionReviewList, planGitConversion,planMixedConversion, readConversionApproval, readConversionDecisions, writeConversionFile, type ConversionDecision } from '../src/core/persistence/git-conversion.ts';@@ -148,6 +149,57 @@ for (const backend of testBackends()) describe(`[${backend}] conversion by conte} finally { files.done(); }}, { databaseUrl, setup }), 240_000);+ const staleHold = async (engine: BrainEngine, incarnation: string, slug: string) => {+ const [page] = await engine.executeRaw<{ id: string }>("SELECT id::text FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation, path: `${slug}.md`, source_path: `${slug}.md`, slug, page_id: Number(page!.id),+ code: 'concurrent_write', message: 'A write moved the page during the pass.', upstream_version: '0'.repeat(64), observed_at: new Date().toISOString(),+ run_id: null, mode: 'managed', meta: { recovery_version: 1, blob_oid: '0'.repeat(40) } }));+ };++ test('item 3: a hold written after the plan over a page that moved since is bound, so its re-run never imports over the database', () => managedBrain(async brain => {+ const { engine } = brain;+ const files = outside();+ try {+ await evidenceSource(brain);+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });+ const plan = await planGitConversion(engine, 'default', { decisions });+ installFaultHook(async point => {+ if (point !== 'conversion:after_recheck') return;+ await databaseOnlyEdit(engine, 'notes/file', 'A racing database write under a hold.');+ await staleHold(engine, plan.incarnation, 'notes/file');+ });+ let error: unknown;+ try { await applyGitConversion(engine, 'default', plan.preview.preview_hash, { ...PROCESSING, decisions }); } catch (caught) { error = caught; } finally { installFaultHook(undefined); }+ expect(error).toMatchObject({ code: 'git_conversion_incomplete', detail: 'changed_since_preview' });+ expect(await body(engine, 'notes/file')).toBe('A racing database write under a hold.');+ expect(conversionRecovery(error)).toMatchObject({ mode: 'mixed', reclassified: ['notes/file.md'] });+ expect(await strict(engine)).toBe(false);+ } finally { files.done(); }+ }, { databaseUrl, setup }), 240_000);++ test('item 3: a planned hold another run replaced after the plan stops the apply before any strict pass', () => managedBrain(async brain => {+ const { engine } = brain;+ const files = outside();+ try {+ await evidenceSource(brain);+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });+ await staleHold(engine, (await planGitConversion(engine, 'default')).incarnation, 'notes/same');+ const plan = await planGitConversion(engine, 'default', { decisions });+ expect(plan.holds.map(hold => hold.path)).toEqual(['notes/same.md']);+ installFaultHook(async point => {+ if (point !== 'conversion:after_recheck') return;+ await new Promise(resolve => setTimeout(resolve, 5));+ await staleHold(engine, plan.incarnation, 'notes/same');+ });+ let error: unknown;+ try { await applyGitConversion(engine, 'default', plan.preview.preview_hash, { ...PROCESSING, decisions }); } catch (caught) { error = caught; } finally { installFaultHook(undefined); }+ expect(error).toMatchObject({ code: 'git_conversion_incomplete', detail: 'changed_since_preview' });+ expect(conversionRecovery(error)).toMatchObject({ mode: 'mixed', phase: 'holds' });+ expect(await strict(engine)).toBe(false);+ expect(await holds(engine)).toContain('notes/same.md');+ } finally { files.done(); }+ }, { databaseUrl, setup }), 240_000);+test('item 6: a failure after the flip reports the mode, commits, push and writes, and the rollback keeps the adopted pages\' live content', () => managedBrain(async brain => {const { engine, root } = brain;const files = outside();@@ -210,6 +262,30 @@ for (const backend of testBackends()) describe(`[${backend}] conversion by conte} finally { files.done(); }}, { databaseUrl, setup }), 240_000);+ test('item 6: a partial approved apply that fails after a commit reports that commit; an approval\'s decisions are checked like a decisions file', () => managedBrain(async brain => {+ const { engine, root } = brain;+ const files = outside();+ try {+ await evidenceSource(brain);+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });+ const approval = conversionApproval(await planGitConversion(engine, 'default', { decisions }));+ const twice = join(files.dir, 'twice.json');+ await writeConversionFile(engine, twice, '--approval-out', { ...approval, decisions: [...approval.decisions, approval.decisions[0]] });+ await expect(readConversionApproval(engine, twice, 'default')).rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('decided twice') });++ writeFileSync(join(root, 'notes/db.md'), note('notes/db', 'A commit that landed after the approval.'));+ git(root, 'commit', '-qam', 'a commit after the approval');+ const base = git(root, 'rev-parse', 'HEAD');+ installFaultHook(async point => { if (point === 'conversion:group_committed') throw new Error('injected after the first group'); });+ let error: unknown;+ try { await applyApprovedConversion(engine, 'default', approval, PROCESSING); } catch (caught) { error = caught; } finally { installFaultHook(undefined); }+ expect(error).toMatchObject({ message: 'injected after the first group' });+ expect(conversionShas(root, base)).toHaveLength(1);+ expect(conversionRecovery(error)).toMatchObject({ mode: 'mixed', phase: 'adopt', commits: conversionShas(root, base), rollback: [] });+ expect(await strict(engine)).toBe(false);+ } finally { files.done(); }+ }, { databaseUrl, setup }), 240_000);+test('item 7: an approval nothing moved under applies whole, as its hash would', () => managedBrain(async brain => {const { engine } = brain;const files = outside();diff --git a/test/git-gap-direction-evidence-d4.test.ts b/test/git-gap-direction-evidence-d4.test.tsindex 03f73cd9a3..253d253b7d 100644--- a/test/git-gap-direction-evidence-d4.test.ts+++ b/test/git-gap-direction-evidence-d4.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -8,6 +8,7 @@ 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 { 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';import { dbAheadOfGitEntry } from '../src/commands/doctor/checks/db-ahead-of-git.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -40,6 +41,18 @@ describe('decideDirection (d4 classifier)', () => {expect(decideDirection('row', 'head', [v(2, 'x')], [b('o1', 'y')])).toMatchObject({ kind: 'no_evidence', basis: 'no_shared_state' });expect(decideDirection('row', null, [v(2, 'x')], [b('o1', null)])).toMatchObject({ kind: 'no_evidence' });});+ test('a revert on one side is a move: the newest shared state decides, not any older match', () => {+ expect(decideDirection('A', 'C', [v(3, 'B'), v(2, 'A')], [b('oB', 'B'), b('oA', 'A')])).toMatchObject({ kind: 'both_moved', basis: 'conflicting_history' });+ expect(decideDirection('C', 'A', [v(3, 'B'), v(2, 'A')], [b('oB', 'B'), b('oA', 'A')])).toMatchObject({ kind: 'both_moved', basis: 'conflicting_history' });+ expect(decideDirection('B', 'C', [v(3, 'B'), v(2, 'A')], [b('oB', 'B'), b('oA', 'A')])).toMatchObject({ kind: 'git_wins_file_moved', blob: 'oB' });+ expect(decideDirection('C', 'B', [v(4, 'C'), v(3, 'B'), v(2, 'A')], [b('oA', 'A')])).toMatchObject({ kind: 'adopt_db_moved', version: 3 });+ });+ test('a one-sided verdict needs the other side read in full', () => {+ const full = { versions: false, blobs: false };+ expect(decideDirection('row', 'head', [v(2, 'older')], [b('o1', 'row')], { ...full, versions: true })).toMatchObject({ kind: 'no_evidence', basis: 'history_truncated' });+ expect(decideDirection('row', 'head', [v(2, 'head')], [b('o1', 'older')], { ...full, blobs: true })).toMatchObject({ kind: 'no_evidence', basis: 'history_truncated' });+ expect(decideDirection('row', 'head', [v(2, 'older')], [b('o1', 'row')], { ...full, blobs: true })).toMatchObject({ kind: 'git_wins_file_moved' });+ });});for (const backend of testBackends()) describe(`git-gap direction evidence (d4): ${backend}`, () => {@@ -130,6 +143,34 @@ for (const backend of testBackends()) describe(`git-gap direction evidence (d4):expect(done!.message).toContain('default: 7 live page(s), 7 equal');}, 120000);+ test('a source nested in a larger repository reads its history, and a database revert under a Git edit is both_moved', async () => {+ const top = tempDir('git-gap-nested-'), root = join(top, 'brain');+ git(top, 'init', '-q');+ put(top, 'README.md', 'outside the source\n');+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ const write = async (slug: string, text: string) => { put(root, `${slug}.md`, (await rendered(slug)).replace(/Body [ABC]\./, text)); };+ for (const slug of ['notes/file-moved', 'notes/reverted']) { await body(slug, 'Body A.'); await write(slug, 'Body A.'); }+ commitAll(top, 'first');+ await engine.createVersion('notes/reverted'); await body('notes/reverted', 'Body B.'); await write('notes/reverted', 'Body B.');+ commitAll(top, 'both sides to B');+ await engine.createVersion('notes/reverted'); await body('notes/reverted', 'Body A.');+ await write('notes/reverted', 'Body C.'); await write('notes/file-moved', 'Body C.');+ commitAll(top, 'git edits after the database revert');+ const pages: GitGapPage[] = [];+ await censusGitGap(engine, 'default', { sample: 0, evidence: true, collect: page => { pages.push(page); } });+ const bySlug = Object.fromEntries(pages.map(page => [page.slug, page]));+ expect(bySlug['notes/file-moved']).toMatchObject({ state: 'git_ahead', evidence: { kind: 'git_wins_file_moved', basis: 'row_matches_older_file' } });+ expect(bySlug['notes/reverted']).toMatchObject({ evidence: { kind: 'both_moved', basis: 'conflicting_history' } });++ // A review or decisions file is refused anywhere in the Git working tree that holds the source, and through a symlink into it.+ await expect(writeConversionFile(engine, join(top, 'review.json'), '--list-out', {})).rejects.toMatchObject({ code: 'conversion_file_in_source_root' });+ const outside = tempDir('git-gap-files-');+ put(root, 'decisions.json', '{}');+ symlinkSync(join(root, 'decisions.json'), join(outside, 'decisions.json'));+ await expect(readConversionDecisions(engine, join(outside, 'decisions.json'), 'default')).rejects.toMatchObject({ code: 'conversion_file_in_source_root' });+ expect(await writeConversionFile(engine, join(outside, 'review.json'), '--list-out', {})).toBe(join(outside, 'review.json'));+ }, 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 });