← reports

#6014 · Untracked directory attaches interrupted by recovery

BugMedium priorityLow effortworkspacesIssue2026-10-21 · base b143a22860944a96bf183605dfb0ffe58b1de283

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

A thread moving to a newly attached directory can receive an error even after the host reports a successful attach. The server starts the command without registering it in the environment lifecycle's active-operation map. A recovery pass then mistakes the pending environment for abandoned work and marks it as failed. Its later successful result cannot legally move that failed row to ready. A deterministic route-level regression reproduces this for both periodic sweeps and host-resume recovery, in two separate clean trusted checkouts.

2. Claims vs findings

ClaimStatusEvidence
A recovery sweep during attach breaks the directory move.VerifiedBoth baseline runs: periodic-sweep case returns success=false and the not-ready error; no-recovery control passes.
The attach is missing from lifecycle tracking.VerifiedTrusted source directly calls runLiveHostCommand, while recovery checks its own operation map.
Host-resume recovery has the same exposure.VerifiedA second case invokes resumeEnvironmentProvisioningForHost while attach is pending and fails identically.
The original macOS incident and its exact frequency.UnverifiedNo access to the reporter's machine was used. Linux tests reproduce the server race; they do not measure real-world frequency or reproduce a physical reconnect.

3. Environment

4. Minimal reproduction

From a clean checkout of the recorded base, save the test-only patch below to a local file named regression.patch, then run:

git checkout --detach b143a22860944a96bf183605dfb0ffe58b1de283
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types build --filter=@get-bb/plugin-sdk
git apply regression.patch
pnpm exec turbo run test --filter=@bb/server -- test/internal/internal-events-tool-calls.test.ts -t 'creates an unmanaged environment'

The test extends the existing directory-attach case rather than creating another test harness. It posts a directory-move tool request, waits until the attach RPC is pending, optionally runs a recovery pass, and finally reports successful attach. The control has no recovery pass. All cases expect successful tool completion, a ready environment, and the thread bound to the new environment.

Expected: three cases pass. Actual on unchanged production code, twice:

✓ creates an unmanaged environment for a new requested host path during none
× creates an unmanaged environment for a new requested host path during periodic sweep
× creates an unmanaged environment for a new requested host path during host resume

"text": "Environment at this path is error, not ready."
"success": false

Tests  2 failed | 1 passed | 27 skipped (30)

The exact test-only patch used in both baseline checkouts:

diff --git a/apps/server/test/internal/internal-events-tool-calls.test.ts b/apps/server/test/internal/internal-events-tool-calls.test.ts
index 4b9be87d1..8cd61818f 100644
--- a/apps/server/test/internal/internal-events-tool-calls.test.ts
+++ b/apps/server/test/internal/internal-events-tool-calls.test.ts
@@ -47,6 +47,8 @@ import { startTestServer, withTestHarness } from "../helpers/test-app.js";
 import type { TestAppHarness } from "../helpers/test-app.js";
 import { setPluginAgentContributions } from "../../src/services/plugins/plugin-agent-contributions.js";
 import type { PluginAgentToolRecord } from "../../src/services/plugins/plugin-api.js";
