SuperAPI AI Directory

cleanup-agent-team-node-processes

Agents & models

View repository

Updated 10-16 07:26

About this skill

Clean up Agent Team residual processes

Overview

In a Windows / PowerShell environment, after heavy use of agent team, if you suspect there are residual processes that can be attributed to the current run — node.exe、npx.exe, Windows command handlers / wrappers (such as cmd.exe、powershell.exe、pwsh.exe、conhost.exe), agent browser browser processes (such as chrome.exe / msedge.exe / chromium.exe), or agent browser CLI processes — use this skill within the installed skill directory.

The core principle is: first audit the current command output, then only clean up processes that are reviewable, explainable, and have a clearly narrowed scope. By default, do not generate process ledgers, reports, or other cleanup artifacts in the current workspace, repository, or skill directory.

The execution subject of this skill is the scripts/agent-team-node-cleanup.ps1 distributed with the skill and native Windows process information. The AI agent is only responsible for extracting narrowly scoped parameters from the current task context, executing scripts, and interpreting results; it must not rely on a specific AI model, external model CLI, or model-specific capabilities to complete the cleanup, nor leave the responsibility for cleaning up temporary files to a subsequent model.

WorkBuddy starts a prewarm pool via a daemon, and within the pool it further starts command wrappers, Node MCP services, and native agent-browser workers. A large number of processes can only trigger an audit, not prove a leak or idleness; this skill groups by a single immutable process snapshot. When the command line is not visible, the script outputs only when the daemon→sidecar→MCP server→non-WorkBuddy subtree structure is complete and a sibling pool branch exists topology-inferred medium-confidence audit objects, without generating fabricated pool IDs. A high-confidence explicit pool can use a unique pool ID or PID; a medium-confidence topology pool can only use an exact root PID. Both must be generated into a stop plan only after the listener observation succeeds, the subtree has no protected role, and the operator separately confirms that the pool is not the current session and is already idle.

This skill is used for post-hoc cleanup after an agent team run, not for daily process management.

The first judgment is not "is there a target process name," but whether the resource consumption actually comes from residual processes of the current agent run. If high CPU, disk, or memory comes from Code.exe、rg.exe、tsserver.js, file watchers, AI indexers, Windows Defender, build artifacts, or cache directories, it should be redirected to VSCode exclusion rules, search indexing, file watching, TypeScript Server, Defender exclusions, or cache governance, and no cleanup should be performed.

