Reports

#6301 · Skill refresh terminates idle provider descendants

BugHigh priorityMedium efforthost · providers · provider-codex

GitHub issue · October 26, 2026 · trusted main 3540a699e29034b53da32bb7efa6f5b4055209eb

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

1. TL;DR

A provider can have no active turn while its subprocesses are still doing work. Changing an injected skill then asking the runtime manager for the same thread replaces the entire runtime, stopping those descendants. This test runs the real runtime manager, real agent runtime, production Codex bridge, and real operating-system processes; only the Codex app-server protocol backend is the repository's fake fixture. An unchanged-catalog control preserves the runtime and watcher, while the changed-catalog case destroys both. The central lifecycle failure reproduces twice; the reporter's macOS shell commands and historical timeline are not independently verified.

2. Claims vs findings

ClaimFindingEvidence
A changed skill catalog replaces an idle runtime at next thread preparation.VerifiedSame runtime with unchanged content; different runtime after editing the staged source, with all other setup unchanged.
Untracked provider descendants are lost.VerifiedA real descendant with a SIGHUP handler is alive before invalidation and no longer running afterward.
Busy work follows a different retention path.Verified in source and existing testsThe busy-target branch returns current roots without immediate shutdown. The existing 45 manager tests pass.
Codex supports a dynamic extra-roots method.Verified in sourceThe production bridge's skills/configure handler sends skills/extraRoots/set to sessions.
Specific plugin installs, all shell background commands, macOS behavior, exact restart notifications, and session-detachment workaround.UnverifiedNo real plugin install, real Codex service, macOS machine, or detached-session workaround was exercised. Descendants that move outside the shutdown group need not die.

3. Environment

4. Minimal reproduction

The focused regression is authored from trusted repository fixtures, not copied from the issue. It protects process survival at the runtime-manager boundary, which existing tests do not cover: those tests use a fake runtime and explicitly expect idle replacement. No production seam or dependency is added.

  1. Prepare the trusted source and build using the commands below.
  2. Save and apply the complete test patch below.
  3. Run the focused test. It starts a real production bridge with the trusted protocol fixture. An author-written wrapper starts a persistent descendant in the same process group.
  4. Observe the control preserve that process. Editing only the skill content causes the next ensureEnvironment call to shut down the original runtime.
git clone https://github.com/get-bb/bb.git bb-6301
cd bb-6301
git checkout --detach 3540a699e29034b53da32bb7efa6f5b4055209eb
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
# Save the complete patch below as /tmp/repro-6301.patch.
git apply /tmp/repro-6301.patch
pnpm exec turbo run test --filter=@bb/host-daemon -- src/runtime-manager.test.ts -t 'issue 6301'
# Existing tests, excluding the intentionally failing regression:
pnpm exec turbo run test --filter=@bb/host-daemon -- src/runtime-manager.test.ts -t '^(?!.*issue 6301)' 

Expected: the watcher remains alive across a skill refresh. Actual: the control passes, then the survival assertion fails with the following output. Exit status is 1, intentionally proving the bug.

issue-6301-evidence {"unchangedRuntimePreserved":true,"changedRuntimePreserved":false,"trackedActiveThreads":0,"trackedBackgroundWork":false,"watcherSurvived":false}
AssertionError: skill refresh must not terminate a live provider descendant: expected false to be true // Object.is equality
      Tests  1 failed | 45 skipped (46)
   Start at  06:17:34
   Duration  2.96s (transform 1.23s, setup 0ms, import 1.69s, tests 1.08s, environment 0ms)

Complete regression patch

All code needed beyond the pinned repository is inline. The test uses existing workspace fixtures but does not fake the runtime, provider bridge, or process termination. On Linux, zombies count as terminated rather than live work.

diff --git a/apps/host-daemon/src/runtime-manager.test.ts b/apps/host-daemon/src/runtime-manager.test.ts
index e4aafb2cb..f11730db1 100644
--- a/apps/host-daemon/src/runtime-manager.test.ts
+++ b/apps/host-daemon/src/runtime-manager.test.ts
@@ -3,6 +3,12 @@ import fs from "node:fs/promises";
 import os from "node:os";
 import path from "node:path";
 import { promisify } from "node:util";
