Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): the Git-scope manifest refuses symlinks, not a filesystem's spelling of a tracked path
garrytanfceaf3030afa
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 6757ec94f8..0c2b4f50b1 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -41,7 +41,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340.- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.test.ts`.-- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.+- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). #6510: `trackedBytes` checks for symlinks with `lstat` on every directory component between the canonical root and the leaf, then the leaf, on every read (no cache across files: a parent swapped to a symlink after the first file would otherwise let a later leaf read outside the root), reading through the Git spelling; the former `realpath(path) === path` proxy refused a checkout whose volume spells a name differently (APFS NFC/NFD, case-insensitive volumes) with no symlink anywhere. Tests: `test/persistence-manifest-git-scope.test.ts`, `test/worktree-manifest-unicode.test.ts` (synthetic realpath-spelling spy on Linux, parent-swap, case-spelling where the tmpdir is case-insensitive), `test/hardened-git-filters.test.ts`.- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, the `#6210` block of `test/persistence-git-coalescing-5530.slow.test.ts` (Postgres via its e2e twin).- `src/core/persistence/consumer-election.ts` — #6317 (B1b): the consumer mode machine (`probing` → `full` | `waiter_only` → `promoted`) and `WaiterOnlyConsumer`, the `PersistenceConsumerLike` surface for a resident process (`sync`, `jobs`, `autopilot`, `mcp`) that found a live full consumer of this host and claims nothing: `wake()` is a no-op, settlement listeners still fire through `settledWaiters`, `status()` reports `waiter_only` with the owner's identity. `electOwner` re-probes every tick and promotes on the owner's progress (lapsed 60 s, wedged, not full, gone); a promoted consumer drains back after three healthy ticks of a `full` owner only, so promotion storms converge. `forceOwnConsumer(reason)` is `--no-delegate`'s process flag.- `src/core/persistence/consumer-lane.ts` — #6317 (reporter ask 2): `consumerStatementEngine`, the Proxy that routes the consumer's own tick statements (idle probe, switch read, recovery and expired-claim scans, capacity, releases, floor) to `executeRawDirect` while the dual pool is active (`GBRAIN_DIRECT_DATABASE_URL` or the Supabase-derived direct URL), so the owner's round-trips avoid a transaction-mode pooler; `status().connection = { lane, pooler_mode, direct_host? }` says which lane is in use, and one `[persistence] phase=start reason=transaction_pooler` line prints when only a `prepare=false` URL exists.diff --git a/src/core/persistence/worktree-manifest.ts b/src/core/persistence/worktree-manifest.tsindex 151e2d1759..a7edbae6cf 100644--- a/src/core/persistence/worktree-manifest.ts+++ b/src/core/persistence/worktree-manifest.ts@@ -146,20 +146,35 @@ const outsideCheckout = (canonical: string) => unsafe('Canonical worktree transf`The Git index of ${canonical} lists a path that leaves the checkout (a hand-edited or corrupted index), so no manifest was recorded and nothing outside the checkout was read. `+ 'Ask the user to replace the checkout with a fresh git clone of the same repository at the same commit, then run the step again.');-/** The working-tree bytes of a tracked path; null when it is missing on disk (counted as deleted). */+/**+ * The working-tree bytes of a tracked path; null when it is missing on disk (counted as deleted).+ *+ * #6510: the symlink check is `lstat` on every directory component between the canonical root and the leaf, then+ * the leaf, on every read; a symlink anywhere refuses. The earlier `realpath(path) === path` proxy conflated "resolves+ * through a link" with "the filesystem spells this name differently", which is legal on a normalization-insensitive+ * volume (APFS answers an NFC request with the NFD entry) and on a case-insensitive one, and falsely refused with+ * `writer_manifest_unsafe`. The bytes are read through the Git spelling, never through an alias. No component is+ * cached across files: a parent replaced by a symlink after the first file of a manifest would otherwise let a later+ * leaf read outside the root.+ */function trackedBytes(canonical: string, rel: string): Buffer | null {if (!insideCheckout(rel)) throw outsideCheckout(canonical);- const path = join(canonical, ...rel.split('/'));+ const parts = rel.split('/');+ const path = join(canonical, ...parts);const within = relative(canonical, path);if (within === '' || within.split(sep)[0] === '..' || isAbsolute(within)) throw outsideCheckout(canonical);- let real: string;- try { real = realpathSync(path); } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT' || (error as NodeJS.ErrnoException).code === 'ENOTDIR') return null;- throw error;+ let component = canonical;+ for (let i = 0; i < parts.length; i++) {+ component = join(component, parts[i]!);+ let info;+ try { info = lstatSync(component); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || (error as NodeJS.ErrnoException).code === 'ENOTDIR') return null;+ throw error;+ }+ if (info.isSymbolicLink()) throw unsafe('The canonical checkout manifest requires a symlink-free checkout.',+ `${rel} in the checkout resolves through a symlink, so no manifest was recorded. Ask the user to replace the link with a real file or directory (or remove it), then run the step again.`);+ if (i < parts.length - 1 ? !info.isDirectory() : !info.isFile()) return null;}- if (real !== path || lstatSync(path).isSymbolicLink()) throw unsafe('The canonical checkout manifest requires a symlink-free checkout.',- `${rel} in the checkout resolves through a symlink, so no manifest was recorded. Ask the user to replace the link with a real file or directory (or remove it), then run the step again.`);- if (!lstatSync(path).isFile()) return null;return readFileSync(path);}diff --git a/test/worktree-manifest-unicode.test.ts b/test/worktree-manifest-unicode.test.tsnew file mode 100644index 0000000000..f4471b6014--- /dev/null+++ b/test/worktree-manifest-unicode.test.ts@@ -0,0 +1,160 @@+/**+ * #6510: the Git-scope manifest hashes a tracked file through its Git spelling and refuses only real symlinks.+ *+ * On macOS APFS (normalization-insensitive) Git's index spells `café.md` in NFC while `realpath` answers with the+ * on-disk NFD entry, and master's `realpath(path) === path` proxy refused the checkout with `writer_manifest_unsafe`+ * although nothing was a symlink; a case-insensitive volume whose index case differs from the on-disk case fails the+ * same way. The fix lstat's every directory component and the leaf (per read, no cache) and never consults the alias.+ *+ * Linux (ext4) is normalization-sensitive, so the positive case is SYNTHETIC: a same-inode hard link supplies the NFD+ * entry and `fs.realpathSync` is spied to return that spelling for the NFC path, exactly what APFS would answer (the+ * spy fixture idea is PR #6520's, @javieraldape). It is a behavioural fail-first on master (old refusal vs. the correct+ * digest), not an APFS reproduction; the case-spelling case runs only where the tmpdir is case-insensitive. The+ * negatives (leaf/parent symlink, submodule, tracked symlink, and a parent swapped to a symlink after the first file+ * was read) pass before and after and pin what the fix must keep refusing; the hand-edited index escape stays pinned+ * in test/persistence-manifest-git-scope.test.ts.+ *+ * `spyOn(fs, …)` is process-global; every spy is synchronous and restored in `finally`.+ */+import { expect, spyOn, test } from 'bun:test';+import * as fs from 'node:fs';+import { execFileSync } from 'node:child_process';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { worktreeManifest } from '../src/core/persistence/worktree-manifest.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: 'pipe' }).toString().trim();+const unsafe = expect.objectContaining({ code: 'writer_manifest_unsafe' });+const NFC = 'caf\u00e9.md', NFD = NFC.normalize('NFD');++/** A Git checkout (precomposed index) holding one tracked file named in NFC; `fn` gets the root and both spellings. */+function fixture(fn: (root: string, nfc: string, nfd: string) => void): void {+ const home = fs.mkdtempSync(join(tmpdir(), 'gbrain-manifest-unicode-'));+ const root = fs.realpathSync(home);+ try {+ git(root, 'init', '-q');+ git(root, 'config', 'core.precomposeunicode', 'true');+ const nfc = join(root, NFC);+ fs.writeFileSync(nfc, 'Synthetic commitment: keep the complete file.\n');+ git(root, 'add', NFC);+ fn(root, nfc, nfc.normalize('NFD'));+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+}++/** `fs.realpathSync(path)` answers `real` (what a normalization- or case-insensitive volume would say); everything else is real. */+function withSpelling(path: string, real: string, fn: () => void): void {+ const original = fs.realpathSync;+ const probe = spyOn(fs, 'realpathSync').mockImplementation(((p: fs.PathLike, opts?: unknown) =>+ String(p) === path ? real : original(p, opts as never)) as typeof fs.realpathSync);+ try { fn(); } finally { probe.mockRestore(); }+}++test('positive (synthetic): a canonically equivalent realpath spelling keeps the Git path key and the file digest', () => {+ fixture((root, nfc, nfd) => {+ // APFS resolves both spellings to one entry; ext4 needs a same-inode alias for the NFD name to exist at all.+ if (!fs.existsSync(nfd)) fs.linkSync(nfc, nfd);+ const baseline = worktreeManifest(root, { withFiles: true });+ expect(Object.keys(baseline.files!)).toEqual([NFC]);+ withSpelling(nfc, nfd, () => {+ const manifest = worktreeManifest(root, { withFiles: true });+ expect(manifest.digest).toBe(baseline.digest);+ expect(manifest.file_count).toBe(1);+ expect(manifest.files).toEqual(baseline.files);+ });+ });+});++test('a case-spelling mismatch between the index and the disk is not a symlink (case-insensitive volumes only)', () => {+ const home = fs.mkdtempSync(join(tmpdir(), 'gbrain-manifest-case-'));+ try {+ fs.writeFileSync(join(home, 'Probe.txt'), 'x');+ if (!fs.existsSync(join(home, 'probe.txt'))) return; // normalization- and case-sensitive host: nothing to prove here+ const root = fs.realpathSync(home);+ git(root, 'init', '-q');+ fs.mkdirSync(join(root, 'notes'));+ fs.writeFileSync(join(root, 'notes', 'a.md'), 'Synthetic note.\n');+ // The index spells the path with another case than the disk does.+ git(root, 'update-index', '--add', '--cacheinfo', '100644', git(root, 'hash-object', join(root, 'notes', 'a.md')), 'Notes/A.md');+ const manifest = worktreeManifest(root, { withFiles: true });+ expect(Object.keys(manifest.files!)).toEqual(['Notes/A.md']);+ expect(manifest.file_count).toBe(1);+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+});++test('a leaf symlink is still refused, whatever spelling realpath answers', () => {+ fixture((root, nfc, nfd) => {+ fs.rmSync(nfc);+ const target = join(root, 'target.md');+ fs.writeFileSync(target, 'Synthetic linked target.\n');+ fs.symlinkSync(target, nfc);+ expect(() => worktreeManifest(root)).toThrow(unsafe);+ withSpelling(nfc, nfd, () => expect(() => worktreeManifest(root)).toThrow(unsafe));+ });+});++test('a symlink parent directory is still refused, whatever spelling realpath answers', () => {+ fixture((root, nfc) => {+ const parent = join(root, 'caf\u00e9');+ const target = join(root, 'target'); fs.mkdirSync(target);+ fs.writeFileSync(join(target, 'note.md'), 'Synthetic parent-link target.\n');+ fs.symlinkSync(target, parent, process.platform === 'win32' ? 'junction' : 'dir');+ // A regular index entry under the parent, not a symlink Git mode: only the component check can see the link.+ git(root, 'update-index', '--add', '--cacheinfo', '100644', git(root, 'hash-object', nfc), 'caf\u00e9/note.md');+ const path = join(parent, 'note.md');+ expect(() => worktreeManifest(root)).toThrow(unsafe);+ withSpelling(path, path.normalize('NFD'), () => expect(() => worktreeManifest(root)).toThrow(unsafe));+ });+});++test('a parent directory swapped to a symlink after the first file of the manifest was read is refused (no manifest-long cache)', () => {+ const home = fs.mkdtempSync(join(tmpdir(), 'gbrain-manifest-swap-'));+ try {+ const root = fs.realpathSync(home);+ const outside = fs.mkdtempSync(join(tmpdir(), 'gbrain-manifest-swap-outside-'));+ try {+ git(root, 'init', '-q');+ fs.mkdirSync(join(root, 'd'));+ fs.writeFileSync(join(root, 'd', 'a.md'), 'first\n');+ fs.writeFileSync(join(root, 'd', 'b.md'), 'second\n');+ git(root, 'add', 'd/a.md', 'd/b.md');+ // Outside the root: a directory holding a same-named b.md with other bytes.+ fs.writeFileSync(join(outside, 'b.md'), 'OUTSIDE THE ROOT\n');+ // Between the two reads (paths are hashed in sorted order), replace d/ by a symlink to the outside directory.+ const original = fs.readFileSync;+ let swapped = false;+ const probe = spyOn(fs, 'readFileSync').mockImplementation(((p: fs.PathLike | number, opts?: unknown) => {+ const bytes = original(p as never, opts as never);+ if (String(p) === join(root, 'd', 'a.md') && !swapped) {+ swapped = true;+ fs.renameSync(join(root, 'd'), join(outside, 'd-moved'));+ fs.symlinkSync(outside, join(root, 'd'), process.platform === 'win32' ? 'junction' : 'dir');+ }+ return bytes;+ }) as typeof fs.readFileSync);+ try { expect(() => worktreeManifest(root, { scope: 'git' })).toThrow(unsafe); } finally { probe.mockRestore(); }+ expect(swapped).toBe(true);+ } finally { fs.rmSync(outside, { recursive: true, force: true }); }+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+});++test('a tracked symlink (mode 120000) and a submodule (160000) refuse from the index before any read', () => {+ fixture((root) => {+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'synthetic');+ const head = git(root, 'rev-parse', 'HEAD');+ git(root, 'update-index', '--add', '--cacheinfo', '160000', head, 'caf\u00e9');+ expect(() => worktreeManifest(root)).toThrow(unsafe);+ git(root, 'update-index', '--force-remove', 'caf\u00e9');+ const linkBlob = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: 'target.md' }).toString().trim();+ git(root, 'update-index', '--add', '--cacheinfo', '120000', linkBlob, 'link.md');+ expect(() => worktreeManifest(root)).toThrow(unsafe);+ });+});++test('a tracked file missing on disk counts as deleted, a directory in a file slot too', () => {+ fixture((root, nfc) => {+ fs.rmSync(nfc);+ expect(worktreeManifest(root, { withFiles: true })).toMatchObject({ file_count: 0, files: {} });+ fs.mkdirSync(nfc);+ expect(worktreeManifest(root, { withFiles: true })).toMatchObject({ file_count: 0, files: {} });+ });+});