Safety Rules

  • By default, execute dry-run first. The script's default mode only outputs the JSON audit results to the standard output of the current command, does not stop processes, and does not pass -OutputPath。
  • Prohibit killing processes in bulk by node.exe、npx.exe、cmd.exe、powershell.exe、pwsh.exe、conhost.exe, browser process name, wrapper command, or a single keyword.
  • Diagnose the resource source first, do not kill first. If the issue is not residual processes of the current agent run, do not apply this skill's cleanup.
  • When judging attribution, look at PID, PPID,CommandLine、ExecutablePath、CreationTime, working directory clues, listening ports, whether the parent process is still alive, and agent keyword hits at the same time.
  • Agent run attribution must be traceable back to multiple evidence points among runId, sessionId, parent agent, task name, checkpoint, execution log, trace, failed retry / scheduled retry, manual confirmation record, listening port, PPID, and command line; when there is only one clue, it can only be recorded as pending audit.
  • When evidence is missing, lower the confidence. When the working directory cannot be safely read, keep it as an unresolved clue and do not fabricate deterministic conclusions.
  • WorkBuddy's session attribution uses the current / not-current / unknown three-state. When both the command line and available path evidence are empty, the parent-child topology is incomplete, and the role cannot be identified, keep unknown; do not treat an older creation time, no recent new child processes, or no listening ports alone as not-current or proof of idleness.
  • WorkBuddy daemon、sidecar、codebuddy --serve --mcp-config MCP servers, unknown roles, UI / renderer / utility / crashpad / GPU, nested prewarm pools, the current PowerShell protection chain, and sessions specified via -ProtectedProcessId can never be cleaned up. Outside the selected pool root, as long as any of these WorkBuddy roles appears at any level of the subtree, the entire pool is permanently blocked and StopPlan is empty. Both ordinary Git Bash and WorkBuddy shell snapshot bash only audit, and do not automatically Apply.
  • WorkBuddy Apply must use -WorkBuddyPoolId or -WorkBuddyPoolPid to uniquely match one pool, and at the same time explicitly pass in -ConfirmWorkBuddyPoolNotCurrent and -ConfirmWorkBuddyPoolIdle. High-confidence explicit pools may use ID or PID;topology-inferred medium-confidence pools only accept an exact root PID; low-confidence pools are permanently blocked. The former confirmation is only responsible for session ownership, and the latter is only responsible for idleness; passing only one of them cannot substitute for the other, nor can it generate candidates. The script will not claim that it can automatically know the current session pool based solely on process age.
  • Listener observation uses the two states known / unknown , and the result is written to ListenerObservation。Get-NetTCPConnection . When unavailable or the query fails, it must record unknown and the reason, and use listener-observation-unknown to block Apply; observation failure must not be treated as zero listeners. After successful observation, if any descendant PID of the target WorkBuddy pool is listening on a TCP port, the entire pool cleanup is still blocked.
  • Native agent-browser-win32-x64.exe enters that pool only when the complete parent-child topology proves that it is within the selected pool; external processes with the same name do not enter the stop plan.
  • Before cleanup, the task context and dry-run output must be verified within the current session, but by default they are not persisted as a report. High-risk stops involving listening ports, long-running service keywords, still-alive parent processes, or unclear ownership must first obtain manual confirmation.
  • Only when -Applyis explicitly passed in, and the -OutputPath required by the script is pointed to the operating system temporary directory, is it possible to call Stop-Process; the general path must also provide a sufficiently narrow -IncludePattern, while the WorkBuddy path must provide a unique pool selector and explicit confirmation.
  • -Apply、-Force and the temporary JSON used for stuck recovery must be deleted in the same PowerShell try/finally segment; whether the command succeeds, fails, or throws an exception, it must not leave agent-process-ledger*.json。
  • -Force in the workspace. It can only serve as a second gate: used only after the ordinary stop path fails and the PID is still verifiable.
  • For one-off Node CLIs that still have a direct parent cmd.exe , automatic cleanup is still refused by default. Only when the regular dry-run output has been verified, the user has explicitly enabled the stuck recovery gate, and command characteristics, sustained CPU spinning, and no listening ports are simultaneously proven, is it allowed to stop the Node child process; never automatically stop the parent cmd.exe。
  • by this means. Protect long-running services: MCP gateway, tool marketplace, memory service, monitoring service, scheduled tasks, queue worker, SSE / chat session, RAG / vector service, IDE / editor extension host, development servers explicitly retained by the user, and package manager background tasks are not cleaned up by default.
  • After cleanup, the target PID and listening ports must be re-sampled, and only after confirming the result may it be said that the environment has been cleaned up.

Workflow

  1. First diagnose the source of the resource and define the cleanup scope; do not touch processes right away.

    • First distinguish whether the resource source is node.exe、Code.exe、rg.exe、tsserver.js, a watcher, an AI indexer, Windows Defender, or scanning caused by build artifacts / cache directories.
    • If it is not a residual process left over from the current agent run, move on to governing files.exclude、search.exclude、files.watcherExclude, TypeScript Server memory / watch configuration, Defender exclusions, or cache cleanup.
    • Which agent team run just ended?
    • Which runId, sessionId, parent agent, task name, checkpoint, log fragment, trace, failed retry / scheduled retry, manual confirmation record, workspace, or command fragment can identify the processes owned by this task?
    • Which long-running development servers, editors, package managers, or terminal tasks must be excluded?
  2. Audit candidate processes, only view command output, do not write workspace files.

powershell -ExecutionPolicy Bypass -File scripts/agent-team-node-cleanup.ps1

