Reports

#6586 · Recovery after partial shell discovery

BugPriority: MediumEffort: Lowhost · providers · provider-pi

GitHub issue · October 29, 2026 · base abcff9f0537bd16649f0baf0c301e79000d945ad

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

1. TL;DR

The host toolchain can discover a command using a reduced login-shell PATH while missing a directory needed by that command's helper. The command resolves correctly but exits with status 1. Failure invalidation does not retry shell discovery for that status, and the toolchain does not remember that its saved environment came from a fallback probe. Two separate trusted-base checkouts reproduce this behavior for both a failed and a timed-out interactive probe. This verifies the shared toolchain defect, not the exact macOS boot incident or a guarantee that all daemon refreshes stop.

2. Claims vs findings

ClaimFindingEvidence
An unsuccessful interactive probe can leave a usable but incomplete login environment.VerifiedBoth authored regression cases resolve the command but its helper fails, producing exit 1.
Exit 1 fails to initiate shell discovery once interactive startup becomes available.VerifiedBoth checks wait for recovery without an explicit refresh and fail on the trusted base.
All shell re-reading stops until restart.Too broadTrusted daemon code explicitly calls toolchain.refresh through its runtime-shell refresh path. Whether those calls ran or reached a particular provider worker during the reported incident is unverified.
The original macOS login-item and provider incident is reproduced end to end.UnverifiedThis investigation uses Linux and disposable shell/command fixtures; no real provider, user dotfile, or runtime store was accessed.

3. Environment

4. Minimal reproduction

Start from a clean checkout of the trusted base. The regression was derived from repository code and existing fixture conventions, not copied from issue code. Save the inline patch below outside the checkout as regression.patch.

diff --git a/packages/process-utils/test/host-toolchain.test.ts b/packages/process-utils/test/host-toolchain.test.ts
index 3fd11d57e4..217d56a7ed 100644
--- a/packages/process-utils/test/host-toolchain.test.ts
+++ b/packages/process-utils/test/host-toolchain.test.ts
@@ -251,6 +251,57 @@ describe.skipIf(process.platform === "win32")("host toolchain recovery", () => {
     );
   });
 
