Skip to content

refactor(exec): one stop entry and one terminal source for shell tasks - #2206

Merged
eric8810 merged 20 commits into
mainfrom
dim/2032-exec-stop
Nov 26, 2026
Merged

eric8810 merged 20 commits into
mainfrom
dim/2032-exec-stop

Conversation

@eric8810

@eric8810 eric8810 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #2032

Board A of #2032 after #2002: the persistent shell's tasks get the same owner as every other exec task.

What changed

  • One stop entry. BackgroundExec.stop stops every task. dyn ExecStop, exec_stop.rs, the execStop catalog name and the optional-service reads added by Serve hostPlatform's data methods; withdraw the execHost face #2002 (Session::service_opt, Branch::service_opt, and the internal TimelineContext::public_opt it used) are deleted. session.exec.stop calls BackgroundExec in both profiles, keeps one error mapping and answers exec_task_read for task-fact read failures.
  • ShellSession hands its tasks to BackgroundExec. A runInBackground job and a command that outlives its foreground wait are registered through BackgroundExec.start with the owner task id, after HostPlatform accepted the command. ShellSession's own background table, settlement, hold and synthesized reset_result are gone. The foreground queue and occupancy policy stay; the queue only waits for the occupying command's terminal (a new exec/ended, or wait on the owner record).
  • A shell command's stop is confirmed by its owner. HostPlatform.kill writes Ctrl+C and waits for the command's terminal. Depending on the shell, the interrupt prints the end marker and the command ends with the interrupted line's own status (which can be success when the line continues past the interrupted command), or it aborts the whole wrapper line; a command still running after two seconds cannot end inside the live shell, so the owner signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweep records the command as a reset. The foreground-group signal is what releases the command on macOS, which has no /proc tree for the group walk to reach it, and terminating a shell — a command's stop, a shell kill or a Session close — releases that group the same way before the shell's terminal exists. The stop is bounded and the record is settled only once its terminal exists; BackgroundExec publishes that terminal.
  • One terminal source. Foreground commands return the owner's terminal as the tool result; a handed-off task is published once as exec/ended by BackgroundExec. A task's known exit survives both paths: the result builds its exitCode/signal from the owner's reply fields, so a handed-off shell command and a detached job that ended non-zero report the code even though their terminal is failed, and their summary names it. Before a shell records its own terminal it attempts to release each live job with a known pid by SIGKILL — the job's group and, where the platform can enumerate them, its descendants — and waits up to two seconds, so a job that ignores SIGTERM is gone before its terminal and exec/ended exist; the terminal sweep keeps a SIGKILL backstop. Release is best effort (see Known issues). No layer composes or publishes early.
  • Shell initialization tolerates a startup consumer. The init wrapper is written again until a copy's own start marker and then its end marker reached the shell's tail; each copy carries its own marker pair, so an end marker a startup consumer printed for an earlier copy cannot complete a later one. A shell can spend its first input on a startup consumer (zsh's newuser wizard, for example), and that consumer, a ZDOTDIR, or a platform_home/HOME mismatch no longer loses the initialization. The typed line carries the marker fragments separately, so its echo cannot satisfy the check.
  • No shell output handling in ShellSession. Its retained buffer, the private lossless shell event page (shell_events, ShellEventRequest/ShellEventPage, the per-shell event ring) and the job-marker stripping (job_marker) are removed; HostPlatform already parses the markers and records the terminals. The init no longer registers a command record: it reads the shell's tail, the owner read A.4 names.
  • A dead shell is noticed once its owner record is terminal. ensure_shell checks the owner record of the shell it holds, so a command that arrives after the shell ended and whose record is already terminal spawns the new shell instead of writing into it. The Serve hostPlatform's data methods; withdraw the execHost face #2002 window between the worker releasing the PTY and recording the terminal (the EXIT_STDIO_GRACE read drain, up to about 100 ms) remains: a command in that window still gets Shell is not running from the write and an error result. This change narrows that window; closing it is not part of it.

An ablation pass removed what the change made redundant: ShellSession's timeline, SessionLifecycle and dispatcher fields (BackgroundExec takes the hold and writes the facts; no shell path dispatches), Settlement, BackgroundTask, occupy_tail/occupy_exit, the Notify-based occupancy wake (replaced by the owner's terminal probe), the duplicated shell-exit note formatting, HostPlatform's now-unused private shell event ring, and the unused terminate_job helper. What stays and why: the foreground queue and its occupancy mark stay because serializing commands in one PTY is ShellSession's policy; the pwsh wrapper keeps its detached child and completion file because the owner's job record needs them; BackgroundExec.start stays off the data face because it needs the live process handle.

Callers migrated

  • session.exec.stop (crates/dim-app-server/src/connection.rs).
  • stop_background_task (tests/integration/tests/minimal_execution.rs) reads BackgroundExec instead of dyn ExecStop.
  • No other caller used the removed entries.

Docs