The script audits these target process names by default:node.exe、npx.exe、cmd.exe、powershell.exe、pwsh.exe、conhost.exe、chrome.exe、msedge.exe、chromium.exe、agent-browser.exe、agent-browser-cli.exe、WorkBuddy.exe、agent-browser-win32-x64.exe、bash.exe. If you need to narrow the audit scope, you can explicitly pass -ProcessName node.exe,cmd.exe; this only affects the audit sampling scope and will not bypass candidate blocking rules. Do not append -OutputPathto dry-run just to "keep evidence"; unless the user explicitly requests an export, standard output is the complete result of this dry-run.

The WorkBuddy grouping is included in dry-run by default, with no extra switch needed; the command is still stdout-only:

powershell -ExecutionPolicy Bypass -File scripts/agent-team-node-cleanup.ps1

In the results, ListenerObservation will first state whether the listener query succeeded;WorkBuddyGrouping will list CoreProcesses、PrewarmPools, each pool's DescendantPids、RecognitionMethod、IdentificationEvidence、Confidence、SessionState、ProtectionReasons、Decision and StopPlan. Both high-confidence pools identified explicitly by the command line and medium-confidence pools inferred by conservative topology can be audit targets; a medium-confidence pool's PoolId can be null, and can only be precisely selected via -WorkBuddyPoolPid . Pools that are valid but have not yet completed double confirmation remain needs-confirmation; pools with low confidence, unknown listener observation, protection, containing listeners, or containing protected roles in the subtree are blocked. The script will not automatically generate candidate-zombie-*。

  1. Before performing cleanup, review the dry-run output line by line.

These fields need focused checking:

Field Why it matters
Pid / ParentPid Determine parent-child process relationships and orphan status.
Name / ProcessFamily Distinguish Node runtime, command wrappers, agent browser CLI, or browsers.
CommandLine Distinguish agent workers, MCP services, package scripts, and user development servers.
ExecutablePath Confirm the Node binary path to avoid assuming all Node processes can be cleaned up.
CreationTime / AgeMinutes Avoid stopping processes that were just spawned and are still working.
WorkingDirectoryHint When the command line has cwd-related parameters, help determine which workspace the process belongs to.
ListeningPorts Mark development servers or MCP transports that require manual review.
ListenerObservation Distinguish "observed and zero listeners" from "listener query unavailable / failed"; the latter blocks cleanup.
ParentAlive Candidates whose parent process no longer exists are more likely to be orphan processes.
AgentKeywordMatches Help determine ownership, including clues such as agent-browser、agent_browser、playwright、remote-debugging-port , but cannot be used alone as a basis for cleanup.
AgentBrowserEvidence Browser process-specific evidence, requiring at least clues such as agent browser / Playwright / profile / run / session / workspace together with include or working directory; ordinary Chrome / Edge will not become candidates by default.
SafetyIssues Blocking reasons for automatic cleanup.
WorkBuddyGrouping WorkBuddy core chain, prewarm pool boundaries, tri-state session ownership, confidence, protection reasons, and single-pool stop plan.

Summary.NodeProcessCount is a compatibility field; prioritize looking at Summary.TargetProcessCount and Summary.ProcessNameCounts。

Beyond the script fields, also verify agent run dimensional evidence against the existing context of the current session: runId / sessionId, parent agent or parent task, checkpoint, log location, trace, failure retry / scheduled retry status, manual confirmation conclusion, port purpose, PPID chain, and full command line. No new report is needed for this; when this evidence cannot be completed, do not escalate the process to a cleanable candidate.

  1. Only after narrowing the candidate list is cleanup allowed to proceed.

When cleaning up a WorkBuddy pool that has been confirmed outside the script as not belonging to the current session and already idle, use only one pool ID or PID. The Apply ledger still goes only in the system temporary directory, and in the same section finally delete:

