Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): disk provenance names only bytes the page holds (#8071)

garrytane02d6d015afb
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 28ea569fdb..4140c4e55b 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -15,7 +15,7 @@
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. #6712 (one page, one fate): a window group publishes whatever its predecessor became; nothing is cancelled for another page's failure, and dependency edges (`sync-group.ts` `dependencyKeys`, `freezeFollowers`' `taken`) keep two changes of one page out of the same group and out of the window while one is in flight. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the members after it stay admitted at the head of the window, so every admitted request's identity stays in the cursor until its own receipt is read (`groupStep`, `promoteWindow`). Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) only orders: under lanes a member whose predecessor member is unfinished releases its claim and waits; a predecessor that ended, committed or not, lets it publish (#6712). `WINDOW_CANCEL_MESSAGE` and `laneFaultCancelMessage` stay only so older receipts still read as legacy knock-ons. Test: `test/sync-group-member-order.test.ts`.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (`adoptCursor`, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode in `inherited_options`; nothing refuses over processing options, and `explicitProcessing` is gone. Admitted requests keep their own intent principal: they are read under it (`admittedBy`), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (`withDrainLease`, `src/core/persistence/sync-lease.ts`), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (`assertDrainLease`). Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits the pass stamps drain step `finish` and emits `managed_sync.finish`; then (unless `noExtract`) the owner derives links for the source's stale pages through `links-maintenance.ts` under `FINISH_BUDGET_MS` (pages left over stay stale for `gbrain extract --stale`), so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from `selectManagedCursor` (`sync-cursor-key.ts`), which every managed caller crosses: a run without `--strategy` and without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching. `SyncOpts.embedDeferred` (the cost gate's auto-defer) is frozen on the intent and treated as `noEmbed` by preparation, never as a processing option a resume adopts or compares (`test/persistence-sync-cursor-strategy-6696.test.ts`).
-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `sync-import-provenance` records (`recordSyncImportProvenance`, batched `recordSyncImportProvenances`) also carry `disk_sha256` / `disk_blob_oid` (the bytes the write left on disk), `revision` and `parser` (`syncImportParser`: `SYNC_IMPORT_PARSER_VERSION`, Markdown chunker, schema pack; never the release); records from before them, or from a repair, lack them and readers take them as unknown. `screenFrozenImport` builds its input with `frozenImportScreenInput` (rename base, the run's pack, sanity and purge tombstones) and screens it with `screenFrozenContent`, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one summary read per call, cached per request, plus, when the scope holds files and the call returned hits, one read for the hits' holds (by page id, `op_checkpoints_sync_hold_page_idx`, migration v200) and the count of holds that could match the query (`stampHeldHits`; the notice names it, also names embedding-held pages, and escalates); `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.
+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `sync-import-provenance` records (`recordSyncImportProvenance`, batched `recordSyncImportProvenances`) also carry `disk_sha256` / `disk_blob_oid` (bytes on disk the page holds, #8071), `revision` and `parser` (`syncImportParser`: `SYNC_IMPORT_PARSER_VERSION`, Markdown chunker, schema pack; never the release); records from before them, or from a repair, lack them and readers take them as unknown. `screenFrozenImport` builds its input with `frozenImportScreenInput` (rename base, the run's pack, sanity and purge tombstones) and screens it with `screenFrozenContent`, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one summary read per call, cached per request, plus, when the scope holds files and the call returned hits, one read for the hits' holds (by page id, `op_checkpoints_sync_hold_page_idx`, migration v200) and the count of holds that could match the query (`stampHeldHits`; the notice names it, also names embedding-held pages, and escalates); `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.
- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold (only while it is the `holdObservedAt` observation when the intent carries one, so a hold a newer sync wrote stays) and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. An import of a segmented body seals itself, so the inline text seal is skipped and its `afterCommit` is forwarded. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. A Markdown import's preparation carries `importProvenance` (`SyncPreparedMutation`); its publication writes it in the publish transaction with the page id, `revision` and the disk half (`syncDiskProvenance` over the canonical writeback, else `syncDiskBytes`), and a no-op waiver writes the same record instead. The checkpoint (`applyManagedSyncCheckpoint`) keeps a repository-root source's pinned slug mode (`sync-slug-mode.ts`). Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`. `syncGitTopLevel` answers the checkout's `git rev-parse --show-toplevel` once per root and sync run, reading it again when the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md. An intent with `embedDeferred` (#6696) prepares as `noEmbed` whatever the cursor's stored options say.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. GBRA-130 A-1 (site `links.extract_stale`, one `ItemRun` per source): a failing page is reported (`failed`, `failures`) and skipped; a run-scoped error stops the run after in-flight pages settle, recording nothing; a tripped breaker stops a scoped run (`item_failures_systemic`) or skips that source in a brain-wide run (`systemic`). Content failures are counted and held by `links-extraction-holds.ts`; a page of a deleted source fails `unknown_source` (`PageSourceMissingError`). The sync tail inherits this. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`, `test/pathological/a1-links-extract.test.ts` (both engines).
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 0500d7e310..2b5f5b9e40 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -469,13 +469,13 @@ async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p:
* #6712 PR 1: the import provenance a code or image publication records in its transaction, as a Markdown import records
* its own: the page's revision after the write, the bytes on disk (the file: neither writes one back) and the parser.
*/
-function syncFileProvenance(row: WriteRequest, p: SyncIntent, root: string, rawSha256: string): (tx: BrainEngine) => Promise<void> {
+function syncFileProvenance(row: WriteRequest, p: SyncIntent, root: string, imported: Buffer): (tx: BrainEngine) => Promise<void> {
return async tx => {
const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if (!final || final.page.deleted_at != null) return;
await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(final.page.id), origin: p.sourcePath!,
- raw_sha256: rawSha256, ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, revision: final.revision,
- parser: syncImportParserFor(p.sourcePath!, null), ...syncDiskProvenance(syncDiskBytes(root, p.path!, p.content!, p.rawHash), p.target) });
+ raw_sha256: sha256(imported), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, revision: final.revision,
+ parser: syncImportParserFor(p.sourcePath!, null), ...syncDiskProvenance(syncDiskBytes(root, p.path!, imported, p.rawHash), p.target) });
};
}
@@ -499,9 +499,18 @@ function publishedSyncNoop(row: WriteRequest, p: SyncIntent, root: string, snaps
} };
}
-/** The bytes on disk of an import that writes no file back: its frozen content when that is the file (raw hash), else the file read now (null: absent). */
-export function syncDiskBytes(root: string, path: string, content: string, rawHash: string | null): Uint8Array | null {
- return rawHash !== null && rawHash === sha256(content) ? Buffer.from(content) : readSyncFile(root, path);
+/**
+ * The bytes on disk of an import that writes no file back, as its provenance records them: the imported bytes when they
+ * are the file (raw hash), else the file read now (null: absent) when it holds those bytes up to line endings. #8071: any
+ * other file bytes are not what the page holds; the record names the imported bytes instead, or a later commit of the
+ * newer bytes would classify `fileSame` and never be imported.
+ */
+export function syncDiskBytes(root: string, path: string, imported: Buffer, rawHash: string | null): Uint8Array | null {
+ if (rawHash !== null && rawHash === sha256(imported)) return imported;
+ const disk = readSyncFile(root, path);
+ if (!disk || disk.equals(imported)) return disk;
+ const text = disk.toString('utf8'), lf = (value: string) => value.replace(/\r\n/g, '\n');
+ return disk.equals(Buffer.from(text)) && lf(text) === lf(imported.toString('utf8')) ? disk : imported;
}
/** A pass's stamp is refused because the pass no longer holds the source (its lease went, or another pass pinned since). */
@@ -815,11 +824,11 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
if (isImageFilePath(p.sourcePath)) {
return prepareManagedSyncImage(engine, row, { content: p.content, sourcePath: p.sourcePath, path: p.path, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly },
{ root, snapshot, ...(moved && moved.slug !== row.slug ? { renamedFrom: { slug: moved.slug } } : {}), noEmbed: p.processingOptions?.noEmbed === true || p.embedDeferred === true, companyApproval: !!p.companyApproval, validate, releaseHold, clock, screening: !!screening,
- recordProvenance: syncFileProvenance(row, p, root, sha256(Buffer.from(p.content, 'base64'))),
+ recordProvenance: syncFileProvenance(row, p, root, Buffer.from(p.content, 'base64')),
refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause) });
}
if (isCodeFilePath(p.sourcePath)) return prepareManagedSyncCode(engine, row, { content: p.content, sourcePath: p.sourcePath, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly, companyApproval: !!p.companyApproval },
- { snapshot, validate, releaseHold, recordProvenance: syncFileProvenance(row, p, root, sha256(p.content)), clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });
+ { snapshot, validate, releaseHold, recordProvenance: syncFileProvenance(row, p, root, Buffer.from(p.content)), clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });
const schema = p.companyApproval?.schema;
if (schema && p.processingOptions?.noSchemaPack) throw syncPublicationRefusal('profile_incompatible', 'Company source approval requires its pinned schema pack.', row,
{ ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },
@@ -958,7 +967,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
},
() => releaseHold(tx),
async () => { if (final) await recordSyncImportProvenance(tx, { ...importProvenance, page_id: Number(final.page.id), revision: final.revision,
- ...syncDiskProvenance(writeback ? Buffer.from(canonicalFile) : syncDiskBytes(root, p.path!, p.content!, p.rawHash), p.target) }); },
+ ...syncDiskProvenance(writeback ? Buffer.from(canonicalFile) : syncDiskBytes(root, p.path!, Buffer.from(p.content!), p.rawHash), p.target) }); },
]);
preparedImport.postimage = final;
const writeState = applied.noop ? {} : await syncWriteState(tx, row, live?.page, installed?.segmented, applied.parsedPage?.frontmatter);
diff --git a/test/e2e/sync-disk-provenance-8071-postgres.test.ts b/test/e2e/sync-disk-provenance-8071-postgres.test.ts
new file mode 100644
index 0000000000..fe056cf024
--- /dev/null
+++ b/test/e2e/sync-disk-provenance-8071-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-disk-provenance-8071.test.ts'));
diff --git a/test/sync-disk-provenance-8071.test.ts b/test/sync-disk-provenance-8071.test.ts
new file mode 100644
index 0000000000..1307be6e29
--- /dev/null
+++ b/test/sync-disk-provenance-8071.test.ts
@@ -0,0 +1,106 @@
+/**
+ * #8071: a managed sync never records, as the bytes an import left on disk, file bytes the page does not hold.
+ *
+ * The pass settles a path as `matched` when the commit's blob is in the page's import record (`blob_oid` or
+ * `disk_blob_oid`, sync-classify.ts). An import that published the pinned blob while the file held other bytes recorded
+ * those bytes as `disk_blob_oid` (sync-prepare.ts `syncDiskBytes` read the file at publication), so once they were
+ * committed the path matched, the stamp moved `last_commit` past the commit and the page kept the older text, with no hold.
+ *
+ * Protects, each ending with the edit committed and a plain sync that must import it (`last_commit` = HEAD, the
+ * committed body, no hold):
+ * - a new file with an uncommitted edit at sync;
+ * - a reparse candidate edited after the level read and committed after its freeze, inside one pass (the shape of one
+ * batch commit landing mid-pass);
+ * - a page with no import record (imported by an older release) with an uncommitted edit at sync;
+ * Control: a CRLF copy of the pinned bytes still records its own blob, and the next sync re-imports nothing.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));
+ commit(root, 'notes');
+};
+const body = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page.compiled_truth.trim() ?? null;
+const pageId = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.id;
+const incarnationOf = async (engine: BrainEngine) => (await engine.executeRaw<{ i: string }>("SELECT incarnation::text AS i FROM sources WHERE id='default'"))[0]!.i;
+const recordKey = async (engine: BrainEngine, slug: string) => `default:${await incarnationOf(engine)}:${await pageId(engine, slug)}`;
+const record = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ blob: string | null; disk: string | null }>(
+ "SELECT completed_keys->0->>'blob_oid' AS blob, completed_keys->0->>'disk_blob_oid' AS disk FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
+ [SYNC_IMPORT_PROVENANCE_OP, await recordKey(engine, slug)]))[0] ?? null;
+/** What the source records once the committed edit is synced: the checkpoint, the page's body and the holds. */
+const landed = async (engine: BrainEngine, slug: string, result: Awaited<ReturnType<typeof performManagedSync>>) => ({
+ last_commit: (await engine.executeRaw<{ c: string }>("SELECT last_commit AS c FROM sources WHERE id='default'"))[0]!.c,
+ body: await body(engine, slug), held: (result.held ?? []).map(hold => hold.path) });
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ describe(`#8071 disk provenance names only bytes the page holds (${backend})`, () => {
+ test('a new file with an uncommitted edit imports its pinned bytes; the edit, once committed, is imported', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/d.md'), note('notes/d', 'The original body of notes/d.')); commit(root, 'add d');
+ const pinned = git(root, 'rev-parse', 'HEAD:notes/d.md');
+ writeFileSync(join(root, 'notes/d.md'), note('notes/d', 'The edited body of notes/d.'));
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ expect({ body: await body(engine, 'notes/d'), record: await record(engine, 'notes/d') })
+ .toEqual({ body: 'The original body of notes/d.', record: { blob: pinned, disk: pinned } });
+ commit(root, 'edit d');
+ const synced = await performManagedSync(engine, OPTS);
+ expect(await landed(engine, 'notes/d', synced)).toEqual({ last_commit: git(root, 'rev-parse', 'HEAD'), body: 'The edited body of notes/d.', held: [] });
+ }, { setup, databaseUrl }), 180_000);
+
+ test('a reparse candidate edited after the level read and committed after its freeze is imported in the same pass', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,parser,parser_version}','"an-older-parser"'::jsonb) WHERE op=$1 AND fingerprint=$2`,
+ [SYNC_IMPORT_PROVENANCE_OP, await recordKey(engine, 'notes/b')]);
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,obligations,converged,parser_fp}','\"an-older-parser\"'::jsonb) WHERE op='managed-sync-pass'");
+ let edited = false, committed = false;
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:level_read' && !edited) { edited = true; writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'The edited body of notes/b.')); }
+ if (point === 'sync:after_freeze' && (detail as { path?: string }).path === 'notes/b.md' && edited && !committed) { committed = true; commit(root, 'edit b'); }
+ });
+ const pass = await performManagedSync(engine, OPTS);
+ installFaultHook(undefined);
+ expect({ edited, committed, status: pass.status }).toEqual({ edited: true, committed: true, status: 'synced' });
+ expect(await landed(engine, 'notes/b', pass)).toEqual({ last_commit: git(root, 'rev-parse', 'HEAD'), body: 'The edited body of notes/b.', held: [] });
+ }, { setup, databaseUrl }), 180_000);
+
+ test('a page with no import record and an uncommitted edit at sync keeps its body; the edit, once committed, is imported', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, await recordKey(engine, 'notes/c')]);
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A later body of notes/a.')); commit(root, 'change a');
+ writeFileSync(join(root, 'notes/c.md'), note('notes/c', 'The edited body of notes/c.'));
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ expect(await body(engine, 'notes/c')).toBe('The committed body of notes/c.');
+ commit(root, 'edit c');
+ const synced = await performManagedSync(engine, OPTS);
+ expect(await landed(engine, 'notes/c', synced)).toEqual({ last_commit: git(root, 'rev-parse', 'HEAD'), body: 'The edited body of notes/c.', held: [] });
+ }, { setup, databaseUrl }), 180_000);
+
+ test('control: a CRLF copy of the pinned bytes still records its own blob, and the next sync re-imports nothing', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const lf = note('notes/d', 'The body of notes/d.');
+ writeFileSync(join(root, 'notes/d.md'), lf); commit(root, 'add d');
+ writeFileSync(join(root, 'notes/d.md'), lf.replace(/\n/g, '\r\n'));
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ expect(await record(engine, 'notes/d')).toEqual({ blob: git(root, 'rev-parse', 'HEAD:notes/d.md'), disk: git(root, 'hash-object', 'notes/d.md') });
+ const again = await performManagedSync(engine, OPTS);
+ expect({ status: again.status, added: again.added, modified: again.modified }).toEqual({ status: 'up_to_date', added: 0, modified: 0 });
+ }, { setup, databaseUrl }), 180_000);
+ });
+}