Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 1 lane B review: file_drift refuses under sync.holds=fail; lost manifest walks HEAD's tree; kernel rechecks the parser fingerprint; oversized working copy falls through
garrytan5b2b3c412763
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 424bc93122..7c085556f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,7 +14,7 @@ identifiers and attribution are available in the pre-removal Git revision- **#6712 PR 1 (lane B): content-addressed resume.** Discovery prescreens each existing page against its import provenance (bytes on disk, the revision the import wrote, the parser fingerprint) with one `ls-tree`; a match is passed by the guarded no-op kernel's bounded checks in one transaction, with no freeze or preparation. A no-change tree walk of a 2,000-page fixture dropped from 10.5 s to 0.9 s (PGLite) and 9.1 s to 0.8 s (local Postgres). Receipts carry `prescreened`. Code, image, file-repair and published no-op publishes now write full provenance.- **#6712 PR 1 (lane B): `file_drift`.** A managed sync no longer imports a file over a database version of its page that sync never saw (the page moved since the file's last recorded import, or, in a tree walk, has no usable record on an upgraded brain); the file is held `file_drift` unless the import is a proven no-op or a sync request wrote the current revision. `gbrain repair file-drift` is the exit; `storage.keep_db` prefixes go to the keep_db worker instead of a hold.-- **#6712 PR 1 (lane B): a lost manifest re-discovers against HEAD** on the next sync instead of stopping with `storage_error`.+- **#6712 PR 1 (lane B): a lost manifest re-discovers the whole tree at HEAD** on the next sync instead of stopping with `storage_error`, so a file the lost run imported and HEAD later reverted is restored.## [0.60.248.0] - 2026-10-15diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 85759d5831..11c63446c3 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -187,7 +187,7 @@ with each file and fix the ones that need no guessing."*| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. || <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |-| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing or a sync request wrote its current revision. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |+| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing or a sync request wrote its current revision. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. || <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. || <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). || <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. Since 0.60.179.0 (#6513) the same hold covers a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: that refusal used to block the cursor with no exit, because `--retry-failed` replays the same pin against the same bytes, `sources refresh` refuses `sync_in_progress` on the unfinished cursor and `--acknowledge-managed` refuses `cursor_unfinished`. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are not a conflict either: the page imports and the file is left as it is. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5e5ee2e27f..a6c070d565 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -629,8 +629,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.242.0', text: 'A chunk vector is now tied to the chunk\'s text and its full embedding input rather than its position. When an edit inserts or removes chunks above it, a projection rebuild moves the unchanged chunk to its new index with its vector instead of dropping it, so only new or changed chunks wait for embedding. An embed that finishes after the page changed now commits the vectors of the chunks that are still the same (same text, source and embedding input) and leaves the rest for the next run, instead of discarding the whole run; the page\'s embedding signature is stamped only when every chunk got its vector. A vector built under an old title or synopsis is still dropped.' },// #6712 PR 1 lane B (prescreen, file_drift, lost-manifest re-discovery); `since` is a placeholder until the merge-slot stamp.{ since: '0.60.249.0', text: 'A managed sync now skips a file whose import provenance matches it (same bytes on disk, the page still at the revision that import wrote, the same parser) without preparing it: discovery prescreens it and the guarded no-op checks pass it in one transaction. Sync receipts carry a `prescreened` count. A no-change tree walk of 2,000 pages dropped from about 10 s to under 1 s. `--full` bypasses the prescreen.' },- { since: '0.60.249.0', text: 'A managed sync no longer imports a file over a database version of its page that sync never saw. When the page changed since its file was last imported (or, in a tree walk such as a first sync, `--full` or an unreachable checkpoint, has no usable import record) and the import would change it, the file is held with the new code `file_drift` and the page keeps the database version; `gbrain repair file-drift --prefer database|file` resolves it. Pages under `storage.keep_db` prefixes are not held: the keep_db worker reconciles them from the database. These holds never escalate.' },- { since: '0.60.249.0', text: 'A managed sync whose frozen manifest is missing no longer stops with `storage_error` until an explicit `--retry-failed`: the next sync re-discovers against HEAD and finishes, skipping what the lost run already imported. Dry runs and company-brain sources keep the refusal.' },+ { since: '0.60.249.0', text: 'A managed sync no longer imports a file over a database version of its page that sync never saw. When the page changed since its file was last imported (or, in a tree walk such as a first sync, `--full` or an unreachable checkpoint, has no usable import record) and the import would change it, the file is held with the new code `file_drift` and the page keeps the database version; `gbrain repair file-drift --prefer database|file` resolves it. Pages under `storage.keep_db` prefixes are not held: the keep_db worker reconciles them from the database. These holds never escalate; with `sync.holds=fail` the run stops with `file_drift` instead.' },+ { since: '0.60.249.0', text: 'A managed sync whose frozen manifest is missing no longer stops with `storage_error` until an explicit `--retry-failed`: the next sync re-discovers the whole tree at HEAD and finishes, skipping what the lost run already imported. Dry runs and company-brain sources keep the refusal.' },// #6712 PR 0 (#6694 + write-only provenance); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.248.0', text: 'A managed sync of a source rooted at its Git repository root now checkpoints whichever `slug_root_mode` the source pins (both modes give it the same slugs) and keeps that pin; before, a `source-root` pin failed every checkpoint with `revision_conflict`. A plain `gbrain sync --no-pull --source <id>` now finishes a checkpoint that already failed this way. On a source in a subdirectory, a pin that changes while a sync runs is refused as `slug_root_mode_mismatch` (a person chooses the mode) instead of `revision_conflict`; restoring the pin lets the next plain sync finish. After a downgrade, an older gbrain reports these as `revision_conflict` again.' },{ since: '0.60.248.0', text: 'Managed-sync import provenance now also records the bytes each publish left on disk (`disk_sha256`, `disk_blob_oid`: the canonical writeback when sync rewrote the file), the page revision it produced and what parsed it (import parser version, Markdown chunker, schema pack), and a sync that skips an unchanged file records the same. Nothing reads these yet; a later release uses them to skip unchanged files. Records written before this release lack them and are replaced on the next import of their page; an older gbrain ignores them.' },diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex cc591f21f2..25a6c37b26 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -263,12 +263,12 @@ function cutDiscoveryToSlice(discovered: SyncDiscovery, slicing: Pick<SyncSliceCif (cut.done && discovered.target === head) delete discovered.stagedHead; else discovered.stagedHead = head;}export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, context?: ManagedSyncContext,- stage?: { target: string; head: string; slice?: Pick<SyncSliceCursor, 'phase' | 'after'> }): Promise<SyncDiscovery> {+ stage?: { target: string; head: string; slice?: Pick<SyncSliceCursor, 'phase' | 'after'> }, walk = false): Promise<SyncDiscovery> {const { binding, root, gitRoot, sourceId, incarnation, source } = context ?? await resolveManagedSyncContext(engine, opts);const company = currentCompanyBrainSync(sourceId);if (!company && !stage && !opts.dryRun) {const resume = await resumableSliceStage(engine, opts, gitRoot, sourceId, incarnation);- if (resume) return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, resume);+ if (resume) return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, resume, walk);}const strategy = opts.strategy ?? source.config?.strategy ?? 'markdown';const nativeRoot = realpathSync.native(root), nativeGitRoot = realpathSync.native(gitRoot);@@ -292,7 +292,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c// #6349: a staged run stops at a commit, so uncommitted working-tree changes wait for the stage that reaches HEAD.const working = !company && !stage && (detached || (opts.workingTree ?? (await engine.getConfig('sync.include_working_tree') === 'true')));const dirty = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitRoot);- const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;+ const delta = !opts.full && !walk && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;const entries = new Map<string, SyncEntry>();const renamedFrom = new Map<string, string>();let workingTreeKept: string[] | undefined;@@ -445,7 +445,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c`This sync of ${sourceId} selected ${selected.length} entries, above the 100,000-entry and 16 MiB cursor bound; nothing was written. Narrow it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);// #6349 (P4.4): a first sync or a `--full` tree walk has no commit axis to stage on; the target is cut into path slices// (re-entered as a stage so the slices read the pinned tree alone, never the working tree).- return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, { target, head, slice: { phase: 'import', after: null } });+ return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, { target, head, slice: { phase: 'import', after: null } }, walk);}const discovered: SyncDiscovery = { discoveredAt, ...(released.length ? { releasedHolds: released } : {}), ...(retryTaken.length ? { retryTaken } : {}),...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}), ...(stage ? { stagedHead: stage.head } : {}),diff --git a/src/core/persistence/sync-prescreen.ts b/src/core/persistence/sync-prescreen.tsindex 9a463ea906..ff6e793079 100644--- a/src/core/persistence/sync-prescreen.ts+++ b/src/core/persistence/sync-prescreen.ts@@ -39,7 +39,8 @@ export type SyncDriftSide = 'database' | 'both' | 'unknown';/** Provenance rows read per statement. */const PROVENANCE_CHUNK = 5000;-const sameParser = (a: SyncImportParser | null | undefined, b: SyncImportParser) => !!a && a.parser_version === b.parser_version+/** Whether a recorded parser fingerprint is this binary's for the page (the prescreen and its kernel run both check it). */+export const sameParser = (a: SyncImportParser | null | undefined, b: SyncImportParser) => !!a && a.parser_version === b.parser_version&& a.markdown_chunker === b.markdown_chunker && (a.schema_pack ?? null) === b.schema_pack;/** The drift side of one entry from its record and pinned blob, or null when nothing needs guarding (`prescreened`: a kernel candidate). */diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 95fae43cf7..5c8291f098 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -441,10 +441,10 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass}}// #6712 PR 1: an import whose page moved since its file was last imported runs only as a proven no-op (sync-prescreen.ts).- if (entry.drift && holdsOn && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page)+ if (entry.drift && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page): await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {- const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null });- assertActive();+ if (!holdsOn) throw syncRunRefusal('file_drift', 'An import would overwrite a database version of the page that sync never saw.', retry, `Page ${slug} in source ${cursor.sourceId} changed in the database since ${entry.path} was last imported, and the file differs from it, so the run stopped before admitting it (sync.holds=fail).`);+ const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null }); assertActive();return { hold: fileDriftHold(entry, slug, pageId, frozenIntent, { sides: entry.drift, revision: snapshot.revision, proof }) };}if (screening && !image) {@@ -1012,7 +1012,7 @@ async function prescreenRun(engine: BrainEngine, cursor: Cursor, key: string, ruconst entries = prescreenedHead(cursor.entries, cursor.index, run.missed, run.limit);if (!entries.length || cursor.pending) return null;stampDrainStep('waiver_run', run.signal);- const done = await waivePrescreenedRun(engine, cursor, entries, key, { embeddingRequested: run.embeddingRequested }, (tx, count) => {+ const done = await waivePrescreenedRun(engine, cursor, entries, key, { embeddingRequested: run.embeddingRequested, noSchemaPack: !!cursor.processingOptions?.noSchemaPack }, (tx, count) => {let next: Cursor = cursor;for (let i = 0; i < count; i++) next = waivedCursor(next, { kind: 'import', kernel: [] });return writeCursor(tx, key, cursor, { ...next, counts: { ...next.counts, prescreened: (cursor.counts.prescreened ?? 0) + count },@@ -1474,8 +1474,8 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPcatch (error) {if (!(error instanceof MissingSyncManifest) || opts.dryRun || company) throw error;missingManifestCursor = error.cursor; phase = 'discovery'; discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();- // #6712 PR 1 (L1): a lost manifest re-discovers against HEAD; the prescreen passes what the lost run imported, so the old cursor is a skip-ahead.- const replaced = await replaceCursor(engine, key, error.cursor, { ...await discoverManagedSync(engine, opts, context), authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);+ // #6712 PR 1 (L1): a lost manifest re-discovers HEAD's whole tree (the lost run may have imported files last_commit..HEAD no longer names); the prescreen passes what it imported.+ const replaced = await replaceCursor(engine, key, error.cursor, { ...await discoverManagedSync(engine, opts, context, undefined, true), authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);if ('wait' in replaced) return { ...result(error.cursor, 'partial', 'writer_pending'), ...(authority.writer.remote ? {} : { retryWait: replaced.wait }) };cursor = replaced;}diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex b909c7965c..3d6646fb93 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -9,7 +9,10 @@ import { join } from 'node:path';import type { BrainEngine, PageSnapshot } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';-import { heldGitPaths, readSyncImportProvenances, recordSyncImportProvenances, syncDiskProvenance, type SyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';+import { heldGitPaths, readSyncImportProvenances, syncImportParserFor, recordSyncImportProvenances, syncDiskProvenance, type SyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';+import { sameParser } from './sync-prescreen.ts';+import { isSyncReadBound } from './sync-screen.ts';+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { sha256 } from './digest.ts';import { startClaimPhase } from './claim-phase.ts';import { inspectUnchanged, KERNEL_PAGE_SQL, kernelPageWork, screeningRequest, type KernelPage, type NoopKernelWaiver } from './noop-kernel.ts';@@ -264,10 +267,12 @@ export function prescreenedHead(entries: ReadonlyArray<SyncEntry>, index: number* caller imports that entry through the ordinary path. Only this run skips durably; the prescreen never does.*/export async function waivePrescreenedRun<C extends WaiverCursor & { binding: { owner_epoch: string | number } }>(engine: BrainEngine, cursor: C,- run: readonly PrescreenedEntry[], key: string, input: { embeddingRequested: boolean },+ run: readonly PrescreenedEntry[], key: string, input: { embeddingRequested: boolean; noSchemaPack: boolean },advance: (tx: BrainEngine, count: number) => Promise<C>, reread: (tx: BrainEngine) => Promise<C>): Promise<{ cursor: C; waived: number } | null> {if (!run.length || !noopWaiversEnabled()) return null;for (let i = 0; i < run.length; i += 16) await Promise.all(run.slice(i, i + 16).map(entry => validateSyncAuthority(engine, cursor.authority, entry.slug)));+ // A cursor frozen by another binary or under another schema pack re-checks the parser fingerprint its prescreen matched.+ const pack = input.noSchemaPack ? null : await loadActivePackForEngine(engine, { remote: false, sourceId: cursor.sourceId }).catch(() => null);try {return await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('lock_timeout','2s',true),set_config('statement_timeout','10s',true)");@@ -292,8 +297,9 @@ export async function waivePrescreenedRun<C extends WaiverCursor & { binding: {const page = pages.get(entry.slug), record = records.get(entry.pageId);if (!page || Number(page.id) !== entry.pageId || page.knowledge_revision !== entry.revision || unfinished[i]!.length || holds.has(entry.path)) break chunks;if (kernelPageWork(page, { sourcePath: entry.sourcePath, embeddingRequested: input.embeddingRequested }) !== null) break chunks;- if (!record?.disk_sha256 || record.revision !== entry.revision) break chunks;- const bytes = readSyncFile(cursor.root, entry.path);+ if (!record?.disk_sha256 || record.revision !== entry.revision || !sameParser(record.parser, syncImportParserFor(entry.sourcePath, pack?.identity ?? null))) break chunks;+ let bytes: Buffer | null;+ try { bytes = readSyncFile(cursor.root, entry.path); } catch (error) { if (isSyncReadBound(error)) break chunks; throw error; }if (!bytes || sha256(bytes) !== record.disk_sha256) break chunks;valid++;}diff --git a/test/sync-prescreen-drift-6712.test.ts b/test/sync-prescreen-drift-6712.test.tsindex eac8ad75de..94a18b689f 100644--- a/test/sync-prescreen-drift-6712.test.ts+++ b/test/sync-prescreen-drift-6712.test.ts@@ -14,6 +14,9 @@* equal-content controls (no edit, an unattributed revision whose content equals the file, a changed file on a page* sync wrote last) still skip or import as before;* - a cursor whose manifest is gone re-discovers against HEAD and finishes, the pages the lost run imported prescreened.+ * - review follow-ups: `sync.holds=fail` refuses the drift with `file_drift`; a lost manifest walks HEAD's whole tree (a+ * file the lost run imported and HEAD reverted is restored, a page it added is removed); a fingerprint that changes+ * after discovery and an oversized working copy each fall through to the ordinary path.** Each test fails on the base: there `prescreened` is absent, the tree walk overwrites the database edit, and the* missing manifest stops the run with `storage_error`.@@ -30,6 +33,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { readGitHold, readSyncImportProvenance, SYNC_IMPORT_PARSER_VERSION, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';import { readDriftSkips } from '../src/core/persistence/drift-conflicts.ts';+import { SYNC_READ_BOUND } from '../src/core/persistence/sync-blobs.ts';import { managedBrain } from './helpers/managed-brain.ts';import { waitFor } from './helpers/wait-for.ts';@@ -107,6 +111,28 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect(full).toMatchObject({ prescreened: 0, waived: { imports: SLUGS.length } });}, { databaseUrl, setup }), 180_000);+ test('a fingerprint that changes after discovery froze the prescreen falls through to the ordinary path', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ rewriteHistory(root);+ // One page per slice: the kernel passes notes/a and the rest of the frozen manifest waits, still marked prescreened.+ expect(await performManagedSync(engine, OPTS, { maxPages: 1, maxMs: 60_000 })).toMatchObject({ status: 'partial', prescreened: 1 });+ // As if another binary (another parser) resumed the cursor.+ for (const slug of SLUGS.slice(1)) await tamper(engine, slug, [['parser,parser_version', 'an-older-parser']]);+ expect(await performManagedSync(engine, OPTS)).toMatchObject({ status: 'synced', prescreened: 1 });+ const incarnation = await incarnationOf(engine);+ for (const slug of SLUGS.slice(1)) expect((await readSyncImportProvenance(engine, 'default', incarnation, await pageIdOf(engine, slug)))?.parser?.parser_version).toBe(SYNC_IMPORT_PARSER_VERSION);+ }, { databaseUrl, setup }), 180_000);++ test('an oversized working copy of a prescreened file falls through to the ordinary path instead of failing the run', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ rewriteHistory(root);+ writeFileSync(join(root, 'notes/a.md'), Buffer.alloc(SYNC_READ_BOUND + 1, 'a'));+ const walk = await performManagedSync(engine, OPTS);+ expect(walk).toMatchObject({ status: 'synced', prescreened: SLUGS.length - 1 });+ expect(heldOf(walk)).toEqual([{ path: 'notes/a.md', code: 'file_too_large' }]);+ expect(await bodyOf(engine, 'notes/a')).toContain('The committed body of notes/a.');+ }, { databaseUrl, setup }), 180_000);+test('a database-only edit to a page whose file did not change is held file_drift and not imported', () => managedBrain(async ({ engine, ctx, root }) => {await engine.setConfig('sync.write_through', 'false');expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');@@ -134,6 +160,17 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect(await bodyOf(engine, 'notes/a')).toContain('A second database-only edit of notes/a.');}, { databaseUrl, setup }), 180_000);+ test('with sync.holds=fail the same drift stops the run with file_drift instead of importing over the database edit', () => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('sync.write_through', 'false');+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, ctx, 'notes/a', 'The database-only edit of notes/a.');+ await engine.setConfig('sync.holds', 'fail');+ rewriteHistory(root);+ const outcome = await performManagedSync(engine, OPTS).then(result => result, (error: unknown) => error);+ expect(outcome).toMatchObject({ code: 'file_drift' });+ expect(await bodyOf(engine, 'notes/a')).toContain('The database-only edit of notes/a.');+ }, { databaseUrl, setup }), 180_000);+test('under a storage.keep_db prefix the drifted page is neither held nor imported; the keep_db worker gets it as a candidate', () => managedBrain(async ({ engine, ctx, root }) => {await engine.setConfig('sync.write_through', 'false');expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');@@ -189,4 +226,25 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect(resumed.prescreened).toBeGreaterThanOrEqual(2);for (const slug of SLUGS) expect(await bodyOf(engine, slug)).toContain(`The committed body of ${slug}.`);}, { databaseUrl, setup }), 180_000);++ test('a lost manifest re-discovers the whole tree at HEAD: files the lost run imported and HEAD reverted are restored, its added page is removed', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const original = SLUGS.map(slug => note(slug, `The committed body of ${slug}.`));+ writeFileSync(join(root, 'notes/0-added.md'), note('notes/0-added', 'A page the lost run added.'));+ for (const slug of SLUGS) writeFileSync(join(root, `${slug}.md`), note(slug, `The lost run's body of ${slug}.`));+ commit(root, 'change everything');+ const abort = new AbortController();+ const partial = await performManagedSync(engine, { ...OPTS, signal: abort.signal, onProgress: p => { if (p.bankedFiles === 2) abort.abort(); } });+ expect(partial).toMatchObject({ status: 'partial', filesImported: 2 });+ expect(await bodyOf(engine, 'notes/a')).toContain("The lost run's body of notes/a.");+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest'");+ // HEAD reverts every file the lost run saw, so last_commit..HEAD is empty: only a walk of HEAD's tree finds them.+ SLUGS.forEach((slug, i) => writeFileSync(join(root, `${slug}.md`), original[i]!));+ git(root, 'rm', '-q', 'notes/0-added.md'); commit(root, 'revert');+ let resumed = await performManagedSync(engine, OPTS);+ for (let i = 0; i < 5 && resumed.status === 'partial'; i++) { await new Promise(resolve => setTimeout(resolve, 500)); resumed = await performManagedSync(engine, OPTS); }+ expect(resumed.status).toBe('synced');+ for (const slug of SLUGS) expect(await bodyOf(engine, slug)).toContain(`The committed body of ${slug}.`);+ expect(await engine.getPage('notes/0-added', { sourceId: 'default' })).toBeNull();+ }, { databaseUrl, setup }), 180_000);});