← reports

#6559 · Git index-copy fallback rejects non-directory index paths

BugPriority: MediumEffort: Lowworkspaces GitHub issue2026-10-29 · base 3bacfac9ed69d42392076e5b3da2815bec822cd8

Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro.

1. TL;DR

The Git plugin fails an otherwise valid workspace status read when Git reports an index path beneath a regular file. The optional index-copy optimization checks that path using a real filesystem stat, but handles only missing entries, not a non-directory ancestor. The resulting ENOTDIR escapes before Git can produce its diff. A focused regression reaches the production WorkspaceReads status method with a real repository and real filesystem, reproduces the error in two clean trusted checkouts, and succeeds after a narrow fallback change. This verifies the shared host-layer failure, not the third-party machine integration or its downstream cleanup UI.

2. Claims vs findings

Reported claimFindingEvidence
A resolved index under a marker file aborts workspace status.VerifiedBoth runs reject with ENOTDIR in WorkspaceReads.acquireIndexCopy.
The index-copy fallback handles only an absent index.VerifiedTrusted source catches ENOENT only, and rethrows ENOTDIR.
Skipping the optional copy permits ordinary Git status and diffs.VerifiedAfter the fix, the test observes README.md with one insertion and deletion and a modified-file diff entry.
The third-party machine provider returns this layout in production.Unverified hereNo third-party provider runtime or customer machine was accessed. Only the returned index-path condition is emulated.
Delegate cleanup and all UI consumers fail for that provider.Unverified end to endHost entry calls the verified failing reader, but no customer data, live instance, or cleanup command was used.
Ordinary Git worktrees are unaffected.Mechanism consistentReal Git resolves gitdir indirection itself; the fixture delegates every command except the index-path lookup to real Git. This report does not claim a separate worktree-system test.

3. Environment

4. Minimal reproduction

  1. Clone the public repository and check out the exact trusted base.
  2. Install and build the trusted source, then apply the report's test-only artifact. This patch was written from repository evidence, not copied from issue code.
  3. Run the targeted test. It moves Git metadata outside the worktree, writes a valid gitdir marker, and intercepts only the index-location query to return a path beneath that marker. All other Git commands use the actual Git executable.
git clone https://github.com/get-bb/bb.git bb-issue-6559
cd bb-issue-6559
git checkout 3bacfac9ed69d42392076e5b3da2815bec822cd8
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
curl -fsS https://get-bb.github.io/reports/issues/6559.html | python3 -c 'import html,re,sys; print(html.unescape(re.search(r"<pre id=\"regression-patch\">(.*?)</pre>", sys.stdin.read(), re.S)[1]),end="")' > /tmp/issue-6559-regression.patch
git apply /tmp/issue-6559-regression.patch
pnpm exec turbo run test --filter=bb-plugin-bb--git -- host/index-copy.test.ts -t 'resolved index is below a marker file'

Expected: getStatus returns a modified README.md with one insertion and one deletion; diffFiles returns M README.md.

Actual on unchanged production: the real filesystem rejects the stat and status fails before those assertions.