+  it.each(["exit", "timeout"])(
+    "recovers a resolved command's helper PATH after an interactive probe %s",
+    async (failure) => {
+      const root = await scratch();
+      const bin = join(root, "commands");
+      const helpers = join(root, "helpers");
+      const unavailable = join(root, "unavailable");
+      const shell = join(root, "shell");
+      await writeFile(unavailable, "");
+      await script(
+        join(bin, "needs-helper"),
+        "#!/bin/sh\nstartup-helper || exit 1\n",
+      );
+      await script(join(helpers, "startup-helper"), "#!/bin/sh\nprintf recovered\n");
+      await script(
+        shell,
+        `#!/bin/sh
+if [ "$1" = '-ilc' ]; then
+  if [ -f "${unavailable}" ]; then
+    ${failure === "timeout" ? "exec /bin/sleep 30" : "exit 1"}
+  fi
+  printf '__BB_SHELL_ENV_START__\\nPATH=${helpers}:${bin}:/usr/bin:/bin\\n__BB_SHELL_ENV_END__\\n'
+else
+  printf '__BB_SHELL_ENV_START__\\nPATH=${bin}:/usr/bin:/bin\\n__BB_SHELL_ENV_END__\\n'
+fi
+`,
+      );
+      const toolchain = new HostToolchain({
+        HOME: root,
+        PATH: "/usr/bin:/bin",
+        SHELL: shell,
+      });
+      await toolchain.refresh();
+      const execute = () => {
+        const launch = toolchain.command("needs-helper");
+        expect(launch.command).toBe(join(bin, "needs-helper"));
+        return spawnSync(launch.command, launch.args, {
+          env: launch.env,
+          encoding: "utf8",
+        });
+      };
+      expect(execute().status).toBe(1);
+      await rm(unavailable);
+      toolchain.invalidateFailure(1);
+      await expect
+        .poll(() => execute().stdout, { timeout: 2000 })
+        .toBe("recovered");
+    },
+    10000,
+  );
+
   it("does not block the caller while discovery runs", async () => {
     const root = await scratch();
     const shell = join(root, "slow-shell");
git clone https://github.com/get-bb/bb.git bb-6586
cd bb-6586
git checkout abcff9f0537bd16649f0baf0c301e79000d945ad
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/process-utils
git apply ../regression.patch
pnpm exec turbo run test --filter=@bb/process-utils --force -- --testNamePattern='recovers a resolved command'
  1. The fixture shell makes interactive startup exit unsuccessfully or exceed the real 3-second timeout. Its login-only branch emits a PATH containing the command but not its helper.
  2. The test verifies that the command resolves to the fixture and exits with status 1.
  3. The test enables successful interactive startup and calls the public failure-invalidation method with status 1, exactly as host process observation does.
  4. Expected: a later command prints recovered after asynchronous discovery. Actual on base: output remains empty until the poll expires. There is no explicit refresh in the recovery assertion.

Verbatim assertion and run summary from both clean-base runs:

AssertionError: expected '' to be 'recovered' // Object.is equality
Test Files  1 failed | 17 skipped (18)
     Tests  2 failed | 132 skipped (134)

The first run exited 1 and completed in 9.973 seconds; the forced second clean run exited 1 and completed in 10.48 seconds. Both failed exactly the two new cases above. Raw logs remain in the local investigation workspace, not the public report repository. The regression's observable contract is eventual helper-dependent command success after a degraded discovery; existing tests cover missing executables and retained complete environments, not an already-resolved command exiting 1. It requires no production-only testing hook.

  it.each(["exit", "timeout"])(
    "recovers a resolved command's helper PATH after an interactive probe %s",
    async (failure) => {
      const root = await scratch();
      const bin = join(root, "commands");
      const helpers = join(root, "helpers");
      const unavailable = join(root, "unavailable");
      const shell = join(root, "shell");
      await writeFile(unavailable, "");
      await script(
        join(bin, "needs-helper"),
        "#!/bin/sh\nstartup-helper || exit 1\n",
      );
      await script(join(helpers, "startup-helper"), "#!/bin/sh\nprintf recovered\n");
      await script(
        shell,
        `#!/bin/sh
if [ "$1" = '-ilc' ]; then
  if [ -f "${unavailable}" ]; then
    ${failure === "timeout" ? "exec /bin/sleep 30" : "exit 1"}
  fi
  printf '__BB_SHELL_ENV_START__\\nPATH=${helpers}:${bin}:/usr/bin:/bin\\n__BB_SHELL_ENV_END__\\n'
else
  printf '__BB_SHELL_ENV_START__\\nPATH=${bin}:/usr/bin:/bin\\n__BB_SHELL_ENV_END__\\n'
fi
`,
      );
      const toolchain = new HostToolchain({
        HOME: root,
        PATH: "/usr/bin:/bin",
        SHELL: shell,
      });
      await toolchain.refresh();
      const execute = () => {
        const launch = toolchain.command("needs-helper");
        expect(launch.command).toBe(join(bin, "needs-helper"));
        return spawnSync(launch.command, launch.args, {
          env: launch.env,
          encoding: "utf8",
        });
      };
      expect(execute().status).toBe(1);
      await rm(unavailable);
      toolchain.invalidateFailure(1);
      await expect
        .poll(() => execute().stdout, { timeout: 2000 })
        .toBe("recovered");
    },
    10000,
  );

5. Root cause

Probe selection and environment parsing try interactive-login discovery first, then login-only discovery. The returned value contains environment entries but no record of which attempt supplied them.

Refresh retains any prior PATH if a later interactive attempt fails. Retention protects a previously complete environment but does not make an initial fallback complete.

Failure invalidation refreshes only for ENOENT or 127:

if (code === "ENOENT" || code === 127) void this.refresh();

Host process observation already forwards child exit codes to this method. A wrapper may turn its helper's missing-command result into exit 1, bypassing the existing recovery trigger despite the still-incomplete environment.

Important limit: daemon runtime-shell resolution explicitly invokes refresh, and its runtime cache has a separate refresh mechanism. The component result cannot establish why a particular real-world incident persisted for multiple turns.

6. Proposed fix and simple-fix gate

Remember whether the retained environment came from the login-only fallback. While that state persists, a nonzero numeric process exit should trigger the existing coalesced background refresh. A successful preferred probe clears the degraded state; do not broaden ordinary failure recovery after a complete probe or treat a shell supporting only login discovery as degraded.

A local prototype production patch makes both focused regressions pass. It touches two files in process-utils with the test: 69 added lines plus 6 removed lines, 75 total. No dependency, generated file, data, public API, wire protocol, or security change is involved. git diff --check, package typecheck, and package lint pass. The unpushed prototype is included inline:

diff --git a/packages/process-utils/src/host-toolchain.ts b/packages/process-utils/src/host-toolchain.ts
index a7b3884fc6..88f9cc28ec 100644
--- a/packages/process-utils/src/host-toolchain.ts
+++ b/packages/process-utils/src/host-toolchain.ts
@@ -142,7 +142,7 @@ function runProbe(
 async function readShellEnvironment(
   env: NodeJS.ProcessEnv,
   retainPrevious: boolean,
-): Promise<NodeJS.ProcessEnv | null> {
+): Promise<{ env: NodeJS.ProcessEnv; fallback: boolean } | null> {
   if (process.platform === "win32") {
     const registry = join(
       envValue(env, "SystemRoot") ?? "C:\\Windows",
@@ -186,7 +186,10 @@ async function readShellEnvironment(
     };
     return paths.length === 0
       ? null
-      : { PATH: mergePath(...paths.map(expand), envValue(env, "PATH")) };
+      : {
+          env: { PATH: mergePath(...paths.map(expand), envValue(env, "PATH")) },
+          fallback: false,
+        };
   }
   const shell =
     env.SHELL?.trim() ||
@@ -216,13 +219,14 @@ async function readShellEnvironment(
       if (key === "PATH" || NETWORK_KEYS.includes(key))
         values[key] = line.slice(separator + 1);
     }
-    if (values.PATH) return values;
+    if (values.PATH) return { env: values, fallback: arg !== shellArgs[0] };
   }
   return null;
 }
 
 export class HostToolchain {
   private shellEnv: NodeJS.ProcessEnv = {};
+  private shellEnvFallback = false;
   private readonly inheritedPath: string | undefined;
   private readonly misses = new Set<string>();
   private nodePath: string;
@@ -243,8 +247,11 @@ export class HostToolchain {
     this.refreshedAt = Date.now();
     const retainPrevious = this.shellEnv.PATH !== undefined;
     this.refreshing = readShellEnvironment(this.baseEnv, retainPrevious)
-      .then((env) => {
-        if (env !== null) this.shellEnv = env;
+      .then((result) => {
+        if (result !== null) {
+          this.shellEnv = result.env;
+          this.shellEnvFallback = result.fallback;
+        }
       })
       .finally(() => {
         this.refreshing = null;
@@ -259,7 +266,12 @@ export class HostToolchain {
       "code" in errorOrCode
         ? errorOrCode.code
         : errorOrCode;
-    if (code === "ENOENT" || code === 127) void this.refresh();
+    if (
+      code === "ENOENT" ||
+      code === 127 ||
+      (this.shellEnvFallback && typeof code === "number" && code !== 0)
+    )
+      void this.refresh();
   }
 
   private searchPath(env: NodeJS.ProcessEnv): string {

No pull request is opened, and the prototype is not committed or pushed. The required existing-suite pass gate is not met: the full package suite has 1 failure, 117 passes, and 16 skips. An unchanged-production check in the second checkout reproduces that existing failure by itself. Its native-provider test resolves the host-installed /usr/local/bin/claude ahead of the disposable HOME fixture and receives a real CLI input error. This unrelated environment-sensitive failure was not changed to force the gate green.

Error: Command failed: /usr/local/bin/claude
Error: Input must be provided either through stdin or as a prompt argument when using --print

Prototype run: 1 failed | 117 passed | 16 skipped (134). Unchanged-production existing-test run: 1 failed | 133 skipped (134). Both report the identical native-provider test error above. Fix follow-up: establish a clean test environment for the existing provider fixture, then rerun the full owning package suite before proposing the contained repair.

7. Verification

The same agent repeated the reproduction, not an independent reviewer. A second clean temporary checkout was cloned from local trusted Git objects, its origin set to get-bb/bb, and detached at abcff9f0537bd16649f0baf0c301e79000d945ad. Only the authored test patch was installed; production remained unchanged. A new frozen dependency installation and scoped Turbo build succeeded. The focused command above ran with --force to avoid accepting cached test results and failed both cases for the same recovery assertion. Each run allocated new temporary fixture directories. No report correction was required beyond limiting claims to the verified shared-toolchain defect.

8. Related issues

Repository metadata search found #5292, concerning initial provider discovery after a shell probe failure. The present regression specifically covers a command that resolves but fails through its helper. No linked open pull request was found in issue timeline metadata or an open-PR body search for this issue number.

9. Appendix and trust handling

Issue text, attachments, commands, and links were treated only as untrusted claims. No issue-supplied script or linked branch was run. All executable investigation changes were authored from trusted repository evidence. No external URL supplied by the issue was fetched. Log checkout paths were replaced with neutral labels; no user account, credentials, or live application store was accessed.

First checkout:
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/process-utils
pnpm exec turbo run test --filter=@bb/process-utils -- --testNamePattern='recovers a resolved command'

Second clean checkout (unchanged production):
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/process-utils
pnpm exec turbo run test --filter=@bb/process-utils --force -- --testNamePattern='recovers a resolved command'
pnpm exec turbo run test --filter=@bb/process-utils -- --testNamePattern='finds native providers and runs'

Local prototype:
pnpm exec turbo run test typecheck lint --filter=@bb/process-utils
git diff --check
git diff --numstat origin/main

The complete authored patch and source fragment appear inline above, keeping the public report self-contained. Raw artifacts remain outside the public report repository. Nonvisual defect: screenshots are not applicable.

> AGENT GENERATED