WorkspaceTools.md (exec_stop route, BackgroundExec owner, start callers, stop's terminal and wake), HostPlatform.md (who stops a shell task by id, the shell-command stop, its end-marker outcome and foreground-group signal, the job release and its limits, the tolerant initialization), shell-exec-recovery.md (who registers a shell task, who publishes its terminal), agent-tool-modes.md (stop route), service-faces.md, capability-event-inventory.md (exec fact writers). docs/design/research/1295-host-platform-task-owner.md records #2002's migration steps; its stop/provider paragraphs note that board A replaced that route.

Access-layer allowlist

Base-1 (#2174) landed xtask/access-layer.json. This branch removed the one entry that named an entry it deletes — session-forwarding crates/dim-agent-runtime/src/agent.rs Session::service_opt — in the rebase onto that main, so xtask-check has nothing stale to report. There is no execStop entry and no ShellSession entry.

Known issues

  • The release-before-terminal promise is best effort. The worker only releases jobs whose pid is known and drops kill_job's result: a failed kill is not reported, and a descendant that left the job's group or session can outlive the job's terminal. The terminal sweep keeps a SIGKILL backstop. The new job test covers the POSIX group and /proc tree path; its Windows tree branch runs only where that test runs on Windows, and scripts/test-windows-native.mjs does not list it, so CI does not cover the Windows branch.
  • The Unix Drop foreground-group signal has no fixture. PtyProcessTree::drop signals the terminal's foreground process group on Unix, but no test drops a live PTY tree; removing that call leaves the 29 shell cases green. The terminate path is covered by the Session-close and stop tests.
  • No end-to-end fixture for the pending stop. A shell background job's wrapper always prints its pid marker, so the minimal flow cannot produce a job with an unknown pid; the owner side (bounded task_running, the record staying running, the sweep writing the terminal) is covered by host_platform_flow, and the stop-requested reply is covered by code only. A dedicated fixture would need a test injection point in BackgroundExec.
  • macOS coverage for the command stop. stopping_a_command_that_ignores_the_interrupt_leaves_no_process and closing_a_session_releases_an_occupying_command are selected by scripts/test-macos-native.mjs (their messages branch on cfg!(target_os = "macos")), so the macOS job builds integration_flow and runs both there; this is the proof of the foreground-group path. On Linux the same tests run in the normal suite, where the /proc walk would also reach the command.
  • No forced-cell coverage of the startup consumer. The retry is exercised whenever the shell really runs a consumer: the CI runner's fresh HOME with zsh (the earlier failures), and a fresh local HOME on demand. There is no test that forces a consumer for a shell that has none; the harness gives the test no shell startup directory of its own. The retry's other path — a slow shell — only adds a duplicate idempotent init wrapper.

Behavior notes

  • A stop whose release the owner has not confirmed answers running instead of blocking: the task keeps its record, cleanup and Session hold, and its terminal follows from the confirmed release (cancelled) or the shell sweep (failed{...}). session.exec.stop reports the app error exec_task_running; exec_stop returns a failed result with the same code. An exec/ended is still published exactly once.
  • A stopped shell command ends with the interrupted wrapper line's own status: failed for the interrupted status of a line that stops there (or a reset when the owner had to terminate the shell), and completed when the line continues past the interrupted command (sleep 60 || true). The terminal decides the wake, so a stopped shell command posts its completion notice either way. A stopped runInBackground job and a native command end cancelled and post no completion notice. WorkspaceTools.md states both.
  • The pwsh background job names its stderr file (Standard error: <path>) in the start result, because the ended text now comes from BackgroundExec. Main appended the same note to the ended result (ade859730 crates/dim-agent-capabilities/src/shell_session.rs:1396-1401). Pre-existing and unchanged: the .err path is not registered through register_output, so a model read depends on the file-access rule for unowned files rather than on the shell's registration.
  • a_call_that_converts_before_its_output_writes_only_the_command_output now prefixes sleep 0.1: with timeoutMs: 0 the command could finish before the first wait under load, which made the conversion it tests a race.

Testing

  • cargo test -p dim-agent-integration-tests --test integration_flow minimal_execution — 30 passed, repeated 3 times; cargo test -p dim-agent-capabilities --lib — 86 passed (adds an_init_copy_completes_only_after_its_own_start_marker). Adds a_handed_off_command_keeps_its_exit_code and a_detached_job_keeps_its_exit_code (both fail without the exit fix), closing_a_session_releases_an_occupying_command (the same stubborn command, closed with the Session), stopping_a_command_that_ignores_the_interrupt_leaves_no_process (a converted command that ignores INT, TERM and HUP; its pid is gone after the stop), a_startup_consumer_cannot_skip_the_init (a .zshrc that reads the first wrapper line; the shell still unsets HISTFILE), a_slow_shell_still_initializes (a zsh preexec slower than the retry; fails before the every-copy watch) and a_term_ignoring_job_is_gone_before_its_terminal (a job that ignores SIGTERM exits with its shell; the test asserts the process is not alive at the moment its exec/ended is observed, then that it stays gone, and it fails without the release confirmation) and a_call_after_the_occupying_command_ends_runs. stop_an_occupying_command_returns_and_the_shell_keeps_working now asserts a failed terminal and that the next call runs, both true whether the shell printed the end marker or had to be reset.
  • cargo test -p dim-agent-integration-tests --test integration_flow local_execution — 42 passed, 1 ignored.
  • cargo test -p dim-agent-capabilities --test capabilities_flow host_platform_flow — 32 passed; adds a_job_without_a_pid_stays_running_until_the_shell_sweep (kill answers task_running after two seconds, the record stays running, the shell sweep writes failed{shell_reset}); the 85 and 692-test suites pass with 5 ignored.
  • cargo clippy --workspace --all-targets --locked -- -D warnings, cargo run --locked -p xtask -- check, cargo fmt --all -- --check, node scripts/adr-check.mjs --base origin/main — pass.
  • new_persistent_shells_and_environment_refresh_use_current_preferences with a fresh HOME (zsh's newuser wizard runs) passes 3 of 3; it failed every run before the tolerant init.
  • CI at 0f015ba26 (run 45742432370): changes, windows-cli, macos-native and ci-ok passed. verify (linux) failed two managed_oauth_flow tests with Elapsed(()) (no shell path involved) and passed on the rerun.

@zerob13 zerob13 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One stop owner and one terminal publisher are the right direction. Two behavior regressions block this revision:

  1. Stop must return a bounded, truthful result while the owner retains unresolved cleanup. In the shared wait, an unconfirmed stop can turn into a terminal wait with no deadline. Conversely, the shell reset path can publish a terminal when termination has not confirmed release. Preserve the #2002 invariant for both tool and App Server: return a bounded, explicit unconfirmed result when needed, keep tracking and the Session hold until release is known, then emit the owner's real terminal exactly once. A confirmed reset may be a failed terminal rather than cancelled.
  2. Preserve the numeric exit code for confirmed shell failures. A handed-off command or detached job can have a known nonzero owner exit code and a Failed terminal. The shared result translator drops that code, so event, notice and Stop result lose information visible before the refactor. Verify a confirmed nonzero exit retains its code after handoff.

The Linux job for this exact merge also failed the first-shell preference case and two managed OAuth tests. Those failures remain unattributed; Windows/macOS selected jobs passed and do not establish the unconfirmed-stop invariant. The two findings above are from static review.

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 6c96d21fe56507eaf512e51c31459de235eef482, round 1. The only change since 6f44b530 is the test-only commit that adds the selected shell to the preference assertion; the code and docs are unchanged, so I rechecked the full main...head diff and reran the relevant flows at this head.

The refactor's goal holds. BackgroundExec is the one stop entry and one terminal publisher for native commands, shell jobs and converted shell commands; the removed dyn ExecStop, exec_stop.rs, the optional-service reads and the private shell event page have no callers; ShellSession no longer writes exec facts, the init command waits for its owner terminal, and the covered flows show one exec/ended per admitted task. Two blocking behavior regressions from review 6067192577 still reproduce at this head, and the new stop test still fails on macOS.

Blocking

P1: a shell stop publishes a terminal and releases its Session hold while termination is unconfirmed, and the owner wait has no deadline.

Problem: HostPlatform::kill for a shell command writes Ctrl+C, waits two seconds, then terminates the shell (crates/dim-agent-capabilities/src/host_platform.rs:1236-1258). The stopped command and every job in that shell then get their terminals from ShellTask::sweep (host_platform.rs:4666-4712). The sweep sends one SIGTERM to a job's process group through terminate_job (:3574-3585) and ignores the result; it never uses kill_job and its release wait (:3622-3650). The deleted per-orphan shell-exit path used host.kill, which reaches kill_job and reported an unconfirmed release (main:crates/dim-agent-capabilities/src/shell_session.rs:717-830); this PR makes the sweep the only terminator, so the weaker behavior becomes the contract. TaskRecord::finish runs that sweep (crates/dim-agent-capabilities/src/host_platform/task.rs:125-131), and BackgroundExec appends exec/ended and settles the host task immediately after its supervisor returns (crates/dim-agent-capabilities/src/workspace_tools/background.rs:440-453). The Session hold drops even when a process is still alive, and the record is released, so no later stop can reach it.

The wait is also unbounded when the owner cannot confirm. wait_owner and stop_owner ignore a failed HostPlatform::kill and call wait with timeout_ms: None (background.rs:245-302), and BackgroundExec::stop then waits for the ended watch with no deadline (:709-713). The deleted shell stop returned at once with an explicit stop-requested or exec_terminate_failed result and kept tracking (main:crates/dim-agent-capabilities/src/shell_session.rs:1511-1620), so this regresses both boundedness and truthfulness. When a job release is eventually confirmed, observe_job_release finishes it Cancelled with TaskFailure::TerminateFailed (host_platform.rs:3587-3617), but background_result matches WaitStatus::Cancelled first and returns Command cancelled by user. with no failure code (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2209-2214, :2273). The tool result, the event and the notice then claim a confirmed cancellation that the record did not confirm, contrary to docs/architecture/rust-agent/plugins/WorkspaceTools.md:144.

Failure scenario, reproduced at this head: start runInBackground bash -c 'trap "" TERM; echo $$ > pidfile; while true; do sleep 1; done', then a foreground sleep 60 with timeoutMs: 100, then stop the converted command under zsh. The stop returned in 2.03 s with Failed "shell reset"; the swept job's exec/ended was published Failed "shell reset"; the job process was still alive afterwards, and its record was terminal and settled. The same job survived a shell exit 0 with a terminal Failed "shell exited". A job whose pid never arrives or whose group cannot be released leaves the second wait pending, so exec_stop and the App Server call do not return and the held Session blocks idle unload.

Fix: in the sweep, terminate job children through kill_job and its release wait, and when release is still unconfirmed keep the record live and report that instead of finishing it. Bound wait_owner and stop: return an explicit unconfirmed result (for example exec_terminate_failed) when the owner has not confirmed, keep tracking and the hold until release is known, then publish the owner's real terminal exactly once. In background_result, surface reply.failure for a Cancelled record instead of erasing it.

P2: a confirmed nonzero exit code is dropped after handoff and for detached shell jobs.

Problem: settled_from_reply builds a CommandExit only for WaitStatus::Exited or WaitStatus::Signaled (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2199-2203). The owner records a shell command or job with a known nonzero code as TaskStatus::Failed with exit_code: Some(code) (crates/dim-agent-capabilities/src/host_platform.rs:4797-4827, :4838-4911), so background_result takes the settled.failure.is_some() branch (exec.rs:2220-2229), never reaches the exit branch, and insert_exit receives None (:2273). The event, notice and BackgroundExec.stop result lose the code.

Failure scenario, reproduced at this head: execute sh -c 'sleep 0.6; exit 7' with timeoutMs: 100; the resulting exec/ended, its completion notice, BackgroundExec.wait and a stop of the same record all report Failed "command failed" with no exitCode in the structured content. A runInBackground sh -c 'sleep 0.4; exit 9' behaves the same. The foreground failing_command_reports_exit_code still reports "exit code 3", and the old shell settlement rendered [Command finished with exit code N] (main:crates/dim-agent-capabilities/src/shell_session.rs:1873-1949). So a code the owner knows is lost exactly when the task is handed off or detached.

Fix: derive the exit from reply.exit_code and reply.signal regardless of status, do not let the failure branch mask a known code, include exitCode in the structured result and the code in the summary and note. Add a handoff case and a detached job case with a nonzero code.

P2: the new stop test fails on macOS.

Problem: stop_an_occupying_command_returns_and_the_shell_keeps_working asserts the result contains "shell reset" (tests/integration/tests/minimal_execution.rs:980), but the harness forces /bin/bash (:154). macOS bash 3.2 continues the wrapper line after Ctrl+C, the end marker prints with the interrupted status, and the owner terminal is Failed "command failed", not a reset. The test comment (:949-951), the code comment (crates/dim-agent-capabilities/src/host_platform.rs:50-53) and docs/architecture/rust-agent/plugins/HostPlatform.md:29 state a premise that is false for this shell.

Failure scenario: at this head on Darwin 27.2.0 the test fails 3 of 3 isolated runs at line 979; the full minimal_execution suite is 22 passed, 1 failed. verify (linux) passes it because its bash aborts the line, and macos-native does not run minimal_execution, so CI cannot see it. The product path is correct: the stop returns immediately, the record is Failed, and the next call runs in the same shell.

Fix: assert the invariant (the stop returns a terminal, the record is Failed, the next call runs) and keep the "shell reset" assertion for a shell that is actually terminated, or select zsh and skip when absent. Reword the three comments to say the end marker may print after the interrupt and the shell is terminated only when the command is still running after the wait.

Non-blocking

P3: BackgroundExec::stop's doc comment describes the old terminal. It says a running task "ends cancelled and does not wake" (crates/dim-agent-capabilities/src/workspace_tools/background.rs:670-672). A converted shell command now ends Failed and posts a notice, as WorkspaceTools.md says. start's "terminated and reaped" (:349-350) is also stronger than stop_owner can guarantee. Update both.

P3: the two new behaviors have no tests for the cases that fail. shell_exit_kills_background_jobs uses a TERM-killable sleep (tests/integration/tests/minimal_execution.rs:1274-1322), so it passes while a TERM-ignoring job survives; no test covers a known exit code after handoff. Add both once the behavior is fixed.

P3: access-layer rebase after #2174. #2174's current head (357e4e84) adds Session::service_opt (crates/dim-agent-runtime/src/agent.rs:701) and an allow entry at xtask/access-layer.json:526; this PR deletes the method, and the check fails for an entry that matches fewer occurrences (xtask/check/src/access.rs:125-160). The rebase must delete that entry, and because this PR also retires the execStop catalog name, it should add that name to the file's removed list (xtask/check/src/access.rs:30-36, xtask/src/catalog.rs:94-113). The PR body mentions the allow entry but not the removed name.

Cross-PR and main

git diff --check is clean. Merge-tree with origin/main 8dbcec620, #2178 b1387a0b, #2174 357e4e84, #2202 6867cb64 and #2208 7b1103ad is clean. #1881 ff9825d2 conflicts with main in docs/design/plugins/Report.md, which this PR does not touch. #2197 a27c9af0 (draft) conflicts with this PR in crates/dim-app-server/src/connection.rs; it still resolves dyn ExecStop first and registers the execStop face, so its rebase must route session.exec.stop to BackgroundExec and drop the face.

At 6c96d21f, run 45734131432 passes: changes, verify (linux), macos-native, windows-cli and ci-ok all succeed; path-filtered jobs are skipped. At 6f44b530, verify (linux) failed the first-shell preference case (235 passed, 1 failed) and two managed_oauth_flow tests (499 passed, 2 failed). The preference test is not attributable to this diff: the first command spawns a fresh shell, and the only change in that function is the aliveness probe for an existing shell; it passes 5 of 5 local runs at this head, passed on the 3c611b6e retry, and passed in the 6c96d21f run. The new assertion prints the selected shell, so a recurrence is now discernible. The OAuth failures are outside this PR's code.

Verification

Isolated HOME, TMPDIR and XDG under the data directory, LC_ALL=en_US.UTF-8; temporary probes were reverted and the worktree is clean at the head. No residual processes.

  • minimal_execution at this head: 22 passed, 1 failed (the macOS assertion above). The stop test failed 3 of 3 isolated runs.
  • new_persistent_shells_and_environment_refresh_use_current_preferences: 5 passed of 5.
  • host_platform_flow: 29 passed.
  • Probes: zsh stop of a converted sleep 60 returned in 2.03 s with Failed "shell reset" and the next call ran in a new shell; the handoff command and detached job lost their exit codes; a TERM-ignoring job survived exit 0 and a zsh stop-triggered reset while its exec/ended was published.

Unverified: the Windows and pwsh stop path and the moved stderr path; a forced kill-unconfirmed hang (code path only); the full workspace suite, clippy and xtask check locally; the head CI run's logs beyond its job conclusions.

Verdict: REQUEST_CHANGES.

}
// The interrupt aborted the wrapper line before its end marker
// printed, so the command cannot end inside the live shell.
// Terminating the shell sweeps the command to its terminal.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: selecting the reset terminal here is where the release guarantee is lost. After command.shell.terminate(), the stopped command and every job in that shell get their terminals from ShellTask::sweep (crates/dim-agent-capabilities/src/host_platform.rs:4666-4712); for a job child the sweep sends one SIGTERM through terminate_job (:3574-3585), ignores the result, and never uses kill_job and its release wait (:3622-3650). BackgroundExec then appends exec/ended and settles the record (crates/dim-agent-capabilities/src/workspace_tools/background.rs:440-453), so the Session hold drops and the process becomes untracked. Reproduced at this head: with zsh, a runInBackground TERM-ignoring job plus a converted sleep 60; the stop returned Failed "shell reset" in 2.03 s, the job's exec/ended was published Failed "shell reset", and the job process was still alive. Use kill_job and its release wait in the sweep, and keep an unconfirmed record live and tracked instead of finishing it. See the body for the unbounded wait when kill cannot confirm.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 1a8f542. The new zsh -f change touches only the shell spawn args; the stop path is unchanged. HostPlatform::kill still writes Ctrl+C, waits two seconds and terminates the shell (crates/dim-agent-capabilities/src/host_platform.rs:1236-1257); the sweep still sends one SIGTERM through terminate_job and ignores it (:4704-4707) and finishes the jobs (:4712-4720); BackgroundExec still appends exec/ended and settles before dropping the hold (crates/dim-agent-capabilities/src/workspace_tools/background.rs:437-453); wait_owner and stop_owner still use timeout_ms: None (:245-302); stop still waits for the ended watch with no deadline (:709-711). Reproduced at this head under zsh with a fresh HOME, on the new -f path: the stop returned in 2.03 s with Failed "shell reset", the TERM-ignoring job's exec/ended was published Failed "shell reset", and the job process was still alive. Not fixed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The job half is fixed at this head: with zsh and a fresh HOME, a runInBackground TERM-ignoring job plus a converted sleep 60 stopped in 2.05 s as Failed "shell reset", the job's exec/ended was published, and the job process was gone. The command half remains. For a shell command the second wait at HostPlatform::kill observes only the record that ShellTask::sweep finishes, and the sweep signals only Job children. On macOS the command runs in its own foreground group under job control and kill_tree has no descendant walk, so sh -c 'echo $$ > pidfile; trap "" INT TERM HUP; while true; do sleep 1; done' was still alive when BackgroundExec.stop returned Failed "shell reset" in 2.03 s and the hold dropped. The release loop also ignores kill_job's error and confirms only the process group, so a setsid descendant survives its job's terminal. Details are in the new inline comments.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3c4ef46e9.

  • The shell worker releases its jobs before it writes the shell terminal: for each child record that is still live, it takes the owner pid and runs kill_job (POSIX: SIGKILL the process group and the /proc descendants; Windows: terminate_tree) and waits for it (crates/dim-agent-capabilities/src/host_platform.rs:4582). The terminal sweep keeps a SIGKILL backstop through native::kill_tree instead of one unconfirmed SIGTERM (:4696); the unused terminate_job is deleted, and kill_job's doc no longer says it is only for a job that outlived its shell.
  • New test a_term_ignoring_job_is_gone_before_its_terminal (tests/integration/tests/minimal_execution.rs:1324): a runInBackground sh -c 'trap "" TERM; …; sleep 60', then exit 7. It asserts !alive(pid) at the moment the job's exec/ended is observed, then that it stays gone. I temporarily restored the old behavior (no worker release, SIGTERM sweep) and the test fails; with this head it passes 5 solo runs and in the suite.

Known item, also in the PR body: the worker drops kill_job's result, so "confirm, then write the terminal" is best effort, not a strict guarantee — a platform error or a process that survives SIGKILL leaves only the sweep's SIGKILL. The test covers the POSIX process-group and /proc tree path; its Windows tree branch runs only where that test runs on Windows, and scripts/test-windows-native.mjs does not list it, so CI does not cover the Windows branch.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The job half is fixed at this head and the new !alive assertion is sound: the release runs before worker_record.finish, and kill_job waits for the group, so a pid alive after exec/ended means the confirmation failed. The command half of the P1 remains; see the thread on host_platform.rs:1254.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3b66bb30. HostPlatform::kill for a ShellCommand now calls command.shell.kill_foreground_group() before terminate() (crates/dim-agent-capabilities/src/host_platform.rs:1255); the helper signals the foreground group and waits up to two seconds (:3560-3566, :3597-3611). Verified at 45c02dd4: stopping_a_command_that_ignores_the_interrupt_leaves_no_process passes and fails with the call removed, and macos-native CI is green. Withdrawing the command half of the P1. A separate non-blocking note covers the shell stop/close path.

assert_eq!(ended.task_id, task_id);
assert_eq!(ended.status, ExecStatus::Failed);
assert!(
text(&ended.result).contains("shell reset"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: this assertion does not hold on macOS. The harness forces /bin/bash (tests/integration/tests/minimal_execution.rs:154), and bash 3.2 continues the wrapper line after Ctrl+C: the end marker prints with the interrupted status, HostPlatform.kill returns on its first wait, and the result is Failed "command failed" with preview ^C, not "shell reset". At this head it fails 3 of 3 isolated runs, and the full minimal_execution suite is 22 passed, 1 failed. verify (linux) passes because its bash aborts the line, and macos-native does not run minimal_execution. Assert the invariant (the stop returns a terminal, the record is Failed, the next call runs), and keep "shell reset" for a shell that is actually terminated, or select zsh and skip when absent. The comment above (:949-951) and the same premise in crates/dim-agent-capabilities/src/host_platform.rs:50-53 and docs/architecture/rust-agent/plugins/HostPlatform.md:29 are false for this shell.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 1a8f542. The test is unchanged and still asserts "shell reset" (tests/integration/tests/minimal_execution.rs:979) with the harness forcing /bin/bash (:154). The new zsh -f match changes only zsh arguments, so the bash harness and the premise are unaffected. At this head it fails 3 of 3 isolated runs with Failed "command failed" and preview ^C; verify (linux) passes it because its bash aborts the line, and macos-native does not run minimal_execution. Not fixed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 0f015ba. The test no longer asserts "shell reset"; it asserts a Failed terminal and that the next call runs, and its comment covers both shell behaviors. It passed 3 of 3 isolated runs on Darwin 27.2.0 with the harness's /bin/bash, and the Linux job passes it too. Withdrawing this finding.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3c4ef46e9.

stop_an_occupying_command_returns_and_the_shell_keeps_working (tests/integration/tests/minimal_execution.rs:956) now asserts only what holds for both interrupt outcomes:

  • the stop returns a failed terminal for the task id;
  • the next execute runs (echo after-stop stays in the result).

The doc comment states both owner terminals: the shell may print the end marker after Ctrl+C, so the command ends with its interrupted status, or it aborts the wrapper line and the owner terminates the shell after two seconds, which the sweep records as a reset. The hard "shell reset" assertion is gone, so the test no longer depends on the harness's bash version or on SHELL forcing /bin/bash (:154). Locally 24 passed ×3 at this head.

No known issue for this one.

log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a
timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited
shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a stop is pending answers `task_running`. Command and job logs stay under the output directory the caller gives the owner; the
shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal; because the interrupt aborts the wrapper line before its end marker, a command that does not end within two seconds leaves the owner no way to end it inside the live shell, so `kill` terminates the shell and its terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the mechanism is shell-specific. For macOS bash 3.2 the interrupt does not abort the wrapper line: the command's end marker prints with the interrupted status and kill returns from its first wait without terminating the shell. Only a command still running after two seconds causes the shell termination and a reset. State it that way and correct the same premise at crates/dim-agent-capabilities/src/host_platform.rs:50-53.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 1a8f542. The new zsh paragraph at docs/architecture/rust-agent/plugins/HostPlatform.md:165 is about startup files, not the interrupt. Line 29 and crates/dim-agent-capabilities/src/host_platform.rs:50-53 still state that the interrupt aborts the wrapper line and the two second wait is the universal mechanism. For macOS bash 3.2 the end marker prints after the interrupt and kill returns from its first wait without terminating the shell; only a command still running after two seconds causes the reset. Not fixed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 0f015ba. HostPlatform.md:29 and host_platform.rs:50-53 now say that some shells print the end marker after the interrupt and that only a command still running after two seconds causes the shell termination and reset. Withdrawing this finding.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3c4ef46e9.

The universal claim is gone from the three places:

  • docs/architecture/rust-agent/plugins/HostPlatform.md:29 now says the interrupt's outcome depends on the shell: some print the end marker after Ctrl+C, the command ends with its interrupted status and kill returns from that wait; only a command still running after the two-second wait makes the owner terminate the shell, whose sweep records a reset.
  • SHELL_COMMAND_STOP_WAIT_MS's doc comment (crates/dim-agent-capabilities/src/host_platform.rs:54) and the comment in HostPlatform::kill say the same, instead of asserting that the interrupt aborts the wrapper line.
  • The same page now also states the new job-release promise (:40): before a shell writes its terminal it releases every live job with a SIGKILL escalation and waits for it, and the sweep keeps a SIGKILL backstop.

Known items are the same as the two replies above: the release-before-terminal promise is best effort (kill_job's result is dropped) and the Windows tree branch of that test is not in CI.

@zerob13 zerob13 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous two conditions remain open at 1a8f542107e66ba1ebc6e340d04db34b95f9d412:

  1. When the owner cannot confirm Stop, both callers need a bounded, explicit unresolved result. Keep cleanup and the Session hold until real terminal confirmation, then publish exactly one terminal.
  2. A known nonzero exit status must survive handoff in the terminal event, completion notice, and Stop reply.

New compatibility regression: the zsh launch guard checks only the host home before adding -f. With isolation off and an inherited ZDOTDIR containing .zshrc, a user with no zsh files in home silently loses PATH changes and shell functions. Verify that a fresh unconfigured home avoids the wizard and that first command startup still honors a configured ZDOTDIR. See the zsh startup contract.

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 1a8f542107e66ba1ebc6e340d04db34b95f9d412, round 2. Since 6c96d21f two commits landed: 55636b70 shows the shell's output when initialization times out, and 1a8f5421 keeps zsh's newuser wizard out of the first command by starting zsh with -f when the platform home has none of .zshenv, .zprofile, .zshrc or .zlogin. The three blocking findings in review 6067350223 remain. The init failure seen at 55636b70 is fixed on the default path: with a fresh HOME the preference flow passes 3 of 3 locally. The new fix chooses -f from platform.home rather than the shell's HOME, so it can skip the user's startup files when the two differ.

Blocking

P1: a shell stop publishes a terminal and releases its Session hold while termination is unconfirmed.

HostPlatform::kill for a shell command writes Ctrl+C, waits two seconds, then terminates the shell (crates/dim-agent-capabilities/src/host_platform.rs:1236-1257). The stopped command and every job in that shell get their terminals from ShellTask::sweep (:4676-4721). The sweep sends one SIGTERM to a job's process group through terminate_job (:4704-4707) and ignores the result; it never uses kill_job and its release wait (:3622-3650). BackgroundExec then appends exec/ended and settles the host task (crates/dim-agent-capabilities/src/workspace_tools/background.rs:437-453), so the Session hold drops and the record is released while the process may still be alive. wait_owner and stop_owner ignore a failed kill and wait with timeout_ms: None (:245-302), and BackgroundExec::stop waits for the ended watch with no deadline (:709-711). When a job release is eventually confirmed, observe_job_release finishes it Cancelled with TaskFailure::TerminateFailed (host_platform.rs:3587-3617), but background_result matches WaitStatus::Cancelled first and returns Command cancelled by user. with no failure code (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2210-2214).

Reproduced at this head on the new -f path: with zsh and a fresh HOME, a runInBackground bash -c 'trap "" TERM; echo $$ > pidfile; while true; do sleep 1; done' job plus a foreground sleep 60 with timeoutMs: 100, then stop the converted command. The stop returned in 2.03 s with Failed "shell reset"; the job's exec/ended was published Failed "shell reset"; the job process was still alive afterwards; the record was terminal and settled. A job whose pid never arrives or whose group cannot be released leaves the second wait pending, so the App Server call does not return and the held Session blocks idle unload.

Fix: terminate job children in the sweep through kill_job and its release wait, and keep an unconfirmed record live and tracked. Bound wait_owner and stop; return an explicit unconfirmed result when the owner has not confirmed, and publish the owner's real terminal once. In background_result, surface reply.failure for a Cancelled record.

P2: a confirmed nonzero exit code is dropped after handoff and for detached shell jobs.

settled_from_reply builds a CommandExit only for WaitStatus::Exited or WaitStatus::Signaled (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2199-2203). The owner records a shell command or job with a known nonzero code as TaskStatus::Failed with exit_code: Some(code) (crates/dim-agent-capabilities/src/host_platform.rs:4807-4838, :4848-4888, :4890-4921), so background_result takes the failure branch (exec.rs:2220-2229), never reaches the exit branch, and insert_exit receives None (:2273, :2282-2289).

Reproduced at this head: execute sh -c 'sleep 0.6; exit 7' with timeoutMs: 100, and runInBackground sh -c 'sleep 0.4; exit 9'. Both resulting exec/ended results were Failed "command failed" with no exitCode in the structured content. The foreground failing_command_reports_exit_code still reports "exit code 3". A code the owner knows is lost exactly when the task is handed off or detached.

Fix: derive the exit from reply.exit_code and reply.signal regardless of status, do not let the failure branch mask a known code, and add exitCode to the structured result and the summary. Add a handoff case and a detached job case with a nonzero code.

P2: the new stop test fails on macOS.

stop_an_occupying_command_returns_and_the_shell_keeps_working asserts the result contains "shell reset" (tests/integration/tests/minimal_execution.rs:979), but the harness forces /bin/bash (:154). macOS bash 3.2 continues the wrapper line after Ctrl+C, the end marker prints with the interrupted status, and the owner terminal is Failed "command failed", not a reset. The test comment (:949-951), the code comment (crates/dim-agent-capabilities/src/host_platform.rs:50-53) and docs/architecture/rust-agent/plugins/HostPlatform.md:29 state a premise that is false for this shell. The new zsh -f match changes only zsh arguments, so it does not alter this test's bash harness or its premise.

At this head on Darwin 27.2.0 the test fails 3 of 3 isolated runs at line 979 with Failed "command failed" and preview ^C; the product path is correct: the stop returns, the record is Failed, and the next call runs in the same shell. verify (linux) passes it because its bash aborts the line, and macos-native does not run minimal_execution.

Fix: assert the invariant (the stop returns a terminal, the record is Failed, the next call runs) and keep "shell reset" for a shell that is actually terminated, or select zsh and skip when absent. Reword the three comments.

P2: the zsh -f decision uses the platform home, not the shell's HOME.

start_shell chooses -f when zsh_startup_files(&self.home) is false (crates/dim-agent-capabilities/src/host_platform.rs:4405), but the shell is spawned with self.env, whose HOME is unchanged (:4408-4420). HostPlatformConfig.home is the reported user home (:2332-2335), and ServerConfig.platform_home documents that a host with an isolated home sets it (crates/dim-app-server/src/lib.rs:85-89). The process HOME, which zsh reads for its startup files, can differ from platform.home, so the check and the shell disagree.

Failure scenario: platform.home is an empty isolated directory and the process HOME has a .zshrc. zsh starts with -f and the .zshrc is skipped. Reproduced at this head: platform.home pointed at an empty directory, the shell HOME held export PROBE_RC=loaded, and execute printf 'rc=%s' "$PROBE_RC" returned rc=. Without the new match the rc loads. Conversely, platform.home has a .zshrc but the shell HOME is fresh: no -f, the wizard consumes the init line and the first command fails, which is the failure this commit intended to fix. The check also ignores ZDOTDIR, which can move zsh's startup files, so no path check in start_shell mirrors zsh's lookup.

Fix: prefer a tolerant init that cannot lose a command to a startup consumer, for example prefix the wrapper line with a sacrificial character, or accept the init when the end marker appears in the shell tail. If the startup check stays, read HOME from self.env and account for ZDOTDIR, and add a test where the two homes differ. The new doc paragraph at HostPlatform.md:165 should name the home the check uses.

Non-blocking

P3: BackgroundExec::stop's doc comment describes the old terminal. It says a running task "ends cancelled and does not wake" (crates/dim-agent-capabilities/src/workspace_tools/background.rs:670-672). A converted shell command now ends Failed and posts a notice. start's "terminated and reaped" (:349-350) is stronger than stop_owner can guarantee. Update both.

P3: the new behaviors still have no tests for the cases that fail. shell_exit_kills_background_jobs uses a TERM-killable sleep (tests/integration/tests/minimal_execution.rs:1275), so it passes while a TERM-ignoring job survives; no test covers a known exit code after handoff; the zsh -f branch has no dedicated test, and the preference flow exercises it only when the process HOME is fresh. Add them with the fixes.

P3: the interrupt premise remains in the docs and code comment. docs/architecture/rust-agent/plugins/HostPlatform.md:29 and crates/dim-agent-capabilities/src/host_platform.rs:50-53 still say the interrupt aborts the wrapper line and the two second wait is the universal mechanism. For macOS bash 3.2 the end marker prints after the interrupt and kill returns from its first wait without terminating the shell; only a command still running after two seconds causes the reset. The new zsh paragraph at HostPlatform.md:165 does not correct this.

P3: access-layer rebase after #2174. #2174's current head a05a4423 adds an allow entry for Session::service_opt at xtask/access-layer.json:526 (the method is on main at crates/dim-agent-runtime/src/agent.rs:701); this PR deletes the method, and the check rejects an entry that matches fewer occurrences (xtask/check/src/access.rs:125-160). The rebase must delete that entry. Because this PR retires the execStop catalog name, it should also add that name to the file's removed list (xtask/check/src/access.rs:30-36, xtask/src/catalog.rs:94-113); the current list is empty. The PR body mentions the allow entry but not the removed name.

Init timeout and zsh change

The 55636b70 message is sound as a diagnostic: the shell tail is bounded to 50 KiB and 2000 lines (crates/dim-agent-capabilities/src/host_platform/output.rs:152-160), the init command publishes no exec/started or exec/ended, and the shell is stopped after the tail is read. The 1a8f5421 change removes the default-path wizard failure: with a fresh HOME and zsh, new_persistent_shells_and_environment_refresh_use_current_preferences passes 3 of 3 locally, and the shell starts with -f. The change does not touch the stop, sweep or exit-code paths, and the P1 and P2 probes reproduce above. Its remaining problem is the home source in the new P2.

Cross-PR and main

git diff --check is clean. Merge-tree with origin/main 8dbcec620, #2178 b1387a0b, #2174 a05a4423, #2202 6867cb64, #2208 7b1103ad and #2209 d9e79ebb is clean. #1881 ff9825d2 conflicts with main in docs/design/plugins/Report.md, which this PR does not touch. #2197 conflicts with this PR and with main in crates/dim-app-server/src/connection.rs; its current head 6d99623e still resolves dyn ExecStop first (connection.rs:1627-1643) and registers the execStop face (lib.rs:1690), and the brief's a27c9af0 has the same route, so its rebase must route session.exec.stop to BackgroundExec and drop the face.

CI

At 1a8f5421, run 45738937110 passes: changes, verify (linux), macos-native, windows-cli and ci-ok all succeed, and new_persistent_shells_and_environment_refresh_use_current_preferences passed in verify (linux). At 55636b70, run 45736662896 failed that test with the init timeout; at 6c96d21f, run 45734131432 passed.

Verification

Isolated HOME, TMPDIR and XDG under the data directory, LC_ALL=en_US.UTF-8; probes were reverted; the worktree is clean at the head; no residual processes.

  • minimal_execution at this head: 22 passed, 1 failed (the macOS stop test).
  • minimal_execution stop test at this head: 3 of 3 isolated runs failed at line 979 with Failed "command failed" and preview ^C.
  • P1 probe under zsh on the -f path: the stop returned in 2.03 s with Failed "shell reset"; the TERM-ignoring job's exec/ended was published Failed "shell reset"; the job process was alive; cleanup was SIGKILL and no residual process.
  • P2 probe: handoff exit 7 and detached exit 9 both published Failed "command failed" with no exitCode.
  • Preference flow with a fresh HOME and zsh: 3 of 3 runs passed, exercising the -f branch.
  • host_platform_flow at this head: 29 passed.
  • Home mismatch probe: an empty platform.home plus a shell HOME with a .zshrc skipped the rc (rc= empty).
  • Merge-tree and git diff --check results are above.

Unverified: a Linux local run of the zsh wizard (CI is the evidence); the Windows and pwsh stop path and the moved stderr path; a forced kill-unconfirmed hang (code path only); the full workspace suite, clippy and xtask check locally.

Verdict: REQUEST_CHANGES.

// zsh's newuser module runs a startup wizard when the user has
// none of its startup files, and that wizard reads the first
// command as its answer.
ShellEdition::Zsh if !zsh_startup_files(&self.home) => vec!["-i", "-f"],

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: this check reads self.home, but the shell inherits HOME from self.env (:4408-4420), and HostPlatformConfig.home can differ from the process HOME (crates/dim-app-server/src/lib.rs:85-89, ServerConfig.platform_home). With platform.home empty and the shell HOME holding a .zshrc, zsh starts with -f and the user's startup file is skipped; at this head printf 'rc=%s' "$PROBE_RC" returned rc= with export PROBE_RC=loaded in the shell HOME's .zshrc. With platform.home holding the .zshrc and a fresh shell HOME, no -f is added and the wizard still consumes the init line. The check also ignores ZDOTDIR. Prefer a tolerant init that cannot lose a command to a startup consumer (a leading sacrificial character, or accepting the init when the end marker appears in the tail); if this check stays, read HOME from self.env and account for ZDOTDIR, and add a test where the two homes differ. The new doc line at docs/architecture/rust-agent/plugins/HostPlatform.md:165 should name the home the check uses.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The zsh -f decision and its home check are gone at 0f015ba, so platform.home no longer selects the shell's startup files. Verified with an isolated HOME: a fresh HOME with the shell HOME's .zshrc loads that rc, and with ZDOTDIR set and a fresh HOME the ZDOTDIR .zshrc loads. Withdrawing this specific finding. The replacement retry has its own holes: it accepts an end marker without the start marker, so a consumer that exits after consuming a prefix of the wrapper can skip the init (reproduced with a 177-character consumer: BANGHIST on and HISTFILE set), and the real wizard did not exit, timing out the init, in 5 of 5 forced runs. See the new inline on shell_session.rs:598.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3c4ef46e9.

The home check is gone; the init is now tolerant instead of choosing zsh arguments.

  • ShellSession::send_initial (crates/dim-agent-capabilities/src/shell_session.rs:558) writes the init wrapper and rewrites it every 1 s, for at most 10 s, until the end marker appears in the shell task's tail. A start marker means a copy is already running, so it does not rewrite; the typed line carries the marker fragments separately, so its echo cannot satisfy the check.
  • The zsh -f selection and zsh_startup_files are removed (HostPlatform::start_shell args are back to -i). Nothing reads self.home for shell startup any more, so platform_home versus the shell's HOME, ZDOTDIR, or a distro's own startup prompt cannot pick the wrong behavior or lose the command. A slow shell only gets a duplicate idempotent init wrapper.
  • Verified with a fresh HOME and zsh (the wizard runs): 3 of 3 passes; that case failed every run before (10/10).

Known item, also in the PR body: no test forces a startup consumer for a shell that has none — the harness gives the test no shell startup directory of its own. The consumer path is exercised where the shell really runs one (CI's fresh HOME with zsh, or a fresh local HOME).

eric8810 added a commit that referenced this pull request Nov 26, 2026
Review round on #2206:

- Shell initialization no longer depends on which home the shell reads. The
  init wrapper is written again until its end marker reaches the shell's tail,
  so a startup consumer (zsh's newuser wizard), a `ZDOTDIR` or a
  `platform_home`/`HOME` mismatch cannot lose it. The zsh `NO_RCS` argument and
  the home check that selected it are removed.
- A shell's background jobs are released, and their release confirmed, before
  the shell records its terminal: the worker kills each live job with the
  SIGKILL escalation and waits for it. The terminal sweep keeps a SIGKILL
  backstop instead of one unconfirmed SIGTERM, and the unused `terminate_job`
  helper is gone. A job that ignores SIGTERM no longer outlives its terminal.
- The interrupt wording matches what shells do: some print the end marker after
  Ctrl+C and end the command with its interrupted status; only a command still
  running after the two-second wait makes the owner terminate the shell and
  sweep it as a reset.
- The converted-command stop test asserts the terminal and that the next call
  runs, both of which hold for either shell behavior, and a new test stops a
  shell with a SIGTERM-ignoring job and checks the process is gone.

Refs #2032

@zerob13 zerob13 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 0f015ba26419f2443d7bb91bcc863a6404fd1add. The zsh startup compatibility finding is closed: the launch no longer skips user startup files, and the init retry handles wizard input.

  1. Unconfirmed Stop still needs a bounded, truthful result. The shell worker now attempts to release jobs before publishing, but it ignores the release result. If release cannot be confirmed, the shell can still publish a terminal while a child remains, and the shared wait can still wait without a deadline. Verify that both Stop callers return bounded, explicit unresolved status, cleanup and the Session hold remain active, and exactly one real terminal is published after confirmation. Checking eventual PID disappearance after the terminal does not establish that ordering.
  2. Preserve a known nonzero exit code after handoff. The shared formatter still drops the code on a failed owner terminal. Verify that the event, completion notice and Stop reply all retain the same known code.

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 0f015ba26419f2443d7bb91bcc863a6404fd1add, round 3. The new commit changes the startup wrapper, the shell-exit job release, the interrupt wording and the two stop tests; it does not touch BackgroundExec, background_result or the stop wait. I rechecked the full main...head diff and reran the flows at this head.

The refactor's goal still holds. BackgroundExec is the one stop entry and one terminal publisher for native commands, shell jobs and converted shell commands. The new commit fixes the demonstrated P1 case: with zsh, a runInBackground job that ignores SIGTERM plus a converted sleep 60 stopped in 2.05 s as Failed "shell reset", the job's exec/ended was published, and the job process was gone. It also fixes the macOS stop test and removes the zsh -f check. Three blocking areas remain: the shell-command half of the stop invariant, the dropped exit code, and the startup retry.

Blocking

P1: a reset shell command's own process tree is not terminated, so a stop publishes a failed terminal and releases the Session hold while the command runs.

Problem: HostPlatform::kill for a shell command writes Ctrl+C, waits two seconds, and then terminates the shell (crates/dim-agent-capabilities/src/host_platform.rs:1245-1259). Its second wait observes only the command record, and that record becomes terminal because ShellTask::sweep finishes every non-terminal child after the shell is gone (host_platform.rs:4666-4713). The sweep kills only TaskKind::Job children (:4693-4698); a ShellCommand child is never signalled. On POSIX the shell is interactive with job control, so eval $'<command>' runs the command in its own foreground process group, not the shell's group. native::kill_tree sends SIGKILL only to descendants found through /proc on Linux and otherwise only to kill(-shell_pid) (:2745-2762); macOS has no /proc, so the command group is not reached, and PtyProcessTree::terminate returns Ok(()) after its two-second poll even when it broke on the deadline (:3522-3549). BackgroundExec then appends exec/ended and drops the hold (crates/dim-agent-capabilities/src/workspace_tools/background.rs:437-453). The prior round's diagnosis named this unconfirmed terminal; the job half is fixed, the command half is not.

Failure scenario, reproduced at this head on Darwin 27.2.0: execute sh -c 'echo $$ > pidfile; trap "" INT TERM HUP; while true; do sleep 1; done' with timeoutMs: 100, then stop the converted task through BackgroundExec. The stop returned Failed "shell reset" after 2.03 s, exec/ended was published, the Session hold was released, and the command's process was still alive. Its sleep child was reparented and survived too. The same command with only INT and TERM trapped dies because the kernel sends SIGHUP to the foreground group when the session leader dies; adding HUP, which daemons and editors commonly ignore, is enough to leak it.

Fix: terminate the command's process group before publishing a reset, for example by recording the PTY's foreground group at command start and killing it, or by walking descendants with libproc on macOS. If the owner cannot confirm the command's release, return an explicit unconfirmed result and keep the record and the Session hold instead of finishing it from the sweep. Treat kill_tree returning without a confirmed release the same way.

P2: a confirmed nonzero exit code is still dropped after handoff and for detached shell jobs.

Problem: settled_from_reply builds a CommandExit only for WaitStatus::Exited or WaitStatus::Signaled (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2185-2203). The owner records a shell command or job with a known nonzero code as TaskStatus::Failed with exit_code: Some(code) (crates/dim-agent-capabilities/src/host_platform.rs:4797-4823, :4880-4916), so background_result takes the failure branch first (exec.rs:2205-2230), never reaches the exit branch, and insert_exit receives None (:2273).

Failure scenario, reproduced at this head: execute sh -c 'sleep 0.6; exit 7' with timeoutMs: 100, and runInBackground sh -c 'sleep 0.4; exit 9'. Both exec/ended results were Failed "command failed" with no exitCode in the structured content. A code the owner knows is lost exactly when the task is handed off or detached; the foreground failing_command_reports_exit_code still reports "exit code 3".

Fix: derive the exit from reply.exit_code and reply.signal regardless of status, do not let the failure branch mask a known code, and add exitCode to the structured result and the summary. Add a handoff case and a detached job case with a nonzero code. This finding is unchanged since round 1 and was not touched by 0f015ba2.

P2: the startup retry can accept a partial wrapper as initialized, and a consumer that keeps prompting still defeats it.

Problem: send_initial accepts the end marker whenever it appears in the shell tail (crates/dim-agent-capabilities/src/shell_session.rs:597-598), even when the start marker was never seen. started gates only the next write (:586-596). A startup consumer that exits after consuming a prefix of the wrapper line leaves the remainder to the shell, which can execute the trailing printf that prints the end marker. The init command then never runs, but the loop returns Ok(()). The doc claim that the echoed text cannot pass for the marker (docs/architecture/rust-agent/plugins/HostPlatform.md:165-169) covers echo, not a partially executed line.

Failure scenario, reproduced at this head with an isolated HOME: a .zshrc that sets a probe variable, then reads exactly 177 characters one at a time (the wrapper's end printf starts at offset 177). The first shell command ran and showed bang=on, hist=<home>/.zsh_history, so setopt NO_BANGHIST and unset HISTFILE had not run, while send_initial returned success. The consequences are not cosmetic: with history expansion on, a later command containing ! can be expanded or rejected, and every model command is appended to the user's history file. Separately, I ran the real zsh-newuser-install function from a .zshrc with a fresh HOME: in 5 of 5 runs the wizard did not exit and the init ended with "shell did not initialize; captured output: ..." at the 10 s deadline. That invocation is the wizard's edit mode, not the module's first-run path, so it does not show the CI path failing, but it shows that repeating the wrapper is not a general tolerance for a consumer that expects answers, and the PR records no forced-consumer test.

Fix: accept success only when the start marker was seen before the end marker (require started). Keep the newuser wizard out of the first command, for example by restoring a NO_RCS start chosen from the shell's own HOME and ZDOTDIR when the user has no startup files, rather than feeding a wizard arbitrary lines. Add a test with a forced consumer.

Non-blocking

P3: BackgroundExec::stop's doc comment still describes the old terminal. It says a running task "ends cancelled and does not wake" (crates/dim-agent-capabilities/src/workspace_tools/background.rs:670-672). A converted shell command now ends Failed and wakes, as WorkspaceTools.md:681-690 says. start's "terminated and reaped" (:349-350) is also stronger than the reset path can now guarantee.

P3: the new release confirmation is process-group scoped. kill_job waits for the job's group to disappear (crates/dim-agent-capabilities/src/host_platform.rs:3663-3681), and the worker release loop ignores its error (:4592-4594). A job command that starts a new session has a descendant outside that group. Reproduced at this head on macOS: runInBackground sh -c 'python3 escape.py & wait', where the child calls os.setsid(); on exit 7 the job's exec/ended was published Failed "shell exited" while the escaped child was alive. On Linux the /proc walk reaches it. Either state the limit or enumerate descendants on macOS; at minimum do not ignore kill_job's error.

P3: the failing behaviors still lack tests. a_term_ignoring_job_is_gone_before_its_terminal checks only the root pid, so a session-escaping child passes. No test covers a known exit code after handoff, a forced startup consumer, or a shell command that survives the reset. Add them with the fixes.

P3: access-layer rebase after #2174. #2174 (a05a4423) adds the Session::service_opt allow entry at xtask/access-layer.json:526 and keeps removed: []. This PR deletes that method, and the check rejects an entry that matches fewer occurrences (xtask/check/src/access.rs:125-160). The rebase must delete that entry. Because this PR retires the execStop catalog name, it should also add execStop to removed (xtask/check/src/access.rs:30-36); the PR body mentions the first but not the second.

Prior threads

  • The macOS stop test finding is fixed: the assertion now holds for either shell behavior, and the test passed 3 of 3 isolated runs on Darwin 27.2.0.
  • The zsh -f home-source finding is withdrawn: the check and NO_RCS argument are gone, and the retry is independent of platform.home. With a fresh HOME, the shell HOME's .zshrc loads, and with ZDOTDIR set and a fresh HOME its .zshrc loads as well.
  • The interrupt-premise finding is withdrawn: HostPlatform.md:29 and host_platform.rs:50-53 now say that some shells print the end marker after the interrupt and only a command still running after two seconds causes a reset.

Cross-PR and main

git diff --check is clean. Merge-tree with origin/main 076df0a1, #2178 b1387a0b and #2174 a05a4423 is clean. #2197 f2f6c8de conflicts with this PR in crates/dim-app-server/src/connection.rs; its head still resolves dyn ExecStop first (connection.rs:1632) and must route session.exec.stop to BackgroundExec when rebased. #1881 ff9825d2 conflicts with main in docs/design/plugins/Report.md, which this PR does not touch.

CI

At the head, run 45742432370 attempt 1: changes, windows-cli and macos-native succeeded; verify (linux) failed on managed_oauth_flow::grok_device_flow_observes_slowdown_expiry_cancellation_and_uri_trust (managed_oauth_flow.rs:902, Elapsed(())) and managed_oauth_flow::managed_provider_selection_http_recovery_and_restart_flow (:267, Elapsed(())). The same two tests failed at 6f44b530 in round 1 and are outside this diff. A second attempt of verify (linux) started at 02:44:23Z and is still running, so ci-ok has not run yet. The Linux run did pass minimal_execution including the new job test, the stop test and the preference test, plus integration_flow and capabilities_flow. static-checks, dependencies, web, scripts and acp-registry were skipped by path filters.

Verification

Isolated HOME, TMPDIR and XDG under the review data directory, LC_ALL=en_US.UTF-8; temporary probes were reverted and the worktree is clean at the head; no residual processes.

  • minimal_execution: 24 passed, 0 failed at this head.
  • stop_an_occupying_command_returns_and_the_shell_keeps_working: 3 of 3 passed (Darwin 27.2.0, bash 3.2).
  • a_term_ignoring_job_is_gone_before_its_terminal: 3 of 3 passed.
  • new_persistent_shells_and_environment_refresh_use_current_preferences with a fresh HOME: 3 of 3 passed.
  • P1 probes: the zsh job stop returned in 2.05 s with the TERM-ignoring job dead; the HUP/INT/TERM-ignoring converted command returned in 2.03 s with the command alive; the escaped job descendant was alive when its terminal was published.
  • P2 exit-code probes: handoff exit 7 and detached exit 9 both published Failed "command failed" with no exitCode.
  • Init probes: a fresh HOME, a whole-line consumer and a ZDOTDIR consumer all initialized; the 177-character partial consumer skipped the init; the forced real wizard timed out 5 of 5.

Unverified: a Linux local run of the HUP-ignoring command leak and the wizard (the Linux kill_tree has the /proc walk; CI is the only Linux evidence); the Windows and pwsh stop path; a forced kill_job timeout or D-state process; full workspace clippy and xtask check locally (CI skipped static-checks).

Verdict: REQUEST_CHANGES.

// line, so no end marker can print). Terminating the shell
// sweeps the command to its terminal.
command.shell.terminate();
if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status == WaitStatus::Running {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: this wait observes the record, not the command. ShellTask::sweep finishes every non-terminal child after the shell dies (crates/dim-agent-capabilities/src/host_platform.rs:4666-4713), and it signals only Job children (:4693-4698). On POSIX the wrapper runs the command in its own foreground group under job control, and native::kill_tree reaches descendants only through the /proc walk on Linux (:2745-2762); on macOS it only kills kill(-shell_pid). So the second wait returns because the sweep made the record terminal, while the command's process tree is alive, and BackgroundExec then appends exec/ended and drops the hold (crates/dim-agent-capabilities/src/workspace_tools/background.rs:437-453). Reproduced at this head on Darwin 27.2.0: execute sh -c 'echo $$ > pidfile; trap "" INT TERM HUP; while true; do sleep 1; done' with timeoutMs: 100, then BackgroundExec.stop; the stop returned Failed "shell reset" in 2.03 s and the command was still alive. Adding HUP to the traps is enough; without it the kernel SIGHUP kills the foreground group when the session leader dies. Fix: kill the command's process group, or walk descendants with libproc on macOS, before declaring a reset; when release cannot be confirmed, return an explicit unconfirmed result and keep the record and the Session hold instead of finishing it from the sweep.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 3c4ef46e9; the new commit changes only HostPlatform.md and the job test, so this path is unchanged. Reproduced again at this head on Darwin 27.2.0: execute sh -c 'echo $$ > pidfile; trap "" INT TERM HUP; while true; do sleep 1; done' with timeoutMs: 100, then BackgroundExec.stop returned Failed "shell reset" in 2.03 s with the command still alive. The second wait (host_platform.rs:1254) still observes only the record sweep finishes (:4666-4712), sweep still signals only TaskKind::Job (:4694-4698), and macOS kill_tree still reaches only kill(-shell_pid) (:2745-2767). The job half is fixed and covered; this half is not.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4a.

The command runs in the terminal's foreground process group, not the shell's, and macOS has no /proc tree for the group walk. HostPlatform::kill now signals that group explicitly before it terminates the shell:

  • PtyProcessTree::kill_foreground_group reads tcgetpgrp through portable-pty, skips a group led by the shell itself, sends SIGKILL, and answers the leader.
  • ShellTask::kill_foreground_group performs it under the PTY handle, then waits up to two seconds for the group to disappear (wait_group_gone) before terminate kills the shell's own group and its sweep records the command's terminal (crates/dim-agent-capabilities/src/host_platform.rs, the ShellCommand arm of kill, and the helpers next to PtyProcessTree).

New test stopping_a_command_that_ignores_the_interrupt_leaves_no_process (tests/integration/tests/minimal_execution.rs): your repro — sh -c 'echo $$ > pid; trap "" INT TERM HUP; while true; do sleep 1; done' with timeoutMs: 100 — then the stop must return a failed terminal and gone(pid). Its message branches on cfg!(target_os = "macos"), so scripts/test-macos-native.mjs selects it; the macOS job builds integration_flow and runs it, which is the proof of the foreground-group path. On Linux the same test runs in the normal suite; there the /proc walk would also reach the command, so macOS is where the test discriminates.

Known limit, also in the PR body: a descendant that left the group or session can still escape; release is best effort.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3b66bb30. host_platform.rs:1255 releases the terminal foreground group before the shell is terminated, and wait_group_gone (:3597-3611) waits for it. Verified at 45c02dd4: the test passes, and fails with the call removed (the pid survives). Withdrawing; the shell stop/close path is raised as a new non-blocking comment on the same line.

write_at = now + INIT_RETRY;
}
match &tail {
Ok(tail) if tail.text.contains(&end_marker) => return Ok(()),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: this accepts an end marker even when the start marker never appeared, so a startup consumer that exits after consuming a prefix of the wrapper leaves the trailing printf to run as a command and the init is never executed. Reproduced at this head with an isolated HOME: a .zshrc that sets a probe and reads exactly 177 characters one at a time (the lead-in to the end printf). The next command showed bang=on and HISTFILE=<home>/.zsh_history, so setopt NO_BANGHIST and unset HISTFILE were skipped while this returned Ok. History expansion can also rewrite or reject a later command containing !. Separately, the real zsh-newuser-install run from a .zshrc did not exit and the init ended with "shell did not initialize" at the 10 s deadline in 5 of 5 runs; that is the wizard's edit mode, not the module's first-run path, so it does not show the CI path failing, but the retry has no forced-consumer test. Fix: require started before accepting the end marker, keep the wizard out by choosing NO_RCS from the shell's own HOME and ZDOTDIR when the user has no startup files, and add a forced-consumer test.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 3c4ef46e9; send_initial is unchanged. started gates only the rewrite (shell_session.rs:586-596) and the end marker alone returns Ok (:597-598). Reproduced again with an isolated HOME and zsh: a .zshrc that reads 177 characters one at a time skipped the init (the next command showed bang=on and HISTFILE set) while initialization returned success. A forced-consumer test is feasible: the harness HOME is a scratch directory, so writing .zshrc there and selecting /bin/zsh reproduces it; skip when zsh is absent. Require started before accepting the end marker.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4a.

send_initial now tracks whether a copy's start marker reached the shell's tail and accepts an end marker only after that (started && tail.text.contains(&end_marker)); an end marker that a startup consumer emitted by itself no longer counts, and the next retry runs the wrapper again (crates/dim-agent-capabilities/src/shell_session.rs, send_initial). The doc comment states the rule.

New test a_startup_consumer_cannot_skip_the_init (tests/integration/tests/minimal_execution.rs): a scratch HOME whose .zshrc sets HISTFILE and then read -rs the first wrapper line, a platform built on /bin/zsh with that HOME in its child environment, and an assertion that the first command sees histfile=unset — i.e. the init really ran. It returns early when /bin/zsh is absent.

Docs: HostPlatform.md's persistent-shell paragraph describes the retry and the start-marker requirement.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3b66bb30. send_initial records the start marker at crates/dim-agent-capabilities/src/shell_session.rs:589 and accepts the end marker only when started at :600. Verified with a 177-character consumer: the old acceptance ended with HISTFILE=/tmp/dim-consumer-history, this head ends with HISTFILE unset. Withdrawing. The committed test does not exercise this path (separate comment).

_ => None,
};
if let Some(pid) = pid {
let _ = kill_job(pid, job_tree(pid)).await;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the release result is discarded and the confirmation is group scoped. kill_job waits only for kill(-pid, 0) to report ESRCH (crates/dim-agent-capabilities/src/host_platform.rs:3663-3681), so a descendant that left the group is not seen, and a timeout is ignored here before the shell terminal and every child terminal are published. Reproduced at this head on macOS: runInBackground sh -c 'python3 escape.py & wait' where the child calls os.setsid(); on exit 7 the job's exec/ended was Failed "shell exited" and the escaped child was still alive. On Linux the /proc walk reaches it. Fix: enumerate descendants on macOS, and when kill_job returns Err keep the record live and report an unconfirmed release.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 3c4ef46e9. The worker still drops kill_job's result (host_platform.rs:4592-4594) and kill_job still confirms only the process group (:3606-3614, :3662-3680); a descendant that calls setsid survives its job's terminal. The new HostPlatform.md:40-42 states the release as a guarantee, while the PR body records it as best effort. Narrow the sentence and name the session-escape limit, or keep the job record live and return an explicit unconfirmed result.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4a.

The wording now matches the code instead of promising a guarantee. HostPlatform.md says the shell "attempts to release each live job whose pid is known": SIGKILL to the job's group and, where the platform can enumerate them, its descendants, then a wait of up to two seconds; the sweep keeps a SIGKILL backstop. It also states the limits: kill_job's result is dropped, so a failed kill is not reported as such, and a descendant that left the job's group or session can outlive the job's terminal. The PR body's known-issues section says the same.

I kept the release in the shell worker and did not keep the job record open for an explicit unconfirmed result: that result shape would change the job terminal's contract, which this board does not own.

The job half that you confirmed working is unchanged.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed at 45c02dd4. docs/architecture/rust-agent/plugins/HostPlatform.md:40-44 now says the worker attempts to release each live job whose pid is known, SIGKILLs the group and enumerable descendants, waits up to two seconds, drops kill_job's result, and names the descendant that can outlive the job's terminal. That matches crates/dim-agent-capabilities/src/host_platform.rs:4632. Withdrawing the doc finding.

@zerob13 zerob13 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 3c4ef46e92c7342d19eb62a5a44477b79f5933ef. ZDOTDIR compatibility stays closed. The strengthened cleanup fixture passed in exact CI, but the unresolved owner cases remain.

  1. If release cannot be confirmed, both Stop paths must return a bounded, explicit unresolved result. Keep cleanup and the Session hold through real confirmation and publish exactly one terminal afterward. The worker still discards a failed release result; a passing confirmed-path fixture does not cover that branch.
  2. Preserve the same known nonzero exit code across handoff in the terminal event, completion notice and Stop reply.
  3. Previously missed startup defect, independently checked in code. The init wait accepts the trailing marker even without evidence the init command ran. A startup reader can consume the leading portion while the tail command still executes, leaving the shell in a different configuration from successful bootstrap. See the peer observation. Verify a partially consumed init never reports success until initialization has actually taken effect. This does not reopen normal zsh startup-file handling.

@eric8810
eric8810 requested a review from zerob13 November 26, 2026 03:40

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 3c4ef46e92c7342d19eb62a5a44477b79f5933ef, round 4. Since 0f015ba2 the only change is 3c4ef46e9: four lines in HostPlatform.md and one assertion plus its import in the job test. I rechecked the full main...head diff and all seven review threads, and reran the affected flows at this head.

The refactor's goal holds. BackgroundExec is the one stop entry and one terminal publisher for native commands, shell jobs and converted shell commands; dyn ExecStop, exec_stop.rs, the optional-service reads and the private shell event page have no callers; ShellSession no longer writes exec facts. The new job test is sound and passes, and the new doc sentence is directionally right, but all three blockers from round 3 reproduce unchanged at this head.

Blocking

P1: a reset shell command's own process tree is not terminated, so the stop publishes a failed terminal and releases the Session hold while the command runs.

Problem: HostPlatform::kill for a shell command writes Ctrl+C, waits two seconds, and then terminates the shell (crates/dim-agent-capabilities/src/host_platform.rs:1237-1260). Its second wait (:1254) observes only the command record, and that record becomes terminal because ShellTask::sweep finishes every non-terminal child after the shell dies (:4666-4712). The sweep signals only TaskKind::Job children (:4694-4698); a ShellCommand child is never signalled. The shell runs the wrapper through eval under job control, so the command is in its own foreground process group. PtyProcessTree::terminate (:3522-3534) calls native::kill_tree, which reaches descendants through /proc only on Linux; on macOS it only sends kill(-shell_pid) (:2745-2767). BackgroundExec then appends exec/ended, settles and drops the hold (crates/dim-agent-capabilities/src/workspace_tools/background.rs:436-453).

Failure scenario, reproduced at this head on Darwin 27.2.0: execute sh -c 'echo $$ > pidfile; trap "" INT TERM HUP; while true; do sleep 1; done' with timeoutMs: 100, then BackgroundExec.stop. The stop returned Failed "shell reset" in 2.03 s and the command was still alive. Without HUP in the trap list the kernel's SIGHUP kills the group; HUP is the signal long-running servers commonly ignore, so the leak is realistic.

Fix: kill the PTY's foreground process group, or walk descendants with libproc on macOS, before declaring the reset; when release cannot be confirmed, return an explicit unconfirmed result and keep the record and the Session hold, as the earlier review requires.

P2: a confirmed nonzero exit code is still dropped after handoff and for detached shell jobs.

Problem: settled_from_reply builds a CommandExit only for WaitStatus::Exited or WaitStatus::Signaled (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2185-2205). The owner records a shell command or job with a known nonzero code as TaskStatus::Failed with exit_code: Some(code) (crates/dim-agent-capabilities/src/host_platform.rs:4797-4828, :4880-4911). background_result takes the failure branch first (exec.rs:2207-2279), never reaches the exit branch, and insert_exit receives None (:2273).

Failure scenario, reproduced at this head: runInBackground sh -c 'exit 7' and a converted sleep 0.3; sh -c 'exit 7' both published exec/ended as Failed with text "command failed" and no exitCode in the structured content. The foreground failing_command_reports_exit_code still reports "exit code 3", so the same status reports differently depending on handoff.

Fix: derive the exit from reply.exit_code and reply.signal regardless of status, add exitCode to the structured result and the summary, and add one handoff and one detached-job test with a nonzero code.

P2: the startup retry accepts an end marker without the start marker, so a partial consumer skips the init.

Problem: send_initial returns Ok whenever the end marker appears in the shell tail (crates/dim-agent-capabilities/src/shell_session.rs:597-598). started gates only the next write (:586-596). A startup consumer that exits after consuming a prefix of the wrapper leaves the trailing printf to run as a command; the end marker prints and the init never executes.

Failure scenario, reproduced at this head with an isolated HOME and zsh: a .zshrc that reads exactly 177 characters one at a time (the wrapper's end printf starts at offset 177). The next command printed bang=on and HISTFILE set to the scratch home's .zsh_history, while send_initial returned success and the session continued. History expansion can rewrite or reject a later command containing !, and every model command is appended to that file. docs/architecture/rust-agent/plugins/HostPlatform.md:168-172 claims no startup consumer can lose the initialization, which this contradicts.

Fix: accept success only when the start marker was seen before the end marker. A forced-consumer test is feasible: the harness's HOME is a scratch directory, so a test can write .zshrc there and select /bin/zsh, skipping when zsh is absent. The PR body's Known issues section says the harness gives no startup directory, which is not correct.

Non-blocking

P3: the new job-release sentence in HostPlatform.md:40-42 promises more than the code does. The worker releases only TaskKind::Job children whose pid is known (host_platform.rs:4584-4594) and drops kill_job's result. kill_job sends SIGKILL directly, with no TERM-to-KILL escalation (:3606-3614), and on POSIX confirms only kill(-pid, 0) ESRCH (:3662-3680), so a descendant that calls setsid survives its job's terminal. The PR body records this as best effort; the page should say so and name the session-escape limit, or keep the terminal live until release is confirmed. The test change itself is sound: the release completes before worker_record.finish, so a pid alive after exec/ended means the confirmation failed, and the assertion covers exactly that.

P3: BackgroundExec::stop's doc comment still describes the old terminal. It says a running task "ends cancelled and does not wake" (crates/dim-agent-capabilities/src/workspace_tools/background.rs:670-672). A stopped shell command now ends Failed, or Completed as below, and does wake, as WorkspaceTools.md:680-682 states. start's "terminated and reaped" (:349-350) is also stronger than the reset path can guarantee.

P3: WorkspaceTools.md:680-682 says a stopped shell command's terminal is failed, but it can be completed. The terminal is the wrapper line's $?. Measured at this head: execute sleep 60 || true with timeoutMs: 100, then stop, returned Completed with "Command completed." and posted the completion notice. State the terminal as the interrupted line's status, usually failed and completed when the line continues and ends successfully, or decide that a stop records failed or cancelled regardless of the wrapped status.

P3: tests still missing. The new job test covers its case. No test covers a known exit code after handoff, a forced startup consumer, or a shell command that survives the reset. Each one fails at this head, so they can be written before the fixes and used to gate them.

Prior threads

  • The job half of the P1 is fixed at this head: the release runs before the shell terminal and the new !alive assertion is sound. The command half remains, as reproduced above.
  • The macOS stop-test finding, the zsh -f home-source finding and the interrupt-premise finding remain withdrawn from round 3; the new commit does not change the code those threads discuss.
  • The exit-code finding remains open and is not addressed by 3c4ef46e9 or by the PR body's Known issues. The group-scoped release and stale stop doc comments remain open.
  • The access-layer entry is a merge-order requirement, not a defect at this head: xtask/access-layer.json does not exist on the branch.

Cross-PR and main

git merge-tree is clean against origin/main 076df0a1 and the current heads of #2174 4f59f2fa, #2178 0506c22b, #2197 eccd6d38, #2210 d99838e1 and #2211 ae694e9f. #1881 ff9825d2 conflicts only in docs/design/plugins/Report.md, a file this PR does not touch, the same conflict it has with main. The current #2174 head 4f59f2fa still has the Session::service_opt allow entry at xtask/access-layer.json:526 and "removed": [] at :869. After #2174 merges, this PR's rebase must delete that entry, and because this PR retires the execStop catalog name, it should add execStop to removed (xtask/check/src/access.rs rejects a removed name that comes back). #2197 adds docs/architecture/rust-agent/plugins/ShellSession.md, which describes the old ownership and dyn ExecStop; whichever PR lands second must update it. #2197 also still registers dyn ExecStop in lib.rs. #1881's conflict is with main in an unrelated report page.

CI

At 3c4ef46e9, run 45747234906: changes, windows-cli, macos-native, verify (linux) and ci-ok pass. static-checks, scripts, web, dependencies and acp-registry are skipped by path filters, so xtask check and clippy were not exercised by CI at this head.

Verification

Isolated HOME, TMPDIR and XDG under the review data directory, LC_ALL=en_US.UTF-8; probe edits reverted and the worktree is clean at the head; no residual processes.

  • minimal_execution: 24 passed, 0 failed at this head, including the new job test and the stop test.
  • P1 probe: the HUP/INT/TERM-ignoring converted command's stop returned Failed "shell reset" in 2.03 s with the command still alive.
  • Exit-code probes: runInBackground sh -c 'exit 7' and a converted command with the same status both lost the code.
  • Init probe: the 177-character .zshrc consumer skipped the init (bang=on, history file set) while initialization returned success.
  • Stop-status probe: sleep 60 || true stopped as Completed.

Unverified: the Windows kill_job tree branch and its test (CI does not run that test on Windows); a forced kill_job timeout or an unkillable process, so the unbounded BackgroundExec.stop wait is not demonstrated; a Linux local run of the reset-command leak (the Linux /proc walk reaches it and CI runs the suite there); the real zsh-newuser-install path this round.

Verdict: REQUEST_CHANGES.

tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well
as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job
children. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is
children. Before a shell writes its terminal, it releases every live job with a SIGKILL

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this promises more than the code does. The worker releases only TaskKind::Job children whose pid is known (crates/dim-agent-capabilities/src/host_platform.rs:4584-4594) and drops kill_job's result. kill_job sends SIGKILL directly, without a TERM-to-KILL escalation (:3606-3614), and POSIX confirms only kill(-pid, 0) ESRCH (:3662-3680), so a descendant that calls setsid survives its job's terminal. Say "attempts to release each live job with a known pid by SIGKILL, waits up to two seconds, and keeps the sweep's SIGKILL backstop", or keep the record live until release is confirmed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4a; same change as the other job-release thread.

HostPlatform.md now says the shell "attempts to release each live job whose pid is known" by SIGKILL (group plus enumerable descendants), waits up to two seconds, and keeps the sweep's SIGKILL backstop, then names the limits: the worker drops kill_job's result, and a descendant that left the group or session can outlive the job's terminal. No guarantee remains in the page or in the PR body.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4. docs/architecture/rust-agent/plugins/HostPlatform.md:40-44 now states the release attempt, the two-second wait, the dropped kill_job result, and the session-escape limit, matching crates/dim-agent-capabilities/src/host_platform.rs:4632. Withdrawing.

A persistent shell's first command is the init wrapper, and the shell may spend its first
input on a startup consumer instead — zsh's newuser module runs a wizard when the user has no
startup files. `ShellSession` writes that wrapper again until its end marker reaches the shell's
tail, so no startup consumer can lose the initialization; the wrapper uses the same marker

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: this is false for a partial startup consumer. send_initial returns Ok when the end marker appears even if the start marker never did (crates/dim-agent-capabilities/src/shell_session.rs:597-598); a consumer that exits after consuming the wrapper's prefix leaves the trailing printf to print the end marker, and the init never runs. Reproduced at this head with a .zshrc that reads 177 characters: the next command showed bang=on and HISTFILE set while initialization returned success.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4a; this is the same defect as the init thread.

send_initial accepts an end marker only after a copy's start marker reached the shell's tail, the retry runs the wrapper again when a consumer ate it, and a_startup_consumer_cannot_skip_the_init covers a .zshrc that reads the first line (asserts the init's unset HISTFILE took effect). HostPlatform.md:172 and the function's doc comment state the start-marker requirement.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 3b66bb30. The end marker alone no longer returns Ok: started is set at crates/dim-agent-capabilities/src/shell_session.rs:589 and gates the return at :600. Verified with a 177-character consumer (init skipped before, runs now), so docs/architecture/rust-agent/plugins/HostPlatform.md:170-174 is accurate. Withdrawing.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 496d4d22f.

docs/architecture/rust-agent/plugins/HostPlatform.md:172-174 now says the wrapper is written again "until one copy's start marker and then its end marker reached the shell's tail", and that an end marker a consumer emitted by itself does not count — matching send_initial, which records the start marker before it can accept the end marker.

Also from the delta: PtyProcessTree::kill_foreground_group is now pub(crate); its only caller is the shell module.

every other status posts the completion notice. A command that started as a
native process and a persistent shell's background job both end `cancelled`, so
neither wakes. A shell command is interrupted in its persistent shell; its
terminal is `failed` (the interrupted command's exit status, or a shell reset

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: a stopped shell command is not always failed. The terminal is the wrapper line's $?; a line that continues after the interrupt and ends successfully reports 0. Measured at this head: execute sleep 60 || true with timeoutMs: 100, then stop, returned Completed with "Command completed." and posted the completion notice. State the terminal as the interrupted line's status, or decide that a stop always records failed or cancelled.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented at 45c02dd4a.

WorkspaceTools.md now says a stopped shell command's terminal is the interrupted wrapper line's own status: an interrupted command followed by || true ends completed, a line that stops there ends failed, and a line the shell aborts ends with the owner's shell reset. HostPlatform.md's kill sentence says the same. The completion wake follows the terminal, so the completed case posts a notice.

No code change: the terminal stays the owner's record, per #2032 A.3 ("nobody composes or publishes a result"). The existing stop_an_occupying_command_returns_and_the_shell_keeps_working uses sleep 60, where both interrupt outcomes are failed, and its comment now says that is specific to this command.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 45c02dd4. docs/architecture/rust-agent/plugins/WorkspaceTools.md:680-683 now says the terminal is the interrupted wrapper line's own status, that || true ends completed, and that a shell abort ends with the owner's shell reset, matching crates/dim-agent-capabilities/src/host_platform.rs:4849-4879 and the sweep at :4705-4752. Withdrawing.

eric8810 added a commit that referenced this pull request Nov 26, 2026
Review round on #2206:

- A shell command that outlives Ctrl+C runs in the terminal's foreground
  process group, not the shell's. `HostPlatform::kill` now signals that group
  with SIGKILL and waits for it before it terminates the shell, so the command
  itself is released on macOS, where no `/proc` tree reaches it. The shutdown
  keeps the shell's own group to `PtyProcessTree::terminate`.
- The init accepts an end marker only after a copy's start marker reached the
  shell's tail. An end marker a startup consumer emitted by itself no longer
  counts as initialization.
- The job-release wording matches the code: release is best effort, a failed
  kill is not reported, and a descendant that left the job's group or session
  can outlive its terminal.

Tests: `stopping_a_command_that_ignores_the_interrupt_leaves_no_process` and
`a_startup_consumer_cannot_skip_the_init`; the macOS flow selection includes the
first so that path runs on macOS.

Refs #2032
@eric8810
eric8810 requested a review from yyhhyyyyyy November 26, 2026 04:18

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review at 45c02dd, round 5

Reviewed head 45c02dd4a2b27e9f0b89f8577dd7a29c84fc59a9 (base origin/main c68dad5a). Since 3c4ef46e9 the branch adds two commits: 3b66bb30 (release a stopped shell command's foreground group and require a started init) and 45c02dd4 (docs only). The group release is correct and its test fails when the call is removed; the init fix is correct and a partial-consumer probe shows the old acceptance failing and the new one passing. The docs now match the code. One prior blocker remains, the dropped exit code, and three non-blocking gaps are new or still open: the new init test never runs a startup consumer, the shell stop/close path still leaves a foreground command on macOS, and the stop doc comment still describes the old terminal.

Blocking

P2: a confirmed nonzero exit code is dropped after handoff and for detached shell jobs

The owner records a shell command or a shell job with a known nonzero code as TaskStatus::Failed with exit_code: Some(code) (crates/dim-agent-capabilities/src/host_platform.rs:4860-4864 and :4873 for commands, :4907-4913 for jobs). TaskStatus::Failed maps to WaitStatus::Failed (crates/dim-agent-capabilities/src/host_platform/task.rs:31). settled_from_reply builds a CommandExit only for WaitStatus::Exited | WaitStatus::Signaled (crates/dim-agent-capabilities/src/workspace_tools/exec.rs:2199-2203), and background_result takes the settled.failure.is_some() branch first (exec.rs:2220-2228), so insert_exit receives None.

Failure scenario, reproduced at this head: runInBackground with sh -c 'exit 7', and a converted sleep 0.3; sh -c 'exit 7' with timeoutMs: 100, both published exec/ended as Failed with summary "command failed" and no exitCode in the structured content. The foreground path still reports "exit code 3" in failing_command_reports_exit_code, so the same status reports differently depending on handoff. On main the removed owner path formatted reply.exit_code regardless of status (wait_code, crates/dim-agent-capabilities/src/shell_session.rs:1873-1882 on main), so this is introduced by the refactor.

Fix: derive the exit from reply.exit_code and reply.signal whenever they are present, independent of the status match, use exit_failure_summary for the Failed summary, and add one handoff test and one detached-job test with a nonzero code.

Non-blocking

P3: a_startup_consumer_cannot_skip_the_init never runs a startup consumer

Two independent reasons:

  • The test writes .zshrc under home (tests/integration/tests/minimal_execution.rs:1051-1058) and passes zsh_platform(&home), but Harness::new calls with_context, which replaces the shell's HOME with a fresh scratch cwd (:187-192). zsh never reads that file. Probe: a marker write added to that .zshrc never ran, and the shell's HOME was the harness cwd (marker_loaded=false rc_in_shell_home=false).
  • Even in the shell's real HOME, read -r __dim_init_line (:1054-1056) consumes the whole wrapper line, which the old acceptance already handled because no end marker prints. Reverting crates/dim-agent-capabilities/src/shell_session.rs:600 to the old end-marker-only condition still passes this test.

So the test does not gate the fixed line. The fix itself is sound: with a 177-character consumer that leaves the trailing printf to emit the end marker, the old acceptance ended with rc=loaded histfile=/tmp/dim-consumer-history (init skipped), and this head ends with rc=loaded histfile=unset (the retry ran the init). Suggest writing the .zshrc into harness.cwd after Harness::new and before session(), consuming a 177-character prefix one character at a time, and asserting the init ran.

P3: a shell stop still leaves a foreground command running on macOS

kill_foreground_group is called only in the TaskKind::ShellCommand branch (crates/dim-agent-capabilities/src/host_platform.rs:1255). The TaskKind::Shell branch (:1228) calls shell.terminate(), whose worker calls PtyProcessTree::terminate (:3525-3537). On POSIX that calls native::kill_tree(self.pid) (:2748-2769); the /proc children walk is Linux-only, so on macOS only kill(-shell_pid) runs, and a command in the terminal's separate foreground group survives. ShellSession::stop_shell uses this path (crates/dim-agent-capabilities/src/shell_session.rs:361-374) and is reached by the close effect (shell_session.rs:1216-1218) and the init timeout.

Failure scenario, reproduced at this head with the harness's /bin/bash on Darwin 27.2.0: execute a stubborn foreground command (trap "" INT TERM HUP; while true) with timeoutMs: 100, then session.close(). The command's exec/ended was published as Failed while the process was still alive after two seconds (alive=true ends=[(task, Failed)]). This is not introduced by 3b66bb30, but it is the same invariant as the fixed P1 on a second stop path. Fix: perform the foreground release inside PtyProcessTree::terminate (or in the TaskKind::Shell branch before terminate) so every shell termination path covers it.

P3: BackgroundExec::stop's doc comment still describes the old terminal

crates/dim-agent-capabilities/src/workspace_tools/background.rs:670-672 says a running task "ends cancelled and does not wake". A stopped shell command ends Failed or Completed and does wake; docs/architecture/rust-agent/plugins/WorkspaceTools.md:683 now says so. Update the comment.

Prior threads

  • The command half of the P1 is fixed at 3b66bb30: host_platform.rs:1255 releases the foreground group before terminating, and the new test fails when that call is removed. Withdrawn.
  • The startup-consumer P2 is fixed at 3b66bb30: shell_session.rs:589 records the start marker and :600 requires it. Withdrawn; the test-coverage gap above remains.
  • The job-release doc P3 is fixed at 45c02dd4: HostPlatform.md:40-44 now states the attempt, the two-second wait, the dropped result, and the session-escape limit. Withdrawn.
  • The WorkspaceTools stopped-status P3 is fixed at 45c02dd4: WorkspaceTools.md:680-683 says the terminal is the wrapper line's status and that || true can complete. Withdrawn.
  • The missing-tests P3 is partly addressed: the stop and startup tests now exist, but the startup test is vacuous (above) and no test covers the exit code after handoff or for a detached job.
  • The exit-code P2 remains, reproduced above.
  • The stop-comment P3 remains, as above.

CI at 45c02dd

Check runs for the head, fetched at the time of writing:

  • changes: success
  • macos-native: success (completed 04:20:33Z); its script selects stopping_a_command_that_ignores_the_interrupt_leaves_no_process because the body checks cfg!(target_os = "macos")
  • windows-cli: success (completed 04:23:59Z)
  • verify (linux): in progress (started 04:19:09Z); it runs fmt, clippy, xtask check and the workspace tests
  • static-checks, scripts, web, dependencies, acp-registry: skipped by path filters

Merge state

The API reports mergeable: true, rebaseable: true, mergeable_state: blocked (review decision). The PR records base main at ade85973; local origin/main is c68dad5a. git merge-tree --write-tree origin/main HEAD is clean, tree c0042712abe8b225650fdc68ff0540a93a352992.

Verification

Isolated HOME, TMPDIR and XDG under the review data directory, LC_ALL=en_US.UTF-8, cargo --locked --offline (there is no cargo-locked.sh in this repository at this head), CARGO_TARGET_DIR under the data directory.

  • cargo test -p dim-agent-integration-tests --test integration_flow minimal_execution:: -- --test-threads=2: 26 passed, 0 failed at 45c02dd4, and 26 passed at 3b66bb30.
  • cargo fmt --all -- --check: exit 0.
  • Init gating: with shell_session.rs:600 reverted to end-marker-only, the committed startup test still passes (exit 0), while a 177-character consumer probe shows init skipped (rc=loaded histfile=/tmp/dim-consumer-history); at the head the same probe shows rc=loaded histfile=unset.
  • Stop gating: with the kill_foreground_group() call removed, stopping_a_command_that_ignores_the_interrupt_leaves_no_process fails with "process 95422 survived the stop"; restored, it passes.
  • Exit-code probe at the head: detached and converted commands both end Failed, summary "command failed", no exitCode.
  • Close probe: alive=true ends=[(task, Failed)] after session.close().
  • Probe edits reverted, worktree clean at the head; the one process left by the disabled-release probe was killed; no residual processes.

Unverified

  • Windows: kill_foreground_group is a no-op there and relies on the portable-pty job's terminate; minimal_execution is #[cfg(unix)], so no test exercises that path. windows-cli runs cargo test -p dim-cli --lib, not this suite.
  • Linux local behavior of the group release and the close path; verify (linux) had not finished when these drafts were written.
  • Clippy and xtask check: static-checks was skipped; verify (linux) runs them and was in progress. cargo fmt passes locally.
  • Shells with job control off (the guard at host_platform.rs:3561-3563) and programs that move the terminal foreground themselves (nested job control) are untested.
  • The wait_group_gone timeout with an unkillable process is untested.

Verdict: REQUEST_CHANGES. The two code fixes are sound and verified, but the dropped exit code is unchanged and was blocking in round 4.

// terminal's foreground process group, which a shell that
// aborts the line leaves running; signal it before terminating
// the shell, whose sweep records the command's terminal.
command.shell.kill_foreground_group().await;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this release covers only the shell command branch. The TaskKind::Shell branch above (:1228) calls shell.terminate(), and PtyProcessTree::terminate (:3525-3537) calls native::kill_tree(self.pid) (:2748-2769); the /proc walk is Linux-only, so on macOS only kill(-shell_pid) runs and a command in the terminal's separate foreground group survives. ShellSession::stop_shell (crates/dim-agent-capabilities/src/shell_session.rs:361-374) uses this path, and the close effect reaches it at shell_session.rs:1216-1218. Reproduced at this head on Darwin 27.2.0: a stubborn execute command (trap "" INT TERM HUP; while true) with timeoutMs: 100, then session.close(), published exec/ended as Failed while the pid was still alive after two seconds (alive=true ends=[(task, Failed)]). Not introduced here, but it is the same invariant as the fixed P1 on a second stop path. Consider moving the foreground release into PtyProcessTree::terminate (or running it in the TaskKind::Shell branch before terminate) so every shell termination path covers it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 496d4d22; this delta does not touch it. Probe at this head on Darwin: an execute command with trap "" INT TERM HUP; while true and timeoutMs: 100, then session.close(), published exec/ended as Failed while the pid was still alive after two seconds (alive=true ends=[(task, Failed)]). The fix is still to release the foreground group on the TaskKind::Shell path (crates/dim-agent-capabilities/src/host_platform.rs:1227-1236) before terminate, or inside PtyProcessTree::terminate (:3525-3537).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at f125d5f38.

The release now sits in the shell's own termination, not only in a command's stop: PtyProcessTree::terminate signals the terminal's foreground process group and waits for it after the shell root is reaped (crates/dim-agent-capabilities/src/host_platform.rs, the Unix branch of terminate), so the TaskKind::Shell kill — session.close(), a branch close, an unload, and a shell command's stop that terminates the shell — all release the command that was running. The Unix Drop signals that group too before it kills the tree.

New test closing_a_session_releases_an_occupying_command (tests/integration/tests/minimal_execution.rs): your repro — trap "" INT TERM HUP; while true with timeoutMs: 100 — then session.close(); it asserts the occupying task's terminal is published as failed and gone(pid). It is selected by scripts/test-macos-native.mjs (its message branches on cfg!(target_os = "macos")), so the macOS job runs it, which is the proof of the foreground-group path.

The HostPlatform.md kill sentence now says terminating a shell — a command stop, a shell kill or a Session close — releases that group before the sweep.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f125d5f3, verified at this head. PtyProcessTree::terminate signals the terminal foreground group before native::kill_tree and waits for it after the root wait (crates/dim-agent-capabilities/src/host_platform.rs:3529-3543), and both the TaskKind::Shell kill and the owner-shutdown branch run through the worker's tree.terminate() (:4589-4621); the close effect is :2414-2422 and ShellSession's close calls stop_shell (crates/dim-agent-capabilities/src/shell_session.rs:1204-1223). closing_a_session_releases_an_occupying_command (tests/integration/tests/minimal_execution.rs:1051-1094) passes 3 of 3 and fails with process ... survived the Session close when the terminate release is removed; the command stop test still passes under that mutation because HostPlatform::kill releases the group at :1255. scripts/test-macos-native.mjs --list selects both tests, so macOS CI runs the foreground-group path. wait_group_gone and the root wait are each bounded at two seconds (:3604-3618), so a process that survives SIGKILL delays a close, it does not hang it. One remaining gap: removing only the Unix Drop release (:3586-3593) leaves all 27 minimal tests green, so that backstop is untested.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remains at 80411561. The new pending-stop commit does not touch the Unix Drop release at crates/dim-agent-capabilities/src/host_platform.rs:3586-3592; removing self.kill_foreground_group() there still leaves all 29 minimal_execution tests green. Optional P3, no change requested for approval.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recorded at 67f87ee8b.

PtyProcessTree's Unix Drop foreground-group signal has no fixture — dropping a live PTY tree is not reachable from the flow tests, and removing that call leaves the 29 shell cases green; the terminate path is covered through the Session-close and stop tests. It is now in the PR body's known issues as you allowed, no code change.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recorded and verified at 68ff0118.

The Unix Drop foreground release is in the PR body's Known issues, and the terminate path remains covered by the session-close and stop tests. The optional item is withdrawn; no code change requested.

async fn a_startup_consumer_cannot_skip_the_init() {
let home = scratch("zsh-consumer");
std::fs::write(
home.join(".zshrc"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this .zshrc is never sourced. Harness::new calls with_context, which replaces the shell's HOME with a fresh scratch cwd (minimal_execution.rs:187-192), so the scratch home passed to zsh_platform at :1059 is not the shell's HOME. Probe: a marker write added to this file never ran (marker_loaded=false rc_in_shell_home=false), and the shell HOME was the harness cwd. Even in the real HOME, read -r __dim_init_line (:1054-1056) consumes the whole wrapper line, which the old end-marker-only acceptance already handled; reverting crates/dim-agent-capabilities/src/shell_session.rs:600 to the old condition still passes this test. The fix itself is verified with a 177-character consumer (init skipped before, runs now). Suggest writing the rc into harness.cwd after Harness::new and before session(), consuming a 177-character prefix one character at a time, and asserting the init ran.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 496d4d22f.

  • The consumer .zshrc is written into harness.cwd after Harness::new, which is the HOME the harness gives the shell (Harness::with_context replaces platform.env's HOME with that cwd), so zsh really reads it.
  • It consumes a prefix character by character until the buffer holds eval $' and ends with '; — the boundary before the final printf — and then returns. The shell executes the remaining printf, so only the end marker reaches the tail while the init never ran. That is the end-marker-only state the code must reject.
  • HISTFILE is set by that .zshrc, so histfile=unset now depends on the init's unset HISTFILE; with the end-marker-only check restored, the test fails with histfile=/tmp/dim-consumer-history (verified), and with this head it passes 3 of 3.
  • /bin/zsh absent still skips the case; the doc comment says so.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawn. The reworked test is not vacuous: Harness::with_context sets the shell's HOME to harness.cwd (tests/integration/tests/minimal_execution.rs:187-192), the rc consumes only the prefix before the trailing printf and cannot consume its end marker, and with crates/dim-agent-capabilities/src/shell_session.rs:600 reverted to the end-marker-only condition the test fails with histfile=/tmp/dim-consumer-history; at this head it passes. The remaining cross-attempt pairing is noted separately.

@eric8810
eric8810 requested a review from yyhhyyyyyy November 26, 2026 04:33
…ails

The first-command shell selection occasionally failed on CI without showing what
the tool answered. Show the result text in the assertion message.

Refs #2032
The init command's capture is empty when the shell never runs the wrapper, so
the failure reported nothing that explained it. Read the shell task's tail
instead. A fresh HOME with zsh, for example, runs the new-user wizard, which
consumes the wrapper line and now leaves that wizard text in the message.

Refs #2032
zsh loads its newuser module at boot when the user has none of `.zshenv`,
`.zprofile`, `.zshrc` or `.zlogin`; the module runs a startup wizard that reads
the first line as its answer. A persistent shell in such a home never printed the
init end marker and the first command failed with "shell did not initialize".

Start zsh with `NO_RCS` only in that case: there is no user startup file to load,
and skipping the global rcs is what keeps the wizard from consuming the command.
A home with any of those files keeps loading them as before.

The minimal-execution preference flow reproduced this deterministically with a
fresh HOME and now passes.

Refs #2032
Review round on #2206:

- Shell initialization no longer depends on which home the shell reads. The
  init wrapper is written again until its end marker reaches the shell's tail,
  so a startup consumer (zsh's newuser wizard), a `ZDOTDIR` or a
  `platform_home`/`HOME` mismatch cannot lose it. The zsh `NO_RCS` argument and
  the home check that selected it are removed.
- A shell's background jobs are released, and their release confirmed, before
  the shell records its terminal: the worker kills each live job with the
  SIGKILL escalation and waits for it. The terminal sweep keeps a SIGKILL
  backstop instead of one unconfirmed SIGTERM, and the unused `terminate_job`
  helper is gone. A job that ignores SIGTERM no longer outlives its terminal.
- The interrupt wording matches what shells do: some print the end marker after
  Ctrl+C and end the command with its interrupted status; only a command still
  running after the two-second wait makes the owner terminate the shell and
  sweep it as a reset.
- The converted-command stop test asserts the terminal and that the next call
  runs, both of which hold for either shell behavior, and a new test stops a
  shell with a SIGTERM-ignoring job and checks the process is gone.

Refs #2032
…inal

The page said only that shell exit sweeps its children. State the new promise:
before the shell writes its terminal it releases each live job with a SIGKILL
escalation and waits for it.

The SIGTERM-ignoring job test now asserts the process is not alive at the moment
its `exec/ended` is observed, so it pins release-before-terminal instead of a
two-second window.

Refs #2032
Review round on #2206:

- A shell command that outlives Ctrl+C runs in the terminal's foreground
  process group, not the shell's. `HostPlatform::kill` now signals that group
  with SIGKILL and waits for it before it terminates the shell, so the command
  itself is released on macOS, where no `/proc` tree reaches it. The shutdown
  keeps the shell's own group to `PtyProcessTree::terminate`.
- The init accepts an end marker only after a copy's start marker reached the
  shell's tail. An end marker a startup consumer emitted by itself no longer
  counts as initialization.
- The job-release wording matches the code: release is best effort, a failed
  kill is not reported, and a descendant that left the job's group or session
  can outlive its terminal.

Tests: `stopping_a_command_that_ignores_the_interrupt_leaves_no_process` and
`a_startup_consumer_cannot_skip_the_init`; the macOS flow selection includes the
first so that path runs on macOS.

Refs #2032
A stopped shell command's terminal is the interrupted wrapper line's own
status: it can be `completed` when the line continues past the interrupted
command (`sleep 60 || true`), `failed` for the interrupted status of a line that
stops there, or a shell reset when the owner had to terminate the shell.

Also match the job-release text to the code: the worker attempts to release each
live job whose pid is known, by SIGKILL and a wait of up to two seconds, and
drops `kill_job`'s result.

Refs #2032
The test wrote its `.zshrc` into a home the harness replaces, read the wrapper
whole, and asserted a value an empty home produces anyway. It now writes the
consumer into the shell's HOME after the harness exists, consumes the line up to
the boundary before the final `printf`, and keeps `HISTFILE` set only if the init
did not run. The relaxed end-marker check fails it.

Also: `HostPlatform.md` says initialization waits for one copy's start marker and
then its end marker, and `PtyProcessTree::kill_foreground_group` is crate-only.

Refs #2032
…r the init

Delta review on #2206:

- Terminating a shell for any reason — a shell command's stop, a shell kill or
  a Session close — now signals the terminal's foreground process group and
  waits for it, so the command the shell was running does not outlive the
  shell's terminal. `PtyProcessTree::terminate` and its `Drop` both do it.
- Each init attempt carries its own marker pair, and an attempt counts only when
  its own start marker precedes its end marker in the tail. An end marker a
  startup consumer printed for an earlier attempt no longer completes a later
  one. `init_complete` holds the order rule.

Tests: `closing_a_session_releases_an_occupying_command` (Session close path,
selected by the macOS flow list) and the unit test
`an_init_copy_completes_only_after_its_own_start_marker`.

Refs #2032
The owner records a known exit code on a `failed` terminal: a shell command
that ended non-zero, or a shell job whose completion marker carried it. The
background result only built a `CommandExit` for an `exited` or `signaled` wait
status, so `exec/ended` for those tasks carried no `exitCode` and said "command
failed".

`settled_from_reply` now derives the exit from the reply's own fields, so any
terminal that has one reports it, and a `CommandFailed`/`UnknownExit` summary
names the exit status through `exit_failure_summary`.

Also: `BackgroundExec::stop`'s doc comment no longer claims a stopped task always
ends `cancelled`; a shell command ends with the interrupted line's own status and
wakes, matching `WorkspaceTools.md`.

Tests: `a_handed_off_command_keeps_its_exit_code` and
`a_detached_job_keeps_its_exit_code`; both fail without the fix.

Refs #2032
`BackgroundExec::stop`'s doc comment is part of the generated TypeScript
declaration; regenerate it after the wording change.

Refs #2032
The two exit-status tests only asserted `exitCode`, so reverting the summary
match in `background_result` kept them green while `exec/ended` said "command
failed". They now assert the `summary` field and the result text, and the
detached-job case also asserts the stored record `BackgroundExec.stop` answers.

Refs #2032
The retry replaced its only marker pair every second, even after that copy had
started, so a copy that completed after the retry interval had its completion
discarded and the shell could report a timeout after initializing.

A started copy is now left to finish; a new copy is written only while the
current one has not started. Each copy keeps its own markers, so an end marker
from an earlier copy still cannot complete a later one.

Refs #2032
Per the #2002 owner contract, a job whose release is unconfirmed stays running
until the release or the shell sweep writes its terminal, and the stop answers a
stop-requested result instead of blocking.

- `BackgroundExec.stop` subscribes to a per-task pending flag. The supervisor
  sets it when `HostPlatform.kill` answers anything but a confirmed kill
  (`task_running`, a kill failure, an I/O error), and the stop answers
  `TaskError::Running` at once. A fallback bound keeps the reply bounded even
  when a confirmed kill's terminal never arrives.
- The record stays running and the Session hold and cleanup stay with the
  supervisor, which keeps waiting; the terminal still comes only from the
  confirmed release or the shell sweep, so exactly one `exec/ended` follows.
- `session.exec.stop` maps the pending stop to the app error
  `exec_task_running`, and `exec_stop` returns a failed result with code
  `exec_task_running` and a sentence that says the stop is not confirmed yet.
- `HostPlatform.md` states the owner side: a job with no pid answers
  `task_running` after two seconds and keeps a watcher; a failed kill keeps the
  watcher; the record stays running until the release or the sweep.

Test: `host_platform_flow::a_job_without_a_pid_stays_running_until_the_shell_sweep`
(bounded `task_running`, record running, sweep terminal). The normal release is
still `cancelled` in `stop_background_task`.

Refs #2032
The retry only checked its newest marker pair, so a copy still executing when
the next one was written could never complete the initialization: a shell slower
than the retry interval (a `preexec` that sleeps, for example) printed every
copy's end marker within the deadline and was still reported as uninitialized.

Every written copy keeps its markers until the deadline and any copy whose own
start marker precedes its own end marker completes the initialization. A copy
that started is still not replaced, so copies no longer queue behind each other
once the shell runs one.

Test: `a_slow_shell_still_initializes` (zsh `preexec` sleeping 1.5 s); it fails
on the previous loop with `shell did not initialize`.

Refs #2032
Base-1 (#2174) landed `xtask/access-layer.json`, and this branch removes
`Session::service_opt`; the listed entry no longer has a definition, so
`xtask-check` would report it as listed one and found none.

Refs #2032

@yyhhyyyyyy yyhhyyyyyy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review at 4037ca7, round 12

Reviewed head 4037ca7598418c9ae578ed8d3c83e504938bd7e4 (base origin/main 508d69911f2b444885066819e94b1e6acf8b65d1), the full main...head (22 files, 1168 insertions, 1369 deletions). The r11 review approved 68ff0118. Since then the branch was rebased onto current main and adds one commit, 4037ca759. The patch is preserved and the access layer list now matches the code. No blocking finding.

Blocking

None.

Rebase and the new commit

  • git range-diff ade859730..68ff0118 508d69911..4037ca75 pairs the 19 old commits with the new history one to one; 18 are identical, and commit 17 (804115613 / 929e95590) differs only in the regenerated npm/branch-services.d.ts. Its SessionsErrorThrown now also carries #2174's routed codes (npm/branch-services.d.ts:1830), and TaskErrorThrown carries the new running variant (:1833), matching TaskError at crates/dim-agent-capabilities/src/workspace_tools/background.rs:55-68. Commit 20 is new: 4037ca759 removes five lines from xtask/access-layer.json, the session-forwarding entry for Session::service_opt that #2174 landed beside Session::service (xtask/access-layer.json:521).
  • No service_opt or public_opt call remains, and no execStop catalog name remains. Call::ExecStop is still the session.exec.stop RPC variant, and its arm now calls BackgroundExec (crates/dim-app-server/src/connection.rs:1627-1650). The exec_stop workspace tool and the Call::ExecStop variant remain; both are live-facing names, not the removed service.
  • cargo run --locked -p xtask-check passes with access layer passed (172 allowed), service declarations passed and the other checks. cargo run --locked -p xtask -- check passes with plugin documents passed (43 plugins). cargo fmt --all -- --check passes. The PR body's Access-layer allowlist section matches the tree.

Older items

  • The r11 blocking item remains fixed at this head. The Rust patch is identical to 68ff0118: send_initial keeps every written pair (crates/dim-agent-capabilities/src/shell_session.rs:570), accepts only a pair whose own start marker precedes its own end marker (:587, :1241-1244), and stops writing once a copy started (:592-609).
  • Remaining P3, not blocking: the harness does not clear ZDOTDIR (tests/integration/tests/minimal_execution.rs:187-197; :191 retains every env entry except HOME), so on a machine that sets it a_startup_consumer_cannot_skip_the_init can pass without exercising the consumer. Fix: drop ZDOTDIR from platform.env.
  • Remaining P3, not blocking: if a failed terminal append removes a task while stop waits, both watches close; the pending arm maps a closed watch to running (crates/dim-agent-capabilities/src/workspace_tools/background.rs:755) while the ended arm would answer closed (:752-753), so the reply depends on the select race at :750-756. It needs the append failure path, and the next stop reads the Timeline. Fix: treat a closed pending watch as closed.
  • The started write gate still has no direct test; after the every-copy watch it only bounds how many copies queue. No request.
  • Withdrawn items remain withdrawn: the Unix Drop foreground-release fixture and the end-to-end pending-stop fixture are recorded in the PR body's Known issues.

Cross-PR

  • #2197 (open, head b29d2886) adds docs/architecture/rust-agent/plugins/ShellSession.md, whose line 6 says the part provides dyn ExecStop, and whose table lists B:Timeline (:21), B:Dispatcher (:22) and S:SessionLifecycle (:24). At this head ShellSessionPlugin injects BackgroundExec, HostPlatform, BranchLifecycle, SessionConfig and TimelineIdentity (crates/dim-agent-capabilities/src/shell_session.rs:1178-1184), and the ExecStop service is gone. git merge-tree --write-tree 4037ca75 b29d2886 exits 0, so the text merges, but the merged tree's plugin-document comparison (xtask/src/plugin_docs.rs:73-79) would fail. Whichever lands second updates the page and the stop face.
  • #2174 is now in main; the new commit removes the entry that main landed, and the access check passes at 172 allowed.

CI and verification

At this head changes, macos-native and windows-cli pass; verify (linux) is in progress; scripts, static-checks, web, dependencies and acp-registry skip by path filters. Locally, with an isolated HOME, TMPDIR and XDG under the review data directory and the pinned 1.100.0 toolchain, the range-diff above, xtask-check, xtask check and fmt --check pass; the worktree is clean at the head. The Rust patch is identical to 68ff0118, where the 30-case minimal_execution suite, the init cases and the pending-stop flow passed; macos-native builds and runs its suite at this head.

Unverified

  • The merged-tree plugin-document outcome with #2197 is derived from the page, the injected set and the checker, not executed.
  • Windows runtime behavior of the init and job-release paths, as before.
  • verify (linux) was still running when this review was written.

Verdict: APPROVE.

@eric8810
eric8810 removed the request for review from zerob13 November 26, 2026 14:09
@eric8810
eric8810 merged commit 79ce0a2 into main Nov 26, 2026
eric8810 added a commit that referenced this pull request Nov 26, 2026
`main` at `06f14021e` lists `("execStop", "control")` among the product's
internal names, while #2206 took the `ExecStop` service out of the
capabilities crate. `cargo run -p xtask -- check` therefore fails on main
itself:

    execStop: internal(control) names no catalog service

The name has nothing left to mark, so it leaves the list. Verified against
`origin/main` in a scratch checkout before touching this branch: the same
failure appears there with none of this branch's changes.

Refs #2032
Refs #2227
eric8810 added a commit that referenced this pull request Nov 26, 2026
#2206 gave the ShellSession part its stop path through BackgroundExec and
left the page listing Timeline, Dispatcher and SessionLifecycle, which the
part no longer injects: `cargo run -p xtask -- check` fails on main with
three "dependency table explains ... which it does not inject" findings.
The row and the sentence about `dyn ExecStop` go with the code they
described.

Refs #2032
Refs #2227
yyhhyyyyyy added a commit that referenced this pull request Nov 26, 2026
fix(exec): restore the repository checks after #2206
eric8810 added a commit that referenced this pull request Nov 26, 2026
- The usage cache key fingerprints the whole tool definition, so a
  schema-only change no longer reuses the previous request's cost.
- #2206 removed ExecStop after #2197 added its face; drop the face and the
  ShellSession page's stop wording, and align the dependency table with the
  part's injects. This restores the repository check.

Refs #2135
soulmachine pushed a commit to soulmachine/dim that referenced this pull request Nov 27, 2026
Two leftovers kept `xtask check` red on main:

- The product still marked `execStop` as `internal(control)`, but arcships#2206 removed
  that service; the catalog check reported that the entry names no catalog
  service.
- `ShellSession.md` still described `B:Timeline`, `B:Dispatcher` and
  `S:SessionLifecycle` as dependencies and named a `dyn ExecStop` the part no
  longer provides. The page now lists the services the part injects and says
  `session.exec.stop` goes to the branch's `BackgroundExec`.

Refs arcships#2206
Refs arcships#2032
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants