Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): stop agent jobs that escape the CLI's process group on macOS and Windows #33691

Closedc-ehrlich(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/33691/headopened View on GitHub

On macOS and Windows, a Claude Bash tool job that moves to its own process group and loses its shell survives the CLI that started it. In one incident, a timed-out find … | head was auto-backgrounded. Claude Code then reported the task failed (exit 144) and stopped tracking it. bfs and head kept running for 19.5 hours with PPID 1 in their own group. The existing group kill and EOF watcher in spawnClaudeProcessGroup miss such jobs, and AgentScope is a no-op off Linux.

Fix

AgentScope on macOS and Windows is now a process tracker (apps/server/src/process/trackedAgentScope.ts). Linux keeps its systemd scopes unchanged.

  • Tracking: after spawning the CLI, the Claude adapter calls a new AgentScope.adopt(unit, pid). While any adopted session lives, a process-table snapshot records each session's descendants by pid and start time: ps every 5 s, PowerShell CIM every 15 s on Windows.
  • Ownership: recorded processes stay owned through reparenting, process group changes and setsid. A known process's new children join its session.
  • Signals: the existing paths call stop on CLI exit and kill on force stop. Both signal only recorded identities, revalidated against a fresh table read just before signaling. A child older than its listed parent sits under a reused pid and is never treated as a descendant.
  • Force stop: now kills the thread's newest session on macOS and Windows without a systemd unit (outcome killed).
  • Restart recovery: each server instance keeps <stateDir>/agent-processes/<instance> with its own pid and start time plus tracked identities. A starting server stops what a dead instance recorded, then removes its record. A record whose server is still running is left alone.
  • Scope: cleanup never runs per turn or on client disconnect, so background tasks keep spanning turns. Terminals (survivesRestart) and shared daemons (Codex app-server, OpenCode) get no unit. Sibling sessions and newer sessions in the same thread are untouched.
  • Windows exit path: the Claude CLI now also runs its stop on exit.

Why not an environment marker

The reviewed proposal put a session nonce in each agent's environment. It can't be read back: on macOS 15.8, ps -E prints no environment, even for the caller's own shell. sysctl KERN_PROCARGS2 returns another same-user process's argv but not its environment. The session ID doesn't work either, because Claude's Bash tool setsids every command; I checked with getsid. Ancestry snapshots are the generic option that needs no root on both macOS and Windows.

Side finding, not changed here: PortScanner's macOS agent-thread attribution reads T3CODE_THREAD_ID through ps -E, so it likely attributes nothing on macOS 15.

Limitations

  • A job that leaves the tree between two snapshots is missed: less than 5 s on macOS, less than 15 s on Windows. The incident job sat in the tree for at least 70 s.
  • Processes started through launchd or a service manager are never descendants. This is a backstop, not containment like a cgroup or Job Object.
  • Exit-time cleanup does not fix mid-session leaks. A job Claude stopped tracking keeps running until that CLI exits or the user force-stops the thread, since T3 can't tell whether a job is still wanted.
  • Providers: only Claude adopts. ACP, Pi and Muse get a unit, and their existing stop(unit) calls are no-ops until they adopt. Codex and OpenCode are shared daemons and are not tracked. Behavior for those providers is unchanged.
  • Windows: parser and descendant logic are unit-tested; the PowerShell path has not run on a Windows machine.
  • Cost: while any Claude session is open, one ps runs every 5 s (about 10 ms each), or one PowerShell every 15 s on Windows.

Validation

  • Reproduction: ClaudeAgentSdkQueryRunner.test.ts › "stops a job that left the CLI's group and lost its shell when the session closes". A fake CLI's tool shell starts a job in a new group via setpgrp, then exits while the CLI runs. With the default scope, today's macOS/Windows behavior, the test times out. It passes with the tracker. It also asserts the job keeps running while the session is open.
  • Tracker tests (real subprocesses): trackedAgentScope.test.ts covers exit cleanup sparing a sibling session and a newer same-thread session, and force stop without a systemd unit. It also covers restart recovery after simulated server death while sparing a live instance's record, plus parser and pid-reuse units. These tests run on POSIX (skipped on Windows), so Linux CI covers them through ps.
  • Checks: vp run check:changed passes (format, lint, knip, typecheck of 35 packages, tests beside changes). agentScope.test.ts and ThreadManagementService.test.ts pass.

Upstream Claude Code report (draft, not filed)

Background Bash task marked failed (exit 144) leaves its processes running Claude Code 2.1.309, macOS 15. A foreground Bash command (find <dir> … | head; find / …) hit the 60 s timeout and was auto-backgrounded. About 10 s later the task was reported as failed with exit code 144 and no longer tracked. The pipeline's children (bfs, head) kept running for 19.5 hours with PPID 1 in the shell's process group, while the CLI session stayed alive. Expected: when a background task is reported failed or stopped, its whole process group is terminated, or the task stays tracked until it is. Repro sketch: run a long pipeline that exceeds the Bash timeout so it auto-backgrounds; when the task is reported failed, check ps -o pid,ppid,pgid,command for its processes.

🤖 Generated with Claude Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. @@ -0,0 +306,21 @@
      306+ }),
      307+ );
      308+ yield* ensurePolling;
      309+ });
      310+
      311+ // Runs when the agent exits: whatever it started and left behind is stopped.
      312+ const stop: AgentScopeShape["stop"] = Effect.fn("AgentScope.stop")(function* (unit) {
      313+ threadByUnit.delete(unit);
      314+ const targets = yield* lock.withPermits(1)(
      315+ Effect.gen(function* () {
      316+ const session = sessions.get(unit);
      317+ if (session === undefined) return undefined;
      318+ sessions.delete(unit);
      319+ if (sessionByThread.get(session.threadId) === unit)
      320+ sessionByThread.delete(session.threadId);
      321+ const rows = yield* readTable;
      322+ if (rows === undefined) {
      323+ yield* Effect.logWarning("Could not stop an exited agent's processes");
      324+ return undefined;
      325+ }
      326+ return { processes: trackedProcesses(rows, session.processes), rows };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High process/trackedAgentScope.ts:318

      When readTable fails during stop, the session is removed before the failure check, so its recorded process identities are no longer retried and the next persistence drops them. Read the table successfully before removing the session and its thread mapping.

      Suggested change
      318- sessions.delete(unit);
      319- if (sessionByThread.get(session.threadId) === unit)
      320- sessionByThread.delete(session.threadId);
      321- const rows = yield* readTable;
      322- if (rows === undefined) {
      323- yield* Effect.logWarning("Could not stop an exited agent's processes");
      324- return undefined;
      325- }
      326- return { processes: trackedProcesses(rows, session.processes), rows };
      318+ const session = sessions.get(unit);
      319+ if (session === undefined) return undefined;
      320+ const rows = yield* readTable;
      321+ if (rows === undefined) {
      322+ yield* Effect.logWarning("Could not stop an exited agent's processes");
      323+ return undefined;
      324+ }
      325+ sessions.delete(unit);
      326+ if (sessionByThread.get(session.threadId) === unit)
      327+ sessionByThread.delete(session.threadId);
      328+ return { processes: trackedProcesses(rows, session.processes), rows };
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/process/trackedAgentScope.ts around lines 318-326:
      
      When `readTable` fails during `stop`, the session is removed before the failure check, so its recorded process identities are no longer retried and the next persistence drops them. Read the table successfully before removing the session and its thread mapping.
      @@ -0,0 +240,21 @@
      240+ // one starting up while the previous one shuts down, keeps its agents.
      241+ const recoverLeftovers = Effect.fn("trackedAgentScope.recoverLeftovers")(function* () {
      242+ const entries = yield* fileSystem
      243+ .readDirectory(ownersDir)
      244+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
      245+ const previous = entries.filter((entry) => INSTANCE_FILE.test(entry) && entry !== instance);
      246+ if (previous.length === 0) return;
      247+ const rows = yield* readTable;
      248+ if (rows === undefined) return;
      249+ for (const entry of previous) {
      250+ const file = path.join(ownersDir, entry);
      251+ const text = yield* fileSystem.readFileString(file).pipe(Effect.orElseSucceed(() => ""));
      252+ const [ownerLine = "", ...lines] = text.split("\n");
      253+ const [owner] = parseRecord(ownerLine);
      254+ if (owner !== undefined && trackedProcesses(rows, new Map([owner])).has(owner[0])) continue;
      255+ const targets = trackedProcesses(rows, parseRecord(lines.join("\n")));
      256+ if (targets.size > 0) {
      257+ yield* Effect.logWarning("Stopping agent processes left by a previous server", {
      258+ count: targets.size,
      259+ });
      260+ yield* terminate(targets, rows);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High process/trackedAgentScope.ts:260

      Restart recovery can terminate an unrelated process when a PID from a later record is reused while an earlier record is being cleaned up. recoverLeftovers passes the same initial rows snapshot to every terminate call, so the PID/start-time check in signal compares against stale data before calling process.kill by PID; re-read the table and validate each record's process identities immediately before signaling.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/process/trackedAgentScope.ts around line 260:
      
      Restart recovery can terminate an unrelated process when a PID from a later record is reused while an earlier record is being cleaned up. `recoverLeftovers` passes the same initial `rows` snapshot to every `terminate` call, so the PID/start-time check in `signal` compares against stale data before calling `process.kill` by PID; re-read the table and validate each record's process identities immediately before signaling.
      @@ -0,0 +279,21 @@
      279+ return Effect.gen(function* () {
      280+ while (sessions.size > 0) {
      281+ yield* Effect.sleep(platform === "win32" ? WINDOWS_POLL_INTERVAL : POSIX_POLL_INTERVAL);
      282+ yield* refresh;
      283+ }
      284+ }).pipe(
      285+ Effect.ensuring(Effect.sync(() => (polling = false))),
      286+ Effect.forkIn(layerScope),
      287+ Effect.asVoid,
      288+ );
      289+ });
      290+
      291+ const adopt: AgentScopeShape["adopt"] = Effect.fn("AgentScope.adopt")(function* (unit, pid) {
      292+ const threadId = threadByUnit.get(unit);
      293+ if (threadId === undefined) return;
      294+ yield* ready;
      295+ yield* lock.withPermits(1)(
      296+ Effect.gen(function* () {
      297+ const rows = yield* readTable;
      298+ const root = rows?.find((row) => row.pid === pid);
      299+ if (rows === undefined || root === undefined || !threadByUnit.has(unit)) return;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High process/trackedAgentScope.ts:299

      If the initial process-table read fails during adopt, this CLI is never tracked, even after later snapshots succeed. The rows === undefined guard returns before storing the session, and ensurePolling only polls existing sessions; because the spawn callback calls adopt once, retain the pending root identity and retry the adoption after a failed read.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/process/trackedAgentScope.ts around line 299:
      
      If the initial process-table read fails during `adopt`, this CLI is never tracked, even after later snapshots succeed. The `rows === undefined` guard returns before storing the session, and `ensurePolling` only polls existing sessions; because the spawn callback calls `adopt` once, retain the pending root identity and retry the adoption after a failed read.
    3. Approvability

      Verdict: Needs Human Approval

      Macroscope's review found this PR requires human approval — This adds automatic cleanup of tracked Claude subprocesses on macOS and Windows, including after server restarts. The new diagnostic suppression and changed default lifecycle require human review; an unresolved restart-recovery finding also identifies potential termination of unrelated processes.

      Needs human approval because:

      • 3 blocking correctness issues found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Explain Change →

      No actionable comments were generated in the recent review.

      Walkthrough

      Agent scopes now track process trees on macOS and Windows, persist session records, and clean up tracked processes. The Claude adapter adopts child PIDs into these scopes and stops the scope when the child exits.

      Changes: Tracked agent process lifecycle

      Layer / File(s)Summary
      Agent scope adoption contract
      packages/shared/src/AgentScope.ts
      AgentScopeShape adds adopt(unit, pid). The default scope implements it as a no-op.
      Process identity and ancestry
      apps/server/src/process/trackedAgentScope.ts, apps/server/src/process/trackedAgentScope.test.ts
      Process rows from POSIX and Windows are parsed into PID, parent PID, and start time. Process-tree tracking uses start times to distinguish reused PIDs. Tests cover parsing and ancestry.
      Session tracking and cleanup
      apps/server/src/process/trackedAgentScope.ts, apps/server/src/process/trackedAgentScope.test.ts
      Tracked scopes refresh and persist process trees, recover records from prior instances, and stop or kill tracked processes. Tests cover escaped jobs, session isolation, and restart recovery.
      Platform selection and Claude adoption
      apps/server/src/process/agentScope.ts, apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts, apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
      macOS and Windows use the tracked scope. The Claude adapter adopts a child PID when available and stops its scope on child exit. A CLI lifecycle test checks cleanup when the session closes.

      Estimated code review effort: 4 (Complex) | ~45 minutes

      Change: Bug fix

      Sequence Diagram(s)

      sequenceDiagram
        participant ClaudeAdapterV2
        participant TrackedAgentScope
        participant ProcessTable
        participant SessionRecord
        ClaudeAdapterV2->>TrackedAgentScope: adopt unit and child PID
        TrackedAgentScope->>ProcessTable: read process rows
        ProcessTable-->>TrackedAgentScope: return PID ancestry and start times
        TrackedAgentScope->>SessionRecord: persist tracked process tree
        ClaudeAdapterV2->>TrackedAgentScope: stop scope when child exits
        TrackedAgentScope->>ProcessTable: read current process rows
        TrackedAgentScope->>ProcessTable: signal remaining tracked processes

      Suggested labels: bugfix

      Suggested reviewers: josephv123, juliusmarminge

      Merge Risk: Minimal · up to 97c11

      This change adds process tracking so Claude agent jobs on macOS and Windows are stopped when they escape the CLI's process group. No actionable merge-blocking issue was found. The PowerShell path has not been run on Windows, which is worth confirming in normal testing.

      Pre-merge checks: Passed 4

      Check nameStatusExplanation
      Title checkPassedThe title clearly identifies the main change: stopping Claude agent jobs that escape the CLI process group on macOS and Windows.
      Description checkPassedThe description explains the problem, the fix and its scope, key limitations, and focused verification results. It does not include the required Scope and approval section or state why this focused fi…
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Description check

      Explanation

      The description explains the problem, the fix and its scope, key limitations, and focused verification results. It does not include the required Scope and approval section or state why this focused fix qualifies without prior approval, but the remaining required information is substantial.

      Finishing Touches

      Generate unit tests (beta)

      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Recent review info

      Run configuration

      Commits

      Reviewing files that changed from the base of the PR and between 20bb685e68fda77f60f9324f0db96d4ef06902d2 and 97c116a0cfb08cfc0455048b8c22ccda5015b3cc.

      Files selected for processing: 6

      • apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
      • apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
      • apps/server/src/process/agentScope.ts
      • apps/server/src/process/trackedAgentScope.test.ts
      • apps/server/src/process/trackedAgentScope.ts
      • packages/shared/src/AgentScope.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Sign in to join this conversation.