Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

give windows a triage battery and fix the reported windows bugs (#3396)

ktd99dd9132bb0
diff --git a/.github/workflows/windows-runtime-triage.yml b/.github/workflows/windows-runtime-triage.yml
index 56ec0b5e3f..c07e8bba5e 100644
--- a/.github/workflows/windows-runtime-triage.yml
+++ b/.github/workflows/windows-runtime-triage.yml
@@ -1,9 +1,18 @@
# The Windows runtime triage loop (operator directive 2026-09-28): the
-# windows-latest runner is a full Windows Server VM, so this on-demand
-# workflow runs the real crate batteries on ANY ref - the iteration
-# surface for the runtime reds. The mandatory windows-latest CI job on
-# PR heads stays the merge-bar authority; this dispatchable run is the
-# fast loop (fix -> push -> dispatch -> triage -> repeat).
+# windows runner is a full Windows Server VM, so this workflow runs the
+# real crate batteries on ANY ref - the iteration surface for the runtime
+# reds.
+#
+# The Windows test surface (operator directive 2026-10-08: "we need to
+# give you an easy way to test things"): the PR wave gates every
+# Windows-touched PR with the scripted TUI battery, the nightly wave
+# re-runs it (plus the deep crate batteries) on main, and the dispatch
+# input stays the fast loop for triage (fix -> push -> dispatch ->
+# repeat). The battery boots the freshly-built binary as a real daemon and
+# drives the three reported breakages headlessly - session reopen renders
+# the old history, a subagent's session stays a distinct store entry, and
+# non-ASCII agent-message text survives rendering - uploading the pane
+# dumps as run artifacts the fleet can download and inspect.
name: windows-runtime-triage
on:
@@ -13,6 +22,25 @@ on:
description: "The ref to battery on Windows (branch, tag, or SHA; empty = this branch's head)"
required: false
default: ""
+ # The PR wave: every Windows-touched PR (crate source, the Windows
+ # installers, the workflow itself, the build manifests) runs the tui
+ # battery before review - the repeatable Windows verifier every future
+ # lane gets for free, without a persistent VM.
+ pull_request:
+ types: [opened, synchronize, reopened, ready_for_review]
+ branches: [main]
+ paths:
+ - "crates/**"
+ - ".github/workflows/windows-runtime-triage.yml"
+ - "install.ps1"
+ - "install-rust.sh"
+ - "scripts/**"
+ - "Cargo.toml"
+ - "Cargo.lock"
+ # The nightly wave: main gets the battery every night even when no PR
+ # touched it (the schedule trigger runs on the default branch only).
+ schedule:
+ - cron: "0 4 * * *"
permissions:
contents: read
@@ -28,8 +56,91 @@ env:
CARGO_INCREMENTAL: 0
jobs:
+ # The contributor-trust gate (the ci.yml trust job's own class): PR
+ # authors must be a bot, a collaborator, or a vouched contributor before
+ # they bill a windows runner minute.
+ trust:
+ name: contributor trust
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ outputs:
+ allowed: ${{ github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || steps.vouch.outputs.vouched == 'true' }}
+ steps:
+ - name: Check pull request author
+ id: vouch
+ if: github.event_name == 'pull_request'
+ uses: mitchellh/vouch/action/check-user@d66fa29a64600490892131ad87597c30c91fcac4 # v1
+ with:
+ user: ${{ github.event.pull_request.user.login }}
+ allow-fail: true
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ # THE WINDOWS TEST SURFACE (the operator's 2026-10-08 ask): the freshly
+ # built binary booted as a real daemon, driven through the three
+ # scripted TUI scenarios of crates/pa-cli/tests/windows_runtime_triage_e2e.rs
+ # (the reopen battery, the subagent-distinct battery, the glyph-panes
+ # battery), with captured headless panes uploaded for renderer inspection.
+ # The runner is pinned to windows-2022 (never the mutable windows-latest):
+ # the same reviewed-baseline rule the release build-windows job carries.
+ windows-runtime-tui-battery:
+ name: windows tui battery (reopen, subagent distinct, unicode panes)
+ needs: trust
+ if: needs.trust.result == 'success' && needs.trust.outputs.allowed == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)
+ runs-on: windows-2022
+ permissions:
+ contents: read
+ timeout-minutes: 90
+ env:
+ # Captured headless panes supplement native terminal validation.
+ WINDOWS_RUNTIME_TRIAGE_DUMP_DIR: '${{ github.workspace }}\win-tui-dumps'
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ ref: ${{ inputs.ref || github.ref }}
+ # The pinned SHA is the toolchain pin: this action version has no
+ # `toolchain` input, and its parse step hard-codes 1.98.1. Change
+ # the compiler by changing the SHA; a `toolchain:` input is ignored.
+ - uses: dtolnay/rust-toolchain@ce678459e9fc7500d337468f904b95f1b5c10b5e # 1.98.1 action pin; the SHA selects the toolchain
+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
+ with:
+ key: windows-tui-battery
+ # The binary the battery boots is `CARGO_BIN_EXE_prime-agent` - the
+ # same commit's fresh build. The explicit step names the freshly
+ # built binary and warms the test run's build.
+ - name: Build the binary the battery boots (locked)
+ run: cargo build --locked -p pa-cli --bin prime-agent
+ # Console VT setup/restore; redirected CI stdout can take the no-op branch.
+ - name: The Windows console mode regression
+ shell: bash
+ run: |
+ set -euo pipefail
+ cargo test --locked -p pa-types --lib console -- --nocapture
+ - name: Run the triage battery (the three scripted TUI scenarios)
+ shell: bash
+ run: |
+ set -euo pipefail
+ # The panes must land in the artifact dir: a green battery with
+ # an unset dump dir would upload no renderer evidence.
+ test -n "${WINDOWS_RUNTIME_TRIAGE_DUMP_DIR}" \
+ || { echo "::error::WINDOWS_RUNTIME_TRIAGE_DUMP_DIR is unset"; exit 1; }
+ cargo test --locked -p pa-cli --test windows_runtime_triage_e2e -- --test-threads=1 --nocapture
+ # Renderer evidence only: these frames do not validate console glyphs.
+ - name: Upload the pane dumps
+ if: always()
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: windows-tui-dumps-${{ github.run_id }}
+ path: win-tui-dumps
+ if-no-files-found: warn
+
+ # The deep battery (the multi-hour debug loop; the full pa-cli e2e set
+ # alone runs past three hours on this runner - measured twice): the
+ # on-demand/nightly arm stays, but it must not bill on every PR.
windows-battery:
name: windows battery (on-demand)
+ if: github.event_name != 'pull_request'
runs-on: windows-latest
# GitHub-hosted jobs stop at six hours whatever this says, so 360 is
# the real maximum. The full pa-cli e2e set alone runs past it on this
diff --git a/crates/pa-cli/src/lib.rs b/crates/pa-cli/src/lib.rs
index eb1ee12f1d..d73e5095f8 100644
--- a/crates/pa-cli/src/lib.rs
+++ b/crates/pa-cli/src/lib.rs
@@ -133,6 +133,9 @@ fn main_impl(args: &[String], runtime: &dyn mode::Runtime) -> Result<i32, String
let app_mode = mode::AppMode::resolve(&parsed, std::io::stdin().is_terminal());
+ // Enable Windows VT processing before raw ANSI mode writes.
+ pa_types::platform::console_init();
+
if public_command.attach_agent.is_some() && app_mode != mode::AppMode::Interactive {
return Err("attach requires an interactive terminal".to_string());
}
diff --git a/crates/pa-cli/src/main.rs b/crates/pa-cli/src/main.rs
index e253678aad..e7df156408 100644
--- a/crates/pa-cli/src/main.rs
+++ b/crates/pa-cli/src/main.rs
@@ -6,5 +6,7 @@ fn main() {
pa_types::memory_release::cap_thread_arenas();
let args: Vec<String> = std::env::args().skip(1).collect();
let code = pa_cli::main_with_runtime(&args, &pa_cli::PrintRuntime);
+ // Restore the Windows VT bit before process exit.
+ pa_types::platform::console_restore();
std::process::exit(code);
}
diff --git a/crates/pa-cli/tests/windows_runtime_triage_e2e.rs b/crates/pa-cli/tests/windows_runtime_triage_e2e.rs
new file mode 100644
index 0000000000..4bd9d1446a
--- /dev/null
+++ b/crates/pa-cli/tests/windows_runtime_triage_e2e.rs
@@ -0,0 +1,684 @@
+// large_futures: stack futures on hot paths by design. too_many_lines:
+// style gate only.
+#![allow(clippy::large_futures, clippy::too_many_lines)]
+
+//! The Windows runtime triage battery (the operator's 2026-10-08 ask: "we
+//! need to give you an easy way to test things"): three scripted TUI
+//! scenarios that boot the freshly-built binary against a real daemon and
+//! assert the Windows-reported breakages stay fixed. The workflow
+//! `.github/workflows/windows-runtime-triage.yml` runs this battery on
+//! windows-2022 for Windows-touched PRs and nightly on main, and uploads
+//! the captured pane dumps (`WINDOWS_RUNTIME_TRIAGE_DUMP_DIR`) as run
+//! artifacts the fleet can read.
+//!
+//! The scenarios map one-to-one onto the operator's report:
+//! (1) `tui_reopen_renders_the_old_history` - reopening an old session
+//! showed none of the old messages: the battery writes real turns,
+//! stops the daemon (the cold-reopen path - the session is no longer
+//! live), starts a fresh one, reopens the stored file, and asserts
+//! the rendered frames contain BOTH old user messages and BOTH old
+//! replies.
+//! (2) `subagent_session_stays_a_distinct_store_entry` - all sessions
+//! and their subagents appeared grouped into one session: the
+//! battery creates a parent session and a REAL child (the daemon
+//! create carrying `parentSessionPath`/`rlmDepth` - the same
+//! durable create a `rlm.spawn` issues) and asserts the two store
+//! entries are distinct files with distinct header ids, the child's
+//! header names the parent, and the agents view nests the child
+//! under the parent as its own row.
+//! (3) `agent_message_rows_dump_their_glyphs` checks non-ASCII text in
+//! user and assistant headless frames, dumping them when configured.
+//! It does not validate console glyphs, fonts or `ConPTY` input/output.
+//!
+//! The harness is PORTABLE by design: the same battery runs in the linux
+//! CI shards (so every lane gates it) and on the windows-2022 runner (the
+//! Windows surface). The daemon endpoint is a Unix socket on unix hosts
+//! and a named pipe on Windows (`--daemon-socket` carries the pipe name);
+//! everything else - the scripted engine, the headless TUI driver, the
+//! store reads - is platform-neutral product code.
+
+#[cfg(unix)]
+use std::os::unix::process::CommandExt;
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::time::{Duration, Instant};
+
+use pa_tui::interactive::{
+ HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection, SessionSelection, UiMode,
+};
+use serde_json::{json, Map, Value};
+
+/// The daemon supervisor spawned as the freshly-built binary
+/// (`CARGO_BIN_EXE_prime-agent --mode daemon`).
+struct Supervisor {
+ child: Child,
+ socket: PathBuf,
+}
+
+impl Drop for Supervisor {
+ fn drop(&mut self) {
+ stop_supervisor(self);
+ }
+}
+
+/// Stop the daemon by protocol (the product's own graceful path), then
+/// hard-kill the child. The portable form: the daemon client rides the
+/// platform transport (named pipe on Windows, Unix socket elsewhere), so
+/// the shutdown works on every host.
+fn stop_supervisor(supervisor: &mut Supervisor) {
+ let socket = supervisor.socket.clone();
+ // The shutdown rides its own thread: `Drop` can run inside the async
+ // test's runtime, where `block_on` would be a nested runtime.
+ let shutdown = std::thread::spawn(move || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("shutdown runtime");
+ runtime.block_on(async move {
+ let Ok((client, events)) = pa_tui::daemon_client::DaemonClient::connect(&socket).await
+ else {
+ return;
+ };
+ let shutdown = pa_types::daemon::DaemonCommand::Shutdown {
+ id: None,
+ force: Some(true),
+ rest: Map::default(),
+ };
+ let _ = client.request_with_timeout(shutdown, 1_500).await;
+ client.close();
+ drop(events);
+ });
+ });
+ let _ = shutdown.join();
+ let _ = supervisor.child.kill();
+ let _ = supervisor.child.wait();
+}
+
+/// The daemon endpoint for this test run: a Unix socket file under the
+/// test dir on unix hosts, a uniquely named pipe on Windows (pipe names
+/// are host-global, so a unique suffix keeps parallel test binaries from
+/// colliding).
+fn daemon_endpoint(dir: &Path) -> PathBuf {
+ #[cfg(unix)]
+ {
+ dir.join("daemon.sock")
+ }
+ #[cfg(not(unix))]
+ {
+ // Pipe names are host-global, so the unique suffix keeps parallel
+ // test binaries from colliding (the temp dir does not appear in
+ // the name).
+ let _ = dir;
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|stamp| stamp.as_nanos())
+ .unwrap_or_default();
+ PathBuf::from(format!(
+ r"\\.\pipe\prime-agent-triage-{}-{unique}",
+ std::process::id()
+ ))
+ }
+}
+
+/// Spawn the freshly-built binary as a daemon supervisor.
+// The supervisor child is killed and reaped by `Supervisor`'s Drop; the lint cannot see past the spawn site.
+#[allow(clippy::zombie_processes)]
+fn spawn_supervisor(dir: &Path) -> Supervisor {
+ let socket = daemon_endpoint(dir);
+ let agent_dir = dir.join("agent");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ let mut command = Command::new(env!("CARGO_BIN_EXE_prime-agent"));
+ command
+ .args(["--mode", "daemon", "--daemon-socket"])
+ .arg(&socket)
+ .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)
+ // The daemon's startup catalog refresh must never reach the network
+ // from a test: PI_OFFLINE keeps it on the bundled snapshot.
+ .env("PI_OFFLINE", "1")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ // The launcher strips inherited worker role env vars before spawning
+ // the supervisor; a CLI running inside a daemon worker must not leak
+ // them.
+ for var in [
+ pa_daemon::worker::WORKER_ROLE_ENV,
+ pa_daemon::worker::WORKER_TOKEN_ENV,
+ pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV,
+ pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV,
+ pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV,
+ pa_daemon::worker::WORKER_SOCKET_ENV,
+ pa_daemon::worker::WORKER_INSTANCE_ID_ENV,
+ pa_daemon::worker::WORKER_SCRIPT_ENV,
+ ] {
+ command.env_remove(var);
+ }
+ // Ambient provider credentials must not leak into the daemon's
+ // catalog: every spawned supervisor here serves models.json fixtures
+ // only.
+ for provider in pa_ai::models_generated::get_providers() {
+ if let Some(vars) = pa_ai::env_api_keys::get_api_key_env_vars(provider) {
+ for var in vars {
+ command.env_remove(var);
+ }
+ }
+ }
+ command.env_remove("PRIME_TEAM_ID");
+ command.env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ );
+ command.env("PA_DAEMON_WORKER_CONNECT_TIMEOUT_MS", "90000");
+ // Die with this test binary on unix (the protocol teardown below is
+ // the exit path; this is the backstop for a failing test).
+ #[cfg(unix)]
+ unsafe {
+ command.pre_exec(move || {
+ libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL);
+ Ok(())
+ });
+ }
+ let child = command.spawn().expect("spawn prime-agent --mode daemon");
+ Supervisor { child, socket }
+}
+
+/// Wait until the session's runtime lease is free (no live owner), the
+/// bounded cold-reopen drain: a killed supervisor's workers exit on their
+/// supervisor-lost watchdog, never instantly.
+fn drain_session_lease(agent_dir: &Path, session_path: &Path) {
+ let deadline = Instant::now() + Duration::from_secs(45);
+ while Instant::now() < deadline {
+ if pa_daemon::lease::live_lease_owner(agent_dir, session_path).is_none() {
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(250));
+ }
+ panic!("the killed daemon's worker still held the session lease past the drain bound");
+}
+
+/// Wait until the supervisor answers a client connect (the readiness
+/// probe - a named pipe has no socket file to poll for).
+async fn wait_for_daemon(socket: &Path) {
+ let deadline = Instant::now() + Duration::from_secs(90);
+ while Instant::now() < deadline {
+ if let Ok((client, events)) = pa_tui::daemon_client::DaemonClient::connect(socket).await {
+ client.close();
+ drop(events);
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("the supervisor never answered a client connect");
+}
+
+/// The base options every TUI run in this battery uses: the scripted
+/// engine, the isolated session dir, no networked model, no onboarding.
+fn tui_options(socket: &Path, session_dir: &Path, script: &Path) -> InteractiveOptions {
+ InteractiveOptions {
+ models: None,
+ socket_path: socket.to_path_buf(),
+ cwd: session_dir.to_path_buf(),
+ model_catalog: Vec::new(),
+ model_configured_providers: std::collections::HashSet::default(),
+ model_recent_models: Vec::new(),
+ default_thinking_level: None,
+ session_dir: Some(session_dir.to_path_buf()),
+ script_path: Some(script.to_path_buf()),
+ model_selection: ModelSelection::default(),
+ no_session: false,
+ session: SessionSelection::New,
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: true,
+ theme: "prime".to_string(),
+ code_block_indent: " ".to_string(),
+ tree_filter_mode: String::new(),
+ branch_summary_skip_prompt: false,
+ version: "0.0.0".to_string(),
+ onboarding: None,
+ telemetry_disabled: Some(true),
+ client_auth: None,
+ traces: None,
+ provider_auth: None,
+ update_commands: None,
+ telemetry: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ session_rlm_depth: None,
+ session_has_children: false,
+ restore_dock_focus: false,
+ client_settings: None,
+ prompt_stash: std::sync::Arc::default(),
+ }
+}
+
+/// The headless run's wall (the unix harness's bound): a turn that never
+/// settles parks the run forever; the wall makes that a failing test.
+const HEADLESS_RUN_BOUND: Duration = Duration::from_secs(180);
+
+async fn run_headless_bounded(
+ options: InteractiveOptions,
+ plan: HeadlessPlan,
+) -> pa_tui::interactive::InteractiveOutcome {
+ match tokio::time::timeout(
+ HEADLESS_RUN_BOUND,
+ pa_tui::interactive::run_interactive(options, UiMode::Headless(plan)),
+ )
+ .await
+ {
+ Ok(outcome) => outcome.expect("interactive run"),
+ Err(tokio::time::error::Elapsed { .. }) => {
+ panic!("the headless run exceeded {HEADLESS_RUN_BOUND:?}: the wedge class - a turn never settled")
+ }
+ }
+}
+
+/// Write one scenario's captured panes to the workflow dump dir when the
+/// workflow set it (the artifact the fleet downloads); a no-op with a
+/// logged reason otherwise (the linux CI shards run without it).
+fn dump_frames(scenario: &str, frames: &[String]) {
+ let Ok(dir) = std::env::var("WINDOWS_RUNTIME_TRIAGE_DUMP_DIR") else {
+ eprintln!("{scenario}: WINDOWS_RUNTIME_TRIAGE_DUMP_DIR unset - no pane dump written");
+ return;
+ };
+ let dir = PathBuf::from(dir);
+ std::fs::create_dir_all(&dir).expect("create the dump dir");
+ for (index, frame) in frames.iter().enumerate() {
+ let path = dir.join(format!("{scenario}-frame-{index:03}.txt"));
+ std::fs::write(path, frame).expect("write the pane dump");
+ }
+ let joined = dir.join(format!("{scenario}-frames.txt"));
+ std::fs::write(joined, frames.join("\n")).expect("write the joined pane dump");
+}
+
+/// The daemon-protocol session create the battery uses: the scripted
+/// engine's responses ride the script file; a parent path + depth make
+/// the session a real subagent (the same durable create a `rlm.spawn`
+/// issues).
+// The harness mirrors the daemon Create command's own config rows; a builder struct would shadow the protocol.
+#[allow(clippy::too_many_arguments)]
+async fn create_session_via_daemon(
+ socket: &Path,
+ script_path: &Path,
+ script: &Value,
+ cwd: &Path,
+ session_dir: &Path,
+ name: Option<&str>,
+ parent_session_path: Option<&Path>,
+ rlm_depth: Option<u64>,
+) -> String {
+ std::fs::write(script_path, script.to_string()).expect("write script");
+ let (client, _events) = pa_tui::daemon_client::DaemonClient::connect(socket)
+ .await
+ .expect("connect supervisor");
+ let mut config = json!({
+ "cwd": cwd.display().to_string(),
+ "sessionDir": session_dir.display().to_string(),
+ "script": script_path.display().to_string(),
+ "telemetryDisabled": true,
+ });
+ if let Some(parent) = parent_session_path {
+ config["parentSessionPath"] = json!(parent.display().to_string());
+ config["rlmDepth"] = json!(rlm_depth.unwrap_or(1));
+ }
+ let data = client
+ .request_ok(pa_types::daemon::DaemonCommand::Create {
+ id: None,
+ session_path: None,
+ continue_recent: None,
+ no_session: None,
+ name: name.map(str::to_string),
+ config: Some(config),
+ telemetry_disabled: None,
+ runtime_metadata: None,
+ lifecycle: None,
+ env: None,
+ launch_env: None,
+ rest: Map::default(),
+ })
+ .await
+ .expect("create session");
+ client.close();
+ // The DURABLE identity: `sessionId` is the session file's header id
+ // (`activeSessionId` is the live worker's ephemeral id - the worker's
+ // lifecycle rows publish both).
+ data.get("sessionId")
+ .or_else(|| data.get("id"))
+ .and_then(Value::as_str)
+ .expect("session id")
+ .to_string()
+}
+
+/// Every session file under `session_dir` with a readable header.
+fn session_files(session_dir: &Path) -> Vec<PathBuf> {
+ let mut files = Vec::new();
+ for entry in std::fs::read_dir(session_dir)
+ .expect("session dir")
+ .flatten()
+ {
+ let path = entry.path();
+ if path.extension().and_then(|ext| ext.to_str()) == Some("jsonl") {
+ files.push(path);
+ }
+ }
+ files.sort();
+ files
+}
+
+/// The single session file under `session_dir` (each scenario starts with
+/// an empty store), with its header id.
+fn the_session_file(session_dir: &Path) -> (PathBuf, String) {
+ let files = session_files(session_dir);
+ assert_eq!(files.len(), 1, "exactly one session file: {files:?}");
+ let path = files[0].clone();
+ let header = pa_daemon::session_store::read_session_header(&path)
+ .expect("the session file carries a readable header");
+ (path, header.id)
+}
+
+/// Scenario (1): reopening an old session renders its old messages. The
+/// first run writes real turns; the daemon is stopped (the cold-reopen
+/// path - no live worker holds the history); a fresh daemon boots against
+/// the same store; the reopened session must render the OLD messages.
+#[tokio::test]
+async fn tui_reopen_renders_the_old_history() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let script_path = dir.path().join("reopen-script.json");
+
+ // Run 1: a fresh session with two scripted turns.
+ std::fs::write(
+ &script_path,
+ json!({ "responses": [
+ { "text": "the reopen battery reply one" },
+ { "text": "the reopen battery reply two" },
+ ]})
+ .to_string(),
+ )
+ .expect("write script");
+ let mut supervisor = spawn_supervisor(dir.path());
+ wait_for_daemon(&supervisor.socket).await;
+ let mut options = tui_options(&supervisor.socket, &session_dir, &script_path);
+ options.cwd = dir.path().to_path_buf();
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::Submit("the reopen battery question".to_string()),
+ HeadlessStep::WaitIdle { timeout_ms: 60_000 },
+ HeadlessStep::Submit("the reopen battery follow up".to_string()),
+ HeadlessStep::WaitIdle { timeout_ms: 60_000 },
+ ],
+ width: 100,
+ height: 30,
+ };
+ let first = run_headless_bounded(options, plan).await;
+ assert!(!first.frames.is_empty(), "the first run captured frames");
+ let rendered = first.frames.join("\n");
+ assert!(
+ rendered.contains("the reopen battery reply one"),
+ "the first scripted turn rendered:\n{rendered}"
+ );
+ drop(first);
+
+ // The store persisted the turns before the daemon goes away.
+ let (session_path, session_id) = the_session_file(&session_dir);
+ assert!(
+ std::fs::read(&session_path)
+ .expect("the session file persisted")
+ .len()
+ > 100,
+ "the session file holds the turns"
+ );
+
+ // The cold reopen: the daemon (and its live worker) are gone; a fresh
+ // supervisor boots against the same store.
+ stop_supervisor(&mut supervisor);
+ // The killed supervisor's session workers can outlive it (unix's
+ // PDEATHSIG kills only the supervisor's own child; Windows has no
+ // equivalent - the worker exits on its supervisor-lost watchdog),
+ // and a lingering worker holds the session's runtime lease: a
+ // reopen before it exits answers the session-hold refusal, not the
+ // stored history. Drain the lease first (the first windows-runner
+ // run of this battery caught exactly this class: the reopen came
+ // back with an empty session id).
+ drain_session_lease(&agent_dir, &session_path);
+ let second_supervisor = spawn_supervisor(dir.path());
+ wait_for_daemon(&second_supervisor.socket).await;
+
+ // Run 2: the stored session reopens and renders the OLD messages.
+ let mut options = tui_options(&second_supervisor.socket, &session_dir, &script_path);
+ options.cwd = dir.path().to_path_buf();
+ options.session = SessionSelection::Resume(session_path.clone());
+ let plan = HeadlessPlan {
+ steps: vec![HeadlessStep::WaitRender {
+ needle: "the reopen battery reply one".to_string(),
+ timeout_ms: 60_000,
+ }],
+ width: 100,
+ height: 30,
+ };
+ let reopened = run_headless_bounded(options, plan).await;
+ // The panes dump BEFORE the asserts: a red run uploads its evidence
+ // (the workflow's red-runs-too contract). The durable identity is
+ // asserted below - the triage loop reads the ids from the failure
+ // message itself, never from a log row.
+ dump_frames("reopen-history", &reopened.frames);
+ assert_eq!(
+ reopened.session_id, session_id,
+ "the reopen attached the stored session, not a new one"
+ );
+ let rendered = reopened.frames.join("\n");
+ assert!(
+ rendered.contains("the reopen battery question"),
+ "the OLD user message renders on reopen (the operator's report 1):\n{rendered}"
+ );
+ assert!(
+ rendered.contains("the reopen battery reply one"),
+ "the OLD scripted reply renders on reopen (the operator's report 1):\n{rendered}"
+ );
+ assert!(
+ rendered.contains("the reopen battery reply two"),
+ "the second OLD scripted reply renders on reopen:\n{rendered}"
+ );
+ dump_frames("reopen-history", &reopened.frames);
+}
+
+/// Scenario (2): a subagent's session stays a DISTINCT store entry - a
+/// separate file with its own header id naming the parent - and the agents
+/// view nests it under the parent instead of merging everything into one
+/// session row.
+#[tokio::test]
+async fn subagent_session_stays_a_distinct_store_entry() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let supervisor = spawn_supervisor(dir.path());
+ wait_for_daemon(&supervisor.socket).await;
+
+ // The parent session (a real daemon create, scripted engine).
+ let parent_script = dir.path().join("parent-script.json");
+ create_session_via_daemon(
+ &supervisor.socket,
+ &parent_script,
+ &json!({ "responses": [ { "text": "the parent orchestrates" } ] }),
+ dir.path(),
+ &session_dir,
+ Some("triage-parent"),
+ None,
+ None,
+ )
+ .await;
+ let (parent_path, parent_id) = the_session_file(&session_dir);
+
+ // The child: the REAL subagent create (the daemon create carrying
+ // `parentSessionPath`/`rlmDepth` - the same durable create a
+ // `rlm.spawn` issues).
+ let child_script = dir.path().join("child-script.json");
+ let child_id = create_session_via_daemon(
+ &supervisor.socket,
+ &child_script,
+ &json!({ "responses": [ { "text": "the child works" } ] }),
+ dir.path(),
+ &session_dir,
+ Some("triage-child"),
+ Some(&parent_path),
+ Some(1),
+ )
+ .await;
+ assert_ne!(parent_id, child_id, "the child is its own session");
+
+ // The store keeps TWO distinct entries with distinct header ids.
+ let files = session_files(&session_dir);
+ assert_eq!(files.len(), 2, "two distinct store entries: {files:?}");
+ let child_path = files
+ .iter()
+ .find(|path| path.as_path() != parent_path.as_path())
+ .expect("the child's own file")
+ .clone();
+ let parent_header =
+ pa_daemon::session_store::read_session_header(&parent_path).expect("parent header");
+ let child_header =
+ pa_daemon::session_store::read_session_header(&child_path).expect("child header");
+ assert_eq!(parent_header.id, parent_id);
+ assert_eq!(child_header.id, child_id);
+ assert_ne!(parent_path, child_path, "separate store files");
+ assert_eq!(
+ child_header.parent_session.as_deref().map(Path::new),
+ Some(parent_path.as_path()),
+ "the child's header names the parent's file"
+ );
+ assert_eq!(child_header.rlm_depth, Some(1), "the child's depth");
+ assert!(
+ parent_header.parent_session.is_none(),
+ "the parent stays a root"
+ );
+
+ // The daemon's own session list reports both, with distinct files.
+ let (client, _events) = pa_tui::daemon_client::DaemonClient::connect(&supervisor.socket)
+ .await
+ .expect("connect supervisor");
+ let list = client
+ .request_ok(pa_types::daemon::DaemonCommand::List {
+ id: None,
+ all: None,
+ cwd: None,
+ session_dir: None,
+ include_client_owned: None,
+ rest: Map::default(),
+ })
+ .await
+ .expect("list");
+ client.close();
+ let sessions = list["sessions"].as_array().cloned().unwrap_or_default();
+ let parent_row = sessions
+ .iter()
+ .find(|row| row["sessionFile"] == json!(parent_path.display().to_string()))
+ .expect("the parent row names the parent file");
+ let child_row = sessions
+ .iter()
+ .find(|row| row["sessionFile"] == json!(child_path.display().to_string()))
+ .expect("the child row names the child's OWN file");
+ assert_eq!(
+ parent_row["sessionId"],
+ json!(parent_id),
+ "the parent row's session id: {parent_row}"
+ );
+ assert_eq!(
+ child_row["sessionId"],
+ json!(child_id),
+ "the child row's session id: {child_row}"
+ );
+
+ // The agents view nests the child under the parent - the operator's
+ // report 2: sessions and subagents must NOT merge into one session.
+ let options = pa_tui::agents_view::AgentsViewOptions {
+ socket_path: supervisor.socket.clone(),
+ cwd: dir.path().to_path_buf(),
+ session_dir: Some(session_dir.clone()),
+ theme: "prime".to_string(),
+ version: "0.0.0".to_string(),
+ anchor_session_id: None,
+ scope: None,
+ query: None,
+ expanded_ancestors: Vec::new(),
+ selected_row_identity: None,
+ selected_key: None,
+ status_message: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ show_hardware_cursor: false,
+ incident_notice_state: None,
+ create_config: serde_json::json!({}),
+ };
+ let plan = pa_tui::agents_view::AgentsHeadlessPlan {
+ steps: vec![
+ pa_tui::agents_view::AgentsStep::WaitSettle { timeout_ms: 30_000 },
+ pa_tui::agents_view::AgentsStep::Key("alt+right".to_string()),
+ pa_tui::agents_view::AgentsStep::WaitSettle { timeout_ms: 30_000 },
+ ],
+ width: 120,
+ height: 36,
+ };
+ let view = pa_tui::agents_view::run_agents_view(
+ options,
+ pa_tui::agents_view::AgentsViewUiMode::Headless(plan),
+ None,
+ )
+ .await
+ .expect("agents view run")
+ .outcome;
+ // The panes dump BEFORE the asserts: a red run uploads its evidence.
+ dump_frames("subagent-distinct", &view.frames);
+ let rendered = view.frames.join("\n");
+ assert!(
+ rendered.contains("triage-parent"),
+ "the parent's own session row renders:\n{rendered}"
+ );
+ assert!(
+ rendered.contains("triage-child"),
+ "the child's own session row renders nested under the parent:\n{rendered}"
+ );
+ assert!(
+ rendered.contains("1 subagent"),
+ "the parent's summary row counts its distinct child:\n{rendered}"
+ );
+}
+
+/// Scenario (3): preserve non-ASCII user/assistant text in headless frames.
+/// This renderer regression does not exercise console, font or `ConPTY` I/O.
+#[tokio::test]
+async fn agent_message_rows_dump_their_glyphs() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let script_path = dir.path().join("glyph-script.json");
+ std::fs::write(
+ &script_path,
+ json!({ "responses": [ { "text": "reply café 中文 ◆ ▸" } ] }).to_string(),
+ )
+ .expect("write script");
+ let supervisor = spawn_supervisor(dir.path());
+ wait_for_daemon(&supervisor.socket).await;
+ let mut options = tui_options(&supervisor.socket, &session_dir, &script_path);
+ options.cwd = dir.path().to_path_buf();
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::Submit("question café 中文 ◆ ▸".to_string()),
+ HeadlessStep::WaitIdle { timeout_ms: 60_000 },
+ ],
+ width: 100,
+ height: 30,
+ };
+ let outcome = run_headless_bounded(options, plan).await;
+ dump_frames("glyph-rows", &outcome.frames);
+ let rendered = outcome.frames.join("\n");
+ assert!(
+ rendered.contains("question café 中文 ◆ ▸"),
+ "the user message row renders:\n{rendered}"
+ );
+ assert!(
+ rendered.contains("reply café 中文 ◆ ▸"),
+ "the agent message row renders:\n{rendered}"
+ );
+}
diff --git a/crates/pa-cli/tests/windows_runtime_triage_workflow.rs b/crates/pa-cli/tests/windows_runtime_triage_workflow.rs
new file mode 100644
index 0000000000..6d5d1ce522
--- /dev/null
+++ b/crates/pa-cli/tests/windows_runtime_triage_workflow.rs
@@ -0,0 +1,304 @@
+// large_futures: stack futures on hot paths by design. too_many_lines:
+// style gate only.
+#![allow(clippy::large_futures, clippy::too_many_lines)]
+
+//! The windows-runtime-triage workflow's contract gates (the operator's
+//! 2026-10-08 ask: "we need to give you an easy way to test things" - a
+//! repeatable Windows test surface for the fleet). The workflow IS the
+//! test surface, so this file pins its contract the same way
+//! `release_workflow.rs` pins the release pipeline's:
+//!
+//! - the PR trigger: every Windows-touched PR (crate source, the
+//! Windows installers, the workflow itself, the build manifests) runs
+//! the battery before review;
+//! - the nightly trigger: main gets the battery every night even when
+//! no PR touched it;
+//! - the `windows-runtime-tui-battery` job: the freshly-built binary
+//! driven through the three scripted TUI scenarios
+//! (`windows_runtime_triage_e2e.rs`), with the captured pane dumps
+//! uploaded as a run artifact (`if: always()` - the fleet reads the
+//! dumps from a red run too);
+//! - the runner pin: windows-2022, never the mutable `windows-latest`
+//! (the reviewed-baseline rule the release build already carries);
+//! - the deep `windows-battery` job stays the on-demand/nightly loop,
+//! not a per-PR gate (the full pa-cli e2e set runs past three hours
+//! on that runner - measured twice).
+//!
+//! The battery source file's three scenario tests are asserted by name, so
+//! the workflow and the battery it claims to run cannot drift apart.
+
+use std::fs;
+use std::path::PathBuf;
+
+/// The repo root (crates/pa-cli -> crates -> root): the workflow and the
+/// battery live there.
+fn repo_root() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .ancestors()
+ .nth(2)
+ .map(PathBuf::from)
+ .expect("worktree root")
+}
+
+/// The committed windows-runtime-triage workflow, parsed as YAML. YAML 1.1
+/// readers may hand back the `on` key as a boolean (`true`), so the trigger
+/// accessor handles both spellings.
+fn workflow_yaml() -> (serde_yaml::Value, serde_yaml::Value) {
+ let text = fs::read_to_string(repo_root().join(".github/workflows/windows-runtime-triage.yml"))
+ .expect("read .github/workflows/windows-runtime-triage.yml");
+ let workflow: serde_yaml::Value =
+ serde_yaml::from_str(&text).expect("windows-runtime-triage.yml parses as YAML");
+ let triggers = workflow
+ .get("on")
+ .or_else(|| workflow.get("true"))
+ .cloned()
+ .expect("the workflow declares its triggers");
+ (workflow, triggers)
+}
+
+/// One job's definition by name.
+fn job(workflow: &serde_yaml::Value, name: &str) -> serde_yaml::Value {
+ workflow
+ .get("jobs")
+ .and_then(|jobs| jobs.get(name))
+ .cloned()
+ .unwrap_or_else(|| panic!("the workflow carries the {name:?} job"))
+}
+
+/// The steps' `run:` scripts of one job, in order.
+fn step_runs(job: &serde_yaml::Value) -> Vec<String> {
+ job.get("steps")
+ .and_then(serde_yaml::Value::as_sequence)
+ .map(|steps| {
+ steps
+ .iter()
+ .map(|step| {
+ step.get("run")
+ .and_then(serde_yaml::Value::as_str)
+ .unwrap_or_default()
+ .to_string()
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// The battery's scenario test names: the workflow must drive exactly
+/// these, and the battery file must keep defining them.
+const SCENARIO_TESTS: [&str; 3] = [
+ "tui_reopen_renders_the_old_history",
+ "subagent_session_stays_a_distinct_store_entry",
+ "agent_message_rows_dump_their_glyphs",
+];
+
+#[test]
+fn the_battery_source_defines_the_three_scenarios() {
+ let battery =
+ fs::read_to_string(repo_root().join("crates/pa-cli/tests/windows_runtime_triage_e2e.rs"))
+ .expect("read the battery source");
+ for scenario in SCENARIO_TESTS {
+ assert!(
+ battery.contains(&format!("async fn {scenario}")),
+ "the battery defines the {scenario} test"
+ );
+ }
+ assert!(
+ !battery.contains("#![cfg(unix)]"),
+ "the battery is the Windows surface: a whole-file unix gate would skip it on windows"
+ );
+}
+
+#[test]
+fn the_pr_wave_runs_on_windows_touched_paths() {
+ let (_, triggers) = workflow_yaml();
+ let pull_request = triggers
+ .get("pull_request")
+ .expect("the workflow carries the pull_request trigger");
+ let branches = pull_request
+ .get("branches")
+ .and_then(serde_yaml::Value::as_sequence)
+ .expect("the pull_request trigger names its branches");
+ assert!(
+ branches
+ .iter()
+ .any(|branch| branch.as_str() == Some("main")),
+ "the PR wave gates main: {branches:?}"
+ );
+ let paths = pull_request
+ .get("paths")
+ .and_then(serde_yaml::Value::as_sequence)
+ .expect("the pull_request trigger carries a Windows-touched paths filter");
+ let paths: Vec<&str> = paths.iter().filter_map(serde_yaml::Value::as_str).collect();
+ assert!(
+ paths.contains(&"crates/**"),
+ "every crate-source PR is Windows-touched: {paths:?}"
+ );
+ assert!(
+ paths
+ .iter()
+ .any(|path| path.ends_with("windows-runtime-triage.yml")),
+ "workflow edits re-run the workflow: {paths:?}"
+ );
+ assert!(
+ paths.contains(&"install.ps1"),
+ "the Windows installer is Windows-touched: {paths:?}"
+ );
+}
+
+#[test]
+fn the_nightly_wave_runs_on_main() {
+ let (_, triggers) = workflow_yaml();
+ let schedule = triggers
+ .get("schedule")
+ .and_then(serde_yaml::Value::as_sequence)
+ .expect("the workflow carries the nightly schedule");
+ assert!(
+ schedule.iter().any(|entry| entry.get("cron").is_some()),
+ "a nightly cron entry exists: {schedule:?}"
+ );
+}
+
+#[test]
+fn the_dispatch_loop_stays_available() {
+ let (_, triggers) = workflow_yaml();
+ assert!(
+ triggers.get("workflow_dispatch").is_some(),
+ "the on-demand triage dispatch stays (the fast fix->push->dispatch loop)"
+ );
+}
+
+#[test]
+fn the_tui_battery_job_boots_the_binary_and_dumps_the_panes() {
+ let (workflow, _) = workflow_yaml();
+ let job = job(&workflow, "windows-runtime-tui-battery");
+
+ // The runner pin: windows-2022, never the mutable windows-latest (the
+ // reviewed-baseline rule the release build's job comment carries).
+ let runs_on = job
+ .get("runs-on")
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the job pins its runner");
+ assert_eq!(
+ runs_on, "windows-2022",
+ "the battery runs on the pinned image, not the mutable label"
+ );
+
+ // The contributor-trust gate: PR authors must be vouched (the ci.yml
+ // trust job's own class - an unvouched author must not bill a
+ // windows runner).
+ let needs = job
+ .get("needs")
+ .map(|needs| match needs {
+ serde_yaml::Value::Sequence(entries) => entries
+ .iter()
+ .filter_map(serde_yaml::Value::as_str)
+ .collect::<Vec<_>>(),
+ serde_yaml::Value::String(single) => vec![single.as_str()],
+ _ => Vec::new(),
+ })
+ .unwrap_or_default();
+ assert!(
+ needs.contains(&"trust"),
+ "the battery job needs the trust gate: {needs:?}"
+ );
+ let condition = job
+ .get("if")
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the job gates itself on the trust verdict");
+ assert!(
+ condition.contains("outputs.allowed == 'true'"),
+ "the job runs only for allowed authors: {condition}"
+ );
+ assert!(
+ condition.contains("draft"),
+ "draft PRs do not bill the runner: {condition}"
+ );
+
+ // The freshly-built binary: the daemon the battery boots IS the
+ // freshly-built binary, so the job builds it first.
+ let runs = step_runs(&job);
+ let build = runs
+ .iter()
+ .find(|run| run.contains("cargo build --locked -p pa-cli --bin prime-agent"))
+ .expect("the job builds the freshly-built binary");
+ assert!(
+ build.contains("--target x86_64-pc-windows-msvc")
+ || build.contains("-p pa-cli --bin prime-agent"),
+ "the build step names the binary: {build}"
+ );
+
+ // Console mode regression; CI stdout may be redirected.
+ runs.iter()
+ .find(|run| run.contains("cargo test --locked -p pa-types --lib console"))
+ .expect("the job runs the pa-types console battery on the runner");
+
+ // The battery: the three scripted TUI scenarios, with the dump dir the
+ // panes land in for the artifact.
+ let battery = runs
+ .iter()
+ .find(|run| run.contains("--test windows_runtime_triage_e2e"))
+ .expect("the job runs the windows_runtime_triage_e2e battery");
+ assert!(
+ battery.contains("cargo test --locked -p pa-cli"),
+ "the battery runs locked: {battery}"
+ );
+ assert!(
+ battery.contains("WINDOWS_RUNTIME_TRIAGE_DUMP_DIR"),
+ "the battery writes its pane dumps to the artifact dir: {battery}"
+ );
+
+ // The panes ride the artifact: the icon dump the fleet downloads and
+ // inspects, uploaded on red runs too.
+ let steps = job
+ .get("steps")
+ .and_then(serde_yaml::Value::as_sequence)
+ .expect("the job carries steps");
+ let upload = steps
+ .iter()
+ .find(|step| {
+ step.get("uses")
+ .and_then(serde_yaml::Value::as_str)
+ .is_some_and(|uses| uses.starts_with("actions/upload-artifact"))
+ })
+ .expect("the job uploads the pane dumps");
+ let upload_if = upload
+ .get("if")
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the upload step carries its condition");
+ assert!(
+ upload_if.contains("always()"),
+ "the dumps upload on red runs too: {upload_if}"
+ );
+ let upload_name = upload
+ .get("with")
+ .and_then(|with| with.get("name"))
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the upload names its artifact");
+ assert!(
+ upload_name.starts_with("windows-tui-dumps-"),
+ "the artifact is the windows-tui-dumps set: {upload_name}"
+ );
+ let upload_path = upload
+ .get("with")
+ .and_then(|with| with.get("path"))
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the upload names its path");
+ assert!(
+ upload_path.contains("win-tui-dumps"),
+ "the upload carries the dump dir: {upload_path}"
+ );
+}
+
+#[test]
+fn the_deep_battery_stays_off_the_pr_wave() {
+ let (workflow, _) = workflow_yaml();
+ let job = job(&workflow, "windows-battery");
+ let condition = job
+ .get("if")
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the deep battery job keeps its dispatch/nightly gating");
+ assert!(
+ condition.contains("github.event_name != 'pull_request'"),
+ "the deep battery (the multi-hour debug loop) must not bill on every PR: {condition}"
+ );
+}
diff --git a/crates/pa-core/src/session/window_cache.rs b/crates/pa-core/src/session/window_cache.rs
index 8d3930f671..5fff3f2ede 100644
--- a/crates/pa-core/src/session/window_cache.rs
+++ b/crates/pa-core/src/session/window_cache.rs
@@ -180,6 +180,16 @@ pub enum AppendOwnership {
/// No runtime lease: append without publishing an incremental snapshot.
Unleased,
}
+/// Whether the file's last byte is a newline: the append boundary probe.
+fn file_tail_is_newline(path: &Path) -> io::Result<bool> {
+ use std::io::{Read, Seek};
+ let mut probe = std::fs::File::open(path)?;
+ let mut tail = [0u8; 1];
+ probe.seek(std::io::SeekFrom::End(-1))?;
+ probe.read_exact(&mut tail)?;
+ Ok(tail[0] == b'\n')
+}
+
/// Append authoritative JSONL bytes. Only a caller holding the existing session
/// lease may incrementally certify the cache. Rows must have fresh writer IDs.
/// Cache failures never fail a successful durable append.
@@ -189,6 +199,15 @@ pub enum AppendOwnership {
/// The durable append's I/O error; a failed incremental certification is dropped.
pub fn append_cached(path: &Path, bytes: &[u8], ownership: AppendOwnership) -> io::Result<()> {
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
+ // The torn-tail boundary (the append-only reopen's belt): an
+ // unterminated final row - a crashed append the repair failed to
+ // re-terminate, its errors swallowed - must not merge with the first
+ // appended row: both would be lost to the index. One newline before
+ // the payload keeps the torn row alone (the loaders skip it) and the
+ // appended rows parseable. A no-op on a healthy file.
+ if file.metadata()?.len() > 0 && !file_tail_is_newline(path)? {
+ file.write_all(b"\n")?;
+ }
file.write_all(bytes)?;
file.flush()?;
crate::platform::fsync(&file)?;
diff --git a/crates/pa-core/src/session/window_tests.rs b/crates/pa-core/src/session/window_tests.rs
index 69ba4d833a..93e334e76a 100644
--- a/crates/pa-core/src/session/window_tests.rs
+++ b/crates/pa-core/src/session/window_tests.rs
@@ -969,3 +969,35 @@ async fn boundary_window_snapshot_keeps_the_historical_read() {
"the pre-window row must stay served through the historical read"
);
}
+
+/// The append-only reopen's belt (the keeper review's torn-tail finding): a
+/// crashed append's unterminated final row - one the repair failed to
+/// re-terminate, its errors swallowed - must not merge with the first
+/// appended row: both would be lost to the index. The append boundary
+/// guard writes one newline first, so the appended row parses on its own
+/// line and the torn row alone stays skipped.
+#[test]
+fn append_cached_bounds_an_unterminated_tail() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("torn.jsonl");
+ std::fs::write(
+ &path,
+ "{\"type\":\"session\",\"id\":\"s\",\"timestamp\":\"2026-10-08T00:00:00.000Z\"}\n{\"type\":\"message\",\"id\":\"torn\",\"timestamp\":\"2026-10-08T00:00:00.000Z\"",
+ )
+ .unwrap();
+ let appended =
+ b"{\"type\":\"message\",\"id\":\"after\",\"timestamp\":\"2026-10-08T00:00:00.000Z\"}\n";
+ append_cached(&path, appended, AppendOwnership::Unleased).unwrap();
+ let text = std::fs::read_to_string(&path).unwrap();
+ let mut parsed = Vec::new();
+ for (index, line) in text.lines().enumerate() {
+ if serde_json::from_str::<serde_json::Value>(line).is_ok() {
+ parsed.push(index);
+ }
+ }
+ assert_eq!(
+ parsed,
+ vec![0, 2],
+ "the header and the appended row parse on their own lines; the torn row alone stays skipped:\n{text}"
+ );
+}
diff --git a/crates/pa-daemon/src/session_store.rs b/crates/pa-daemon/src/session_store.rs
index f8e1eca445..6c3e0e7ee1 100644
--- a/crates/pa-daemon/src/session_store.rs
+++ b/crates/pa-daemon/src/session_store.rs
@@ -123,6 +123,11 @@ pub struct SessionFile {
pub(crate) leaf_id: Option<String>,
pub(crate) window: Option<SessionWindow>,
pub(crate) lease: Option<std::sync::Arc<crate::lease::SessionLease>>,
+ /// Rows the full reader skipped as unparsable (the TS loader's
+ /// lenient skip): zero on a healthy file. A reopen that found damage
+ /// logs this count (silent skips are how a torn session degraded
+ /// unnoticed — the operator's 2026-10-08 report).
+ pub(crate) skipped_lines: usize,
/// Whether this session has already drawn the Anthropic subscription
/// ban-risk warning (the once-per-session-lifecycle gate, operator
/// directive 2026-09-29): hydrated from the persisted
diff --git a/crates/pa-daemon/src/session_store/read.rs b/crates/pa-daemon/src/session_store/read.rs
index 5e4dad7910..6e2e4032b0 100644
--- a/crates/pa-daemon/src/session_store/read.rs
+++ b/crates/pa-daemon/src/session_store/read.rs
@@ -157,6 +157,7 @@ impl SessionFile {
window: None,
lease: None,
anthropic_warning_shown: false,
+ skipped_lines: 0,
};
for line in lines {
let line = line.with_context(read_context)?;
@@ -164,9 +165,13 @@ impl SessionFile {
if trimmed.is_empty() {
continue;
}
- // Malformed lines are skipped, matching the TS loader.
- if let Ok(entry) = serde_json::from_str::<SessionEntry>(trimmed) {
- file.push_index(entry);
+ // Malformed lines are skipped, matching the TS loader. The
+ // count rides the store so the reopen that found damage can
+ // log it (the rows now STAY on disk: an append-only reopen
+ // never deletes what it skipped).
+ match serde_json::from_str::<SessionEntry>(trimmed) {
+ Ok(entry) => file.push_index(entry),
+ Err(_) => file.skipped_lines += 1,
}
}
fold_child_usage_attributions(&mut file.entries);
@@ -210,6 +215,7 @@ impl SessionFile {
window: None,
lease: None,
anthropic_warning_shown,
+ skipped_lines: 0,
};
// The raw rows are consumed in place: each line String drops as soon as its
// parsed entry joins the store.
@@ -304,6 +310,7 @@ impl SessionFile {
window: None,
lease: None,
anthropic_warning_shown: false,
+ skipped_lines: 0,
}
}
}
diff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rs
index 5a0f531e1c..6649e716e6 100644
--- a/crates/pa-daemon/src/worker/create.rs
+++ b/crates/pa-daemon/src/worker/create.rs
@@ -216,6 +216,19 @@ impl Worker {
match loaded {
Ok(mut opened) => {
opened_existing_session = true;
+ if opened.skipped_lines > 0 {
+ // The rows stay on disk (the append-only
+ // reopen): the skip count is the damage
+ // report the torn-tail repair can act on — a
+ // silent skip is how a torn session degraded
+ // unnoticed (the operator's 2026-10-08
+ // report).
+ eprintln!(
+ "pa-daemon: session {} skipped {} unparsable row(s) on open; they stay on disk",
+ path.display(),
+ opened.skipped_lines
+ );
+ }
// The session-model restore records its decision only for a path
// this worker opened — a failed open never leaks the binding into a
// later create.
@@ -251,17 +264,23 @@ impl Worker {
false,
);
let _ = opened.append_session_state("active");
- let persisted = if opened.window.is_some() {
- opened.persist_appended(append_start)
- } else {
- opened.rewrite()
- };
+ // A reopen is APPEND-ONLY (the operator's 2026-10-08
+ // report: a reopened session showed none of the old
+ // messages): the full reader skips malformed rows in
+ // memory, and the legacy full-file rewrite this
+ // arm carried DELETED them from disk — a gap early
+ // in the parent chain took the whole transcript
+ // with it. Only the rows this open appended
+ // persist; the file keeps every original byte for
+ // the torn-tail repair to see.
+ let persisted = opened.persist_appended(append_start);
if let Err(error) = persisted {
return response_failure(None, "create", &error.to_string(), None);
}
- // Prime the usage fold on the file's final identity (the full-reader
- // fallback's rewrite replaces the inode), off the runtime and before
- // the core lock: summaries under the lock fold only the appended tail.
+ // Prime the usage fold on the file's final identity,
+ // off the runtime and before the core lock:
+ // summaries under the lock fold only the appended
+ // tail.
let primed = path.clone();
let _ = tokio::task::spawn_blocking(move || {
crate::session_store::read_session_info(&primed)
diff --git a/crates/pa-daemon/src/worker/create_collapse_tests.rs b/crates/pa-daemon/src/worker/create_collapse_tests.rs
index 9184eddc6c..e412af30d1 100644
--- a/crates/pa-daemon/src/worker/create_collapse_tests.rs
+++ b/crates/pa-daemon/src/worker/create_collapse_tests.rs
@@ -269,3 +269,73 @@ async fn fresh_create_ignores_a_legacy_crash_orphan() {
let killed = worker.dispatch("kill", &json!({})).await;
assert!(killed.success, "{killed:?}");
}
+
+#[tokio::test]
+async fn a_resume_is_append_only_and_never_deletes_rows() {
+ // The reopen contract (the operator's 2026-10-08 report: reopening an
+ // old session showed none of the old messages): a resumed session is
+ // APPEND-ONLY. The TS-style loader skips a malformed row in memory,
+ // but the file keeps it — a reopen that rewrites the file (the
+ // pre-windowing behavior the full-reader arm still carried) deletes
+ // the row permanently, and a gap early in the parent chain takes the
+ // whole transcript with it: the branch walk stops at the gap.
+ let dir = tempfile::tempdir().unwrap();
+ let session_dir = dir.path().join("sessions");
+ std::fs::create_dir_all(&session_dir).unwrap();
+ let mut store = SessionFile::create("/tmp", None, 0);
+ let path = session_dir.join(session_file_name(store.session_id()));
+ store.set_path(path.clone());
+ store.rewrite().unwrap();
+ let mut last_id = String::new();
+ for text in ["the first turn", "the second turn"] {
+ last_id = store.append_entry(
+ "message",
+ json!({ "message": { "role": "user", "content": text } }),
+ );
+ }
+ store.rewrite().unwrap();
+ // A mid-file unparsable row between two valid rows: the tail stays
+ // healthy, so the torn-tail repair leaves the file alone; only the
+ // loader's row-skip sees it.
+ let mut original = std::fs::read_to_string(&path).unwrap();
+ // The torn row is newline-terminated: a MID-file unparsable row the
+ // loader skips (the tail stays healthy, so the torn-tail repair leaves
+ // the file alone — that repair owns only the trailing row).
+ let torn = "{\"type\":\"message\",\"id\":\"torn-row\",\"parentId\":nu\n";
+ let after_torn = format!(
+ "{{\"type\":\"message\",\"id\":\"after-the-gap\",\"parentId\":\"{last_id}\",\"timestamp\":\"2026-10-08T00:00:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"the row after the gap\"}}}}\n"
+ );
+ original.push_str(torn);
+ original.push_str(&after_torn);
+ std::fs::write(&path, &original).unwrap();
+ let bytes_before = std::fs::read(&path).unwrap();
+
+ let worker = worker_in(dir.path(), "resume-append-only");
+ let response = worker
+ .dispatch(
+ "create",
+ &json!({"cwd": "/tmp", "sessionPath": path.display().to_string()}),
+ )
+ .await;
+ assert!(response.success, "{response:?}");
+ let bytes_after = std::fs::read(&path).unwrap();
+ assert!(
+ bytes_after.starts_with(&bytes_before),
+ "the reopen appends without touching a single original byte\nbefore:\n{bytes_before:?}\nafter:\n{bytes_after:?}"
+ );
+ let text_after = String::from_utf8_lossy(&bytes_after);
+ assert!(
+ text_after.contains(torn),
+ "the unparsable row stays on disk for the repair to see"
+ );
+ assert!(
+ text_after.contains("the row after the gap"),
+ "the row after the gap stays byte-for-byte"
+ );
+ assert!(
+ text_after.contains("the first turn"),
+ "the pre-gap rows stay byte-for-byte"
+ );
+ let killed = worker.dispatch("kill", &json!({})).await;
+ assert!(killed.success, "{killed:?}");
+}
diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rs
index 6f7e1459b8..5d7e3e80ae 100644
--- a/crates/pa-tui/src/agents_view/render.rs
+++ b/crates/pa-tui/src/agents_view/render.rs
@@ -792,6 +792,8 @@ impl Renderer {
) -> Result<Renderer> {
match ui {
AgentsViewUiMode::Terminal => {
+ // Enable Windows VT processing before raw ANSI mode writes.
+ pa_types::platform::console_init();
// The raw-mode bracket's `cfmakeraw` write clears IXON, the kernel's one
// trigger for lifting a pending Ctrl+S stop (see the flow e2e's launch route).
crossterm::terminal::enable_raw_mode()?;
diff --git a/crates/pa-tui/src/agents_view_forest/lineage.rs b/crates/pa-tui/src/agents_view_forest/lineage.rs
index 49f74eafbf..245f437017 100644
--- a/crates/pa-tui/src/agents_view_forest/lineage.rs
+++ b/crates/pa-tui/src/agents_view_forest/lineage.rs
@@ -48,7 +48,7 @@ fn find_parent_index(
if let Some(saved) = &records[index].saved {
if let Some(parent_path) = saved.get("parentSessionPath").and_then(Value::as_str) {
if !parent_path.is_empty() {
- keys.push(format!("file:{parent_path}"));
+ keys.push(crate::agents_view_state::file_identity(parent_path));
}
}
}
diff --git a/crates/pa-tui/src/agents_view_forest/summary.rs b/crates/pa-tui/src/agents_view_forest/summary.rs
index 78b344a31e..a357ee2560 100644
--- a/crates/pa-tui/src/agents_view_forest/summary.rs
+++ b/crates/pa-tui/src/agents_view_forest/summary.rs
@@ -73,7 +73,10 @@ pub fn summary_identity(summary: &Value) -> String {
);
}
if let Some(file) = get("sessionFile") {
- return format!("file:{file}");
+ // The identity converges the two Windows string forms of one
+ // session file (the same normalizer every join key rides - the
+ // reply flow's row lookup must land on Windows too).
+ return crate::agents_view_state::file_identity(file);
}
if let Some(active) = get("activeSessionId") {
return format!("active:{active}");
diff --git a/crates/pa-tui/src/agents_view_forest/tests.rs b/crates/pa-tui/src/agents_view_forest/tests.rs
index 5a9e0be873..adc5ee14c6 100644
--- a/crates/pa-tui/src/agents_view_forest/tests.rs
+++ b/crates/pa-tui/src/agents_view_forest/tests.rs
@@ -1127,3 +1127,68 @@ fn one_dropdown_renders_the_full_fleet_roster() {
);
}
}
+
+/// The daemon publishes one session file in two string forms on Windows
+/// (the operator's 2026-10-08 report: all sessions and their subagents
+/// appeared grouped into one session): live worker summaries and the
+/// saved-catalog scan serve the raw `C:\...` form, while the spawn
+/// ledger's seeded roster rows and passive saved rows serve
+/// `Path::canonicalize`'s verbatim `\\?\C:\...` form. The ledger-derived
+/// row carries NO id-level parent keys, so the `file:` key is its only
+/// link - the forest must nest through the split (the daemon's own
+/// `same_session_file` converges the same two forms; the view's keys must
+/// too).
+#[test]
+fn a_ledger_child_nests_across_the_windows_path_forms() {
+ let raw_parent = r"C:\Users\kevin\.prime\agent\sessions\0f1e2-parent.jsonl";
+ let verbatim_parent = r"\\?\C:\Users\kevin\.prime\agent\sessions\0f1e2-parent.jsonl";
+ let verbatim_child =
+ r"\\?\C:\Users\kevin\.prime\agent\session-artifacts\0f1e2-parent\sub-1\c1.jsonl";
+ let mut parent = parent_summary("0f1e2-parent");
+ parent["sessionFile"] = json!(raw_parent);
+ let mut seeded = child_summary("c1", "0f1e2-parent", "worker one");
+ // The ledger-derived shape: verbatim forms, and the id-level parent
+ // keys absent (the ledger stores only paths).
+ seeded["sessionFile"] = json!(verbatim_child);
+ seeded["parentSessionPath"] = json!(verbatim_parent);
+ seeded["parentActiveSessionId"] = serde_json::Value::Null;
+ seeded["parentSessionId"] = serde_json::Value::Null;
+ seeded["rlmDepth"] = json!(1);
+ let roster = vec![
+ roster_entry("0f1e2-parent", "idle", &parent),
+ roster_entry("seeded-c1", "inactive", &seeded),
+ ];
+ let saved = vec![
+ json!({ "id": "0f1e2-parent", "path": raw_parent }),
+ json!({
+ "id": "c1",
+ "path": verbatim_child,
+ "parentSessionPath": verbatim_parent,
+ "rlmDepth": 1,
+ }),
+ ];
+ let records = reconcile_unified_sessions(&roster, &saved);
+ let rollups = compute_rollups(&records);
+ let rows = build_rows(
+ &records,
+ None,
+ &HashSet::default(),
+ &HashSet::default(),
+ &rollups,
+ None,
+ );
+ // RED on main: the child's `file:\\?\...` parent key never matches the
+ // parent's raw `file:C:\...` alias, so the child degrades to a second
+ // top-level Agent row and the parent renders no subagent line - the
+ // grouping the operator saw.
+ assert_eq!(
+ rows.iter().filter(|row| row.kind == RowKind::Agent).count(),
+ 1,
+ "the ledger child nests under its parent through the split: {rows:?}"
+ );
+ assert!(
+ rows.iter()
+ .any(|row| row.kind == RowKind::SubagentSummary && row.title.starts_with("1 subagent")),
+ "the parent's summary line counts the child: {rows:?}"
+ );
+}
diff --git a/crates/pa-tui/src/agents_view_state.rs b/crates/pa-tui/src/agents_view_state.rs
index 3944ce48e5..6e2dcd416a 100644
--- a/crates/pa-tui/src/agents_view_state.rs
+++ b/crates/pa-tui/src/agents_view_state.rs
@@ -73,10 +73,34 @@ fn get_str<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
.filter(|s| !s.is_empty())
}
-/// The canonical file identity (the saved catalog already serves absolute paths, so lexical
+/// The stable key form of a session-file path. The daemon publishes the
+/// SAME file in two string forms on Windows (the operator's 2026-10-08
+/// grouped-sessions report): live worker summaries and the saved-catalog
+/// scan serve the raw `C:\...` form, while the spawn ledger's seeded
+/// roster rows and passive saved rows serve `Path::canonicalize`'s
+/// verbatim `\\?\C:\...` form - and Windows paths compare
+/// case-insensitively on the filesystem. The join keys must converge the
+/// same two forms the daemon's own `same_session_file` converges, or
+/// ledger-derived children detach and each family re-groups under one
+/// wrong root.
+pub(crate) fn normalize_session_file_path(path: &str) -> String {
+ let trimmed = path
+ .strip_prefix(r"\\?\UNC\")
+ .map(|rest| format!(r"\\{rest}"))
+ .or_else(|| path.strip_prefix(r"\\?\").map(str::to_string))
+ .unwrap_or_else(|| path.to_string());
+ if cfg!(windows) {
+ trimmed.to_lowercase()
+ } else {
+ trimmed
+ }
+}
+
+/// The canonical file identity: the normalized path under the `file:` key
+/// prefix (the saved catalog already serves absolute paths, so lexical
/// normalization is enough; TS canonicalizes).
-fn file_identity(path: &str) -> String {
- format!("file:{path}")
+pub(crate) fn file_identity(path: &str) -> String {
+ format!("file:{}", normalize_session_file_path(path))
}
/// The aliases of one roster entry summary, in TS order.
diff --git a/crates/pa-tui/src/app.rs b/crates/pa-tui/src/app.rs
index 788ebd2b6c..79ebf7833e 100644
--- a/crates/pa-tui/src/app.rs
+++ b/crates/pa-tui/src/app.rs
@@ -78,6 +78,8 @@ fn run_app_surface(
// A panic anywhere between the mount below and the deliberate teardown must still hand
// the terminal back whole (the same unwind-guard contract the session surface arms).
let _surface_restore = crate::exit_restore::SurfaceRestore::armed();
+ // Enable Windows VT processing before raw ANSI mode writes.
+ pa_types::platform::console_init();
// The raw-mode bracket's `cfmakeraw` write clears IXON, the kernel's one trigger for
// lifting a pending Ctrl+S stop (see the flow e2e's launch route).
terminal::enable_raw_mode()?;
diff --git a/crates/pa-tui/src/bin/pa-tui-replay.rs b/crates/pa-tui/src/bin/pa-tui-replay.rs
index 60d37cf6d0..4322681fc7 100644
--- a/crates/pa-tui/src/bin/pa-tui-replay.rs
+++ b/crates/pa-tui/src/bin/pa-tui-replay.rs
@@ -72,6 +72,16 @@ fn newest_session() -> Result<std::path::PathBuf> {
}
fn main() -> Result<()> {
+ // Restore Windows VT on success and early error returns.
+ if let Err(error) = replay() {
+ pa_types::platform::console_restore();
+ return Err(error);
+ }
+ pa_types::platform::console_restore();
+ Ok(())
+}
+
+fn replay() -> Result<()> {
let args = Args::parse();
let path = match &args.session {
Some(p) => std::path::PathBuf::from(p),
diff --git a/crates/pa-tui/src/config_selector.rs b/crates/pa-tui/src/config_selector.rs
index a3fa9b3b0e..a99383349c 100644
--- a/crates/pa-tui/src/config_selector.rs
+++ b/crates/pa-tui/src/config_selector.rs
@@ -562,6 +562,8 @@ fn run_selector_surface(
// A panic anywhere between the mount and the deliberate teardown
// must still hand the terminal back whole.
let _surface_restore = crate::exit_restore::SurfaceRestore::armed();
+ // Enable Windows VT processing before raw ANSI mode writes.
+ pa_types::platform::console_init();
// The raw-mode bracket's `cfmakeraw` write clears IXON, the kernel's
// one trigger for lifting a pending Ctrl+S stop.
terminal::enable_raw_mode()?;
diff --git a/crates/pa-tui/src/exit_restore.rs b/crates/pa-tui/src/exit_restore.rs
index 70b668ecca..6ffca0664d 100644
--- a/crates/pa-tui/src/exit_restore.rs
+++ b/crates/pa-tui/src/exit_restore.rs
@@ -91,6 +91,8 @@ pub(crate) fn restore_terminal() {
let _ = crossterm::terminal::disable_raw_mode();
let _ = report_cooked_repair();
let _ = out.flush();
+ // Restore Windows VT after the final ANSI cleanup writes.
+ pa_types::platform::console_restore();
}
/// The shared exit tail: synchronized output off, SGR reset, cursor
diff --git a/crates/pa-tui/src/interactive/render.rs b/crates/pa-tui/src/interactive/render.rs
index 94b6120b44..b8923286f4 100644
--- a/crates/pa-tui/src/interactive/render.rs
+++ b/crates/pa-tui/src/interactive/render.rs
@@ -168,6 +168,8 @@ impl Renderer {
) -> Result<Renderer> {
match ui {
UiMode::Terminal => {
+ // Enable Windows VT processing before raw ANSI mode writes.
+ pa_types::platform::console_init();
// The raw-mode bracket's own `cfmakeraw` write clears IXON, which is the
// kernel's one trigger for lifting a pending Ctrl+S stop: a tty stopped at the
// shell prompt self-heals here (verified by the flow e2e's launch route).
diff --git a/crates/pa-tui/src/subagents.rs b/crates/pa-tui/src/subagents.rs
index 2332984367..49789aaf58 100644
--- a/crates/pa-tui/src/subagents.rs
+++ b/crates/pa-tui/src/subagents.rs
@@ -41,7 +41,7 @@ impl SessionIdentity {
keys.push(format!("session:{id}"));
}
if let Some(path) = self.session_file.as_deref() {
- keys.push(format!("file:{path}"));
+ keys.push(crate::agents_view_state::file_identity(path));
}
keys
}
@@ -78,7 +78,7 @@ pub(crate) fn summary_parent_keys(summary: &Value) -> Vec<String> {
keys.push(format!("session:{id}"));
}
if let Some(path) = get_str(summary, "parentSessionPath") {
- keys.push(format!("file:{path}"));
+ keys.push(crate::agents_view_state::file_identity(path));
}
keys
}
@@ -93,7 +93,7 @@ pub(crate) fn summary_identity_keys(summary: &Value) -> Vec<String> {
keys.push(format!("session:{id}"));
}
if let Some(path) = get_str(summary, "sessionFile") {
- keys.push(format!("file:{path}"));
+ keys.push(crate::agents_view_state::file_identity(path));
}
keys
}
@@ -147,7 +147,13 @@ pub(crate) fn depth_consistent_binding(
else {
return false;
};
- parent_file == Some(parent_path) && parent_depth == Some(depth - 1)
+ // The binding compares the SAME file's two Windows string forms (the
+ // raw summary form against the ledger's verbatim form), so it folds
+ // through the shared normalizer - an exact compare detaches the
+ // ledger's children exactly where the forest's keys do.
+ let parent_file = parent_file.map(crate::agents_view_state::normalize_session_file_path);
+ let normalized_path = crate::agents_view_state::normalize_session_file_path(parent_path);
+ parent_file.as_deref() == Some(normalized_path.as_str()) && parent_depth == Some(depth - 1)
}
/// Every row whose summary descends from `parent`, breadth-first over the
diff --git a/crates/pa-types/src/platform/mod.rs b/crates/pa-types/src/platform/mod.rs
index 399a8bafb5..2fb6e61323 100644
--- a/crates/pa-types/src/platform/mod.rs
+++ b/crates/pa-types/src/platform/mod.rs
@@ -8,6 +8,7 @@ pub mod identity;
pub mod process;
pub mod terminal;
pub mod transport;
+pub mod windows_console;
#[cfg(windows)]
pub(crate) mod windows_pipe;
@@ -21,3 +22,4 @@ pub use transport::{
bind_transport, connect_blocking, connect_transport, BlockingTransportStream,
TransportListener, TransportStream,
};
+pub use windows_console::{init as console_init, restore as console_restore};
diff --git a/crates/pa-types/src/platform/windows_console.rs b/crates/pa-types/src/platform/windows_console.rs
new file mode 100644
index 0000000000..e288bbe320
--- /dev/null
+++ b/crates/pa-types/src/platform/windows_console.rs
@@ -0,0 +1,194 @@
+//! Enable VT processing before the TUI's raw ANSI mode writes, restoring
+//! only the bit this module added on exit. Redirected stdout is untouched.
+//! Rust std provides console-aware Unicode I/O;
+//! changing console-wide codepages is unnecessary and affects other users
+//! of the attached console. Pipes retain their ordinary byte I/O.
+//! The FFI uses pinned Win32 constants without a windows-sys dependency.
+
+/// The original output mode, used to restore only the VT bit we added.
+#[cfg(windows)]
+#[derive(Clone, Copy)]
+struct OriginalConsole {
+ output_mode: u32,
+}
+
+#[cfg(windows)]
+static ORIGINAL: std::sync::OnceLock<OriginalConsole> = std::sync::OnceLock::new();
+
+/// The kernel32 console surface, as a hand-declared extern wall (repo
+/// policy: pinned constants and externs, no windows-sys dependency -
+/// same policy as the named-pipe transport and the process wall).
+#[cfg(windows)]
+mod winapi {
+ // The Win32 header names stay verbatim: the pinned-constants wall mirrors them.
+ #![allow(non_snake_case)]
+
+ use std::ffi::c_void;
+
+ /// `winbase.h` `STD_OUTPUT_HANDLE`: the console output handle.
+ const STD_OUTPUT_HANDLE: i32 = -11;
+ /// `wincon.h` `ENABLE_VIRTUAL_TERMINAL_PROCESSING`: the console's VT
+ /// parsing bit (0x4).
+ const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
+
+ type Handle = *mut c_void;
+
+ extern "system" {
+ fn GetStdHandle(which: i32) -> Handle;
+ fn GetConsoleMode(handle: Handle, mode: *mut u32) -> i32;
+ fn SetConsoleMode(handle: Handle, mode: u32) -> i32;
+ #[cfg(test)]
+ fn GetConsoleOutputCP() -> u32;
+ #[cfg(test)]
+ fn GetConsoleCP() -> u32;
+ }
+
+ /// The process's console output handle, null when none.
+ pub(crate) fn stdout_handle() -> Handle {
+ unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }
+ }
+
+ /// The output handle's console mode; `None` when the handle is not a
+ /// console (a redirect/pipe) - the console gate.
+ pub(crate) fn output_mode(handle: Handle) -> Option<u32> {
+ let mut mode = 0;
+ let ok = unsafe { GetConsoleMode(handle, std::ptr::from_mut(&mut mode)) };
+ (ok != 0).then_some(mode)
+ }
+
+ pub(crate) fn set_output_mode(handle: Handle, mode: u32) -> bool {
+ unsafe { SetConsoleMode(handle, mode) != 0 }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn output_codepage() -> u32 {
+ unsafe { GetConsoleOutputCP() }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn input_codepage() -> u32 {
+ unsafe { GetConsoleCP() }
+ }
+
+ pub(crate) const fn enable_vt() -> u32 {
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING
+ }
+}
+
+/// Enable VT on attached stdout without changing console codepages.
+/// Idempotent; a no-op for redirected stdout and non-Windows hosts.
+pub fn init() {
+ #[cfg(windows)]
+ {
+ let handle = winapi::stdout_handle();
+ let Some(original_mode) = winapi::output_mode(handle) else {
+ return;
+ };
+ let _ = ORIGINAL.set(OriginalConsole {
+ output_mode: original_mode,
+ });
+ let _ = winapi::set_output_mode(handle, original_mode | winapi::enable_vt());
+ }
+}
+
+/// Restore only the VT bit added by [`init`], preserving other mode bits.
+/// Best-effort; a no-op when no console was prepared.
+pub fn restore() {
+ #[cfg(windows)]
+ {
+ let Some(original) = ORIGINAL.get() else {
+ return;
+ };
+ let handle = winapi::stdout_handle();
+ let Some(current) = winapi::output_mode(handle) else {
+ return;
+ };
+ if current & winapi::enable_vt() != 0 && original.output_mode & winapi::enable_vt() == 0 {
+ // Only the VT bit [`init`] added comes off: raw mode (an
+ // input-handle state) and any other bit the exit funnel's own
+ // restores own stay untouched.
+ let _ = winapi::set_output_mode(handle, current & !winapi::enable_vt());
+ }
+ }
+}
+
+#[cfg(all(test, windows))]
+mod windows_tests {
+ use super::*;
+
+ /// The restore rides a drop guard: a failed assert below must still
+ /// hand the console's session state back (the review rule for tests
+ /// that touch shared state).
+ struct ConsoleRestoreOnPanic;
+ impl Drop for ConsoleRestoreOnPanic {
+ fn drop(&mut self) {
+ restore();
+ }
+ }
+
+ /// Check VT setup/restore and that both console codepages stay intact.
+ /// CI may redirect stdout, in which case init must remain a no-op.
+ #[test]
+ fn init_preserves_codepages_and_restores_vt() {
+ let handle = winapi::stdout_handle();
+ let Some(original_mode) = winapi::output_mode(handle) else {
+ // A redirected (non-console) stdout: the gate keeps the
+ // codepages untouched - a CI `tee` or a piped run must never
+ // flip the host console.
+ let before = (winapi::output_codepage(), winapi::input_codepage());
+ init();
+ assert_eq!(
+ (winapi::output_codepage(), winapi::input_codepage()),
+ before,
+ "a non-console stdout must not be prepared"
+ );
+ return;
+ };
+ let original_output_cp = winapi::output_codepage();
+ let original_input_cp = winapi::input_codepage();
+
+ let _console_restore = ConsoleRestoreOnPanic;
+
+ init();
+ assert_eq!(winapi::output_codepage(), original_output_cp);
+ assert_eq!(winapi::input_codepage(), original_input_cp);
+ let mode = winapi::output_mode(handle).expect("the console mode");
+ assert_ne!(
+ mode & winapi::enable_vt(),
+ 0,
+ "the VT bit rides the output mode: {mode:#x}"
+ );
+
+ restore();
+ assert_eq!(
+ winapi::output_codepage(),
+ original_output_cp,
+ "the output codepage stays unchanged"
+ );
+ assert_eq!(
+ winapi::input_codepage(),
+ original_input_cp,
+ "the input codepage stays unchanged"
+ );
+ let back = winapi::output_mode(handle).expect("the console mode");
+ assert_eq!(
+ back & winapi::enable_vt(),
+ original_mode & winapi::enable_vt(),
+ "the restore hands back the original mode's VT state"
+ );
+ }
+}
+
+#[cfg(all(test, not(windows)))]
+mod portable_tests {
+ use super::*;
+
+ /// The non-Windows contract the call sites rely on: both fns are
+ /// total no-ops (the TUI mount and the exit funnel call them
+ /// unconditionally).
+ #[test]
+ fn the_no_windows_arms_are_no_ops() {
+ init();
+ restore();
+ }
+}