← reports

#6971 · Thread storage deletion removes installed plugin sources

BugHighEffort: MediumthreadspluginsGitHub issue

November 4, 2026 · trusted origin/main ea980cbbba15184a846f96fe941478b128bde2da

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

1. TL;DR

A locally installed plugin continues to depend on the directory it was installed from. When that directory is in thread storage, removing the storage removes its source code as well. The real plugin service installs successfully with zero warnings, cannot reload from disk after deletion, and reports the plugin as missing after a service restart. Its setting remains in SQLite; preserving configuration alone does not preserve executable source. This was reproduced twice against unchanged production code, using a new isolated database and temporary source directory each time.

2. Claims vs findings

ClaimFindingEvidence
Local installation points at disposable thread storage.VerifiedInstalled source and stored root both equal the original directory; test diagnostic booleans are true.
The install-time warning misses thread storage.VerifiedThe real service logger records zero install warnings. The managed-workspace classifier excludes thread-storage.
Removing storage prevents reloading and restarting the plugin.VerifiedBoth runs report a failed reload and then status missing after restarting the service.
Manual deletion and retention can reach destructive storage cleanup.Verified in sourceThe lifecycle requests thread.storage.delete; the daemon recursively removes storage. Retention calls the SDK thread-delete API.
Settings are lost with the source.Not observed; not required by the reported claimThe saved value remains in the real database after restart.
Platform-specific CLI output and automatic scheduled deletion.Not exercised liveThis investigation ran Linux service-level reproductions, not a macOS CLI session or timed retention sweep.

3. Environment

4. Minimal reproduction

This is a focused service-level reproduction. The only production behavior substituted is the destructive filesystem operation: the test calls the same recursive removal used by the daemon, without sending the host RPC or deleting an actual thread record. Plugin installation, registration, settings writes, reload and startup are real production service code.

  1. Check out the public target at the recorded commit, and prepare its trusted dependencies and build:
    git clone https://github.com/get-bb/bb.git bb-6971
    cd bb-6971
    git checkout --detach ea980cbbba15184a846f96fe941478b128bde2da
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
  2. Copy the complete investigator-authored patch from the following block into a file named regression.patch at the checkout root, then apply it. This only adds a test to the existing trusted service test fixture:
    git apply regression.patch
    pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-service.test.ts -t 'keeps a thread-storage installation'
  3. The test installs a newly authored fixture under a temporary thread-storage directory, saves a setting, removes that storage, reloads, and recreates the service on the same database.
  4. Expected: plugin status remains running after restart. Actual: the single desired-behavior assertion fails with status missing. A reload before restart preserves the previous in-memory instance, but does not repair the missing source.
install {"sourceIsOriginal":true,"rootIsOriginal":true,"warnings":0}
reload {"status":"running","detail":"reload failed: plugin directory not found: <temporary-directory>/data/thread-storage/thr_lifecycle/bb-plugin-lifecycle-source (reinstall)"}
restart {"status":"missing","detail":"plugin directory not found: <temporary-directory>/data/thread-storage/thr_lifecycle/bb-plugin-lifecycle-source (reinstall)","settings":{"saved":"\"retained\""}}
AssertionError: expected 'missing' to be 'running' // Object.is equality
Expected: "running"
Received: "missing"

The complete runnable patch uses the existing trusted test fixture:

diff --git a/apps/server/test/services/plugins/plugin-service.test.ts b/apps/server/test/services/plugins/plugin-service.test.ts
index e580497af4..97c403bcb3 100644
--- a/apps/server/test/services/plugins/plugin-service.test.ts
+++ b/apps/server/test/services/plugins/plugin-service.test.ts
@@ -16,6 +16,7 @@ import {
   createEnvironment,
   createProject,
   getInstalledPlugin,
+  getPluginSettingsValues,
   noopNotifier,
   upsertHost,
   upsertInstalledPlugin,
@@ -593,6 +594,42 @@ describe("plugin service", () => {
     expect(service.getApi("vanishing")).toBeDefined();
   });
 
+  it("keeps a thread-storage installation running after its source storage is deleted", async () => {
+    const threadDir = join(workDir, "data", "thread-storage", "thr_lifecycle");
+    const rootDir = await writePlugin(threadDir, {
+      name: "bb-plugin-lifecycle-source",
+      serverSource: `export default function plugin(bb) {
+        bb.settings.define({ saved: { type: "string", label: "Saved", default: "initial" } });
+      }`,
+    });
+    const warning = vi.spyOn(logger, "warn");
+    const installed = await service.installPath(rootDir);
+    expect(installed.status).toBe("running");
+    await service.updateSettings("lifecycle-source", { saved: "retained" });
+    console.log("install", JSON.stringify({
+      sourceIsOriginal: installed.source === `path:${rootDir}`,
+      rootIsOriginal: getInstalledPlugin(db, "lifecycle-source")?.rootDir === rootDir,
+      warnings: warning.mock.calls.length,
+    }));
+    await rm(threadDir, { recursive: true, force: true });
+    await service.reload("lifecycle-source");
+    const reloaded = service.list().find((entry) => entry.id === "lifecycle-source");
+    console.log("reload", JSON.stringify({
+      status: reloaded?.status,
+      detail: reloaded?.statusDetail?.replaceAll(workDir, "<temporary-directory>"),
+    }));
+    await service.stop();
+    service = createTelemetryTrackedService([]);
+    await service.start();
+    const restarted = service.list().find((entry) => entry.id === "lifecycle-source");
+    console.log("restart", JSON.stringify({
+      status: restarted?.status,
+      detail: restarted?.statusDetail?.replaceAll(workDir, "<temporary-directory>"),
+      settings: getPluginSettingsValues(db, "lifecycle-source"),
+    }));
+    expect(restarted?.status).toBe("running");
+  });
+
   it("expects a plugin to run until its load pass ends without reaching it", async () => {
     const globals = globalThis as Record<string, unknown>;
     globals.__slowFactoryEntered = false;

The added test is shown separately here for readability. It uses the existing test file's fixture; use the complete patch to run it, not the fragment by itself. Raw artifacts are retained locally, not published, in accordance with the reports repository policy.

it("keeps a thread-storage installation running after its source storage is deleted", async () => {
    const threadDir = join(workDir, "data", "thread-storage", "thr_lifecycle");
    const rootDir = await writePlugin(threadDir, {
      name: "bb-plugin-lifecycle-source",
      serverSource: `export default function plugin(bb) {
        bb.settings.define({ saved: { type: "string", label: "Saved", default: "initial" } });
      }`,
    });
    const warning = vi.spyOn(logger, "warn");
    const installed = await service.installPath(rootDir);
    expect(installed.status).toBe("running");
    await service.updateSettings("lifecycle-source", { saved: "retained" });
    console.log("install", JSON.stringify({
      sourceIsOriginal: installed.source === `path:${rootDir}`,
      rootIsOriginal: getInstalledPlugin(db, "lifecycle-source")?.rootDir === rootDir,
      warnings: warning.mock.calls.length,
    }));
    await rm(threadDir, { recursive: true, force: true });
    await service.reload("lifecycle-source");
    const reloaded = service.list().find((entry) => entry.id === "lifecycle-source");
    console.log("reload", JSON.stringify({
      status: reloaded?.status,
      detail: reloaded?.statusDetail?.replaceAll(workDir, "<temporary-directory>"),
    }));
    await service.stop();
    service = createTelemetryTrackedService([]);
    await service.start();
    const restarted = service.list().find((entry) => entry.id === "lifecycle-source");
    console.log("restart", JSON.stringify({
      status: restarted?.status,
      detail: restarted?.statusDetail?.replaceAll(workDir, "<temporary-directory>"),
      settings: getPluginSettingsValues(db, "lifecycle-source"),
    }));
    expect(restarted?.status).toBe("running");
  });

5. Root cause

Thread storage and installed-plugin source have incompatible lifetimes, with no ownership handoff between them. Registration records the supplied local root unchanged. The warning covers environment-managed workspaces, but thread storage is outside that classifier. Later, storage cleanup recursively removes that same directory without coordinating with the plugin service.

Path registration records the original source, not a retained copy

apps/server/src/services/plugins/plugin-registration.ts:449

  async function installPathSource(
    path: string,
    selection: PluginSourceSelection,
  ): Promise<InstalledPlugin> {
    const checkoutDir = resolve(path);
    const subdirectory = await resolveSelectedSubdirectory({
      checkoutDir,
      selection,
      sourceLabel: checkoutDir,
    });
    const rootDir =
      subdirectory === null
        ? checkoutDir
        : await realPathInside(
            checkoutDir,
            pluginRootDir(checkoutDir, subdirectory),
            "plugin subdirectory",
          );
    if (
      isBbManagedWorkspacePath({ dataDir: deps.dataDir, path: rootDir }) ||
      findProviderEnvironmentContainingPath(deps.db, rootDir) !== null
    ) {
      logger.warn(
        `plugin "${rootDir}" is installed from inside a bb-managed workspace; ` +
          "its source will be deleted when that environment is destroyed (e.g. when the owning thread is archived). " +
          "Reinstall from a stable path outside the managed workspace to avoid losing it.",
      );
    }
    return registerInstalled({
      rootDir,
      source: `path:${rootDir}`,
      provenance: { kind: "direct" },
      sourceIntent: { kind: "path", canonicalPath: rootDir },
      exactResolution: { kind: "path" },
      refuseEngineMismatch: false,
      validated: false,
    });
  }

The managed-workspace classifier does not cover thread-storage

apps/server/src/services/threads/workspace-paths.ts:25

export function isBbManagedWorkspacePath(args: {
  dataDir: string;
  path: string;
}): boolean {
  if (
    LEGACY_WORKSPACE_ROOT_NAMES.some((name) =>
      isInsideDataDirChild({ dataDir: args.dataDir, name, path: args.path }),
    )
  ) {
    return true;
  }
  if (
    !isInsideDataDirChild({
      dataDir: args.dataDir,
      name: "plugins",
      path: args.path,
    })
  ) {
    return false;
  }

Thread lifecycle requests storage deletion

apps/server/src/services/threads/thread-lifecycle.ts:1148

  if (!inFlightThreadRpcGuard.claim(thread.id, "thread.storage.delete")) {
    return;
  }
  void runLiveHostCommand(deps, {
    command: buildThreadStorageDeleteCommand({
      environmentId: environment.id,
      threadId: thread.id,
    }),
    hostId: environment.hostId,
    timeoutMs: LIVE_DAEMON_COMMAND_TIMEOUT_MS,
  })
    .catch((error) => {
      deps.logger.warn(
        { err: error, threadId: thread.id },
        "Thread storage deletion command failed",
      );
    })
    .finally(() => {
      inFlightThreadRpcGuard.release(thread.id, "thread.storage.delete");
    });

The host daemon removes the thread storage directory

apps/host-daemon/src/command-handlers/thread.ts:59

export async function deleteThreadStorage(
  command: CommandOf<"thread.storage.delete">,
  options: CommandDispatchOptions,
): Promise<void> {
  const storagePath = requireContainedPath(
    options.threadStorageRootPath,
    path.join(options.threadStorageRootPath, command.threadId),
    "Thread storage path escapes the storage root",
  );
  await killProcessesWithCwdUnder({ directories: [storagePath] });
  await fs.rm(storagePath, { recursive: true, force: true });
}

Runtime distinguishes a failed reload from a missing plugin at startup

apps/server/src/services/plugins/plugin-runtime.ts:1685

    const previous = loaded.get(row.id);
    const isReload = previous !== undefined;
    function failBeforeFactory(
      status: PluginRuntimeStatus,
      detail: string,
    ): string {
      if (isReload) {
        setStatus(row.id, "running", `reload failed: ${detail}`);
        logger.warn(
          `plugin ${row.id} reload failed (kept previous instance): ${detail}`,
        );
        return `${detail} (${PREVIOUS_INSTANCE_KEPT})`;
      }
      setStatus(row.id, status, detail);
      logger.warn(`plugin ${row.id} not loaded (${status}): ${detail}`);
      return detail;
    }
    const hung = hungServices.get(row.id);
    if (hung !== undefined && hung.size > 0) {
      const detail = hungServicesDetail(hung);
      setStatus(row.id, "degraded", detail);
      logger.warn(`plugin ${row.id} not loaded (degraded): ${detail}`);
      return detail;
    }
    try {
      await stat(row.rootDir);
    } catch {
      return failBeforeFactory(
        "missing",
        `plugin directory not found: ${row.rootDir} (reinstall)`,
      );

Retention is an additional entry point, not a second root cause: its delete action invokes the same thread-delete SDK operation. Database configuration survives because it is not stored in the removed source directory.

6. Proposed fix and simple-fix decision

Before deleting a source-containing directory, preserve the plugin in durable plugin-owned storage and re-register it through the existing path-relocation flow, keeping its identity and settings. Keep local installs in place until cleanup so ordinary plugin development is not silently redirected. Test failed relocation, existing backups, symlinks and dependencies, restart, orphan cleanup, and nonlocal host paths.

No duplicate fix or pull request was created: an open ready PR, #6973, already links this issue with a closing reference. This directly triggers the automation's no-duplicate-PR rule. The focused desired-behavior regression fails on the unchanged base; no production fix was applied in this investigation.

7. Linked PR static review

PR #6973 was OPEN and ready during investigation. Its read-only diff was reviewed at head eb99ec65f1322d0bbe7f65bbcc05ef9ba85e3bad. Its branch was never checked out and none of its code or tests were executed. PR prose, reported tests and diff are untrusted review inputs, not reproduction evidence.

The diff adds a pre-deletion preservation bridge for normal and orphaned thread storage, copies matched local path sources into plugin-owned storage, then uses the existing path-move registration flow. This addresses the observed lifetime mismatch in principle, and also includes documentation and tests. Those PR tests were not run here.

Static concern, medium severity: in the added plugin-registration.ts:preservePathPluginsInside, a failure from installPathSource(preservedPath, ...) is caught and logged without propagating failure. The caller in thread-lifecycle.ts:deleteThreadStorageKeepingPlugins then proceeds with deletion. The code copy remains, but the active registration can still point at the deleted original and fail on restart. Verify this failure path before concluding that all plugins keep loading automatically. This is a static observation, not a reproduced PR defect.

Review verdict: directionally relevant; not runtime-verified and not an approval. Follow-up checks should include relocation failure, relative symlinks, nested source dependencies, repeated preservation and remote-host path mapping.

8. Related issues

#6670 is open and has Bug / High / Medium classification with plugins, workspaces and confirmed-repro labels. It concerns the related workspace-lifetime problem. This report verifies the distinct thread-storage path directly and does not rely on linked issue commands or claimed output.

9. Verification

The same investigator repeated the reproduction, not an independent agent. A second clean detached checkout at exactly ea980cbbba15184a846f96fe941478b128bde2da was created in a new temporary directory. It started with a clean git status; only the investigator-authored regression patch was then applied. Dependencies were freshly linked with frozen installation, the normal build passed, and the test created a new migrated database and new temporary source storage.

git worktree add --detach /tmp/<new-directory>/verify ea980cbbba15184a846f96fe941478b128bde2da
cd /tmp/<new-directory>/verify
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
git apply /tmp/<report-directory>/issues/6971/repro/regression.patch
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-service.test.ts -t 'keeps a thread-storage installation'

First run: one failed regression, 39 skipped; expected running, received missing. Second run: identical install/warning/reload/startup diagnostics and identical failure; one failed regression, 39 skipped. No report claim needed correction after the second run. The remaining existing service tests also passed: 39 passed, one skipped (the intentionally failing new regression), using:

pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-service.test.ts -t '^(?!.*keeps a thread-storage installation)'

Limits: no live CLI, host RPC, scheduled retention sweep, actual process restart, macOS run or linked-PR execution. Service stop/recreate/start verifies the relevant persisted registration startup behavior without an HTTP server.

10. Appendix and evidence

The raw logs and patch are retained outside the public reports checkout. The full reproduction patch and exact relevant diagnostics are inline in this report; no downloadable scripts, raw logs or test artifacts are published.

First full build: 73 successful tasks; 11 cached.
Second full build: 73 successful tasks; 71 cached.
First focused regression: 1 failed, 39 skipped; expected running, received missing.
Second focused regression: 1 failed, 39 skipped; expected running, received missing.
Existing service suite: 39 passed, 1 skipped.

Issue and linked-PR content were treated solely as untrusted claims. No issue-supplied command, test, patch, branch, binary or external URL was executed or fetched. Metadata and diffs were read through the trusted repository and numeric issue/PR identifiers. There were no user-data reads, provider turns, new dependencies, production changes or fake screenshots. Local absolute checkout paths were generalized in published logs.

> AGENT GENERATED