A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
continue turns that a graceful daemon shutdown aborted (#3407)
Sebastian Müllerd8c60343799d
diff --git a/.changes/fix-graceful-shutdown-continuation.md b/.changes/fix-graceful-shutdown-continuation.mdnew file mode 100644index 0000000000..6e781979fc--- /dev/null+++ b/.changes/fix-graceful-shutdown-continuation.md@@ -0,0 +1,2 @@+- A graceful daemon shutdown can continue interrupted turns on restart while explicitly cancelled queued input remains parked.+- A daemon shutdown interrupted mid-stop (a lost shutdown verdict, or a supervisor death inside the stop pass) keeps the session resumable on the next boot instead of archiving it.diff --git a/crates/pa-daemon/src/branch_navigation.rs b/crates/pa-daemon/src/branch_navigation.rsindex fa2c87f545..70bab60f47 100644--- a/crates/pa-daemon/src/branch_navigation.rs+++ b/crates/pa-daemon/src/branch_navigation.rs@@ -495,6 +495,7 @@ impl TreeNavigation {let mut core = self.core.lock().unwrap();if core.busy {core.abort_requested = true;+ core.turn_cancelled = true;// The interrupted turn's aborted row stays off the wire and out of the// store (TS's navigation path never surfaces one).core.suppress_aborted_row = true;diff --git a/crates/pa-daemon/src/compaction.rs b/crates/pa-daemon/src/compaction.rsindex 24f7ffc68f..f17e199e81 100644--- a/crates/pa-daemon/src/compaction.rs+++ b/crates/pa-daemon/src/compaction.rs@@ -155,6 +155,7 @@ impl CompactionManager {let mut core = self.core.lock().unwrap();if core.busy {core.abort_requested = true;+ core.turn_cancelled = true;// TS `compact()` detaches from agent events before the abort, so the// interrupted turn's aborted row never reaches the wire or the session file.core.suppress_aborted_row = true;diff --git a/crates/pa-daemon/src/journal.rs b/crates/pa-daemon/src/journal.rsindex 4423c942e7..ebefebc431 100644--- a/crates/pa-daemon/src/journal.rs+++ b/crates/pa-daemon/src/journal.rs@@ -229,6 +229,12 @@ pub struct WorkerQueueItemRecord {/// restores as "queued" — the only class a fresh snapshot can batch.#[serde(default = "queue_policy_default")]pub policy: String,+ /// The forced-steering batch flag: a restored forced item keeps its+ /// one-turn batch semantics.+ #[serde(default)]+ pub forced_batch: bool,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub images: Vec<pa_agent::types::ImageContent>,}fn queue_visible_default() -> bool {@@ -261,9 +267,18 @@ pub struct WorkerQueueSnapshotRecord {pub active_session_id: String,pub steering: Vec<WorkerQueueItemRecord>,pub follow_up: Vec<WorkerQueueItemRecord>,+ /// The queued-input suspension at snapshot time: a restored parked+ /// queue stays parked until an explicit resume site clears it.+ #[serde(default)]+ pub suspended: bool,pub recorded_at: String,}+/// One session's latest queue snapshot as read back for a restore: the+/// steering and follow-up lanes, and whether queued input was suspended+/// when they were recorded (a parked queue revives still parked).+pub type QueueSnapshotLanes = (Vec<WorkerQueueItemRecord>, Vec<WorkerQueueItemRecord>, bool);+/// Latest busy/operation per active session, plus the latest queue/// snapshot per session.pub struct WorkerRecoveryJournal {@@ -416,6 +431,7 @@ impl WorkerRecoveryJournal {active_session_id: &str,steering: &[WorkerQueueItemRecord],follow_up: &[WorkerQueueItemRecord],+ suspended: bool,) -> Result<()> {let record = WorkerQueueSnapshotRecord {version: QUEUE_SNAPSHOT_VERSION,@@ -423,6 +439,7 @@ impl WorkerRecoveryJournal {active_session_id: active_session_id.to_string(),steering: steering.to_vec(),follow_up: follow_up.to_vec(),+ suspended,recorded_at: crate::util::now_iso(),};append_record(&self.path, &serde_json::to_value(&record)?)?;@@ -449,6 +466,7 @@ impl WorkerRecoveryJournal {operation: &str,steering: &[WorkerQueueItemRecord],follow_up: &[WorkerQueueItemRecord],+ suspended: bool,) -> Result<()> {let snapshot = WorkerQueueSnapshotRecord {version: QUEUE_SNAPSHOT_VERSION,@@ -456,6 +474,7 @@ impl WorkerRecoveryJournal {active_session_id: active_session_id.to_string(),steering: steering.to_vec(),follow_up: follow_up.to_vec(),+ suspended,recorded_at: crate::util::now_iso(),};let verdict_unchanged = self.latest.get(active_session_id).is_some_and(|previous| {@@ -496,13 +515,14 @@ impl WorkerRecoveryJournal {/// The latest persisted queue rows for `active_session_id`.#[must_use]- pub fn latest_queue_snapshot(- &self,- active_session_id: &str,- ) -> Option<(Vec<WorkerQueueItemRecord>, Vec<WorkerQueueItemRecord>)> {- self.queue_snapshots- .get(active_session_id)- .map(|record| (record.steering.clone(), record.follow_up.clone()))+ pub fn latest_queue_snapshot(&self, active_session_id: &str) -> Option<QueueSnapshotLanes> {+ self.queue_snapshots.get(active_session_id).map(|record| {+ (+ record.steering.clone(),+ record.follow_up.clone(),+ record.suspended,+ )+ })}/// Read the latest queue snapshot for a session straight from a journal@@ -515,10 +535,10 @@ impl WorkerRecoveryJournal {pub fn read_queue_snapshot(path: &Path,active_session_id: &str,- ) -> Result<Option<(Vec<WorkerQueueItemRecord>, Vec<WorkerQueueItemRecord>)>> {+ ) -> Result<Option<QueueSnapshotLanes>> {Ok(parse_queue_snapshot_records(path)?.remove(active_session_id)- .map(|record| (record.steering, record.follow_up)))+ .map(|record| (record.steering, record.follow_up, record.suspended)))}fn compact(&self, finalize: Finalize) -> Result<()> {@@ -572,6 +592,10 @@ fn parse_queue_snapshot_records(path: &Path) -> Result<HashMap<String, WorkerQueactive_session_id: active_session_id.to_string(),steering: parse_snapshot_lane(record.get("steering")),follow_up: parse_snapshot_lane(record.get("follow_up")),+ suspended: record+ .get("suspended")+ .and_then(Value::as_bool)+ .unwrap_or(false),recorded_at: record.get("recorded_at").and_then(Value::as_str)@@ -600,6 +624,8 @@ fn parse_snapshot_lane(value: Option<&Value>) -> Vec<WorkerQueueItemRecord> {queue_key: None,queue_visible: true,policy: queue_policy_default(),+ forced_batch: false,+ images: Vec::new(),}),Value::Object(_) => serde_json::from_value(entry.clone()).ok(),_ => None,@@ -685,18 +711,24 @@ mod tests {queue_key: None,queue_visible: true,policy: queue_policy_default(),+ forced_batch: false,+ images: Vec::new(),};sequential- .record_queue_snapshot("s1", std::slice::from_ref(&item), &[])+ .record_queue_snapshot("s1", std::slice::from_ref(&item), &[], false).unwrap();sequential.record("s1", "sess1", Some("/a.jsonl"), true, "prompt_accepted").unwrap();- sequential.record_queue_snapshot("s1", &[], &[]).unwrap();+ sequential+ .record_queue_snapshot("s1", &[], &[], false)+ .unwrap();sequential.record("s1", "sess1", Some("/a.jsonl"), false, "turn_end").unwrap();- sequential.record_queue_snapshot("s1", &[], &[]).unwrap();+ sequential+ .record_queue_snapshot("s1", &[], &[], false)+ .unwrap();sequential.record("s1", "sess1", Some("/a.jsonl"), false, "turn_end").unwrap();@@ -709,13 +741,32 @@ mod tests {"prompt_accepted",std::slice::from_ref(&item),&[],+ false,).unwrap();batched- .record_queue_checkpoint("s1", "sess1", Some("/a.jsonl"), false, "turn_end", &[], &[])+ .record_queue_checkpoint(+ "s1",+ "sess1",+ Some("/a.jsonl"),+ false,+ "turn_end",+ &[],+ &[],+ false,+ ).unwrap();batched- .record_queue_checkpoint("s1", "sess1", Some("/a.jsonl"), false, "turn_end", &[], &[])+ .record_queue_checkpoint(+ "s1",+ "sess1",+ Some("/a.jsonl"),+ false,+ "turn_end",+ &[],+ &[],+ false,+ ).unwrap();let strip_stamps = |path: &std::path::Path| -> Vec<Value> {@@ -744,7 +795,7 @@ mod tests {assert_eq!(latest_a[0].busy, latest_b[0].busy);assert_eq!(latest_a[0].operation, latest_b[0].operation);let restored = WorkerRecoveryJournal::read_queue_snapshot(&batched_path, "s1").unwrap();- assert_eq!(restored, Some((Vec::new(), Vec::new())));+ assert_eq!(restored, Some((Vec::new(), Vec::new(), false)));let _ = fs::remove_dir_all(sequential_path.parent().unwrap());let _ = fs::remove_dir_all(batched_path.parent().unwrap());}@@ -758,8 +809,16 @@ mod tests {// Replace the journal with a directory: every append open now fails.fs::remove_file(&path).unwrap();fs::create_dir(&path).unwrap();- let result =- journal.record_queue_checkpoint("s1", "sess1", None, true, "prompt_accepted", &[], &[]);+ let result = journal.record_queue_checkpoint(+ "s1",+ "sess1",+ None,+ true,+ "prompt_accepted",+ &[],+ &[],+ false,+ );assert!(result.is_err());assert!(journal.latest.get("s1").is_some_and(|record| !record.busy));let _ = fs::remove_dir_all(path.parent().unwrap());@@ -819,6 +878,8 @@ mod tests {queue_key: None,queue_visible: true,policy: queue_policy_default(),+ forced_batch: false,+ images: Vec::new(),};let mut journal = WorkerRecoveryJournal::open(&path).unwrap();journal@@ -830,10 +891,20 @@ mod tests {"prompt_accepted",std::slice::from_ref(&item),&[],+ false,).unwrap();journal- .record_queue_checkpoint("s1", "sess1", Some("/a.jsonl"), false, "turn_end", &[], &[])+ .record_queue_checkpoint(+ "s1",+ "sess1",+ Some("/a.jsonl"),+ false,+ "turn_end",+ &[],+ &[],+ false,+ ).unwrap();let after_first_settle = fs::read_to_string(&path).unwrap().lines().count();journal@@ -845,11 +916,21 @@ mod tests {"prompt_accepted",std::slice::from_ref(&item),&[],+ false,).unwrap();let after_second_admission = fs::read_to_string(&path).unwrap().lines().count();journal- .record_queue_checkpoint("s1", "sess1", Some("/a.jsonl"), false, "turn_end", &[], &[])+ .record_queue_checkpoint(+ "s1",+ "sess1",+ Some("/a.jsonl"),+ false,+ "turn_end",+ &[],+ &[],+ false,+ ).unwrap();let content = fs::read_to_string(&path).unwrap();let lines: Vec<&str> = content.lines().filter(|l| !l.trim().is_empty()).collect();@@ -882,14 +963,23 @@ mod tests {let path = temp_path("unchanged-nocompact.recovery.jsonl");let mut journal = WorkerRecoveryJournal::open(&path).unwrap();journal- .record_queue_checkpoint("s1", "sess1", None, true, "prompt_accepted", &[], &[])+ .record_queue_checkpoint(+ "s1",+ "sess1",+ None,+ true,+ "prompt_accepted",+ &[],+ &[],+ false,+ ).unwrap();journal- .record_queue_checkpoint("s1", "sess1", None, false, "turn_end", &[], &[])+ .record_queue_checkpoint("s1", "sess1", None, false, "turn_end", &[], &[], false).unwrap();let lines_after_settle = fs::read_to_string(&path).unwrap().lines().count();journal- .record_queue_checkpoint("s1", "sess1", None, false, "turn_end", &[], &[])+ .record_queue_checkpoint("s1", "sess1", None, false, "turn_end", &[], &[], false).unwrap();let lines_after_unchanged = fs::read_to_string(&path).unwrap().lines().count();assert_eq!(lines_after_unchanged, lines_after_settle + 1);@@ -916,6 +1006,8 @@ mod tests {queue_key: None,queue_visible: true,policy: queue_policy_default(),+ forced_batch: false,+ images: Vec::new(),};let mut journal = WorkerRecoveryJournal::open(&path).unwrap();journal@@ -927,6 +1019,7 @@ mod tests {"prompt_accepted",std::slice::from_ref(&item),&[],+ /*suspended*/ false,).unwrap();let whole = serde_json::to_string(&WorkerRecoveryRecord {@@ -1007,8 +1100,12 @@ mod tests {queue_key: None,queue_visible: true,policy: queue_policy_default(),+ forced_batch: false,+ images: Vec::new(),};- journal.record_queue_snapshot("s1", &[item], &[]).unwrap();+ journal+ .record_queue_snapshot("s1", &[item], &[], /*suspended*/ false)+ .unwrap();drop(journal);let mut bytes = fs::read(&path).unwrap();let marker = b"safeXinstruction";diff --git a/crates/pa-daemon/src/prompt_admission.rs b/crates/pa-daemon/src/prompt_admission.rsindex 2cfd7909a3..bf24fcb997 100644--- a/crates/pa-daemon/src/prompt_admission.rs+++ b/crates/pa-daemon/src/prompt_admission.rs@@ -588,6 +588,7 @@ impl Worker {&& core.running_admission_ids.contains(admission_id);if abort_running {core.abort_requested = true;+ core.turn_cancelled = true;}(status, dropped_queued, abort_running)};diff --git a/crates/pa-daemon/src/queue_commands.rs b/crates/pa-daemon/src/queue_commands.rsindex 3cae2d3dfd..26197ff0a3 100644--- a/crates/pa-daemon/src/queue_commands.rs+++ b/crates/pa-daemon/src/queue_commands.rs@@ -1,5 +1,5 @@-//! The queue-lane command surface: `mutate_queued_message` and-//! `resume_queue`. Wire contract: `get_queue` and the+//! Queue-lane mutation command: `mutate_queued_message`.+//! Wire contract: `get_queue` and the//! `session_action_update` events expose each lane's message previews,//! and a mutation addresses one preview by `lane` + `index` + `expectedText`.@@ -147,26 +147,6 @@ impl Worker {}response}-- /// `resume_queue`: the queue's queued work resumes (the turn runner- /// drains the lanes when idle); the failure string is TS-verbatim for the empty queue.- pub(crate) fn handle_resume_queue(&self) -> DaemonResponse {- if let Err(response) = self.require_created("resume_queue") {- return response;- }- // The suspension clears first, so `resume_queue` is a resume- // site even when it answers "No queued work to resume".- self.resume_queued_input();- let has_queued_work = {- let core = self.core.lock().unwrap();- !core.steering.is_empty() || !core.follow_up.is_empty()- };- if !has_queued_work {- return response_failure(None, "resume_queue", "No queued work to resume", None);- }- self.work_notify.notify_one();- response_success(None, "resume_queue", None)- }}/// Apply one mutation to a lane; the caller owns the cross-lane move adiff --git a/crates/pa-daemon/src/supervisor/signals_shutdown.rs b/crates/pa-daemon/src/supervisor/signals_shutdown.rsindex d600a40c08..fb7af6698b 100644--- a/crates/pa-daemon/src/supervisor/signals_shutdown.rs+++ b/crates/pa-daemon/src/supervisor/signals_shutdown.rs@@ -32,8 +32,10 @@ impl Supervisor {resident.note_retired();// The stop tombstone persists before the worker is even told (TS// `stopWorkerUntracked`): a supervisor that dies between here and the worker's- // exit leaves durable stop intent, and the next boot finishes the stop.- if self.persist_stop_tombstone(&resident).await.is_err() {+ // exit leaves durable stop intent, and the next boot finishes the stop. The+ // tombstone is the resumable stop variant: a lost step after it keeps the+ // session instead of archiving it.+ if self.persist_stop_tombstone_stop(&resident).await.is_err() {self.log_line(&format!("session worker {} stop tombstone could not persist; leaving the worker untouched (the next boot retries the stop)",resident.worker_id@@ -44,12 +46,12 @@ impl Supervisor {.route_command_typed(&resident,"shutdown",- json!({}),+ json!({ "daemonShutdown": true }),ROUTE_TIMEOUT_MS,RouteAdmission::SupervisorInternal,).await;- self.retire_worker_after_stop(&resident).await;+ self.retire_worker_after_stop(&resident, true).await;}self.registry.clear().await;// The workers are all stopped now, so the accept loop may exit; the gate alonediff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex 1bd9831128..ef18e23a42 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -73,7 +73,7 @@ impl Supervisor {// only with a provably-gone process — the settle is not a death certificate.let settled = self.finalize_worker_stop(resident, None).await;if settled {- if self.retire_worker_after_stop(resident).await {+ if self.retire_worker_after_stop(resident, false).await {self.log_line(&format!("finished the tombstoned stop of session worker {}",resident.worker_id@@ -93,7 +93,7 @@ impl Supervisor {if resident.descriptor.lock().await.owner_client_id.is_some() {self.finalize_owned_stop(resident).await;}- if self.retire_worker_after_stop(resident).await {+ if self.retire_worker_after_stop(resident, false).await {self.log_line(&format!("finished the tombstoned per-session stop of session worker {}",resident.worker_id@@ -785,7 +785,7 @@ impl Supervisor {}// The per-session stop shares the terminal-stop contract: the descriptor dies only// with a provably-gone process — a worker that missed the shutdown stays adoptable.- self.retire_worker_after_stop(resident).await;+ self.retire_worker_after_stop(resident, false).await;// A client-owned (ephemeral) worker's scheduled jobs die with the// registration (TS `cancelEphemeralWorkerScheduledJobs`).let ephemeral = resident.descriptor.lock().await.owner_client_id.is_some();@@ -812,13 +812,15 @@ impl Supervisor {pub(super) async fn retire_worker_after_stop(self: &Arc<Self>,resident: &Arc<ResidentWorker>,+ keep_interrupted_work: bool,) -> bool {- let (pid, start_id, recovery_journal_path) = {+ let (pid, start_id, recovery_journal_path, no_session) = {let descriptor = resident.descriptor.lock().await;(descriptor.pid as u32,descriptor.process_start_id.clone(),descriptor.recovery_journal_path.clone(),+ descriptor.create_command.no_session == Some(true),)};// An unobservable identity never receives the escalation's signals; a live process@@ -847,6 +849,21 @@ impl Supervisor {// run their teardown reap: kill the `bash()` groups they// journaled before the descriptor dies with its files.self.reap_dead_worker_orphans(resident).await;+ if keep_interrupted_work+ && !no_session+ && crate::journal::WorkerRecoveryJournal::read_interrupted(Path::new(+ &recovery_journal_path,+ ))+ {+ // A shutdown-continued worker keeps descriptor and journal so+ // the next boot can adopt the interrupted work. An in-memory+ // noSession worker has no saved conversation to adopt.+ let mut descriptor = resident.descriptor.lock().await;+ descriptor.stop_requested_at = None;+ descriptor.archive_on_stop = None;+ let _ = persist_worker(&resident.descriptor_path, &descriptor);+ return false;+ }// Metadata retirement historically treats failed liveness probes// as gone. Journal deletion needs positive owner-death evidence:// an unobservable process may still be writing durable work.@@ -1174,7 +1191,7 @@ mod tests {let resident =ResidentWorker::new("w-gone".to_string(), descriptor, descriptor_path.clone());- assert!(supervisor.retire_worker_after_stop(&resident).await);+ assert!(supervisor.retire_worker_after_stop(&resident, false).await);assert!(!journal_path.exists(),@@ -1219,17 +1236,17 @@ mod tests {let resident =ResidentWorker::new("w-retire".to_string(), descriptor, descriptor_path.clone());- assert!(!supervisor.retire_worker_after_stop(&resident).await);+ assert!(!supervisor.retire_worker_after_stop(&resident, false).await);assert!(descriptor_path.is_dir());assert!(crate::descriptor::read_identity_pending(&descriptor_path).is_some());std::fs::remove_dir(&descriptor_path).expect("unblock descriptor path");persist_worker(&descriptor_path, &*resident.descriptor.lock().await).expect("descriptor persisted for retry");- assert!(supervisor.retire_worker_after_stop(&resident).await);+ assert!(supervisor.retire_worker_after_stop(&resident, false).await);assert!(!descriptor_path.exists());assert!(crate::descriptor::read_identity_pending(&descriptor_path).is_none());- assert!(supervisor.retire_worker_after_stop(&resident).await);+ assert!(supervisor.retire_worker_after_stop(&resident, false).await);}#[tokio::test]diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 0ee063d342..8d37c8b67b 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -296,6 +296,8 @@ impl Worker {created: false,attached_client_ids: Vec::new(),abort_requested: false,+ turn_cancelled: false,+ turn_completed: false,suppress_aborted_row: false,shutdown_requested: false,last_activity_ms: 0,@@ -847,8 +849,8 @@ impl Worker {/// no destructors, so the caller must have settled the close first).async fn exit_after_close(&self) -> ! {// Shutdown keeps the resume entry and exits the process (TS- // `closeKeepsResumeEntry("shutdown")`).- let _ = self.record_recovery(false, "shutdown");+ // `closeKeepsResumeEntry("shutdown")`); `handle_shutdown` already+ // recorded the recovery verdict.self.close_listener_then_cleanup_socket().await;std::process::exit(0)}@@ -860,7 +862,7 @@ impl Worker {"pa-daemon worker {}: registration refused (the supervisor no longer owns this identity); retiring",std::process::id());- let _ = self.handle_shutdown().await;+ let _ = self.handle_shutdown(&json!({})).await;self.exit_after_close().await;}}diff --git a/crates/pa-daemon/src/worker/agent_message_tests.rs b/crates/pa-daemon/src/worker/agent_message_tests.rsindex e8afdb6943..594afd3fd1 100644--- a/crates/pa-daemon/src/worker/agent_message_tests.rs+++ b/crates/pa-daemon/src/worker/agent_message_tests.rs@@ -503,7 +503,7 @@ async fn assert_clear_queue_bounces(restore_queue: bool) {// above have already completed their synchronous checkpoint writes.drop(worker.recovery.lock().unwrap().take());let journal = WorkerRecoveryJournal::open(&worker.config.recovery_journal_path).unwrap();- let (steering, follow_up) = restore_queue_snapshot(&journal, "target-session");+ let (steering, follow_up, _) = restore_queue_snapshot(&journal, "target-session");assert_eq!(steering.len(), 1, "agent row checkpoint must be durable");assert_eq!(follow_up.len(), 1, "prompt checkpoint must be durable");// The replacement worker owns the reopened sink for clear's checkpoint.diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rsindex 7866c55ab8..681afac90a 100644--- a/crates/pa-daemon/src/worker/commands.rs+++ b/crates/pa-daemon/src/worker/commands.rs@@ -92,7 +92,7 @@ impl Worker {"worker_deliver_message" => self.handle_worker_deliver_message(payload),"update_snapshot" => self.handle_update_snapshot(),"kill" => self.handle_kill(payload).await,- "shutdown" => self.handle_shutdown().await,+ "shutdown" => self.handle_shutdown(payload).await,"rename" => self.handle_rename("rename", payload),"set_session_name" => self.handle_rename("set_session_name", payload),"mark_anthropic_warning_shown" => self.handle_mark_anthropic_warning_shown(),@@ -327,6 +327,7 @@ impl Worker {{let mut core = self.core.lock().unwrap();core.abort_requested = true;+ core.turn_cancelled = true;// The queue parks and a plain prompt is rejected until a// resume site fires.core.queued_input_suspended = true;@@ -685,6 +686,7 @@ impl Worker {}let mut core = self.core.lock().unwrap();core.abort_requested = true;+ core.turn_cancelled = true;// The same TS `requestAbort()` suspension as the bare `abort`.core.queued_input_suspended = true;drop(core);@@ -774,6 +776,7 @@ impl Worker {{let mut core = self.core.lock().unwrap();core.abort_requested = true;+ core.turn_cancelled = true;core.steering.clear();core.follow_up.clear();}diff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rsindex a314558c29..7ae49e2b2d 100644--- a/crates/pa-daemon/src/worker/create.rs+++ b/crates/pa-daemon/src/worker/create.rs@@ -482,11 +482,11 @@ impl Worker {}// Restore the persisted queue snapshot (crash/respawn recovery) from// the worker recovery journal.- let (steering, follow_up) = {+ let (steering, follow_up, restored_suspended) = {let guard = self.recovery.lock().unwrap();match guard.as_ref() {Some(journal) => restore_queue_snapshot(journal, &self.config.active_session_id),- None => (VecDeque::new(), VecDeque::new()),+ None => (VecDeque::new(), VecDeque::new(), false),}};// The session's settings-seeded switches: a restarted session re-seeds@@ -527,6 +527,9 @@ impl Worker {core.cwd = cwd;core.steering = steering;core.follow_up = follow_up;+ // The restored lanes carry their suspension: a user-aborted queue+ // revives still parked, never auto-running its prompts.+ core.queued_input_suspended = restored_suspended;// A resumed session's tool counter re-seeds from its file: a// revived worker keeps the count its roster rows carried.core.tool_use_count = store.tool_call_count();@@ -551,6 +554,8 @@ impl Worker {}core.created = true;core.abort_requested = false;+ core.turn_cancelled = false;+ core.turn_completed = false;// A fresh session starts live: the previous close's// `session_closed` marker clears with the new session.if let Some(agent_engine) = &self.agent_engine {@@ -561,7 +566,10 @@ impl Worker {core.active_service_tier = clamped_tier;core.steering_mode.clone_from(&steering_mode);core.follow_up_mode.clone_from(&follow_up_mode);- core.forced_all_steering = false;+ // The restored rows carry their forced-batch flag: the batch+ // gate rides the lane, so a restored forced batch keeps its+ // one-turn semantics.+ core.forced_all_steering = core.steering.iter().any(|item| item.forced_batch);core.scoped_models.clone_from(&scoped_entries);core.retry_abort_requested = false;// The session's depth falls back to the opened file's header: a resumeddiff --git a/crates/pa-daemon/src/worker/lifecycle.rs b/crates/pa-daemon/src/worker/lifecycle.rsindex 1b59668546..893e76bff7 100644--- a/crates/pa-daemon/src/worker/lifecycle.rs+++ b/crates/pa-daemon/src/worker/lifecycle.rs@@ -11,7 +11,7 @@ impl Worker {/// capture; the queue lanes persist BEFORE replying, so the reported queue/// and the durable respawn state agree (`busy` is the continuation signal).pub(crate) fn handle_update_snapshot(&self) -> DaemonResponse {- let (core_data, lanes) = {+ let (core_data, lanes, suspended) = {let core = self.core.lock().unwrap();let store = core.store.as_ref();let data = json!({@@ -37,12 +37,13 @@ impl Worker {"busy": core.busy,"compacting": core.compacting,});- (data, queue_lanes(&core))+ (data, queue_lanes(&core), core.queued_input_suspended)};// Journal the lanes after releasing the core lock (record paths take// the locks in the opposite order).self.persist_queue_snapshot(core_data["activeSessionId"].as_str().unwrap_or_default(),+ suspended,&lanes,);response_success(None, "update_snapshot", Some(core_data))@@ -61,7 +62,8 @@ impl Worker {/// Graceful stop: the connection loop exits the process after/// replying. The session's telemetry finalizes first.- pub(crate) async fn handle_shutdown(&self) -> DaemonResponse {+ pub(crate) async fn handle_shutdown(&self, payload: &Value) -> DaemonResponse {+ let daemon_wide = payload.get("daemonShutdown").and_then(Value::as_bool) == Some(true);// The session is closing: the continuation mint sites and their// settle-hook retries bail, but unlike a kill the close KEEPS the// resume entry — the scheduled jobs survive for the later wake.@@ -73,15 +75,18 @@ impl Worker {self.side_questions.abort_all_and_settle(SIDE_QUESTION_SETTLE_TIMEOUT).await;- {+ let interrupted_turn = {let mut core = self.core.lock().unwrap();+ // Every explicit cancellation also sets `abort_requested`.+ let interrupted_turn = core.busy && !core.abort_requested && !core.turn_completed;// The shutdown gate closes FIRST: a racing execute_bash must see the// stop before the abort runs — a claim that slipped in after the// abort would register a controller nothing later cancels, and the// exit leaves its child running.core.shutdown_requested = true;core.abort_requested = true;- }+ interrupted_turn+ };// The running user bash goes with the stop: the passivation stop must// never leave the user's process running after the worker exits. Each// run kills its tree in its own task, so the stop waits (bounded) for@@ -97,6 +102,34 @@ impl Worker {self.compaction.abort();self.tree_navigation.abort();self.await_session_work_settled().await;+ // A daemon-wide shutdown that interrupted a running turn queues the+ // continuation prompt so the next boot resumes the turn.+ let continue_turn = daemon_wide && interrupted_turn && {+ let mut core = self.core.lock().unwrap();+ let still_interrupted = !core.turn_cancelled && !core.turn_completed;+ if still_interrupted {+ core.steering.push_front(QueuedItem {+ priority: QueuePriority::Human,+ preview: None,+ message: crate::update_restore::UPDATE_RESTART_CONTINUATION_PROMPT.to_string(),+ custom_message: None,+ agent_message: None,+ queue_key: None,+ admission_id: None,+ images: Vec::new(),+ done: None,+ queue_visible: false,+ policy: TurnPolicy::Direct,+ forced_batch: false,+ });+ }+ still_interrupted+ };+ if continue_turn {+ self.checkpoint_queue(QueueCheckpoint::Admitted {+ operation: "prompt_accepted",+ });+ }// The children close before the exit (an unreachable child must not// block the worker's own exit); their resume entries and scheduled// jobs survive.@@ -117,6 +150,15 @@ impl Worker {// the process exit, and no late report reclaims the pane.let reporter = self.herdr.lock().unwrap().clone();reporter.release().await;+ // The verdict is durable BEFORE the reply: the supervisor may escalate+ // the stop as soon as the reply lands. Parked (suspended) lanes are not+ // busy: they wait for an explicit resume.+ let busy = {+ let core = self.core.lock().unwrap();+ !core.queued_input_suspended+ && (!core.steering.is_empty() || !core.follow_up.is_empty())+ };+ let _ = self.record_recovery(busy, "shutdown");response_success(None, "shutdown", None)}@@ -206,6 +248,7 @@ impl Worker {let busy = core.busy || core.compacting;if busy {core.abort_requested = true;+ core.turn_cancelled = true;}busy};@@ -319,6 +362,64 @@ impl Worker {Ok(())}+ /// `resume_queue`: the queue's queued work resumes (the turn runner+ /// drains the lanes when idle); the failure string is TS-verbatim for the empty queue.+ pub(crate) fn handle_resume_queue(&self) -> DaemonResponse {+ if let Err(response) = self.require_created("resume_queue") {+ return response;+ }+ let queued_at_transition = {+ let mut recovery = self.recovery.lock().unwrap();+ let mut core = self.core.lock().unwrap();+ let has_queued_work = !core.steering.is_empty() || !core.follow_up.is_empty();+ // Persist only the idle parked transition. Active turns have already+ // picked their inputs out of these lanes; rewriting that snapshot+ // could erase their original recovery evidence. An idle compaction+ // picks nothing, so it checkpoints like any idle resume.+ let checkpoint_idle_resume = core.queued_input_suspended && !core.busy;+ if let (true, Some(journal)) = (checkpoint_idle_resume, recovery.as_mut()) {+ let lanes = crate::worker::queue_lanes(&core);+ let store = core.store.as_ref();+ let session_file = store.map(|store| store.path.to_string_lossy().to_string());+ // Keep pickup and cancellation blocked until this transition+ // is durable; failure leaves the live suspension unchanged.+ if let Err(error) = journal.record_queue_checkpoint(+ &core.active_session_id,+ store.map_or("", crate::session_store::SessionFile::session_id),+ session_file.as_deref(),+ has_queued_work,+ "queue_resumed",+ &lanes.steering,+ &lanes.follow_up,+ /*suspended*/ false,+ ) {+ eprintln!("pa-daemon: queue resume checkpoint failed: {error:#}");+ return response_failure(+ None,+ "resume_queue",+ "Could not persist queue resume state",+ None,+ );+ }+ }+ // Busy and already-resumed calls retain legacy behavior+ // without replacing the saved admission snapshot.+ core.queued_input_suspended = false;+ has_queued_work+ };+ // Only effects run after unlock; a concurrent later abort must not have+ // its suspension cleared again here.+ self.wake_queued_input();+ let has_queued_work = queued_at_transition || {+ let core = self.core.lock().unwrap();+ !core.steering.is_empty() || !core.follow_up.is_empty()+ };+ if !has_queued_work {+ return response_failure(None, "resume_queue", "No queued work to resume", None);+ }+ response_success(None, "resume_queue", None)+ }+/// Clear the queued-input suspension and wake the turn runner so parked/// lanes drain; an owed continuation re-evaluates here too.pub(crate) fn resume_queued_input(&self) {@@ -328,6 +429,12 @@ impl Worker {core.queued_input_suspended = false;}}+ self.wake_queued_input();+ }++ /// Wake queued work and re-evaluate owed continuations without changing+ /// the suspension gate.+ pub(crate) fn wake_queued_input(&self) {self.work_notify.notify_one();if let Some(engine) = self.agent_engine.as_ref() {engine.retry_owed_goal_continuation();diff --git a/crates/pa-daemon/src/worker/queue.rs b/crates/pa-daemon/src/worker/queue.rsindex 43343b4684..2520099599 100644--- a/crates/pa-daemon/src/worker/queue.rs+++ b/crates/pa-daemon/src/worker/queue.rs@@ -256,7 +256,7 @@ pub(crate) fn checkpoint_queue_recovery(};// The lanes are read under the recovery lock (a microsecond core hold —// never across the journal's fsyncs): no persist interleaves this read.- let (active_session_id, session_id, session_file, lanes, turn_in_flight) = {+ let (active_session_id, session_id, session_file, lanes, turn_in_flight, suspended) = {let core = core_lock.lock().unwrap();(core.active_session_id.clone(),@@ -269,6 +269,7 @@ pub(crate) fn checkpoint_queue_recovery(.map(|s| s.path.to_string_lossy().to_string()),queue_lanes(&core),core.busy,+ core.queued_input_suspended,)};let (busy, operation) = match checkpoint {@@ -291,6 +292,7 @@ pub(crate) fn checkpoint_queue_recovery(operation,&lanes.steering,&lanes.follow_up,+ suspended,);}@@ -305,6 +307,8 @@ pub(crate) fn queue_lanes(core: &SessionCore) -> QueueLanes {queue_key: item.queue_key.clone(),queue_visible: item.queue_visible,policy: item.policy.journal_value().to_string(),+ forced_batch: item.forced_batch,+ images: item.images.clone(),}).collect()}@@ -325,6 +329,10 @@ pub(crate) fn gather_delivery_batch(core: &mut SessionCore, lane: Lane) -> Vec<Qlet Some(first) = items.front() else {return Vec::new();};+ // Only a real pickup starts a new delivery. Empty or parked lanes retain+ // the prior delivery's cancellation and successful completion facts.+ core.turn_cancelled = false;+ core.turn_completed = false;// The armed set forces "all" only when the front item is armed; an un-armed// front disarms the batch once no armed item remains queued.let forced = lane == Lane::Steering && core.forced_all_steering && first.forced_batch;@@ -365,10 +373,8 @@ pub(crate) fn gather_delivery_batch(core: &mut SessionCore, lane: Lane) -> Vec<Qpub(crate) fn restore_queue_snapshot(journal: &WorkerRecoveryJournal,active_session_id: &str,-) -> (VecDeque<QueuedItem>, VecDeque<QueuedItem>) {+) -> (VecDeque<QueuedItem>, VecDeque<QueuedItem>, bool) {fn pending(lanes: Vec<crate::journal::WorkerQueueItemRecord>) -> VecDeque<QueuedItem> {- // Images on a queued prompt do not survive the restart; the- // delivery rows ride the item record without them.lanes.into_iter().map(|record| {@@ -399,25 +405,22 @@ pub(crate) fn restore_queue_snapshot(agent_message,queue_key: record.queue_key,admission_id: None,- images: Vec::new(),+ images: record.images,done: None,queue_visible: record.queue_visible,policy,- forced_batch: false,+ forced_batch: record.forced_batch,}}).collect()}- let mut steering = VecDeque::new();- let mut follow_up = VecDeque::new();- if let Some((steering_lanes, follow_up_lanes)) =- journal.latest_queue_snapshot(active_session_id)- {- steering = pending(steering_lanes);- follow_up = pending(follow_up_lanes);+ match journal.latest_queue_snapshot(active_session_id) {+ Some((steering, follow_up, suspended)) => {+ (pending(steering), pending(follow_up), suspended)+ }+ None => (VecDeque::new(), VecDeque::new(), false),}- (steering, follow_up)}/// Admit one held autonomous continuation through the follow-up lane:diff --git a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs b/crates/pa-daemon/src/worker/recovery_verdict_tests.rsindex fea7574389..eda36bdd95 100644--- a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs+++ b/crates/pa-daemon/src/worker/recovery_verdict_tests.rs@@ -67,7 +67,7 @@ async fn idle_time_injected_admission_is_busy_evidence() {);let latest = latest_record(&worker);assert_eq!(latest.operation, "follow_up_queued");- let (steering, follow_up) = WorkerRecoveryJournal::read_queue_snapshot(+ let (steering, follow_up, _) = WorkerRecoveryJournal::read_queue_snapshot(&worker.config.recovery_journal_path,"target-session",)@@ -126,7 +126,7 @@ async fn a_bash_completion_notice_admits_the_steering_lane_with_busy_evidence());let latest = latest_record(&worker);assert_eq!(latest.operation, "steer_queued");- let (steering, _) = WorkerRecoveryJournal::read_queue_snapshot(+ let (steering, _, _) = WorkerRecoveryJournal::read_queue_snapshot(&worker.config.recovery_journal_path,"target-session",)@@ -249,7 +249,7 @@ async fn cancelled_admission_drop_settles_the_verdict() {);let latest = latest_record(&worker);assert_eq!(latest.operation, "queue_dropped");- let (steering, follow_up) = WorkerRecoveryJournal::read_queue_snapshot(+ let (steering, follow_up, _) = WorkerRecoveryJournal::read_queue_snapshot(&worker.config.recovery_journal_path,"target-session",)@@ -276,7 +276,7 @@ async fn mid_turn_withdrawal_keeps_the_in_flight_turn_busy() {latest.busy,"the in-flight turn keeps the withdrawal's verdict busy");- let (steering, follow_up) = WorkerRecoveryJournal::read_queue_snapshot(+ let (steering, follow_up, _) = WorkerRecoveryJournal::read_queue_snapshot(&worker.config.recovery_journal_path,"target-session",)diff --git a/crates/pa-daemon/src/worker/session_core.rs b/crates/pa-daemon/src/worker/session_core.rsindex 2147bfae20..d5faabfdba 100644--- a/crates/pa-daemon/src/worker/session_core.rs+++ b/crates/pa-daemon/src/worker/session_core.rs@@ -22,6 +22,10 @@ pub(crate) struct SessionCore {pub(crate) created: bool,pub(crate) attached_client_ids: Vec<String>,pub(crate) abort_requested: bool,+ /// Explicit cancellation of this picked delivery; graceful shutdown is excluded.+ pub(crate) turn_cancelled: bool,+ /// A successful terminal Done was observed for this picked delivery.+ pub(crate) turn_completed: bool,/// A flow that detaches from the interrupted turn's events (a manual/// `compact`, a branch navigation) swallowed the aborted row in TS, so the/// gate's aborted-row exception stays closed while it settles its turn.@@ -123,6 +127,8 @@ impl SessionCore {created: true,attached_client_ids: Vec::new(),abort_requested: false,+ turn_cancelled: false,+ turn_completed: false,suppress_aborted_row: false,shutdown_requested: false,last_activity_ms: 0,diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rsindex 983db81849..13ee1d866f 100644--- a/crates/pa-daemon/src/worker/summary.rs+++ b/crates/pa-daemon/src/worker/summary.rs@@ -142,12 +142,22 @@ impl Worker {/// Persist the queue lanes to the recovery journal. Call after/// releasing the core lock: `record_recovery` takes the locks in/// the opposite order.- pub(crate) fn persist_queue_snapshot(&self, active_session_id: &str, lanes: &QueueLanes) {+ pub(crate) fn persist_queue_snapshot(+ &self,+ active_session_id: &str,+ suspended: bool,+ lanes: &QueueLanes,+ ) {let mut guard = self.recovery.lock().unwrap();let Some(journal) = guard.as_mut() else {return;};- let _ = journal.record_queue_snapshot(active_session_id, &lanes.steering, &lanes.follow_up);+ let _ = journal.record_queue_snapshot(+ active_session_id,+ &lanes.steering,+ &lanes.follow_up,+ suspended,+ );}/// One queue-lane recovery checkpoint: the lane snapshot and thediff --git a/crates/pa-daemon/src/worker/tests/queue_tests.rs b/crates/pa-daemon/src/worker/tests/queue_tests.rsindex e93036ef9f..3b93c95064 100644--- a/crates/pa-daemon/src/worker/tests/queue_tests.rs+++ b/crates/pa-daemon/src/worker/tests/queue_tests.rs@@ -291,11 +291,11 @@ fn legacy_queue_record_priority_defaults_by_row_and_keeps_order() {})).unwrap();journal- .record_queue_snapshot("legacy", &[machine, human, future], &[])+ .record_queue_snapshot("legacy", &[machine, human, future], &[], false).unwrap();drop(journal);let reopened = WorkerRecoveryJournal::open(&path).unwrap();- let (lane, _) = restore_queue_snapshot(&reopened, "legacy");+ let (lane, _, _) = restore_queue_snapshot(&reopened, "legacy");assert_eq!(lane.iter().map(|item| item.message.as_str())@@ -335,6 +335,8 @@ fn queue_snapshot_round_trips_through_the_recovery_journal() {queue_key: Some("heartbeat:hb-1".to_string()),queue_visible: true,policy: "injected".to_string(),+ forced_batch: false,+ images: Vec::new(),};let plain = crate::journal::WorkerQueueItemRecord {message: "follow-me".to_string(),@@ -344,18 +346,21 @@ fn queue_snapshot_round_trips_through_the_recovery_journal() {queue_key: None,queue_visible: true,policy: "queued".to_string(),+ forced_batch: false,+ images: Vec::new(),};journal.record_queue_snapshot("session-a",std::slice::from_ref(&heartbeat),std::slice::from_ref(&plain),+ false,).unwrap();// A reopen (respawned worker) reads the latest snapshot per session.drop(journal);let reloaded = WorkerRecoveryJournal::open(&journal_path).unwrap();- let (steering, follow_up) = restore_queue_snapshot(&reloaded, "session-a");+ let (steering, follow_up, _) = restore_queue_snapshot(&reloaded, "session-a");assert_eq!(steering.len(), 1);assert_eq!(steering[0].message, heartbeat.message);assert_eq!(steering[0].priority, QueuePriority::Background);@@ -375,7 +380,7 @@ fn queue_snapshot_round_trips_through_the_recovery_journal() {.unwrap();drop(compacting);let compacted = WorkerRecoveryJournal::open(&journal_path).unwrap();- let (steering, _) = restore_queue_snapshot(&compacted, "session-a");+ let (steering, _, _) = restore_queue_snapshot(&compacted, "session-a");assert_eq!(steering.len(), 1);assert_eq!(steering[0].custom_message, heartbeat.custom_message);let _ = std::fs::remove_dir_all(&dir);@@ -393,7 +398,7 @@ fn a_version_one_queue_snapshot_restores_as_plain_rows() {).unwrap();let journal = WorkerRecoveryJournal::open(&journal_path).unwrap();- let (steering, follow_up) = restore_queue_snapshot(&journal, "session-b");+ let (steering, follow_up, _) = restore_queue_snapshot(&journal, "session-b");assert_eq!(steering.len(), 1);assert_eq!(steering[0].message, "steer-me");assert_eq!(steering[0].preview, None);diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rsindex adf3629f84..048692f22f 100644--- a/crates/pa-daemon/src/worker/turn.rs+++ b/crates/pa-daemon/src/worker/turn.rs@@ -45,7 +45,7 @@ impl TurnRunner {pub(super) async fn run(self) {loop {let engine = self.engine.clone();- let item: Option<Vec<QueuedItem>> = {+ let item: Option<(Lane, Vec<QueuedItem>)> = {let mut core = self.core.lock().unwrap();if core.shutdown_requested {drop(core);@@ -69,7 +69,7 @@ impl TurnRunner {core.abort_requested = false;core.retry_abort_requested = false;core.running_tool_calls.clear();- Some(items)+ Some((Lane::Steering, items))} else if core.follow_up.front().is_some() {let items = gather_delivery_batch(&mut core, Lane::FollowUp);core.running_admission_ids = items@@ -80,13 +80,13 @@ impl TurnRunner {core.abort_requested = false;core.retry_abort_requested = false;core.running_tool_calls.clear();- Some(items)+ Some((Lane::FollowUp, items))} else {core.busy = false;None}};- if let Some(items) = item {+ if let Some((lane, items)) = item {// No pickup checkpoint: admission recorded its busy evidence; the// settle's `turn_end` verdict parks the session later. The item leaves// the queue projection BEFORE its turn starts (a stale row would@@ -109,7 +109,7 @@ impl TurnRunner {let _ = self.emit_action_update(&snapshot);}self.push_roster_delta();- self.run_turn(engine, items).await;+ self.run_turn(engine, lane, items).await;} else {self.idle_notify.notify_waiters();// Every park re-stamps the activity end: the idle-eviction@@ -312,7 +312,8 @@ impl TurnRunner {pub(super) async fn run_turn(&self,engine: std::sync::Arc<dyn SessionEngine>,- items: Vec<QueuedItem>,+ lane: Lane,+ mut items: Vec<QueuedItem>,) {let Some((first, batched)) = items.split_first() else {return;@@ -390,8 +391,12 @@ impl TurnRunner {.iter().filter_map(|item| item.admission_id.clone()).collect();- let items_done: Vec<oneshot::Sender<TurnSettle>> =- items.into_iter().filter_map(|item| item.done).collect();+ // The done senders leave the items behind (done = None): on+ // shutdown, the batch's unaccepted tail returns to its lane below.+ let items_done: Vec<oneshot::Sender<TurnSettle>> = items+ .iter_mut()+ .filter_map(|item| item.done.take())+ .collect();let turn_outcome = Arc::new(std::sync::Mutex::new(None::<TurnSettle>));let turn_outcome_slot = Arc::clone(&turn_outcome);// Whether the engine surfaced any `agent_end` this run (the@@ -421,11 +426,17 @@ impl TurnRunner {// post-join flag read raced `handle_abort`).let abort_gate_armed = Arc::new(std::sync::atomic::AtomicBool::new(false));let abort_gate_armed_seen = Arc::clone(&abort_gate_armed);+ let batch_len = items.len();+ // The accepted prefix must survive an engine panic after persistence.+ let accepted_prefix = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let accepted_prefix_seen = Arc::clone(&accepted_prefix);let turn = tokio::task::spawn_blocking(move || {// The engine's own terminal `turn_end` frame keeps the// trailing `Done` fallback silent.let mut engine_turn_ended = false;- let mut active_committed = false;+ // The picked batch's accepted rows (primary, then one per+ // batched item) that passed the abort gate and persisted.+ let mut accepted_rows = 0usize;let mut active_running = false;// Restored next-turn rows are PREFIX rows: the "Starting" row// drops at the accepted row. The flip closure reads the flag@@ -664,17 +675,20 @@ impl TurnRunner {// The `committing`/`running` transitions ride the events that mark the moments.let mut action_frame: Option<SessionActionSnapshot> = None;if !emitting_prefix_rows.get()- && !active_committed+ && accepted_rows < batch_len&& matches!(event,EngineEvent::UserMessage(_) | EngineEvent::CustomMessage(_)){- active_committed = true;- if let Some(active) = core.active_action.as_mut() {- active.phase = "committing".to_string();+ accepted_rows += 1;+ accepted_prefix_seen.store(accepted_rows, std::sync::atomic::Ordering::SeqCst);+ if accepted_rows == 1 {+ if let Some(active) = core.active_action.as_mut() {+ active.phase = "committing".to_string();+ }+ action_frame = Some(session_snapshot(&core));}- action_frame = Some(session_snapshot(&core));} else if !active_running&& matches!(event,@@ -689,6 +703,9 @@ impl TurnRunner {}let done_result = match &event {EngineEvent::Done(result) => {+ if result.is_ok() {+ core.turn_completed = true;+ }pa_core::session_engine::compaction_trace::trace("turn.done_emitted",&serde_json::json!({@@ -1047,6 +1064,7 @@ impl TurnRunner {engine.run_prompt(prompt_index, request, &aborted_probe, &mut emit);});let _ = turn.await;+ let accepted_rows = accepted_prefix.load(std::sync::atomic::Ordering::SeqCst);// The emit path is joined: a stale parked partial must not// surface after the settle events.coalescer.close();@@ -1055,6 +1073,18 @@ impl TurnRunner {let engine_reported_run_end = engine_agent_end.load(std::sync::atomic::Ordering::SeqCst);let more_queued = {let mut core = self.core.lock().unwrap();+ // A shutdown never loses admitted input: the batch items whose+ // transcript row never persisted exist nowhere else, so they+ // return to the front of their lane, in order.+ if core.shutdown_requested && !core.turn_cancelled {+ let lane_items = match lane {+ Lane::Steering => &mut core.steering,+ Lane::FollowUp => &mut core.follow_up,+ };+ for item in items.into_iter().skip(accepted_rows).rev() {+ lane_items.push_front(item);+ }+ }let more_queued = !core.steering.is_empty() || !core.follow_up.is_empty();// Publish the note clear and idle transition atomically to// roster readers, which capture core then the engine note.diff --git a/crates/pa-daemon/src/worker/turn_stream_tests.rs b/crates/pa-daemon/src/worker/turn_stream_tests.rsindex 03bea316dd..10fe819de2 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests.rs@@ -29,6 +29,8 @@ fn burst_runner(engine: Arc<dyn SessionEngine>) -> TurnRunner {created: false,attached_client_ids: Vec::new(),abort_requested: false,+ turn_cancelled: false,+ turn_completed: false,suppress_aborted_row: false,shutdown_requested: false,compacting: false,@@ -84,6 +86,7 @@ async fn turn_session_events(engine: Arc<dyn SessionEngine>) -> Vec<Value> {runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,@@ -216,6 +219,7 @@ async fn gate_sighting_events(runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,@@ -293,6 +297,7 @@ async fn a_suppressed_abort_still_ends_the_engine_turn() {runner.run_turn(dynamic,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,@@ -346,6 +351,7 @@ async fn a_turns_tool_executions_count_onto_the_summary() {runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,@@ -462,6 +468,7 @@ async fn model_transitions_reach_the_worker_owned_session_file() {runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,@@ -539,6 +546,7 @@ async fn prompt_restore_boundary_is_supplied_only_for_file_backed_stores() {runner.run_turn(dynamic,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rs b/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rsindex f796e98670..948c54fcfa 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rs@@ -70,6 +70,7 @@ async fn turn_session_events_with_custom_message(runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Background,preview: None,@@ -198,7 +199,7 @@ async fn a_delivered_agent_message_turn_emits_the_custom_row() {Arc::new(ScriptedEngine::from_value(&json!({ "responses": ["ack"] })).unwrap_or_default());let runner = burst_runner(Arc::clone(&engine));let mut subscription = runner.events.subscribe();- runner.run_turn(engine, vec![item]).await;+ runner.run_turn(engine, Lane::Steering, vec![item]).await;let mut events = Vec::new();while let Ok(frame) = subscription.try_recv() {if frame.outbound_type == "session_event" {diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/feed.rs b/crates/pa-daemon/src/worker/turn_stream_tests/feed.rsindex 84842838c3..9944d53931 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/feed.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/feed.rs@@ -15,6 +15,7 @@ async fn the_waiting_prompt_resolves_only_after_the_turn_settles() {runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,@@ -121,6 +122,7 @@ async fn roster_feed_publishes_live_tool_activity() {runner.run_turn(engine,+ Lane::Steering,vec![QueuedItem {priority: QueuePriority::Human,preview: None,diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rsindex 7114efb5e0..889a1a138e 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs@@ -867,6 +867,7 @@ async fn the_async_completion_notice_delivery_keeps_the_live_note() {runner.run_turn(engine.clone(),+ Lane::Steering,vec![queued_prompt("review the installer", TurnPolicy::Queued)],).await;@@ -877,7 +878,11 @@ async fn the_async_completion_notice_delivery_keeps_the_live_note() {);let notice = runner.core.lock().unwrap().steering.pop_front();runner- .run_turn(engine.clone(), vec![notice.expect("the queued notice row")])+ .run_turn(+ engine.clone(),+ Lane::Steering,+ vec![notice.expect("the queued notice row")],+ ).await;assert_eq!(engine.note_at_notice_turn.lock().unwrap().as_deref(),@@ -907,6 +912,7 @@ async fn queued_follow_up_keeps_the_note_until_its_final_end() {runner.run_turn(engine.clone(),+ Lane::Steering,vec![queued_prompt("review", TurnPolicy::Queued)],).await;@@ -915,7 +921,9 @@ async fn queued_follow_up_keeps_the_note_until_its_final_end() {Some("halfway through the review"));let follow_up = runner.core.lock().unwrap().follow_up.pop_front().unwrap();- runner.run_turn(engine.clone(), vec![follow_up]).await;+ runner+ .run_turn(engine.clone(), Lane::FollowUp, vec![follow_up])+ .await;assert_eq!(engine.note_at_notice_turn.lock().unwrap().as_deref(),Some("halfway through the review")@@ -939,6 +947,7 @@ async fn withdrawing_follow_up_after_agent_end_clears_the_note_at_settle() {runner.run_turn(engine.clone(),+ Lane::Steering,vec![queued_prompt("review", TurnPolicy::Queued)],).await;@@ -1108,6 +1117,7 @@ async fn an_aborted_run_clears_the_note_at_its_idle_settle() {runner.run_turn(engine_for_turn,+ Lane::Steering,vec![queued_prompt("review the gate", TurnPolicy::Queued)],).await;@@ -1151,6 +1161,7 @@ async fn an_aborted_run_never_exposes_an_idle_summary_with_its_old_note() {runner.run_turn(engine_for_turn,+ Lane::Steering,vec![queued_prompt("review the gate", TurnPolicy::Queued)],).await;diff --git a/crates/pa-daemon/src/worker/update_snapshot_tests.rs b/crates/pa-daemon/src/worker/update_snapshot_tests.rsindex 4b32ccf4b6..1aec442331 100644--- a/crates/pa-daemon/src/worker/update_snapshot_tests.rs+++ b/crates/pa-daemon/src/worker/update_snapshot_tests.rs@@ -562,6 +562,7 @@ async fn restored_lane_rows_keep_the_child_status_provenance() {let content = "[child-exited: no-reply child:lane]\n\nLast assistant text: done".to_string();worker.persist_queue_snapshot("target-session",+ false,&QueueLanes {steering: vec![crate::journal::WorkerQueueItemRecord {priority: Some(QueuePriority::Background),@@ -571,11 +572,13 @@ async fn restored_lane_rows_keep_the_child_status_provenance() {queue_key: None,queue_visible: true,policy: "queued".to_string(),+ forced_batch: false,+ images: Vec::new(),}],follow_up: Vec::new(),},);- let (steering, follow_up) = {+ let (steering, follow_up, _) = {let recovery = worker.recovery.lock().unwrap();let journal = recovery.as_ref().unwrap();assert_eq!(diff --git a/crates/pa-daemon/tests/rlm_children_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_children_replacement_e2e.rsindex 39e0bfc2f1..4b3ce6c64e 100644--- a/crates/pa-daemon/tests/rlm_children_replacement_e2e.rs+++ b/crates/pa-daemon/tests/rlm_children_replacement_e2e.rs@@ -675,6 +675,25 @@ fn restart_relists_child(delay_ms: u64, display_status: &str) {std::thread::sleep(Duration::from_millis(100));}+ if delay_ms == 0 {+ // The completed display precedes the child's terminal-notice+ // follow-up. Drain that notice and its parent turn before closing+ // the idle fixture; otherwise restart correctly revives owed work.+ client.send_command(+ "completed-child-quiescent",+ &json!({+ "type": "wait_for_idle",+ "activeSessionId": parent_id,+ "waitForRlmQuiescence": true,+ }),+ );+ let quiescent = client.read_response("completed-child-quiescent");+ assert_eq!(+ quiescent["success"], true,+ "completed child and parent notice did not settle: {quiescent}"+ );+ }+client.send_command("bye", &json!({ "type": "shutdown" }));let deadline = Instant::now() + Duration::from_secs(30);while daemondiff --git a/crates/pa-daemon/tests/supervisor_restart_e2e/main.rs b/crates/pa-daemon/tests/supervisor_restart_e2e/main.rsindex d65dc63324..2cad7e8381 100644--- a/crates/pa-daemon/tests/supervisor_restart_e2e/main.rs+++ b/crates/pa-daemon/tests/supervisor_restart_e2e/main.rs@@ -412,4 +412,5 @@ mod boot_cleanup;mod plain_boot;mod restart;mod revival;+mod shutdown_continue;mod update_boot;diff --git a/crates/pa-daemon/tests/supervisor_restart_e2e/shutdown_continue.rs b/crates/pa-daemon/tests/supervisor_restart_e2e/shutdown_continue.rsnew file mode 100644index 0000000000..7720622eff--- /dev/null+++ b/crates/pa-daemon/tests/supervisor_restart_e2e/shutdown_continue.rs@@ -0,0 +1,242 @@+//! Graceful daemon shutdown regressions: an interrupted turn continues after+//! the restart, a lost shutdown verdict never archives the session, and a+//! revived user-parked queue stays parked.+use super::*;++/// The first tool's delay outlasts the shutdown or abort that lands mid-turn.+fn busy_turn() -> Value {+ json!({+ "text": "busy-turn",+ "toolCalls": [+ { "toolCallId": "call-1", "toolName": "bash", "args": {}, "result": "listed", "delayMs": 5_000 },+ { "toolCallId": "call-2", "toolName": "bash", "args": {}, "result": "unfinished" },+ ],+ })+}++/// Boot a supervisor in `dir`, create one scripted session, and prompt it:+/// (daemon, client, session id, session file).+fn boot_with_prompted_session(dir: &Path) -> (Daemon, Client, String, String) {+ let sessions_dir = dir.join("agent").join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ let daemon = spawn_supervisor(&dir.join("daemon.sock"), &dir.join("agent"));+ wait_socket_ready(&dir.join("daemon.sock"));+ let (mut client, _hello) = Client::connect(&dir.join("daemon.sock"));+ let script = dir.join("script.json");+ let responses = json!([busy_turn(), { "text": "next-turn", "delayMs": 10 }]);+ std::fs::write(&script, json!({ "responses": responses }).to_string()).expect("write script");+ let created = call(+ &mut client,+ &json!({+ "type": "create",+ "config": {+ "cwd": dir.to_string_lossy(),+ "sessionDir": sessions_dir.to_string_lossy(),+ "script": script.to_string_lossy(),+ },+ }),+ );+ assert_eq!(created["success"], true, "create failed: {created}");+ let session = created["data"]["id"]+ .as_str()+ .expect("session id")+ .to_string();+ let session_file = created["data"]["sessionFile"]+ .as_str()+ .expect("session file")+ .to_string();+ let prompted = call(+ &mut client,+ &json!({ "type": "prompt", "activeSessionId": session, "message": "go" }),+ );+ assert_eq!(prompted["success"], true, "prompt failed: {prompted}");+ (daemon, client, session, session_file)+}++fn call(client: &mut Client, command: &Value) -> Value {+ client.send_command("cmd", command);+ client.read_response("cmd")+}++fn rows(session_file: &str) -> Vec<Value> {+ std::fs::read_to_string(session_file)+ .unwrap_or_default()+ .lines()+ .filter_map(|line| serde_json::from_str(line).ok())+ .collect()+}++fn message_rows(session_file: &str) -> Vec<Value> {+ rows(session_file)+ .into_iter()+ .filter(|row| row["type"] == "message")+ .collect()+}++fn wait_for(what: &str, mut done: impl FnMut() -> bool) {+ let deadline = Instant::now() + Duration::from_secs(30);+ while !done() {+ assert!(Instant::now() < deadline, "timed out: {what}");+ std::thread::sleep(Duration::from_millis(50));+ }+}++fn wait_for_assistant_row(session_file: &str) {+ wait_for("the turn never started", || {+ rows(session_file)+ .iter()+ .any(|row| row["message"]["role"] == "assistant")+ });+}++fn shut_down(client: &mut Client, daemon: &mut Daemon) {+ let shutdown = call(client, &json!({ "type": "shutdown" }));+ assert_eq!(shutdown["success"], true, "shutdown failed: {shutdown}");+ wait_for("the supervisor never exited", || {+ daemon.child.try_wait().expect("try wait").is_some()+ });+}++#[test]+fn graceful_shutdown_continues_the_aborted_turn_after_restart() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let (mut daemon, mut client, _session, session_file) = boot_with_prompted_session(dir.path());+ // The shutdown lands during call-1, so call-2 never starts and the turn+ // ends aborted, not completed.+ wait_for_assistant_row(&session_file);+ shut_down(&mut client, &mut daemon);++ let mut daemon = spawn_supervisor(&dir.path().join("daemon.sock"), &dir.path().join("agent"));+ wait_socket_ready(&dir.path().join("daemon.sock"));+ // The revived worker runs the continuation prompt: a second user row+ // followed by an assistant reply that was not aborted.+ wait_for("the interrupted turn never continued", || {+ let rows = rows(&session_file);+ let Some(continuation) = rows+ .iter()+ .enumerate()+ .filter(|(_, row)| row["message"]["role"] == "user")+ .nth(1)+ .map(|(at, _)| at)+ else {+ return false;+ };+ rows[continuation + 1..].iter().any(|row| {+ row["message"]["role"] == "assistant" && row["message"]["stopReason"] != "aborted"+ })+ });+ let (mut client, _hello) = Client::connect(&dir.path().join("daemon.sock"));+ shut_down(&mut client, &mut daemon);+}++/// The daemon-wide shutdown persists the resumable stop tombstone, so a+/// boot that finishes the stop after the verdict was lost keeps the session.+#[test]+fn a_lost_shutdown_verdict_never_archives_the_session() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let (socket, agent_dir) = (dir.path().join("daemon.sock"), dir.path().join("agent"));+ let (mut daemon, mut client, session, session_file) = boot_with_prompted_session(dir.path());+ wait_for_busy_journal_evidence(&agent_dir, &socket, &session);++ // SIGSTOP freezes the worker: the routed shutdown is never answered and+ // no verdict is written.+ let worker_pid = child_pids_of(daemon.child.id())[0].to_string();+ let stopped = Command::new("kill")+ .args(["-STOP", worker_pid.as_str()])+ .status();+ assert!(stopped.expect("kill -STOP").success());+ let shutdown = call(&mut client, &json!({ "type": "shutdown" }));+ assert_eq!(shutdown["success"], true, "shutdown failed: {shutdown}");+ let descriptor_path =+ pa_daemon::descriptor::descriptor_dir(&agent_dir, &socket).join(format!("{session}.json"));+ wait_for("the shutdown never persisted its stop tombstone", || {+ std::fs::read_to_string(&descriptor_path)+ .ok()+ .and_then(|content| serde_json::from_str::<Value>(&content).ok())+ .is_some_and(|descriptor| descriptor["stopRequestedAt"].is_string())+ });++ // Both processes die inside the stop pass; the worker's SIGKILL writes+ // no verdict.+ daemon.child.kill().expect("kill supervisor");+ daemon.child.wait().expect("reap supervisor");+ Command::new("kill")+ .args(["-9", worker_pid.as_str()])+ .status()+ .expect("kill -9 the worker");++ // The next boot finishes the tombstoned stop (the descriptor goes away).+ let mut daemon = spawn_supervisor(&socket, &agent_dir);+ wait_socket_ready(&socket);+ wait_for("the tombstoned stop never finished", || {+ !descriptor_path.exists()+ });+ let archived = rows(&session_file)+ .iter()+ .any(|row| row["type"] == "session_state" && row["state"]["status"] == "archived");+ assert!(!archived, "a lost shutdown verdict archived the session");+ let (mut client, _hello) = Client::connect(&socket);+ shut_down(&mut client, &mut daemon);+}++/// A crash after a user abort revives the session from the abort-settle+/// journal row; its restored queue keeps the suspension instead of running+/// the parked prompt.+#[test]+fn a_revived_user_parked_queue_stays_parked() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let (socket, agent_dir) = (dir.path().join("daemon.sock"), dir.path().join("agent"));+ let (mut daemon, mut client, session, session_file) = boot_with_prompted_session(dir.path());+ wait_for_assistant_row(&session_file);+ let queued = call(+ &mut client,+ &json!({ "type": "follow_up", "activeSessionId": session, "message": "remain parked" }),+ );+ assert_eq!(queued["success"], true, "follow_up failed: {queued}");+ let aborted = call(+ &mut client,+ &json!({ "type": "abort", "activeSessionId": session }),+ );+ assert_eq!(aborted["success"], true, "abort failed: {aborted}");+ let get_state = json!({ "type": "get_state", "activeSessionId": session });+ wait_for("the aborted turn never settled", || {+ call(&mut client, &get_state)["data"]["isStreaming"] == false+ });+ let parked_rows = message_rows(&session_file);++ // kill -9 the supervisor first (a live one would settle the journal on+ // the worker's death), then the worker: the abort-settle row remains.+ let worker_pid = child_pids_of(daemon.child.id())[0].to_string();+ daemon.child.kill().expect("kill supervisor");+ daemon.child.wait().expect("reap supervisor");+ Command::new("kill")+ .args(["-9", worker_pid.as_str()])+ .status()+ .expect("kill -9 the worker");++ let restart_before = pa_daemon::util::now_iso();+ let mut daemon = spawn_supervisor(&socket, &agent_dir);+ wait_socket_ready(&socket);+ let log_path = pa_daemon::paths::daemon_log_path(&socket, &agent_dir);+ wait_for("the parked session was not revived", || {+ distinct(workers_registered_since(&log_path, &restart_before)) == vec![session.clone()]+ });+ let (mut client, _hello) = Client::connect(&socket);+ let queue = call(+ &mut client,+ &json!({ "type": "get_queue", "activeSessionId": session }),+ );+ assert_eq!(+ queue["data"]["followUp"],+ json!(["remain parked"]),+ "{queue}"+ );+ let state = call(&mut client, &get_state);+ assert_eq!(state["data"]["isStreaming"], false, "{state}");+ assert_eq!(+ message_rows(&session_file),+ parked_rows,+ "the revived worker ran the parked input without a resume"+ );+ shut_down(&mut client, &mut daemon);+}