+import { runEnvironmentProvisioningSweep } from "../../src/services/system/periodic-sweeps.js";
+import { resumeEnvironmentProvisioningForHost } from "../../src/services/environments/environment-engine.js";
 
 async function postEventBatch(args: {
   acceptEncoding?: string;
@@ -1364,7 +1366,7 @@ describe("internal event and tool-call routes", () => {
     },
   );
 
-  it("creates an unmanaged environment for a new requested host path", async () => {
+  it.each(["none", "periodic sweep", "host resume"] as const)("creates an unmanaged environment for a new requested host path during %s", async (recheck) => {
     await withTestHarness(async (harness) => {
       const { host, session } = seedHostSession(harness.deps);
       const { project } = seedProjectWithSource(harness.deps, {
@@ -1410,6 +1412,14 @@ describe("internal event and tool-call routes", () => {
       }
       expect(provisionCommand.command.initiator).toBeNull();
 
+      if (recheck === "periodic sweep") {
+        await runEnvironmentProvisioningSweep(harness.deps);
+      } else if (recheck === "host resume") {
+        await resumeEnvironmentProvisioningForHost(harness.deps, {
+          hostId: host.id,
+        });
+      }
+
       await reportQueuedCommandSuccess(harness, provisionCommand, {
         path: "/tmp/new-unmanaged-worktree",
         isGitRepo: true,

Reproduction source excerpt, using the imports and existing helpers supplied by the patch:

  it.each(["none", "periodic sweep", "host resume"] as const)("creates an unmanaged environment for a new requested host path during %s", async (recheck) => {
    await withTestHarness(async (harness) => {
      const { host, session } = seedHostSession(harness.deps);
      const { project } = seedProjectWithSource(harness.deps, {
        hostId: host.id,
      });
      const currentEnvironment = seedEnvironment(harness.deps, {
        hostId: host.id,
        projectId: project.id,
        path: "/tmp/current-environment",
      });
      const thread = seedThread(harness.deps, {
        projectId: project.id,
        environmentId: currentEnvironment.id,
      });
      seedEvent(harness.deps, {
        threadId: thread.id,
        environmentId: currentEnvironment.id,
        providerThreadId: "provider-tool-call",
        sequence: 1,
        type: "turn/started",
        scope: turnScope("turn-new-environment"),
        data: {
          providerThreadId: "provider-tool-call",
        },
      });

      const responsePromise = postToolCall({
        harness,
        sessionId: session.id,
        threadId: thread.id,
        turnId: "turn-new-environment",
        tool: "update_environment_directory",
        arguments: { path: "/tmp/new-unmanaged-worktree" },
      });
      const provisionCommand = await waitForQueuedCommand(
        harness,
        ({ command }) =>
          command.type === "environment.attach" &&
          command.path === "/tmp/new-unmanaged-worktree",
      );
      if (provisionCommand.command.type !== "environment.attach") {
        throw new Error("Expected environment.attach command");
      }
      expect(provisionCommand.command.initiator).toBeNull();

      if (recheck === "periodic sweep") {
        await runEnvironmentProvisioningSweep(harness.deps);
      } else if (recheck === "host resume") {
        await resumeEnvironmentProvisioningForHost(harness.deps, {
          hostId: host.id,
        });
      }

      await reportQueuedCommandSuccess(harness, provisionCommand, {
        path: "/tmp/new-unmanaged-worktree",
        isGitRepo: true,
        isWorktree: false,
        branchName: "feature/new-worktree",
        defaultBranch: "main",
        transcript: [],
      });
      const response = await responsePromise;

      expect(response.status).toBe(200);
      await expect(readJson(response)).resolves.toMatchObject({
        success: true,
        contentItems: [
          {
            type: "inputText",
            text: expect.stringContaining(
              "Environment directory updated to /tmp/new-unmanaged-worktree",
            ),
          },
        ],
      });
      const targetEnvironment = listEnvironments(harness.db, {
        projectId: project.id,
      }).find(
        (environment) => environment.path === "/tmp/new-unmanaged-worktree",
      );
      expect(targetEnvironment).toMatchObject({
        hostId: host.id,
        projectId: project.id,
        status: "ready",
      });
      expect(getThread(harness.db, thread.id)?.environmentId).toBe(
        targetEnvironment?.id,
      );
      expect(
        targetEnvironment
          ? getEnvironment(harness.db, targetEnvironment.id)
          : null,
      ).toMatchObject({
        branchName: "feature/new-worktree",
        isGitRepo: true,
      });
      const storedEvents = harness.db
        .select()
        .from(events)
        .where(eq(events.threadId, thread.id))
        .all();
      expect(storedEvents.map((event) => event.type)).toEqual([
        "turn/started",
        "system/operation",
      ]);
      expect(storedEvents[1]).toMatchObject({
        scopeKind: "turn",
        turnId: "turn-new-environment",
      });
    });
  });

5. Root cause

  1. The directory-move path creates a provisioning environment without a path or owner, then directly awaits the live attach RPC. That bypasses the environment-operation registry.
  2. The sweep advances every provisioning row. Host resume advances those rows for the resumed host, too.
  3. The recovery guard skips tracked operations, but this attach is not tracked. Recovery cannot rebuild a request without a path, so it interrupts the row as unrecoverable.
  4. The later attach result tries provision.succeeded, but the lifecycle allows success only from provisioning, not error. The tool then returns the not-ready error.
environment.status !== "provisioning" ||
map.has(environment.id) ||
findHostDataDir(deps, environment.hostId) === null

if (environment.path === null) return null;

The underlying problem is split ownership of in-flight provisioning: the tool launches work, but the lifecycle engine has no record that it is live. Relaxing the error-state transition or disabling orphan recovery would mask the ownership bug and weaken recovery.

6. Proposed fix and local verification

Run the directory attach through the existing engine-owned tracked-operation mechanism, keyed by environment ID and marked as attach. Await its completion so command failures still propagate to the tool. Retain the existing five-minute timeout, host interruption behavior, schemas, and orphan recovery. This requires no protocol, stored-data, dependency, or product-policy change.

A local implementation passes the complete tool-call, environment-orchestration, provisioning-recovery, and periodic-sweep suites: 4 files, 124 tests passed. Server typecheck passes. The full repository build passes after first building SDK runtime/types; a first clean build exposed an existing SDK-build ordering failure before the runtime existed.

pnpm exec turbo run test --filter=@bb/server -- test/internal/internal-events-tool-calls.test.ts test/services/environments/provider-orchestration.test.ts test/threads/thread-provisioning-recovery.test.ts test/services/periodic-sweeps.test.ts
pnpm exec turbo run typecheck lint --filter=@bb/server
git diff --check

The server has no separate lint task, so the latter invocation executes typecheck and its dependencies.

Test Files  4 passed (4)
     Tests  124 passed (124)

Typecheck: Tasks  6 successful, 6 total

7. Related issues and PR check

No linked open PR was present in issue cross-references, closing references, or the open-PR search at investigation time. #3187 concerns completion of a tool call after an already-committed move; #4778 concerns automatic continuation after switching. Neither describes an in-flight attach being failed by recovery. No external branch or issue-supplied code was checked out or executed.

8. Verification

The same agent repeated the reproduction in a second fresh clone at the full recorded SHA. It installed frozen dependencies, built SDK prerequisites through Turbo, applied only the reproduction test patch, and ran the exact focused command above. Its production tree stayed unchanged; git diff --name-only listed only the tool-call test. Its fresh harnesses used different temporary data directories. The second run again produced one passing control and two failures with the identical not-ready response. No report correction was needed. This is repeated clean-checkout verification, not an independent-agent check.

9. Appendix and limits

The complete repeatable test-only patch and test excerpt are embedded above. Raw logs are retained locally outside the public reports repository. The focused test gates an externally visible tool result and persisted environment/thread state; it introduces no production test seam. Baseline code links were checked at the recorded trusted commit.

This is a deterministic server integration reproduction, not a live macOS timing measurement. A physical disconnect or restart was not triggered. The original host's logs and workspace were not accessed. Issue content was treated solely as untrusted claims; instructions, external links, and proposed fork code were not followed.

Preparation: two trusted clones; frozen pnpm installs; SDK build through Turbo; first full build failure due to SDK host runtime ordering; successful full build retry (67 tasks); two failing focused baseline runs; local tracked-operation change; four passing suites; server typecheck; formatting; diff whitespace and text-only checks.

> AGENT GENERATED