fix(broker): address #1939 must-fix PTY delivery review findings

Closed
KH
2mo ago
+1049-79

Addresses the must-fix (M1–M6) review threads on #1939 (trunk → main, carrying #1891), plus thread #17 (OpenCode any_output, reassigned here as the OpenCode instance of M2). The other P2/P3 items are handled separately by train-relay-1939.

  • M1 (pty_worker.rs ~2786): a terminally failed, already-written delivery is latched. Its id is fenced against replay for the PTY lifetime; the fence is unbounded, and a replay gets delivery_failed, never a second paste. Injection holds until the composer is provably idle, or until an operator-wide flush_injections releases it explicitly. A tail missing from the viewport is not treated as proof the draft is gone.
  • M2 (delivery_verification.rs 188/185/419, detection.rs 48): generic any_output (including OpenCode) cannot confirm a draft whose tail ends at, straddles, or appears anywhere after the cursor, nor while this body's text sits to the cursor's right. Only known prompt and border glyphs are ignored; a placeholder is not body text. A wrapped-echo compact-tail match keeps the same-read suffix, so its turn marker is not lost.
  • M3 (worker_events.rs 1069/1090): delivery_failed sets BlockedOnSend (and publishes stuck) only while other deliveries for the worker are pending. Otherwise the worker returns to Working and publishes working, replacing any earlier stuck.
  • M4 (wrap.rs 139, pty_worker.rs 2521): recovery writes are cancellable in the PTY drainer, which re-checks before the primary key and after the follow-up delay. Human input withholds queued End/CR/LF in both worker and wrap mode. The recovery ack now assesses real acceptance after a takeover instead of always failing.
  • M5 (worker_events.rs 953): a PTY delivery_verified must carry harness_acceptance or completed_replay. Legacy echo/timeout_fallback or unqualified PTY frames are ignored and do not clear custody. Headless confirmations are unchanged.
  • M6 (pty_worker.rs 1422): only a non-empty, drainer-admitted write_pty takes composer ownership.

Human reviewer: please check explicitly

  • Chunked Codex initial write, partial-body latch (pty_worker.rs, initial_injection_incomplete arm). This is the one fix without a dedicated regression test: the arm sits inside the worker select loop, and the repo has no harness that drives that loop. It calls the tested latch_failed_written_delivery helper, so please confirm by reading that the call happens before the arm returns and that the injection text passed is the body that was being written.
  • Latch release policy. A failed draft now holds injection until the composer is provably idle (composer_is_idle), or until an operator-wide flush_injections. Harnesses the broker cannot model as idle will therefore wait for a human flush after a terminal failure. That is fail-closed by design, but it is a behaviour change worth a deliberate sign-off.

Verification (local, at 0202e9f81; CI never runs on PRs into trunk: rust-ci.yml gates changes to non-PR events or trunk→main)

