Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: managed sync makes no object fetches in a partial clone (GST-2331)

garrytanae6d5958b8a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 39b70a3448..1f77c91bc0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A managed sync no longer fetches Git objects in a partial clone (`git clone --filter`).** Every Git read a managed sync makes now runs with Git's transports and lazy fetching switched off. A file whose blob the clone never fetched is imported from your checkout when the checkout holds exactly that blob, and otherwise held alone as `git_object_missing`, with a message that names the partial clone and the `git cat-file -p <blob>` that fetches it. A blobless clone with a normal checkout syncs every file as before.
+
+### Itemized changes
+
+- `src/core/hardened-git.ts`: `NO_LAZY_FETCH_ENV` (`GIT_NO_LAZY_FETCH=1`, Git 2.45+) is what a managed-sync read that runs under `gitChildEnv` adds beside `HARDENED_GIT_ARGS`, whose `protocol.allow=never` fails an object fetch on any Git version.
+- `syncGit` and `syncGitAsync` (`sync-discovery.ts`), every read in `sync-blobs.ts` (`ls-tree`, `cat-file --batch`), the `git show` fallback, the delta and working-tree diff (`sync-delta.ts`), the rename-identity `cat-file` stream, the metafile head reads, the origin-evidence history walk and ignore check, the held-deletion read, the unindexed-file listing and the pending-import checks now run with both.
+- `src/core/persistence/sync-entry-fault.ts`: in a partial clone the `git_object_missing` hold names the partial clone and its fix is `git cat-file -p <blob>`; in any other checkout it still names `git fsck --connectivity-only`.
+- A partial clone with no checkout (`--no-checkout`) holds every committed file `git_object_missing`. When rename detection needs an older blob the partial clone lacks, the sync compares the whole tree instead: the new path imports as a new page and the old page is deleted, so that rename does not keep its page.
+- Tests: `test/sync-partial-clone-2331.test.ts` on PGLite and Postgres, with a marker on the partial clone's object fetches and a check that it never ran, plus a blobless clone that syncs a second commit after a pull.
+
## [0.60.648.0] - 2026-11-10
**A managed sync no longer imports a file that Git stores through a filter, such as a git-crypt encrypted note, as if its stored bytes were the page.** The file alone is held `content_filter_owned` with a message that says gbrain does not run a repository's filter programs during sync (and names git-crypt when the file starts with its header), and the rest of the source imports and moves on. Reported by @JustinTSmith (#9024) and first fixed by @Masashi-Ono0611 (#9026).
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 5f22b705a0..a07dcc73a1 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -58,6 +58,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters behind the `src/commands/sync.ts` façade, which re-exports them; `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the other `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, OS-relative paths normalized to Git slash form by `gitRelativePath`, and the delete/rename slug resolvers (`resolveSlugByPathOrSourcePath` — see its dedicated entry above — plus the verified `resolveSlugsForRemovedPaths`/`resolveRemovedPathSlug`). `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate), with stored paths normalized before scope filtering, plus sync deadline/stall resolution (the default and env deadlines are progress-aware; `syncWatchdogPlan` and `syncDeadlineStopNotice` build the watchdog options and its stdout stop notice — see the `process-watchdog.ts` entry). `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row. GBRA-133 2b.3: a `--no-pull` estimate (`estimateInlineNewTokens` / `CostGateContext.noPull`) prices local HEAD and never fetches origin. `sync-git.ts` adds `gitAsync` / `discoverGitRootAsync` / `isDetachedHeadAsync`, which classic sync preflight, finalize, the lossless delta, upstream observation and the source filesystem lock now use, so a resident sync spawns no synchronous Git.
-- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper, consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`). NO dirty/untracked probe in the estimator — pricing dirty files would create phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget, `GIT_OPTIONAL_LOCKS=0` (`git-env.ts` `GIT_READ_ENV`: sync's Git reads never take `index.lock`). Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`. Classic sync reads the same delta as bytes instead: `computeLosslessSyncDelta` / `buildLosslessWorkingTreeManifest` run `git diff --raw -z -M` (and `ls-files -z --others`) into a Buffer and `parseRawDiffZ` keeps each name exactly as Git has it (no trim, no unquoting); a name that is not UTF-8 or holds a control character goes to `unsupported` (present) or `gone` (left the tree) instead of the manifest, and a gitlink (mode 160000) that appears goes to `gitlinks`, never the manifest (seam `_setGitBytesRunnerForTests`). Managed discovery and the cost estimator keep `computeSyncDelta`. Pinned by `test/pathological/s-classic-byte-paths.test.ts`.
+- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper, consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`). NO dirty/untracked probe in the estimator — pricing dirty files would create phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget, `GIT_OPTIONAL_LOCKS=0` (`git-env.ts` `GIT_READ_ENV`: sync's Git reads never take `index.lock`). GST-2331: runs with `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`. Classic sync reads the same delta as bytes instead: `computeLosslessSyncDelta` / `buildLosslessWorkingTreeManifest` run `git diff --raw -z -M` (and `ls-files -z --others`) into a Buffer and `parseRawDiffZ` keeps each name exactly as Git has it (no trim, no unquoting); a name that is not UTF-8 or holds a control character goes to `unsupported` (present) or `gone` (left the tree) instead of the manifest, and a gitlink (mode 160000) that appears goes to `gitlinks`, never the manifest (seam `_setGitBytesRunnerForTests`). Managed discovery and the cost estimator keep `computeSyncDelta`. Pinned by `test/pathological/s-classic-byte-paths.test.ts`.
- `src/core/sync-byte-paths.ts` — classic sync's byte-exact names (GBRA-133). `classifyGitPathBytes` (strict UTF-8 with the BOM kept, no `[\x00-\x1f\x7f]`, else `not_utf8` / `control_character`); the `unsupported_path` hold key `encodeBytePathKey` (`/gbrain-bytes/` + the path with each byte outside a printable UTF-8 character, and `%`, as `%XX`; Git never emits a leading `/`, so it never equals a path) and `decodeBytePathKey` (canonical keys only, else null); `displayBytePath` (C escapes, 200-character cap); `bytePathItemId` (first 16 hex of the bytes' sha256); `bytePathRenameCommand` (printf octal escapes piped NUL-terminated to `xargs -0 git mv`, plain ASCII); `bytePathHoldGone` (lstat of the exact bytes; null for an ordinary key), read by `commands/sync/holds.ts` re-screen and full-sync settle; `unsupportedPathHoldFix`, dispatched by `gitHoldFix` (ask_user rename, argv a read-only `sources status`, then `sync --no-pull`).
- `src/commands/sync/unsupported-paths.ts` — classic sync's routing of the lossless delta's extras: `selectBytePaths` applies the manifest's scope / exclude / syncability filters (name probed with U+FFFD for bad bytes and `_` for control characters) and makes paths mode-relative; `holdUnsupportedPaths` writes each `unsupported_path` hold (`writeGitHold`, mode legacy, slug and page null, never gating the bookmark), schedules the holds of `gone` names to clear and prints one `gitlink_not_followed` line; `gitlinkFields` puts `gitlinks_not_followed` on the result (declared on `SyncResult` by module augmentation here) for the run that advances past them.
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.md
index a1b8b2fa72..407f1d5af8 100644
--- a/docs/architecture/key-files/files-and-sync-2.md
+++ b/docs/architecture/key-files/files-and-sync-2.md
@@ -19,14 +19,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth unless `SyncableOptions.metafilePage` says a nested one is a page: `metafileIsPage(path, head, mode)` is true for an `isNestedSkipMetafile` path whose closed leading frontmatter has a non-empty top-level `type:` or `title:` under `sync.metafile_pages` `typed` and no top-level `slug:` naming another page (#7341: such a file stays scaffolding instead of being held `frontmatter_slug_conflict`), the one default `DEFAULT_METAFILE_PAGES_MODE`; `off` skips every metafile; `readMetafilePagesMode` reads the key); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` adds the head of the file on disk, so a typed nested metafile page is mirrored and published like any page), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.
- `src/core/sync-metafile-pages.ts` — the head readers behind `sync.metafile_pages`: `metafilePagePredicate(mode, read, rootRelative)` (memoized, the `SyncableOptions.metafilePage` every classifying caller passes), `diskMetafileHeads(root)` (regular files only, never a symlink), `gitMetafileHeads(gitRoot, commits)` (first commit that has the path; `prime` batch-reads blobs a caller already streams through one `cat-file --batch-check` plus one `--batch`), `firstMetafileHead` (disk, then the last synced blob, so a deleted file is judged as last committed), `listMetafileNamedBlobs` (one `ls-tree`), and the classic backfill marker `sync.metafile_pages.applied.<source>` (`metafileBackfillDue` / `recordMetafilePagesApplied`, written with the bookmark): a source that has not finished a sync under `typed` adds its tree's nested metafile-named files to the next delta once. Managed sync instead folds the mode into the pass selection fingerprint (`sync-pass-run.ts`; unchanged under `off`). Only metafile-named paths are ever read. `config set sync.metafile_pages` refuses a value outside `typed | off` (`src/commands/config/sync-metafile-pages-value.ts`); the restore check and doctor `missing_recorded_files` (`persistence/detached-pages.ts`) judge a recorded nested metafile with the same disk-then-last-synced predicate `sync --full` uses. Pinned by `test/sync-metafile-pages.test.ts` (classic) and `test/persistence-sync-metafile-pages.test.ts` (managed, PGLite and Postgres).
-- `src/core/sync-rename-identity.ts` — the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption in `sync-discovery.ts`: two different explicit ids hold `legacy_slug_conflict`, reason `explicit_id_conflict`). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ. GBRA-133 S-51: an id, `slug:` or title holding U+0000 or a lone surrogate is absent before any SQL (never normalized), so the pair takes the ordinary unconfirmed-rename rules; both identity reads batch every path and, on SQLSTATE 22021/22P05 only, retry path by path, and the inexact pairs carrying a refused value come back in `heldRenames` (classic `preflight.ts` holds them as `rename_identity_unreadable`, keeping the old page; with `holdUnreadable` unset, as in managed discovery, the error is rethrown). `redecideHeldRename` decides a held pair again from the kept page's stored id and title once its file changes. Any other error propagates. Pinned by `test/pathological/s-51-rename-identity-unreadable.test.ts`.
+- `src/core/sync-rename-identity.ts` — the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads; GST-2331: under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a side a partial clone lacks reads as no identity and the pair is downgraded) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption in `sync-discovery.ts`: two different explicit ids hold `legacy_slug_conflict`, reason `explicit_id_conflict`). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ. GBRA-133 S-51: an id, `slug:` or title holding U+0000 or a lone surrogate is absent before any SQL (never normalized), so the pair takes the ordinary unconfirmed-rename rules; both identity reads batch every path and, on SQLSTATE 22021/22P05 only, retry path by path, and the inexact pairs carrying a refused value come back in `heldRenames` (classic `preflight.ts` holds them as `rename_identity_unreadable`, keeping the old page; with `holdUnreadable` unset, as in managed discovery, the error is rethrown). `redecideHeldRename` decides a held pair again from the kept page's stored id and title once its file changes. Any other error propagates. Pinned by `test/pathological/s-51-rename-identity-unreadable.test.ts`.
- `src/core/sync-identity-downgrades.ts` — durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv; the per-pair remedy every surface prints (`identityRemedyParts`, `identityRemedy`, `withIdentityRemedies`, `renameIdentityPreviewArgv`, `remedyAction`; on a managed brain the remedy is `--close` with `carry_unavailable: managed_remedy_unavailable`); `settleIdentityDowngrade` (sets `completed_keys[0].disposition = { kind: remedied | closed, at }` on an open record); `identityRestoreAvailable` (the decideUnboundWrite rule) keeps the restore off the report and doctor on an unbound Postgres source with a checkout, where it would refuse `owner_unavailable`.
- `src/core/repair/rename-identity.ts` — `gbrain repair rename-identity` (#6729), explicit-only, preview-bound, destructive. `plan` selects one open pair (`--slug`/`--from`), hashes `identityRemedyParts` (brain, pair, both page ids and revisions, disposition) and saves the approved set; with no pair named it lists the open pairs. On a managed brain a carry preview returns no items with `details.code: managed_remedy_unavailable` and the `--close` preview, and an apply refuses with that code. `carryIdentity` (classic only): one maintenance transaction under both page locks re-checks the hash, the open record and `fenceRowChecks`, merges matching fence rows onto the old rows, retires the provisional page under `purgedSlug`, moves the old page to the new slug (`updateSlug` redirect), moves the provisional's page-id rows (`movePageIdReferences`), imports the new file, settles the record `remedied`. `--close` settles `closed`. Refusals: `fact_rows_collide`, `managed_remedy_unavailable`, `changed_since_preview`, `preview_changed`, `invalid_params`.
- `src/core/persistence/sync-prescreen.ts` — #6712 PR 1 (L1): the discovery prescreen and drift baseline. After `discoverManagedSync` freezes identities, `prescreenSyncEntries` reads the pinned blobs (`readTreeBlobs`, one recursive listing for a large set) and the import provenance of every Git import of an existing page, and `classifyBaseline` marks each `prescreened` (disk blob, revision and `syncImportParserFor` fingerprint all match; bypassed under `--full` and for held paths) or `drift` (`database`: the page moved, the file did not; `both`/`unknown` in a tree walk or for a `file_drift` hold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-through `git` effect), is not guarded (`fileBackedRevisions`), and drifted pages under `storage.keep_db` prefixes leave the manifest as drift candidates (`releaseKeepDbDrift`, `recordDriftSkip`). The run passes prescreened entries through `waivePrescreenedRun` (`sync-waivers.ts`); `freezeEntry` holds a drifted import `file_drift` (`fileDriftHold`, `sync-page-fault.ts`) unless `sameContentAtOrigin` proves it a no-op. `movedDriftHolds` re-screens drift holds whose page moved. Tests: `test/sync-prescreen-drift-6712.test.ts` (both engines).
- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.
- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path; `slug` is the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin through `bindOrigin` (B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM), `streamed-sync-origin-b14.test.ts` (both engines).
-- `src/core/persistence/sync-entry-fault.ts` — GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source. `nullBytesRefusal` holds a Markdown text with U+0000 `content_null_bytes` (line of the first NUL; a UTF-16 byte order mark says save as UTF-8), from `screenFrozenImport` with holds on and as a typed run stop under `sync.holds=fail`. `filterOwnedRefusal` (GST-2312, #9024), checked first on the same two paths, holds `content_filter_owned` a blob starting with git-crypt's header or a committed blob whose path names a Git filter driver other than `lfs`, configured here or not (`pinnedFilterDriver` in `sync-screen.ts`, at the pinned commit or a company plan's revision, read with `readFilterDrivers`' batched `git check-attr --source` on git 2.40+, or `read-tree` into a temporary index and `check-attr --cached` on an older git; with `HARDENED_GIT_ARGS` and `GIT_NO_LAZY_FETCH=1`, so the attribute read runs no repository program and fetches nothing; it first checks with `ls-tree` and `cat-file --batch-check` that each `.gitattributes` that applies is present, and a path under a missing one makes `pinnedFilterDriver` throw `git_object_missing` via `missingAttributesRefusal`; `NO_REPOSITORY_PROGRAMS` keeps `core.fsmonitor` and hooks off the module's other reads, whose blob reads this change leaves as they were). `committedContentOrMissing` (called by `pinnedContent` when the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throws `git_object_missing`; a committed name with U+FFFD that names nothing on disk (a name that is not UTF-8) throws `path_not_utf8` first. `directoryAt` lets a deletion whose name became a directory apply (freeze and the owner's raw-hash check). `freezeFaultHold` is `freezeEntry`'s catch (`sync-run.ts` wraps `freezeEntryOnce`): `git_object_missing` and `path_not_utf8` are held under their codes; a page-body fault (`PAGE_BODY_FAULT_CODES`: `page_body_segmented`, `page_body_rows_unreadable`, e.g. a segmented page whose segment rows don't cover its body) is held `page_write_failed` with `write_failure.code` set to that code, which `sync status` classifies by the `freeze_page_body_*` rows of `SYNC_FAULT_TABLE`; any other `OperationError` and every run-scoped error (`classifyItemFailure` scope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is held `page_write_failed` with `write_failure.origin: 'freeze'` and `request_id: null`, re-tested by every sync until held `HOLD_ATTEMPTS_NEEDS_HUMAN` times; a run with `ITEM_BREAKER_MIN_ITEMS` faults and no more clean freezes than faults is systemic and rethrows.
+- `src/core/persistence/sync-entry-fault.ts` — GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source. `nullBytesRefusal` holds a Markdown text with U+0000 `content_null_bytes` (line of the first NUL; a UTF-16 byte order mark says save as UTF-8), from `screenFrozenImport` with holds on and as a typed run stop under `sync.holds=fail`. `filterOwnedRefusal` (GST-2312, #9024), checked first on the same two paths, holds `content_filter_owned` a blob starting with git-crypt's header or a committed blob whose path names a Git filter driver other than `lfs`, configured here or not (`pinnedFilterDriver` in `sync-screen.ts`, at the pinned commit or a company plan's revision, read with `readFilterDrivers`' batched `git check-attr --source` on git 2.40+, or `read-tree` into a temporary index and `check-attr --cached` on an older git; with `HARDENED_GIT_ARGS` and `GIT_NO_LAZY_FETCH=1`, so the attribute read runs no repository program and fetches nothing; it first checks with `ls-tree` and `cat-file --batch-check` that each `.gitattributes` that applies is present, and a path under a missing one makes `pinnedFilterDriver` throw `git_object_missing` via `missingAttributesRefusal`; GST-2331: every read of `sync-blobs.ts` runs with `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so the blob reads fetch nothing either and an object a partial clone lacks reads as missing). `committedContentOrMissing` (called by `pinnedContent` when the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throws `git_object_missing` (GST-2331: in a partial clone, a promisor remote or `extensions.partialClone` read with `syncGit config --get-regexp`, the message names the partial clone and the fix is `git cat-file -p <blob>`; otherwise `git fsck --connectivity-only`); a committed name with U+FFFD that names nothing on disk (a name that is not UTF-8) throws `path_not_utf8` first. `directoryAt` lets a deletion whose name became a directory apply (freeze and the owner's raw-hash check). `freezeFaultHold` is `freezeEntry`'s catch (`sync-run.ts` wraps `freezeEntryOnce`): `git_object_missing` and `path_not_utf8` are held under their codes; a page-body fault (`PAGE_BODY_FAULT_CODES`: `page_body_segmented`, `page_body_rows_unreadable`, e.g. a segmented page whose segment rows don't cover its body) is held `page_write_failed` with `write_failure.code` set to that code, which `sync status` classifies by the `freeze_page_body_*` rows of `SYNC_FAULT_TABLE`; any other `OperationError` and every run-scoped error (`classifyItemFailure` scope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is held `page_write_failed` with `write_failure.origin: 'freeze'` and `request_id: null`, re-tested by every sync until held `HOLD_ATTEMPTS_NEEDS_HUMAN` times; a run with `ITEM_BREAKER_MIN_ITEMS` faults and no more clean freezes than faults is systemic and rethrows.
- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`.
- `src/core/url-source-origin.ts`, `src/commands/sources-record-origin.ts` and `src/commands/doctor/checks/url-source-origin.ts` — who added a URL source (`sources.config.added_by_remote_caller`). Both add paths write it (`true` for a remote caller, `false` for the local operator); only an explicit `true` reads as remote. URL sources added before that record existed carry none, and nothing stored tells a remote caller's add from the local operator's (same row, same default clone directory); a clone outside `$GBRAIN_HOME/clones/<id>` (or a `clones/<id>` under an earlier home) proves a local add. A URL clone counts when `isOwnedClone` accepts it, so an unmarked clone at the default directory is listed too. `urlSourcesWithoutOrigin` (read-only) feeds the wave check `url_source_origin` (host-only, `resolution: 'operator'`, `warn` with an `ask_user` fix whose argv is the preview). `recordSourceOrigin(engine, ids, { origin, apply, remote })` backs `gbrain sources record-origin <id>... --remote|--local [--apply] [--json]`: it throws `trusted_local_only` unless `remote === false`, previews unless `apply`, writes `true` (`--remote`) or `false` (`--local`) in one transaction that re-reads the row `FOR UPDATE` and refuses `source_changed` if its path or URL moved; on a managed brain that transaction runs inside `withTopologyLocks` after `lockTopologyRows`, the locks a reclone takes (a held lock refuses the id `source_busy`), and `runManagedSourceClone` takes the config it clones with from its own locked admission read, so a record and a reclone never interleave. `--remote --apply` also writes `LFS_OFF_CLONE_CONFIG` into the repository's shared config (`--git-common-dir`; `git config --file`, not run in the checkout) before the row, reads the effective values back (`lockDownGaps`) and throws when a worktree-scoped or included setting overrides one, and locks down an already-remote source whose checkout lacks it (no git-lfs refusal for it unless Git cannot place the checkout, `lfs_unknown`); each key's existing values are removed before its one value is written, in a `config.lock` copy renamed over the config in one step; a throw is reported for its id as `write_failed` and the batch continues. It never removes a `true`, and refuses `--remote` for a checkout with any tracked `filter=lfs` path or a committed `.gitattributes` declaring `filter=lfs` outside a comment line (`lfs_tracked`, worded per case; read with `hardenedGitSync` `ls-files -- ':(attr:filter=lfs)'` plus every committed `.gitattributes` blob from `ls-tree -z` records split at their first tab, then `cat-file`, so clone-local attributes cannot hide one, and read again under the locks), or one it cannot inspect (`lfs_unknown`, whose reason names the cause: checkout missing, not its own repository's top level by a realpath comparison, owned by another user (`safe.directory`), or a Git read failed), because a lock-down reclone would not match the stored writer manifest there. An unborn HEAD with an empty index (a clone of an empty repository) has no committed attributes and passes. Without git-lfs files the tracked bytes are the same, so no manifest is written. Pinned by `test/url-source-origin.test.ts` (PGLite and Postgres).
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index be44cf9e93..1f9fc9b1b1 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -40,6 +40,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/write-gate-scan.ts` + `scripts/trust-dry-run-scan.ts` — read-only exposure scan: keyset batches over pages, facts, takes and timeline entries, tier projected from deterministic signals (connector source, webhook/clipper page, `mcp:*`/capture/transcript page, agent fact lanes, `persistence_requests` operation and authority; none -> `unknown`), flag/quarantine counts and families per tier and table, counts and pattern names only. The script runs it in a REPEATABLE READ READ ONLY transaction (PGLite: on a copy of the data directory). Test: `test/write-gate-scan.test.ts`.
-- `src/core/git-env.ts` + `src/core/hardened-git.ts` — #7584, the operator's `safe.directory` in scrubbed Git environments: `hardenedGitEnvironment` still drops system and global config and every `GIT_*` variable, but carries the operator's `safe.directory` entries (system and global, read from `/` with `git config --includes --show-scope` and cached for 30 s, then `GIT_CONFIG_*`) as environment config, so a source repository owned by another user reads once the operator allows it. `gitChildEnv` carries the environment entries the same way (`envSafeDirectories`, `safeDirectoryEnv`). Every other key in those places stays out. `gitChildEnv` also drops Git's global pathspec switches (`GIT_PATHSPEC_ENV_VARS`: `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_ICASE_PATHSPECS`; `extra` can still set one). gbrain's writers mark each path literal with `literalPathspecs` (`:(literal)<path>`), never `git --literal-pathspecs`, which Git exports to every hook and child as `GIT_LITERAL_PATHSPECS=1`, where a hook's glob pathspec then matches nothing. Tests: `test/hardened-git-safe-directory-7584.test.ts` (ownership forced with `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper on PATH), `test/git-literal-pathspec-hooks-7759.test.ts`.
+- `src/core/git-env.ts` + `src/core/hardened-git.ts` — #7584, the operator's `safe.directory` in scrubbed Git environments: `hardenedGitEnvironment` still drops system and global config and every `GIT_*` variable, but carries the operator's `safe.directory` entries (system and global, read from `/` with `git config --includes --show-scope` and cached for 30 s, then `GIT_CONFIG_*`) as environment config, so a source repository owned by another user reads once the operator allows it. `gitChildEnv` carries the environment entries the same way (`envSafeDirectories`, `safeDirectoryEnv`). Every other key in those places stays out. `gitChildEnv` also drops Git's global pathspec switches (`GIT_PATHSPEC_ENV_VARS`: `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_ICASE_PATHSPECS`; `extra` can still set one). gbrain's writers mark each path literal with `literalPathspecs` (`:(literal)<path>`), never `git --literal-pathspecs`, which Git exports to every hook and child as `GIT_LITERAL_PATHSPECS=1`, where a hook's glob pathspec then matches nothing. GST-2331: `NO_LAZY_FETCH_ENV` (`GIT_NO_LAZY_FETCH=1`) is what a managed-sync read that runs under `gitChildEnv` adds beside `HARDENED_GIT_ARGS`, so a partial clone fetches nothing (Git before 2.45 ignores the variable, and `protocol.allow=never` fails the fetch): `syncGit`/`syncGitAsync`, every read in `sync-blobs.ts`, `sync-delta.ts`'s text runner (a rename whose old blob the clone lacks fails the diff, `diff_failed`, and discovery walks the whole tree), `sync-rename-identity.ts`, `sync-metafile-pages.ts`, `sync-origin-evidence.ts`, `sync-held-deletions.ts`, `unindexed-files.ts` and `pending-import.ts`. Tests: `test/hardened-git-safe-directory-7584.test.ts` (ownership forced with `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper on PATH), `test/git-literal-pathspec-hooks-7759.test.ts`, `test/sync-partial-clone-2331.test.ts`.
- `src/core/outside-content.ts` — GBRA-221: `neutralizeOutsideText(text)`, the one neutralizer for text a third party wrote before it lands in a page body (Gmail/Calendar/Contacts renders in `google-render.ts`, GitHub `renderItemPage`/`renderRepoCard`, chat transcripts in `transcripts/render.ts`, `book-mirror` chapter output). It escapes every `gbrain<ws>:<ws><name>` marker token to `gbrain\:<name>` (case-insensitive), `[Source:` to `[Source\:`, and backslash-prefixes each timeline sentinel, bare `## Timeline`/`## History` heading, dated timeline row or heading, transcript message anchor and date heading, using the parsers' own predicates. Idempotent and readable; apply it per outside field (or a composed line holding one), never to a whole page that may hold gbrain's own fences or citations. Also owns `escapeAnchorLines` and `MESSAGE_ANCHOR_RE` (re-exported by `transcripts/render.ts`). New connectors use it.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 713700cebc..a6df210a6d 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2118,7 +2118,7 @@ More: [docs/guides/write-refusals.md#git_lfs_not_enabled](../../docs/guides/writ
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone. | An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing. | Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold. | agent | `repeat the read that failed` | 1 | no |
+| A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone. | An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing. | In a partial clone (git clone --filter), which sync never fetches from, fetch the blob with git cat-file -p <blob> in the checkout or check the file out; otherwise run git fsck in the checkout to see what is missing and restore it with git fetch (a shallow clone) or from a backup. Then sync again; every sync re-tests the hold. | agent | `repeat the read that failed` | 1 | no |
More: [docs/guides/write-refusals.md#git_object_missing](../../docs/guides/write-refusals.md#git_object_missing)
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 877686bde6..69b619a30b 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -108,8 +108,8 @@ of making a duplicate.
| `file_unreadable` (sync hold) | `file_unreadable` | A managed sync held one file because it is not a readable regular file inside the source root: a symlink (to a file outside the root or inside it), a non-regular file, or a permission or loop error. Sync never reads or follows it. Until GBRA-130 the whole sync stopped at that file on every run and the rest of the source never imported; now only the file waits. A source root that is itself replaced by a symlink still refuses the whole sync. | Make the file a readable regular file in the checkout (replace the symlink with the file, fix its permissions) or exclude it with `sync.exclude`, and commit. A commit that changes it re-screens the hold on the next sync; after a permission fix run `gbrain sources retry-held <source>`, then the same sync. |
| <a id="page_write_failed"></a>`page_write_failed` (sync hold) | `page_write_failed` | A managed sync held one file because its write failed the same way three times (the same code, origin, error class and SQLSTATE in this source), with an error gbrain cannot classify: an owner exception (for example Postgres 54000 when a frontmatter tag is too long for its index), or a refusal the receipt does not explain. Until GBRA-130 every sync stopped `blocked_by_failures` at that file and the rest of the source never imported; now the file is held and the rest of the source syncs. The first two failures still stop the run, so a one-off defect never holds a file. | Read the receipt the hold names (`gbrain write-request <request_id>`, read-only). Fix the file when the error names its content (shorten the tag, split the page), or report the receipt with the gbrain version. Then `gbrain sources retry-held <source>` and the same sync. An upgrade re-tests the file on its own. A hold whose `meta.write_failure.origin` is `freeze` (GBRA-133) is different: sync could not even prepare the file (an unexpected error while reading or screening it, before any request was admitted), so it holds it on the first failure and names the error in the hold message; the next syncs re-test it on their own until it has been held 3 times, so a transient fault clears without help. When most files of one run fail that way the run stops instead (the cause is not the files). |
| <a id="content_null_bytes"></a>`content_null_bytes` (sync hold) | `content_null_bytes` | A managed sync held one Markdown file because its text holds NUL bytes (U+0000). Page text is stored as UTF-8 without NUL bytes. The usual cause is a UTF-16 file (a Windows "Unicode" save; the hold says so when the file starts with a UTF-16 byte order mark), a binary file named `.md` or a crash-padded file. Until GBRA-133 the whole managed sync stopped at that file on every run (`storage_error`, SQLSTATE 22P05) and the rest of the source never imported; now only the file waits. With `sync.holds=fail` the run stops with `content_null_bytes` instead of holding. | Save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or leave it out with `sync.exclude`), then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. |
-| <a id="content_filter_owned"></a>`content_filter_owned` (sync hold) | `content_filter_owned` | A managed sync held one committed file because Git stores it through a filter: its path has a `filter` attribute at the synced commit naming a clean/smudge driver (whether or not this checkout's Git config defines it, since the commit may have been cleaned on another machine), or its bytes start with git-crypt's header. The committed bytes are what the filter's clean program wrote (git-crypt ciphertext, for one), not the text in your checkout, and gbrain does not run a repository's filter programs during sync, so it cannot turn them into text. Sync reads the attribute at the synced commit with `git check-attr --source` (git 2.40 or newer) or, on an older git, from a temporary index of that commit with `check-attr --cached`. Those reads run with fsmonitor, hooks and every Git transport switched off and with lazy fetching off, so reading the attribute runs no repository program and fetches nothing; when a partial clone lacks a `.gitattributes` that applies to the file, the file is held `git_object_missing` instead. This release does not change how sync reads the file's own blob; object fetches in partial clones are handled in a follow-up. A plain-text file under a `filter` attribute nobody uses is held too: the hold is the safe side and loses nothing. Before, a filtered file imported its stored bytes as the page text, and a git-crypt file was held `content_null_bytes`. A page imported from such a file before this release is left as it is until the file changes. Git LFS pointers are not this hold. With `sync.holds=fail`, and on a company-brain source, the run stops with `content_filter_owned` instead of holding. | Leave the file out with `sync.exclude`, or commit it without the filter so Git stores its text, then `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. For a plain-text file under a filter attribute nobody uses, remove the attribute from `.gitattributes`, commit, and run `gbrain sources retry-held <source>`: a commit that changes only `.gitattributes` does not re-screen the file. |
-| <a id="git_object_missing"></a>`git_object_missing` (sync hold) | `git_object_missing` | A managed sync held one committed file because the commit names a Git object the checkout no longer has (an interrupted `git gc`, a partial clone without its promisor remote, disk corruption) and the working-tree copy differs from it or is gone, or because a partial clone lacks a `.gitattributes` that applies to the file at that commit, so sync cannot read whether a Git filter owns it (sync fetches nothing to find out). When the working-tree bytes hash to the committed blob id, sync imports them and holds nothing. Until GBRA-133 the whole managed sync stopped at that file on every run. | Run `git fsck --connectivity-only` in the checkout to see what is missing, restore it with `git fetch` (a partial or shallow clone) or from a backup, then `gbrain sync --source <source> --no-pull`. Every sync re-tests the hold. |
+| <a id="content_filter_owned"></a>`content_filter_owned` (sync hold) | `content_filter_owned` | A managed sync held one committed file because Git stores it through a filter: its path has a `filter` attribute at the synced commit naming a clean/smudge driver (whether or not this checkout's Git config defines it, since the commit may have been cleaned on another machine), or its bytes start with git-crypt's header. The committed bytes are what the filter's clean program wrote (git-crypt ciphertext, for one), not the text in your checkout, and gbrain does not run a repository's filter programs during sync, so it cannot turn them into text. Sync reads the attribute at the synced commit with `git check-attr --source` (git 2.40 or newer) or, on an older git, from a temporary index of that commit with `check-attr --cached`. Those reads run with fsmonitor, hooks and every Git transport switched off and with lazy fetching off, so reading the attribute runs no repository program and fetches nothing; when a partial clone lacks a `.gitattributes` that applies to the file, the file is held `git_object_missing` instead. Every other Git read of a managed sync fetches nothing either (see `git_object_missing`). A plain-text file under a `filter` attribute nobody uses is held too: the hold is the safe side and loses nothing. Before, a filtered file imported its stored bytes as the page text, and a git-crypt file was held `content_null_bytes`. A page imported from such a file before this release is left as it is until the file changes. Git LFS pointers are not this hold. With `sync.holds=fail`, and on a company-brain source, the run stops with `content_filter_owned` instead of holding. | Leave the file out with `sync.exclude`, or commit it without the filter so Git stores its text, then `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. For a plain-text file under a filter attribute nobody uses, remove the attribute from `.gitattributes`, commit, and run `gbrain sources retry-held <source>`: a commit that changes only `.gitattributes` does not re-screen the file. |
+| <a id="git_object_missing"></a>`git_object_missing` (sync hold) | `git_object_missing` | A managed sync held one committed file because the commit names a Git object the checkout no longer has (an interrupted `git gc`, a partial clone without its promisor remote, disk corruption) and the working-tree copy differs from it or is gone, or because a partial clone lacks a `.gitattributes` that applies to the file at that commit, so sync cannot read whether a Git filter owns it (sync fetches nothing to find out). When the working-tree bytes hash to the committed blob id, sync imports them and holds nothing. A managed sync never fetches a missing object: every Git read it makes runs with Git's transports and lazy fetching switched off, so in a partial clone (`git clone --filter`) a blob the clone never fetched fails the read and the hold names the partial clone. A blobless clone with a normal checkout syncs as usual, because checking out fetched every file it holds; a partial clone with no checkout (`--no-checkout`) holds every committed file. When rename detection needs an older blob the partial clone lacks, the sync compares the whole tree instead, so the new path imports as a new page and the old page is deleted. Until GBRA-133 the whole managed sync stopped at that file on every run. | In a partial clone, fetch the blob the hold names with `git cat-file -p <blob>` in the checkout (or check the file out), then `gbrain sync --source <source> --no-pull`. Otherwise run `git fsck --connectivity-only` in the checkout to see what is missing, restore it with `git fetch` (a shallow clone) or from a backup, then sync the same way. Every sync re-tests the hold. |
| <a id="path_not_utf8"></a>`path_not_utf8` (sync hold) | `path_not_utf8` | A managed sync held one committed file because its name is not valid UTF-8 (a Latin-1 name from an older system, an archive or a network share). Git hands the name back with U+FFFD for the bytes that are not UTF-8, and no Git read or file matches that decoded name, so nothing is imported from it. Until GBRA-133 the managed sync either stopped at that file on every run or skipped it with no hold; now only the file waits and the hold names it. With `sync.holds=fail` the run stops with `path_not_utf8` instead of holding. | Rename the file to a UTF-8 name (`git -c core.quotePath=true ls-files` shows its exact bytes; `convmv -f latin1 -t utf8` converts a Latin-1 name), commit, then `gbrain sync --source <source> --no-pull`. The rename clears the hold. |
| <a id="write_interrupted"></a>`write_interrupted` | `write_interrupted` | A transient interruption kept ending this managed write: the database ended its own statements (SQLSTATE `57014`, a statement timeout or cancel) at preparation or inside its publication transaction, a statement inside that transaction ran on a plan cached before a migration changed its table (SQLSTATE `0A000`, "cached plan must not change result type"; the next claim prepares it again), or its publication ran past `persistence.publication_ceiling_ms` and its grace and the owner cancelled it. Each interruption throws the preparation away, but it is load or latency, not the write's content, so it has its own budget: the request is claimed again after a backoff (1 s, 2 s, 4 s, 8 s, then 15 s, scheduled on the request as `next_attempt_at`; no claim, root lock or connection is held while it waits, and `gbrain sources writer status` names the waiting head `transient_backoff`) up to `persistence.max_transient_retries` times (default 5, 0 to 20), and the next interruption finishes it `failed` instead of preparing it again without limit. Interruptions never spend `persistence.max_preparation_attempts`, which preparations cut off at their deadline keep ([`preparation_stalled`](#preparation_stalled)). Nothing was published: a worktree-backed write's canonical file is restored before the failure is recorded. Contention with other transactions (`55P03` lock timeout, `40001` serialization failure, `40P01` deadlock) is released as `database_contention` uncounted, and a dropped connection or a database that is restarting or out of connections is never counted. The receipt's message and owner-only `error_detail` name the interruptions (`attempts`), the retry limit (`limit`, `limit_key`), the `cause` (`statement_cancel`, `stale_plan` or `publication_ceiling`) and the SQLSTATE (`sqlstate`, public). A managed sync member is held like [`preparation_stalled`](#write_interrupted-hold): the run moves past it and the rest of the source lands, `gbrain sync status` lists the hold (class `page`, safe action `retry`, [runbook row](sync-unblock-runbook.md)), and `gbrain sources retry-held` re-admits it. A group's shared read the database cancels is charged once, to the first member that settles with it, never to every member; and the charge commits with the claim's release, so a crash between them never counts it twice. With `persistence.preparation_deadlines` off nothing is counted and no backoff applies. | Run `gbrain sources writer status --source <source> --json` (read-only: the owner, its pool, what its writes wait on), then submit the write again with a new `request_id` once the database is less loaded; for a held sync file, run `gbrain sources retry-held <source>` and the same sync with its options. A `publication_ceiling` cause on a page that legitimately takes longer to publish is the user's call: ask before raising `persistence.publication_ceiling_ms` (or the database `statement_timeout` for a `statement_cancel`). If the same write ends this way again, report its request id with `gbrain doctor --json`. Do not raise `persistence.max_transient_retries` to get past it. |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index a11262cfb7..03958a92f1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1701 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move)
+src/core/behavior-change-notice.ts 1702 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (since TBD until the merge slot; rows are data and cannot move)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index a5ad0e6eb1..748f34f491 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1503,6 +1503,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.637.0', id: 'purge_keeps_committed_file_gst2201', text: 'The retention purge (the autopilot purge phase, the `purge` job and `gbrain pages purge-deleted`) never removes a soft-deleted page\'s file that is committed at its source\'s last synced commit or at HEAD. A page sync deleted whose file is back is left for the sync that restores it (counted as deferred); any other such page is removed database-only (receipt `write_through.skipped: committed_file`) and its file stays. A page whose file is gone, or a person\'s delete that never removed its file (for example because another page shared it), purges as before. A page purge (`gbrain delete <slug> --purge` and the retention purge) now also redacts the timeline text the page\'s `add_timeline_entry` receipts kept (the entry\'s summary and source, `bullet`), compacted ones included.' },
{ since: '0.60.647.0', id: 'remember_share_gst2243', text: 'A member credential\'s `remember` still saves privately on `memory/members/<member>` by default, and can now pass `share: true` to save the fact on its subject\'s page for everyone who reads the source, as every non-member caller does. A member\'s explicit `visibility: "world"`, which used to be saved as private without a word, is now refused (`invalid_params`, reason `member_share_required`) and nothing is saved; `share: true` with `visibility: "private"`, or onto a page whose facts are kept private, is refused too (`share_target_restricted` for the page). Only the brain host can withdraw a shared fact. With ambient writeback on, a member credential\'s instructions say to omit `visibility` and use `share: true` for team facts, and a credential that may name a member through `x-qm-actor` is told to do so on those calls and pass `visibility: "world"` on the rest. Every `remember` reply, for any caller, now names the `page` the fact went to and its `visibility`. QM\'s `memory_write` is unchanged.' },
{ since: '0.60.648.0', id: 'sync_filter_owned_hold_9024', text: 'A managed sync now holds a committed file that Git stores through a filter (a path whose `filter` attribute at the synced commit names a driver other than Git LFS, whether or not this checkout configures that driver, or a file starting with git-crypt\'s header) as `content_filter_owned`, and the rest of the source syncs. Before, such a file imported its stored bytes (git-crypt ciphertext, for one) as the page text, or a git-crypt file was held `content_null_bytes`. gbrain still never runs a repository\'s filter programs (or `core.fsmonitor`) during sync, and reading the filter attribute fetches nothing, so a partial clone that lacks a `.gitattributes` that applies to the file holds it `git_object_missing`; the hold names git-crypt when the header matches and says to leave the file out with `sync.exclude` or commit it without the filter, and for a plain-text file under a filter attribute nobody uses, to remove the attribute and run `gbrain sources retry-held`. A page an older version already imported from such a file is left as it is until the file changes; then the file is held. With `sync.holds=fail`, and on a company-brain source (which never holds), the run stops with `content_filter_owned`. Classic (unmanaged) sync is unchanged.' },
+ { since: 'TBD', id: 'sync_reads_fetch_nothing_gst2331', text: 'A managed sync now makes no object fetches in a partial clone (`git clone --filter`): every Git read it makes runs with Git\'s transports and lazy fetching switched off. A committed file whose blob the partial clone never fetched imports from the working tree when those bytes are the committed blob, and is otherwise held `git_object_missing` with a message that names the partial clone and the `git cat-file -p <blob>` that fetches it; a partial clone with no checkout holds every committed file this way. A blobless clone with a normal checkout syncs as before. When rename detection needs an older blob the partial clone lacks, the sync compares the whole tree instead: the new path imports as a new page and the old page is deleted, so that rename does not keep its page. Before, the sync fetched a missing object from the partial clone\'s remote.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5ff2c4b818..a8ffd3e3be 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -382,7 +382,7 @@ export const CODES = {
git_target_ignored: { class: 'caller', summary: "A .gitignore rule excludes the canonical file, so its Git effect cannot commit it; the effect parks at once.", suggestion: 'Remove or narrow the rule and commit that change, then run gbrain sources writer retry-effects <source> --parked-code git_target_ignored; or keep the file out of Git and leave the effect parked.' },
git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },
git_unavailable: { class: 'retryable', summary: "A git command did not complete." },
- git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },
+ git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'In a partial clone (git clone --filter), which sync never fetches from, fetch the blob with git cat-file -p <blob> in the checkout or check the file out; otherwise run git fsck in the checkout to see what is missing and restore it with git fetch (a shallow clone) or from a backup. Then sync again; every sync re-tests the hold.' },
git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'held_drift_unknown_differs', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database', 'ignore_status_unknown', 'no_record_both_moved', 'no_record_no_evidence'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; no_record_both_moved and no_record_no_evidence, a page with no import record whose content history shows both sides moved, or shows nothing, until the owner's --decisions file decides it; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted; ignore_status_unknown, a target whose ignore status Git cannot read (beyond a symlink, outside the checkout, a timed-out check). There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },
git_conversion_delta: { class: 'consent', actor: 'user', summary: "An approved conversion found pages that changed since the approval, or decisions it did not approve, so only the unchanged pages were applied and the source stays mixed.", why: "gbrain sources canonical --to git --apply --approved applies only the pages whose slug, revision, committed blob, evidence and action are the ones the owner approved. A page that changed since, a new page, a database edit the plan would now discard, and any decision the approval did not hold stay unapplied and are listed (delta) with counts; nothing outside the approved set is applied without a new decision.", docs: 'docs/guides/git-canonical.md#approval-across-time', suggestion: 'Relay the delta list and its counts to the owner; once they decide, preview again with --approval-out and apply the new approval.' },
conversion_file_in_source_root: { class: 'caller', summary: "A conversion review list, decisions file or approval was refused because its path is inside a source's checkout.", why: "Those files name pages and paths. Written or read only outside every registered source root and the Git working tree holding it (mode 0600), they can never be synced, imported or committed.", docs: 'docs/guides/git-canonical.md#review-list-and-decisions', suggestion: 'Pass a path outside every source checkout, e.g. under ~/.gbrain.' },
diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.ts
index 50092d59ad..aa8b122098 100644
--- a/src/core/hardened-git.ts
+++ b/src/core/hardened-git.ts
@@ -28,6 +28,14 @@ export const HARDENED_GIT_ARGS: readonly string[] = ['--no-pager', '--no-optiona
'-c', 'submodule.recurse=false', '-c', 'protocol.allow=never', '-c', 'credential.helper=',
'-c', 'maintenance.auto=false', '-c', 'gc.auto=0'];
+/**
+ * GST-2331: what a managed-sync Git read that runs under `gitChildEnv` adds to it beside `HARDENED_GIT_ARGS`. In a partial
+ * clone, Git fetches an object the repository lacks, and a fetch is configured by the checkout; `GIT_NO_LAZY_FETCH=1`
+ * (Git 2.45+) reports the object missing instead, and the args' `protocol.allow=never` fails the fetch on any Git, so the
+ * read fails and nothing is fetched.
+ */
+export const NO_LAZY_FETCH_ENV: NodeJS.ProcessEnv = { GIT_NO_LAZY_FETCH: '1' };
+
const OPERATOR_CONFIG_TTL_MS = 30_000;
let operatorConfig: { key: string; at: number; values: string[] } | null = null;
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index ef376a569b..325e91a1cb 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -22,6 +22,7 @@ import { isAbsolute, join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { gitChildEnv } from '../git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from '../hardened-git.ts';
import { opError, type OperationError } from '../ops/contract.ts';
import { PENDING_IMPORT_MESSAGE, PENDING_IMPORT_OWNER } from './verb-errors.ts';
@@ -43,12 +44,12 @@ function gitRead(root: string, args: string[], signal?: AbortSignal): Promise<st
return gitBytes(root, args, signal).then(out => out.toString('utf8'));
}
-/** #8826: gitRead's stdout as bytes, for an answer that must not be decoded lossily. */
+/** #8826: gitRead's stdout as bytes, for an answer that must not be decoded lossily. GST-2331: a partial clone fetches nothing for it. */
function gitBytes(root: string, args: string[], signal?: AbortSignal): Promise<Buffer> {
return new Promise((resolve, reject) => {
if (signal?.aborted) { reject(signal.reason); return; }
const group = process.platform !== 'win32';
- const child = spawn('git', ['-c', 'core.quotepath=false', '-C', root, ...args], { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'ignore'], detached: group });
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', root, ...args], { env: gitChildEnv(NO_LAZY_FETCH_ENV), stdio: ['ignore', 'pipe', 'ignore'], detached: group });
const kill = (name: NodeJS.Signals) => { try { if (group && child.pid) process.kill(-child.pid, name); else child.kill(name); } catch { /* already gone */ } };
const stdout: Buffer[] = [];
let settled = false;
diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.ts
index cfd198ea92..35bf5dc896 100644
--- a/src/core/persistence/sync-blobs.ts
+++ b/src/core/persistence/sync-blobs.ts
@@ -5,14 +5,15 @@
* 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.
+ * `git show` per entry. GST-2331: every read runs with `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so no repository
+ * program runs and a partial clone fetches nothing: an object the repository lacks reads as missing.
*/
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { gitChildEnv } from '../git-env.ts';
-import { HARDENED_GIT_ARGS } from '../hardened-git.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from '../hardened-git.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
/** The sync read bound (`readSyncFile`): bigger files are held without being read. The page ceiling (page-size-policy.ts), which also covers MAX_IMAGE_BYTES. */
@@ -20,15 +21,9 @@ export const SYNC_READ_BOUND = PAGE_MAX_BYTES;
export interface TreeBlob { oid: string; size: number }
-/**
- * GST-2312 (#9024): the configuration every read here runs with, so no repository-configured program starts: `check-attr`
- * reads the index, and reading the index runs `core.fsmonitor`.
- */
-export const NO_REPOSITORY_PROGRAMS: readonly string[] = ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null'];
-
function git(gitRoot: string, args: string[], input?: string, maxBuffer = 32 * 1024 ** 2, env: NodeJS.ProcessEnv = {}): Buffer {
- return execFileSync('git', ['-c', 'core.quotepath=false', ...NO_REPOSITORY_PROGRAMS, '--literal-pathspecs', '-C', gitRoot, ...args],
- { env: gitChildEnv(env), timeout: 60_000, maxBuffer, stdio: ['pipe', 'pipe', 'pipe'], ...(input !== undefined ? { input } : {}) });
+ return execFileSync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '--literal-pathspecs', '-C', gitRoot, ...args],
+ { env: gitChildEnv({ ...NO_LAZY_FETCH_ENV, ...env }), timeout: 60_000, maxBuffer, stdio: ['pipe', 'pipe', 'pipe'], ...(input !== undefined ? { input } : {}) });
}
/** At this many paths `readTreeBlobs` lists the whole tree once instead of path chunks (#6712: the prescreen of a tree walk). */
@@ -96,14 +91,13 @@ export interface MissingAttributes { attributes: string; oid: string }
* committed blob a filter owns holds what the filter's clean program stored (git-crypt ciphertext, for one), not the text
* of the checkout, and sync never runs a repository's filters. Git 2.40 and newer read the attributes with
* `check-attr --source=<target>`; an older git reads `target` into a temporary index (`read-tree`) and asks
- * `check-attr --cached` there. Every call takes `HARDENED_GIT_ARGS` and `GIT_NO_LAZY_FETCH=1`, so no repository
- * program runs and a partial clone fetches nothing. Git then reads a `.gitattributes` the repository lacks as empty, so
+ * `check-attr --cached` there. Like every read here, each call fetches nothing in a partial clone (GST-2331). Git then reads a `.gitattributes` the repository lacks as empty, so
* the ones that apply are checked first, and a path under a missing one maps to it instead of to a driver.
*/
export function readFilterDrivers(gitRoot: string, target: string, gitPaths: string[]): Map<string, string | null | MissingAttributes> {
const out = new Map<string, string | null | MissingAttributes>();
if (gitPaths.length === 0) return out;
- const read = (args: string[], input?: string, env: NodeJS.ProcessEnv = {}) => git(gitRoot, [...HARDENED_GIT_ARGS, ...args], input, undefined, { GIT_NO_LAZY_FETCH: '1', ...env });
+ const read = (args: string[], input?: string, env: NodeJS.ProcessEnv = {}) => git(gitRoot, args, input, undefined, env);
if (checkAttrSource === undefined) {
const [major, minor] = (/git version (\d+)\.(\d+)/.exec(read(['version']).toString('utf8')) ?? ['', '0', '0']).slice(1).map(Number);
checkAttrSource = major! > 2 || major === 2 && minor! >= 40;
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 78b0a3c6c7..64b2b665fc 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -33,8 +33,9 @@ import { assertManagedSyncActive } from './sync-authority.ts';
import { decideOriginTwins, readOriginClaimants, slugPathOccupied, type OriginConflict } from './origin-twins.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
-import { NO_REPOSITORY_PROGRAMS, readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';
+import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';
import { gitChildEnv } from '../git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from '../hardened-git.ts';
import { readOriginEvidence } from './sync-origin-evidence.ts';
import { sourceDbOnlyVerdict } from './source-storage.ts';
import { dbOnlyVerdict, storageConfigFromYaml, unresolvedDbOnlyIn } from '../storage-config.ts';
@@ -111,14 +112,15 @@ export async function syncExcludePatterns(engine: Pick<BrainEngine, 'getConfig'>
return [...extra, ...(await engine.getConfig('sync.exclude') ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)]
.map(v => v.endsWith('/') ? `${v}**` : v);
}
+/** GST-2331: one managed-sync Git read, under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`: no repository program runs, and a partial clone fetches nothing (a missing object fails the read). */
export function syncGit(root: string, args: string[]): string {
- return execFileSync('git', ['-c', 'core.quotepath=false', '-C', root, ...args],
- { env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });
+ return execFileSync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', root, ...args],
+ { env: gitChildEnv(NO_LAZY_FETCH_ENV), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });
}
/** `syncGit` without blocking the event loop while Git runs (a level read: a synchronous spawn held timers for 200+ ms on a loaded host). */
const execFileAsync = promisify(execFile);
export async function syncGitAsync(root: string, args: string[]): Promise<string> {
- return (await execFileAsync('git', ['-c', 'core.quotepath=false', '-C', root, ...args], { env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2 })).stdout;
+ return (await execFileAsync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', root, ...args], { env: gitChildEnv(NO_LAZY_FETCH_ENV), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2 })).stdout;
}
/**
* A sync file or root failed a confinement or identity check. These helpers
@@ -834,5 +836,5 @@ export function readSyncContent(discovery: SyncDiscovery, entry: SyncEntry): str
argv: ['gbrain', 'sync', '--no-pull', '--working-tree', '--source', discovery.sourceId] } });
return bytes.toString('utf8');
}
- return syncGit(discovery.gitRoot, [...NO_REPOSITORY_PROGRAMS, 'show', `${discovery.target}:${syncGitPath(discovery, entry.path)}`]);
+ return syncGit(discovery.gitRoot, ['show', `${discovery.target}:${syncGitPath(discovery, entry.path)}`]);
}
diff --git a/src/core/persistence/sync-entry-fault.ts b/src/core/persistence/sync-entry-fault.ts
index f65e3b48d7..afff3d13bb 100644
--- a/src/core/persistence/sync-entry-fault.ts
+++ b/src/core/persistence/sync-entry-fault.ts
@@ -11,7 +11,8 @@
* `content_filter_owned` instead of importing ciphertext as the page (or, with git-crypt's NUL header, a generic NUL hold).
* - `committedContentOrMissing` (S-33): a committed file whose Git blob is gone (an interrupted gc, a partial clone
* without its promisor, disk corruption) imports from the working tree when those bytes hash to the committed blob
- * id; otherwise it is refused `git_object_missing`, which the freeze holds, naming `git fsck` / `git fetch`.
+ * id; otherwise it is refused `git_object_missing`, which the freeze holds, naming `git fsck` / `git fetch`. GST-2331: sync
+ * fetches nothing, so in a partial clone the refusal names the partial clone and the `git cat-file -p` that fetches the blob.
* - `committedContentOrMissing` (S-7): a committed name that is not valid UTF-8 (Latin-1 bytes from an old system or a zip)
* reads back from Git with U+FFFD for its undecodable bytes, a name no Git read or file finds; it is refused
* `path_not_utf8`, which the freeze holds, naming the rename that fixes it.
@@ -33,7 +34,7 @@ import { isWriteCapacityWait } from './admission-retry.ts';
import { PAGE_BODY_FAULT_CODES } from './sync-fault-class.ts';
import { gitBlobOid } from './digest.ts';
import { readBlobBytes, type MissingAttributes, type TreeBlob } from './sync-blobs.ts';
-import { readSyncFile, type SyncEntry } from './sync-discovery.ts';
+import { readSyncFile, syncGit, type SyncEntry } from './sync-discovery.ts';
import type { GitHoldRecord } from './sync-holds.ts';
type HoldEntry = Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action'>;
@@ -84,7 +85,9 @@ export function missingAttributesRefusal(cursor: { gitRoot: string; sourceId: st
/**
* S-33: the content of a committed entry whose pinned read failed with `error`. When the commit names a blob for the path
* that the repository no longer has, the working-tree bytes are used if they hash to that blob id (the same bytes);
- * otherwise `git_object_missing` is thrown. Any other failure (no blob at the path, the object present) is rethrown.
+ * otherwise `git_object_missing` is thrown. Any other failure (no blob at the path, the object present) is rethrown. GST-2331:
+ * in a partial clone (a promisor remote, or `extensions.partialClone`) the blob was never fetched, and sync fetches nothing, so the refusal says so
+ * and its fix is the `git cat-file -p` that fetches it.
*/
export function committedContentOrMissing(cursor: { root: string; gitRoot: string; sourceId: string }, entry: Pick<SyncEntry, 'path'>, blob: TreeBlob | null, error: unknown): string {
if (entry.path.includes('\uFFFD') && !existsAt(cursor.root, entry.path)) {
@@ -98,9 +101,18 @@ export function committedContentOrMissing(cursor: { root: string; gitRoot: strin
let bytes: Buffer | null = null;
try { bytes = readSyncFile(cursor.root, entry.path); } catch { bytes = null; }
if (bytes && gitBlobOid(bytes, blob.oid.length === 64 ? 'sha256' : 'sha1') === blob.oid) return bytes.toString('utf8');
+ let partial = false;
+ try { partial = syncGit(cursor.gitRoot, ['config', '--get-regexp', '^(extensions\\.partialclone|remote\\..*\\.promisor)$']).split('\n').some(line => /^extensions\.partialclone \S|^remote\..*\.promisor (true|yes|on|1)$/i.test(line)); } catch { partial = false; }
+ const copy = bytes ? ' and the working-tree file differs from it' : ' and the working tree has no copy of it';
+ if (partial) throw opError('git_object_missing', `The Git object of ${entry.path} at the synced commit is missing from the repository.`,
+ `${entry.path} is committed as blob ${blob.oid}, which the repository of source ${cursor.sourceId}, a partial clone (git clone --filter), never fetched${copy}. `
+ + 'Sync fetches nothing from a remote, so nothing was imported from it. '
+ + `Fetch the object in the checkout (git cat-file -p ${blob.oid} fetches it from the partial clone's remote) or check the file out, then run gbrain sync --source ${cursor.sourceId} --no-pull.`,
+ { detail: blob.oid, fix: { argv: ['git', '-C', cursor.gitRoot, 'cat-file', '-p', blob.oid], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Fetches the missing blob from the partial clone\'s remote, so the next sync can read the file.', verify: { argv: ['gbrain', 'sources', 'status', cursor.sourceId, '--json'] } } });
throw opError('git_object_missing', `The Git object of ${entry.path} at the synced commit is missing from the repository.`,
- `${entry.path} is committed as blob ${blob.oid}, but the repository of source ${cursor.sourceId} no longer has that object${bytes ? ' and the working-tree file differs from it' : ' and the working tree has no copy of it'}, so nothing was imported from it. `
- + `Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then run gbrain sync --source ${cursor.sourceId} --no-pull.`,
+ `${entry.path} is committed as blob ${blob.oid}, but the repository of source ${cursor.sourceId} no longer has that object${copy}, so nothing was imported from it. `
+ + `Run git fsck in the checkout to see what is missing, restore it with git fetch (a shallow clone) or from a backup, then run gbrain sync --source ${cursor.sourceId} --no-pull.`,
{ detail: blob.oid, fix: { argv: ['git', '-C', cursor.gitRoot, 'fsck', '--connectivity-only'], consent: [], actor: 'user', requires_exclusive: false,
why: 'Lists the missing objects (read-only); git fetch, or a restore from a backup, brings them back.', verify: { argv: ['gbrain', 'sources', 'status', cursor.sourceId, '--json'] } } });
}
diff --git a/src/core/persistence/sync-held-deletions.ts b/src/core/persistence/sync-held-deletions.ts
index 6ec896bfd5..384bc40e85 100644
--- a/src/core/persistence/sync-held-deletions.ts
+++ b/src/core/persistence/sync-held-deletions.ts
@@ -21,6 +21,7 @@ import { promisify } from 'node:util';
import type { BrainEngine } from '../engine.ts';
import { execFile } from '../spawn.ts';
import { gitChildEnv } from '../git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from '../hardened-git.ts';
import { ghostFileBacked } from '../repair/ghost-pages.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { fileMatchesSnapshot } from './page-prepare.ts';
@@ -126,7 +127,7 @@ async function proveHeldDeletions(engine: BrainEngine, level: ShadowLevel, conte
/** The blob `path` held in the deleting commit's first parent: the file's last committed bytes. */
async function lastCommittedBlob(gitRoot: string, commit: string, path: string): Promise<string | null> {
try {
- const { stdout } = await execFileAsync('git', ['-C', gitRoot, 'rev-parse', '--verify', '--quiet', `${commit}^1:${path}`], { env: gitChildEnv(), encoding: 'utf8', timeout: 60_000 });
+ const { stdout } = await execFileAsync('git', [...HARDENED_GIT_ARGS, '-C', gitRoot, 'rev-parse', '--verify', '--quiet', `${commit}^1:${path}`], { env: gitChildEnv(NO_LAZY_FETCH_ENV), encoding: 'utf8', timeout: 60_000 });
return stdout.trim() || null;
} catch {
return null;
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index bb118f099a..6e53a5a904 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -917,7 +917,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
case 'git_object_missing':
return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),
- user_message: `The Git object of ${record.path}${record.meta.blob_oid ? ` (blob ${record.meta.blob_oid})` : ''} is missing from the checkout of source ${source}, and its working-tree copy differs or is gone, so sync holds it and the rest of the source keeps syncing. Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then run gbrain sync --source ${source} --no-pull.`,
+ user_message: `The Git object of ${record.path}${record.meta.blob_oid ? ` (blob ${record.meta.blob_oid})` : ''} is missing from the checkout of source ${source}, and its working-tree copy differs or is gone, so sync holds it and the rest of the source keeps syncing. Sync fetches nothing, so in a partial clone (git clone --filter) fetch the blob with git cat-file -p ${record.meta.blob_oid ?? '<blob>'} in the checkout or check the file out; otherwise run git fsck in the checkout to see what is missing and restore it with git fetch (a shallow clone) or from a backup. Then run gbrain sync --source ${source} --no-pull.`,
why: 'An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names; nothing is imported from a guess, and every sync re-tests the hold.',
verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
case 'path_not_utf8':
diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.ts
index 61c78ca7d5..2659f46313 100644
--- a/src/core/persistence/sync-origin-evidence.ts
+++ b/src/core/persistence/sync-origin-evidence.ts
@@ -14,7 +14,7 @@
import { execFile, spawn } from '../spawn.ts';
import { promisify } from 'node:util';
import { gitChildEnv } from '../git-env.ts';
-import { NulRecordSplitter } from '../hardened-git.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV, NulRecordSplitter } from '../hardened-git.ts';
import { ignoreCandidates } from './ignore-rules.ts';
const execFileAsync = promisify(execFile);
@@ -31,11 +31,11 @@ const WALK_TIMEOUT_MS = 600_000;
const INDEXES_PER_ROOT = 2;
const GIT_MAX_BUFFER = 64 * 1024 ** 2;
-/** `literal`: the paths are pathspecs read literally (`log`); `check-ignore` takes plain pathnames and refuses the magic. */
+/** `literal`: the paths are pathspecs read literally (`log`); `check-ignore` takes plain pathnames and refuses the magic. GST-2331: every read here fetches nothing in a partial clone. */
async function git(gitRoot: string, args: string[], literal = false): Promise<{ code: number; stdout: string }> {
try {
- const { stdout } = await execFileAsync('git', ['-c', 'core.quotepath=false', ...(literal ? ['--literal-pathspecs'] : []), '-C', gitRoot, ...args],
- { env: gitChildEnv(), encoding: 'utf8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER });
+ const { stdout } = await execFileAsync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, ...(literal ? ['--literal-pathspecs'] : []), '-C', gitRoot, ...args],
+ { env: gitChildEnv(NO_LAZY_FETCH_ENV), encoding: 'utf8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER });
return { code: 0, stdout };
} catch (error) {
const e = error as { code?: unknown; stdout?: unknown; killed?: boolean };
@@ -46,7 +46,7 @@ async function git(gitRoot: string, args: string[], literal = false): Promise<{
/** `git check-ignore --no-index -z --stdin` over `paths` (NUL-separated both ways, so any byte in a name survives). */
function checkIgnore(gitRoot: string, paths: readonly string[]): Promise<{ code: number; stdout: string }> {
return new Promise(resolve => {
- const child = spawn('git', ['-c', 'core.quotepath=false', '-C', gitRoot, 'check-ignore', '--no-index', '-z', '--stdin'], { env: gitChildEnv(), stdio: ['pipe', 'pipe', 'ignore'] });
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', gitRoot, 'check-ignore', '--no-index', '-z', '--stdin'], { env: gitChildEnv(NO_LAZY_FETCH_ENV), stdio: ['pipe', 'pipe', 'ignore'] });
const chunks: Buffer[] = [];
let size = 0, settled = false;
const done = (code: number) => { if (!settled) { settled = true; clearTimeout(timer); resolve({ code, stdout: Buffer.concat(chunks).toString('utf8') }); } };
@@ -85,7 +85,7 @@ export function __resetHistoryIndexesForTest(): void { historyIndexes.clear(); }
*/
function walkHistory(gitRoot: string, revs: string[], onCommit?: (commits: number) => void): Promise<Map<string, PathHistory> | null> {
return new Promise(resolve => {
- const child = spawn('git', ['-c', 'core.quotepath=false', '-C', gitRoot, 'log', '--full-history', '--no-renames', '--diff-merges=first-parent', '-z',
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', gitRoot, 'log', '--full-history', '--no-renames', '--diff-merges=first-parent', '-z',
'--format=%x1e%H%x1f%P%x1f%an%x1f%aI%x1f%s', '--name-status', ...revs, '--'], { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'ignore'] });
const paths = new Map<string, PathHistory>();
const splitter = new NulRecordSplitter();
diff --git a/src/core/persistence/unindexed-files.ts b/src/core/persistence/unindexed-files.ts
index d05a90a0d7..ab307f67d1 100644
--- a/src/core/persistence/unindexed-files.ts
+++ b/src/core/persistence/unindexed-files.ts
@@ -51,6 +51,7 @@ import type { BrainEngine } from '../engine.ts';
import type { SyncOpts } from '../../commands/sync.ts';
import { spawn } from '../spawn.ts';
import { gitChildEnv } from '../git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from '../hardened-git.ts';
import { isSyncMetafile, matchesAnyGlob, metafileIsPage, resolveSlugForPath } from '../sync.ts';
import { screenImportContent } from '../import-screen.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
@@ -160,8 +161,8 @@ function visitBlobSlices<T extends TreeBlob>(gitRoot: string, entries: T[], visi
/** The blobs of `target` under `scope` in tree order, after `after`, in batches; the child stops when the consumer does. */
async function* treeBatches(gitRoot: string, target: string, scope: string, after: string | null, size: number, revisit?: ReadonlySet<string>): AsyncGenerator<TreeEntry[]> {
- const child = spawn('git', ['-c', 'core.quotepath=false', '--literal-pathspecs', '-C', gitRoot, 'ls-tree', '-r', '-l', '-z', target, ...(scope ? ['--', scope] : [])],
- { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '--literal-pathspecs', '-C', gitRoot, 'ls-tree', '-r', '-l', '-z', target, ...(scope ? ['--', scope] : [])],
+ { env: gitChildEnv(NO_LAZY_FETCH_ENV), stdio: ['ignore', 'pipe', 'pipe'] });
let stderr = '';
child.stderr!.on('data', (chunk: Buffer) => { stderr = (stderr + chunk.toString('utf8')).slice(0, 2000); });
const exit = new Promise<number | null>((resolve, reject) => { child.on('error', reject); child.on('close', resolve); });
diff --git a/src/core/sync-delta.ts b/src/core/sync-delta.ts
index 75c39bddb8..1bbce26dbb 100644
--- a/src/core/sync-delta.ts
+++ b/src/core/sync-delta.ts
@@ -35,6 +35,7 @@ import { execFileSync } from './spawn.ts';
import { execFileBounded } from './bounded-child-exec.ts';
import { buildSyncManifest, type SyncManifest } from './sync.ts';
import { GIT_READ_ENV, gitChildEnv } from './git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from './hardened-git.ts';
import { classifyGitPathBytes, displayBytePath, type UnsupportedPathReason } from './sync-byte-paths.ts';
/** Runs a git subcommand in `repoPath` and returns trimmed stdout (throws on failure). */
@@ -43,10 +44,12 @@ export type GitRunner = (repoPath: string, args: string[]) => string;
// Mirrors `git()` + `buildGitInvocation()` in commands/sync.ts: `core.quotepath=false`
// so non-ASCII (CJK) paths arrive as UTF-8; 30s timeout; 100 MiB maxBuffer (a
// 100K-file `--name-status` diff tops out ~10-20 MiB — Node's 1 MiB default
-// would ENOBUFS-crash the sync with no log line).
+// would ENOBUFS-crash the sync with no log line). GST-2331: managed discovery reads through it, so it runs under
+// HARDENED_GIT_ARGS and NO_LAZY_FETCH_ENV; rename detection that needs a blob a partial clone lacks fails the diff
+// (`diff_failed`, the full tree walk) instead of fetching it.
const DEFAULT_GIT_RUNNER: GitRunner = (repoPath, args) =>
- execFileSync('git', ['-c', 'core.quotepath=false', '-C', repoPath, ...args], {
- env: gitChildEnv(GIT_READ_ENV),
+ execFileSync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', repoPath, ...args], {
+ env: gitChildEnv({ ...GIT_READ_ENV, ...NO_LAZY_FETCH_ENV }),
encoding: 'utf-8',
timeout: 30_000,
maxBuffer: 100 * 1024 * 1024,
diff --git a/src/core/sync-metafile-pages.ts b/src/core/sync-metafile-pages.ts
index cbffb69aa3..d6834bb23a 100644
--- a/src/core/sync-metafile-pages.ts
+++ b/src/core/sync-metafile-pages.ts
@@ -10,6 +10,7 @@ import { execFileSync } from './spawn.ts';
import { closeSync, lstatSync, openSync, readSync } from 'node:fs';
import { join } from 'node:path';
import { gitChildEnv } from './git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from './hardened-git.ts';
import { readBlobBytes, type TreeBlob } from './persistence/sync-blobs.ts';
import type { BrainEngine } from './engine.ts';
import { isNestedSkipMetafile, metafileIsPage, METAFILE_HEAD_BYTES, SYNC_METAFILE_PAGES_KEY, SYNC_SKIP_FILES, type MetafilePagesMode } from './sync.ts';
@@ -61,8 +62,9 @@ export function diskMetafileHeads(root: string): MetafileHeadReader {
const nameOf = (path: string) => path.slice(path.lastIndexOf('/') + 1);
const metafileNamed = (path: string) => (SYNC_SKIP_FILES as readonly string[]).includes(nameOf(path));
+/** GST-2331: a metafile read fetches nothing in a partial clone; an object the repository lacks reads as no file. */
function git(gitRoot: string, args: string[], input: string, maxBuffer = 64 * 1024 ** 2): Buffer {
- return execFileSync('git', ['-c', 'core.quotepath=false', '-C', gitRoot, ...args], { env: gitChildEnv(), timeout: 60_000, maxBuffer, input, stdio: ['pipe', 'pipe', 'pipe'] });
+ return execFileSync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', gitRoot, ...args], { env: gitChildEnv(NO_LAZY_FETCH_ENV), timeout: 60_000, maxBuffer, input, stdio: ['pipe', 'pipe', 'pipe'] });
}
/** Blob ids and sizes of `<commit>:<path>`-style object names through one `cat-file --batch-check`; missing names are absent. */
diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.ts
index 4c0e2ceade..cdf3826613 100644
--- a/src/core/sync-rename-identity.ts
+++ b/src/core/sync-rename-identity.ts
@@ -35,6 +35,7 @@ import { loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';
import type { BrainEngine } from './engine.ts';
import { spawn } from './spawn.ts';
import { GIT_READ_ENV, gitChildEnv } from './git-env.ts';
+import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from './hardened-git.ts';
import { explicitMarkdownTitle } from './markdown.ts';
import { isMarkdownFilePath, resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason, type RenameSideSource, type SyncManifest } from './sync.ts';
import { computeSyncDelta, type SyncDeltaResult } from './sync-delta.ts';
@@ -83,11 +84,11 @@ export function frontmatterIdentity(head: Buffer | string | null): FrontmatterId
return { id: field('id', true), slug: field('slug'), title, digest };
}
-/** The first 64 KiB of each `<rev>:<path>` object through one `git cat-file --batch` stream; null for a missing object or a non-blob. */
+/** The first 64 KiB of each `<rev>:<path>` object through one `git cat-file --batch` stream; null for a missing object or a non-blob (GST-2331: one a partial clone lacks is never fetched). */
export async function catFileHeads(repo: string, objects: string[]): Promise<Array<Buffer | null>> {
if (objects.length === 0) return [];
return new Promise((done, fail) => {
- const child = spawn('git', ['-c', 'core.quotepath=false', '-C', repo, 'cat-file', '--batch'], { env: gitChildEnv(GIT_READ_ENV), stdio: ['pipe', 'pipe', 'pipe'] });
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', repo, 'cat-file', '--batch'], { env: gitChildEnv({ ...GIT_READ_ENV, ...NO_LAZY_FETCH_ENV }), stdio: ['pipe', 'pipe', 'pipe'] });
const out: Array<Buffer | null> = [];
let pending: Buffer = Buffer.alloc(0), remaining = -1, blob = false, kept: Buffer[] = [], keptBytes = 0, stderr = '';
child.stdout!.on('data', (chunk: Buffer) => {
diff --git a/test/pathological/s-classic-byte-paths.test.ts b/test/pathological/s-classic-byte-paths.test.ts
index 93d9e00fe7..26a4a0b0c9 100644
--- a/test/pathological/s-classic-byte-paths.test.ts
+++ b/test/pathological/s-classic-byte-paths.test.ts
@@ -112,7 +112,7 @@ describe('sync Git reads take no optional lock (GIT_OPTIONAL_LOCKS=0)', () => {
try {
const realGit = execFileSync('bash', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();
mkdirSync(bin); mkdirSync(repo);
- writeFileSync(join(bin, 'git'), '#!/bin/sh\nsub=""\nskip=0\nfor a in "$@"; do\n if [ $skip = 1 ]; then skip=0; continue; fi\n case "$a" in -c|-C) skip=1; continue;; esac\n sub="$a"; break\ndone\n'
+ writeFileSync(join(bin, 'git'), '#!/bin/sh\nsub=""\nskip=0\nfor a in "$@"; do\n if [ $skip = 1 ]; then skip=0; continue; fi\n case "$a" in -c|-C) skip=1; continue;; --*) continue;; esac\n sub="$a"; break\ndone\n'
+ 'printf \'%s %s\\n\' "${GIT_OPTIONAL_LOCKS:-unset}" "$sub" >> "$PROBE_GIT_LOG"\nPATH=\'' + process.env.PATH + '\' exec ' + realGit + ' "$@"\n');
chmodSync(join(bin, 'git'), 0o755);
gitIn(repo, 'init', '-q', '-b', 'main'); gitIn(repo, 'config', 'user.name', 'Example'); gitIn(repo, 'config', 'user.email', '[email protected]');