bb-plugin-bb--git:test:  FAIL  |bb-plugin-bb--git:isolated| host/index-copy.test.ts > WorkspaceReads index copy > reads status and diffs when the resolved index is below a marker file
bb-plugin-bb--git:test: Error: ENOTDIR: not a directory, stat '/tmp/bb-vt-TEMP/bb-index-copy-marker-TEMP/.git/index'
bb-plugin-bb--git:test:  ❯ WorkspaceReads.acquireIndexCopy host/workspace-reads.ts:947:19
bb-plugin-bb--git:test:     945|   private async acquireIndexCopy(): Promise<IndexCopy | null> {
bb-plugin-bb--git:test:     946|     const realPath = await this.realIndexPath();
bb-plugin-bb--git:test:     947|     const stats = await fs.stat(realPath).catch((error: unknown) => {
bb-plugin-bb--git:test:        |                   ^
bb-plugin-bb--git:test:     948|       if (error instanceof Error && "code" in error && error.code === …
bb-plugin-bb--git:test:     949|         return null;
bb-plugin-bb--git:test:  ❯ WorkspaceReads.withIndexEnv host/workspace-reads.ts:925:18
bb-plugin-bb--git:test:  ❯ host/workspace-reads.ts:547:24
bb-plugin-bb--git:test: 
bb-plugin-bb--git:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
bb-plugin-bb--git:test: 
bb-plugin-bb--git:test:

The test-only patch and complete test are inline. Raw evidence and separate reproduction files remain in the local investigation backup, not the public reports repository.

Test-only regression patch
diff --git a/plugins/git/host/index-copy.test.ts b/plugins/git/host/index-copy.test.ts
index cd92c3306c..0282af6f43 100644
--- a/plugins/git/host/index-copy.test.ts
+++ b/plugins/git/host/index-copy.test.ts
@@ -43,6 +43,37 @@ afterEach(() => {
 });
 
 describe.skipIf(process.platform === "win32")("WorkspaceReads index copy", () => {
+  it("reads status and diffs when the resolved index is below a marker file", async () => {
+    const repo = await initRepo(await makeTempDir("bb-index-copy-marker-"));
+    const storage = await makeTempDir("bb-index-copy-storage-");
+    const gitDir = path.join(storage, "git-dir");
+    await fs.rename(path.join(repo, ".git"), gitDir);
+    await fs.writeFile(path.join(repo, ".git"), `gitdir: ${gitDir}\n`);
+    await fs.writeFile(path.join(repo, "README.md"), "edited\n");
+    const realGit = execFileSync("which", ["git"], { encoding: "utf8" }).trim();
+    const shimDir = await makeTempDir("bb-git-marker-index-");
+    await fs.writeFile(
+      path.join(shimDir, "git"),
+      `#!/bin/sh\ncase " $* " in *" rev-parse --git-path index "*) printf '.git/index\\n'; exit 0;; esac\nexec "${realGit}" "$@"\n`,
+      { mode: 0o755 },
+    );
+    vi.stubEnv("PATH", `${shimDir}${path.delimiter}${process.env.PATH ?? ""}`);
+    const reads = new WorkspaceReads(repo, tmpdir());
+
+    try {
+      expect(
+        await reads.getStatus({ freshness: fresh(), ...STATUS_BUDGET }),
+      ).toMatchObject({
+        workingTree: {
+          files: [{ path: "README.md", insertions: 1, deletions: 1 }],
+        },
+      });
+      expect(await changedFiles(reads)).toEqual(["M README.md"]);
+    } finally {
+      await reads.dispose();
+    }
+  });
+
   it("sees a same-size rewrite made in the second of git add", async () => {
     const repo = await initRepo(await makeTempDir("bb-index-copy-racy-"));
     await fs.writeFile(path.join(repo, "f.txt"), "cccc\n");
Complete regression test file
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { initRepo, makeTempDir } from "@bb/test-helpers";
import { runGit } from "bb-environment-provider-host/workspace-git";
import { WorkspaceReads } from "./workspace-reads.js";

let freshReads = 0;
function fresh() {
  freshReads += 1;
  return { work: `copy-work-${freshReads}`, refs: `copy-refs-${freshReads}` };
}

const UNCOMMITTED = { type: "uncommitted" } as const;
const STATUS_BUDGET = {
  maxUntrackedLineStatFiles: 50,
  maxUntrackedLineStatBytes: 1024 * 1024,
};

function changedFiles(reads: WorkspaceReads) {
  return reads
    .diffFiles({
      freshness: fresh(),
      target: UNCOMMITTED,
      maxFiles: 50,
      ignoreWhitespace: false,
    })
    .then((result) =>
      result.files.map((file) => `${file.statusLetter} ${file.path}`),
    );
}

async function startOfSecond(): Promise<void> {
  const remainder = 1_000 - (Date.now() % 1_000);
  await new Promise((resolve) => setTimeout(resolve, remainder + 20));
}

afterEach(() => {
  vi.restoreAllMocks();
  vi.unstubAllEnvs();
});

describe.skipIf(process.platform === "win32")("WorkspaceReads index copy", () => {
  it("reads status and diffs when the resolved index is below a marker file", async () => {
    const repo = await initRepo(await makeTempDir("bb-index-copy-marker-"));
    const storage = await makeTempDir("bb-index-copy-storage-");
    const gitDir = path.join(storage, "git-dir");
    await fs.rename(path.join(repo, ".git"), gitDir);
    await fs.writeFile(path.join(repo, ".git"), `gitdir: ${gitDir}\n`);
    await fs.writeFile(path.join(repo, "README.md"), "edited\n");
    const realGit = execFileSync("which", ["git"], { encoding: "utf8" }).trim();
    const shimDir = await makeTempDir("bb-git-marker-index-");
    await fs.writeFile(
      path.join(shimDir, "git"),
      `#!/bin/sh\ncase " $* " in *" rev-parse --git-path index "*) printf '.git/index\\n'; exit 0;; esac\nexec "${realGit}" "$@"\n`,
      { mode: 0o755 },
    );
    vi.stubEnv("PATH", `${shimDir}${path.delimiter}${process.env.PATH ?? ""}`);
    const reads = new WorkspaceReads(repo, tmpdir());

    try {
      expect(
        await reads.getStatus({ freshness: fresh(), ...STATUS_BUDGET }),
      ).toMatchObject({
        workingTree: {
          files: [{ path: "README.md", insertions: 1, deletions: 1 }],
        },
      });
      expect(await changedFiles(reads)).toEqual(["M README.md"]);
    } finally {
      await reads.dispose();
    }
  });

  it("sees a same-size rewrite made in the second of git add", async () => {
    const repo = await initRepo(await makeTempDir("bb-index-copy-racy-"));
    await fs.writeFile(path.join(repo, "f.txt"), "cccc\n");
    await runGit(["add", "f.txt"], { cwd: repo });
    await runGit(["commit", "-m", "f"], { cwd: repo });
    await new Promise((resolve) => setTimeout(resolve, 1_100));
    await startOfSecond();
    await fs.writeFile(path.join(repo, "f.txt"), "bbbb\n");
    await runGit(["add", "f.txt"], { cwd: repo });
    await fs.writeFile(path.join(repo, "f.txt"), "cccc\n");
    await new Promise((resolve) => setTimeout(resolve, 1_500));

    expect(await changedFiles(new WorkspaceReads(repo, tmpdir()))).toEqual([]);
  });

  it("keeps the index copy until reads using it finish when disposed mid-read", async () => {
    const repo = await initRepo(await makeTempDir("bb-index-copy-dispose-"));
    await fs.writeFile(path.join(repo, "README.md"), "edited\n");
    const realGit = execFileSync("which", ["git"], { encoding: "utf8" }).trim();
    const shimDir = await makeTempDir("bb-git-slow-diff-");
    const marker = path.join(shimDir, "diff-started");
    await fs.writeFile(
      path.join(shimDir, "git"),
      `#!/bin/sh\ncase " $* " in *" diff "*) touch "${marker}"; sleep 0.5;; esac\nexec "${realGit}" "$@"\n`,
      { mode: 0o755 },
    );
    vi.stubEnv("PATH", `${shimDir}${path.delimiter}${process.env.PATH ?? ""}`);
    const reads = new WorkspaceReads(repo, tmpdir());
    const pending = changedFiles(reads);
    await vi.waitFor(() => fs.access(marker), { timeout: 5_000, interval: 20 });
    await reads.dispose();

    expect(await pending).toEqual(["M README.md"]);
  });

  it("writes no shared index into the repository when core.splitIndex is on", async () => {
    const repo = await initRepo(await makeTempDir("bb-index-copy-split-"));
    await runGit(["config", "core.splitIndex", "true"], { cwd: repo });
    await runGit(["update-index", "--split-index"], { cwd: repo });
    await fs.writeFile(path.join(repo, "README.md"), "edited\n");
    await fs.writeFile(path.join(repo, "new.txt"), "new\n");
    const sharedIndexes = async () =>
      (await fs.readdir(path.join(repo, ".git"))).filter((name) =>
        name.startsWith("sharedindex."),
      );
    const before = await sharedIndexes();
    const reads = new WorkspaceReads(repo, tmpdir());

    await reads.getStatus({ freshness: fresh(), ...STATUS_BUDGET });
    expect((await changedFiles(reads)).sort()).toEqual([
      "A new.txt",
      "M README.md",
    ]);
    expect(await sharedIndexes()).toEqual(before);
  });

  it("re-reads an untracked file whose same-tick rewrite keeps its stat signature", async () => {
    const repo = await initRepo(await makeTempDir("bb-index-copy-tick-"));
    const file = path.join(repo, "notes.txt");
    await fs.writeFile(file, "one\n");
    const tick = Math.floor(Date.now() / 1_000) * 1_000;
    const realLstat = fs.lstat.bind(fs);
    vi.spyOn(fs, "lstat").mockImplementation(async (target, options) => {
      const stats = await realLstat(target, options);
      if (target !== file) return stats;
      return Object.assign(stats, { mtimeMs: tick, ctimeMs: tick, ino: 1 });
    });
    const reads = new WorkspaceReads(repo, tmpdir());
    const untracked = async () =>
      (
        await reads.getStatus({ freshness: fresh(), ...STATUS_BUDGET })
      ).workingTree.files.find((entry) => entry.path === "notes.txt");

    expect(await untracked()).toMatchObject({ insertions: 1 });
    await fs.writeFile(file, "a\nb\n");
    expect(await untracked()).toMatchObject({ insertions: 2 });
  });
});

5. Root cause

The host status handler calls WorkspaceReads.getStatus. Status enrichment runs Git diff through withIndexEnv and acquireIndexCopy. The index location is resolved by rev-parse; acquireIndexCopy stats it and returns null for ENOENT, which already means run the diff without a replacement GIT_INDEX_FILE. POSIX reports ENOTDIR, rather than ENOENT, when a non-final path component is a regular file. Because that code is not recognized, the optional optimization becomes a hard failure of the workspace read.

  private async acquireIndexCopy(): Promise<IndexCopy | null> {
    const realPath = await this.realIndexPath();
    const stats = await fs.stat(realPath).catch((error: unknown) => {
      if (error instanceof Error && "code" in error && error.code === "ENOENT") {
        return null;
      }
      throw error;
    });
    if (stats === null) return null;

This is not a general inability of Git to operate through a marker file: the fixture has valid backing metadata and real Git can read it. The incompatible assumption is that the advertised index must be traversable through the host filesystem.

6. Proposed fix

Handle ENOTDIR alongside ENOENT at the index stat boundary. Reuse the existing null fallback so Git reads its own index without a copied GIT_INDEX_FILE. Do not catch every filesystem error: permission failures and unexpected I/O failures should retain their existing error reporting. No public SDK, CLI, wire contract, packaging, data, or authentication changes are needed.

The implemented candidate changes two files in the existing Git subsystem: 36 additions plus one deletion, 37 total changed text lines. No binary, dependency, generated, migration, or lockfile changes.

7. Verification

The same agent repeated the reproduction, not an independent reviewer. A second clean checkout at 3bacfac9ed69d42392076e5b3da2815bec822cd8 received only the test patch; production source remained unchanged. Its frozen install and full build passed, and the same focused Turbo command failed with the same ENOTDIR and production stack, using a new temporary repository. No correction to the root-cause claim was needed.

bb-plugin-bb--git:test:  FAIL  |bb-plugin-bb--git:isolated| host/index-copy.test.ts > WorkspaceReads index copy > reads status and diffs when the resolved index is below a marker file
bb-plugin-bb--git:test: Error: ENOTDIR: not a directory, stat '/tmp/bb-vt-TEMP/bb-index-copy-marker-TEMP/.git/index'
bb-plugin-bb--git:test:  ❯ WorkspaceReads.acquireIndexCopy host/workspace-reads.ts:947:19
bb-plugin-bb--git:test:     945|   private async acquireIndexCopy(): Promise<IndexCopy | null> {
bb-plugin-bb--git:test:     946|     const realPath = await this.realIndexPath();
bb-plugin-bb--git:test:     947|     const stats = await fs.stat(realPath).catch((error: unknown) => {
bb-plugin-bb--git:test:        |                   ^
bb-plugin-bb--git:test:     948|       if (error instanceof Error && "code" in error && error.code === …
bb-plugin-bb--git:test:     949|         return null;
bb-plugin-bb--git:test:  ❯ WorkspaceReads.withIndexEnv host/workspace-reads.ts:925:18
bb-plugin-bb--git:test:  ❯ host/workspace-reads.ts:547:24
bb-plugin-bb--git:test: 
bb-plugin-bb--git:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
bb-plugin-bb--git:test: 
bb-plugin-bb--git:test:

Temporary filesystem identifiers in the error excerpts are redacted to TEMP. Error codes, production frames, assertions, and test totals are unchanged.

8. Related issues

A search for existing Git-index reports found #3905, a different workspace-subdirectory diff failure. It does not describe this index-stat error. No linked open PR or open PR mentioning #6559 existed when the investigation and fix started.

9. Appendix and limits

The report verifies the precise host failure and the focused repair. It does not assert that a live third-party machine was tested, that every downstream consumer was driven, or that the third-party implementation never uses GIT_INDEX_FILE for another purpose.

Untrusted-data handling: the issue's proposed repair and procedural steps were treated only as claims. No supplied code, external link, branch, or machine command was executed; the test and repair were derived from trusted main source.

Investigation commands included trusted-main fetches, read-only GitHub metadata and related-issue searches, git worktree creation at the recorded SHA, frozen installs, SDK type builds, full Turbo builds, the focused regression, relevant full checks, git diff --check, and the changed-line calculation. No workflow or subagent was started.