{
  "status": "Read-only investigation complete; no production or test files were edited, and no builds/tests were run per assignment constraints.",
  "source_grounding": [
    "The existing RED analog is `crates/spt-daemon/tests/brain_decouple.rs`. It already creates a real broker/PTY/local-IPC stack and a non-reading remote controller (`suspended_brain_controller_is_stall_evicted_take_completes_viewer_ticks`, lines 220-375). Its helper substrate is reusable: isolated home/name and scoped child kill at lines 69-93; real flood PTY child at 95-120; framed send/connect at 122-135; bounded subscribe at 137-193; stall-evict query at 195-218.",
    "That test deliberately proves only viewer progress, logical takeover, promptness, and the stall-evict tally (brain_decouple.rs:26-35, 348-374). Its black-hole thread sleeps 120 seconds and is abandoned to process exit (261-287), so it cannot detect a physically stranded writer or connection.",
    "`ControllerSink` retains both the per-connection `SharedSend` and the controller writer `JoinHandle` (`crates/spt-daemon/src/broker.rs`:620-656). `controller_writer` marks the write in flight, acquires `SharedSend`, and performs blocking `write_frame` (`broker.rs`:1558-1698, especially 1603-1643 and 1658-1688).",
    "Logical stall eviction only records the eviction and removes the controller sink (`stall_evict_controller`, broker.rs:1179-1212). It performs no transport cancel, connection shutdown, or writer join. Independently, `handle_conn` keeps its own `SharedSend`, blocks reading the still-open peer, and reaches connection cleanup only after read EOF (`broker.rs`:3029-3050 and 3226-3245). Thus dropping the logical controller row does not release the physical write/thread/connection.",
    "The active capture demonstrates the missing assertion. Four real `--take` installs immediately entered nonzero-sequence writes and acquired the send lock (`daemon.stderr.active.log`:8162-8178: seq 174/20/19/19). Logical eviction fired for all four (`8234-8237`), but those writes did not return then. They returned `result=error` only when `BRAIN_UPDATE_RESTART` closed the brain about 128 seconds after write start (`8522-8529`, `8532`, `8565`, `8582`). A second cycle again entered nonzero writes (`8781-8791`, `9052-9060`), logically evicted at `9269-9272`, and had no corresponding `CTRL_WRITE_DONE` through the captured tail at line 9530.",
    "The helper itself only keeps rc stdin alive: `keep-rc.ps1`:6-11 pipes one blank line plus an infinite sleeping producer into `spt.exe rc <endpoint> --take`. It does not itself black-hole stdout; the parent must retain a redirected stdout pipe without reading it. The exact parent command used by the operator is not checked into the repo/capture."
  ],
  "proposed_test": {
    "file": "`crates/spt-daemon/tests/brain_decouple.rs`, immediately after existing `suspended_brain_controller_is_stall_evicted_take_completes_viewer_ticks` (currently ends at line 375). Keep it in this binary to reuse the exact real-broker/PTY/wire helpers and the documented nextest/process-isolation contract at lines 45-51.",
    "symbol": "`#[cfg(windows)] #[test] fn non_draining_controller_stall_evict_releases_writer_and_connection()`",
    "why_windows_only": "The RED condition being locked down is the observed synchronous Windows named-pipe framed write. A large finite burst can fill UDS buffers too, but the load-bearing regression gate should not weaken the exact Windows mechanism into a platform-dependent timing test. The existing cross-platform test remains the logical/fan-out companion.",
    "new_private_helpers": [
      "`accept_one_with_handler(&Arc<Broker>, &str) -> (Stream, JoinHandle<()>)`: start one `Broker::serve_once`, dial/hello with existing `connect`, and return that connection's handler handle. `Broker::serve_once` is already public specifically for tests (`broker.rs`:2919-2927); no production API addition is needed.",
      "`finite_burst_spawn_req(endpoint)`: Windows `cmd` child that waits for trigger line 1, emits `SEED`, waits for trigger line 2, emits a finite roughly 1-2 MiB burst, then remains alive. Finite output is important: it exceeds named-pipe capacity but stays far below both the 4096-frame controller queue and 4096-chunk ring, isolating the 400 ms in-flight-write eviction from the separate 5 s full-channel eviction and preserving the replay floor.",
      "`send_input_no_ack(conn, sid, bytes)`: reuse `InputReq`/`encode_bytes` and send `KIND_INPUT` with `ack=false`, matching the fire-and-forward controller path and ensuring no handler ack competes for `SharedSend`. The no-ack wire contract is already represented in `tests/broker.rs`:726-739 and 759-775.",
      "`session_snapshot(conn, sid) -> SessionInfo` and `stall_evict_count_on(conn)`: bounded reads on a dedicated draining control connection using `KIND_SESSIONS`/`KIND_SESSIONS_REPLY` and `KIND_STALL_EVICTS`/reply. Keep every blocking read on a worker + `recv_timeout`, following `brain_decouple.rs`:137-218 and `inject_control_wedge.rs`:248-280.",
      "`wait_finished(&JoinHandle<()>, Duration) -> bool`: poll `is_finished` in short slices. Do not move the handle into a join worker until it is finished; the main test needs to retain a direct witness to the exact black-hole connection.",
      "`take_from_and_first_output(name, sid, from_seq, deadline)`: a draining fresh controller that subscribes from the frozen nonzero cursor and returns both `SubscribeOutcome` and the first `OutputEvent.seq`, irrespective of whether output or `KIND_SUBSCRIBED` wins wire ordering."
    ]
  },
  "orchestration": [
    "Set `SPT_BRAIN_WRITE_DEADLINE_MS=400`, initialize the existing isolated home, bind a real `Broker`, and use `accept_one_with_handler` for the spawner connection and the eventual black-hole connection. Only after the black-hole connection is accepted should the ordinary `broker.serve()` loop start for probe/fresh-controller connections; this prevents it racing `serve_once` and preserves the exact handler handle.",
    "Spawn the finite-burst child through the real `KIND_SPAWN` path and obtain `sid`. This retains the production PTY drain (`PtySession::drain` feeds `OutputLog::append`, broker.rs:3335-3388).",
    "Connect remote controller R with `SubscribeReq { intent: Control, by: Some(\"operator-one\"), from_seq: 0 }`. Drain through its `KIND_SUBSCRIBED` acknowledgement. This establishes an honest remote controller before black-holing; it avoids the subscribe-ack/send-lock race during the actual stall.",
    "Send trigger 1 with `ack=false`; continue draining R until a real `OutputEvent` containing `SEED` has `seq > 0`. Record `drained_seq`. This is the non-vacuous sequence precondition: the next PTY output written after reads stop is necessarily nonzero.",
    "Query the dedicated control connection and assert the precondition `controller_by == Some(\"operator-one\")`; record the baseline stall-evict tally.",
    "Send trigger 2 with `ack=false` and never read R again. Poll `Broker::session_output_seq(sid)` until it is at least `drained_seq + 64`, proving the real PTY produced and the broker sequenced the finite burst. The finite burst then stops while the child remains alive.",
    "After the 400 ms deadline, send `KIND_SESSIONS` on the independent draining control connection. This executes `reap_dead_controller -> stall_evict_controller` and is the logical-eviction synchronization point. Read the reply within a 2-3 second watchdog; then query the tally.",
    "Record `logical_release_at`. Without reading from or dropping R, require R's captured `handle_conn` JoinHandle to become finished within a separate bounded physical-release deadline (recommended 2 seconds, i.e. 5x the shrunk write deadline), then `join()` it successfully.",
    "Move the still-unread client R into a bounded write probe and assert a new framed command fails. This verifies the old physical connection is unusable; a merely-cleared controller slot with a live pipe cannot pass.",
    "Open fresh controller C and subscribe from the frozen `resume_seq`. Drain it and assert control succeeds and the first replayed output sequence equals that frozen cursor. Because `from_seq > 0`, `become_controller` selects raw ring entries `seq >= from_seq`, not the cold repaint (`broker.rs`:1040-1047); this proves cancellation did not skip the frame whose old write never completed.",
    "Collect all booleans/results before asserting. On the RED path, explicitly drop R to unblock the old writer, bounded-join what can finish, kill only `broker.session_pid(sid)` with existing `kill_pid`, and call `broker.stop`; do not let an expected failure ride nextest's global slow timeout."
  ],
  "exact_assertions": [
    "`seed.seq > 0` and decoded seed bytes contain the marker: the gate drove real, nonzero-sequence PTY output.",
    "Before the burst: `controller_by == Some(\"operator-one\")`.",
    "After the logical probe: `stall_evict_count == baseline + 1` (exactly one isolated session/controller) and post-snapshot `controller_by.is_none()`.",
    "Let `high_water = Broker::session_output_seq(sid).unwrap()`. Assert `frozen_resume > 0 && frozen_resume < high_water`; successful writes advanced the cursor only through the last physically accepted frame, while later real PTY frames remain in the ring (`delivered_through` contract at broker.rs:701-719; writer advances only after `write_frame` succeeds at 1640-1643/1686-1695).",
    "The `KIND_SESSIONS_REPLY`/logical eviction completes within the logical watchdog, so the test distinguishes logical success from physical cleanup rather than reporting a generic broker hang.",
    "`r_handler.is_finished()` becomes true before `logical_release_at + 2s`, then `r_handler.join().is_ok()`. The future fix must define connection-handler completion to occur only after its hard-cancelled controller writer has been joined; this makes the handler join the observable writer/thread completion witness without a new protocol/test API.",
    "A bounded `write_frame` on old R returns `Err`, proving physical connection shutdown while the client still holds its endpoint.",
    "Fresh controller outcome is `Controller` (or `TookControl` only if implementation preserves a transitional incumbent) and its first `OutputEvent.seq == frozen_resume`; preferably require `Controller` because the post-eviction slot was asserted empty."
  ]
}