Files

42 lines
2.6 KiB
Python

"""Ends a worker whose claude -p printed its final result and then waits on background shells that have gone quiet.
Claude Code's own time limit for a background command cannot do this: `BASH_DEFAULT_TIMEOUT_MS` and `BASH_MAX_TIMEOUT_MS` only raise the limit, and a call's `timeout` of up to 2 hours replaces the 10 minutes of a `claude -p` run (docs: code.claude.com/docs/en/tools-reference.md → "Time limit for background commands"). On 2026-11-18 a worker waited 95 minutes in an `until` loop whose `pgrep -f` matched its own command line.
The stops go to RECORD in the project's transcript archive rather than to the judge's records: the judge reads a worker's transcript, so the archive is where the pattern can be counted when it becomes a rule-hook ban (item 421).
"""
import pathlib
from loop_effects.effects import Effects, say, Streaming
from loop_effects.child_shells import Shell
from text_files.utc_stamp import utc
# Seconds without a line from the worker before a check, so a check is 5 minutes after its last line.
CHECK_EVERY = 300
# Seconds a shell's output must have been quiet before the shell is stopped.
QUIET = 180
RECORD = "lingering-workers.md"
def stopped_shells(proc: Streaming, printed_result: bool, record: pathlib.Path, effects: Effects) -> None:
"""Stops the shells of a claude that is still alive CHECK_EVERY seconds after it printed its final result (printed_result), saying each stop on the terminal and in record. A claude whose latest line is not a result is working and keeps its shells, and so does one with a shell that wrote output within QUIET seconds or runs a busy tool or holds a heavy slot, as `Shell.runs_busy_tool` and `Shell.holds_slot` say. A subagent's shells are children of the claude too, so they count like its own: a subagent that prints keeps them, and one inside a single quiet call loses it."""
if not printed_result:
return
now = effects.now()
shells = proc.shells()
if any(now - shell.written <= QUIET or shell.runs_busy_tool or shell.holds_slot for shell in shells):
return
for shell in shells:
proc.stop(shell)
line = stop_line(shell, now)
say(line, effects, stdout=True)
try:
record.parent.mkdir(parents=True, exist_ok=True)
with record.open("a") as handle:
handle.write(f"- {utc(now)} {line}\n")
except OSError as failure:
say(f"could not record the stop in {record}: {failure.strerror}", effects)
def stop_line(shell: Shell, now: float) -> str:
return f"stopped shell {shell.pid}, which held a worker after its final result; it had run {int(now - shell.started)} s and written nothing for {int(now - shell.written)} s: {shell.command}"