Symptom: ProcessRegistry.spawn_local starts every terminal(background=true) job in its own session, and
the agent-lifecycle sweeps that stop jobs (kill_all on release, agent_close, a turn timeout) only run
while the owner is alive. A CLI, TUI or worker that is SIGKILLed / OOM-killed / crashes left every job
running on init. Measured on Linux (tbg_probe, kill -9 the owner, check at +10 s, 2/2 runs): pipe job
1/1 alive, pipe job with a child 2/2 alive. A PTY job's hangup stops only jobs that keep the default
SIGHUP action: a HUP-ignoring PTY job (`nohup`'d server, trap '' HUP) and its child 2/2 alive.
Change (tools/process_registry_ownership.py, a new ProcessRegistry mixin; process_registry.py is at its
size cap and shrinks by 10 lines): a local background job's process group goes to the owner-death
supervisor (process_identity layer 4) for as long as the job's own process runs: pipe jobs start through spawn_owned
(purpose="terminal-background", recorded in the spawn ledger), PTY jobs hand their pty.fork group to
own_process_groups. The group is released when the job leaves _running (exit, kill, reconcile) and by
_reap_untracked after a failed setup, so a job's deliberate `server &` survivors keep today's
behaviour once the job ends. A foreground command that yields to background (adopt_local) hands its
supervised group to the job instead of releasing it.
Deliberately NOT owned (they must outlive the owner):
- persist_on_release jobs (#41225, ec5c9c738a): the user asked for them to outlive the agent.
- every job of a gateway (a host that ran recover_from_checkpoint, or a supervised gateway): it
re-adopts the jobs a crashed predecessor left running, so its own jobs must survive its crash the
same way. Its clean shutdown still kills them (kill_all(source="gateway_shutdown")).
- Windows: the layer-3 job object covers ownership; the spawn path there is unchanged.
The systemd-scope, TERM->KILL tree kill, start-time PID-reuse guards and post-kill survivor checks stay:
they cover a live owner.
Result: same probe, 3/3 runs: pipe 0/1, pipe+child 0/2, HUP-ignoring PTY job + child 0/2 alive; the
persist_on_release job 1/1 alive (as intended). tests/tools/test_terminal_owned_jobs.py now also covers
jobs: kill -9 owner vs live control owner (jobs + PTY job + command die, persist_on_release job lives,
control untouched), a recovering host's jobs outlive its kill -9, finished job releases, yielded
command keeps its group until the job ends, unowned jobs never reach the supervisor. 5/5 green x3, 5/5
red on the pre-change code, each red on its own mutation (8 mutations). Two existing tests build
sessions by hand or fake Popen + os.killpg; they now carry the new field / stub the supervisor.
_reap_untracked moves into the mixin unchanged apart from the release.
Background terminal commands run `bash -lic` with no env snapshot, so a
~/.profile or distro /etc/profile that resets PATH dropped every parent-only
dir (bare `hermes` / the venv's tools: command not found), while the same
command in the foreground now resolved. spawn_local gains an opt-in
restore_login_path that prepends the SAME _append_dropped_path_entries
prelude the foreground snapshot uses, fed from the spawn env's PATH; the
terminal tool's local background spawn turns it on. The registry's shell
argv shape is unchanged.
process_registry.py and its test file are over the 2,000-line target and may
only shrink: the PTY/pipe Enter choice collapses to one expression and the two
submit_stdin tests move to tests/tools/test_process_registry_submit.py.
submit_stdin appended \n unconditionally, but raw-mode TUIs (claude,
vim, htop) bind Enter to \r — what a real keyboard sends — so submitted
input never registered as Enter in interactive TUI sessions. Send \r
for PTY sessions instead; canonical-mode children are unaffected since
the tty driver's ICRNL maps \r to \n. Same reason tmux send-keys Enter
transmits \r. Non-PTY (pipe) sessions keep \n.
Claude-Session: https://claude.ai/code/session_013LH6C3g6wjMjhSXRauyVCW
- spawn_local records why a pty=true spawn fell back to pipe mode
(ProcessSession.pty_fallback); the stdin errors name that reason instead
of telling the agent to repeat a pty=true request that already failed.
- A background cron run dispatches with model=None: the run session is the
only source of the notice's model, so a refused fire of a pinned job no
longer prints the pin it never ran.
- Tests wait on the completion queue / wait_until instead of sleep polling,
and spawn in tmp_path.
terminal(background=true) without pty connects stdin to /dev/null, so
`read x; echo $x` exits before any process_manage write and the write
said only "Process has already finished". Name the cause and the pty=true
relaunch there too (same PTY-availability guard).
A background cronjob(action='run') completion rendered "Model: ?" and
"API calls: 0" whatever the job did: _manual_run_completion hard-coded
api_calls 0 and the dispatch only knew the job's model pin (None on the
default model). The runner now reads the fire's run session from
state.db (list_cron_job_runs by execution id, summed over its
compression chain); with no run session the fields are omitted, and the
async-delegation event and renderer omit them instead of printing ?/0.
process_manage write/submit on a local background process spawned
without pty said "non-local backend or stdin closed". The new sibling
tools/process_registry_stdin.py says to relaunch with pty=true, except
where a PTY cannot be had (isolated worker log spawn, PTY library
missing) or the backend is non-local. process_registry.py line count
unchanged.
Found on Hermes Cloud staging.
The deferred tool_search catalog shows each tool's first sentence clipped to
60 chars, so lines like 'image_generate: Generate high-quality images from
text prompts, or edit /…' hid that it edits with reference images on the
user's configured model. An agent skipped it and called FAL directly with a
hardcoded model.
- catalog line cap 60 -> 80 (CATALOG_SUMMARY_MAX_CHARS); every built-in
tool's first sentence now fits and leads with what it does
- image_generate/video_generate say they use the configured model;
image_generate says to use it rather than direct API calls/scripts
- web_search/web_extract/browser_exec name when to use each other
- drop a duplicated cronjob sentence and filler in skill_view/video_generate
- regenerate tests/fixtures/prompt_surface
spawn_via_env accepted cwd but never passed it to env.execute, so
terminal(background=True, workdir=...) on docker/ssh/modal/daytona/
singularity and plugin backends ran in whatever directory the shared
environment last cd'd to. Pass it through execute's wrapper exactly as
the foreground path does.
spawn_via_env (every non-local backend: docker, ssh, modal, singularity,
daytona, plugin backends such as bubblewrap) turned a launch wrapper that
produced no PID, or an env.execute that raised, into an exited
failed_start ProcessSession and returned it. spawn_background_process
treated any returned session as started, so the model was told
"Background process started" with a session_id that was never
registered (process_manage poll: not_found) and the real reason
(e.g. no bash in the image, sandbox gone) was dropped.
A launch that never started is not a session: spawn_via_env now raises
with the wrapper's exit code and output, like a failed Popen on the local
path, and spawn_background_process's existing error branch returns
exit_code -1 with that reason.
Follow-up to the poll() drain fix: macOS poll() does not support device
fds and reports a PTY master as POLLNVAL, i.e. "ready" at once, so
PtyBridge.read() would return b"" without waiting and the dashboard /
Desktop terminal pane's read loop would spin a core on every Mac.
fd_wait now wraps selectors.DefaultSelector (epoll on Linux, kqueue on
macOS; kqueue supports ptys since 10.9), which has no FD_SETSIZE ceiling
either. Each reader owns one waiter for its lifetime and closes it: the
foreground drain, the background reader and the PtyBridge (opened in
__init__, closed in close()). The background reader marks itself
selectable only when the waiter actually registered.
Tests: one case drives the real terminal drain and the background reader
above fd 1024; the other drives a real PTY above fd 1024 and asserts an
idle read waits for its timeout (the macOS-poll spin). Both are
platforms("posix"), so the macOS lane runs them. The existing PTY
EAGAIN-race test now stubs the waiter instead of select.select.
Co-authored-by: Mohamad Kanso <91088196+MohamadKanso@users.noreply.github.com>
select.select() raises ValueError "filedescriptor out of range in select()"
once a watched fd reaches FD_SETSIZE (1024), which a long-lived gateway or
desktop process hits as it accumulates open fds. Every drain caught that
ValueError as "fd already closed" and silently dropped output with no error
signal (issue #94928).
Introduce a shared poll()-based fd waiter (tools/environments/fd_wait.py) and
use it in all three drain sites: tools/environments/base_output.py (terminal
and read_file), tools/process_registry.py (background processes), and
hermes_cli/pty_bridge.py (PTY terminal sessions). poll() has no FD_SETSIZE
ceiling, and POLLHUP/POLLERR read as ready so the caller's read observes the
real EOF.
Regression tests hold more than 1024 fds and assert the drain and the terminal
path still capture output (tests/tools/test_drain_high_fd.py).
Fixes#94928
Signed-off-by: Anthony Holten <anthony.holten1@gmail.com>
The post-turn safety-net drain took every event off the shared queue but held only the draining
session's owners. Idle session A's completion, sitting in session B's hands while B checked
ownership, left A in neither the queue nor a hold, so a reaper could close A and the requeued notice
was then dropped as unowned. The drain now dequeues through drained_for(), which holds every
dequeued event's owner until the foreign events are requeued and its own are routed.
_rebuild_session_agent (Bot Chat capability refresh) installed a replacement agent without the old
one's raw spawning ids, so a process started before a compression rotation stopped pinning its
session and fell outside the new agent's close kill set. The replacement now inherits them.
Three gaps in the live-state keepalive:
- Dequeue is not delivery. The poller takes events off the shared queue before routing them, so
between get() and turn admission the owner was in neither the queue nor running, and a reaper could
close it; a foreign profile's poller holding the event then dropped it as unowned. Pollers now
dequeue through take_ready(), which records an in-flight hold per owner in the same queue-mutex
critical section as the dequeue, released only after routing (admit, requeue or drop) returns. The
post-turn safety-net drain holds the session's owners the same way.
- An exit recorded but not yet published could be pruned by a concurrent spawn, erasing the only
record that a notice was coming. _prune_if_needed now skips finish-claimed entries whose
completion event is unset.
- Stop only ignored queued notices, so a running watch kept a stopped, disconnected session alive
forever. A stopped session can admit no notification turn until the user's next prompt, so it is
never pinned by pending notices.
The keepalive matched processes by the session's current key, which compression rotates while the
process keeps its original owner id, so a pre-compression watcher stopped pinning its session even
though agent close still kills it. It also released the session the instant the process exited,
before the completion was queued and dequeued, so a reaper in that window still lost the notice.
ProcessRegistry.awaits_notification() now matches on owner_task_id (the same field close() kills by,
via the agent's _process_owner_task_ids) and keeps the owner awaited for a bounded grace after exit.
A watch that was disabled no longer pins anything.
Models re-issue byte-identical process_manage wait/poll calls on a background
process that has printed nothing new: in 30 days of one heavy user's sessions,
~1,900 of 2,235 waits repeated the previous call verbatim, each a full model
turn (~231k prompt tokens on a frontier model), often right after the timeout
note said the process was still running.
After the second consecutive wait/poll on a running session with no new
output, Hermes now enables notify_on_complete for that session (stamping
gateway routing and arming the per-process watcher when it was spawned
silently, so messaging chats get the exit too) and the result tells the model
not to wait or poll again: the exit code and final output arrive as their own
message. New output, exit, or any other action on the session resets the count.
Only where a completion can reach the agent: finite turns (chat -q / -z),
cron, Kanban workers, stateless API sessions and delegated subagents keep the
old result. terminal.process_wait_auto_notify: false restores the old
behaviour everywhere.
The counting/policy lives in tools/process_registry_wait_policy.py; the
process_registry facade only routes session-action results through it.
join_heartbeat_outputs guessed a tick's truncation from its text: a job
that printed "...(10 earlier characters omitted)" was read as a cut
tick, and the fold dropped every earlier tick's output even when the
combined text fit. The registry now puts the tail in "output" and the
cut count in "omitted"; the fold adds the counts, and the marker is
rendered once, by the notification formatter. The regex and its
reverse parser are gone.
Review finding on #140185 (Greptile)
Refs #134889 (RT-28)
Refs #140138
A terminal(background=true, heartbeat=N) liveness tick had no producer
identity, so the session authority refused every tick (invalid_params)
and the watch drain requeued it on every pass, in local and messaging
chats alike: the agent never heard about a long job until it exited.
A tick now carries the same per-event identity as a watch match (its
own event id, kept across a requeue), so a retried tick is admitted
once. A tick that finds an earlier tick of its process still queued in
the chat cancels it and carries its output, tail-capped like any tick
with an exact omitted count, so a busy chat holds one waiting tick turn
per process and no tick output is lost; a tick that already started has
read its own. Only the gateway's own queued tick is ever withdrawn: a
client input whose id merely looks like one is never touched.
No tick runs after its process's completion: the completion withdraws a
waiting tick, and a later tick is dropped. A failure preparing one tick
requeues it instead of dropping the rest of the drained events.
A local tick's card is the internal_notification kind with a one-line
receipt, so an idle classic CLI opens the turn and shows the reply. The
kinds a producer card may name are now their own closed set, apart from
the set that allows silence.
Tests run the local cases on two profiles of one multiplexed gateway and
a Discord chat through the real authorities, adapters, turn path and
SQLite, and also pin the served profile's Bot Chat relay and Desktop
watch/completion admission, with the frozen policy each turn ran on,
across a restart.
(cherry picked from commit 98b17852d67078d78d462bf6da3cf76f89faa640)
On main the terminal tool, its background processes and execute_code ran
with the launching shell's environment: an activated venv, nvm/pyenv
shims, PATH. Under the one gateway they ran with the daemon's
environment, so `python`, `node` and friends resolved to whatever the
gateway was started with.
The allowlisted toolchain part of a session's client_env (PATH,
VIRTUAL_ENV, CONDA_*/NODE_*/NVM_*/PYENV_*, GOPATH, GOROOT, CARGO_HOME,
RUSTUP_HOME, JAVA_HOME, plus names a profile lists in the new
terminal.client_env_passthrough) now replaces the daemon's values for that
session's local terminal commands, background processes and execute_code
children only, including execute_code's project-mode interpreter choice.
PATH stays the gateway's when the client sent none. The backend's own
terminal.env still wins. No full shell snapshot is taken. Messaging, cron
and Desktop sessions keep the gateway's environment.
Credential-looking names are never sent, stored or bound: one predicate,
is_secret_env_name, now shared with execute_code's secret policy, drops
them on the client, before the policy is stored and again before binding
(secrets keep using terminal.env_passthrough). execute_code applies its
whole scrub, including the delegated-child restrictions, after merging the
client's toolchain, and its list now also strips *COOKIE* names.
Refs #134889 (T3)
Refs #139523
375 commits from main (0e427d788d). 24 files conflicted; the resolutions that carry a decision:
- /initiate-setup: main removed the command (25bf722063). Its gateway rewrite, CLI handler and the
Desktop kickoff go with main; this branch's command-layer admission of it is dropped too
(gateway/session_commands.py _PROMPT_COMMANDS, its slash.exec test row, the parity doc row), and
the Desktop slash dispatcher loses the `hidden` option that only the kickoff used.
- Code this branch moved out of its old file, carrying main's edits to the moved copy:
first-contact notes (gateway/run_turn.py -> run_turn_prepare.py: no message/setup_command),
the TUI agent factory (tui_gateway/server.py -> agent_factory.py: onboarding toolsets at build,
setup_beat/set_theme lifecycle cards, no cli platform extras on a coding selection), the serve
lifespan (web_server.py -> web_server_app.py standalone_lifespan: first-install probe before the
state.db reconcile, onboarding due answer after the setup bootstrap), and the compression child
publish (the shared _publish_compression_child_on_conn reads the parent's model_config).
- agent/auxiliary_client.py: both import changes (_route_key from main; this branch's move of
_without_structured_output_format).
- Desktop: main's onboarding run (decideOnboarding, OnboardingEnd, card-waiting Send) replaces the
kickoff; this branch's prepared-submission slash path, request_id on session.create and
PreparedImageRecovery stay. Pool-limits imports are dropped (this branch removed the pool).
createBackendSessionForSend takes main's (preview, overrides) signature.
- ci.yaml detect job: main's `ref: inputs.commit` plus this branch's sparse checkout.
- package.json / lock: main's vitest 4.1.11 plus this branch's ws 8.21.1.
- Generated: gateway-contract.openrpc.json regenerated; parity doc regenerated.
pm.install.activate puts the store's tool dirs first on the backend's
PATH, so Hermes's own code finds the pinned binaries. The terminal built
its PATH from the same environment, so every command the user or the
agent ran got Hermes's node, npm, python and rg ahead of the ones the
user installed. On the Windows Store build that was worse than a version
surprise. cmd.exe cannot start the packaged node.exe, so `npx` failed
with "Access is denied" even with Node.js installed.
pm/user_facing.py moves the store's tool dirs behind the user's own
entries for terminal commands, foreground and background. Hermes's
tools stay as the fallback for a machine without them. Two exceptions:
- Hermes's Python stops just before the Windows app-alias dir when that
dir holds only the Microsoft Store stub (no python3.N.exe), so a
machine without Python still runs a real one.
- On Windows, Git Bash's dirs stay first. They are store dirs too, and
a non-login `bash -c` needs its coreutils ahead of System32's.
Hermes's own operations keep the pinned tools: pm.install.activate is
unchanged, and file search resolves PM's ripgrep (previous commit).
Linux, through LocalEnvironment: `type -ap node python3 rg` lists the
user's Nix copies first and ~/.hermes/tools second. Before this commit
it listed ~/.hermes/tools first.
Conflicts (5 files):
- gateway/run_notifications.py: main lifted completion ownership into a new
GatewayNotificationOwnershipMixin (run_notifications_ownership.py); the branch had lifted the
update watcher into GatewayUpdateNotificationsMixin. The mixin inherits both. Kept both sides
of the completion-event metadata (the branch's automation identities + local display card,
main's proven_session_id / completion_ids), and in the async-delegation group the branch's
authority admission runs first, then main's terminal-parent drop. Neither function main moved
was changed on the branch.
- gateway/run_turn.py: the branch moved _hmwa_resolve_session into run_turn_prepare.py; main's
one changed line there (the resolver receives the proven session id and completion ids) is
ported into run_turn_prepare.py.
- hermes_cli/subcommands/sessions.py: keep both main's lazy cmd_sessions and the branch's
rename/discard parser helper.
- ui-tui: keep both canonicalEn and connectorsEn catalogs; keep the branch's interfaces import
plus main's findSlashCommand import.
tools/process_registry.py already imports from process_registry_notifications at module level, so the drain's function-level import joins it and the file stays at its 2788-line cap on main. No behaviour change.
Build on the attributed delegate-provenance fix. Share ownership validation with durable preflight, keep child-process policy profile-scoped before batching, and retain explicit user boundaries and live handoff semantics.
Conflicts: tests/hermes_cli/test_finite_chat_delegation.py and
tests/tools/test_completed_process_results.py, where main's lint sweep (0006a5e229) added
check=False to subprocess.run calls this branch had rewritten. Kept the branch's test bodies
and carried check=False onto their subprocess.run calls.
#135348 ran ruff's UP037 autofix with ruff.strict.toml's target-version = "py314". On 3.14
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.
- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
`Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
these quotes alone and only strips the two that are genuinely redundant, which this commit
strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.
- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
`Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
these quotes alone and only strips the two that are genuinely redundant, which this commit
strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
(cherry picked from commit 7091436b76e7dd51f2d350b2780fda231103eac6)
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
A managed worker is a per-turn interpreter. `terminal(background=true)`
spawned the child with stdout=PIPE whose only reader was a thread in that
worker. When the worker exited at its turn boundary the read end closed;
the child's next write took SIGPIPE (`broken_pipe`) and died, and the next
worker's `recover_from_checkpoint` (F24) adopted only a bare PID with
"output history unavailable". Reproduced on r6-base with a real managed
turn: a `trap ... PIPE` in the command fired, the output never reached any
interpreter, and turn two's `process_manage wait` returned `not_found`
(probe_b*_base.log), with and without notify_on_complete.
Root fix, no new subsystem: inside a registered worker process
(`is_worker_process()`) a local background spawn writes stdout+stderr to
an owner-only append log under the profile home
(logs/process-output/<proc_id>.log) and its shell records `$?` beside it
(<proc_id>.exit, an EXIT trap - the same contract the env-backend
wrapper already uses). The log path rides the process checkpoint. The
spawner tails the file while it lives; whoever adopts the checkpoint next
(the session's next worker, or the owner at startup) restarts a reader
from offset 0, so output and the recorded exit are collected exactly as a
spawner would, and a process that died past the trap settles `lost`. A
log-backed adoption is decided by its reader, never by the PID-reuse
heuristic, so a recycled PID is still never signalled. PTY mode is not
offered to worker spawns (a PTY master dies with the worker the same
way). Outside a worker nothing changes: the pipe/PTY readers are
untouched. notify_on_complete inside a worker is already declined by the
previous commit (no reader for the worker's completion queue); the
model is told to poll/wait, which now works across the boundary.
Retention: a log is removed only once its recorded exit is older than
the process-results retention (7 days); a still-running quiet process
keeps its log.
Shape: tools/process_registry.py stays at 2,766 lines (three duplicated
comment blocks folded to offset the wiring); the reader lives in the new
tools/process_registry_output_log.py mixin.
Red on r6-base (process_registry.py + _checkpoint.py swapped to r6-base,
output_log module removed):
test_worker_spawned_process_output_and_exit_survive_the_spawner:
AssertionError: {'status': 'not_found', 'error': 'No process with ID proc_d17db6107b4d'}
test_next_managed_turn_reads_the_previous_workers_background_output: FAILED
Green after: 2 passed (exit_code 7, output 'FIRST_42\nSECOND_42\n'
collected by a different interpreter / the next managed turn).
Adjacent: 45 files (tests/tools/test_process_*, completed_process_results,
local_background_child_hang, subagent_process_handoff, terminal_*background*,
zombie_process_cleanup, threaded_process_handle, tests/gateway/test_managed_*,
worker_ledger_tool_execution, worker_agent_execution)
341 passed, 0 failed, 7 skipped.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5462648005
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
_is_wsl_launcher_command and _WSL_LAUNCHER_NAMES move unchanged into
tools/process_registry_wsl.py; process_registry imports the function back.
Code-health FILE_LINES ratchet on PR #106742 (process_registry.py 2793 > 2788).
(cherry picked from commit f35413feae9748a630119fcc08c46d070b22e2cd)
12 conflicted files, resolved in three lanes:
- gateway/run.py: take the branch split; main's tirith removal and spool-replay
ordering ported into run_runtime_init.py / run_bootstrap.py.
- config migrations: main keeps v50 (tirith); the branch's bot-chat timeout removal
becomes v51 (_config_version 51, template + test updated).
- hermes_state_usage.py: main's voice_chat task route threaded through the branch's
owner transaction; worker.persist usage allowlist accepts task.
- tui_gateway/server.py: branch side; main's edits applied where the code now lives
(agent_factory, session_registry). Desktop sessions get the catalog toolset on the
authority path; daemon-run finite CLI turns are not watched turns; lazy session info
reports nous/welcome on the free tier.
- Desktop/Ink: one branch-child spinner fix (main's route-token check); main's
uninstall i18n keys kept, pool keys stay removed; voice_turn forwarded and accepted
by the authority submit (surface_v1.voice_turn).
- chat_ws / PTY keepalive test: main's stricter test kept.
Greptile 4198572811: the guard now finds subprocess/os/asyncio calls as ast.Call nodes, so multi-line calls are checked, and the 27 calls it newly flagged (pixel-art ffmpeg and 26 others) pass stdin=DEVNULL.
* fix(process): a kill's result stands on every backend, and a failed scope stop never counts as stopped
Follow-up to #133434, which fixed these races for local processes only.
Non-local backends (spawn_via_env) settle through _env_poller_loop, which
still wrote the session's final state without the session lock:
- It set exit_code before _finish_exited, so a kill that landed first ended
as killed with the sandbox's exit code. The exit now goes through
_finish_exited alone, and a committed kill keeps its code.
- Its backend-lost path set exited/-1/lost directly, replacing a recorded
kill. It now goes through _finish_exited(reason="lost"), so the kill stands
and the completion is still published by its owner.
- A log delta (or a log-rotation reset) fetched before a kill was applied
after it, so the session's output no longer matched the kill's snapshot.
Both are now dropped once the session has exited, decided under the lock.
A failed systemd scope stop could still count as a successful stop:
- A recovered PID that died between get() and _signal_kill ignored the stop
result and returned a plain already_exited. It now reports
scope_stop_failed.
- kill_all counted already_exited as stopped even when the scope stop
failed, and only looked at _running, so a session that exited after being
picked kept a live scope that no later sweep retried. Every kill path now
stops the scope through _stop_scope, which marks a failed stop pending;
kill_all does not count a result with scope_stop_failed and also retries
finished sessions whose stop is pending.
_log_delta_command moves unchanged into tools/process_registry_env_log.py
(ProcessRegistry._log_delta_command stays as an alias) to keep
process_registry.py under its size cap.
Refs #132358. Both gaps were found by @andrexibiza in the review of #133434.
* fix(process): pruning keeps a session whose scope stop is pending
kill_all retries a failed scope stop through the finished session, but
_prune_if_needed still evicted that session by TTL (measured from process
start, so a long-running process was prunable the moment it finished) or
by capacity, leaving a possibly live scope with no retry target. Sessions
with _scope_stop_pending are now exempt from both until the stop succeeds;
capacity pruning drops the oldest prunable session instead.
Found by the independent review of #133648.
- process_registry._reap_untracked: delegate to _terminate_host_pid with the
session's recorded host_start_time instead of a raw killpg -- pgid == pid
only proves group leadership, and a reaped child recycled onto an unrelated
group leader would still have been signalled. The helper revalidates the
kernel start time and refuses on mismatch, and settles descendants from a
psutil snapshot so no group signal is needed at all.
- browser_tool_lifecycle._legacy_kill_process_tree: in the non-leader path,
snapshot descendants via psutil before proc.kill() and kill each
individually -- a bare proc.kill() left grandchildren holding the capture
pipe's write end, reintroducing the communicate() hang the helper exists
to prevent.
_kill_process_tree fallback and three latent killpg callers resolved
os.getpgid(child) and signalled the result unconditionally. A child that
shares the caller's group resolves to that group, so TERM+KILL took down
the whole Hermes tree; a reaped-and-recycled pid resolves to a foreign
leader's group. Signal the group only when pgid == pid, the rule
deadline.kill_process_tree and _subprocess_compat already use, and fall
back to signalling the direct child otherwise.
Child exit, result finalization, notice publication and output consumption are
separate steps, but several callers treated an earlier one as the last:
- A duplicate _move_to_finished set _completion_event while the owning call was
still before its notice, so a one-shot parent could exit without the follow-up.
Only the call that moved the session out of _running releases waiters now, and
it always does, even when its publish raises.
- _finish_exited ran mark_exited without the session lock, so a kill committed
between its `killed` check and its writes was overwritten with exited/0.
- After a reconcile flips `exited` ahead of a reader still on its final drain,
wait/read_log/kill no longer consume the partial output as the completion,
and poll no longer marks it observed. poll/read_log/kill decide that under
the same lock hold as their snapshot, so a reader finishing in between cannot
make an earlier partial snapshot count as the whole output.
- kill_process ignored a failed systemd scope stop. It now returns an error
with scope_stop_failed whenever the stop fails, including when the root
exited meanwhile (that proves nothing about detached descendants); the
session keeps its unit so a later kill retries the stop. An already-exited
session reports scope_stop_failed too.
Process-tree termination and post-kill survivor checks move into
tools/process_registry_termination.py (ProcessTerminationMixin) to keep
process_registry.py under its size cap. The only change in the move:
_live_descendants logs the traceback of the failure it swallows.
Refs #132358. The races were found by @andrexibiza and @jonpol01 in that thread.
When poll/wait/list saw the direct child exit while the reader was still
behind, the reconcile asked the reader to finish and flipped the session to
exited at once. The reader then stopped after ONE more 4 KiB chunk, so the
rest of the pipe - up to a whole pipe buffer, the job's final lines - was
never read, and the caller had already been handed a snapshot without it
(wait() also marked that snapshot consumed, suppressing the completion).
After a finish request the reader now drains what is already buffered
(zero-timeout select, capped so a grandchild that floods the pipe still
cannot pin it), and the reconcile waits briefly for the reader to publish
before falling back to marking the exit itself.
(cherry picked from commit f8266be8ccc682482f18aaeeccb4d397b5310a9b)
Since systemd 254, `systemd-run --scope` expands $VAR / ${VAR} / $$ in the
command line itself (--expand-environment defaults to yes), so a background
command under a supervised gateway ran rewritten: `$$` became a literal `$`,
`${arr[@]}` became '' with a warning on stderr.
_systemd_scope_argv is the single argv choke point shared by the availability
probe, the pipe/PTY background spawns and restart-safe cron/kanban children,
so pass `--expand-environment=no` there. systemd-run < 254 rejects the
option (and never expanded in scope mode), so the existing cached probe drops
it and re-probes once when systemd-run names it in the rejection — no extra
subprocess on modern hosts and no lost isolation on old ones.
Fixes#132385.
Scoping a supervised dashboard/serve backend's background processes moved them out of the
backend's service cgroup, so they survived a backend restart, but nothing in dashboard/serve
startup recovers the process checkpoint: they kept running while process list/poll/kill could
not find them, and the next spawn dropped their checkpoint record. Recovering them in serve
would conflict with the gateway owning background processes (#106742). Revert to main's
behaviour for dashboard/serve (workers stay in the backend's cgroup and die with it) and leave
escapee cleanup there to the serve-to-gateway cutover.
Tests: the escapee in the hang test printed before the kill deadline, which ended the reader's
blocked read and let the old close finish in time, so the test passed without the fix. The hang
test's escapee is now silent; late-output rejection has its own test. Removing the reader-close
guard now fails the hang test.
The reader checked session.exited and then appended, so a chunk read before
the kill could pass the check, lose the CPU while kill_process snapshotted the
output and set exited, and then land in the killed session (and be streamed)
after the kill returned.
ProcessSession.append_output_if_running() checks exited and appends under the
same session lock the kill holds for its snapshot, and _ingest_output(...,
unless_exited=True) only scans and streams a chunk it admitted. A chunk is now
either in the kill's receipt or dropped. The pipe reader is unchanged.
Tests: a deterministic regression pauses the reader between reading a chunk
and buffering it, runs the real kill, then resumes, and asserts the chunk is
in neither the receipt, the buffer nor the live stream. The escapee spawn
helper now terminates the PTY child it spawned if its readiness check fails.
Review follow-ups on the deferred PTY close:
- The reader can now outlive a kill while a detached descendant holds the
slave open. It keeps draining, but no longer appends to or streams into the
killed session, so the output stays as the kill reported it.
- The live-reader guard in _release_finished_handles is POSIX-only. pywinpty
reads don't block, so Windows closes the PTY on the finish path as before.
Tests:
- The unscoped kill test has the escapee print after the kill and asserts the
killed session never receives that output.
- New test_start_server_marks_the_process_as_backend_host drives the real
web_server.start_server entry point, so removing the mark_backend_host()
call fails a test.
- The live scope test bounds its escapee to 30 s and terminates the PTY child
it spawned on failure (the reparented escapee is left to its bound).