A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
keep the draft consumed when the daemon socket closes after a prompt
Sebastian Müller4247a2599561
diff --git a/.changes/fix-tui-draft-consumed-on-close.md b/.changes/fix-tui-draft-consumed-on-close.mdnew file mode 100644index 0000000000..8bd94e1068--- /dev/null+++ b/.changes/fix-tui-draft-consumed-on-close.md@@ -0,0 +1 @@+- Keep a submitted prompt draft consumed when the daemon connection closes before its reply, preventing an accidental duplicate submission after reconnect. Inspired by [Pi Durable](https://github.com/earendil-works/pi/tree/main/packages/durable) and [Pi Pocket's §05 “Exactly once” explanation](https://tannermidd.github.io/pi-pocket/durable.html#once).diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f77b0d678d..a5bd2f6be6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -374,6 +374,9 @@ jobs:for scenario in graceful_shutdown goal_backoff draft_disconnect; doverifier="scripts/review_${scenario}_parity.py"if [ -f "${verifier}" ]; then+ if [ "${scenario}" = "draft_disconnect" ]; then+ python3 scripts/test_review_draft_disconnect_parity.py || comparison_status=1+ fipython3 "${verifier}" --receipt "${RUNNER_TEMP}/lifecycle-parity-receipts/${scenario}.json" || comparison_status=1fidonediff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rsindex bd55096d7d..960ec8db1b 100644--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs@@ -5644,18 +5644,22 @@ async fn assert_close_reason_survives_late_turn_status(reason: &str, explanation!rendered.contains("reply must not arrive"),"held response leaked:\n{rendered}");- let last = outcome.frames.last().expect("final frame");- assert!(- last.contains("turn failed: prompt cancelled"),- "the post-close cancellation must reach the frame:\n{last}"- );assert!(- last.contains(&error_row),- "close error row must persist after cancellation:\n{last}"+ !rendered.contains("timed out waiting for the headless render condition"),+ "the close/cancellation render barrier must complete:\n{rendered}");+ // Verify coexistence after the cancellation status in one observed frame.+ // A later successful reconnect may resync the transcript again.+ let checkpoint = outcome+ .frames+ .iter()+ .find(|frame| frame.contains("turn failed: prompt cancelled") && frame.contains(&error_row))+ .unwrap_or_else(|| {+ panic!("the close error and cancellation must share a frame:\n{rendered}")+ });assert!(- !last.contains(&format!("session closed ({reason})")),- "info downgrade remains:\n{last}"+ !checkpoint.contains(&format!("session closed ({reason})")),+ "info downgrade remains:\n{checkpoint}");drop(supervisor);}diff --git a/crates/pa-daemon/tests/supervisor_e2e/tool_results.rs b/crates/pa-daemon/tests/supervisor_e2e/tool_results.rsindex 990e0890dc..101c3736d5 100644--- a/crates/pa-daemon/tests/supervisor_e2e/tool_results.rs+++ b/crates/pa-daemon/tests/supervisor_e2e/tool_results.rs@@ -78,7 +78,9 @@ fn tool_result_entries_persisted_and_streamed() {tool_result_message = event["message"].clone();}}- Some("turn_end") => break,+ // The first turn ends after the tool result; the scripted final+ // assistant response is persisted only before agent_end.+ Some("agent_end") => break,_ => {}}}diff --git a/crates/pa-tui/src/daemon_client.rs b/crates/pa-tui/src/daemon_client.rsindex b3fe652779..4e28e40415 100644--- a/crates/pa-tui/src/daemon_client.rs+++ b/crates/pa-tui/src/daemon_client.rs@@ -227,21 +227,41 @@ pub(crate) fn client_event_from_value(value: &Value) -> Option<DaemonClientEvent}}+struct PendingRequest {+ reply: oneshot::Sender<Result<DaemonResponse, anyhow::Error>>,+ direct_owner: Option<Arc<()>>,+}+/// Connection state shared between the request side and the reader task.#[derive(Default)]pub(crate) struct Shared {/// Pending requests keyed by envelope id. `Ok` is a daemon answer/// (including a refusal); `Err` is a transport failure — a refusal is/// recoverable UI data, a dead connection is fatal.- pending: Mutex<HashMap<String, oneshot::Sender<Result<DaemonResponse, anyhow::Error>>>>,+ pending: Mutex<HashMap<String, PendingRequest>>,}impl Shared {+ pub(crate) fn register_pending(+ &self,+ id: String,+ reply: oneshot::Sender<Result<DaemonResponse, anyhow::Error>>,+ direct_owner: Option<Arc<()>>,+ ) {+ self.pending.lock().unwrap().insert(+ id,+ PendingRequest {+ reply,+ direct_owner,+ },+ );+ }+pub(crate) fn resolve(&self, id: &str, response: DaemonResponse) -> bool {let mut pending = self.pending.lock().unwrap();pending.remove(id)- .is_some_and(|tx| tx.send(Ok(response)).is_ok())+ .is_some_and(|request| request.reply.send(Ok(response)).is_ok())}/// Fail every pending request whose id starts with `prefix` with a@@ -255,8 +275,28 @@ impl Shared {.cloned().collect();for id in dead {- if let Some(tx) = pending.remove(&id) {- let _ = tx.send(Err(anyhow!(error.to_string())));+ if let Some(request) = pending.remove(&id) {+ let _ = request.reply.send(Err(anyhow!(error.to_string())));+ }+ }+ }++ /// A replaced link's EOF must not cancel requests sent over its successor.+ pub(crate) fn fail_direct_pending(&self, owner: &Arc<()>, error: &str) {+ let mut pending = self.pending.lock().unwrap();+ let dead: Vec<String> = pending+ .iter()+ .filter(|(_, request)| {+ request+ .direct_owner+ .as_ref()+ .is_some_and(|candidate| Arc::ptr_eq(candidate, owner))+ })+ .map(|(id, _)| id.clone())+ .collect();+ for id in dead {+ if let Some(request) = pending.remove(&id) {+ let _ = request.reply.send(Err(anyhow!(error.to_string())));}}}@@ -618,7 +658,7 @@ impl DaemonClient {};let line = serde_json::to_string(&envelope)?;let (tx, rx) = oneshot::channel::<Result<DaemonResponse>>();- self.shared.pending.lock().unwrap().insert(id.clone(), tx);+ self.shared.register_pending(id.clone(), tx, None);// The reader runs on another worker: it can die (and run its failure// sweep) between the entry check and this registration. Re-check after// inserting — a death it missed is caught here.@@ -699,10 +739,7 @@ impl DaemonClient {.map_err(|_| DirectRequestError::NotSent)?;let (reply_tx, reply_rx) = oneshot::channel::<Result<DaemonResponse>>();self.shared- .pending- .lock()- .unwrap()- .insert(id.to_string(), reply_tx);+ .register_pending(id.to_string(), reply_tx, Some(Arc::clone(&link.owner)));if !link.send(frame) {self.shared.pending.lock().unwrap().remove(id);return Err(DirectRequestError::NotSent);diff --git a/crates/pa-tui/src/daemon_client/tests.rs b/crates/pa-tui/src/daemon_client/tests.rsindex 918ff49f5e..3618a06ffc 100644--- a/crates/pa-tui/src/daemon_client/tests.rs+++ b/crates/pa-tui/src/daemon_client/tests.rs@@ -394,11 +394,7 @@ fn fail_pending_resolves_a_transport_failure_not_a_refusal() {// masquerade as a daemon refusal and keep the UI alive.let shared = Shared::default();let (tx, rx) = oneshot::channel();- shared- .pending- .lock()- .unwrap()- .insert("daemon_1".to_string(), tx);+ shared.register_pending("daemon_1".to_string(), tx, None);shared.fail_pending("daemon_", "the daemon connection closed");let error = rx.blocking_recv().unwrap().unwrap_err();assert!(!is_daemon_rejection(&error));diff --git a/crates/pa-tui/src/direct_transport.rs b/crates/pa-tui/src/direct_transport.rsindex 4604ec4889..8b118e3207 100644--- a/crates/pa-tui/src/direct_transport.rs+++ b/crates/pa-tui/src/direct_transport.rs@@ -40,6 +40,8 @@ pub(crate) struct DirectLink {pub(crate) active_session_id: String,/// The worker socket this link is pinned to.pub(crate) socket_path: String,+ /// Private per-connection identity; a reconnect to the same session is distinct.+ pub(crate) owner: Arc<()>,writer: mpsc::UnboundedSender<Vec<u8>>,alive: Arc<AtomicBool>,}@@ -236,6 +238,7 @@ pub(crate) async fn connect_direct(}let alive = Arc::new(AtomicBool::new(true));+ let owner = Arc::new(());let (frame_tx, mut frame_rx) = mpsc::unbounded_channel::<Vec<u8>>();// Writer pump: one frame at a time, exits when the link closes.tokio::spawn(async move {@@ -251,6 +254,7 @@ pub(crate) async fn connect_direct(let shared = Arc::clone(&shared);let event_tx = event_tx.clone();let alive = Arc::clone(&alive);+ let owner = Arc::clone(&owner);let active_session_id = ticket.active_session_id.clone();tokio::spawn(async move {while let Ok(Some(frame)) = reader.read_frame().await {@@ -279,9 +283,9 @@ pub(crate) async fn connect_direct(let _ = event_tx.send(event);}}- // The worker socket closed: every direct-link request in- // flight fails now instead of riding out its timeout.- shared.fail_pending("direct_", "the session connection closed");+ // Only this connection's requests fail: a replacement may already+ // have registered its own requests in the same pending map.+ shared.fail_direct_pending(&owner, "the session connection closed");// An intentional close (client `close`, session switch, link// replacement) marks the link dead before its writer's// shutdown reaches this EOF; only an unmarked exit is the@@ -296,6 +300,7 @@ pub(crate) async fn connect_direct(Ok(DirectLink {active_session_id: ticket.active_session_id.clone(),socket_path: ticket.socket_path.clone(),+ owner,writer: frame_tx,alive,})@@ -443,7 +448,10 @@ mod tests {/// Minimal scripted worker: hello, one `peer_auth` response, then the/// process dies (the socket tears down like a `SIGKILLed` worker).- async fn spawn_mock_worker(listener: tokio::net::UnixListener) {+ async fn spawn_mock_worker(+ listener: tokio::net::UnixListener,+ close: Option<tokio::sync::oneshot::Receiver<()>>,+ ) {let (stream, _) = listener.accept().await.expect("accept");let (reader, mut writer) = stream.into_split();let mut reader =@@ -484,6 +492,9 @@ mod tests {.unwrap();writer.write_all(&frame).await.unwrap();writer.flush().await.unwrap();+ if let Some(close) = close {+ let _ = close.await;+ }drop(writer);}@@ -506,7 +517,7 @@ mod tests {token: "t".to_string(),expires_at: "2999-01-01T00:00:00.000Z".to_string(),};- tokio::spawn(async move { spawn_mock_worker(listener).await });+ tokio::spawn(async move { spawn_mock_worker(listener, None).await });let shared = Arc::new(crate::daemon_client::Shared::default());let (event_tx, event_rx) = mpsc::unbounded_channel();let link = connect_direct(&ticket, shared, event_tx)@@ -547,6 +558,85 @@ mod tests {);}+ /// Hold both real worker sockets open until all pending requests are+ /// registered. Releasing A's EOF is the observable cancellation barrier;+ /// no scheduler delay can move it before B's registration.+ #[tokio::test]+ async fn replaced_link_eof_only_fails_its_own_pending_requests() {+ async fn held_link(+ shared: Arc<Shared>,+ ) -> (+ DirectLink,+ tokio::sync::oneshot::Sender<()>,+ tempfile::TempDir,+ ) {+ let dir = tempfile::TempDir::new().unwrap();+ let socket = dir.path().join("worker.sock");+ let listener = tokio::net::UnixListener::bind(&socket).unwrap();+ let ticket = DaemonPeerTransportTicket {+ purpose: "session_client".to_string(),+ socket_path: socket.to_string_lossy().to_string(),+ socket_identity: pa_types::platform::socket_identity(&socket).unwrap(),+ worker_instance_id: "inst-1".to_string(),+ active_session_id: "abc123".to_string(),+ grant_id: "g1".to_string(),+ token: "t".to_string(),+ expires_at: "2999-01-01T00:00:00.000Z".to_string(),+ };+ let (close_tx, close_rx) = tokio::sync::oneshot::channel();+ tokio::spawn(async move { spawn_mock_worker(listener, Some(close_rx)).await });+ let (event_tx, _) = mpsc::unbounded_channel();+ let link = connect_direct(&ticket, shared, event_tx).await.unwrap();+ (link, close_tx, dir)+ }++ let shared = Arc::new(Shared::default());+ // Even reconnects to the same session need distinct ownership.+ let (a, close_a, _a_dir) = held_link(Arc::clone(&shared)).await;+ let (b, close_b, _b_dir) = held_link(Arc::clone(&shared)).await;+ assert!(!Arc::ptr_eq(&a.owner, &b.owner));+ let (a_tx, a_rx) = tokio::sync::oneshot::channel();+ let (b_tx, mut b_rx) = tokio::sync::oneshot::channel();+ let (daemon_tx, mut daemon_rx) = tokio::sync::oneshot::channel();+ shared.register_pending("direct_1".to_string(), a_tx, Some(Arc::clone(&a.owner)));+ shared.register_pending("direct_2".to_string(), b_tx, Some(Arc::clone(&b.owner)));+ shared.register_pending("daemon_3".to_string(), daemon_tx, None);+ a.close();+ close_a.send(()).unwrap();+ let failure = timeout(Duration::from_secs(2), a_rx)+ .await+ .expect("A EOF processed")+ .expect("transport error delivered")+ .unwrap_err();+ assert_eq!(failure.to_string(), "the session connection closed");+ assert!(matches!(+ b_rx.try_recv(),+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)+ ));+ assert!(matches!(+ daemon_rx.try_recv(),+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)+ ));+ for id in ["direct_2", "daemon_3"] {+ let response = serde_json::from_value(json!({+ "type": "response", "id": id, "command": "prompt", "success": true,+ }))+ .unwrap();+ assert!(shared.resolve(id, response));+ }+ assert!(b_rx.await.unwrap().is_ok());+ assert!(daemon_rx.await.unwrap().is_ok());+ // B's own EOF still fails B's requests; ownership does not mask death.+ let (b_tx, b_rx) = tokio::sync::oneshot::channel();+ shared.register_pending("direct_4".to_string(), b_tx, Some(Arc::clone(&b.owner)));+ close_b.send(()).unwrap();+ assert!(timeout(Duration::from_secs(2), b_rx)+ .await+ .expect("B EOF processed")+ .unwrap()+ .is_err());+ }+#[test]fn ticket_shape_gates() {const FRESH: &str = "2999-01-01T00:00:00.000Z";diff --git a/crates/pa-tui/src/session_ui/prompt.rs b/crates/pa-tui/src/session_ui/prompt.rsindex c6ba8bd152..838d77d657 100644--- a/crates/pa-tui/src/session_ui/prompt.rs+++ b/crates/pa-tui/src/session_ui/prompt.rs@@ -76,6 +76,19 @@ pub(crate) struct PromptOrder {pub(crate) submitted_at: std::time::Instant,}+// A refused request is definitive even when its message quotes a transport failure.+// Queued requests that lose their reply must stay consumed across session changes too.+fn prompt_may_have_been_sent(error: &anyhow::Error) -> bool {+ !crate::daemon_client::is_daemon_rejection(error)+ && (crate::daemon_client::is_daemon_timeout(error)+ || (crate::daemon_client::is_daemon_unreachable(error)+ && error.chain().any(|cause| {+ let message = cause.to_string().to_lowercase();+ message.contains("connection closed")+ || message.starts_with("connection to the prime agent daemon closed")+ })))+}+impl SessionUi {const MAX_PASTED_IMAGE_BYTES: usize = 64 * 1024 * 1024;@@ -791,20 +804,22 @@ impl SessionUi {) -> Result<()> {self.prompt_in_flight = self.prompt_in_flight.saturating_sub(1);// The submit's session is no longer the mounted one: the outcome never applies bookkeeping- // to the new session, but a FAILED outlived submit still shows its error row and retains- // its rejected draft into the session it was typed for; a succeeded one stays silent.+ // to the new session. A failed outlived submit still shows its error row, but only a+ // definitive failure retains the draft in its original session; a success stays silent.if note.active_session_id != self.active_session_id {// Borrow the settled result here: the ladder below owns it.if let Some(error) = note.result.as_ref().err() {let rendered = format!("{error:#}");self.error_row(&rendered, view);- self.retain_rejected_draft(- ¬e.text,- ¬e.session_id,- note.generation,- note.stashed_images.clone(),- view,- );+ if !prompt_may_have_been_sent(error) {+ self.retain_rejected_draft(+ ¬e.text,+ ¬e.session_id,+ note.generation,+ note.stashed_images.clone(),+ view,+ );+ }}return Ok(());}@@ -921,13 +936,10 @@ impl SessionUi {);return Ok(());}- // A DIRECT-link transport failure after the frame was queued: the daemon may have- // admitted the turn, so the draft stays consumed like the timeout arm.- let direct_sent = crate::daemon_client::is_daemon_unreachable(&error)- && rendered- .to_lowercase()- .contains("session connection closed");- if direct_sent {+ // A transport failure after the frame was queued (a direct link, or the+ // supervisor socket closing mid-flight): the daemon may have admitted the turn,+ // so the draft stays consumed like the timeout arm.+ if prompt_may_have_been_sent(&error) {self.error_row(&format!("{rendered} — the request may have been sent; the turn may still start"@@ -990,3 +1002,29 @@ impl SessionUi {store.for_session(stash_session_id).stash_draft_head(stash);}}++#[cfg(test)]+mod prompt_delivery_tests {+ use super::prompt_may_have_been_sent;++ #[test]+ fn distinguishes_ambiguous_delivery_from_definitive_failure() {+ for message in [+ "the daemon connection closed",+ "the session connection closed",+ "Connection to the Prime Agent daemon closed. Socket: fixture.",+ "Timed out after 100ms waiting for the Prime Agent daemon response",+ ] {+ assert!(prompt_may_have_been_sent(&anyhow::anyhow!(message)));+ }+ assert!(!prompt_may_have_been_sent(&anyhow::anyhow!(+ "the daemon connection is closed"+ )));+ let refusal = crate::daemon_client::RequestRejected {+ command: "prompt".to_string(),+ message: "the daemon connection closed".to_string(),+ error_info: None,+ };+ assert!(!prompt_may_have_been_sent(&anyhow::Error::new(refusal)));+ }+}diff --git a/crates/pa-tui/tests/daemon_rejection_headless.rs b/crates/pa-tui/tests/daemon_rejection_headless.rsindex 79b2062319..0848083e00 100644--- a/crates/pa-tui/tests/daemon_rejection_headless.rs+++ b/crates/pa-tui/tests/daemon_rejection_headless.rs@@ -50,6 +50,8 @@ struct MockSupervisor {hold_turn_ms: u64,/// Drop the connection when the next prompt arrives (the dead-daemon transport case).close_on_prompt: bool,+ /// Rebind to s2 before closing, so the pending prompt outcome outlives its active id.+ rebind_before_close: bool,/// Reject the `create` command with this message (the saved-session open refusal: "session/// worker create failed: Session is already active in <id>: <file>").reject_create: Option<String>,@@ -71,6 +73,8 @@ struct SharedAnswers {reject_prompt_index: Option<usize>,hold_turn_ms: u64,close_on_prompt: bool,+ /// Rebind to s2 before closing, so the pending prompt outcome outlives its active id.+ rebind_before_close: bool,reject_create: Option<String>,}@@ -83,6 +87,7 @@ impl MockSupervisor {reject_prompt_index: None,hold_turn_ms: 0,close_on_prompt: false,+ rebind_before_close: false,reject_create: None,create_answers: Vec::new(),}@@ -103,6 +108,7 @@ impl MockSupervisor {reject_prompt_index: self.reject_prompt_index,hold_turn_ms: self.hold_turn_ms,close_on_prompt: self.close_on_prompt,+ rebind_before_close: self.rebind_before_close,reject_create: self.reject_create,});let mut connections = Vec::new();@@ -243,7 +249,23 @@ impl SharedAnswers {);}"attach" => {- write_json(&mut writer, &attach_data(id));+ let mut data = attach_data(id);+ if self.rebind_before_close && !self.prompt_requests.lock().unwrap().is_empty()+ {+ data["data"]["activeSessionId"] = json!("s2");+ data["data"]["snapshot"]["activeSessionId"] = json!("s2");+ data["data"]["snapshot"]["summary"]["id"] = json!("s2");+ data["data"]["snapshot"]["state"]["activeSessionId"] = json!("s2");+ }+ write_json(&mut writer, &data);+ }+ "detach"+ if self.rebind_before_close+ && !self.prompt_requests.lock().unwrap().is_empty() =>+ {+ // attach_session has adopted s2 before detaching s1. Resolve the pending+ // prompt only now, after the mounted id has observably changed.+ break;}"prompt" => {let index = {@@ -251,6 +273,17 @@ impl SharedAnswers {requests.push(command.clone());requests.len() - 1};+ if self.close_on_prompt && self.rebind_before_close {+ write_json(+ &mut writer,+ &json!({+ "type": "session_binding",+ "previousActiveSessionId": "s1",+ "activeSessionId": "s2",+ }),+ );+ continue;+ }if self.close_on_prompt {// The dead-daemon case: dropping both halves fails the in-flight request// with the transport error.@@ -627,22 +660,29 @@ fn rejected_mid_turn_submission_renders_the_error_row_and_keeps_running() {}/// Handled, not fatal (operator directive: the user never loses their TUI to a daemon hiccup);-/// the loss is surfaced twice, never silently swallowed.+/// the loss is surfaced twice, and the close-after-send draft stays consumed so the natural+/// resubmit never runs the prompt twice.#[test]-fn dead_connection_on_prompt_keeps_the_run_mounted_and_arms_the_reconnect() {+fn dead_connection_on_prompt_keeps_the_draft_consumed_and_arms_the_reconnect() {let steps = vec![HeadlessStep::Type("hello".to_string()),HeadlessStep::Key(enter()),+ HeadlessStep::WaitRender {+ needle: "the daemon connection closed — reconnecting".to_string(),+ timeout_ms: 2000,+ },+ HeadlessStep::WaitRender {+ needle: "Daemon reconnected".to_string(),+ timeout_ms: 4000,+ },+ HeadlessStep::Key(enter()),HeadlessStep::WaitMs(300),];let run = run_plan_with(steps, |supervisor| {supervisor.close_on_prompt = true;}).expect("a dead connection keeps the run mounted");- let all = run.frames.join(- "-",- );+ let all = run.frames.join("\n");assert!(all.contains("\u{26a0} Error: the daemon connection closed"),"the dead connection surfaces as the error row:\n{all}"@@ -651,14 +691,49 @@ fn dead_connection_on_prompt_keeps_the_run_mounted_and_arms_the_reconnect() {all.contains("the daemon connection closed — reconnecting"),"the reconnect driver is armed for the loss:\n{all}");+ assert_eq!(+ run.prompt_requests.len(),+ 1,+ "the close-after-send prompt never dispatches twice"+ );+ let last = run.frames.last().map(String::as_str).unwrap_or_default();assert!(- all.contains("hello"),- "the dead-connection draft returned to the editor:\n{all}"+ !last.contains("hello"),+ "the draft stays consumed after the close:\n{last}");}/// TS `onSubmit` passes its captured `streamingBehavior` to the fallthrough prompt, so alt+enter/// on unknown slash text parks on the follow-up lane, not the steering lane.+/// A queued prompt remains consumed even if a session-binding event wins the outcome race.+#[test]+fn close_after_rebind_keeps_the_outlived_prompt_consumed() {+ let steps = vec![+ HeadlessStep::Type("hello".to_string()),+ HeadlessStep::Key(enter()),+ HeadlessStep::WaitRender {+ needle: "Daemon reconnected".to_string(),+ timeout_ms: 4000,+ },+ HeadlessStep::Key(enter()),+ HeadlessStep::WaitMs(300),+ ];+ let run = run_plan_with(steps, |supervisor| {+ supervisor.close_on_prompt = true;+ supervisor.rebind_before_close = true;+ })+ .expect("the rebind and connection loss keep the run mounted");+ assert_eq!(+ run.prompt_requests.len(),+ 1,+ "the outlived draft never replays"+ );+ let all = run.frames.join("\n");+ assert!(all.contains("Daemon reconnected"), "reconnected: {all}");+ let last = run.frames.last().map(String::as_str).unwrap_or_default();+ assert!(!last.contains("hello"), "the draft stays consumed: {last}");+}+#[test]fn slash_fallthrough_follow_up_keeps_the_follow_up_lane() {let steps = vec![diff --git a/scripts/review_draft_disconnect_parity.py b/scripts/review_draft_disconnect_parity.pynew file mode 100644index 0000000000..f4afd4966f--- /dev/null+++ b/scripts/review_draft_disconnect_parity.py@@ -0,0 +1,650 @@+#!/usr/bin/env python3+"""Real-binary #3401 parity: isolated supervisor failures and ordinary PTY input.++No inference, ambient state, binary installation, or production daemon is used.+A short owned daemon supplies each binary's actual hello/schema. The supervisor+fixture then exercises the ordinary --daemon-socket UI, with no test-only flags.+All terminal captures and wire observations are preserved in the receipt.+"""+import argparse+import codecs+import hashlib+import json+import os+from pathlib import Path+import pty+import re+import select+import signal+import socket+import struct+import subprocess+import sys+import tempfile+import threading+import time+import fcntl+import termios+import unicodedata++TS_ARCHIVE_SHA256 = "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2"+LIMIT = 35+PROMPT = "DRAFT_DISCONNECT_SENTINEL"+PROBE = "DRAFT_TRANSPORT_PROBE"+TS_SOURCE_COMMIT = "7d442aafa985f9342134fac16c2ef41f03fb45c1"+REFUSAL = "Fixture definitively refused this prompt"+++def digest(path):+ with open(path, "rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()+++def stop(process):+ if process.poll() is None:+ try:+ os.killpg(process.pid, signal.SIGTERM)+ except ProcessLookupError:+ return+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ process.wait(timeout=5)+++def env_for(root, kind):+ env = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TZ")+ if key in os.environ}+ if kind == "ts" and "PI_PACKAGE_DIR" in os.environ:+ env["PI_PACKAGE_DIR"] = os.environ["PI_PACKAGE_DIR"]+ for key in ("PRIME_AGENT_KERNEL_PYTHON", "PA_E2E_KERNEL_PYTHON"):+ if key in os.environ:+ env[key] = os.environ[key]+ for name in ("home", "tmp", "xdg", "agent/sessions"):+ (root / name).mkdir(parents=True, exist_ok=True)+ env.update(HOME=str(root / "home"), TMPDIR=str(root / "tmp"),+ XDG_CONFIG_HOME=str(root / "xdg"),+ PRIME_AGENT_CODING_AGENT_DIR=str(root / "agent"),+ PI_CODING_AGENT_DIR=str(root / "agent"), TERM="xterm-256color",+ PRIME_AGENT_MODEL_PROVIDER="parity-local", PRIME_AGENT_MODEL="parity-1",+ PI_OFFLINE="1", DO_NOT_TRACK="1")+ (root / "agent/settings.json").write_text(json.dumps({+ "onboardingCompleted": True, "onboardingShown": True,+ "telemetry": {"noticeShown": True}}))+ (root / "agent/models.json").write_text(json.dumps({"providers": {+ "parity-local": {"api": "openai-completions", "baseUrl": "http://127.0.0.1:1/v1",+ "apiKey": "fixture-only", "models": [{"id": "parity-1",+ "name": "Parity 1", "contextWindow": 128000, "maxTokens": 4096}]}}}))+ return env+++def actual_hello(binary, root, env):+ path = root / "hello.sock"+ with open(root / "hello-daemon.log", "wb") as log:+ process = subprocess.Popen([str(binary), "--mode", "daemon", "--daemon-socket", str(path)],+ cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ try:+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError("hello-discovery daemon exited before greeting")+ try:+ with socket.socket(socket.AF_UNIX) as sock:+ sock.settimeout(2)+ sock.connect(str(path))+ with sock.makefile("rb") as stream:+ hello = json.loads(stream.readline())+ if hello.get("type") != "daemon_hello" or not hello.get("schemaId"):+ raise RuntimeError(f"invalid actual hello: {hello}")+ return hello+ except (FileNotFoundError, ConnectionRefusedError, socket.timeout):+ # Poll actual socket readiness, bounded by the discovery deadline.+ threading.Event().wait(0.05)+ raise TimeoutError("hello-discovery socket readiness")+ finally:+ stop(process)+++class Screen:+ """Minimal xterm cell capture; raw ANSI is retained separately for audit."""+ def __init__(self, width=120, height=40):+ self.width, self.height = width, height+ self.cells = [[" "] * width for _ in range(height)]+ self.row = self.col = 0+ self.saved = (0, 0)+ self.pending = ""+ self.decoder = codecs.getincrementaldecoder("utf-8")("replace")++ def text(self):+ return "\n".join("".join(row).rstrip() for row in self.cells)++ def feed(self, data):+ self.pending += self.decoder.decode(data)+ replies = []+ while self.pending:+ if self.pending[0] == "\x1b":+ if len(self.pending) < 2:+ break+ if self.pending[1] in "]P_^":+ end = re.search(r"\x07|\x1b\\", self.pending[2:])+ if end is None:+ break+ self.pending = self.pending[2 + end.end():]+ continue+ if self.pending[1] == "[":+ match = re.match(r"\x1b\[([0-?]*)([ -/]*)([@-~])", self.pending)+ if match is None:+ break+ params, _, command = match.groups()+ self.pending = self.pending[match.end():]+ nums = [int(x) if x.isdigit() else 0 for x in params.lstrip("?<>").split(";")]+ n = nums[0] or 1+ if command in "Hf":+ self.row = min(self.height - 1, max(0, (nums[0] or 1) - 1))+ self.col = min(self.width - 1, max(0, ((nums[1] if len(nums) > 1 else 1) or 1) - 1))+ elif command == "A": self.row = max(0, self.row - n)+ elif command == "B": self.row = min(self.height - 1, self.row + n)+ elif command == "C": self.col = min(self.width - 1, self.col + n)+ elif command == "D": self.col = max(0, self.col - n)+ elif command == "G": self.col = min(self.width - 1, n - 1)+ elif command == "J":+ if nums[0] in (2, 3): self.cells = [[" "] * self.width for _ in range(self.height)]+ elif nums[0] == 0:+ self.cells[self.row][self.col:] = [" "] * (self.width - self.col)+ for row in range(self.row + 1, self.height): self.cells[row] = [" "] * self.width+ elif command == "K":+ start, end = (0, self.width) if nums[0] == 2 else ((0, self.col + 1) if nums[0] == 1 else (self.col, self.width))+ self.cells[self.row][start:end] = [" "] * (end - start)+ elif command == "P":+ line = self.cells[self.row]+ line[self.col:] = (line[self.col + n:] + [" "] * n)[:self.width - self.col]+ elif command == "X":+ end = min(self.width, self.col + n)+ self.cells[self.row][self.col:end] = [" "] * (end - self.col)+ elif command == "n" and nums[0] == 6:+ replies.append(f"\x1b[{self.row + 1};{self.col + 1}R".encode())+ elif command == "c": replies.append(b"\x1b[?1;2c")+ continue+ command = self.pending[1]+ self.pending = self.pending[2:]+ if command == "7": self.saved = (self.row, self.col)+ elif command == "8": self.row, self.col = self.saved+ elif command in "()" and self.pending: self.pending = self.pending[1:]+ continue+ char, self.pending = self.pending[0], self.pending[1:]+ if char == "\r": self.col = 0+ elif char == "\n":+ self.row += 1+ if self.row >= self.height:+ self.cells.pop(0); self.cells.append([" "] * self.width); self.row = self.height - 1+ elif char == "\b": self.col = max(0, self.col - 1)+ elif char >= " " and not unicodedata.combining(char):+ if self.col >= self.width: self.col = 0; self.row = min(self.height - 1, self.row + 1)+ self.cells[self.row][self.col] = char+ self.col += 2 if unicodedata.east_asian_width(char) in "WF" else 1+ return replies+++def fixture_state(root, active):+ # AgentConnectionState in the pinned TS binary's source commit (types.ts).+ # No model selected: model and contextUsage are optional on the wire.+ return {"activeSessionId": active, "cwd": str(root), "sessionId": "fixture-durable",+ "sessionName": "Draft fixture", "thinkingLevel": "off", "serviceTier": "default",+ "availableThinkingLevels": ["off"], "isStreaming": False,+ "isCompacting": False, "isBashRunning": False, "retryAttempt": 0,+ "steeringMode": "all", "followUpMode": "all", "leafId": None,+ "autoCompactionEnabled": False, "messageCount": 0, "compactionCount": 0,+ "sessionActions": {"queuedCount": 0, "steering": [], "followUps": []},+ "goal": {"active": False, "status": "idle", "tokensUsed": 0,+ "timeUsedSeconds": 0, "continuationsUsed": 0},+ "scopedModels": [], "activeToolNames": []}+++class Supervisor:+ def __init__(self, path, hello, scenario, root):+ self.path, self.hello, self.scenario, self.root = path, hello, scenario, root+ self.listener = socket.socket(socket.AF_UNIX)+ self.listener.bind(str(path)); self.listener.listen(); self.listener.settimeout(0.2)+ self.done = threading.Event()+ self.lock = threading.Lock()+ self.sockets, self.threads, self.errors = [], [], []+ self.commands, self.prompts, self.prompt_envelopes = [], [], []+ self.accepted_prompts, self.result_acks = [], []+ self.journal, self.settled = {}, set()+ self.messages = []+ self.attaches = 0+ self.closed = False+ self.rebound = False+ self.post_close_attached = False+ self.thread = threading.Thread(target=self.accept, daemon=True)+ self.thread.start()++ def send(self, sock, data):+ sock.sendall((json.dumps(data) + "\n").encode())++ def settle(self, sock, active, key, index, emit=True):+ # Each admitted synthetic turn finishes once; cached result replay+ # does not execute another turn. No real provider is called.+ marker = f"Fixture settled {index}"+ message = {"role": "assistant", "stopReason": "stop",+ "api": "openai-completions", "provider": "parity-local", "model": "parity-1",+ "timestamp": 1750000000000, "usage": {"input": 0, "output": 0,+ "cacheRead": 0, "cacheWrite": 0, "totalTokens": 0,+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}},+ "content": [{"type": "text", "text": marker}]}+ with self.lock:+ if key in self.settled:+ return+ self.settled.add(key)+ prompt = self.prompts[index - 1]+ self.messages.extend([{"role": "user", "content": [{"type": "text", "text": prompt["message"]}],+ "timestamp": 1750000000000}, message])+ if not emit:+ return # Completed history survives lost events and is delivered by attach.+ for event in ({"type": "turn_start"},+ {"type": "message_start", "message": message},+ {"type": "message_end", "message": message},+ {"type": "turn_end", "message": message, "toolResults": []}):+ self.send(sock, {"type": "session_event", "activeSessionId": active, "event": event})++ def accept(self):+ while not self.done.is_set():+ try: sock, _ = self.listener.accept()+ except socket.timeout: continue+ except OSError: return+ sock.settimeout(0.2)+ self.sockets.append(sock)+ thread = threading.Thread(target=self.serve, args=(sock,), daemon=True)+ self.threads.append(thread); thread.start()++ def serve(self, sock):+ # The pinned protocol requires this for prompt dispatch. Advertise only+ # the admission path implemented here; leave direct-peer routing disabled.+ hello = dict(self.hello, serverCapabilities=["session_input_admission"], clientId="draft-fixture")+ buffer = b""+ try:+ self.send(sock, hello)+ while not self.done.is_set():+ try: data = sock.recv(65536)+ except socket.timeout: continue+ if not data: return+ buffer += data+ while b"\n" in buffer:+ line, buffer = buffer.split(b"\n", 1)+ if not line.strip(): continue+ envelope = json.loads(line)+ command = envelope.get("command", envelope)+ name = command.get("type")+ request_id = envelope.get("id")+ client_id = envelope.get("clientId")+ key = (client_id, request_id)+ with self.lock:+ self.commands.append(command)+ active = "s2" if self.rebound else "s1"+ response = {"type": "response", "id": request_id, "command": name,+ "success": True, "data": {}}+ if name == "ack_result":+ # TS supervisor acknowledges its journal and returns undefined;+ # this one-way command must not receive a synthetic response.+ with self.lock:+ ack_key = (client_id, command.get("commandId"))+ self.result_acks.append({"clientId": client_id, "commandId": command.get("commandId")})+ self.journal.pop(ack_key, None)+ continue+ if name == "create":+ response["data"] = {"activeSessionId": active, "id": active,+ "sessionId": "fixture-durable", "sessionFile": str(self.root / "agent/sessions/fixture.jsonl")}+ elif name == "attach":+ state = fixture_state(self.root, active)+ with self.lock:+ messages = list(self.messages)+ state["messageCount"] = len(messages)+ response["data"] = {"protocol": hello["protocol"], "activeSessionId": active,+ "snapshot": {"activeSessionId": active, "summary": {"id": active, "cwd": str(self.root)},+ "state": state, "messages": messages, "lastEventSequence": 0, "lastEventCursor": None},+ "client": {"id": "draft-fixture", "capabilities": []},+ "lastEventSequence": 0, "lastEventCursor": None}+ with self.lock:+ self.attaches += 1+ if self.closed: self.post_close_attached = True+ elif name == "prompt":+ # daemon-mode's accepted prompt success has no data payload.+ response.pop("data", None)+ if not client_id or not request_id:+ raise RuntimeError("prompt envelope lacks clientId/id for recovery identity")+ with self.lock:+ self.prompt_envelopes.append({"id": request_id, "clientId": client_id, "command": command})+ cached = self.journal.get(key)+ if cached is not None:+ # Exact TS supervisor semantics: (clientId, commandId) completion+ # returns the cached result without dispatching the prompt again.+ cached_response, index = cached+ self.send(sock, cached_response)+ if cached_response["success"]:+ self.settle(sock, active, key, index)+ continue+ with self.lock:+ self.prompts.append(command)+ index = len(self.prompts)+ first = index == 1+ if first and self.scenario == "refusal":+ response.update(success=False, error=REFUSAL)+ with self.lock:+ # Model complete-before-reply loss, not pending/uncertain journal+ # recovery. This scenario tests a lost ACK for a completed admission.+ self.journal[key] = (dict(response), index)+ if response["success"]:+ self.accepted_prompts.append({"id": request_id, "clientId": client_id,+ "command": command})+ if first and self.scenario == "rebind_close":+ self.settle(sock, active, key, index, emit=False)+ self.rebound = True+ self.send(sock, {"type": "session_binding", "previousActiveSessionId": "s1", "activeSessionId": "s2"})+ continue+ if first and self.scenario == "queued_close":+ self.settle(sock, active, key, index, emit=False)+ self.closed = True+ return # Admission/result cached; reply intentionally lost.+ elif name == "detach" and self.scenario == "rebind_close" and self.rebound and not self.closed:+ self.closed = True+ return # The attach already adopted s2 before it requested detach(s1).+ elif name == "list": response["data"] = {"sessions": []}+ elif name == "heartbeats_list": response["data"] = {"heartbeats": []}+ elif name == "roster_subscribe": response["data"] = {"changed": [], "removed": [], "resync": True}+ elif name == "get_available_models": response["data"] = {"models": []}+ elif name == "get_resource_snapshot":+ # AgentConnectionResourceSnapshot from the pinned TS source.+ response["data"] = {"contextFiles": [], "skills": [], "prompts": [],+ "extensions": [], "themes": [], "diagnostics": {+ "skills": [], "prompts": [], "extensions": [], "themes": []}}+ elif name == "get_session_stats":+ # AgentSession.getSessionStats's empty-session return shape.+ response["data"] = {"sessionId": "fixture-durable", "userMessages": 0,+ "assistantMessages": 0, "toolCalls": 0, "toolResults": 0,+ "totalMessages": 0, "cost": 0, "tokens": {+ "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}}+ with self.lock:+ response["data"].update(userMessages=len(self.messages) // 2,+ assistantMessages=len(self.messages) // 2,+ totalMessages=len(self.messages))+ elif name == "get_context_tree":+ # Pinned AgentSession.getContextTree / ContextTreeNode and+ # usage.emptyUsage: an empty session is a single active root.+ usage = {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": 0, "cost": {"input": 0, "output": 0,+ "cacheRead": 0, "cacheWrite": 0, "total": 0}}+ response["data"] = {"id": "root", "label": "Draft fixture", "status": "active",+ "ownUsage": usage, "totalUsage": usage, "children": []}+ elif name == "get_model_catalog": response["data"] = {"models": [], "configuredProviders": []}+ elif name == "get_commands": response["data"] = {"commands": []}+ elif name == "list_kernel_bash": response["data"] = {"commands": []}+ elif name == "factory_activity": response["data"] = {"activity": [], "jobs": []}+ elif name in ("get_state", "get_connection_state"):+ response["data"] = fixture_state(self.root, active)+ with self.lock:+ response["data"]["messageCount"] = len(self.messages)+ elif name == "get_mcp_connections": response["data"] = {"connections": []}+ elif name == "detach": response["data"] = {}+ else:+ self.errors.append(f"unexpected command: {name}")+ response.update(success=False, error=f"Unsupported fixture command: {name}")+ self.send(sock, response)+ if name == "prompt" and response["success"]:+ self.settle(sock, active, key, index)+ except (BrokenPipeError, ConnectionResetError):+ pass+ except Exception as error:+ if not self.done.is_set(): self.errors.append(f"{type(error).__name__}: {error}")+ finally:+ sock.close()++ def close(self):+ self.done.set(); self.listener.close()+ for sock in self.sockets:+ try: sock.shutdown(socket.SHUT_RDWR)+ except OSError: pass+ self.thread.join(timeout=2)+ for thread in self.threads: thread.join(timeout=2)+ if self.thread.is_alive() or any(thread.is_alive() for thread in self.threads):+ raise RuntimeError("owned supervisor threads did not terminate")+++class Terminal:+ def __init__(self, command, root, env):+ self.master, slave = pty.openpty()+ attrs = termios.tcgetattr(slave)+ attrs[3] &= ~(termios.ECHO | termios.ICANON)+ termios.tcsetattr(slave, termios.TCSANOW, attrs)+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 120, 0, 0))+ self.process = subprocess.Popen(command, cwd=root, env=env, stdin=slave,+ stdout=slave, stderr=slave, start_new_session=True)+ os.close(slave)+ self.screen, self.raw = Screen(), bytearray()++ def pump(self):+ if select.select([self.master], [], [], 0.05)[0]:+ try: data = os.read(self.master, 65536)+ except OSError: data = b""+ self.raw.extend(data)+ for reply in self.screen.feed(data): os.write(self.master, reply)++ def wait(self, label, predicate, server):+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ self.pump()+ if server.errors: raise RuntimeError(f"supervisor fixture error: {server.errors}")+ if self.process.poll() is not None: raise RuntimeError(f"UI exited during {label}: {self.process.returncode}")+ if predicate(): return+ raise TimeoutError(label)++ def send(self, data): os.write(self.master, data.encode())++ def close(self):+ stop(self.process)+ os.close(self.master)+++def scenario(kind, binary, root, hello, name):+ root.mkdir()+ env = env_for(root, kind)+ server = Supervisor(root / "fixture.sock", hello, name, root)+ terminal = None+ result = {"scenario": name, "executed": False, "screens": {}}+ try:+ terminal = Terminal([str(binary), "--daemon-socket", str(server.path)], root, env)+ terminal.wait("initial attach and visible terminal", lambda: server.attaches >= 1+ and bool(terminal.screen.text().strip()), server)+ terminal.send(PROMPT)+ terminal.wait("typed sentinel visibly in editor", lambda: PROMPT in terminal.screen.text(), server)+ terminal.send("\r")+ terminal.wait("first prompt received", lambda: len(server.prompts) == 1, server)+ if name == "refusal":+ terminal.wait("definite refusal and restored draft", lambda: REFUSAL in terminal.screen.text()+ and PROMPT in terminal.screen.text(), server)+ else:+ terminal.wait("reconnected attach and visible reconnect result", lambda: server.post_close_attached+ and ("Fixture settled 1" in terminal.screen.text()+ or any(phrase in terminal.screen.text().lower() for phrase in+ ("daemon reconnected", "daemon restarted (v0.9.8) - reconnected"))), server)+ result["screens"]["before_resubmit"] = terminal.screen.text()+ before = len(server.prompts)+ terminal.send("\r")+ if name == "refusal":+ terminal.wait("resubmitted refusal visibly settled", lambda:+ "Fixture settled 2" in terminal.screen.text(), server)+ # A visible marker typed afterwards is the barrier that Enter has been handled;+ # the next prompt also proves the post-reconnect transport is operational.+ terminal.send(PROBE)+ terminal.wait("probe visibly typed", lambda: PROBE in terminal.screen.text(), server)+ result["screens"]["after_resubmit"] = terminal.screen.text()+ terminal.send("\r")+ terminal.wait("transport probe received", lambda: any(PROBE in p.get("message", "") for p in server.prompts), server)+ probe_index = next(index + 1 for index, prompt in enumerate(server.prompts)+ if PROBE in prompt.get("message", ""))+ terminal.wait("transport probe visibly settled", lambda:+ f"Fixture settled {probe_index}" in terminal.screen.text(), server)+ result.update(executed=True, dispatches_before_resubmit=before,+ rebound=server.rebound, reconnected=server.post_close_attached)+ except Exception as error:+ result["error"] = f"{type(error).__name__}: {error}"+ finally:+ if terminal is not None:+ result["terminal_raw"] = terminal.raw.decode("utf-8", "replace")+ result["screens"]["final"] = terminal.screen.text()+ try:+ terminal.close()+ except Exception as error:+ result.setdefault("cleanup_errors", []).append(f"UI cleanup: {type(error).__name__}: {error}")+ try:+ server.close()+ except Exception as error:+ result.setdefault("cleanup_errors", []).append(f"supervisor cleanup: {type(error).__name__}: {error}")+ # Snapshot only after the owned UI has stopped and all fixture threads joined.+ # A late dispatch cannot be hidden behind an earlier passing invariant.+ messages = [p.get("message") for p in server.prompts]+ expected = [PROMPT, PROMPT, PROBE] if name == "refusal" else [PROMPT, PROBE]+ accepted = [item["command"].get("message") for item in server.accepted_prompts]+ wire_messages = [item["command"].get("message") for item in server.prompt_envelopes]+ result.update(wire_commands=server.commands, prompts=messages,+ wire_prompt_messages=wire_messages,+ prompt_envelopes=server.prompt_envelopes,+ accepted_logical_prompts=server.accepted_prompts,+ accepted_logical_messages=accepted, result_acks=server.result_acks,+ persisted_messages=server.messages,+ expected_prompts=expected, fixture_errors=server.errors,+ draft_restored=name == "refusal" and messages == expected,+ draft_consumed=name != "refusal" and messages == expected,+ invariant_passed=bool(result["executed"] and messages == expected+ and accepted == [PROMPT, PROBE] and not server.errors and not result.get("cleanup_errors")))+ return result+++def classify_validation(receipt):+ """Classify real observations; passing the targeted check does not prove full parity."""+ comparisons = {}+ for name in ("queued_close", "refusal", "rebind_close"):+ sides = [receipt.get("results", {}).get(kind, {}).get("scenarios", {}).get(name, {}) for kind in ("ts", "rust")]+ executed = all(x.get("executed") for x in sides)+ comparisons[name] = {"comparable": name != "rebind_close",+ "both_executed": executed,+ "same_logical_prompt_observations": bool(executed and sides[0].get("prompts") == sides[1].get("prompts")),+ "same_accepted_logical_observations": bool(executed and sides[0].get("accepted_logical_messages") == sides[1].get("accepted_logical_messages")),+ "same_wire_prompt_observations": bool(executed and sides[0].get("wire_prompt_messages") == sides[1].get("wire_prompt_messages")),+ "both_invariants_passed": all(x.get("invariant_passed") for x in sides)}+ for name, comparison in comparisons.items():+ if not comparison["comparable"]:+ comparison["status"] = "not_comparable"+ comparison["reason"] = (+ "Pinned TS source " + TS_SOURCE_COMMIT + " has no session_binding or "+ "previousActiveSessionId protocol; session_replaced retains the active ID. "+ "The Rust-only rebind fixture cannot establish a TS behavioral difference."+ )+ elif not comparison["both_executed"]:+ comparison["status"] = "incomplete"+ else:+ comparison["status"] = "matched" if all(comparison[key] for key in (+ "same_logical_prompt_observations", "same_accepted_logical_observations",+ "both_invariants_passed")) else "different"+ receipt["comparisons"] = comparisons+ receipt["shared_contract_parity"] = bool("preflight_error" not in receipt and all(+ comparisons[name]["status"] == "matched" for name in ("queued_close", "refusal")))+ # Full parity remains unproven when a requested scenario is not comparable.+ receipt["parity"] = bool("preflight_error" not in receipt and all(+ item["comparable"] and all(item[key] for key in ("both_executed", "same_logical_prompt_observations",+ "same_accepted_logical_observations", "both_invariants_passed"))+ for item in comparisons.values()))+ # Targeted validation is distinct from full rendered/wire parity. The pinned+ # TS binary cannot execute the Rust binding extension, so only its recorded+ # unsupported-case timeout is expected; every other error fails validation.+ errors = []+ if "preflight_error" in receipt:+ errors.append("preflight failed")+ results = receipt.get("results", {})+ for kind in ("ts", "rust"):+ side = results.get(kind, {})+ if not side or "error" in side:+ errors.append(f"{kind}: binary setup failed or missing")+ for name in ("queued_close", "refusal", "rebind_close"):+ scenario_result = side.get("scenarios", {}).get(name, {})+ if not scenario_result:+ errors.append(f"{kind}/{name}: result missing")+ continue+ if scenario_result.get("fixture_errors") or scenario_result.get("cleanup_errors"):+ errors.append(f"{kind}/{name}: fixture or cleanup failed")+ if any(not isinstance(scenario_result.get(field), list) for field in (+ "prompts", "accepted_logical_messages", "wire_prompt_messages")):+ errors.append(f"{kind}/{name}: prompt observations missing")+ if kind == "ts" and name == "rebind_close":+ if (scenario_result.get("error") != "TimeoutError: reconnected attach and visible reconnect result"+ or scenario_result.get("executed") is not False+ or scenario_result.get("invariant_passed") is not False):+ errors.append("ts/rebind_close: expected unsupported-case observation missing")+ elif (scenario_result.get("error") or scenario_result.get("executed") is not True+ or scenario_result.get("invariant_passed") is not True):+ errors.append(f"{kind}/{name}: execution or invariant failed")+ if not receipt["shared_contract_parity"]:+ errors.append("shared contracts did not match")+ receipt["validation_scope"] = (+ "Both shared draft contracts plus the Rust-only binding regression. "+ "Pinned TS binding is not comparable; full frame/wire parity remains unproven."+ )+ receipt["validation_errors"] = errors+ receipt["validation_passed"] = not errors+ return receipt["validation_passed"]+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--receipt", required=True, type=Path)+ args = parser.parse_args()+ repo = Path(__file__).resolve().parent.parent+ receipt_path = args.receipt.resolve()+ if receipt_path == repo or repo in receipt_path.parents:+ print("receipt must be outside repository", file=sys.stderr)+ return 1+ receipt = {"fixture": "pr3401-draft-disconnect", "results": {},+ "fixture_schema_source_commit": TS_SOURCE_COMMIT,+ "comparison_scope": "Targeted accepted logical prompt/draft behavior; complete result recovery is keyed by the actual (clientId, commandId), so same-ID wire retries are recorded but do not dispatch a second prompt. Raw IDs, attempts, terminals and commands are retained; full frame/wire equivalence is not asserted.",+ "ci_provenance": {key: os.environ.get(key) for key in ("GITHUB_RUN_ID", "GITHUB_SHA")},+ "ts_reference": {"version": "0.9.8", "expected_archive_sha256": TS_ARCHIVE_SHA256},+ "pre_send_limitation": "A deterministically dead client before send needs the in-process death-watch seam; the binary fixture tests definitive refusal separately."}+ try:+ if sys.platform != "linux": raise RuntimeError("real binary fixture requires Linux")+ event_path = os.environ.get("GITHUB_EVENT_PATH")+ if event_path:+ event = json.loads(Path(event_path).read_text())+ receipt["ci_provenance"]["pull_request_head_sha"] = event.get("pull_request", {}).get("head", {}).get("sha")+ archive = Path(os.environ["PA_TS_ARCHIVE"])+ receipt["ts_reference"]["verified_archive_sha256"] = digest(archive)+ if digest(archive) != TS_ARCHIVE_SHA256: raise RuntimeError("official TS archive SHA-256 mismatch")+ with tempfile.TemporaryDirectory(prefix="pa-draft-parity-") as temp:+ for kind in ("ts", "rust"):+ item = receipt["results"][kind] = {}+ try:+ binary = Path(os.environ.get(f"PA_{kind.upper()}_BINARY") or os.environ[f"{kind.upper()}_BINARY"]).resolve()+ if not binary.is_file() or not os.access(binary, os.X_OK): raise RuntimeError("missing executable")+ item.update(binary=str(binary), sha256=digest(binary))+ root = Path(temp) / kind; root.mkdir()+ env = env_for(root, kind)+ version = subprocess.run([str(binary), "--version"], cwd=root, env=env,+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=15, check=True)+ item["version"] = version.stdout.strip()+ if kind == "ts" and "0.9.8" not in item["version"]: raise RuntimeError("unexpected TS version")+ item["actual_hello"] = actual_hello(binary, root, env)+ item["scenarios"] = {name: scenario(kind, binary, root / name, item["actual_hello"], name)+ for name in ("queued_close", "refusal", "rebind_close")}+ except Exception as error: item["error"] = f"{type(error).__name__}: {error}"+ except Exception as error: receipt["preflight_error"] = f"{type(error).__name__}: {error}"+ classify_validation(receipt)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")+ print(json.dumps(receipt, indent=2, sort_keys=True))+ return 0 if receipt["validation_passed"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/test_review_draft_disconnect_parity.py b/scripts/test_review_draft_disconnect_parity.pynew file mode 100644index 0000000000..bcb450d995--- /dev/null+++ b/scripts/test_review_draft_disconnect_parity.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""Decision-only regression tests; these never launch either product binary."""+import copy+import unittest++from review_draft_disconnect_parity import classify_validation+++def completed_observations():+ accepted = ["sentinel", "probe"]+ scenarios = {}+ for name in ("queued_close", "refusal", "rebind_close"):+ scenarios[name] = {"executed": True, "invariant_passed": True,+ "fixture_errors": [], "prompts": accepted[:],+ "accepted_logical_messages": accepted[:],+ "wire_prompt_messages": accepted[:]}+ scenarios["refusal"]["prompts"] = ["sentinel", "sentinel", "probe"]+ scenarios["refusal"]["wire_prompt_messages"] = ["sentinel", "sentinel", "probe"]+ rust = {"scenarios": scenarios}+ ts = copy.deepcopy(rust)+ ts["scenarios"]["queued_close"]["wire_prompt_messages"] = ["sentinel", "sentinel", "probe"]+ ts["scenarios"]["rebind_close"] = {+ "executed": False, "invariant_passed": False, "fixture_errors": [],+ "error": "TimeoutError: reconnected attach and visible reconnect result",+ "prompts": ["sentinel"], "accepted_logical_messages": ["sentinel"],+ "wire_prompt_messages": ["sentinel"]}+ return {"results": {"ts": ts, "rust": rust}}+++class ValidationDecisionTests(unittest.TestCase):+ def test_complete_shared_contracts_and_rust_extension_validate_without_full_parity(self):+ receipt = completed_observations()+ before = copy.deepcopy(receipt["results"])+ self.assertTrue(classify_validation(receipt))+ self.assertTrue(receipt["shared_contract_parity"])+ self.assertFalse(receipt["parity"])+ self.assertEqual(receipt["comparisons"]["rebind_close"]["status"], "not_comparable")+ self.assertFalse(receipt["comparisons"]["queued_close"]["same_wire_prompt_observations"])+ self.assertEqual(receipt["results"], before)++ def test_incomplete_shared_execution_fails_on_either_side(self):+ for kind in ("ts", "rust"):+ for name in ("queued_close", "refusal"):+ with self.subTest(kind=kind, name=name):+ receipt = completed_observations()+ receipt["results"][kind]["scenarios"][name]["executed"] = False+ self.assertFalse(classify_validation(receipt))++ def test_changed_logical_acceptance_fails(self):+ receipt = completed_observations()+ receipt["results"]["ts"]["scenarios"]["queued_close"]["accepted_logical_messages"].append("sentinel")+ self.assertFalse(classify_validation(receipt))++ def test_shared_invariant_or_prompt_difference_fails(self):+ for kind in ("ts", "rust"):+ for name in ("queued_close", "refusal"):+ for field, value in (("invariant_passed", False), ("prompts", ["different"])):+ with self.subTest(kind=kind, name=name, field=field):+ receipt = completed_observations()+ receipt["results"][kind]["scenarios"][name][field] = value+ self.assertFalse(classify_validation(receipt))++ def test_missing_observations_fail_even_when_both_sides_omit_them(self):+ for name in ("queued_close", "refusal", "rebind_close"):+ for field in ("prompts", "accepted_logical_messages", "wire_prompt_messages"):+ with self.subTest(name=name, field=field):+ receipt = completed_observations()+ for kind in ("ts", "rust"):+ del receipt["results"][kind]["scenarios"][name][field]+ self.assertFalse(classify_validation(receipt))++ def test_unsupported_case_requires_the_exact_recorded_failure(self):+ for field, value in (("error", None), ("executed", True), ("invariant_passed", True)):+ with self.subTest(field=field):+ receipt = completed_observations()+ receipt["results"]["ts"]["scenarios"]["rebind_close"][field] = value+ self.assertFalse(classify_validation(receipt))++ def test_rust_rebind_must_execute_and_pass(self):+ for field in ("executed", "invariant_passed"):+ with self.subTest(field=field):+ receipt = completed_observations()+ receipt["results"]["rust"]["scenarios"]["rebind_close"][field] = False+ self.assertFalse(classify_validation(receipt))++ def test_unexpected_scenario_errors_fail_even_if_other_flags_are_green(self):+ for kind in ("ts", "rust"):+ for name in ("queued_close", "refusal", "rebind_close"):+ with self.subTest(kind=kind, name=name):+ receipt = completed_observations()+ receipt["results"][kind]["scenarios"][name]["error"] = "unexpected protocol failure"+ self.assertFalse(classify_validation(receipt))++ def test_fixture_and_cleanup_errors_fail_on_every_scenario(self):+ for kind in ("ts", "rust"):+ for name in ("queued_close", "refusal", "rebind_close"):+ for field in ("fixture_errors", "cleanup_errors"):+ with self.subTest(kind=kind, name=name, field=field):+ receipt = completed_observations()+ receipt["results"][kind]["scenarios"][name][field] = ["failed"]+ self.assertFalse(classify_validation(receipt))++ def test_missing_results_fail(self):+ for kind in ("ts", "rust"):+ for name in ("queued_close", "refusal", "rebind_close"):+ with self.subTest(kind=kind, name=name):+ receipt = completed_observations()+ del receipt["results"][kind]["scenarios"][name]+ self.assertFalse(classify_validation(receipt))+ receipt = completed_observations()+ del receipt["results"][kind]+ self.assertFalse(classify_validation(receipt))+ self.assertFalse(classify_validation({}))++ def test_preflight_or_binary_setup_errors_fail(self):+ receipt = completed_observations()+ receipt["preflight_error"] = "archive checksum mismatch"+ self.assertFalse(classify_validation(receipt))+ for kind in ("ts", "rust"):+ receipt = completed_observations()+ receipt["results"][kind]["error"] = "could not launch binary"+ self.assertFalse(classify_validation(receipt))+++if __name__ == "__main__":+ unittest.main()