+import { fileURLToPath } from "node:url";
+import { createAgentRuntime } from "@bb/agent-runtime";
+import {
+  createScriptedEchoLaunch,
+  fullRuntimeOptions,
+} from "../../../packages/agent-runtime/src/test/runtime-test-harness.js";
 import type { AgentRuntime, AgentRuntimeOptions } from "@bb/agent-runtime";
 import type { ThreadEvent } from "@bb/domain";
 import { threadScope, turnScope } from "@bb/domain";
@@ -709,6 +715,114 @@ describe("RuntimeManager", () => {
     expect(firstEntry.runtime.shutdown).toHaveBeenCalledTimes(1);
   });
 
+  it("issue 6301 preserves a provider descendant across an idle skill update", async () => {
+    const dataDir = await makeTempDir("bb-6301-");
+    const processLogPath = path.join(dataDir, "provider-processes.log");
+    const watcherPidPath = path.join(dataDir, "watcher.pid");
+    const scriptPath = path.join(dataDir, "app-server.json");
+    const wrapperPath = path.join(dataDir, "app-server-wrapper.mjs");
+    const fakeServerPath = fileURLToPath(new URL(
+      "../../../plugins/provider-codex/src/bridge/fake-codex-app-server.mjs",
+      import.meta.url,
+    ));
+    await fs.writeFile(scriptPath, JSON.stringify({ processLogPath }));
+    await fs.writeFile(wrapperPath, [
+      'import { spawn } from "node:child_process";',
+      'import { writeFileSync } from "node:fs";',
+      `const watcher = spawn(process.execPath, ["-e", ${JSON.stringify('process.on("SIGHUP", () => {}); setInterval(() => {}, 1000)')}], { stdio: "ignore" });`,
+      `writeFileSync(${JSON.stringify(watcherPidPath)}, String(watcher.pid));`,
+      `await import(${JSON.stringify(fakeServerPath)});`,
+    ].join("\n"));
+    const source = await writeInjectedSkillSource({
+      dataDir,
+      name: "runtime-probe",
+      token: "catalog-one",
+    });
+    const launch = createScriptedEchoLaunch({
+      pluginId: "provider-codex",
+      modulePath: fileURLToPath(new URL(
+        "../../../plugins/provider-codex/src/bridge/bridge.ts",
+        import.meta.url,
+      )),
+    });
+    const manager = new RuntimeManager({
+      dataDir,
+      provisionWorkspace: createProvisionWorkspaceMock(dataDir),
+      createRuntime: (options) => createAgentRuntime({
+        ...options,
+        env: {
+          ...options.env,
+          BB_CODEX_BRIDGE_APP_SERVER_COMMAND: process.execPath,
+          BB_CODEX_BRIDGE_APP_SERVER_ARGS: JSON.stringify([wrapperPath, scriptPath]),
+        },
+      }),
+    });
+    let watcherPid = 0;
+    const watcherIsRunning = async () => {
+      if (!isPidAlive(watcherPid)) return false;
+      if (process.platform !== "linux") return true;
+      const status = await fs.readFile(`/proc/${watcherPid}/stat`, "utf8").catch(() => "");
+      return status.length > 0 && !/^\d+ \(.*\) Z /u.test(status);
+    };
+    try {
+      const first = await manager.ensureEnvironment({
+        environmentId: "env-probe",
+        workspacePath: dataDir,
+        injectedSkillSources: [source],
+        targetThreadId: "thread-probe",
+      });
+      await first.runtime.startThread({
+        environmentId: "env-probe",
+        projectId: "project-probe",
+        threadId: "thread-probe",
+        providerId: "codex",
+        bridgeLaunch: launch,
+        options: fullRuntimeOptions,
+      });
+      watcherPid = Number(await fs.readFile(watcherPidPath, "utf8"));
+      await new Promise((resolve) => setTimeout(resolve, 100));
+      expect(await watcherIsRunning()).toBe(true);
+      expect(first.runtime.getLiveThreadIds()).toEqual([]);
+      expect(first.runtime.hasOpenBackgroundWork()).toBe(false);
+      const unchanged = await manager.ensureEnvironment({
+        environmentId: "env-probe",
+        workspacePath: dataDir,
+        injectedSkillSources: [source],
+        targetThreadId: "thread-probe",
+      });
+      expect(unchanged.runtime).toBe(first.runtime);
+      expect(await watcherIsRunning()).toBe(true);
+      await writeInjectedSkillSource({
+        dataDir,
+        name: "runtime-probe",
+        token: "catalog-two",
+      });
+      const changed = await manager.ensureEnvironment({
+        environmentId: "env-probe",
+        workspacePath: dataDir,
+        injectedSkillSources: [source],
+        targetThreadId: "thread-probe",
+      });
+      for (let attempt = 0; attempt < 100 && await watcherIsRunning(); attempt += 1) {
+        await new Promise((resolve) => setTimeout(resolve, 20));
+      }
+      const watcherSurvived = await watcherIsRunning();
+      console.log("issue-6301-evidence", JSON.stringify({
+        unchangedRuntimePreserved: unchanged.runtime === first.runtime,
+        changedRuntimePreserved: changed.runtime === first.runtime,
+        trackedActiveThreads: first.runtime.getLiveThreadIds().length,
+        trackedBackgroundWork: first.runtime.hasOpenBackgroundWork(),
+        watcherSurvived,
+      }));
+      expect(watcherSurvived, "skill refresh must not terminate a live provider descendant").toBe(true);
+    } finally {
+      await manager.shutdownAll();
+      if (await watcherIsRunning()) process.kill(watcherPid, "SIGKILL");
+      await fs.rm(dataDir, { recursive: true, force: true });
+      await fs.rm(launch.dataDir, { recursive: true, force: true });
+    }
+  });
+
   it("replaces an idle runtime that hosts the target thread and keeps the new staged catalog", async () => {
     const dataDir = await makeTempDir("bb-runtime-manager-skills-idle-host-");
     const source = await writeInjectedSkillSource({

5. Root cause

Idle skill-catalog invalidation shuts down the whole runtime; provider subprocess descendants are not counted as active work and are terminated by process-group cleanup.

The activity predicate counts terminals, active/pending turn IDs, and BB-tracked background work. It does not inspect running descendants.

apps/host-daemon/src/runtime-manager.ts:609

  private entryHasActiveRuntimeWork(entry: RuntimeEntry): boolean {
    return (
      entry.terminals.size > 0 ||
      entry.runtime.getLiveThreadIds().length > 0 ||
      entry.runtime.hasOpenBackgroundWork()
    );
  }

A catalog mismatch takes the retention branch only while work is active. Otherwise replacement removes the environment and awaits runtime shutdown.

apps/host-daemon/src/runtime-manager.ts:681

  private async replaceEntryForSkillCatalog(
    args: ReplaceEntryForSkillCatalogArgs,
  ): Promise<void> {
    if (
      this.entryHasActiveRuntimeWork(args.entry) ||
      this.hasInFlightThreadCommand(args.entry, args.targetThreadId)
    ) {
      throw new SkillCatalogConflictError({
        environmentId: args.entry.environmentId,
        activeCatalogHash: args.entry.skillCatalogHash,
        requestedCatalogHash: args.skillConfig.catalogHash,
      });
    }

    this.entries.delete(args.entry.environmentId);
    await args.entry.runtime.shutdown();
    await this.cleanupUnusedInjectedSkillStagingDirs([
      args.skillConfig.catalogHash,
    ]);
  }

  private async ensureCompatibleEntry(
    args: EnsureCompatibleEntryArgs,
  ): Promise<RuntimeEntry | null> {
    if (
      args.entry.shellEnvGeneration !== this.shellEnvGeneration &&
      !this.entryHasActiveRuntimeWork(args.entry) &&
      !this.hasInFlightThreadCommand(args.entry, args.targetThreadId)
    ) {
      this.entries.delete(args.entry.environmentId);
      await args.entry.runtime.shutdown();
      await this.cleanupUnusedInjectedSkillStagingDirs(
        args.skillConfig ? [args.skillConfig.catalogHash] : [],
      );
      return null;
    }

    if (
      args.skillConfig === null ||
      args.entry.skillCatalogHash === args.skillConfig.catalogHash ||
      (args.entry.skillCatalogHash === null &&
        args.skillConfig.skillRoots.length === 0)
    ) {
      return args.entry;
    }

    if (
      args.targetThreadId !== undefined &&
      (this.entryHasActiveRuntimeWork(args.entry) ||
        this.hasInFlightThreadCommand(args.entry, args.targetThreadId))
    ) {
      args.entry.retainedSkillCatalogHashes.add(args.skillConfig.catalogHash);
      return {
        ...args.entry,
        skillCatalogHash: args.skillConfig.catalogHash,
        skillRoots: args.skillConfig.skillRoots,
      };
    }

    await this.replaceEntryForSkillCatalog({
      entry: args.entry,
      skillConfig: args.skillConfig,
      ...(args.targetThreadId !== undefined
        ? { targetThreadId: args.targetThreadId }
        : {}),
    });
    return null;

The runtime's idle predicate excludes provider-hosted idle sessions. Runtime shutdown then delegates to provider process shutdown; termination is tree-aware rather than merely stopping the bridge leader.

packages/agent-runtime/src/runtime.ts:2585

    getLiveThreadIds() {
      return [
        ...new Set([
          ...turnState.getActiveThreadIds(),
          ...pendingTurnStarts.keys(),
        ]),
      ];
    },

    hasOpenBackgroundWork() {
      return backgroundWorkState.hasOpenWork();
    },

    async shutdown() {
      clearInterval(turnStartWatchdogTimer);
      await Promise.all(
        [...stagedThreadRewinds.keys()].map((leaseId) =>
          discardStagedThreadRewind(leaseId),
        ),
      );
      idleProviderSessionSinceMsByThreadId.clear();
      pendingTurnStarts.clear();
      threadOperationCounts.clear();
      threadGoalState.clear();
      turnState.clear();
      backgroundWorkState.clear();
      threadEventGrammar.clear();
      await providerProcesses.shutdown();
    },
  };

packages/agent-runtime/src/runtime-provider-process.ts:330

  async shutdown(): Promise<void> {
    this.shuttingDown = true;
    const shutdownPromises: Promise<void>[] = [];

    for (const [processKey, providerProcess] of this.processes) {
      shutdownPromises.push(this.terminateProviderProcess({ providerProcess }));
      for (const [, pending] of providerProcess.pending) {
        pending.reject(new Error("Runtime shutting down"));
      }
      providerProcess.pending.clear();

      for (const threadId of providerProcess.identity.threadIds) {
        this.args.onProviderThreadDetached(threadId);
      }
      this.processes.delete(processKey);
    }

packages/agent-runtime/src/runtime-provider-process.ts:543

  private async terminateProviderProcess(
    args: TerminateProviderProcessArgs,
  ): Promise<void> {
    const result = await args.providerProcess.stop({
      gracePeriodMs: args.timeoutMs ?? 5000,
    });
    if (result.treeTermination === "unverified") {
      this.args.onStderr?.(
        "Provider process exited, but descendant cleanup could not be confirmed",
      );
    }
  }

  private handleProviderProcessError(args: ProviderProcessErrorArgs): void {

packages/process-utils/src/process-group.ts:115

    const stopSurvivingMembers = (): void => {
      if (!isProcessGroupAlive(child)) {
        finish();
        return;
      }
      killProcessGroup({ child, signal: "SIGTERM" });
      poll = setInterval(() => {
        if (!isProcessGroupAlive(child)) {
          finish();
        }
      }, PROCESS_GROUP_EXIT_POLL_MS);
    };

    if (hasChildExited(child)) {
      stopSurvivingMembers();
      return;
    }
    child.once("exit", stopSurvivingMembers);
    child.kill("SIGTERM");
  });

The deeper issue is that catalog identity is also embedded in the agent runtime's provider process key. Merely bypassing the manager replacement does not establish that the existing thread receives new skills on its existing app-server.

packages/agent-runtime/src/runtime.ts:359

    args: ResolveProviderProcessKeyArgs,
  ): string {
    const roots = args.skillRoots ?? skillRoots;
    for (const root of roots) {
      if (!path.isAbsolute(root.path)) {
        throw new Error(
          `Agent runtime skill root "${root.id}" must use an absolute path: ${root.path}`,
        );
      }
    }
    const catalogKey =
      roots.length === 0
        ? ""
        : `#skills:${createHash("sha256").update(JSON.stringify(roots)).digest("hex")}`;
    return `${args.providerId}#bridge:${bridgeLaunchProcessKey(args.bridgeLaunch)}${catalogKey}`;
  }

6. Proposed fix and safety gate

Design a provider-capability-aware in-place skill update, preserving existing sessions and staged roots. Codex already accepts skills/configure, but runtime process identity currently includes the roots. Verify catalog removal, busy siblings, provider fallback, and process survival before changing replacement policy.

plugins/provider-codex/src/bridge/bridge.ts:2460

async function handleSkillsConfigure(
  id: string | number,
  params: z.infer<typeof skillsConfigureParamsSchema>,
): Promise<void> {
  configuredSkillExtraRoots = params.roots.map((root) => root.path);
  try {
    for (const session of sessionsByBbThreadId.values()) {
      if (
        session.closing ||
        session.connection === null ||
        session.connection.exited
      ) {
        continue;
      }
      await session.connection.request({
        method: "skills/extraRoots/set",
        params: { extraRoots: configuredSkillExtraRoots },
        resultSchema: ignoredChildResultSchema,
        timeoutMs: CHILD_REQUEST_TIMEOUT_MS,
      });
    }
    sendResult(id, { ok: true });
  } catch (error) {
    sendError(
      id,
      BRIDGE_JSON_RPC_ERRORS.BRIDGE_ERROR,

No pull request opened. A safe hot-refresh fix crosses the daemon's catalog-lifetime policy and the agent runtime's provider-process/session identity, rather than staying in one existing subsystem. Process-descendant accounting also needs a lifecycle policy for persistent children. This fails the automation's simple-fix gate; no production patch, branch, commit, or push was attempted. The local regression-only diff is 114 added text lines, no deletions or binary changes, and passes git diff --check.

7. Related issues and pull requests

No linked open pull request was found in issue cross-reference metadata or the open-PR search for 6301. Issue #5963 concerns skill-catalog hashing cost and #6240 concerns skill-tree limits; neither is evidence of this process-lifecycle failure.

8. Verification

The same agent repeated the test in a second clean detached checkout at the identical trusted commit. The second checkout started clean, performed a separate frozen install and complete build, then received only the same authored regression patch. It used new temporary directories and processes and no ports. Its result was the same intended failure, so no root-cause correction was necessary. This is a repeated clean run, not independent verification.

issue-6301-evidence {"unchangedRuntimePreserved":true,"changedRuntimePreserved":false,"trackedActiveThreads":0,"trackedBackgroundWork":false,"watcherSurvived":false}
AssertionError: skill refresh must not terminate a live provider descendant: expected false to be true // Object.is equality
      Tests  1 failed | 45 skipped (46)
   Start at  06:18:45
   Duration  3.02s (transform 1.24s, setup 0ms, import 1.71s, tests 1.12s, environment 0ms)

The existing manager suite was run separately, excluding only the new intentionally failing regression: 45 passed, 1 skipped. The full builds succeeded with 71 successful tasks in each worktree. The evidence does not claim a real-provider end-to-end run or a validated fix.

9. Appendix and trust boundary

Issue content was used only as claims to test; its suggested remedies and workaround were not executed. Only trusted main and the author-written test wrapper were run. No linked code, external issue URL, credential, real account data, or production instance was accessed.

GitHub metadata was read to classify and check cross-references. Source was fetched and inspected with git, rg, and numbered excerpts; relevant build and test commands are shown above. Full local logs and the regression patch are retained outside the report repository. In accordance with the report repository's policy, no raw logs, scripts, or artifact directories are committed; the reproducible patch and decisive expected-versus-actual output are inline.