A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
factory: deliver run milestone notices to the owning session; count paused runs apart in the TUI (#3713)
Sebastian Müller0487afe9da94
diff --git a/crates/pa-core/src/session_engine/bash_notices.rs b/crates/pa-core/src/session_engine/bash_notices.rsindex 94643383d3..1426785e0f 100644--- a/crates/pa-core/src/session_engine/bash_notices.rs+++ b/crates/pa-core/src/session_engine/bash_notices.rs@@ -1,8 +1,10 @@-//! The detached kernel bash completion notice (the TS async-bash-completion-//! wake: `bash.completed`/`bash.consumed`): the shared notice types, the-//! TS payload validation, and the host-handler registration, plus the-//! in-process sinks a daemonless embedding uses — the completion row-//! steers onto the session's own agent and the embedding's wake fires.+//! The kernel notice seam (the TS async-bash-completion wake): the+//! `bash.completed`/`bash.consumed` notices plus the `factory.progress`+//! run-milestone notice that rides the same steering delivery. Here live+//! the shared notice types, the TS payload validation, and the+//! host-handler registration, plus the in-process sinks a daemonless+//! embedding uses — the notice row steers onto the session's own agent+//! and the embedding's wake fires.use std::sync::{Arc, Mutex, Weak};@@ -10,23 +12,46 @@ use serde_json::Value;use crate::kernel::shared::{host_handler, HostRequestHandlers, BASH_COMPLETED_REQUEST_TYPE};use pa_agent::types::AgentMessage;+use pa_types::session::CustomMessage;-use super::messages::{self, ASYNC_BASH_COMPLETION_CUSTOM_TYPE};+use super::messages::{+ self, ASYNC_BASH_COMPLETION_CUSTOM_TYPE, ASYNC_BASH_COMPLETION_PREVIEW_LABEL,+ FACTORY_PROGRESS_PREVIEW_LABEL,+};use super::{session_message_to_loop, SessionAgentMessage};-/// One detached kernel bash completion (the `bash.completed` host-/// request): the finished command's identity and exit code.+/// One kernel notice the host admits as a steering row (TS+/// `_promptInjectedMessage` with `streamingBehavior: "steer"`,+/// `queueIfBusy`, and `resumeIfIdle`): a detached bash completion+/// (`bash.completed`) or a factory run milestone (`factory.progress`).#[derive(Debug, Clone)]-pub struct BashCompletionNotice {- pub pid: u32,- pub command: String,- pub exit_code: i64,+pub struct KernelNotice {+ /// The durable custom row the woken or steered turn carries.+ pub row: CustomMessage,+ /// The queue strip's label for the row's preview.+ pub preview_label: &'static str,+}++impl KernelNotice {+ /// The `[bash-done]` notice for one finished detached command.+ #[must_use]+ pub fn bash_completion(pid: u32, command: &str, exit_code: i64) -> Self {+ Self {+ row: messages::create_async_bash_completion_message(+ pid,+ command,+ exit_code,+ crate::autonomous::now_millis(),+ ),+ preview_label: ASYNC_BASH_COMPLETION_PREVIEW_LABEL,+ }+ }}-/// The queue-admission seam for one completion notice (the daemon-/// worker's steering lane + runner wake + recovery busy-evidence; the-/// in-process sinks below steer onto the session's own agent).-pub type BashCompletionSink = Arc<dyn Fn(BashCompletionNotice) + Send + Sync>;+/// The queue-admission seam for one kernel notice (the daemon worker's+/// steering lane + runner wake + recovery busy-evidence; the in-process+/// sinks below steer onto the session's own agent).+pub type KernelNoticeSink = Arc<dyn Fn(KernelNotice) + Send + Sync>;/// The kernel read a finished command's result before its notice/// delivered (the `bash.consumed` host request): the queued notice is stale.@@ -43,13 +68,15 @@ pub type BashConsumedSink = Arc<dyn Fn(BashConsumedNotice) + Send + Sync>;/// notice admits its row, so the embedding resumes the idle run.pub type BashNoticeWake = Arc<dyn Fn() + Send + Sync>;-/// The `bash.completed`/`bash.consumed` kernel host handlers (TS-/// `createAsyncBashCompletionHostHandler`/`createAsyncBashConsumedHostHandler`).-pub fn register_bash_notice_host_handlers(- completion: BashCompletionSink,+/// The `bash.completed`/`bash.consumed`/`factory.progress` kernel host+/// handlers (TS `createAsyncBashCompletionHostHandler`,+/// `createAsyncBashConsumedHostHandler`, `createFactoryProgressHostHandler`).+pub fn register_kernel_notice_host_handlers(+ notice: KernelNoticeSink,consumed: BashConsumedSink,handlers: &mut HostRequestHandlers,) {+ let completion = Arc::clone(¬ice);handlers.register(BASH_COMPLETED_REQUEST_TYPE,host_handler(move |payload| {@@ -75,21 +102,31 @@ pub fn register_bash_notice_host_handlers(})}),);+ handlers.register(+ "factory.progress",+ host_handler(move |payload| {+ let notice = notice.clone();+ Box::pin(async move {+ notice(validate_factory_progress(&payload.data)?);+ Ok(serde_json::json!({}))+ })+ }),+ );}/// TS `createAsyncBashCompletionHostHandler` validation: a positive/// integer pid, a non-empty string command, an integer exit code.-fn validate_completion(data: &Value) -> anyhow::Result<BashCompletionNotice> {+fn validate_completion(data: &Value) -> anyhow::Result<KernelNotice> {let consumed = validate_consumed(data)?;let exit_code = data.get("exitCode").and_then(Value::as_i64).ok_or_else(|| anyhow::anyhow!("bash.completed exitCode must be an integer"))?;- Ok(BashCompletionNotice {- pid: consumed.pid,- command: consumed.command,+ Ok(KernelNotice::bash_completion(+ consumed.pid,+ &consumed.command,exit_code,- })+ ))}/// TS `createAsyncBashConsumedHostHandler` validation: a positive integer pid and a@@ -110,6 +147,33 @@ fn validate_consumed(data: &Value) -> anyhow::Result<BashConsumedNotice> {Ok(BashConsumedNotice { pid, command })}+/// The kernel factory executor's milestone payload (`FactoryExecutor._milestone`+/// in `rlm/factory.py`): non-empty `run_id`, `kind`, and `detail` strings, and+/// an optional non-empty `node` string.+fn validate_factory_progress(data: &Value) -> anyhow::Result<KernelNotice> {+ let text = |key: &str| {+ data.get(key)+ .and_then(Value::as_str)+ .filter(|text| !text.is_empty())+ .ok_or_else(|| anyhow::anyhow!("factory.progress {key} must be a non-empty string"))+ };+ let node = data+ .get("node")+ .is_some()+ .then(|| text("node"))+ .transpose()?;+ Ok(KernelNotice {+ row: messages::create_factory_progress_message(+ text("run_id")?,+ text("kind")?,+ node,+ text("detail")?,+ crate::autonomous::now_millis(),+ ),+ preview_label: FACTORY_PROGRESS_PREVIEW_LABEL,+ })+}+/// The session's agent through which the in-process sinks steer and/// withdraw: late-bound because the handlers register before the agent/// exists, and weak so the handler -> agent -> kernel -> handler graph@@ -117,33 +181,27 @@ fn validate_consumed(data: &Value) -> anyhow::Result<BashConsumedNotice> {pub type BashNoticeAgentSlot = Arc<Mutex<Option<Weak<pa_agent::agent::Agent>>>>;/// The in-process sinks over one session's own agent (the daemonless-/// embeddings): a completion steers the `[bash-done]` row onto the-/// agent's steering queue and fires the embedding's wake (TS-/// `queueIfBusy: true` + `resumeIfIdle: true` — the row rides the-/// steering lane and the embedding resumes the idle run); a consumed-/// notice withdraws the queued row.-pub fn register_in_process_bash_notice_handlers(+/// embeddings): a notice steers its row (`[bash-done]` or+/// `[factory-progress]`) onto the agent's steering queue and fires the+/// embedding's wake (TS `queueIfBusy: true` + `resumeIfIdle: true` — the+/// row rides the steering lane and the embedding resumes the idle run); a+/// consumed notice withdraws the queued completion row.+pub fn register_in_process_kernel_notice_handlers(wake: &BashNoticeWake,agent_slot: &BashNoticeAgentSlot,handlers: &mut HostRequestHandlers,) {- let completion_wake = Arc::clone(wake);- let completion_slot = Arc::clone(agent_slot);- let completion: BashCompletionSink = Arc::new(move |notice| {- let Some(agent) = bound_agent(&completion_slot) else {+ let notice_wake = Arc::clone(wake);+ let notice_slot = Arc::clone(agent_slot);+ let notice: KernelNoticeSink = Arc::new(move |notice| {+ let Some(agent) = bound_agent(¬ice_slot) else {return;};- let row = messages::create_async_bash_completion_message(- notice.pid,- ¬ice.command,- notice.exit_code,- crate::autonomous::now_millis(),- );- let Some(row) = session_message_to_loop(&SessionAgentMessage::Custom(row)) else {+ let Some(row) = session_message_to_loop(&SessionAgentMessage::Custom(notice.row)) else {return;};agent.steer(row);- completion_wake();+ notice_wake();});let consumed_slot = Arc::clone(agent_slot);let consumed: BashConsumedSink = Arc::new(move |notice| {@@ -161,7 +219,7 @@ pub fn register_in_process_bash_notice_handlers(}});});- register_bash_notice_host_handlers(completion, consumed, handlers);+ register_kernel_notice_host_handlers(notice, consumed, handlers);}/// The bound agent behind the late slot, when the session still lives.@@ -229,7 +287,7 @@ mod tests {}) as BashNoticeWake};let mut handlers = HostRequestHandlers::default();- register_in_process_bash_notice_handlers(&wake, &slot, &mut handlers);+ register_in_process_kernel_notice_handlers(&wake, &slot, &mut handlers);(agent, slot, wakes, handlers)}@@ -325,6 +383,55 @@ mod tests {);}+ #[tokio::test]+ async fn factory_progress_queues_the_milestone_row_and_fires_the_wake() {+ let (agent, _slot, wakes, handlers) = wired_agent();+ let handler = handlers+ .get("factory.progress")+ .expect("the factory progress handler registered")+ .clone();+ let missing_run = serde_json::json!({ "kind": "paused", "detail": "state a failed" });+ assert!(+ dispatch(&handler, missing_run).await.is_err(),+ "a milestone without a run id is refused"+ );+ let milestone = serde_json::json!({+ "run_id": "run-7",+ "kind": "budget_exceeded",+ "detail": "run budget_ms 2000 exceeded",+ });+ dispatch(&handler, milestone)+ .await+ .expect("the milestone is accepted");+ assert_eq!(+ wakes.load(Ordering::SeqCst),+ 1,+ "the admission fired the wake"+ );+ let queued = agent.remove_queued_messages(|_| true);+ let [AgentMessage::Custom(custom)] = queued.as_slice() else {+ panic!("one custom notice row queued: {queued:?}");+ };+ assert_eq!(+ (+ custom.payload.get("customType"),+ custom.payload.get("content"),+ custom.payload.get("details"),+ ),+ (+ Some(&serde_json::json!("factory_progress_notice")),+ Some(&serde_json::json!(+ "[factory-progress run:run-7] budget-exceeded: run budget_ms 2000 exceeded"+ )),+ Some(&serde_json::json!({+ "runId": "run-7",+ "kind": "budget_exceeded",+ "detail": "run budget_ms 2000 exceeded",+ })),+ )+ );+ }+#[test]fn completion_validation_matches_the_ts_contract() {assert!(validate_completion(&completed_payload(4321, "sleep 1", 0)).is_ok());diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex a4d3f9f600..684ba6e286 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -84,10 +84,10 @@ pub struct SessionEngineConfig {/// Fires when the kernel's last live background `bash()` handle/// settles; `None` installs nothing.pub on_background_work_settled: Option<crate::kernel::shared::BackgroundWorkSettledCallback>,- /// The daemonless bash-completion wake (TS `resumeIfIdle`): with it- /// the engine registers the `bash.completed`/`bash.consumed`- /// handlers whose in-process sinks steer the `[bash-done]` row onto- /// the session's agent and fire the wake. `None` installs nothing —+ /// The daemonless kernel-notice wake (TS `resumeIfIdle`): with it+ /// the engine registers the `bash.completed`/`bash.consumed`/+ /// `factory.progress` handlers whose in-process sinks steer the notice+ /// row onto the session's agent and fire the wake. `None` installs nothing —/// the daemon keeps its worker-lane sinks via the extra handlers.pub bash_notice_wake: Option<super::bash_notices::BashNoticeWake>,/// An externally owned MCP manager: the engine adopts it instead of@@ -452,7 +452,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S// exists (the slot binds below).let bash_notice_agent = super::bash_notices::BashNoticeAgentSlot::default();if let Some(wake) = config.bash_notice_wake.clone() {- super::bash_notices::register_in_process_bash_notice_handlers(+ super::bash_notices::register_in_process_kernel_notice_handlers(&wake,&bash_notice_agent,&mut handlers,diff --git a/crates/pa-core/src/session_engine/messages.rs b/crates/pa-core/src/session_engine/messages.rsindex 78b647c052..197759cb9b 100644--- a/crates/pa-core/src/session_engine/messages.rs+++ b/crates/pa-core/src/session_engine/messages.rs@@ -42,6 +42,11 @@ pub const SESSION_RENAMED_CUSTOM_TYPE: &str = "session_renamed";/// notice's queued row carries (the TUI renders it with its own label,/// no lane prefix).pub const ASYNC_BASH_COMPLETION_PREVIEW_LABEL: &str = "Background command finished";+/// The durable row a factory run milestone (`factory.progress`) admits on+/// the owning session's steering lane.+pub const FACTORY_PROGRESS_NOTICE_CUSTOM_TYPE: &str = "factory_progress_notice";+/// The queue-strip label the factory progress notice's queued row carries.+pub const FACTORY_PROGRESS_PREVIEW_LABEL: &str = "Factory progress";/// The queue-strip preview label for a parked heartbeat fire; the queued row reads/// `Heartbeat prompt: <content>` instead of the lane-labeled preview.pub const HEARTBEAT_PROMPT_PREVIEW_LABEL: &str = "Heartbeat prompt";@@ -232,6 +237,35 @@ pub fn create_async_bash_completion_message(}}+/// The factory run milestone notice: `[factory-progress run:<id>] <kind>: <detail>`,+/// the kernel's `snake_case` kind rendered with hyphens (`budget_exceeded` reads+/// `budget-exceeded`). The details keep the kernel's raw values.+#[must_use]+pub fn create_factory_progress_message(+ run_id: &str,+ kind: &str,+ node: Option<&str>,+ detail: &str,+ timestamp: u64,+) -> pa_types::session::CustomMessage {+ let header_run = sanitize_message_header_value(run_id);+ let header_kind = sanitize_message_header_value(&kind.replace('_', "-"));+ let mut details = serde_json::json!({ "runId": run_id, "kind": kind, "detail": detail });+ if let Some(node) = node {+ details["node"] = serde_json::json!(node);+ }+ pa_types::session::CustomMessage {+ custom_type: FACTORY_PROGRESS_NOTICE_CUSTOM_TYPE.to_string(),+ content: UserContent::Text(format!(+ "[factory-progress run:{header_run}] {header_kind}: {detail}"+ )),+ display: true,+ details: Some(details),+ timestamp,+ rest: serde_json::Map::default(),+ }+}+/// Bash output rendered as a fenced block with a fence longer than any/// backtick run inside the output.fn bash_output_to_text(diff --git a/crates/pa-core/tests/prompt_guards.rs b/crates/pa-core/tests/prompt_guards.rsindex 79dd571269..c19d8d972a 100644--- a/crates/pa-core/tests/prompt_guards.rs+++ b/crates/pa-core/tests/prompt_guards.rs@@ -152,6 +152,8 @@ const INTERNAL_HOST_REQUESTS: &[&str] = &[// fires them; the model never calls them)."bash.completed","bash.consumed",+ // The factory module reports run milestones; the model never calls it.+ "factory.progress",];/// Map one registered host-request type to the prompt token that documentsdiff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex efab15e28a..aaead45632 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -145,10 +145,10 @@ pub struct AgentSessionEngine {/// The stale-row guard's DURABLE terminal row, deferred until after the/// context adoption; `Some` between the seed and the flush.pub(crate) stale_goal_terminal_pending: std::sync::Mutex<Option<pa_core::goals::GoalState>>,- /// The bash-completion queue seams: `bash.completed` admits through the- /// steering lane, `bash.consumed` withdraws its row. `None` outside a- /// daemon worker.- pub(crate) bash_completion_sink: std::sync::Mutex<Option<crate::engine::BashCompletionSink>>,+ /// The kernel-notice queue seams: `bash.completed` and `factory.progress`+ /// admit through the steering lane, `bash.consumed` withdraws a completion+ /// row. `None` outside a daemon worker.+ pub(crate) kernel_notice_sink: std::sync::Mutex<Option<crate::engine::KernelNoticeSink>>,pub(crate) bash_consumed_sink: std::sync::Mutex<Option<crate::engine::BashConsumedSink>>,/// The live agent handle: the eager turn-abort funnel's target, mirrored/// because a running turn holds the core session's mutex.diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex b2c54da62e..9cfef0d8f5 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -138,7 +138,7 @@ impl AgentSessionEngine {goal_budget_crossed: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),goal_input_probe: std::sync::Mutex::new(None),goal_admission_sink: std::sync::Mutex::new(None),- bash_completion_sink: std::sync::Mutex::new(None),+ kernel_notice_sink: std::sync::Mutex::new(None),bash_consumed_sink: std::sync::Mutex::new(None),goal_queue_purge: std::sync::Mutex::new(None),goal_backoff_wake_job_id: std::sync::Mutex::new(None),@@ -950,7 +950,7 @@ impl AgentSessionEngine {let mut handlers = HostRequestHandlers::default();register_agent_message_host_handlers(sender, &mut handlers);register_agent_observe_host_handlers(observer, &mut handlers);- self.register_bash_notice_host_handlers(&mut handlers);+ self.register_kernel_notice_host_handlers(&mut handlers);Some(handlers)}diff --git a/crates/pa-daemon/src/bash_notices.rs b/crates/pa-daemon/src/bash_notices.rsindex fd9659b5c6..8163ca5f4c 100644--- a/crates/pa-daemon/src/bash_notices.rs+++ b/crates/pa-daemon/src/bash_notices.rs@@ -1,44 +1,43 @@-//! The daemon worker's bash-notice seams: the notice types, the TS-//! validation, and the handler registration live in pa-core-//! (`session_engine::bash_notices`); the worker keeps its queue-lane-//! sinks here.+//! The daemon worker's kernel-notice seams (bash completions and factory+//! progress): the notice types, the validation, and the handler+//! registration live in pa-core (`session_engine::bash_notices`); the+//! worker keeps its queue-lane sinks here.use pa_core::kernel::shared::HostRequestHandlers;use crate::agent_engine::AgentSessionEngine;impl AgentSessionEngine {- /// Wire the worker's bash-completion queue seams (called once at+ /// Wire the worker's kernel-notice queue seams (called once at/// construction, before the first session build reads them).////// # Panics////// Panics when a sink mutex is poisoned (a holder panicked while- /// holding the completion or consumed-sink lock).- pub fn set_bash_notice_sinks(+ /// holding the notice or consumed-sink lock).+ pub fn set_kernel_notice_sinks(&self,- completion: crate::engine::BashCompletionSink,+ notice: crate::engine::KernelNoticeSink,consumed: crate::engine::BashConsumedSink,) {*self- .bash_completion_sink+ .kernel_notice_sink.lock()- .expect("bash completion sink lock") = Some(completion);+ .expect("kernel notice sink lock") = Some(notice);*self.bash_consumed_sink.lock().expect("bash consumed sink lock") = Some(consumed);}- /// The `bash.completed`/`bash.consumed` kernel host handlers (TS- /// `createAsyncBashCompletionHostHandler`/`createAsyncBashConsumedHostHandler`).- /// Registered only when both seams are wired — no worker queue leaves the requests- /// honestly unavailable.- pub(crate) fn register_bash_notice_host_handlers(&self, handlers: &mut HostRequestHandlers) {- let Some(completion) = self- .bash_completion_sink+ /// The `bash.completed`/`bash.consumed`/`factory.progress` kernel host+ /// handlers. Registered only when both seams are wired — no worker queue+ /// leaves the requests honestly unavailable.+ pub(crate) fn register_kernel_notice_host_handlers(&self, handlers: &mut HostRequestHandlers) {+ let Some(notice) = self+ .kernel_notice_sink.lock()- .expect("bash completion sink lock")+ .expect("kernel notice sink lock").clone()else {return;@@ -51,8 +50,8 @@ impl AgentSessionEngine {else {return;};- pa_core::session_engine::bash_notices::register_bash_notice_host_handlers(- completion, consumed, handlers,+ pa_core::session_engine::bash_notices::register_kernel_notice_host_handlers(+ notice, consumed, handlers,);}}diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rsindex 00b6acab32..7451f58f2d 100644--- a/crates/pa-daemon/src/engine.rs+++ b/crates/pa-daemon/src/engine.rs@@ -16,10 +16,10 @@ mod wire;pub use scripted::ScriptedEngine;pub(crate) use wire::session_wire_value;pub use wire::{- empty_resource_snapshot, side_question_event_value, AssistantSnapshot, BashCompletionNotice,- BashCompletionSink, BashConsumedNotice, BashConsumedSink, BranchSummaryOutcome,- BranchSummaryRequest, BranchSummaryRun, CompactionOutcome, CompactionRequest, CompactionRun,- EngineEvent, EngineModelSelection, GoalAdmissionSink, GoalContinuation, GoalTurnEndWork,+ empty_resource_snapshot, side_question_event_value, AssistantSnapshot, BashConsumedNotice,+ BashConsumedSink, BranchSummaryOutcome, BranchSummaryRequest, BranchSummaryRun,+ CompactionOutcome, CompactionRequest, CompactionRun, EngineEvent, EngineModelSelection,+ GoalAdmissionSink, GoalContinuation, GoalTurnEndWork, KernelNotice, KernelNoticeSink,PromptBatchRow, PromptRequest, RlmSessionIdentity, SavedSessionContext, SemanticSpawnOrigin,SessionInputProbe, SideQuestionOutcome, SideQuestionRequest, SIDE_QUESTION_STATUS_CANCELLED,SIDE_QUESTION_STATUS_COMPLETE, SIDE_QUESTION_STATUS_ERROR, SIDE_QUESTION_STATUS_RUNNING,diff --git a/crates/pa-daemon/src/engine/wire.rs b/crates/pa-daemon/src/engine/wire.rsindex 9bfdc439d2..fe3535c9f2 100644--- a/crates/pa-daemon/src/engine/wire.rs+++ b/crates/pa-daemon/src/engine/wire.rs@@ -241,11 +241,11 @@ pub enum GoalTurnEndWork {/// held suspension owns the next turn boundary, so the goal mint defers.pub type SessionInputProbe = std::sync::Arc<dyn Fn() -> bool + Send + Sync>;-// The bash-notice plumbing lives in pa-core+// The kernel-notice plumbing lives in pa-core// (`session_engine::bash_notices`); the re-export keeps the// `crate::engine::*` paths the worker's queue lanes compile against.pub use pa_core::session_engine::bash_notices::{- BashCompletionNotice, BashCompletionSink, BashConsumedNotice, BashConsumedSink,+ BashConsumedNotice, BashConsumedSink, KernelNotice, KernelNoticeSink,};/// The worker's goal admission sink: the queue lanes admit a minted goaldiff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 0254de2181..86a1b591d8 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -24,7 +24,7 @@ mod queue;pub use queue::Lane;pub use queue::QueuePriority;pub(crate) use queue::{- admit_autonomous_follow_up, admit_bash_completion_notice, admit_goal_follow_up,+ admit_autonomous_follow_up, admit_goal_follow_up, admit_kernel_notice,checkpoint_queue_recovery, clear_withdrawn_progress_note, enqueue_priority,gather_delivery_batch, parse_custom_message, parse_prompt_images, queue_lanes,restore_queue_snapshot, restored_turn_policy, withdraw_bash_completion_notice, QueueCheckpoint,@@ -609,25 +609,25 @@ impl Worker {);});concrete.set_compaction_summary_sink(summary_sink);- // The bash-completion wake seam (TS `_promptInjectedMessage`- // for `bash.completed`): the handler validates, the sink- // admits/withdraws through the queue lanes.+ // The kernel-notice wake seam (TS `_promptInjectedMessage`+ // for `bash.completed` and `factory.progress`): the handlers+ // validate, the sinks admit/withdraw through the queue lanes.let notice_engine = std::sync::Arc::downgrade(concrete);let notice_core = Arc::clone(&core);let notice_notify = Arc::clone(&work_notify);let notice_recovery = Arc::clone(&recovery);- let completion: crate::engine::BashCompletionSink = Arc::new(move |notice| {+ let notice_sink: crate::engine::KernelNoticeSink = Arc::new(move |notice| {let Some(engine) = notice_engine.upgrade() else {return;};if engine.session_is_closed() {return;}- admit_bash_completion_notice(+ admit_kernel_notice(¬ice_recovery,¬ice_core,¬ice_notify,- ¬ice,+ notice,// Revalidated inside the admission's lock section: the// close paths mark the session BEFORE clearing the lanes.|| engine.session_is_closed(),@@ -645,7 +645,7 @@ impl Worker {engine.as_deref().map(|engine| engine as &dyn SessionEngine),);});- concrete.set_bash_notice_sinks(completion, consumed);+ concrete.set_kernel_notice_sinks(notice_sink, consumed);// The accepted note frames as a session event on the pump.let note_core = Arc::clone(&core);let note_events = events.clone();diff --git a/crates/pa-daemon/src/worker/queue.rs b/crates/pa-daemon/src/worker/queue.rsindex 0f0de62176..43343b4684 100644--- a/crates/pa-daemon/src/worker/queue.rs+++ b/crates/pa-daemon/src/worker/queue.rs@@ -521,22 +521,18 @@ pub(crate) fn admit_goal_follow_up(work_notify.notify_one();}-/// Admit one detached kernel bash completion notice: the row queues on the-/// steering lane (busy sessions keep a visible steer row, idle sessions wake-/// into it); a crash before the delivery revives with the row replaying.-pub(crate) fn admit_bash_completion_notice(+/// Admit one kernel notice (a detached bash completion or a factory run+/// milestone): the row queues on the steering lane (busy sessions keep a+/// visible steer row, idle sessions wake into it); a crash before the+/// delivery revives with the row replaying.+pub(crate) fn admit_kernel_notice(recovery: &std::sync::Mutex<Option<WorkerRecoveryJournal>>,core: &Arc<Mutex<SessionCore>>,work_notify: &Arc<Notify>,- notice: &crate::engine::BashCompletionNotice,+ notice: crate::engine::KernelNotice,session_is_closed: impl Fn() -> bool,) {- let row = pa_core::session_engine::messages::create_async_bash_completion_message(- notice.pid,- ¬ice.command,- notice.exit_code,- crate::util::now_ms(),- );+ let crate::engine::KernelNotice { row, preview_label } = notice;let content = match &row.content {pa_types::ai::UserContent::Text(text) => text.clone(),pa_types::ai::UserContent::Blocks(_) => String::new(),@@ -558,10 +554,7 @@ pub(crate) fn admit_bash_completion_notice(core_guard.steering.push_back(QueuedItem {priority: QueuePriority::Background,// The queue strip's labeled preview (TS `previewLabel`).- preview: Some(format!(- "{}: {content}",- pa_core::session_engine::messages::ASYNC_BASH_COMPLETION_PREVIEW_LABEL- )),+ preview: Some(format!("{preview_label}: {content}")),message: content,custom_message: Some(crate::session_commands::custom_message_value(&row)),agent_message: None,diff --git a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs b/crates/pa-daemon/src/worker/recovery_verdict_tests.rsindex 970c84df94..fea7574389 100644--- a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs+++ b/crates/pa-daemon/src/worker/recovery_verdict_tests.rs@@ -84,15 +84,11 @@ async fn a_bash_completion_notice_admits_the_steering_lane_with_busy_evidence()let worker = created_worker_with_journal().await;worker.dispatch("clear_queue", &json!({})).await;let notify = Arc::new(Notify::new());- admit_bash_completion_notice(+ admit_kernel_notice(&worker.recovery,&worker.core,¬ify,- &crate::engine::BashCompletionNotice {- pid: 4321,- command: "sleep 12; echo RW_WAKE_DONE".to_string(),- exit_code: 0,- },+ crate::engine::KernelNotice::bash_completion(4321, "sleep 12; echo RW_WAKE_DONE", 0),|| false,);let core = worker.core.lock().unwrap();@@ -149,15 +145,11 @@ async fn a_bash_completion_notice_on_a_busy_session_queues_a_visible_steer_row()let worker = created_worker_with_journal().await;worker.core.lock().unwrap().busy = true;let notify = Arc::new(Notify::new());- admit_bash_completion_notice(+ admit_kernel_notice(&worker.recovery,&worker.core,¬ify,- &crate::engine::BashCompletionNotice {- pid: 99,- command: "make gates".to_string(),- exit_code: 2,- },+ crate::engine::KernelNotice::bash_completion(99, "make gates", 2),|| false,);let core = worker.core.lock().unwrap();@@ -174,15 +166,11 @@ async fn bash_consumed_withdraws_the_undelivered_notice_and_settles() {let worker = created_worker_with_journal().await;worker.dispatch("clear_queue", &json!({})).await;let notify = Arc::new(Notify::new());- admit_bash_completion_notice(+ admit_kernel_notice(&worker.recovery,&worker.core,¬ify,- &crate::engine::BashCompletionNotice {- pid: 4321,- command: "sleep 12; echo RW_WAKE_DONE".to_string(),- exit_code: 0,- },+ crate::engine::KernelNotice::bash_completion(4321, "sleep 12; echo RW_WAKE_DONE", 0),|| false,);assert!(diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rsindex 73a7f896ab..7114efb5e0 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs@@ -852,7 +852,7 @@ impl SessionEngine for NoteWitnessEngine {async fn the_async_completion_notice_delivery_keeps_the_live_note() {let engine = Arc::new(NoteWitnessEngine::default());let runner = burst_runner(engine.clone());- // The busy-session row `admit_bash_completion_notice` queues.+ // The busy-session row `admit_kernel_notice` queues.runner.core.lock()diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rsindex 4986bc9435..89fc43a898 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rs@@ -59,15 +59,11 @@ async fn queue_withdrawals_clear_only_the_last_idle_notes() {}}if command == "bash_consumed" {- admit_bash_completion_notice(+ admit_kernel_notice(&worker.recovery,&worker.core,&Arc::new(Notify::new()),- &crate::engine::BashCompletionNotice {- pid: 4321,- command: "fixture command".to_string(),- exit_code: 0,- },+ crate::engine::KernelNotice::bash_completion(4321, "fixture command", 0),|| false,);withdraw_bash_completion_notice(diff --git a/crates/pa-tui/src/agents_view/session_activity.rs b/crates/pa-tui/src/agents_view/session_activity.rsindex dba56bdb8c..38cab4ca67 100644--- a/crates/pa-tui/src/agents_view/session_activity.rs+++ b/crates/pa-tui/src/agents_view/session_activity.rs@@ -9,7 +9,7 @@ use tokio::sync::oneshot;pub(super) struct ActivityRead {pub(super) active_session_id: String,pub(super) shells: Option<usize>,- pub(super) factory_runs: Option<usize>,+ pub(super) factory_runs: Option<crate::factory_view::FactoryRunCounts>,}/// One fetch cycle over the live sessions, off the key loop: each session's kernel answers its@@ -44,7 +44,7 @@ pub(super) fn spawn_session_activity_fetch(};let factory_runs = async {if !factory_supported {- return Some(0);+ return Some(crate::factory_view::FactoryRunCounts::default());}let reply = client.request_ok(DaemonCommand::FactoryActivity {@@ -58,8 +58,11 @@ pub(super) fn spawn_session_activity_fetch(}).await;count(reply, |data| {- crate::factory_view::factory_reply_lists_runs(data)- .then(|| crate::factory_view::live_run_count(data))+ crate::factory_view::factory_reply_lists_runs(data).then(|| {+ crate::factory_view::FactoryRunCounts::of(+ &crate::factory_view::parse_factory_runs(data),+ )+ })})};let (shells, factory_runs) = tokio::join!(shells, factory_runs);@@ -77,10 +80,10 @@ pub(super) fn spawn_session_activity_fetch(}/// A session without a running kernel hosts nothing: zero, not a failed read.-fn count(reply: Result<Value>, count: impl Fn(&Value) -> Option<usize>) -> Option<usize> {+fn count<T: Default>(reply: Result<Value>, count: impl Fn(&Value) -> Option<T>) -> Option<T> {match reply {Ok(data) => count(&data),- Err(error) if crate::daemon_client::is_kernel_not_running(&error) => Some(0),+ Err(error) if crate::daemon_client::is_kernel_not_running(&error) => Some(T::default()),Err(_) => None,}}diff --git a/crates/pa-tui/src/agents_view/tests/activity_lines.rs b/crates/pa-tui/src/agents_view/tests/activity_lines.rsindex 0cfc91a41b..d8015c8fcf 100644--- a/crates/pa-tui/src/agents_view/tests/activity_lines.rs+++ b/crates/pa-tui/src/agents_view/tests/activity_lines.rs@@ -10,7 +10,10 @@ fn with_activity(mode: &mut AgentsViewMode, active: &str, shells: usize, factoryactive.to_string(),SessionActivity {shells,- factory_runs,+ factory_runs: crate::factory_view::FactoryRunCounts {+ running: factory_runs,+ paused: 0,+ },},);mode.rebuild_rows();diff --git a/crates/pa-tui/src/agents_view_forest.rs b/crates/pa-tui/src/agents_view_forest.rsindex f8b855e566..2ec0524c12 100644--- a/crates/pa-tui/src/agents_view_forest.rs+++ b/crates/pa-tui/src/agents_view_forest.rs@@ -126,7 +126,7 @@ pub struct SelectionKey {#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct SessionActivity {pub shells: usize,- pub factory_runs: usize,+ pub factory_runs: crate::factory_view::FactoryRunCounts,}/// One recursive rollup over the record hierarchy (TSdiff --git a/crates/pa-tui/src/agents_view_forest/rows.rs b/crates/pa-tui/src/agents_view_forest/rows.rsindex 7ce8c5bc8f..78afd25938 100644--- a/crates/pa-tui/src/agents_view_forest/rows.rs+++ b/crates/pa-tui/src/agents_view_forest/rows.rs@@ -11,6 +11,7 @@ use crate::agents_view_state::{is_unnamed_empty, now_ms, relative_age, section_rank, summary_for_record, Section,UnifiedRecord,};+use crate::factory_view::FactoryRunCounts;use crate::subagents::{is_subagent_summary, summary_identity_keys, summary_parent_keys};struct BaseRow {@@ -379,7 +380,8 @@ fn merged_summary_row(parent: &BaseRow, depth: usize, expanded: bool) -> AgentsV}}-/// The node's own `$ N shells` and `⚙ N factory runs` lines, each only when its count is nonzero.+/// The node's own `$ N shells` and `⚙ N factory runs` lines, each only when its count is nonzero;+/// paused runs read apart from the running ones (`⚙ 0 factory runs · 1 paused`)./// Like the summary line they reuse the parent's summary, so the open action resolves the parent.fn activity_rows(parent: &BaseRow, depth: usize) -> Vec<AgentsViewRow> {let line = |kind: RowKind, prefix: &str, title: String| AgentsViewRow {@@ -410,13 +412,19 @@ fn activity_rows(parent: &BaseRow, depth: usize) -> Vec<AgentsViewRow> {format!("$ {shells} shell{}", if shells == 1 { "" } else { "s" }),));}- if factory_runs > 0 {+ let FactoryRunCounts { running, paused } = factory_runs;+ if running + paused > 0 {+ let paused = if paused > 0 {+ format!(" \u{b7} {paused} paused")+ } else {+ String::new()+ };rows.push(line(RowKind::FactoryRuns,super::FACTORY_ROW_PREFIX,format!(- "\u{2699} {factory_runs} factory run{}",- if factory_runs == 1 { "" } else { "s" }+ "\u{2699} {running} factory run{}{paused}",+ if running == 1 { "" } else { "s" }),));}diff --git a/crates/pa-tui/src/agents_view_forest/tests.rs b/crates/pa-tui/src/agents_view_forest/tests.rsindex b1833fb979..b74a99097e 100644--- a/crates/pa-tui/src/agents_view_forest/tests.rs+++ b/crates/pa-tui/src/agents_view_forest/tests.rs@@ -414,7 +414,7 @@ fn the_expanded_group_renders_each_agent_once() {#[test]fn selection_pins_a_stale_activity_identity_to_its_kind() {let roster = vec![roster_entry("p", "idle", &parent_summary("p"))];- let counts = activity(&[("p-live", 2, 1)]);+ let counts = activity(&[("p-live", 2, 1, 0)]);let rows = rows_with_activity(&roster, None, &[], &counts);let key = SelectionKey {session_id: Some("p".to_string()),@@ -1252,15 +1252,16 @@ fn a_ledger_child_nests_across_the_windows_path_forms() {);}-fn activity(entries: &[(&str, usize, usize)]) -> HashMap<String, SessionActivity> {+/// Each entry is `(active session, shells, running factory runs, paused factory runs)`.+fn activity(entries: &[(&str, usize, usize, usize)]) -> HashMap<String, SessionActivity> {entries.iter()- .map(|(active, shells, factory_runs)| {+ .map(|&(active, shells, running, paused)| {(- (*active).to_string(),+ active.to_string(),SessionActivity {- shells: *shells,- factory_runs: *factory_runs,+ shells,+ factory_runs: crate::factory_view::FactoryRunCounts { running, paused },},)})@@ -1280,7 +1281,11 @@ fn activity_lines_follow_each_nodes_subagents_block() {roster_entry("c2", "idle", &child_summary("c2", "p", "second child")),roster_entry("gc", "idle", &grandchild),];- let counts = activity(&[("p-live", 2, 1), ("c1-live", 1, 0), ("c2-live", 0, 0)]);+ let counts = activity(&[+ ("p-live", 2, 1, 0),+ ("c1-live", 1, 0, 0),+ ("c2-live", 0, 0, 0),+ ]);let rows = rows_with_activity(&roster, None, &["file:/x/p.jsonl"], &counts);let first_child = rows.iter()@@ -1325,7 +1330,7 @@ fn activity_lines_without_subagents_and_without_counts() {roster_entry("a", "idle", &parent_summary("a")),roster_entry("b", "idle", &parent_summary("b")),];- let rows = rows_with_activity(&roster, None, &[], &activity(&[("a-live", 0, 3)]));+ let rows = rows_with_activity(&roster, None, &[], &activity(&[("a-live", 0, 3, 0)]));let titles: Vec<&str> = rows.iter().map(|row| row.title.as_str()).collect();let a = titles.iter()@@ -1338,3 +1343,25 @@ fn activity_lines_without_subagents_and_without_counts() {"b has no lines and a has no shells line: {titles:?}");}++/// Paused factory runs never read as running: the line counts the running runs and names the+/// paused ones apart, like the dock's paused cluster.+#[test]+fn the_factory_line_counts_paused_runs_apart_from_running_ones() {+ let roster = vec![roster_entry("a", "idle", &parent_summary("a"))];+ let line = |running, paused| {+ rows_with_activity(+ &roster,+ None,+ &[],+ &activity(&[("a-live", 0, running, paused)]),+ )+ .into_iter()+ .filter(|row| row.kind == RowKind::FactoryRuns)+ .map(|row| row.title)+ .collect::<Vec<_>>()+ };+ assert_eq!(line(0, 1), vec!["\u{2699} 0 factory runs \u{b7} 1 paused"]);+ assert_eq!(line(2, 1), vec!["\u{2699} 2 factory runs \u{b7} 1 paused"]);+ assert_eq!(line(1, 0), vec!["\u{2699} 1 factory run"]);+}diff --git a/crates/pa-tui/src/chrome.rs b/crates/pa-tui/src/chrome.rsindex b1af29f8c9..9be4773610 100644--- a/crates/pa-tui/src/chrome.rs+++ b/crates/pa-tui/src/chrome.rs@@ -151,6 +151,9 @@ pub struct ActivityDock {/// only): fully terminal runs never inflate the group, exactly like/// the shells group's running-only scoping.pub factory_runs: Vec<String>,+ /// The same live runs counted running vs paused (the collapsed count+ /// and its paused cluster).+ pub factory_counts: crate::factory_view::FactoryRunCounts,/// Whether the factory group renders at all: the daemon's/// `factory_activity` advertisement (the factory's opt-in gate —/// `factory.enabled`, off by default). A daemon without the lane@@ -742,7 +745,7 @@ pub fn render_activity_dock_segments(return (lines, segments);}// The status-dot vocabulary (`● running / ◐ idle / ○ inactive`): the half- // circle marks waiting work; only the heartbeat pause keeps a dot.+ // circle marks waiting work; only the heartbeat and factory pauses keep a dot.let cluster = |text: &str, color: ThemeColor| {vec![theme.fg_span(ThemeColor::Dim, " · ".to_string()),@@ -753,7 +756,7 @@ pub fn render_activity_dock_segments(// children and nested descendants together — ONE number.let running = dock.subagents_running_direct + dock.subagents_running_nested;let shells = dock.shells.len();- let factory_runs = dock.factory_runs.len();+ let factory = dock.factory_counts;let mut line = vec![Span::raw(" ")];let mut segments: Vec<ActivityDockSegment> = Vec::new();for (index, group) in dock.groups().into_iter().enumerate() {@@ -794,13 +797,21 @@ pub fn render_activity_dock_segments(activity_color(shells),format!("▸ {} shell{}", shells, if shells == 1 { "" } else { "s" }),)),- // The factory page's indicator counts live runs only- // (running, stopping, paused): done and failed runs stay as- // panels inside the factory page, never in the indicator.- ActivityGroup::Factory => line.push(theme.fg_span(- activity_color(factory_runs),- format!("⚙ {factory_runs} factory"),- )),+ // The factory indicator counts the running runs, and the paused+ // ones in their own amber cluster (the heartbeats' grammar): done+ // and failed runs stay as panels inside the factory page.+ ActivityGroup::Factory => {+ line.push(theme.fg_span(+ activity_color(factory.running),+ format!("⚙ {} factory", factory.running),+ ));+ if factory.paused > 0 {+ line.extend(cluster(+ &format!("◐ {} paused", factory.paused),+ ThemeColor::Warning,+ ));+ }+ }ActivityGroup::Goal => line.push(goal_span(dock, theme)),}let end = line.iter().map(|s| str_width(&s.content)).sum();@@ -904,7 +915,7 @@ fn render_expanded_dock_row(theme,width,("⚙", "factory"),- dock.factory_runs.len(),+ dock.factory_counts.running,&dock.factory_runs,),ActivityGroup::Goal => vec![Span::raw(" "), goal_span(dock, theme)],diff --git a/crates/pa-tui/src/chrome/tests.rs b/crates/pa-tui/src/chrome/tests.rsindex e2d98fc769..511524ff00 100644--- a/crates/pa-tui/src/chrome/tests.rs+++ b/crates/pa-tui/src/chrome/tests.rs@@ -258,6 +258,57 @@ fn activity_dock_frames_one_row_with_running_paused_and_goal_counts() {assert!(text.contains("Pursuing goal (12m 05s)"));}+/// A paused factory run never reads as running: the collapsed count holds only the running+/// run (green), and the paused one sits in its own amber cluster, like a paused heartbeat.+#[test]+fn the_collapsed_dock_counts_paused_factory_runs_apart_from_running_ones() {+ let theme = Theme::builtin("prime", ColorMode::TrueColor);+ let colored = |dock: &ActivityDock| {+ render_activity_dock(dock, &theme, 120)[1]+ .iter()+ .skip_while(|span| !span.content.starts_with('⚙'))+ .map(|span| (span.content.clone(), span.style.fg))+ .collect::<Vec<_>>()+ };+ let paused_only = ActivityDock {+ factory_runs: vec!["nightly paused".to_string()],+ factory_counts: crate::factory_view::FactoryRunCounts {+ running: 0,+ paused: 1,+ },+ factory_group: true,+ ..ActivityDock::default()+ };+ let muted = theme.fg_style(ThemeColor::Muted).fg;+ let success = theme.fg_style(ThemeColor::Success).fg;+ let warning = theme.fg_style(ThemeColor::Warning).fg;+ let dim = theme.fg_style(ThemeColor::Dim).fg;+ assert_eq!(+ colored(&paused_only),+ vec![+ ("⚙ 0 factory".to_string(), muted),+ (" · ".to_string(), dim),+ ("◐ 1 paused".to_string(), warning),+ ]+ );+ let mixed = ActivityDock {+ factory_runs: vec!["nightly paused".to_string(), "lint running".to_string()],+ factory_counts: crate::factory_view::FactoryRunCounts {+ running: 1,+ paused: 1,+ },+ ..paused_only+ };+ assert_eq!(+ colored(&mixed),+ vec![+ ("⚙ 1 factory".to_string(), success),+ (" · ".to_string(), dim),+ ("◐ 1 paused".to_string(), warning),+ ]+ );+}+/// ONE number: direct children and nested descendants summed, never a `direct, nested` pair.#[test]fn prompt_bar_subagent_segment_is_the_running_count_only() {@@ -342,6 +393,10 @@ fn the_focused_dock_expands_into_one_row_per_group() {heartbeats_paused: 1,shells: vec!["cargo test · 12.0s".to_string()],factory_runs: vec!["nightly paused".to_string()],+ factory_counts: crate::factory_view::FactoryRunCounts {+ running: 0,+ paused: 1,+ },factory_group: true,goal_label: Some("Pursuing goal (0s)".to_string()),selected: ActivityGroup::Subagents,@@ -376,7 +431,7 @@ fn the_focused_dock_expands_into_one_row_per_group() {let texts = line_texts(&render_activity_dock(&collapsed, &theme, 120));assert_eq!(texts[1..],- [" ◆ 3 subagents · ◷ 2 heartbeats · ◐ 1 paused · ▸ 1 shell · ⚙ 1 factory · Pursuing goal (0s)"]+ [" ◆ 3 subagents · ◷ 2 heartbeats · ◐ 1 paused · ▸ 1 shell · ⚙ 0 factory · ◐ 1 paused · Pursuing goal (0s)"]);}diff --git a/crates/pa-tui/src/factory_view.rs b/crates/pa-tui/src/factory_view.rsindex 439f524ca4..b6ffa683d0 100644--- a/crates/pa-tui/src/factory_view.rs+++ b/crates/pa-tui/src/factory_view.rs@@ -132,6 +132,38 @@ impl FactoryRunSnapshot {Some("running" | "stopping" | "paused")) || self.children_in_flight()}++ /// Whether the run is paused (an escalate, budget, or max-* pause+ /// waiting for resume): live, but not running. Every count splits the+ /// live runs on this one predicate.+ #[must_use]+ pub fn is_paused(&self) -> bool {+ self.state.as_deref() == Some("paused")+ }+}++/// The live runs split on [`FactoryRunSnapshot::is_paused`]: the dock and+/// the agents view show the running runs apart from the paused ones.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct FactoryRunCounts {+ pub running: usize,+ pub paused: usize,+}++impl FactoryRunCounts {+ /// Count the live runs of one parsed reply.+ #[must_use]+ pub fn of(runs: &[FactoryRunSnapshot]) -> Self {+ let mut counts = Self::default();+ for run in runs.iter().filter(|run| run.is_live()) {+ if run.is_paused() {+ counts.paused += 1;+ } else {+ counts.running += 1;+ }+ }+ counts+ }}/// The activity dock's factory row: the live runs (the dock count's own@@ -139,7 +171,7 @@ impl FactoryRunSnapshot {#[must_use]pub fn dock_factory_items(runs: &[FactoryRunSnapshot]) -> Vec<String> {let mut live: Vec<&FactoryRunSnapshot> = runs.iter().filter(|run| run.is_live()).collect();- live.sort_by_key(|run| run.state.as_deref() != Some("paused"));+ live.sort_by_key(|run| !run.is_paused());live.iter().map(|run| match &run.state {Some(state) => format!("{} {state}", run.display_name()),@@ -403,7 +435,7 @@ impl FactoryView {if run.run_id.is_empty() {return actions;}- if run.state.as_deref() == Some("paused") {+ if run.is_paused() {actions.push(FactoryAction::Resume);}if run.is_live() {diff --git a/crates/pa-tui/src/factory_view/tests.rs b/crates/pa-tui/src/factory_view/tests.rsindex b229b31b53..1d1518cf30 100644--- a/crates/pa-tui/src/factory_view/tests.rs+++ b/crates/pa-tui/src/factory_view/tests.rs@@ -1497,6 +1497,15 @@ fn the_dock_count_reads_one_liveness_rule_across_many_runs() {live, 13,"eight live + one stopping + two paused + two done-with-residents");+ // The dock and the agents view split those live runs on the ONE paused+ // predicate: the two paused runs never count as running.+ assert_eq!(+ FactoryRunCounts::of(&runs),+ FactoryRunCounts {+ running: 11,+ paused: 2+ }+ );let find = |id: &str| {runs.iter().find(|run| run.run_id == id)diff --git a/crates/pa-tui/src/session_ui/panels.rs b/crates/pa-tui/src/session_ui/panels.rsindex 1216f59eb2..f87b2e122a 100644--- a/crates/pa-tui/src/session_ui/panels.rs+++ b/crates/pa-tui/src/session_ui/panels.rs@@ -119,9 +119,8 @@ impl SessionUi {// run whose resident children still run keeps its entry like its panel and its stop// control). Fully terminal runs stay as panels inside the factory page, never in the// dock — the shells group's running-only scoping, one lane over.- let factory_runs = crate::factory_view::dock_factory_items(- &crate::factory_view::parse_factory_runs(&self.factory_graph),- );+ let runs = crate::factory_view::parse_factory_runs(&self.factory_graph);+ let factory_runs = crate::factory_view::dock_factory_items(&runs);// The dock's subagent count is the live running count only:// idle and dead registry rows (passivated children the ledger// still seeds) never bloat the collapsed indicator — the expanded@@ -139,6 +138,7 @@ impl SessionUi {heartbeats_paused: paused_heartbeat_count(&self.heartbeat_catalog),shells,factory_runs,+ factory_counts: crate::factory_view::FactoryRunCounts::of(&runs),// The group renders exactly while the daemon advertises the// lane: the factory's opt-in gate (a daemon without the// factory lane never mounts the group).diff --git a/prime-agent-runtime/src/rlm/factory.py b/prime-agent-runtime/src/rlm/factory.pyindex aeed2dd4b5..6afe16a7c4 100644--- a/prime-agent-runtime/src/rlm/factory.py+++ b/prime-agent-runtime/src/rlm/factory.py@@ -1737,6 +1737,10 @@ class FactoryExecutor:run.loop_generation += 1run.state = "running"run.pause_reason = None+ # Re-arm the pause notice: the escalate -> resume -> fail-again+ # retry flow must tell the parent about every pause, not only the+ # first. The budget and max_* notices stay one per run.+ run.milestones.discard("paused")self._touch(run)self._event(run, "resumed", detail="resumed by caller")# An escalate pause holds its failed entry unsettled: re-admit it@@ -2367,9 +2371,9 @@ class FactoryExecutor:async def _milestone(self, run: FactoryRun, kind: str, detail: str, *, node: str | None = None) -> None:"""Record a run milestone and inject one quiet notice (one per kind).- Every milestone lands in the ledger, repeats included: a run that- pauses twice must still show the second pause to the parent reading- ``status()``. Only the parent-visible notice is deduped per kind.+ Every milestone lands in the ledger, repeats included. Only the+ parent-visible notice is deduped per kind; ``resume()`` re-arms the+ ``paused`` notice, so each pause after a resume notifies again."""event = self._event(run, "milestone", milestone=kind, detail=detail, node=node)if kind in run.milestones:@@ -5222,8 +5226,9 @@ watched = await rlm.factory.watch(result["run_id"], 30)failure; `name=` labels the run in status and the TUI.- Pause and failure notices (escalate, budget, max_transitions,max_children, failed, finished) arrive as quiet notices in the- conversation once per kind per run, the pause notices with the resume- call spelled out — a paused run does not need polling to be noticed.+ conversation once per kind per run (an escalate pause notifies again+ after each resume), the pause notices with the resume call spelled+ out — a paused run does not need polling to be noticed.- `stop(run_id)` cancels every running child of the run (idempotent);`resume(run_id)` continues a paused run and raises on a non-paused one;after an escalate pause it first re-admits the failed entry.diff --git a/prime-agent-runtime/test/test_factory.py b/prime-agent-runtime/test/test_factory.pyindex 1c973bfd59..65894467d2 100644--- a/prime-agent-runtime/test/test_factory.py+++ b/prime-agent-runtime/test/test_factory.py@@ -42,8 +42,8 @@ races) plus the accepted review findings from both:finding: the name was dropped, so children always got the generatedlabel);- milestone notices go to the host as validated "factory.progress"- payloads exactly once per kind per run, and a dead bridge leaves the- milestone in the ledger instead of wedging the run.+ payloads once per kind per run (resume re-arms the pause notice), and a+ dead bridge leaves the milestone in the ledger instead of wedging the run."""from __future__ import annotations@@ -4345,12 +4345,12 @@ class FactoryExecutorTest(_ExecutorTestCase):self.assertEqual(self.sleeps.sleeps[sleep_mark:], [1.0])@async_test- async def test_repeated_pause_records_every_milestone_in_the_ledger(self) -> None:- # A run that pauses, resumes, and pauses again must record the second- # pause in the ledger even though the parent notice fires once per- # kind: status() is the only reader of the repeat.+ async def test_a_pause_after_resume_notifies_the_parent_again(self) -> None:+ # A run that pauses, resumes, and pauses again (the escalate retry+ # flow) records both pauses in the ledger AND tells the parent about+ # both: resume() re-arms the paused notice.# a fails once and its re-admitted retry succeeds, so the second- # pause is b's own failure -- the milestone the repeat must record.+ # pause is b's own failure.self.host.child_outcomes["child-1"] = {"status": "error", "error": "a boom"}self.host.outcomes["b"] = {"status": "error", "error": "b boom"}self.store_machine(@@ -4371,16 +4371,12 @@ class FactoryExecutorTest(_ExecutorTestCase):second = await self.settle(result)self.assertEqual(second["state"], "paused")self.assertEqual(self.executor._runs[result["run_id"]].pause_reason, "b boom")- # the second pause is in the ledger with its own event, notice-freemilestones = [event for event in second["events"] if event["kind"] == "milestone"]self.assertEqual([event["milestone"] for event in milestones], ["paused", "paused"])self.assertIn("a boom", milestones[0]["detail"])self.assertIn("b boom", milestones[1]["detail"])- self.assertEqual(self.host.notice_kinds(), ["paused"]) # one notice per kind- # the announced pause keeps "shown"; the repeat (no second notice)- # was only ever read through status(), so it reads "delivered"- self.assertEqual(milestones[0]["stage"], "shown")- self.assertEqual(milestones[1]["stage"], "delivered")+ self.assertEqual(self.host.notice_kinds(), ["paused", "paused"])+ self.assertEqual([event["stage"] for event in milestones], ["shown", "shown"])# -- retries --------------------------------------------------------------------diff --git a/scripts/check_factory_resumption.py b/scripts/check_factory_resumption.pyindex 41514b70aa..ea39407518 100644--- a/scripts/check_factory_resumption.py+++ b/scripts/check_factory_resumption.py@@ -2,7 +2,8 @@"""Hosted real-daemon factory recovery receipt.The kernel runs a real factory child, fails its declared JSON output,-resumes the same entry, and binds the second child's valid output.+resumes the same entry, and binds the second child's valid output. The+owning (parent) session receives the paused and finished notices."""import argparseimport http.server@@ -161,12 +162,25 @@ def observe(binary, root, observed):threading.Event().wait(0.025)observed.setdefault('timed_out_snapshots', []).extend(snapshots)raise AssertionError('factory did not leave running after parent turn completed')+ def parent_notice(kind):+ notice = f'[factory-progress run:{run_id}] {kind}:'+ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ seen = [text for body in list(server.parent_requests)+ for m in body.get('messages', []) if m.get('role') == 'user'+ for text in texts(m.get('content')) if notice in text]+ if seen:+ return seen[0]+ threading.Event().wait(0.025)+ raise AssertionError(f'parent session never received {notice!r}')paused = settled()assert paused['state'] == 'paused', paused+ observed['paused_notice'] = parent_notice('paused')observed['resume_response'] = control.call('factory_activity', activeSessionId=active,action='resume', runId=run_id)observed['probe'] = {'paused': paused, 'done': settled()}validate(observed['probe'])+ observed['finished_notice'] = parent_notice('finished')assert len(server.child_requests) == 3, 'not two producer attempts plus one guarded verifier'observed['behavior_verified'] = Truefinally: