Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): read pinned Git blobs in windows and resolve the Git top level once per run

time-attack44a14631f17a
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 4c7c2d5966..b53e01e329 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -19,9 +19,9 @@
- **`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`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. 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 drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. 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) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. 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`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). 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 be committed; a failed one cancels the group, 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 cancels, releases or falls back to the single path, 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`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. 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 (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, 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.
-- **`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 holds preview `gbrain repair fences --source <id>`, other holds preview `gbrain repair frontmatter`, a mixed source names both. 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. `screenFrozenImport` 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`. `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 lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `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: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
+- **`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 holds preview `gbrain repair fences --source <id>`, other holds preview `gbrain repair frontmatter`, a mixed source names both. 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. `screenFrozenImport` 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 per slice, blobs over the read bound 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 lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `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: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
- **`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 and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. 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. 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`. #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.
+- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. 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.
- **`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. 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`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.ts
index d0bab6ca82..b310636203 100644
--- a/src/core/persistence/sync-blobs.ts
+++ b/src/core/persistence/sync-blobs.ts
@@ -2,6 +2,10 @@
* #5988: batched Git reads for managed sync hold checks and dry runs: blob ids
* and sizes through chunked `ls-tree`, contents through `cat-file --batch`,
* never one process per file and never an unbounded full-tree read.
+ * Managed sync's freeze reads its pinned blobs through `readPinnedBlob` /
+ * `readPinnedContent`: one `ls-tree` per window of upcoming entries and one
+ * `cat-file --batch` per bounded slice of it, instead of an `ls-tree` and a
+ * `git show` per entry.
*/
import { execFileSync } from 'node:child_process';
@@ -42,7 +46,8 @@ export function readBlobContents(gitRoot: string, blobs: TreeBlob[]): Map<string
let offset = 0;
for (const blob of chunk) {
const newline = output.indexOf(10, offset);
- const [oid, , size] = output.subarray(offset, newline).toString('utf8').split(' ');
+ const [oid, kind, size] = output.subarray(offset, newline).toString('utf8').split(' ');
+ if (kind === 'missing' || size === undefined) { offset = newline + 1; continue; }
const start = newline + 1, end = start + Number(size);
out.set(oid!, output.subarray(start, end).toString('utf8'));
offset = end + 1;
@@ -51,3 +56,69 @@ export function readBlobContents(gitRoot: string, blobs: TreeBlob[]): Map<string
return out;
}
+/** Entries one pinned `ls-tree` covers, and the bytes one window's `cat-file --batch` loads at most. */
+export const PINNED_WINDOW = 256;
+const PINNED_WINDOW_BYTES = 8 * 1024 ** 2;
+const COMMIT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
+
+/**
+ * The pinned tree window of the run reading now. A full commit id names
+ * immutable trees and blobs, so an answer read for a later entry of the window
+ * is the answer that entry's own read would give; a different root or target
+ * replaces the window.
+ */
+let pinned: { gitRoot: string; target: string; paths: string[]; blobs: Map<string, TreeBlob | null>; contents: Map<string, string> } | null = null;
+let pinnedWindowSize = PINNED_WINDOW;
+/** Test seam: replace the pinned window size (0 reads every entry alone, as before windows; null restores it); returns the restore function. */
+export function __setPinnedWindowForTests(size: number | null): () => void {
+ const previous = pinnedWindowSize;
+ pinnedWindowSize = size ?? PINNED_WINDOW;
+ pinned = null;
+ return () => { pinnedWindowSize = previous; pinned = null; };
+}
+
+function pinnedWindow(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]) {
+ if (pinned?.gitRoot === gitRoot && pinned.target === target && pinned.blobs.has(gitPath)) return pinned;
+ const paths = [gitPath, ...new Set(upcoming().filter(path => path !== gitPath))].slice(0, pinnedWindowSize);
+ let found: Map<string, TreeBlob>;
+ // A window that cannot be listed (one path git rejects) falls back to this entry alone, which reports its own error.
+ try { found = readTreeBlobs(gitRoot, target, paths); } catch { return null; }
+ pinned = { gitRoot, target, paths, blobs: new Map(paths.map(path => [path, found.get(path) ?? null])), contents: new Map() };
+ return pinned;
+}
+
+/**
+ * The blob of `gitPath` at the pinned `target`, or null when the commit has no
+ * blob there: the answer of `readTreeBlobs` for that one path. `upcoming` lists
+ * the Git paths the run reads next; a path outside the current window lists
+ * itself and up to `PINNED_WINDOW` of them in one `ls-tree`.
+ */
+export function readPinnedBlob(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]): TreeBlob | null {
+ const window = pinnedWindowSize && COMMIT_ID.test(target) ? pinnedWindow(gitRoot, target, gitPath, upcoming) : null;
+ return window ? window.blobs.get(gitPath)! : readTreeBlobs(gitRoot, target, [gitPath]).get(gitPath) ?? null;
+}
+
+/**
+ * The decoded content of the blob at `gitPath` in the pinned `target`, or null
+ * when the window cannot answer it (no blob there, over the sync read bound, or
+ * unreadable); the caller then reads it as before. A miss loads this blob and
+ * the window's later ones, up to `PINNED_WINDOW_BYTES`, in one `cat-file --batch`.
+ */
+export function readPinnedContent(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]): string | null {
+ if (!pinnedWindowSize || !COMMIT_ID.test(target)) return null;
+ const window = pinnedWindow(gitRoot, target, gitPath, upcoming);
+ const blob = window?.blobs.get(gitPath);
+ if (!window || !blob || blob.size > SYNC_READ_BOUND) return null;
+ if (!window.contents.has(blob.oid)) {
+ const slice: TreeBlob[] = [];
+ let bytes = 0;
+ for (const path of window.paths.slice(window.paths.indexOf(gitPath))) {
+ const next = window.blobs.get(path);
+ if (!next || next.size > SYNC_READ_BOUND) continue;
+ if (slice.length && bytes + next.size > PINNED_WINDOW_BYTES) break;
+ bytes += next.size; slice.push(next);
+ }
+ try { window.contents = readBlobContents(gitRoot, slice); } catch { return null; }
+ }
+ return window.contents.get(blob.oid) ?? null;
+}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 9d867c49d5..9d9409fe4c 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -1,7 +1,7 @@
-import { realpathSync } from 'node:fs';
+import { existsSync, lstatSync, realpathSync } from 'node:fs';
import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
import { boundedReads } from './bounded-reads.ts';
-import { basename, join } from 'node:path';
+import { basename, dirname, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
@@ -230,6 +230,26 @@ function companyWritebackRefusal(row: WriteRequest, p: SyncIntent, fenceFixes: r
: `The file of ${row.slug} needs a canonical correction, and a company-brain source never rewrites repository files; correct it in the repository and commit.`);
}
+/**
+ * The checkout's Git top level for one sync run's requests: `git rev-parse --show-toplevel` once per root and run,
+ * read again whenever the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root,
+ * the changes that move the top level of a checkout.
+ */
+const gitTopLevels = new Map<string, { gitRoot: string; dotGit: string }>();
+function dotGitIdentity(root: string, gitRoot: string): string | null {
+ for (let dir = root; dir !== gitRoot; dir = dirname(dir)) if (dir === dirname(dir) || existsSync(join(dir, '.git'))) return null;
+ try { const stat = lstatSync(join(gitRoot, '.git')); return `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`; } catch { return null; }
+}
+export function syncGitTopLevel(root: string, runId: string): string {
+ const key = `${root}\0${runId}`, known = gitTopLevels.get(key);
+ if (known && dotGitIdentity(root, known.gitRoot) === known.dotGit) return known.gitRoot;
+ const gitRoot = realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim());
+ const dotGit = dotGitIdentity(root, gitRoot);
+ if (gitTopLevels.size >= 64) gitTopLevels.clear();
+ if (dotGit === null) gitTopLevels.delete(key); else gitTopLevels.set(key, { gitRoot, dotGit });
+ return gitRoot;
+}
+
/**
* The entry's recorded origin, checked against the checkout (`git rev-parse`, the entry's path under the root) and the
* accepted page (its origin, and the rename source's); a checkpoint has none. `clock` names the steps (#6278).
@@ -254,7 +274,7 @@ async function resolveSyncOrigin(engine: BrainEngine, row: WriteRequest, p: Sync
}
const origin = { path: p.path, sourcePath: p.sourcePath, action: p.kind === 'managed_sync_delete' ? 'delete' as const : 'import' as const, working };
enterClaimStep(clock, 'git_rev_parse', undefined, 'git');
- const originContext = { root, gitRoot: realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim()), target: p.target, slugMode: p.slugMode };
+ const originContext = { root, gitRoot: syncGitTopLevel(root, p.runId), target: p.target, slugMode: p.slugMode };
assertSyncEntryOrigin(originContext, origin);
const originScope = syncOriginScope({ ...originContext, sourceId: row.source_id });
enterClaimStep(clock, 'origin_check', undefined, 'db');
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index a3ab20da36..832cd854de 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -12,7 +12,7 @@ import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDig
import { preparationConfigView } from './config-snapshot.ts';
import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';
-import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
+import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
import { isImageFilePath } from '../sync.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
@@ -41,7 +41,7 @@ import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';
import { isContentRefusal } from '../import-screen.ts';
import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
-import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, pinnedContent, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';
import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';
@@ -352,7 +352,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
`Source ${cursor.sourceId}'s approved company-brain content manifest no longer includes ${entry.path} for this run (its approval changed, or the file is no longer an included path), so nothing was imported for it. If the approval changed, inspect and approve the repository again first (gbrain sources inspect --help).`);
content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');
assertActive();
- } else content = entry.action === 'import' && !oversize ? readSyncContent(cursor, entry) : null;
+ } else content = entry.action === 'import' && !oversize ? pinnedContent(cursor, entry) : null;
// #6340: working-tree bytes that differ from the pinned blob but are committed at HEAD (a commit past the pin on a
// live checkout) are imported as HEAD has them; the pin..HEAD diff later re-imports the same bytes as a no-op.
// Uncommitted bytes keep the pinned content and reach the publication screen (idea from PR #6323).
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 88714e1fa3..871d9d4c5b 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -11,6 +11,8 @@
* normalized file; a dry run lists it in `would_normalize`), and a residual
* fence is held as `invalid_fence`.
*/
+import { realpathSync } from 'node:fs';
+import { relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { loadImportSanityConfig, screenNormalized, type ImportSanityConfig } from '../import-screen.ts';
@@ -25,8 +27,8 @@ import { isImageFilePath, resolveSlugForPath } from '../sync.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { VERSION } from '../../version.ts';
import { sha256 } from './digest.ts';
-import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
-import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
+import { readSyncContent, readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
+import { PINNED_WINDOW, readBlobContents, readPinnedBlob, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';
import type { SyncProcessingOptions } from './sync-authority.ts';
import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';
@@ -55,10 +57,26 @@ export function isSyncReadBound(error: unknown): boolean {
return error instanceof OperationError && error.code === 'request_too_large' && error.message === 'Sync file exceeds the bounded import size.';
}
-/** The pinned blob of one entry (one `ls-tree`), or null when the commit lacks it. */
-export function pinnedBlob(discovery: Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target'>, path: string): TreeBlob | null {
- const gitPath = syncGitPath(discovery, path);
- return readTreeBlobs(discovery.gitRoot, discovery.target, [gitPath]).get(gitPath) ?? null;
+type PinnedCursor = Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target' | 'entries'> & { index: number };
+
+/** Git paths of the committed imports from the cursor's entry on: the window one pinned read lists. */
+function upcomingGitPaths(cursor: PinnedCursor): () => string[] {
+ return () => {
+ const gitRoot = realpathSync.native(cursor.gitRoot), root = realpathSync.native(cursor.root);
+ return cursor.entries.slice(cursor.index, cursor.index + PINNED_WINDOW).filter(entry => entry.action === 'import' && !entry.working)
+ .map(entry => relative(gitRoot, resolve(root, entry.path)).split(sep).join('/'));
+ };
+}
+
+/** The pinned blob of one entry, or null when the commit lacks it; read with the entries after it (`readPinnedBlob`). */
+export function pinnedBlob(cursor: PinnedCursor, path: string): TreeBlob | null {
+ return readPinnedBlob(cursor.gitRoot, cursor.target, syncGitPath(cursor, path), upcomingGitPaths(cursor));
+}
+
+/** The frozen import content of one entry (`readSyncContent`); a committed entry's pinned blob is read with the entries after it. */
+export function pinnedContent(cursor: SyncDiscovery & { index: number }, entry: SyncEntry): string {
+ const content = entry.working ? null : readPinnedContent(cursor.gitRoot, cursor.target, syncGitPath(cursor, entry.path), upcomingGitPaths(cursor));
+ return content ?? readSyncContent(cursor, entry);
}
function heldEntry(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,
diff --git a/test/managed-sync-pinned-reads.test.ts b/test/managed-sync-pinned-reads.test.ts
new file mode 100644
index 0000000000..c0e6343a74
--- /dev/null
+++ b/test/managed-sync-pinned-reads.test.ts
@@ -0,0 +1,264 @@
+/**
+ * GBRA-69: a managed sync reads its pinned blobs in windows (one `ls-tree` per
+ * window of entries, one `cat-file --batch` per bounded slice) instead of an
+ * `ls-tree` and a `git show` per entry, and resolves the checkout's Git top
+ * level once per run. The database a sync leaves must not depend on it: the
+ * same commits synced with per-entry reads (window 0), the default window and
+ * a window of 3 (every boundary crossed) leave identical rows in every table,
+ * over a first sync and a second round of edits, renames, deletes and new
+ * files, including held files (slug conflict, over the read bound) and a
+ * source below the repository root. Each arm gets a fresh brain; ids, times
+ * and UUIDs are replaced by stable labels, blob ids and commits are compared
+ * as they are. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { __setPinnedWindowForTests } from '../src/core/persistence/sync-blobs.ts';
+import { syncGitTopLevel } from '../src/core/persistence/sync-prepare.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-pinned-reads-'));
+const SOURCE = 'pinned-reads';
+let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+const GIT_ENV = { GIT_AUTHOR_DATE: '2026-01-01T00:00:00Z', GIT_COMMITTER_DATE: '2026-01-01T00:00:00Z' };
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...GIT_ENV } }).trim();
+}
+const commit = (root: string) => { git(root, 'add', '-A', '--', 'vault', 'outside'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes'); };
+function write(root: string, files: Record<string, string | null>) {
+ for (const [path, body] of Object.entries(files)) {
+ const full = join(root, path);
+ if (body === null) { rmSync(full); continue; }
+ mkdirSync(join(full, '..'), { recursive: true }); writeFileSync(full, body);
+ }
+}
+
+const pad = (i: number) => String(i).padStart(3, '0');
+const facts = (rows: Array<[number, string]>) => ['<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ ...rows.map(([n, claim]) => `| ${n} | ${claim} | fact | 1.0 | world | high | 2026-01-0${n} | | remember | |`), '<!--- gbrain:facts:end -->'].join('\n');
+const takes = (rows: Array<[number, string]>) => ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',
+ '|---|-------|------|-----|--------|-------|--------|', ...rows.map(([n, claim]) => `| ${n} | ${claim} | take | brain | 0.5 | 2026-07 | notes |`),
+ '<!--- gbrain:takes:end -->'].join('\n');
+function page(i: number, count: number, v = 0): string {
+ const kind = ['note', 'person', 'project'][i % 3]!;
+ const front = [`title: ${kind === 'person' ? `Person Example ${i}` : `Item ${i}`}`, `type: ${kind}`];
+ if (i % 4 === 0) front.push(`tags: [alpha, topic-${i % 5}${v ? ', revised' : ''}]`);
+ if (i % 5 === 0) front.push(`aliases: [item-alias-${i}${v ? `, second-alias-${i}` : ''}]`);
+ const body = [`A durable observation number ${i}${v ? ' (revised)' : ''}, see [[notes/n${pad((i + 7) % count)}]] and [[notes/n${pad((i + 3) % count)}]].`];
+ if (i % 3 === 0) body.push('', facts(v ? [[1, `Fact one of ${i}`], [3, `Fact three of ${i}`]] : [[1, `Fact one of ${i}`], [2, `Fact two of ${i}`]]));
+ if (i % 4 === 1) body.push('', takes(v ? [[1, `Take one of ${i}`]] : [[1, `Take one of ${i}`], [2, `Take two of ${i}`]]));
+ const timeline = i % 2 === 0 ? ['', '<!-- timeline -->', '', '## Timeline', '', `- **2025-0${1 + (i % 9)}-01** | Started item ${i}`,
+ ...(v ? [`- **2026-0${1 + (i % 9)}-15** | Revised item ${i}`] : [`- **2025-1${i % 3}-11** | Reviewed item ${i}`])] : [];
+ return `---\n${front.join('\n')}\n---\n${body.join('\n')}\n${timeline.join('\n')}\n`;
+}
+const COUNT = 24;
+/** The source lives in `vault/` below the repository root; `outside/` is not part of it. */
+const corpus = (): Record<string, string> => ({
+ ...Object.fromEntries(Array.from({ length: COUNT }, (_, i) => [`vault/notes/n${pad(i)}.md`, page(i, COUNT)])),
+ 'vault/notes/crlf.md': '---\r\ntitle: Line endings\r\ntype: note\r\n---\r\nWritten with CRLF line endings.\r\n',
+ 'vault/notes/conflict.md': '---\ntitle: Conflict\nslug: notes/somewhere-else\n---\nDeclares a slug its path does not have.\n',
+ 'vault/notes/broken.md': '---\ntitle: first line of a title\nsecond line of the title\n---\nA synthetic note.\n',
+ 'vault/big/oversize.md': `---\ntitle: Oversize\n---\n${'x'.repeat(10 * 1024 ** 2 + 64)}\n`,
+ 'outside/readme.md': '# Not in the source\n',
+});
+function secondRound(root: string) {
+ const edits: Record<string, string | null> = {};
+ for (const i of [1, 2, 3, 8, 9, 12, 16, 20]) edits[`vault/notes/n${pad(i)}.md`] = page(i, COUNT, 1);
+ for (const i of [5, 13]) edits[`vault/notes/n${pad(i)}.md`] = null;
+ for (let i = COUNT; i < COUNT + 5; i++) edits[`vault/notes/n${pad(i)}.md`] = page(i, COUNT);
+ edits['vault/notes/conflict.md'] = '---\ntitle: Conflict\n---\nNo declared slug any more.\n';
+ edits['vault/notes/broken.md'] = '---\ntitle: Fixed title\n---\nA synthetic note.\n';
+ write(root, edits);
+ git(root, 'mv', `vault/notes/n${pad(6)}.md`, 'vault/notes/moved-six.md');
+ commit(root);
+}
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const TIMESTAMP = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/;
+const VOLATILE = new Set(['id', 'created_at', 'updated_at', 'snapshot_at', 'last_written_at', 'embedded_at', 'decided_at', 'ingested_at', 'claim_expires_at',
+ 'next_attempt_at', 'completed_at', 'published_at', 'generation', 'execution_token', 'sequence', 'source_incarnation', 'incarnation', 'worktree_id',
+ 'consumer_host_id', 'admitter_host_id', 'consumer_version', 'admitter_version', 'digest', 'authority', 'intent_bytes', 'terminal_reservation', 'topology_generation',
+ 'runId', 'run_id', 'cursorKey', 'ownerEpoch', 'holdObservedAt', 'observed_at', 'held_at', 'syncAuthority', 'lane', 'group', 'request_id', 'requestId',
+ 'principal_id', 'revision_principal_id', 'write_principal_id', 'last_write_principal_id', 'archived_principal_id', 'knowledge_revision', 'text_projection_revision',
+ 'revision', 'expected_revision', 'salience_touched_at', 'last_retrieved_at', 'links_extracted_at', 'emotional_weight_recomputed_at', 'embedding',
+ 'embedding_image', 'embedding_multimodal', 'edges_backfilled_at', 'search_vector', 'content_hash', 'revision_write_request_id', 'coordination_path',
+ 'lastAt', 'startedAt']);
+
+/** Every page-derived row the sync wrote, with ids, times, UUIDs and the checkout path replaced by labels. */
+async function dump(e: BrainEngine, root: string): Promise<Record<string, string[]>> {
+ const pages = await e.executeRaw<{ id: number; slug: string }>('SELECT id,slug FROM pages WHERE source_id=$1', [SOURCE]);
+ const slugOf = new Map(pages.map(p => [Number(p.id), p.slug]));
+ const norm = (value: unknown, key = ''): unknown => {
+ if (value === null || value === undefined) return null;
+ if (value instanceof Date) return '<time>';
+ if (Array.isArray(value)) return value.map(v => norm(v, key));
+ if (typeof value === 'object') {
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).filter(([k]) => !VOLATILE.has(k)).sort(([a], [b]) => a < b ? -1 : 1)
+ .map(([k, v]) => [k, /(^|_)page_id$|^pageId$/.test(k) && v != null ? `page(${slugOf.get(Number(v)) ?? 'other'})` : norm(v, k)]));
+ }
+ if (typeof value === 'string') {
+ const text = value.replaceAll(root, '<root>');
+ if (UUID.test(text)) return `<uuid:${key}>`;
+ if (TIMESTAMP.test(text) && !/[T ]00:00:00(\.0+)?([+-]00(:00)?|Z)?$/.test(text)) return '<time>';
+ return text;
+ }
+ return value;
+ };
+ const rows = async (sql: string) => (await e.executeRaw<{ r: unknown }>(sql, [SOURCE])).map(row => JSON.stringify(norm(row.r))).sort();
+ return {
+ pages: await rows('SELECT to_jsonb(p) || jsonb_build_object(\'deleted\', p.deleted_at IS NOT NULL, \'sv\', p.search_vector::text) AS r FROM pages p WHERE source_id=$1'),
+ chunks: await rows('SELECT to_jsonb(c) || jsonb_build_object(\'sv\', c.search_vector::text) AS r FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1'),
+ page_aliases: await rows('SELECT to_jsonb(a) AS r FROM page_aliases a WHERE source_id=$1'),
+ slug_aliases: await rows('SELECT to_jsonb(a) AS r FROM slug_aliases a WHERE source_id=$1'),
+ tags: await rows('SELECT to_jsonb(t) AS r FROM tags t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1'),
+ links: await rows('SELECT to_jsonb(l) AS r FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1'),
+ timeline: await rows('SELECT to_jsonb(t) AS r FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1'),
+ facts: await rows('SELECT to_jsonb(f) - ARRAY[\'superseded_by\',\'consolidated_into\'] || jsonb_build_object(\'expired\', f.expired_at IS NOT NULL) AS r FROM facts f WHERE source_id=$1'),
+ takes: await rows('SELECT to_jsonb(k) - \'superseded_by\' AS r FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1'),
+ versions: await rows('SELECT to_jsonb(v) AS r FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1'),
+ chronicle: await rows('SELECT to_jsonb(c) AS r FROM chronicle_page_state c WHERE source_id=$1'),
+ effects: await rows(`SELECT to_jsonb(e) - ARRAY['state','attempts','error_code','outcome','recovery','recovery_bytes'] AS r FROM persistence_effects e WHERE source_id=$1`),
+ receipts: await rows(`SELECT jsonb_build_object('intent',r.intent,'state',r.state,'error_code',r.error_code,'error_message',r.error_message,
+ 'outcome',r.outcome,'slug',r.slug,'page_id',r.page_id,'publication_started',r.publication_started,'compacted',r.compacted) AS r
+ FROM persistence_requests r WHERE r.source_id=$1`),
+ sources: await rows('SELECT to_jsonb(s) - ARRAY[\'last_sync_at\',\'newest_content_at\'] AS r FROM sources s WHERE id=$1'),
+ // A provenance record is keyed by page id, which Postgres bulk groups may assign in another order.
+ checkpoints: await rows(`SELECT jsonb_build_object('op',op,'fingerprint',regexp_replace(regexp_replace(fingerprint,'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}','<uuid>','g'),'[0-9a-f]{32,}','<key>','g'),
+ 'page_id',CASE WHEN op='sync-import-provenance' THEN substring(fingerprint from ':([0-9]+)$')::integer END,'record',completed_keys) AS r
+ FROM op_checkpoints WHERE completed_keys::text LIKE '%' || $1 || '%' OR fingerprint LIKE '%' || $1 || '%'`)
+ .then(list => list.map(row => row.replace(/("fingerprint":"[^"]*):\d+"(.*"page_id":"(page\([^)]*\))")/, '$1:$3"$2'))),
+ };
+}
+
+/** A `git` on PATH that logs each invocation, so an arm's Git process count is known. */
+function gitCounter(dir: string): { path: string; calls: () => string[] } {
+ const log = join(dir, 'git.log'), bin = join(dir, 'bin');
+ mkdirSync(bin, { recursive: true });
+ const real = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nexec '${real}' "$@"\n`);
+ chmodSync(join(bin, 'git'), 0o755);
+ return { path: `${bin}${delimiter}${process.env.PATH ?? ''}`, calls: () => existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean) : [] };
+}
+
+type Arm = { name: string; window: number | null };
+const ARMS: Arm[] = [{ name: 'per-entry', window: 0 }, { name: 'window', window: null }, { name: 'window-3', window: 3 }];
+
+async function runArm(backend: string, arm: Arm, open: () => Promise<{ engine: BrainEngine; close: () => Promise<void> }>) {
+ const dir = join(home, `${backend}-${arm.name}`), root = join(dir, 'repo');
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ write(root, corpus()); commit(root);
+ const sourceRoot = join(root, 'vault');
+ const { engine, close } = await open();
+ const counter = process.platform === 'win32' ? null : gitCounter(dir);
+ const restore = __setPinnedWindowForTests(arm.window);
+ try {
+ return await withEnv({ GBRAIN_HOME: join(dir, 'home'), ...(counter ? { PATH: counter.path } : {}) }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [SOURCE, sourceRoot]);
+ await claimWorktree(engine, SOURCE, sourceRoot);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const outcomes: unknown[] = [], rounds: Array<Record<string, string[]>> = [];
+ for (const round of [0, 1]) {
+ if (round) secondRound(root);
+ const result = await performSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, drain: true });
+ outcomes.push({ status: result.status, added: result.added, modified: result.modified, deleted: result.deleted, renamed: result.renamed, drain: result.drain?.outcome });
+ rounds.push(await dump(engine, root));
+ }
+ await disposePersistenceConsumer(engine);
+ return { outcomes, rounds, calls: counter?.calls() ?? null, head: git(root, 'rev-parse', 'HEAD') };
+ });
+ } finally { restore(); await close(); }
+}
+
+beforeAll(async () => {
+ if (process.env.DATABASE_URL) template = await persistencePostgresTemplate(process.env.DATABASE_URL);
+}, 120_000);
+afterAll(async () => {
+ await template?.dispose();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const backends: Array<[string, () => Promise<{ engine: BrainEngine; close: () => Promise<void> }>]> = [
+ ['pglite', async () => { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); return { engine, close: () => engine.disconnect() }; }],
+ ['postgres', async () => template!.clone()],
+];
+
+for (const [backend, open] of backends) {
+ test(`${backend}: windowed pinned reads leave the same rows as per-entry reads, with far fewer Git processes`, async () => {
+ if (backend === 'postgres' && !process.env.DATABASE_URL) return;
+ const results = [];
+ for (const arm of ARMS) results.push(await runArm(backend, arm, open));
+ const [legacy, ...windowed] = results;
+ expect(legacy!.outcomes).toEqual([
+ expect.objectContaining({ drain: 'synced' }), expect.objectContaining({ drain: 'synced' })]);
+ const [first, last] = legacy!.rounds;
+ for (const table of ['pages', 'chunks', 'page_aliases', 'tags', 'links', 'timeline', 'facts', 'takes', 'versions', 'receipts', 'checkpoints']) {
+ expect(last![table]!.length).toBeGreaterThan(0);
+ }
+ const holds = first!.checkpoints!.filter(row => row.includes('"op":"sync-hold"'));
+ expect(holds.some(row => row.includes('"code":"file_too_large"'))).toBe(true);
+ expect(holds.some(row => row.includes('"code":"invalid_frontmatter"'))).toBe(true);
+ expect(last!.receipts!.some(row => row.includes('"path":"notes/broken.md"'))).toBe(true);
+ for (const other of windowed) {
+ expect(other.head).toBe(legacy!.head);
+ expect(other.outcomes).toEqual(legacy!.outcomes);
+ for (const [round, rows] of legacy!.rounds.entries()) {
+ const differences = Object.keys(rows).flatMap(table => {
+ const mine = new Set(other.rounds[round]![table]), theirs = new Set(rows[table]);
+ return [...rows[table]!.filter(row => !mine.has(row)).map(row => `round ${round} ${table} per-entry only: ${row}`),
+ ...other.rounds[round]![table]!.filter(row => !theirs.has(row)).map(row => `round ${round} ${table} windowed only: ${row}`)];
+ });
+ expect(differences).toEqual([]);
+ for (const table of Object.keys(rows)) expect(other.rounds[round]![table]!.length).toBe(rows[table]!.length);
+ }
+ }
+ if (!legacy!.calls) return;
+ const count = (calls: string[], verb: RegExp) => calls.filter(call => verb.test(call)).length;
+ const imports = COUNT + 3 + 8 + 5 + 3;
+ expect(count(legacy!.calls, / show [0-9a-f]+:/)).toBeGreaterThanOrEqual(COUNT);
+ expect(count(legacy!.calls, / ls-tree -l /)).toBeGreaterThanOrEqual(COUNT);
+ expect(count(windowed[0]!.calls!, / show [0-9a-f]+:/)).toBe(0);
+ expect(count(windowed[0]!.calls!, / ls-tree -l /)).toBeLessThanOrEqual(4);
+ expect(count(windowed[0]!.calls!, / cat-file --batch$/)).toBeLessThanOrEqual(4);
+ expect(count(windowed[0]!.calls!, / rev-parse --show-toplevel$/)).toBeLessThan(imports / 2);
+ }, 600_000);
+}
+
+test('the Git top level is read once per root and run, and again when the checkout\'s .git changes', async () => {
+ mkdirSync(join(home, 'top-level', 'a', 'b'), { recursive: true });
+ const repo = realpathSync(join(home, 'top-level')), nested = join(repo, 'a', 'b');
+ git(repo, 'init', '-q');
+ const counter = process.platform === 'win32' ? null : gitCounter(join(home, 'top-level-git'));
+ const toplevels = () => execFileSync('git', ['-C', nested, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim();
+ await withEnv(counter ? { PATH: counter.path } : {}, async () => {
+ const reads = () => counter ? counter.calls().filter(call => call.endsWith('rev-parse --show-toplevel')).length : 0;
+ expect(syncGitTopLevel(nested, 'run-1')).toBe(repo);
+ expect(syncGitTopLevel(nested, 'run-1')).toBe(repo);
+ if (counter) expect(reads()).toBe(1);
+ expect(syncGitTopLevel(nested, 'run-2')).toBe(repo);
+ if (counter) expect(reads()).toBe(2);
+ // A repository initialized between the root and the top level moves the top level.
+ git(join(repo, 'a'), 'init', '-q');
+ expect(syncGitTopLevel(nested, 'run-1')).toBe(join(repo, 'a'));
+ expect(syncGitTopLevel(nested, 'run-1')).toBe(toplevels());
+ rmSync(join(repo, 'a', '.git'), { recursive: true, force: true });
+ expect(syncGitTopLevel(nested, 'run-1')).toBe(repo);
+ // A replaced .git at the top level is read again.
+ renameSync(join(repo, '.git'), join(home, 'top-level-old-git'));
+ git(repo, 'init', '-q');
+ const before = reads();
+ expect(syncGitTopLevel(nested, 'run-1')).toBe(repo);
+ if (counter) expect(reads()).toBe(before + 1);
+ });
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 43d4e6ee2f..622d62e476 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -61,6 +61,7 @@ test/managed-sync-group-uncommitted-head.test.ts
test/managed-sync-images-5493.test.ts
test/managed-sync-lanes.test.ts
test/managed-sync-page-fault-holds.test.ts
+test/managed-sync-pinned-reads.test.ts
test/managed-sync-preparation-stalled-holds.test.ts
test/managed-sync-row-parity.test.ts
test/managed-sync-stale-group-head.test.ts