Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): lossless byte-path parsing for classic sync (GBRA-133 PR 1.3)
garrytan302edc132620
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 057e5bc414..fd0e1db1bb 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -58,6 +58,8 @@ 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.-- `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. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.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`). 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.- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 082dd1e803..49c99637a3 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1576,6 +1576,16 @@ More: [docs/guides/shared-checkout-git.md#stuck-rebase](../../docs/guides/shared|---|---|---|---|---|---|---|| A git command did not complete. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### gitlink_not_followed++<a id="gitlink_not_followed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A classic sync range added a gitlink (a submodule or an embedded repository); sync does not follow it, so the linked repository's files are not indexed. | A gitlink records another repository's commit, not files, and that repository may be absent or uninitialized. The rest of the source syncs; the notice (`gitlinks_not_followed` in the result and one stderr line) comes once, in the run that passes the gitlink. | Nothing is blocked. To index the linked repository, check it out and add the checkout as its own source (gbrain sources add <name> --path <checkout>). | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#gitlink_not_followed](../../docs/guides/write-refusals.md#gitlink_not_followed)+### graduation_drain_timeout<a id="graduation_drain_timeout"></a>@@ -3912,6 +3922,18 @@ More: [docs/guides/system-one.md#unpriced_model](../../docs/guides/system-one.md|---|---|---|---|---|---|---|| Prepared mutation does not match its accepted target. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### unsupported_path++<a id="unsupported_path"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Classic sync held a file whose name is not valid UTF-8 or contains a control character, so it cannot be a page path; the rest of the source synced. | Git stores a name as bytes and a page path is text, so importing a lossy decoding would store a path no file has. The hold key spells the exact bytes (`/gbrain-bytes/` plus %XX escapes), the message names an item id bound to them, and the hold re-screens on every sync and clears once the name leaves the tree. | Rename the file to a valid UTF-8 name without control characters (the hold's fix spells the old name with printf escapes, never raw bytes), commit, then run gbrain sync --source <source> --no-pull. | agent | `repeat the read that failed` | 1 | no |++Reasons: `not_utf8`, `control_character`.++More: [docs/guides/write-refusals.md#unsupported_path](../../docs/guides/write-refusals.md#unsupported_path)+### upstream<a id="upstream"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex e270fb4629..96b306004e 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -224,6 +224,8 @@ with each file and fix the ones that need no guessing."*| <a id="absent_from_worktree"></a>`absent_from_worktree` | Classic sync held a file the commit names that is missing from the working tree. Before GBRA-133 it was treated as "deleted after the pin" and dropped silently. The rest of the source imports and the bookmark advances; the hold re-screens on every run and clears when the file is back on disk (it imports) or leaves the commit. | Follow the reason row below. The fix is `ask_user`: restoring the file and committing its deletion are both valid. || <a id="absent_from_worktree-skip_worktree"></a>`absent_from_worktree` (`skip_worktree`) | A sparse checkout (or a skip-worktree bit set by hand) keeps the committed file off disk. | Ask the user: widen the sparse checkout (`git -C <checkout> sparse-checkout add <dir>`; for a hand-set bit, `git -C <checkout> update-index --no-skip-worktree -- <path>` and `git -C <checkout> restore -- <path>`) and the next sync imports it; or leave it out with `sync.exclude`. Keeping it held is also safe. || <a id="absent_from_worktree-deleted_locally"></a>`absent_from_worktree` (`deleted_locally`) | The committed file was deleted from the checkout and the deletion is not committed. | Ask the user: restore it (`git -C <checkout> restore -- <path>`) and the next sync imports it; or commit the deletion (`gbrain git commit-push --path <checkout> -m 'Delete <path>' -- <path>`) and the next sync clears the hold. |+| <a id="unsupported_path"></a><a id="unsupported_path-not_utf8"></a><a id="unsupported_path-control_character"></a>`unsupported_path` (`not_utf8`, `control_character`) | Classic sync: the file's name is not valid UTF-8 (`not_utf8`, a Latin-1 name from an old archive) or contains a control character (`control_character`: a tab, a newline or another byte below 0x20). Git stores a name as bytes and a page path is text, so the file cannot be imported under its own name. Sync reads the diff as bytes (`git diff --raw -z`), never as a lossy decoding: before this the file was checkpointed as "deleted after the pin" with no message (`not_utf8`) or skipped as a malformed name naming no path (`control_character`). The hold key is `/gbrain-bytes/` plus the path with every byte outside a printable UTF-8 character, and every `%`, written `%XX` (`notes/caf%E9.md`); it decodes to the exact bytes and never equals a Git path. The message shows the name C-escaped (`notes/caf\351.md`) with an item id (the first 16 hex digits of the bytes' sha256). The rest of the source syncs and the checkpoint advances. | Rename the file to a valid UTF-8 name without control characters and commit. The fix's `user_message` gives a rename command that spells the old name with printf escapes (`printf 'notes/caf\351.md\000' \| xargs -0 -I{} git mv -- {} 'notes/caf_.md'`, run from the source's checkout), so no raw bytes go on a command line; then `gbrain sync --source <source> --no-pull` imports the file and clears the hold. The hold re-screens on every sync: it stays while a file has that name and clears once the name leaves the tree (renamed, deleted or excluded). |+| <a id="gitlink_not_followed"></a>`gitlink_not_followed` (notice, not a hold) | Classic sync: the range added a gitlink (a submodule or an embedded repository, mode 160000). It records another repository's commit, not files, so its contents are not indexed. Reported once, in the run that passes it: the result's `gitlinks_not_followed` lists the paths and one stderr line names them. Nothing is held and the checkpoint advances. | Nothing to fix. To index the linked repository, check it out and add the checkout as its own source (`gbrain sources add <name> --path <checkout>`). || <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `GBRAIN_SYNC_PARSER_REGRESSION=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). || <a id="takes_holder_invalid"></a>takes holder (`invalid_params`) | `takes_add`, or `takes_supersede` with an explicit `holder`, was given a holder the takes fence cannot carry: empty, whitespace, or not `world`, `brain`, `people/<slug>` or `companies/<slug>` (a legacy bare slug is accepted). The value is trimmed first, so `" world "` is stored as `world`. Nothing was written: before this release such a holder was published into the fence and every later takes write on that page was refused `target_fence_malformed`. A supersede without an override keeps the row's stored holder. A page whose stored holder is already malformed still refuses every takes write (`invalid_fence`); `gbrain repair fences` is the way out. | Resend with a holder in that grammar (`holder: me` on the brain host resolves the owner's holder). For a page already carrying a malformed holder, preview `gbrain repair fences --slug <slug>` and apply it, or edit the `who` cell by hand. Format: [holders](fence-format.md#holders). || <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`, `gbrain repair content --apply --expect <h1>[,<h2>]`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash (for the content lane, one hash per kind in lane order). For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.tsindex c69e87b5b9..c7dbb5a151 100644--- a/src/commands/sync/finalize.ts+++ b/src/commands/sync/finalize.ts@@ -27,13 +27,14 @@ import {import { shouldLogIngest } from '../import.ts';import type { SyncResult } from '../sync.ts';import { settleLegacyHolds } from './holds.ts';+import { gitlinkFields } from './unsupported-paths.ts';import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';import { partial, flushCheckpoint } from './sync-run.ts';import type { SyncPlan, SyncRun } from './sync-run.ts';export async function finishWithoutChanges(engine: BrainEngine,- plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'lastCommit' | 'pin' | 'pullFailed' | 'ckpt' | 'malformedSkipped' | 'totalChanges' | 'holds'>,+ plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'lastCommit' | 'pin' | 'pullFailed' | 'ckpt' | 'malformedSkipped' | 'totalChanges' | 'holds' | 'gitlinks'>,swept: number,): Promise<SyncResult | undefined> {const { opts, company, gitContextRoot, lastCommit, pin, pullFailed, ckpt, malformedSkipped, totalChanges } = plan;@@ -91,6 +92,7 @@ export async function finishWithoutChanges(embedded: 0,pagesAffected: [],...(malformedSkipped.length > 0 ? { malformedSkipped: malformedSkipped.length } : {}),+ ...gitlinkFields(plan),};}return undefined;@@ -216,6 +218,7 @@ export async function finalizeIncrementalSync(...(uncommittedDrift ? { uncommitted: uncommittedDrift } : {}),...(extractError ? { extract_error: extractError } : {}),...identityDowngradesOf(plan),+ ...gitlinkFields(plan),};}diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.tsindex dfcc81aa8d..93e6d7597e 100644--- a/src/commands/sync/holds.ts+++ b/src/commands/sync/holds.ts@@ -31,6 +31,7 @@ import {import { DEFAULT_SOURCE_ID, hasMalformedPathSegment, isCodeFilePath, resolveSlugForPath, sanitizePathForDisplay, slugifyPath } from '../../core/sync.ts';import type { SyncActivePack } from './sync-run.ts';import { isPathContained } from '../../core/path-confine.ts';+import { bytePathHoldGone } from '../../core/sync-byte-paths.ts';import { bindOrigin } from '../../core/persistence/origin-guard.ts';import { CLASSIC_FILE_HOLD_CODES, classifyClassicFile, type ClassicFileHold } from '../../core/classic-file-holds.ts';@@ -111,6 +112,13 @@ function currentVersion(filePath: string): string | null | undefined {export function planHoldRescreen(holds: LegacyHolds, input: { root: string; gitRoot?: string; touched: ReadonlySet<string>; selected: (path: string) => boolean | null }): void {for (const path of holds.retryPaths) if (!holds.existing.has(path)) holds.retryTaken.push(path);for (const [path, record] of holds.existing) {+ // GBRA-133: an unsupported_path hold stays while its exact bytes name a file, and clears once they do not.+ const byteGone = bytePathHoldGone(input.root, path);+ if (byteGone !== null) {+ if (byteGone) holds.gone.push(path);+ if (holds.retryPaths.has(path)) holds.retryTaken.push(path);+ continue;+ }if (input.touched.has(path)) {if (holds.retryPaths.has(path)) holds.retryTaken.push(path);continue;@@ -454,7 +462,7 @@ export async function settleFullSyncHolds(engine: BrainEngine, holds: LegacyHoldif (!holds) return;for (const path of holds.existing.keys()) {if (input.failed.has(path)) continue;- if (input.walked.has(path) || !fileUnderRoot(input.root, path)) await clearLegacyHold(engine, holds, path);+ if (bytePathHoldGone(input.root, path) ?? (input.walked.has(path) || !fileUnderRoot(input.root, path))) await clearLegacyHold(engine, holds, path);}holds.retryTaken.push(...holds.retryPaths);await settleLegacyHolds(engine, holds);diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.tsindex 6e0cf64a46..81d9ff729a 100644--- a/src/commands/sync/preflight.ts+++ b/src/commands/sync/preflight.ts@@ -21,8 +21,8 @@ import {readChunkerVersion,} from '../../core/sync-anchor.ts';import type { SlugRootMode } from '../../core/sync-anchor.ts';-import { buildDetachedWorkingTreeManifest, mergeSyncManifests } from '../../core/sync-delta.ts';-import { confirmedSyncDelta, confirmRenameIdentities, redecideHeldRename, type ConfirmedManifest } from '../../core/sync-rename-identity.ts';+import { buildLosslessWorkingTreeManifest, computeLosslessSyncDelta, mergeSyncManifests, type LosslessDelta } from '../../core/sync-delta.ts';+import { confirmRenameIdentities, redecideHeldRename, type ConfirmedManifest } from '../../core/sync-rename-identity.ts';import {git,isWithinRoot,@@ -52,6 +52,7 @@ import { performFullSync } from './full.ts';import { applyHoldsToManifest, holdUnreadableRenames, planHoldRescreen, redecideUnreadableRenames, wouldHoldFields, type LegacyHolds } from './holds.ts';import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';import type { SyncPlan, SyncActivePack } from './sync-run.ts';+import { holdUnsupportedPaths, NO_BYTE_PATHS, selectBytePaths, type BytePaths } from './unsupported-paths.ts';import { formatUrlClonePullBlock, urlClonePullBlock } from '../../core/url-clone.ts';export type PreflightOutcome = { readonly done: SyncResult } | { readonly plan: SyncPlan };@@ -131,7 +132,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpconst { ckpt, checkpointEvery, pin, completedPaths } = await resolveCheckpointPin(engine, opts, company, gitContextRoot, lastCommit, headCommit);const {- storedVersion, currentVersion, versionMismatch, versionNeverSet, importWorkingTree, workingTreeManifest,+ storedVersion, currentVersion, versionMismatch, versionNeverSet, importWorkingTree, workingTreeManifest, workingTreeBytes,hasWorkingTreeChanges, uncommittedDrift, inScope, scopeRel, isSelectedForRun, excluded, syncOpts,} = await resolveWorkingTreeScope(engine, opts, { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable: !!holds?.active });@@ -223,10 +224,10 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpconst delta = await computeFilteredDelta(engine, opts, {company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,- workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,+ workingTreeManifest, workingTreeBytes, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,});if ('done' in delta) return delta;- const { manifest, filtered, malformedSkipped, syncImportRoot, modePath, heldRenames } = delta;+ const { manifest, filtered, malformedSkipped, syncImportRoot, modePath, heldRenames, bytePaths } = delta;if (holds) {const touched = new Set([...filtered.added, ...filtered.modified, ...filtered.deleted, ...filtered.renamed.flatMap(r => [r.from, r.to])]);for (let i = holds.rescreen.length - 1; i >= 0; i--) if (touched.has(holds.rescreen[i]!)) holds.rescreen.splice(i, 1);@@ -246,12 +247,13 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpreturn { done: { ...dryRunResult({ lastCommit, headCommit, filtered, malformedSkipped, totalChanges }),...(await wouldHoldFields(engine, holds, syncImportRoot, [...filtered.added, ...filtered.modified, ...filtered.renamed.map(r => r.to), ...(holds?.rescreen ?? [])], syncActivePack)) } };}+ await holdUnsupportedPaths(engine, holds, bytePaths);return {plan: {opts, company, repoPath, gitContextRoot, anchorPath, syncImportRoot, syncActivePack, lastCommit, headCommit, pin,pullFailed, ckpt, completedPaths, checkpointEvery, manifest, filtered, malformedSkipped, totalChanges,- uncommittedDrift, inScope, isSelectedForRun, syncOpts, modePath, holds,+ uncommittedDrift, inScope, isSelectedForRun, syncOpts, modePath, holds, gitlinks: bytePaths.gitlinks,},};}@@ -881,8 +883,11 @@ async function resolveWorkingTreeScope(// import request fails closed with the reason (importing without the// manifest would silently skip the very files the caller asked for).let workingTreeManifest: ConfirmedManifest;+ let workingTreeBytes: BytePaths = NO_BYTE_PATHS;try {- workingTreeManifest = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitContextRoot);+ const tree: LosslessDelta = company ? { manifest: { added: [], modified: [], deleted: [], renamed: [] }, ...NO_BYTE_PATHS } : buildLosslessWorkingTreeManifest(gitContextRoot);+ workingTreeManifest = tree.manifest;+ workingTreeBytes = tree;} catch (e) {if (importWorkingTree) {throw new Error(@@ -954,7 +959,7 @@ async function resolveWorkingTreeScope();}return {- storedVersion, currentVersion, versionMismatch, versionNeverSet, importWorkingTree, workingTreeManifest,+ storedVersion, currentVersion, versionMismatch, versionNeverSet, importWorkingTree, workingTreeManifest, workingTreeBytes,hasWorkingTreeChanges, uncommittedDrift, inScope, scopeRel, isSelectedForRun, excluded, syncOpts,};}@@ -973,6 +978,7 @@ async function computeFilteredDelta(fullSyncRoots: { gitContextRoot: string; syncScopeRoot: string; anchorPath: string; slugRootMode: SlugRootMode };importWorkingTree: boolean;workingTreeManifest: ConfirmedManifest;+ workingTreeBytes: BytePaths;detachedHead: boolean;scoped: boolean;slugRootMode: SlugRootMode;@@ -986,11 +992,11 @@ async function computeFilteredDelta(): Promise<| { done: SyncResult }| { manifest: SyncManifest; filtered: SyncManifest; malformedSkipped: string[]; syncImportRoot: string; modePath: (p: string) => string; totalChanges: number;- heldRenames: Array<{ from: string; to: string; gitTo: string; cause: unknown }> }+ heldRenames: Array<{ from: string; to: string; gitTo: string; cause: unknown }>; bytePaths: BytePaths }> {const {company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,- workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,+ workingTreeManifest, workingTreeBytes, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,} = input;// Diff using git diff (net result, not per-commit). v0.42.x (#1794): diff// against the PINNED target, not live HEAD. With a fixed (lastCommit, pin)@@ -1010,7 +1016,8 @@ async function computeFilteredDelta(// throwing — a slow correct reconcile beats a hard error or a silent walk.// #6729: inexact renames keep their page identity only when confirmed, before the company fold, the unsyncable fold// and the hold replay read the manifest; the already-confirmed working-tree manifest merges after.- const delta = await confirmedSyncDelta(engine, gitContextRoot, lastCommit, pin, { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel, holdUnreadable: !!holds?.active });+ // GBRA-133: read as bytes (diff --raw -z), so a name is exactly Git's; names that are not page paths and gitlinks ride beside the manifest.+ const delta = computeLosslessSyncDelta(gitContextRoot, lastCommit, pin);if (delta.status === 'unavailable') {serr(`[sync] delta ${lastCommit.slice(0, 8)}..${pin.slice(0, 8)} unavailable ` +@@ -1018,7 +1025,8 @@ async function computeFilteredDelta();return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };}- const manifest = importWorkingTree ? mergeSyncManifests(delta.manifest, workingTreeManifest) : delta.manifest;+ const confirmed = await confirmRenameIdentities(engine, gitContextRoot, lastCommit, pin, delta.manifest, { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel, holdUnreadable: !!holds?.active });+ const manifest = importWorkingTree ? mergeSyncManifests(confirmed, workingTreeManifest) : confirmed;if (company) {manifest.added.push(...manifest.renamed.map(rename => rename.to));manifest.deleted.push(...manifest.renamed.map(rename => rename.from));@@ -1137,10 +1145,14 @@ async function computeFilteredDelta(const totalChanges = filtered.added.length + filtered.modified.length +filtered.deleted.length + filtered.renamed.length;// GBRA-133 S-51: pairs the identity confirmation could not read, in this run's scope, by the mode's page paths.- const heldRenames = [...(delta.manifest.heldRenames ?? []), ...(importWorkingTree ? workingTreeManifest.heldRenames ?? [] : [])]+ const heldRenames = [...(confirmed.heldRenames ?? []), ...(importWorkingTree ? workingTreeManifest.heldRenames ?? [] : [])].filter(pair => inScope(pair.to) && !excluded(pair.to) && isSelectedForRun(pair.to, syncOpts)).map(pair => ({ from: modePath(pair.from), to: modePath(pair.to), gitTo: pair.to, cause: pair.cause }));- return { manifest, filtered, malformedSkipped, syncImportRoot, modePath, totalChanges, heldRenames };+ const bytePaths = company ? NO_BYTE_PATHS : selectBytePaths({+ unsupported: [...delta.unsupported, ...(importWorkingTree ? workingTreeBytes.unsupported : [])],+ gone: [...delta.gone, ...(importWorkingTree ? workingTreeBytes.gone : [])], gitlinks: delta.gitlinks,+ }, { inScope, excluded, selected: p => isSelectedForRun(p, syncOpts), modeRel: modePath });+ return { manifest, filtered, malformedSkipped, syncImportRoot, modePath, totalChanges, heldRenames, bytePaths };}function dryRunResult(input: {diff --git a/src/commands/sync/sync-run.ts b/src/commands/sync/sync-run.tsindex 98785e9876..dc258ab634 100644--- a/src/commands/sync/sync-run.ts+++ b/src/commands/sync/sync-run.ts@@ -75,6 +75,8 @@ export interface SyncPlan {readonly modePath: (p: string) => string;/** #5988: the run's content holds (null for company-brain sources); its re-screen paths join the import drain. */readonly holds: LegacyHolds | null;+ /** GBRA-133: gitlinks that appeared in this run's range (reported once, never followed). */+ readonly gitlinks: string[];}export interface SyncRun {diff --git a/src/commands/sync/unsupported-paths.ts b/src/commands/sync/unsupported-paths.tsnew file mode 100644index 0000000000..a390d67240--- /dev/null+++ b/src/commands/sync/unsupported-paths.ts@@ -0,0 +1,79 @@+/**+ * Classic sync's byte-path routing (GBRA-133): the delta paths the lossless+ * parser (`computeLosslessSyncDelta`) could not turn into page paths become+ * `unsupported_path` holds in the classic hold store, and gitlinks that appeared+ * are reported once, in the run that advances past them. Neither ever gates+ * the bookmark. Key, display, item id and fix live in core/sync-byte-paths.ts.+ */+import { serr } from '../../core/console-prefix.ts';+import type { BrainEngine } from '../../core/engine.ts';+import { RECOVERY_VERSION } from '../../core/frontmatter-recovery.ts';+import { writeGitHold } from '../../core/persistence/sync-holds.ts';+import { bytePathItemId, displayBytePath, encodeBytePathKey } from '../../core/sync-byte-paths.ts';+import type { LosslessDelta, UnsupportedGitPath } from '../../core/sync-delta.ts';+import type { SyncPlan } from './sync-run.ts';+import type { LegacyHolds } from './holds.ts';++declare module '../sync.ts' {+ interface SyncResult {+ /** GBRA-133: gitlinks (submodules, embedded repositories) that appeared in this run's range; their contents are not synced. */+ gitlinks_not_followed?: string[];+ }+}++/** What the text manifest cannot carry, filtered to this run and in the mode's path form. */+export interface BytePaths { unsupported: UnsupportedGitPath[]; gone: Buffer[]; gitlinks: string[] }++export const NO_BYTE_PATHS: BytePaths = { unsupported: [], gone: [], gitlinks: [] };++/**+ * Keeps the byte paths this run syncs: the same scope, exclude and syncability filters as the text manifest, applied to+ * the name with each undecodable byte read as U+FFFD and each control character as `_` (so a `notes/caf<E9>.md` counts as+ * Markdown and a binary in an excluded folder is left alone), then made relative to the mode's root by `modeRel`.+ */+export function selectBytePaths(delta: Pick<LosslessDelta, 'unsupported' | 'gone' | 'gitlinks'>, filter: {+ inScope: (path: string) => boolean; excluded: (path: string) => boolean; selected: (path: string) => boolean; modeRel: (path: string) => string;+}): BytePaths {+ // eslint-disable-next-line no-control-regex+ const probe = (raw: Buffer) => raw.toString('utf8').replace(/[\x00-\x1f\x7f]/g, '_');+ const keep = (raw: Buffer) => { const path = probe(raw); return filter.inScope(path) && !filter.excluded(path) && filter.selected(path); };+ const rel = (raw: Buffer) => {+ const path = probe(raw);+ return raw.subarray(Buffer.byteLength(path.slice(0, path.length - filter.modeRel(path).length)));+ };+ return {+ unsupported: delta.unsupported.filter(entry => keep(entry.raw)).map(entry => ({ ...entry, raw: rel(entry.raw) })),+ gone: delta.gone.filter(raw => filter.inScope(probe(raw))).map(rel),+ gitlinks: delta.gitlinks.filter(path => filter.inScope(path) && !filter.excluded(path)).map(filter.modeRel),+ };+}++/** Holds each unsupported path (never gating the bookmark), schedules the holds of gone ones to clear, and reports new gitlinks. */+export async function holdUnsupportedPaths(engine: BrainEngine, holds: LegacyHolds | null, paths: BytePaths): Promise<void> {+ if (paths.gitlinks.length) {+ serr(` ${paths.gitlinks.length} gitlink(s) not followed (gitlink_not_followed): ${paths.gitlinks.slice(0, 20).join(', ')}. `+ + 'Submodule and embedded-repository contents are not synced; add a checkout of one as its own source to index it.');+ }+ if (!holds) return;+ for (const raw of paths.gone) {+ const key = encodeBytePathKey(raw);+ if (holds.existing.has(key)) holds.gone.push(key);+ }+ for (const { raw, reason } of paths.unsupported) {+ const key = encodeBytePathKey(raw), shown = displayBytePath(raw), item = bytePathItemId(raw);+ const message = `${shown} (item ${item}) ${reason === 'not_utf8' ? 'has a name that is not valid UTF-8' : 'has a control character in its name'}, `+ + 'so sync cannot use it as a page path; rename the file to import it.';+ await engine.transaction(tx => writeGitHold(tx, {+ source_id: holds.sourceId, incarnation: holds.incarnation, path: key, source_path: key, slug: null, page_id: null,+ code: 'unsupported_path', message, upstream_version: null, observed_at: holds.observedAt, run_id: holds.runId, mode: 'legacy',+ meta: { reason, recovery_version: RECOVERY_VERSION },+ }));+ holds.heldPaths.push(key);+ serr(` Held ${shown} (unsupported_path/${reason}, item ${item}): not imported, the sync continues.`);+ }+}++/** The run result's gitlink field (empty when none appeared). */+export function gitlinkFields(plan: Pick<SyncPlan, 'gitlinks'>): { gitlinks_not_followed?: string[] } {+ return plan.gitlinks.length ? { gitlinks_not_followed: plan.gitlinks } : {};+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 9f8e4affad..fa5d240cbe 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -129,7 +129,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 383ade26e7..4b4153a1d7 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -300,6 +300,7 @@ export const CODES = {git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },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." },+ gitlink_not_followed: { class: 'caller', summary: "A classic sync range added a gitlink (a submodule or an embedded repository); sync does not follow it, so the linked repository's files are not indexed.", why: "A gitlink records another repository's commit, not files, and that repository may be absent or uninitialized. The rest of the source syncs; the notice (`gitlinks_not_followed` in the result and one stderr line) comes once, in the run that passes the gitlink.", docs: 'docs/guides/write-refusals.md#gitlink_not_followed', suggestion: 'Nothing is blocked. To index the linked repository, check it out and add the checkout as its own source (gbrain sources add <name> --path <checkout>).' },graduation_drain_timeout: { class: 'retryable', summary: "Queued or running writes did not drain within --drain-timeout; the move stopped before copying and the source is unchanged.", docs: 'docs/guides/move-to-postgres.md#drain', reasons: ['progressing', 'blocked'], exit: 11 },graduation_embedding_dimension_mismatch: { class: 'caller', summary: "An existing, non-empty target database has a different embedding column layout than the brain being moved.", docs: 'docs/guides/move-to-postgres.md#embeddings' },graduation_foreign_host_binding: { class: 'host_only', summary: "A source's worktree is owned by another host, so this host cannot move it to Postgres.", docs: 'docs/guides/move-to-postgres.md#hosts' },@@ -655,6 +656,7 @@ export const CODES = {unmanaged_database_path: { class: 'host_only', summary: "`gbrain backup create` refused before writing anything: the PGLite data directory is not the managed `<root>/.gbrain/brain.pglite` (a flat config home, or a path reached through a symlink).", why: 'The archive records the managed root it can restore into and refuses to follow a symlink out of it, so a flat or aliased layout cannot be archived without risking a restore into the wrong place.', docs: 'docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy', suggestion: 'Take a quiesced physical copy into a new managed root (`<new-home>/.gbrain/brain.pglite`); the copy is then a normal layout that `gbrain backup create` accepts while it is under the 8 GiB cap.', fix: { ask_user: true, argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only, after the user agrees to the physical copy: doctor opens the brain only when no other gbrain process holds it, so a clean run shows the writers are stopped.", user_message: "This brain is outside what `gbrain backup create` can archive. Stop every gbrain writer on it (gbrain serve, jobs, autopilot, agent sessions), copy the whole data directory and config.json into a new isolated GBRAIN_HOME, point the copy's database_path at the copied data directory, then run gbrain doctor --json with GBRAIN_HOME set to the copy before relying on it.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },unmanaged_path: { class: 'caller', summary: "Reclone only replaces a checkout created and managed by GBrain." },unsupported_export_data: { class: 'unavailable', summary: "The source contains data this export path cannot carry." },+ unsupported_path: { class: 'caller', reasons: ['not_utf8', 'control_character'], summary: "Classic sync held a file whose name is not valid UTF-8 or contains a control character, so it cannot be a page path; the rest of the source synced.", why: "Git stores a name as bytes and a page path is text, so importing a lossy decoding would store a path no file has. The hold key spells the exact bytes (`/gbrain-bytes/` plus %XX escapes), the message names an item id bound to them, and the hold re-screens on every sync and clears once the name leaves the tree.", docs: 'docs/guides/write-refusals.md#unsupported_path', suggestion: 'Rename the file to a valid UTF-8 name without control characters (the hold\'s fix spells the old name with printf escapes, never raw bytes), commit, then run gbrain sync --source <source> --no-pull.' },unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },diff --git a/src/core/git-env.ts b/src/core/git-env.tsindex f88b8c641b..851d255545 100644--- a/src/core/git-env.ts+++ b/src/core/git-env.ts@@ -14,6 +14,13 @@ export const GIT_LOCAL_ENV_VARS = ['GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFconst LOCAL = new Set<string>(GIT_LOCAL_ENV_VARS);+/**+ * Extra env for a Git call that only reads (diff, ls-files, cat-file, rev-parse, status): `GIT_OPTIONAL_LOCKS=0` stops Git+ * taking `index.lock` to refresh the index opportunistically, so a sync never holds the lock a concurrent commit needs.+ * Never for a call that writes (commit, merge, push, update-ref).+ */+export const GIT_READ_ENV: NodeJS.ProcessEnv = { GIT_OPTIONAL_LOCKS: '0' };+export function gitChildEnv(extra: NodeJS.ProcessEnv = {}, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {};for (const [key, value] of Object.entries(source)) {diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 3595b1d24a..e815234c1e 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -44,6 +44,7 @@ import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair,import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';import { classicRenameHoldFix } from '../classic-rename-holds.ts';import { classicFileHoldFix } from '../classic-file-holds.ts';+import { unsupportedPathHoldFix } from '../sync-byte-paths.ts';import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';import type { SyncDiscovery, SyncRename } from './sync-discovery.ts';import { isCodeFilePath, isImageFilePath, isMultimodalEnabled } from '../sync.ts';@@ -73,8 +74,8 @@ type Exec = Pick<BrainEngine, 'executeRaw'>;export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'| 'legacy_slug_conflict' | 'write_interrupted' | 'origin_conflict'- /** GBRA-133 PR 1 (classic sync): src/core/classic-rename-holds.ts and src/core/classic-file-holds.ts. */- | 'rename_identity_unreadable' | 'rename_reconcile_failed' | 'file_unreadable' | 'absent_from_worktree';+ /** GBRA-133 PR 1 (classic sync): src/core/classic-rename-holds.ts, src/core/classic-file-holds.ts and src/core/sync-byte-paths.ts. */+ | 'rename_identity_unreadable' | 'rename_reconcile_failed' | 'file_unreadable' | 'absent_from_worktree' | 'unsupported_path';/*** Flip lane C: the holds of a write that ran out of attempts, its preparation never settling (`preparation_stalled`)* or its statements ended by the database every time (`write_interrupted`). The file is not the problem: they route to@@ -95,7 +96,8 @@ export interface PreparationStallMeta {sync_argv: string[];}export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason | OriginConflictReason- | 'symlink_in_repo' | 'symlink_outside_root' | 'symlink_dangling' | 'symlink_loop' | 'permission_denied' | 'not_regular_file' | 'skip_worktree' | 'deleted_locally';+ | 'symlink_in_repo' | 'symlink_outside_root' | 'symlink_dangling' | 'symlink_loop' | 'permission_denied' | 'not_regular_file' | 'skip_worktree' | 'deleted_locally'+ | 'not_utf8' | 'control_character';export interface GitHoldMeta {reason?: GitHoldReason;@@ -750,6 +752,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'ccase 'frontmatter_slug_conflict':return contentHoldFix(record);case 'file_unreadable': case 'absent_from_worktree': return classicFileHoldFix(record);+ case 'unsupported_path': return unsupportedPathHoldFix(record);default:return record.meta.reason === 'needs_interpretation'? repair(true, `Reading ${record.path} needs an interpretation (folded lines, a duplicate key or an unclosed list); the preview shows the exact proposal for approval.`)diff --git a/src/core/sync-byte-paths.ts b/src/core/sync-byte-paths.tsnew file mode 100644index 0000000000..96f9a6e024--- /dev/null+++ b/src/core/sync-byte-paths.ts@@ -0,0 +1,138 @@+/**+ * Byte-exact Git paths for classic sync (GBRA-133). Git stores a file name as+ * bytes; a page path is text. A name that is not valid UTF-8 (a Latin-1 name+ * from an old archive) or that holds a control character (a tab, a newline)+ * cannot be a page path, so classic sync holds it `unsupported_path` instead of+ * handing the importer a lossy string. This module is the one place that+ * turns those raw bytes into something stored, shown or typed:+ *+ * - the hold key, `/gbrain-bytes/` + the path with every byte that is not part+ * of a printable UTF-8 character (and every `%`) written `%XX` (upper-case+ * hex). It decodes back to the exact bytes, and it never equals a Git path:+ * Git never emits a path that starts with `/`.+ * - the display path, C-escaped like Git's quoting (`notes/caf\351.md`).+ * - the item id, the first 16 hex digits of the bytes' sha256: an opaque+ * selector bound to the bytes, safe on any command line.+ * - the rename command in the fix, which spells the old name with printf+ * escapes and hands it to `git mv` through a pipe, never as raw argv text.+ */+import { createHash } from 'node:crypto';+import { lstatSync } from 'node:fs';+import type { Action } from './agent-output.ts';+import type { GitHoldRecord } from './persistence/sync-holds.ts';++export type UnsupportedPathReason = 'not_utf8' | 'control_character';++export const BYTE_PATH_KEY_PREFIX = '/gbrain-bytes/';++const STRICT_UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });+// eslint-disable-next-line no-control-regex+const CONTROL = /[\x00-\x1f\x7f]/;+const C_ESCAPES: Record<number, string> = { 7: '\\a', 8: '\\b', 9: '\\t', 10: '\\n', 11: '\\v', 12: '\\f', 13: '\\r' };++/** A Git path as sync can use it: the decoded name, or why it cannot be one. */+export function classifyGitPathBytes(raw: Uint8Array): { path: string } | { reason: UnsupportedPathReason } {+ let path: string;+ try { path = STRICT_UTF8.decode(raw); } catch { return { reason: 'not_utf8' }; }+ return CONTROL.test(path) ? { reason: 'control_character' } : { path };+}++/** Splits bytes into printable UTF-8 characters (strings) and single bytes that are not (numbers). */+function segments(raw: Uint8Array): Array<string | number> {+ const out: Array<string | number> = [];+ for (let i = 0; i < raw.length;) {+ const lead = raw[i]!;+ const size = lead < 0x80 ? 1 : lead >= 0xc2 && lead < 0xe0 ? 2 : lead >= 0xe0 && lead < 0xf0 ? 3 : lead >= 0xf0 && lead < 0xf5 ? 4 : 0;+ let char: string | null = null;+ if (size && i + size <= raw.length) {+ try { char = STRICT_UTF8.decode(raw.subarray(i, i + size)); } catch { char = null; }+ }+ if (char === null || CONTROL.test(char)) { out.push(lead); i += 1; continue; }+ out.push(char);+ i += size;+ }+ return out;+}++const hex = (byte: number) => '%' + byte.toString(16).toUpperCase().padStart(2, '0');++/** The hold key of a path's exact bytes (see the module comment). */+export function encodeBytePathKey(raw: Uint8Array): string {+ return BYTE_PATH_KEY_PREFIX + segments(raw).map(part => typeof part === 'number' ? hex(part) : part === '%' ? hex(0x25) : part).join('');+}++/** The exact bytes a hold key names, or null when `key` is not a canonical byte-path key (an ordinary path among them). */+export function decodeBytePathKey(key: string): Buffer | null {+ if (!key.startsWith(BYTE_PATH_KEY_PREFIX)) return null;+ const body = key.slice(BYTE_PATH_KEY_PREFIX.length);+ const bytes: number[] = [];+ for (let i = 0; i < body.length;) {+ if (body[i] === '%') {+ if (!/^[0-9A-F]{2}$/.test(body.slice(i + 1, i + 3))) return null;+ bytes.push(parseInt(body.slice(i + 1, i + 3), 16));+ i += 3;+ continue;+ }+ const char = String.fromCodePoint(body.codePointAt(i)!);+ bytes.push(...Buffer.from(char, 'utf8'));+ i += char.length;+ }+ const raw = Buffer.from(bytes);+ return encodeBytePathKey(raw) === key ? raw : null;+}++/** The path for a terminal or a message: C escapes for control characters and bytes that are not UTF-8, capped at 200 characters. */+export function displayBytePath(raw: Uint8Array): string {+ const shown = segments(raw).map(part => typeof part === 'string' ? (part === '\\' ? '\\\\' : part)+ : C_ESCAPES[part] ?? '\\' + part.toString(8).padStart(3, '0')).join('');+ return shown.length > 200 ? shown.slice(0, 197) + '...' : shown;+}++/** An opaque selector bound to the path's bytes: the first 16 hex digits of their sha256. */+export function bytePathItemId(raw: Uint8Array): string {+ return createHash('sha256').update(raw).digest('hex').slice(0, 16);+}++/** A suggested replacement name: each control character or byte that is not UTF-8 becomes `_`. */+export function suggestedBytePathName(raw: Uint8Array): string {+ return segments(raw).map(part => typeof part === 'number' ? '_' : part).join('');+}++/**+ * The shell command that renames the file, run from the directory the path is relative to. printf writes the old name+ * (octal escapes for every byte outside printable ASCII and for `\ ' %`) followed by NUL, and xargs -0 hands it to git mv,+ * so the command text is plain ASCII and a name ending in a newline survives.+ */+export function bytePathRenameCommand(raw: Uint8Array, newName: string): string {+ const format = [...raw].map(byte => byte >= 0x20 && byte < 0x7f && !'\\\'%'.includes(String.fromCharCode(byte))+ ? String.fromCharCode(byte) : '\\' + byte.toString(8).padStart(3, '0')).join('') + '\\000';+ return `printf '${format}' | xargs -0 -I{} git mv -- {} '${newName.replaceAll("'", "'\\''")}'`;+}++/** Whether a byte-path hold's file is gone from `root` (null: `key` is an ordinary path, not a byte-path key). */+export function bytePathHoldGone(root: string, key: string): boolean | null {+ const raw = decodeBytePathKey(key);+ if (!raw) return null;+ return !lstatSync(Buffer.concat([Buffer.from(root.endsWith('/') ? root : root + '/'), raw]), { throwIfNoEntry: false });+}++/** The fix for an `unsupported_path` hold: the user renames the file (its argv is a read-only status; the name is never in it). */+export function unsupportedPathHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'meta'>): Action {+ const source = record.source_id;+ const raw = decodeBytePathKey(record.path);+ const reason = record.meta.reason === 'control_character' ? 'control_character' : 'not_utf8';+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };+ const what = reason === 'control_character' ? 'has a control character in its name (a tab, a newline or another byte below 0x20)' : 'has a name that is not valid UTF-8';+ const rename = raw+ ? `The file ${displayBytePath(raw)} (item ${bytePathItemId(raw)}) ${what}, so sync cannot use it as a page path and held it; the rest of source ${source} keeps syncing. `+ + `Rename it to a valid UTF-8 name without control characters, from the directory the path is relative to (the source's checkout), for example: `+ + `${bytePathRenameCommand(raw, suggestedBytePathName(raw))} (the old name is spelled with printf escapes). `+ : `A file in source ${source} ${what}, so sync held it; gbrain sources status ${source} --json names it. Rename it to a valid UTF-8 name without control characters. `;+ return { argv: verify.argv, consent: [], actor: 'user', requires_exclusive: false, docs: reason === 'control_character' ? 'docs/guides/write-refusals.md#unsupported_path-control_character' : 'docs/guides/write-refusals.md#unsupported_path-not_utf8',+ user_message: rename + `Then commit the rename and run gbrain sync --source ${source} --no-pull, which imports the file under its new name and clears the hold.`,+ why: 'A page path is text and this name is bytes no text names exactly, so importing it would store a different path than the file has. Renaming the file changes the repository, so the user decides; '+ + 'the hold re-screens on every sync and clears once the old name leaves the tree.',+ then: { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: 'Imports the renamed file and clears the hold once the rename is committed; a file that still has the old name stays held without blocking the rest.' },+ verify };+}diff --git a/src/core/sync-delta.ts b/src/core/sync-delta.tsindex beba40fc0f..5695aa882c 100644--- a/src/core/sync-delta.ts+++ b/src/core/sync-delta.ts@@ -33,7 +33,8 @@*/import { execFileSync } from './spawn.ts';import { buildSyncManifest, type SyncManifest } from './sync.ts';-import { gitChildEnv } from './git-env.ts';+import { GIT_READ_ENV, gitChildEnv } from './git-env.ts';+import { classifyGitPathBytes, displayBytePath, type UnsupportedPathReason } from './sync-byte-paths.ts';/** Runs a git subcommand in `repoPath` and returns trimmed stdout (throws on failure). */export type GitRunner = (repoPath: string, args: string[]) => string;@@ -44,7 +45,7 @@ export type GitRunner = (repoPath: string, args: string[]) => string;// would ENOBUFS-crash the sync with no log line).const DEFAULT_GIT_RUNNER: GitRunner = (repoPath, args) =>execFileSync('git', ['-c', 'core.quotepath=false', '-C', repoPath, ...args], {- env: gitChildEnv(),+ env: gitChildEnv(GIT_READ_ENV),encoding: 'utf-8',timeout: 30_000,maxBuffer: 100 * 1024 * 1024,@@ -158,3 +159,129 @@ export function computeSyncDelta(: null;return { status: 'ok', manifest: detached ? mergeSyncManifests(manifest, detached) : manifest };}++/** Runs a read-only git subcommand in `repoPath` and returns its stdout bytes untouched (throws on failure). */+export type GitBytesRunner = (repoPath: string, args: string[]) => Buffer;++const DEFAULT_GIT_BYTES_RUNNER: GitBytesRunner = (repoPath, args) =>+ execFileSync('git', ['-C', repoPath, ...args], { env: gitChildEnv(GIT_READ_ENV), timeout: 30_000, maxBuffer: 100 * 1024 * 1024 });++let _gitBytesRunner: GitBytesRunner = DEFAULT_GIT_BYTES_RUNNER;++/** Test seam for the lossless parser; `null` restores the default. */+export function _setGitBytesRunnerForTests(fn: GitBytesRunner | null): void {+ _gitBytesRunner = fn ?? DEFAULT_GIT_BYTES_RUNNER;+}++/** A delta path that is not a usable page path (not UTF-8, or a control character), as its exact bytes. */+export interface UnsupportedGitPath { raw: Buffer; reason: UnsupportedPathReason }++/**+ * Classic sync's delta read as bytes (GBRA-133): the manifest of every path that decodes as UTF-8 without a control+ * character, exactly as Git has it (no trim, no unquoting), plus what the text manifest cannot carry: `unsupported`+ * paths present after the range, `gone` unsupported paths that left the tree, and gitlinks (submodules, embedded+ * repositories) that appeared, which sync does not follow.+ */+export interface LosslessDelta {+ manifest: SyncManifest;+ unsupported: UnsupportedGitPath[];+ gone: Buffer[];+ gitlinks: string[];+}++export type LosslessDeltaResult = ({ status: 'ok' } & LosslessDelta) | { status: 'unavailable'; reason: 'anchor_missing' | 'diff_failed' };++function splitNul(out: Buffer): Buffer[] {+ const fields: Buffer[] = [];+ for (let start = 0; start < out.length;) {+ const end = out.indexOf(0, start);+ if (end === -1) { fields.push(out.subarray(start)); break; }+ fields.push(out.subarray(start, end));+ start = end + 1;+ }+ return fields;+}++/** Parses `git diff --raw -z -M` output. Status letters map as `buildSyncManifest` maps them; a gitlink (mode 160000) never enters the manifest. */+export function parseRawDiffZ(out: Buffer): LosslessDelta {+ const delta: LosslessDelta = { manifest: { added: [], modified: [], deleted: [], renamed: [] }, unsupported: [], gone: [], gitlinks: [] };+ const { manifest } = delta;+ const present = (raw: Buffer, list: string[]) => {+ const parsed = classifyGitPathBytes(raw);+ if ('path' in parsed) list.push(parsed.path);+ else delta.unsupported.push({ raw: Buffer.from(raw), reason: parsed.reason });+ };+ const left = (raw: Buffer) => {+ const parsed = classifyGitPathBytes(raw);+ if ('path' in parsed) manifest.deleted.push(parsed.path);+ else delta.gone.push(Buffer.from(raw));+ };+ const gitlink = (raw: Buffer) => {+ const parsed = classifyGitPathBytes(raw);+ delta.gitlinks.push('path' in parsed ? parsed.path : displayBytePath(raw));+ };+ const fields = splitNul(out);+ for (let i = 0; i < fields.length;) {+ const header = fields[i++]!.toString('latin1');+ if (!header.startsWith(':')) continue;+ const [oldMode, newMode, , , status = ''] = header.slice(1).split(' ');+ const action = status[0];+ const first = fields[i++];+ if (!first) break;+ const oldLink = oldMode === '160000', newLink = newMode === '160000';+ if (action === 'R' || action === 'C') {+ const second = fields[i++];+ if (!second) break;+ if (action === 'C') { present(second, manifest.added); continue; }+ const from = classifyGitPathBytes(first), to = classifyGitPathBytes(second);+ if ('path' in from && 'path' in to) {+ const similarity = Number(status.slice(1));+ manifest.renamed.push({ from: from.path, to: to.path, ...(status.length > 1 && Number.isInteger(similarity) ? { similarity } : {}) });+ continue;+ }+ if (!('path' in from)) delta.gone.push(Buffer.from(first));+ present(second, manifest.added);+ continue;+ }+ if (newLink && !oldLink) {+ gitlink(first);+ if (action !== 'A') left(first);+ continue;+ }+ if (oldLink && newLink) continue;+ if (action === 'A') present(first, manifest.added);+ else if (action === 'M' || action === 'T' || action === 'U') present(first, manifest.modified);+ else if (action === 'D' && !oldLink) left(first);+ }+ return delta;+}++/** `computeSyncDelta` read as bytes (classic sync); the same anchor and diff ladder. */+export function computeLosslessSyncDelta(repoPath: string, fromCommit: string, toCommit: string): LosslessDeltaResult {+ const run = _gitBytesRunner;+ try {+ run(repoPath, ['cat-file', '-t', fromCommit]);+ } catch {+ return { status: 'unavailable', reason: 'anchor_missing' };+ }+ let out: Buffer;+ try {+ out = run(repoPath, ['diff', '--raw', '-z', '-M', `${fromCommit}..${toCommit}`]);+ } catch {+ return { status: 'unavailable', reason: 'diff_failed' };+ }+ return { status: 'ok', ...parseRawDiffZ(out) };+}++/** `buildDetachedWorkingTreeManifest` read as bytes (classic sync): tracked changes against HEAD plus untracked files. */+export function buildLosslessWorkingTreeManifest(repoPath: string): LosslessDelta {+ const run = _gitBytesRunner;+ const delta = parseRawDiffZ(run(repoPath, ['diff', '--raw', '-z', '-M', 'HEAD']));+ for (const raw of splitNul(run(repoPath, ['ls-files', '-z', '--others', '--exclude-standard']))) {+ if (raw.length === 0) continue;+ const parsed = classifyGitPathBytes(raw);+ if ('path' in parsed) delta.manifest.added.push(parsed.path);+ else delta.unsupported.push({ raw: Buffer.from(raw), reason: parsed.reason });+ }+ return { ...delta, manifest: { ...delta.manifest, added: unique(delta.manifest.added), modified: unique(delta.manifest.modified), deleted: unique(delta.manifest.deleted) } };+}diff --git a/src/core/sync-git.ts b/src/core/sync-git.tsindex a05d87c807..d038e0ea03 100644--- a/src/core/sync-git.ts+++ b/src/core/sync-git.ts@@ -11,7 +11,7 @@ import { resolveSlugForPath, DEFAULT_SOURCE_ID } from './sync.ts';import { DELETE_BATCH_SIZE } from './engine-constants.ts';import { invalidateGitListingCache, knownOutsideGitRepo, noteGitFailure } from './git-visible-files.ts';import { hasUnresolvedDbOnlyDeclaration, loadStorageConfig } from './storage-config.ts';-import { gitChildEnv } from './git-env.ts';+import { GIT_READ_ENV, gitChildEnv } from './git-env.ts';/*** v0.32.7 CJK wave (codex post-merge F4): resolve a slug by `pages.source_path`@@ -290,6 +290,11 @@ function noteGitCommand(args: string[]): void {if (!READ_ONLY_GIT.has(args[0] ?? '')) invalidateGitListingCache();}+/** `GIT_READ_ENV` for a read-only subcommand (no optional index lock), nothing for one that writes. */+function readOnlyEnv(args: string[]): NodeJS.ProcessEnv {+ return READ_ONLY_GIT.has(args[0] ?? '') ? GIT_READ_ENV : {};+}+/*** Shell out to git with a generous maxBuffer.*@@ -318,7 +323,7 @@ export function git(): string {noteGitCommand(args);return execFileSync('git', buildGitInvocation(repoPath, args, configs), {- env: gitChildEnv(),+ env: gitChildEnv(readOnlyEnv(args)),encoding: 'utf-8',timeout: timeoutMs,maxBuffer: 100 * 1024 * 1024,@@ -336,7 +341,7 @@ export function git(export function gitRawOutput(repoPath: string, args: string[]): string {noteGitCommand(args);return execFileSync('git', buildGitInvocation(repoPath, args, []), {- env: gitChildEnv(),+ env: gitChildEnv(readOnlyEnv(args)),encoding: 'utf-8',timeout: 30000,maxBuffer: 100 * 1024 * 1024,@@ -632,7 +637,7 @@ export function isPathSafe(filePath: string, gitRoot: string): boolean {export function hasOriginRemote(repoPath: string): boolean {try {execFileSync('git', buildGitInvocation(repoPath, ['remote', 'get-url', 'origin']), {- env: gitChildEnv(),+ env: gitChildEnv(GIT_READ_ENV),encoding: 'utf-8',timeout: 30000,stdio: ['ignore', 'ignore', 'ignore'],diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.tsindex 6c7c0a2410..4c0e2ceade 100644--- a/src/core/sync-rename-identity.ts+++ b/src/core/sync-rename-identity.ts@@ -34,7 +34,7 @@ import { JSON_SCHEMA } from 'js-yaml';import { loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';import type { BrainEngine } from './engine.ts';import { spawn } from './spawn.ts';-import { gitChildEnv } from './git-env.ts';+import { GIT_READ_ENV, gitChildEnv } from './git-env.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';@@ -87,7 +87,7 @@ export function frontmatterIdentity(head: Buffer | string | null): FrontmatterIdexport 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(), stdio: ['pipe', 'pipe', 'pipe'] });+ const child = spawn('git', ['-c', 'core.quotepath=false', '-C', repo, 'cat-file', '--batch'], { env: gitChildEnv(GIT_READ_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/e2e/s-classic-byte-paths-postgres.test.ts b/test/e2e/s-classic-byte-paths-postgres.test.tsnew file mode 100644index 0000000000..71bfd71b1f--- /dev/null+++ b/test/e2e/s-classic-byte-paths-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-classic-byte-paths.test.ts'));diff --git a/test/pathological/s-classic-byte-paths.test.ts b/test/pathological/s-classic-byte-paths.test.tsnew file mode 100644index 0000000000..a0e80bbc23--- /dev/null+++ b/test/pathological/s-classic-byte-paths.test.ts@@ -0,0 +1,235 @@+/**+ * GBRA-133 PR 1 item 3 (second half): classic sync reads Git paths as bytes.+ *+ * Before this, classic sync ran `git diff --name-status -M` without `-z` and+ * decoded stdout as UTF-8. A non-UTF-8 name (S-7, `notes/caf<0xE9>.md`) became+ * U+FFFD, the file "did not exist" and was checkpointed as deleted after the+ * pin with no message; tab and newline names (S-2, S-3) were decoded, then+ * skipped as malformed with only a log line naming no path; a gitlink (an+ * embedded repository or submodule, S-23/S-24) left the tree unindexed with+ * nothing said.+ *+ * Protects: such a name never reaches the importer as a lossy string. It is+ * held `unsupported_path` (`not_utf8` | `control_character`) under a key that+ * encodes its exact bytes, with an escaped display path, an item id bound to+ * the bytes and a fix whose argv never carries the name; the healthy sibling+ * imports, the cursor reaches HEAD, no failure-ledger row is written, the hold+ * stays while the file does and clears when a later commit renames it to a+ * valid name (which then imports). A gitlink is reported once, in the run it+ * appears. Quoted names keep importing. Sync's Git reads run with+ * GIT_OPTIONAL_LOCKS=0, so a sync never takes index.lock; writes do not.+ *+ * PGLite always, Postgres when DATABASE_URL is set (test/e2e wrapper).+ */+import { describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { SyncResult } from '../../src/commands/sync.ts';+import { gitHoldItem, readGitSourceHolds, type GitHoldRecord } from '../../src/core/persistence/sync-holds.ts';+import { git, gitRawOutput } from '../../src/core/sync-git.ts';+import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../../src/core/sync-delta.ts';+import { confirmRenameIdentities } from '../../src/core/sync-rename-identity.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, pathologicalArms, renderFix } from './harness.ts';+import { gitIn, md, observe, withProbeEngine, withProbeRepo, type ProbeRepo } from './s-blockers-fixture.ts';++const CAFE = Buffer.concat([Buffer.from('notes/caf'), Buffer.from([0xe9]), Buffer.from('.md')]);+const itemId = (raw: Buffer) => createHash('sha256').update(raw).digest('hex').slice(0, 16);+const sh = (cwd: string, script: string) => execFileSync('bash', ['-c', script], { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });++async function holdsOf(r: ProbeRepo): Promise<GitHoldRecord[]> {+ return (await readGitSourceHolds(r.engine, { sourceIds: [r.sourceId] }))[0]?.holds ?? [];+}++async function pageAt(engine: BrainEngine, sourceId: string, sourcePath: string): Promise<string | null> {+ const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL', [sourceId, sourcePath]);+ return row?.slug ?? null;+}++/** One seeded classic repo, first sync taken; `run` commits the odd input next to ok/healthy-1.md. */+async function withClassic(databaseUrl: string | undefined, run: (r: ProbeRepo) => Promise<void>): Promise<void> {+ await withProbeEngine(databaseUrl, async (engine, home) => {+ await withProbeRepo(engine, 'classic', home, async r => {+ await r.sync();+ r.write('ok/healthy-1.md', md('healthy one'));+ await run(r);+ });+ });+}++describe('unsupported_path key, display and fix (no engine)', () => {+ test('the key encodes the exact bytes, round-trips, and never collides with a Git path', async () => {+ const { encodeBytePathKey, decodeBytePathKey, displayBytePath, bytePathItemId } = await import('../../src/core/sync-byte-paths.ts');+ const tab = Buffer.from('notes/tab\there.md');+ const pct = Buffer.concat([Buffer.from('a%b/'), Buffer.from([0xff, 0x0a])]);+ expect(encodeBytePathKey(CAFE)).toBe('/gbrain-bytes/notes/caf%E9.md');+ expect(encodeBytePathKey(tab)).toBe('/gbrain-bytes/notes/tab%09here.md');+ expect(encodeBytePathKey(pct)).toBe('/gbrain-bytes/a%25b/%FF%0A');+ for (const raw of [CAFE, tab, pct, Buffer.from('notes/jos\u00e9.md')]) expect(decodeBytePathKey(encodeBytePathKey(raw))).toEqual(raw);+ expect(decodeBytePathKey('notes/caf%E9.md')).toBeNull();+ expect(decodeBytePathKey('/gbrain-bytes/notes/%ZZ.md')).toBeNull();+ expect(displayBytePath(CAFE)).toBe('notes/caf\\351.md');+ expect(displayBytePath(Buffer.from('notes/line\nbreak.md'))).toBe('notes/line\\nbreak.md');+ expect(bytePathItemId(CAFE)).toBe(itemId(CAFE));+ });++ test('the rename command in the fix reads the name from printf escapes, so it renames the real file', async () => {+ const { bytePathRenameCommand } = await import('../../src/core/sync-byte-paths.ts');+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-byte-rename-'));+ try {+ for (const raw of [CAFE, Buffer.from("notes/it's 100%\tdone\n.md")]) {+ mkdirSync(join(dir, 'notes'), { recursive: true });+ writeFileSync(Buffer.concat([Buffer.from(dir + '/'), raw]), 'x');+ const command = bytePathRenameCommand(raw, 'notes/renamed.md');+ expect(command).not.toContain('\ufffd');+ expect(/[\x00-\x1f\x7f-\x9f]/.test(command)).toBe(false);+ gitIn(dir, 'init', '-q'); gitIn(dir, 'add', '-A');+ sh(dir, command);+ expect(gitIn(dir, 'ls-files', '-z').split('\0').filter(Boolean)).toEqual(['notes/renamed.md']);+ rmSync(join(dir, '.git'), { recursive: true, force: true }); rmSync(join(dir, 'notes'), { recursive: true, force: true });+ }+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+});++describe('sync Git reads take no optional lock (GIT_OPTIONAL_LOCKS=0)', () => {+ test('diff, ls-files, cat-file and rev-parse carry GIT_OPTIONAL_LOCKS=0; a ref write does not', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-optional-locks-'));+ const bin = join(dir, 'bin'), log = join(dir, 'git.log'), repo = join(dir, 'repo');+ 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'+ + 'printf \'%s %s\\n\' "${GIT_OPTIONAL_LOCKS:-unset}" "$sub" >> "$PROBE_GIT_LOG"\nexec ' + 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]');+ writeFileSync(join(repo, 'a.md'), md('a')); gitIn(repo, 'add', '-A'); gitIn(repo, 'commit', '-qm', 'a');+ const first = gitIn(repo, 'rev-parse', 'HEAD');+ gitIn(repo, 'mv', 'a.md', 'b.md'); writeFileSync(join(repo, 'b.md'), md('a') + 'a longer body, so the rename is inexact\n'); gitIn(repo, 'add', '-A'); gitIn(repo, 'commit', '-qm', 'b');+ const second = gitIn(repo, 'rev-parse', 'HEAD');+ await withEnv({ PATH: bin + ':' + process.env.PATH, PROBE_GIT_LOG: log }, async () => {+ git(repo, ['rev-parse', 'HEAD']);+ git(repo, ['diff', '--name-status', first, second]);+ gitRawOutput(repo, ['ls-files', '-z']);+ expect(computeSyncDelta(repo, first, second).status).toBe('ok');+ buildDetachedWorkingTreeManifest(repo);+ const engine = { executeRaw: async () => [] } as unknown as Pick<BrainEngine, 'executeRaw'>;+ await confirmRenameIdentities(engine, repo, first, second, { added: [], modified: [], deleted: [], renamed: [{ from: 'a.md', to: 'b.md', similarity: 60 }] },+ { sourceId: 'default', sourcePathOf: p => p });+ git(repo, ['update-ref', 'refs/heads/probe', 'HEAD']);+ });+ const lines = readFileSync(log, 'utf8').trim().split('\n').map(line => { const [locks, sub] = line.split(' '); return { locks, sub }; });+ const reads = lines.filter(line => ['rev-parse', 'diff', 'ls-files', 'cat-file'].includes(line.sub!));+ expect(new Set(reads.map(line => line.sub))).toEqual(new Set(['rev-parse', 'diff', 'ls-files', 'cat-file']));+ expect(reads.filter(line => line.locks !== '0')).toEqual([]);+ expect(lines.filter(line => line.sub === 'update-ref')).toEqual([{ locks: 'unset', sub: 'update-ref' }]);+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+});++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`classic byte-path parsing (${backend})`, () => {+ test('S-7: a non-UTF-8 name is held unsupported_path/not_utf8 under its encoded key; the sibling imports and the cursor reaches HEAD', async () => {+ await withClassic(databaseUrl, async r => {+ r.write(CAFE, md('latin1')); r.commitAll('odd');+ const obs = await observe(r, 'ok/healthy-1');+ expect({ thrown: obs.thrown, healthy: obs.healthy, cursorAtHead: obs.cursorAtHead, ledger: obs.ledger }).toEqual({ thrown: null, healthy: true, cursorAtHead: true, ledger: [] });+ const holds = await holdsOf(r);+ const hold = holds.find(h => h.code === 'unsupported_path');+ expectItemFailure(hold && { key: hold.path, code: hold.code }, { key: '/gbrain-bytes/notes/caf%E9.md', code: 'unsupported_path' });+ expect(hold!.meta.reason).toBe('not_utf8');+ expect(hold!.message).toContain('notes/caf\\351.md');+ expect(hold!.message).toContain(itemId(CAFE));+ expect(JSON.stringify(holds)).not.toContain('\ufffd');+ const item = gitHoldItem(hold!);+ expect(item.docs).toBe('docs/guides/write-refusals.md#unsupported_path-not_utf8');+ const fix = item.fix;+ for (const arg of [fix.argv, fix.verify?.argv, fix.then?.argv].flatMap(argv => argv ?? [])) expect(arg).not.toMatch(/notes\/caf|[^\x20-\x7e]/);+ expect(renderFix(fix)).toBe(`gbrain sources status ${r.sourceId} --json`);+ expect(fix.actor).toBe('user');+ expect(fix.user_message).toContain(itemId(CAFE));+ expect(fix.user_message).toContain("printf 'notes/caf\\351.md\\000'");+ expect(fix.then?.argv).toEqual(['gbrain', 'sync', '--source', r.sourceId, '--no-pull']);++ r.write('ok/healthy-2.md', md('healthy two')); r.commitAll('next');+ const again = await observe(r, 'ok/healthy-2');+ expect({ thrown: again.thrown, healthy: again.healthy, cursorAtHead: again.cursorAtHead, ledger: again.ledger }).toEqual({ thrown: null, healthy: true, cursorAtHead: true, ledger: [] });+ expect((await holdsOf(r)).map(h => [h.path, h.code])).toEqual([['/gbrain-bytes/notes/caf%E9.md', 'unsupported_path']]);+ });+ }, 120_000);++ test('S-2/S-3: tab and newline names are held unsupported_path/control_character, not skipped as malformed', async () => {+ await withClassic(databaseUrl, async r => {+ r.write('notes/tab\there.md', md('tab')); r.write('notes/line\nbreak.md', md('newline')); r.commitAll('odd');+ const obs = await observe(r, 'ok/healthy-1');+ expect({ thrown: obs.thrown, healthy: obs.healthy, cursorAtHead: obs.cursorAtHead, ledger: obs.ledger, malformed: obs.malformedSkipped ?? 0 })+ .toEqual({ thrown: null, healthy: true, cursorAtHead: true, ledger: [], malformed: 0 });+ const holds = (await holdsOf(r)).map(h => ({ path: h.path, code: h.code, reason: h.meta.reason })).sort((a, b) => a.path.localeCompare(b.path));+ expect(holds).toEqual([+ { path: '/gbrain-bytes/notes/line%0Abreak.md', code: 'unsupported_path', reason: 'control_character' },+ { path: '/gbrain-bytes/notes/tab%09here.md', code: 'unsupported_path', reason: 'control_character' },+ ]);+ const message = (await holdsOf(r)).find(h => h.path.endsWith('tab%09here.md'))!.message;+ expect(message).toContain('notes/tab\\there.md');+ expect(/[\x00-\x1f]/.test(message)).toBe(false);+ });+ }, 120_000);++ test('S-7: a later commit renaming the file to a valid name imports it and clears the hold', async () => {+ await withClassic(databaseUrl, async r => {+ r.write(CAFE, md('latin1')); r.commitAll('odd');+ await observe(r, 'ok/healthy-1');+ expect((await holdsOf(r)).map(h => h.code)).toEqual(['unsupported_path']);+ sh(r.root, "git mv -- \"$(printf 'notes/caf\\351.md')\" notes/cafe.md");+ r.commitAll('rename to a valid name');+ const obs = await observe(r, 'notes/cafe');+ expect({ thrown: obs.thrown, healthy: obs.healthy, cursorAtHead: obs.cursorAtHead, ledger: obs.ledger }).toEqual({ thrown: null, healthy: true, cursorAtHead: true, ledger: [] });+ expect(await holdsOf(r)).toEqual([]);+ });+ }, 120_000);++ test('S-23: a gitlink is reported once, in the run it appears, and never blocks', async () => {+ await withClassic(databaseUrl, async r => {+ const nested = join(r.root, 'nested'); mkdirSync(nested);+ gitIn(nested, 'init', '-q'); writeFileSync(join(nested, 'n.md'), md('n'));+ gitIn(nested, '-c', 'user.name=E', '-c', '[email protected]', 'add', '-A');+ gitIn(nested, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'n');+ r.commitAll('gitlink');+ expect(gitIn(r.root, 'ls-files', '-s', 'nested')).toStartWith('160000 ');+ const first = await r.sync() as SyncResult & { gitlinks_not_followed?: string[] };+ expect(first.gitlinks_not_followed).toEqual(['nested']);+ expect({ cursorAtHead: await r.lastCommit() === r.head(), holds: await holdsOf(r) }).toEqual({ cursorAtHead: true, holds: [] });+ r.write('ok/healthy-2.md', md('healthy two')); r.commitAll('next');+ const second = await r.sync() as SyncResult & { gitlinks_not_followed?: string[] };+ expect(second.gitlinks_not_followed).toBeUndefined();+ expect(await pageAt(r.engine, r.sourceId, 'ok/healthy-2.md')).toBe('ok/healthy-2');+ });+ }, 120_000);++ test('S-1: a name with double quotes still imports', async () => {+ await withClassic(databaseUrl, async r => {+ r.write('notes/say "hi".md', md('quoted')); r.commitAll('odd');+ const obs = await observe(r, 'ok/healthy-1');+ expect({ thrown: obs.thrown, cursorAtHead: obs.cursorAtHead, ledger: obs.ledger }).toEqual({ thrown: null, cursorAtHead: true, ledger: [] });+ expect(await pageAt(r.engine, r.sourceId, 'notes/say "hi".md')).not.toBeNull();+ expect(await holdsOf(r)).toEqual([]);+ });+ }, 120_000);++ test('S-52: the parser keeps a trailing space; the name is not a Markdown file, so it is skipped like any other, and the cursor reaches HEAD', async () => {+ await withClassic(databaseUrl, async r => {+ r.write('notes/trail.md ', md('trail')); r.commitAll('odd');+ const { computeLosslessSyncDelta } = await import('../../src/core/sync-delta.ts');+ const delta = computeLosslessSyncDelta(r.root, (await r.lastCommit())!, r.head());+ expect(delta.status === 'ok' && delta.manifest.added.sort()).toEqual(['notes/trail.md ', 'ok/healthy-1.md']);+ const obs = await observe(r, 'ok/healthy-1');+ expect({ thrown: obs.thrown, healthy: obs.healthy, cursorAtHead: obs.cursorAtHead, ledger: obs.ledger }).toEqual({ thrown: null, healthy: true, cursorAtHead: true, ledger: [] });+ expect(existsSync(join(r.root, 'notes/trail.md '))).toBe(true);+ });+ }, 120_000);+ });+}