$ledgerPath = Join-Path ([IO.Path]::GetTempPath()) (
  "agent-process-ledger-{0}.json" -f [guid]::NewGuid()
)
try {
  powershell -ExecutionPolicy Bypass `
    -File scripts/agent-team-node-cleanup.ps1 `
    -WorkBuddyPoolId "wb-pool-exact-id" `
    -ConfirmWorkBuddyPoolNotCurrent `
    -ConfirmWorkBuddyPoolIdle `
    -MinAgeMinutes 30 -OutputPath $ledgerPath -Apply
  if ($LASTEXITCODE -ne 0) {
    throw "WorkBuddy pool cleanup failed with exit code $LASTEXITCODE."
  }
} finally {
  Remove-Item -LiteralPath $ledgerPath -Force -ErrorAction SilentlyContinue
}

-ProtectedProcessId should be passed a PID known to belong to the current active session; the script will protect that PID and its ancestor chain. The stop plan is fixed as: first freeze the PID, name, and CreationTime, stop the pool root, wait 2 seconds, then process surviving descendants in the original snapshot from leaf to root by depth. Before each stop, re-verify the triple to prevent PID reuse; new respawns only enter Verification.RespawnedProcessPids, and the same batch does not chase them. The WorkBuddy path prohibits -Force。

command line not visible,RecognitionMethod=topology-inferred and Confidence=medium , the pool ID must not be filled in or guessed. First read the unique root PID from dry-run, then use the same double confirmation and temporary ledger gate:

$ledgerPath = Join-Path ([IO.Path]::GetTempPath()) (
  "agent-process-ledger-{0}.json" -f [guid]::NewGuid()
)
try {
  powershell -ExecutionPolicy Bypass `
    -File scripts/agent-team-node-cleanup.ps1 `
    -WorkBuddyPoolPid 12345 `
    -ConfirmWorkBuddyPoolNotCurrent `
    -ConfirmWorkBuddyPoolIdle `
    -MinAgeMinutes 30 -OutputPath $ledgerPath -Apply
  if ($LASTEXITCODE -ne 0) {
    throw "WorkBuddy topology pool cleanup failed with exit code $LASTEXITCODE."
  }
} finally {
  Remove-Item -LiteralPath $ledgerPath -Force -ErrorAction SilentlyContinue
}
$ledgerPath = Join-Path ([IO.Path]::GetTempPath()) (
  "agent-process-ledger-{0}.json" -f [guid]::NewGuid()
)
try {
  powershell -ExecutionPolicy Bypass `
    -File scripts/agent-team-node-cleanup.ps1 `
    -IncludePattern "run-id-fragment|session-id-fragment|workspace-fragment|task-token" `
    -ExcludePattern "vite|next|storybook|mcp|gateway|tool-market|memory|monitor|cron|scheduler|queue|sse|rag|vector|extensionHost|tsserver|keep-alive" `
    -MinAgeMinutes 30 -OutputPath $ledgerPath -Apply
  if ($LASTEXITCODE -ne 0) {
    throw "Process cleanup failed with exit code $LASTEXITCODE."
  }
} finally {
  Remove-Item -LiteralPath $ledgerPath -Force -ErrorAction SilentlyContinue
}

The general cleanup path will reject -IncludePattern without -OutputPath or without -Apply, and will reject using only the process name or broad keywords such as agent、agent-browser、playwright、codex as include.-OutputPath is an internal script safety gate, not a requirement for users to keep a report; it must point to a unique system temporary file and be automatically deleted by finally .

Only the second gate uses forced termination:

Forced retry must rerun the previous complete code block to generate a new $ledgerPath and continue executing the same try/finally, only appending -Apply after -Force; do not change the path back to the current workspace.

Proven stuck one-off Node CLI exception

This exception applies only to one-off commands already proven by evidence to be synchronous CPU spinning, for example when a Windows path boundary causes --help、--version or a query command to continuously consume CPU with no output and no port. It is not a cleanup entry point for network connections, authentication, MCP, development servers, or general Node high CPU.

First verify the regular dry-run output, and in the current session confirm the command, Node PID, direct parent cmd.exe PID, start time, CPU and stdout/stderr sampling, listening ports, and reproduction evidence. Only after confirming that the command should not run long-term may restricted recovery be performed; do not create a separate standalone report:

$ledgerPath = Join-Path ([IO.Path]::GetTempPath()) (
  "agent-process-ledger-{0}.json" -f [guid]::NewGuid()
)
try {
  powershell -ExecutionPolicy Bypass `
    -File scripts/agent-team-node-cleanup.ps1 `
    -Apply -EnableStuckOneShotRecovery `
    -IncludePattern "run-id-fragment|task-token" `
    -OneShotCommandPattern "(?i)cli\.js\s+--help|neonctl.*--help" `
    -ExcludePattern "mcp|gateway|memory|monitor|cron|scheduler|queue|sse|rag|vector|extensionHost|tsserver|vite|next|storybook" `
    -MinAgeMinutes 5 -CpuSampleIntervalSeconds 5 `
    -MinCpuDeltaSeconds 3 -OutputPath $ledgerPath
  if ($LASTEXITCODE -ne 0) {
    throw "One-shot recovery failed with exit code $LASTEXITCODE."
  }
} finally {
  Remove-Item -LiteralPath $ledgerPath -Force -ErrorAction SilentlyContinue
}

When -EnableStuckOneShotRecovery is enabled, the script strictly requires -Apply, task-level -IncludePattern, -OneShotCommandPattern with arguments rather than only the executable name, and -OutputPath. Recovery candidates must simultaneously satisfy:

  • is only node.exe, the direct parent process is still cmd.exe;
  • the command lines of both the child process and the direct parent process match the same one-off command pattern;
  • reaches -MinAgeMinutes, matches include, does not match exclude, has no listening port, and does not belong to the script's own parent process chain;
  • the increment of two CPU samples reaches -MinCpuDeltaSeconds;
  • apart from parent-process-alive , no safety blocker exists.

The candidate will appear in the command result as candidate-stuck-one-shot . The script first only performs normal termination of the Node child process; the parent cmd.exe When it has not exited on its own, it must return to manual audit; the wrapper must not be terminated in bulk because of a subprocess exception.-Force Still only used for ordinary termination failures of that Node PID, and does not change the parent process handling rules.

  1. Review the resampling results.
    • Confirm that Verification.RemainingCandidatePids is empty; if it is not empty, explain each remaining PID one by one.
    • If the terminal, editor, or MCP runtime is still noticeably slow or very noisy, run the dry-run once more without -OutputPath .
    • If a stopped PID reappears, check the parent service; do not blindly clean it up again.

Candidate rules

The built-in script marks a process as candidate:

  • It belongs to the target process name specified by -ProcessName ;
  • It is not the current PowerShell process, the script host process, or on the current parent process chain;
  • Its lifetime reaches -MinAgeMinutes;
  • It matches at least one -IncludePattern;
  • It does not match any -ExcludePattern;
  • Its parent process no longer exists;
  • It is not listening on a TCP port.
  • If it is a chrome.exe、msedge.exe or chromium.exe browser process, it must also have multiple pieces of evidence such as agent browser / Playwright / profile / run / session / workspace; an ordinary user browser by default only enters audit-only。
  • candidate-stuck-one-shot is a narrow-scope exception protected by -EnableStuckOneShotRecovery : it only exempts the item that the direct parent cmd.exe is alive, and all other candidate gates are retained.
  • The WorkBuddy prewarm pool is by default needs-confirmation, not a candidate. A high-confidence explicit pool must be selected by a unique ID or PID;topology-inferred A medium-confidence pool must be selected by an exact root PID; a low-confidence pool is permanently blocked. Only when the selector, complete age evidence, listener observation is known with zero listeners, no protection chain, no WorkBuddy protection role anywhere in the subtree, and -ConfirmWorkBuddyPoolNotCurrent / -ConfirmWorkBuddyPoolIdle double confirmation are all satisfied at the same time does the pool root become candidate-workbuddy-pool-explicit; its descendants are managed only by the root's frozen StopPlan , and cannot each bypass the parent process liveness gate.

Except for the above WorkBuddy pool decisions, all other processes remain as audit-only or excluded。

Common mistakes

Wrong approach Correction
After the agent team ends, kill all node.exe, command handlers, or browser processes. First generate a ledger, then review the ownership evidence.
Treat high usage by VSCode, search, TS Server, or Defender as leftover processes. First locate the source of the resource usage; if it is not a leftover from the current agent run, switch to configuration governance.
Treat wrapper keywords as the only evidence. Judge by combining the command line, parent process state, age, path, ports, and include/exclude scope together.
Clean up just because the parent process no longer exists. Continue to verify runId, sessionId, checkpoint, logs, trace, ports, the PPID chain, and manual confirmation.
Accidentally harm MCP gateway, memory, monitoring, queue, SSE, RAG / vector, or scheduled tasks. Add long-running services to the exclusion rules; high-risk stops must first be manually confirmed.
Ignore listening ports. Record the ports and determine whether it is a leftover service or a development server intentionally kept.
Treat a listener query failure as no listener. Check ListenerObservation;unknown must block; it cannot be interpreted as an empty list.
Write into the current workspace agent-process-ledger*.json。 dry-run is read-only standard output;-Apply 's -OutputPath uses a system temporary file, and deletes it at finally .
Leave the temporary ledger for a later AI model to clean up. The creation and deletion of the temporary file must be closed-loop within the same deterministic PowerShell segment, without relying on the model for cleanup.
Claim cleanup is complete without re-sampling. Check the script's Verification block, or after cleanup re-run a dry-run that does not write to disk.
Treat a one-off CLI's lack of output or high CPU as a direct reason to kill the process. First verify the dry-run and reproduction evidence; only stop the Node child process when the restricted recovery gate simultaneously matches the exact command, CPU increase, and no port.
Because a one-off Node CLI is stuck, stop its parent cmd.exe。 Only stop candidate-stuck-one-shot the Node PID; whether the parent wrapper exits must be manually reviewed.
Treat WorkBuddy process age or "no new child processes recently" as proof of a zombie. Age is only an auxiliary gate; when session ownership or idleness cannot be proven, keep unknown / needs-confirmation。
Do not pass an exact pool selector, or select multiple pools at once and then Apply. Use only one at a time -WorkBuddyPoolId or -WorkBuddyPoolPid, and pass in the non-current-session and idle double confirmation separately.
Only pass -ConfirmWorkBuddyPoolIdle and treat it as a non-current session. Idle confirmation does not change SessionState; you must also independently pass in -ConfirmWorkBuddyPoolNotCurrent。
Clean up WorkBuddy daemon, sidecar, MCP server, UI / renderer, unknown roles, nested pools, or shell snapshot. All WorkBuddy roles outside the selected root are permanently protected; ordinary Git Bash and shell snapshot bash are audit-only.
Give topology-inferred a guessed pool ID for a medium-confidence pool, or clean up using a non-root PID. Do not generate a fictitious pool ID; only the exact root PID in the dry-run output is allowed, and it must continue to pass the double confirmation and all safety gates.
First kill the node/cmd in the pool, then let the daemon continue to pull in replacements. First stop the pool root, wait 2 seconds, then process the remaining descendants from leaf to root according to the frozen snapshot; new respawns are only reported.

Completion conditions

  • The target PID has stopped, and Verification.RemainingCandidatePids is empty; for each PID that has not stopped, the blocking reason has been explained individually.
  • The dry-run, cleanup, and recovery processes did not generate agent-process-ledger*.json, reports, or other artifacts in the current workspace, repository, or skill directory.
  • Temporary -OutputPath is located in the operating system temporary directory, and has already been deleted in the same segment finally .
  • Cleanup decisions come from script output and Windows process evidence, and do not depend on a specific AI model, external model CLI, or model-generated report.
  • Protected long-running services, user browsers, editors, and development servers were not mistakenly stopped.
  • WorkBuddy Apply only affects the frozen subtree of the single selected pool; core processes, other pools, UI / renderer, external agent-browser, bash, and PID-reused instances did not enter the stop results, and respawns were reported separately.

Resource Index

Path Purpose
scripts/agent-team-node-cleanup.ps1 Windows PowerShell audit and gate cleanup script.
scripts/lib/ Private implementation modules loaded by the entry point in a fixed order.