Toolchain: cargo +1.97.0. The repo has no rust-toolchain pin, and CI installs dtolnay/rust-toolchain@stable (as #1947 does for StarSling). Trunk does not compile on 1.94 because of atomic_try_update (E0658).

Clean env used for broker tests: env -u RELAY_ATTEST_BROKER_HOOK_PATH -u RELAY_ATTEST_GIT_CONFIG_COUNT -u RELAY_ATTEST_GIT_CONFIG_INDEX -u RELAY_ATTEST_SESSION_ID -u GIT_CONFIG_COUNT. Inside a broker-spawned agent shell, those variables leak into the spawner:: git-hook tests; this is independent of this change.

$ cargo +1.97.0 fmt -p agent-relay-broker -p relay-pty -- --check
(no output, exit 0)

# CI's exact command (rust-ci.yml:122), run verbatim on both trees:
$ cargo +1.97.0 clippy -- -D warnings      # PR 0202e9f81: exit 0
$ cargo +1.97.0 clippy -- -D warnings      # trunk da7d54de3: exit 0

$ cargo +1.97.0 clippy -p agent-relay-broker -p relay-pty --all-targets -- -D warnings \
    -A clippy::large_enum_variant -A clippy::result_large_err
exit 0
# Without the two -A flags, the only errors are pre-existing, in untouched code:
#   large_enum_variant  crates/broker/src/node_control.rs:7930
#   result_large_err    crates/broker/src/node_control.rs:8550

$ cargo +1.97.0 test -p relay-pty --lib
test result: ok. 263 passed; 0 failed

$ <clean env> cargo +1.97.0 test -p agent-relay-broker --no-fail-fast
lib:                     test result: ok. 1445 passed; 0 failed; 7 ignored
tests/continuity.rs:     ok. 12 passed
tests/fleet_wire_fixtures.rs: ok. 2 passed
tests/journal_lock_cli.rs:    ok. 3 passed
tests/muse_startup_cli.rs:    ok. 2 passed
# Timing flakes, each in code this PR does not touch; each passed 3/3 when re-run alone:
#   snippets::tests::mcp_preflight_tolerates_broken_pipe_on_write
#   cli_mcp_args::tests::register_timeout_remains_bounded
#   pty_worker::tests::initial_native_pty_human_input_cancels_without_submit_or_replay
#   devin::tests::paste_burst_parks_but_delayed_enter_submits

Red-first (mutation) checks. Each fix was reverted on its own, then cargo +1.97.0 test -p <pkg> --lib <filter> was run and the file restored. All 15 went red. The chunked-Codex latch (Bugbot/cubic) has no dedicated test: that arm sits inside the select loop, which has no harness. It reuses the tested latch_failed_written_delivery and composer_owned_by_delivery helpers.

ItemMutation (reverts the fix)Killing test(s)Result
M1 gatecomposer_owned_by_delivery: drop || failed_composer_latch.is_some()failed_written_delivery_latches_injection_and_fences_replayFAILED 1/1
M1 releasefailed_draft_released: return true unconditionallyfailed_draft_latch_holds_until_the_composer_releases_itFAILED 1/1
M2 any_output / #17assess_harness_acceptance: drop && !tail_touches_cursor(snapshot, &tail)generic_repaint_cannot_confirm_a_draft_straddling_the_cursor, opencode_output_cannot_confirm_a_draft_at_the_cursorFAILED 2/2
M2 wrapped echoend_of_compact_match: compact.rfind(..).filter(|_| false)? (no suffix preserved)wrapped_echo_preserves_same_chunk_acceptance_activityFAILED 1/1
M3let still_blocked = true;terminal_failure_without_remaining_work_does_not_block_the_workerFAILED 1/1
M4drainer: remove the post-delay if is_cancelled() { return Err(write_cancelled()); }cancelled_followup_is_withheld_and_drainer_keeps_running (relay-pty)FAILED 1/1
M5accepted_delivery_verification: drop the echo/timeout_fallback and unqualified-PTY armspty_delivery_verified_requires_harness_acceptanceFAILED 1/1
M6human_write_takes_ownership: return trueonly_an_admitted_nonempty_human_write_takes_ownershipFAILED 1/1
#1954 review: long draftdrop !tail_near_cursor and !has_visible_text_at_or_after_cursor from the generic branchgeneric_output_cannot_confirm_a_long_draft_with_cursor_at_its_startFAILED 1/1
#1954 review: off-viewportfailed_draft_released: also release when the tail is absent from the viewporta_tail_missing_from_the_viewport_does_not_release_the_latchFAILED 1/1
#1954 review: cursor-row chromerestore the blanket !has_visible_text_at_or_after_cursorcursor_row_placeholder_does_not_block_generic_acceptanceFAILED 1/1
#1954 review: off-screen taildrop !body_text_right_of_cursorgeneric_output_cannot_confirm_a_draft_whose_tail_scrolled_awayFAILED 1/1
#1954 review: bordered draft headprobe the cursor row without stripping chromebordered_draft_head_right_of_cursor_stays_inconclusiveFAILED 1/1
#1954 review: symbolic draft headstrip every non-alphanumeric character instead of CURSOR_ROW_CHROMEsymbolic_draft_head_right_of_cursor_stays_inconclusiveFAILED 1/1
#1954 review: published stuckzero-pending case publishes stuck/blocked_on_sendlast_failed_delivery_publishes_a_non_stuck_stateFAILED 1/1

Known follow-up: #1939 P2 (train-relay-1939) adds composer_holds_tail. Whichever of the two PRs merges second should switch failed_draft_released from current_composer(..).contains(&tail) to it, so a > b row inside a body cannot release the latch early.

Regression tests: failed_written_delivery_latches_injection_and_fences_replay, failed_draft_latch_holds_until_the_composer_releases_it, generic_repaint_cannot_confirm_a_draft_straddling_the_cursor, opencode_output_cannot_confirm_a_draft_at_the_cursor, wrapped_echo_preserves_same_chunk_acceptance_activity, compact_match_end_maps_back_to_raw_offsets, terminal_failure_without_remaining_work_does_not_block_the_worker, terminal_failure_with_remaining_work_stays_blocked_on_send, cancelled_followup_is_withheld_and_drainer_keeps_running, pty_delivery_verified_requires_harness_acceptance, only_an_admitted_nonempty_human_write_takes_ownership.

🤖 Generated with Claude Code


[!NOTE]
Medium Risk
Changes core PTY injection, acceptance heuristics, and worker blocking behavior; incorrect latch release could stall queues, but the design is intentionally fail-closed with operator flush override.

Overview
Hardens PTY message delivery so relay injections are not mistaken for acceptance and failed bodies are not pasted over or replayed.

Harness acceptance (delivery_verification) now treats generic post-echo output (e.g. Muse/OpenCode any_output) as inconclusive while a draft’s tail is near the cursor, body text sits right of the cursor, or wrapped echoes need compact-tail matching. failed_draft_released only clears when the composer is provably idle—not when the tail scrolled off-screen. Snapshot::to_plain_from_cursor supports those cursor checks.

PTY worker adds a failed-composer latch: terminally failed written deliveries fence their id from replay, pause further injection until idle (or operator-wide flush_injections), and latch on partial chunked writes and human takeover. write_pty ownership applies only to non-empty, drainer-admitted writes. Submit-key recovery is cancellable via relay-pty so human input cannot fire a delayed Enter/CR on their draft.

Broker runtime ignores PTY delivery_verified without harness_acceptance / completed_replay, and after delivery_failed leaves the worker Working when no other deliveries are pending (instead of staying stuck).

Reviewed by Cursor Bugbot for commit 0202e9f81b81bea4d5b9f1396724f1d9306d162d. Bugbot is set up for automated code reviews on this repo. Configure here.


Agent Relay sessions

  • claude session a4d98f2e · opened via gh pr create · last active 2026-10-10