A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(tui): factory live page with machine diagram highlighting (#3290)
Seth Karten2b962da26907
diff --git a/crates/pa-cli/src/client_settings.rs b/crates/pa-cli/src/client_settings.rsindex 6ad93ec760..df8f3e62ee 100644--- a/crates/pa-cli/src/client_settings.rs+++ b/crates/pa-cli/src/client_settings.rs@@ -181,6 +181,13 @@ impl ClientSettings for CliClientSettings {get_chat_detail,set_chat_detail);+ setting!(+ factory_enabled,+ set_factory_enabled,+ get_factory_enabled,+ set_factory_enabled,+ bool+ );setting!(warnings_anthropic_extra_usage,set_warnings_anthropic_extra_usage,@@ -309,5 +316,27 @@ mod tests {// ...and the /nightly on path's.settings.set_update_channel("nightly").expect("channel");assert_eq!(settings.update_channel().as_deref(), Some("nightly"));++ // The factory's opt-in gate (`/factory on|off|status`): unset reads+ // as disabled (the default off), and the write persists the exact+ // nested-camelCase key the kernel's gate and the daemon's lane+ // advertisement read -- over the same document, leaving the other+ // keys alone.+ assert!(!settings.factory_enabled());+ settings.set_factory_enabled(true).expect("factory enabled");+ assert!(settings.factory_enabled());+ let content =+ std::fs::read_to_string(agent_dir.join("settings.json")).expect("settings file");+ let value: serde_json::Value = serde_json::from_str(&content).expect("parse");+ assert_eq!(value["factory"]["enabled"], true);+ assert_eq!(value["theme"], "dark", "the write leaves the other keys");+ settings+ .set_factory_enabled(false)+ .expect("factory disabled");+ assert!(!settings.factory_enabled());+ let content =+ std::fs::read_to_string(agent_dir.join("settings.json")).expect("settings file");+ let value: serde_json::Value = serde_json::from_str(&content).expect("parse");+ assert_eq!(value["factory"]["enabled"], false);}}diff --git a/crates/pa-core/src/kernel/manager/events.rs b/crates/pa-core/src/kernel/manager/events.rsindex c911ac4307..024c24d384 100644--- a/crates/pa-core/src/kernel/manager/events.rs+++ b/crates/pa-core/src/kernel/manager/events.rs@@ -103,6 +103,12 @@ impl Inner {let _ = waiter.send(fields);return;}+ // The factory bridge's lane shares the done routing: its+ // ids are fresh UUIDs, never a cell request id.+ if let Some(waiter) = lock(&self.guarded).factory_activity_waiters.remove(&id) {+ let _ = waiter.send(fields);+ return;+ }let status = fields.get("status").and_then(Value::as_str)diff --git a/crates/pa-core/src/kernel/manager/mod.rs b/crates/pa-core/src/kernel/manager/mod.rsindex b430fe00ff..0e7023f9a4 100644--- a/crates/pa-core/src/kernel/manager/mod.rs+++ b/crates/pa-core/src/kernel/manager/mod.rs@@ -21,6 +21,7 @@ use crate::kernel::cancellation::{merge_signals, AbortSignal};use crate::kernel::live_kernels;use crate::kernel::orphan_journal;use crate::kernel::protocol::{parse_event, Event, Request, REPL_PROTOCOL_VERSION};+use crate::kernel::shared::FACTORY_ACTIVITY_ACTIONS;use crate::kernel::shared::{parse_attachment_display, parse_diff_display, parse_sent_agent_message, ExecuteOptions,ExecuteResult, ExecuteStatus, HostRequestPayload, KernelAttachment, KernelBashCommands,@@ -28,10 +29,11 @@ use crate::kernel::shared::{KernelShutdownOptions, LateSentAgentMessageCallback, StreamName, AGENT_MESSAGE_DISPLAY_MIME,ATTACHMENT_DISPLAY_MIME, BASH_ACTIVITY_DISPLAY_MIME, BASH_COMMAND_DISPLAY_MIME,DEFAULT_MAX_OUTPUT_CHARS, DEFAULT_SNAPSHOT_DEBOUNCE_MS, DIFF_DISPLAY_MIME,- HOST_REQUEST_SHUTDOWN_TIMEOUT_MS, KERNEL_ABORT_GRACE_MS, KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE,- KERNEL_BUSY_INTERRUPT_INTERVAL_MS, KERNEL_BUSY_REUSE_WAIT_MS, KERNEL_SHUTDOWN_TIMEOUT_MS,- KERNEL_STDERR_LOG_BUDGET_MARKER, MAX_ATTACHMENT_DATA_CHARS, MAX_BACKGROUND_OUTPUT_CHARS,- MAX_KERNEL_STDERR_CHARS, MAX_KERNEL_STDERR_LOG_BYTES, MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS,+ FACTIVITY_SETTLE_TIMEOUT_MS, FACTIVITY_WATCH_TIMEOUT_MS_CAP, HOST_REQUEST_SHUTDOWN_TIMEOUT_MS,+ KERNEL_ABORT_GRACE_MS, KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE, KERNEL_BUSY_INTERRUPT_INTERVAL_MS,+ KERNEL_BUSY_REUSE_WAIT_MS, KERNEL_SHUTDOWN_TIMEOUT_MS, KERNEL_STDERR_LOG_BUDGET_MARKER,+ MAX_ATTACHMENT_DATA_CHARS, MAX_BACKGROUND_OUTPUT_CHARS, MAX_KERNEL_STDERR_CHARS,+ MAX_KERNEL_STDERR_LOG_BYTES, MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS,RESTORE_EXECUTION_TIMEOUT_MS, SNAPSHOT_EXECUTION_TIMEOUT_MS,};use crate::kernel::state_snapshot::{@@ -347,6 +349,9 @@ struct Guarded {/// Resolvers for done events outside the active execution (the shutdown reply).pending_done_waiters: HashMap<String, oneshot::Sender<()>>,bash_activity_waiters: HashMap<String, oneshot::Sender<Value>>,+ /// Resolvers for out-of-band `factory_activity` done events (the+ /// factory bridge's lane; ids never collide with cell requests).+ factory_activity_waiters: HashMap<String, oneshot::Sender<Value>>,host_inflight: Vec<tokio::task::JoinHandle<()>>,active_execution: Option<Arc<ActiveExecution>>,/// Source of the most recently started cell, retained after it finishes so@@ -490,6 +495,7 @@ impl ReplKernelManager {late_handlers: VecDeque::new(),pending_done_waiters: HashMap::new(),bash_activity_waiters: HashMap::new(),+ factory_activity_waiters: HashMap::new(),host_inflight: Vec::new(),active_execution: None,last_cell_code: None,@@ -718,6 +724,91 @@ impl ReplKernelManager {Ok(fields)}+ /// Run one out-of-band `factory_activity` request against the kernel's+ /// factory executor: the `/factory` view's bridge lane. Like+ /// [`Self::bash_activity`] this bypasses the cell FIFO (a running turn+ /// must never delay the live view) and never boots an idle kernel.+ ///+ /// `action` is one of `graph`/`status`/`watch`/`run`/`stop`/`resume`;+ /// `run_id`/`spec_id` carry the target and `timeout_ms` bounds a watch.+ /// The kernel owns the run registry, so the reply is the kernel's+ /// result payload verbatim.+ ///+ /// # Errors+ ///+ /// Returns an error when the kernel is not running, the action or+ /// arguments are invalid, or the request does not settle inside its+ /// per-action bound (a watch gets its own timeout plus a margin; every+ /// other action gets a fixed settle bound).+ pub async fn factory_activity(+ &self,+ action: &str,+ run_id: Option<&str>,+ spec_id: Option<&str>,+ timeout_ms: Option<u64>,+ ) -> anyhow::Result<Value> {+ if !self.is_running() {+ return Err(anyhow!("Kernel is not running"));+ }+ if !FACTORY_ACTIVITY_ACTIONS.contains(&action) {+ return Err(anyhow!("unknown factory activity action"));+ }+ let timeout_ms = timeout_ms.unwrap_or(0).min(FACTIVITY_WATCH_TIMEOUT_MS_CAP);+ let request_id = uuid::Uuid::new_v4().to_string();+ let (tx, rx) = oneshot::channel();+ lock(&self.inner.guarded)+ .factory_activity_waiters+ .insert(request_id.clone(), tx);+ let frame = json!({+ "type": "factory_activity",+ "id": request_id,+ "action": action,+ "runId": run_id,+ "specId": spec_id,+ "timeoutMs": timeout_ms,+ });+ if let Err(error) = self.inner.write_line(&frame).await {+ lock(&self.inner.guarded)+ .factory_activity_waiters+ .remove(&request_id);+ return Err(error);+ }+ // The bound: a watch waits at most its declared timeout, so the+ // margin covers the executor's own settle work; every other action+ // settles inside a fixed window (run/stop/resume issue child+ // requests through the supervisor, which stay well under it).+ let bound_ms = FACTIVITY_SETTLE_TIMEOUT_MS+ + if action == "watch" {+ timeout_ms + FACTIVITY_SETTLE_TIMEOUT_MS+ } else {+ 0+ };+ let Ok(Ok(mut fields)) = tokio::time::timeout(Duration::from_millis(bound_ms), rx).await+ else {+ lock(&self.inner.guarded)+ .factory_activity_waiters+ .remove(&request_id);+ return Err(anyhow!("Kernel factory activity request did not settle"));+ };+ if let Some(object) = fields.as_object_mut() {+ object.remove("event");+ object.remove("id");+ }+ if fields.get("status").and_then(Value::as_str) != Some("ok") {+ return Err(anyhow!(+ "{}",+ fields+ .get("reason")+ .and_then(Value::as_str)+ .unwrap_or("Kernel factory activity failed")+ ));+ }+ fields+ .as_object_mut()+ .and_then(|object| object.remove("result"))+ .ok_or_else(|| anyhow!("Kernel factory activity reply carried no result"))+ }+// -------------------------------------------------------- state ops API/// Serialize the user namespace to disk (best-effort, per-variable).diff --git a/crates/pa-core/src/kernel/manager/teardown.rs b/crates/pa-core/src/kernel/manager/teardown.rsindex a174033ba2..db4bc60254 100644--- a/crates/pa-core/src/kernel/manager/teardown.rs+++ b/crates/pa-core/src/kernel/manager/teardown.rs@@ -155,6 +155,7 @@ impl Inner {g.late_handlers.clear();g.pending_done_waiters.clear();g.bash_activity_waiters.clear();+ g.factory_activity_waiters.clear();let had_background_work = !g.background_bash_handles.is_empty();g.background_bash_handles.clear();// Stale pre-teardown background output must not surface after a restart.diff --git a/crates/pa-core/src/kernel/shared.rs b/crates/pa-core/src/kernel/shared.rsindex d0f61debbb..3effdb648b 100644--- a/crates/pa-core/src/kernel/shared.rs+++ b/crates/pa-core/src/kernel/shared.rs@@ -28,6 +28,20 @@ pub const KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE: &str = "The Python kernel is stilpub const MAX_BACKGROUND_OUTPUT_CHARS: usize = 64 * 1024;pub const MAX_KERNEL_STDERR_CHARS: usize = 8 * 1024;++/// The `factory_activity` out-of-band frame's action vocabulary, mirroring+/// the kernel executor's `ACTIVITY_ACTIONS` (the `/factory` view's bridge).+pub const FACTORY_ACTIVITY_ACTIONS: [&str; 6] =+ ["graph", "status", "watch", "run", "stop", "resume"];++/// Upper bound on one `factory_activity` watch's `timeoutMs` (the kernel+/// caps its own at 60s; the host bridge pins the view's polling cadence+/// lower). Mirrors the kernel's `ACTIVITY_TIMEOUT_MS_CAP` for the preflight.+pub const FACTIVITY_WATCH_TIMEOUT_MS_CAP: u64 = 60_000;++/// Fixed settle bound for one `factory_activity` request (a watch adds its+/// own declared timeout on top, plus this margin for the executor's work).+pub const FACTIVITY_SETTLE_TIMEOUT_MS: u64 = 5_000;pub const MAX_KERNEL_STDERR_LOG_BYTES: u64 = 5 * 1024 * 1024;pub const KERNEL_STDERR_LOG_BUDGET_MARKER: &str = "[stderr log budget exhausted]\n";diff --git a/crates/pa-core/src/platform/process.rs b/crates/pa-core/src/platform/process.rsindex b033212eac..2c851918f2 100644--- a/crates/pa-core/src/platform/process.rs+++ b/crates/pa-core/src/platform/process.rs@@ -330,6 +330,7 @@ pub fn pidfd_signal(fd: i32, signal: Signal) -> bool {any(target_arch = "x86_64", target_arch = "aarch64")))))]+#[must_use]pub fn pidfd_signal(_fd: i32, _signal: Signal) -> bool {false}diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex 2c5d7502c1..2b73a2fe7b 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -163,6 +163,11 @@ pub struct SessionEngine {/// the child-observation sink (the daemon children registry) onto it/// after the build.pub rlm_usage: std::sync::Arc<super::rlm_usage::RlmChildUsageAttributions>,+ /// The factory host bridge (`/factory` view lane): the daemon/TUI+ /// request surface over the kernel's factory runs, built from the+ /// session facts captured in `create_session` (the #3184 capture+ /// pattern) and reached through [`SessionEngine::factory_activity`].+ pub factory_host: super::factory_host::FactoryHost,/// The session's kernel provisioner. The engine is the STRONG owner on/// purpose: the `ipython` tool on the agent and the compaction/// kernel-state probe on the session hold weak references, because the@@ -265,6 +270,10 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S// snapshot is fixed for the session anyway — while the `PI_REQUEST_TIMING`// env half stays live inside the wrappers' per-request check.let request_timing_settings = settings.get_request_timing();+ // Captured before `settings` moves into the resource loader: the+ // factory host bridge's preflight facts (the daemon `allowedModels`+ // pin), like the request-timing snapshot above.+ let factory_allowed_models = settings.get_allowed_models();let (mcp_skill_overrides, mcp_generic_servers, built_manager) =mcp_gating(&settings, config.agent_dir.clone()).await?;let mcp_manager = config@@ -547,6 +556,11 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S},);+ // Captured before the digest context moves the local harness dir and+ // the loop wiring moves the session model: the factory host bridge's+ // config (the #3184 capture pattern).+ let factory_local_harness_dir = local_harness_dir.clone();+ let factory_session_model = Some(model.clone());// Harness digest inputs: global state from the agent dir, local state// from the session artifacts (or the daemon-owned conversation log), and// the interfaces the digest may reference.@@ -841,6 +855,20 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Swiring.rlm_usage.set_telemetry(telemetry.clone());}let goal_driver = wiring.runtime.goal_driver().clone();+ // The factory host bridge: registered from `create_session` (the #3184+ // pattern), so the daemon/TUI factory surface resolves against this+ // session's harness dirs, model registry, and the allowlist pin. The+ // kernel owns the runs; the bridge prefights and tunnels. Captured+ // before the loop wiring moves the session model and the digest moves+ // the local harness dir.+ let factory_host =+ super::factory_host::FactoryHost::new(super::factory_host::FactoryHostConfig {+ agent_dir: config.agent_dir.clone(),+ global_harness_dir: crate::refinement::get_global_harness_state_dir(&config.agent_dir),+ local_harness_dir: factory_local_harness_dir,+ session_model: factory_session_model,+ allowed_models: factory_allowed_models,+ });Ok(SessionEngine {session,skills: resources.skills,@@ -854,6 +882,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Sturn_boundary,telemetry,rlm_usage: wiring.rlm_usage,+ factory_host,provisioner,})}@@ -948,6 +977,59 @@ impl SessionEngine {.await;}+ /// One factory activity over this session's live kernel: the `/factory`+ /// view's bridge lane (graph/status/watch/run/stop/resume). A `run`+ /// prefights the spec's declared models first (allowlist pin, request+ /// auth) so a doomed run fails before any child spawns; then the+ /// out-of-band frame carries the request into the kernel's executor,+ /// which owns the run registry.+ ///+ /// # Errors+ ///+ /// Returns an error when the arguments are invalid, the preflight+ /// fails, the session has no running kernel, or the kernel request+ /// fails or does not settle.+ pub async fn factory_activity(+ &self,+ action: &str,+ run_id: Option<&str>,+ spec_id: Option<&str>,+ timeout_ms: Option<u64>,+ ) -> anyhow::Result<serde_json::Value> {+ let request = super::factory_host::FactoryActivityRequest::parse(+ action, run_id, spec_id, timeout_ms,+ )?;+ if request.action == "run" {+ let spec_id = request+ .spec_id+ .as_deref()+ .ok_or_else(|| anyhow::anyhow!("factory activity run requires specId"))?;+ // The preflight reads the harness states, the model catalog,+ // and the auth caches from disk — blocking work off the+ // executor (the daemon's established settings-read posture:+ // `spawn_blocking`, never the async lane), so a stalled+ // filesystem can never stall the worker's other activity.+ let host = self.factory_host.clone();+ let spec_id = spec_id.to_string();+ let preflight = tokio::task::spawn_blocking(move || host.preflight_run(&spec_id))+ .await+ .map_err(|join| anyhow::anyhow!("factory run preflight join failed: {join}"))?;+ preflight?;+ }+ let manager = self+ .provisioner+ .manager()+ .ok_or_else(|| anyhow::anyhow!("Kernel is not running"))?;+ manager+ .factory_activity(+ request.action,+ request.run_id.as_deref(),+ request.spec_id.as_deref(),+ request.timeout_ms,+ )+ .await+ }+/// Out-of-band kernel bash activity, scoped to this session's live kernel.////// # Errorsdiff --git a/crates/pa-core/src/session_engine/factory_host.rs b/crates/pa-core/src/session_engine/factory_host.rsnew file mode 100644index 0000000000..c3e12f0fd1--- /dev/null+++ b/crates/pa-core/src/session_engine/factory_host.rs@@ -0,0 +1,466 @@+//! The factory host bridge: the session seam that exposes the kernel's+//! factory surface (`factory.graph/status/watch/run/stop/resume`) to the+//! daemon and TUI, the `/factory` view's lane.+//!+//! The factory itself lives in the kernel (`rlm/factory.py`, the Rust port's+//! Python kernel architecture — the executor owns the run registry in kernel+//! memory), so this bridge is host->kernel: the session engine validates the+//! request, prefights a `run` before any child spawns, and rides the+//! out-of-band `factory_activity` kernel frame (the `bash_activity`+//! precedent — a running cell never delays the live view).+//!+//! The module follows the `system_router_host` pattern from #3184: a config+//! struct of session facts captured in `create_session` (the daemon model+//! allowlist pin, the session model), a registry-backed model preflight+//! (exact catalog match, TS short form, the stale-provider gate) that fails+//! loudly before a run starts, and a unit battery in the child module. The+//! direction differs by design: #3184 registers a kernel->host handler, while+//! the factory bridge serves daemon/TUI->kernel requests through+//! [`SessionEngine::factory_activity`]; the executor's own children ride the+//! existing `rlm.spawn` host path, where the daemon allowlist pin is+//! enforced per spawn.++use std::path::PathBuf;++use anyhow::anyhow;+use serde_json::Value;++use crate::kernel::shared::{FACTIVITY_WATCH_TIMEOUT_MS_CAP, FACTORY_ACTIVITY_ACTIONS};+use crate::models::registry::ModelRegistry;+use crate::models::resolver::find_exact_model_reference_match;+use pa_types::ai::Model as AiModel;++/// The session facts the factory bridge resolves against, captured in+/// `create_session` (the #3184 `SystemRouterHostConfig` capture shape).+#[derive(Clone)]+pub struct FactoryHostConfig {+ /// The agent directory: the model registry and auth cache resolve+ /// against it (the `run` preflight's model resolution).+ pub agent_dir: PathBuf,+ /// The global harness state directory (factory spec lookup).+ pub global_harness_dir: PathBuf,+ /// The session's local harness state directory, when it has one+ /// (depth-0 daemon sessions; `None` for engines without artifacts).+ pub local_harness_dir: Option<PathBuf>,+ /// The session model (the agent-side descriptor `create_session`+ /// requires): the declared-selector preflight's stale-provider gate and+ /// the equality fallback for a selector the catalog does not carry (the+ /// spawn path owns the full resolution). The descriptor is lossy by+ /// design, so the preflight crosses it back to the ai side field by+ /// field for the auth check (the #3184 field mapping).+ pub session_model: Option<pa_agent::types::Model>,+ /// The daemon `allowedModels` pin, enforced on every resolved model the+ /// preflight accepts (the per-spawn enforcement stays on the+ /// `rlm.spawn` host path).+ pub allowed_models: Option<Vec<String>>,+}++/// The factory host bridge built from [`FactoryHostConfig`]; held by the+/// session engine, reached through [`SessionEngine::factory_activity`].+#[derive(Clone)]+pub struct FactoryHost {+ config: FactoryHostConfig,+}++impl FactoryHost {+ #[must_use]+ pub fn new(config: FactoryHostConfig) -> Self {+ Self { config }+ }++ /// The global harness state (factory spec lookup's fallback tier).+ fn global_harness_state(&self) -> crate::refinement::HarnessState {+ crate::refinement::load_harness_state(+ &self.config.global_harness_dir,+ crate::refinement::HarnessScope::Global,+ )+ }++ /// The local harness state, when the session has one (the lookup's+ /// first tier, exactly like the kernel harness's unprefixed `get`).+ fn local_harness_state(&self) -> Option<crate::refinement::HarnessState> {+ self.config.local_harness_dir.as_ref().map(|dir| {+ crate::refinement::load_harness_state(dir, crate::refinement::HarnessScope::Local)+ })+ }++ /// Every model selector a stored factory spec declares: an inline+ /// subagent object's `model`, or a referenced harness subagent entry's+ /// `metadata.model`. `None` when the spec is not readable here (the+ /// kernel's `run()` remains the authority and reports unknown specs).+ /// Ids carry the harness's scope prefixes (`local:`/`global:`) verbatim+ /// — the kernel's harness `get` routes them to one store, so the+ /// preflight resolves the exact entry the run will execute. An+ /// unprefixed id resolves local state first, then global — broader+ /// than the kernel's own unprefixed lookup, which reads one store+ /// (a spec stored only globally is an unknown spec to the kernel),+ /// so a global fall-through judges a run the kernel would refuse;+ /// harmless, and the kernel's `run()` remains the authority.+ fn spec_model_selectors(&self, spec_id: &str) -> Option<Vec<String>> {+ let (spec_scope, spec_id) = split_harness_scope(spec_id);+ let global = self.global_harness_state();+ let local = self.local_harness_state();+ let entry = match spec_scope {+ Scope::Local => local+ .as_ref()?+ .entries+ .get(&crate::refinement::RefinementKind::Factory)+ .and_then(|entries| entries.get(spec_id)),+ Scope::Global => global+ .entries+ .get(&crate::refinement::RefinementKind::Factory)+ .and_then(|entries| entries.get(spec_id)),+ Scope::Any => local+ .as_ref()+ .and_then(|state| {+ state+ .entries+ .get(&crate::refinement::RefinementKind::Factory)+ .and_then(|entries| entries.get(spec_id))+ })+ .or_else(|| {+ global+ .entries+ .get(&crate::refinement::RefinementKind::Factory)+ .and_then(|entries| entries.get(spec_id))+ }),+ }?;+ // JSON null is absent, the read every settled seam makes+ // (`refinement::planner`'s dag/machine reads, the kernel's Python+ // writers): a stored `"machine": null` beside a `dag` is the dag+ // form. `Value::Null` is `Some` here without the filter, so the+ // fall-through never reached the `dag` and the preflight read "no+ // declared models" — exempting the dag's selectors from the+ // allowlist and auth checks.+ let arguments = entry+ .arguments+ .get("machine")+ .filter(|value| !value.is_null())+ .or_else(|| entry.arguments.get("dag").filter(|value| !value.is_null()))?;+ let Some(argument_object) = arguments.as_object() else {+ return Some(Vec::new());+ };+ let states = argument_object+ .get("states")+ .or_else(|| argument_object.get("nodes"))?+ .as_array()?;+ let mut subagents: Vec<(Scope, crate::refinement::HarnessEntry)> = Vec::new();+ if let Some(local) = &local {+ if let Some(entries) = local+ .entries+ .get(&crate::refinement::RefinementKind::Subagent)+ {+ for entry in entries.values() {+ subagents.push((Scope::Local, entry.clone()));+ }+ }+ }+ if let Some(entries) = global+ .entries+ .get(&crate::refinement::RefinementKind::Subagent)+ {+ for entry in entries.values() {+ subagents.push((Scope::Global, entry.clone()));+ }+ }+ let mut selectors: Vec<String> = Vec::new();+ for state in states {+ let Some(subagent) = state.get("subagent") else {+ continue;+ };+ let model = if let Some(inline) = subagent.as_object() {+ inline.get("model").and_then(Value::as_str)+ } else {+ // A harness subagent reference: the metadata carries the+ // spawn settings (the kernel resolves the same way). An+ // unreadable reference (a non-string value, or a name no+ // harness entry carries) is the kernel's own `run()`+ // error, not the preflight's (this read stays+ // best-effort): skip the state, never the whole spec —+ // one unresolved reference must not exempt the other+ // states' declared models from the preflight. A scoped+ // reference (`local:`/`global:`) resolves its own+ // store's entry, exactly like the kernel's harness get.+ //+ // The match order is the kernel's own resolution, tier+ // by tier: the id, then the title, within a tier before+ // the next tier (its harness `get` answers the id before+ // the title scan, and the local store is the+ // unprefixed tier). A global id must not shadow a local+ // title — the old id-first sweep matched the global id+ // while the kernel spawned the local titled subagent,+ // validating (and allowlisting) the wrong model. Among+ // duplicate titles within a tier, the kernel's title+ // scan reads `harness.list`, sorted by (kind, path,+ // title, id), so it picks the (path, id)-least entry —+ // the preflight must pick the same one, not whichever+ // entry the store's map iteration happens to offer.+ let Some(reference) = subagent.as_str() else {+ continue;+ };+ let (reference_scope, reference) = split_harness_scope(reference);+ let allows = |scope: Scope| match reference_scope {+ Scope::Any => true,+ other => other == scope,+ };+ let id_in_tier = |tier: Scope| {+ subagents.iter().find(|(scope, candidate)| {+ *scope == tier && allows(*scope) && candidate.id == reference+ })+ };+ let title_in_tier = |tier: Scope| {+ subagents+ .iter()+ .filter(|(scope, candidate)| {+ *scope == tier && allows(*scope) && candidate.title == reference+ })+ .min_by(|a, b| (&a.1.path, &a.1.id).cmp(&(&b.1.path, &b.1.id)))+ };+ [Scope::Local, Scope::Global]+ .into_iter()+ .filter(|tier| allows(*tier))+ .find_map(|tier| id_in_tier(tier).or_else(|| title_in_tier(tier)))+ .and_then(|(_, entry)| entry.metadata.get("model"))+ .and_then(Value::as_str)+ };+ if let Some(model) = model.filter(|model| !model.trim().is_empty()) {+ let model = model.trim().to_string();+ if !selectors.contains(&model) {+ selectors.push(model);+ }+ }+ }+ Some(selectors)+ }++ /// Preflight one `factory run` from the daemon/TUI lane: every model+ /// selector the spec declares must resolve through the credential-backed+ /// catalog, sit inside the daemon allowlist pin, and carry request auth+ /// — a doomed run fails before any child spawns (the #3184 auth+ /// preflight's factory analogue). States without a declared model ride+ /// the existing spawn-path default chain (resolved per spawn); a spec+ /// this host cannot read passes through to the kernel's own `run()`+ /// validation.+ ///+ /// # Errors+ ///+ /// Returns an error when a declared selector is unavailable,+ /// unauthenticated, or expired, sits outside the allowlist pin, or its+ /// provider credentials are stale.+ pub fn preflight_run(&self, spec_id: &str) -> anyhow::Result<()> {+ let Some(selectors) = self.spec_model_selectors(spec_id) else {+ return Ok(());+ };+ let mut registry = ModelRegistry::create(+ crate::auth::AuthStorage::create(&self.config.agent_dir),+ self.config.agent_dir.join("models.json"),+ );+ registry.load_private_authorization_from_cache();+ let searchable: Vec<AiModel> = registry+ .get_rlm_searchable_models()+ .into_iter()+ .cloned()+ .collect();+ for selector in selectors {+ let model = resolve_declared_model(&searchable, &selector)+ .or_else(|| self.session_model_fallback(®istry, &selector))+ .ok_or_else(|| unavailable_error(&selector))?;+ if let Some(allowlist) = &self.config.allowed_models {+ let pinned = format!("{}/{}", model.provider, model.id).to_lowercase();+ if !crate::models::model_allowed(&pinned, allowlist) {+ anyhow::bail!(+ "Requested factory model \"{pinned}\" is blocked by the model allowlist"+ );+ }+ }+ let resolved = registry.get_api_key_and_headers(&model, model.headers.as_ref());+ if !resolved.ok {+ anyhow::bail!(+ "Model \"{}/{}\" is not authenticated: {}",+ model.provider,+ model.id,+ resolved.error.as_deref().unwrap_or("no credential found")+ );+ }+ }+ Ok(())+ }++ /// A declared selector naming the session's own model the catalog does+ /// not carry (a scripted or in-memory model): the spawn path resolves+ /// it, so the preflight gates only the stale/expired provider — the+ /// #3184 session-model fallback gate.+ fn session_model_fallback(&self, registry: &ModelRegistry, selector: &str) -> Option<AiModel> {+ let session_model = self.config.session_model.as_ref()?;+ let session_selector = format!("{}/{}", session_model.provider, session_model.id);+ let matches = selector.trim().eq_ignore_ascii_case(&session_selector)+ || is_short_form_selector(selector, &session_selector);+ if !matches {+ return None;+ }+ let status = registry.get_provider_auth_status(&session_model.provider);+ if status.source != Some(crate::auth::types::AuthSource::Stale)+ && status.label.as_deref() != Some("expired")+ {+ return Some(agent_model_to_ai_model(session_model));+ }+ None+ }+}++/// The ai-side view of the session's agent-side model descriptor, for the+/// preflight's allowlist and auth checks only. The two `Model`s do not+/// share a wire shape (the agent side serializes `base_url`, never carries+/// `input`), and the descriptor is lossy by design (no input modalities,+/// thinking-level map, featured flag, request headers, or compat+/// overrides), so full resolution stays with the catalog and the spawn+/// path (the #3184 `provider_adapter::agent_model_to_ai_model` field+/// mapping).+fn agent_model_to_ai_model(model: &pa_agent::types::Model) -> AiModel {+ AiModel {+ id: model.id.clone(),+ name: model.name.clone(),+ api: model.api.clone(),+ provider: model.provider.clone(),+ base_url: model.base_url.clone(),+ reasoning: model.reasoning,+ thinking_level_map: None,+ input: Vec::new(),+ cost: pa_types::ai::ModelCost {+ input: model.cost.input.into(),+ output: model.cost.output.into(),+ cache_read: model.cost.cache_read.into(),+ cache_write: model.cost.cache_write.into(),+ },+ context_window: model.context_window,+ max_tokens: model.max_tokens,+ featured: None,+ headers: None,+ compat: None,+ }+}++/// The exact catalog match over the searchable set, then the TS short form+/// (`_resolveRlmSubagentModel`'s unique-suffix rule): a bare id resolves+/// only while it names exactly one model.+fn resolve_declared_model(searchable: &[AiModel], selector: &str) -> Option<AiModel> {+ if let Some(model) = find_exact_model_reference_match(selector, searchable) {+ return Some(model.clone());+ }+ let short_form: Vec<&AiModel> = searchable+ .iter()+ .filter(|model| {+ is_short_form_selector(selector, &format!("{}/{}", model.provider, model.id))+ })+ .collect();+ match short_form.len() {+ 1 => Some(short_form[0].clone()),+ _ => None,+ }+}++/// The TS short form: a reference names a model when the full selector ends+/// with `"/<reference>"`, so a bare id like "glm-5.3" also matches+/// "prime-inference/z-ai/glm-5.3".+fn is_short_form_selector(reference: &str, selector: &str) -> bool {+ let normalized = reference.trim().to_lowercase();+ !normalized.is_empty() && selector.to_lowercase().ends_with(&format!("/{normalized}"))+}++/// The unavailable-model refusal (the TS `formatRlmModelUnavailableError`+/// base wording).+fn unavailable_error(reference: &str) -> anyhow::Error {+ anyhow!(+ "Requested factory model \"{reference}\" is unavailable, unauthenticated, or expired; selectors use the form \"provider/model-id\" (e.g. \"prime-inference/internal/glm-5.3-fast\")"+ )+}++/// One harness store a scoped id routes to (`local:`/`global:` prefixes;+/// unprefixed ids resolve either, local first).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Scope {+ Any,+ Local,+ Global,+}++/// Split the harness's scope prefix off an id, mirroring the kernel+/// harness's `_strip_scope_prefix`: `local:x`/`global:x` route to one+/// store (`x` must be non-empty, or the prefix stays part of the id),+/// anything else is unprefixed.+fn split_harness_scope(id: &str) -> (Scope, &str) {+ if let Some(rest) = id.strip_prefix("local:") {+ if !rest.is_empty() {+ return (Scope::Local, rest);+ }+ }+ if let Some(rest) = id.strip_prefix("global:") {+ if !rest.is_empty() {+ return (Scope::Global, rest);+ }+ }+ (Scope::Any, id)+}++/// The out-of-band request the bridge sends into the kernel, validated+/// host-side before the frame: one action with its target and the watch+/// bound.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FactoryActivityRequest {+ pub action: &'static str,+ pub run_id: Option<String>,+ pub spec_id: Option<String>,+ pub timeout_ms: Option<u64>,+}++impl FactoryActivityRequest {+ /// Parse and validate one daemon command payload. Mirrors the kernel+ /// frame's own validation (the kernel re-validates): a known action,+ /// string targets when present, and a bounded watch timeout.+ ///+ /// # Errors+ ///+ /// Returns an error when the action is unknown, a required target is+ /// missing, or the timeout is outside its bounds.+ pub fn parse(+ action: &str,+ run_id: Option<&str>,+ spec_id: Option<&str>,+ timeout_ms: Option<u64>,+ ) -> anyhow::Result<Self> {+ let Some(action) = FACTORY_ACTIVITY_ACTIONS+ .iter()+ .find(|known| **known == action)+ .copied()+ else {+ return Err(anyhow!("unknown factory activity action"));+ };+ if action == "run" && spec_id.is_none_or(|id| id.trim().is_empty()) {+ return Err(anyhow!("factory activity run requires specId"));+ }+ if action != "graph" && action != "run" && run_id.is_none_or(|id| id.trim().is_empty()) {+ return Err(anyhow!("factory activity {action} requires runId"));+ }+ if let Some(timeout_ms) = timeout_ms {+ if timeout_ms > FACTIVITY_WATCH_TIMEOUT_MS_CAP {+ return Err(anyhow!(+ "factory activity timeoutMs must be at most {FACTIVITY_WATCH_TIMEOUT_MS_CAP}"+ ));+ }+ }+ Ok(Self {+ action,+ run_id: run_id+ .filter(|id| !id.trim().is_empty())+ .map(str::to_string),+ spec_id: spec_id+ .filter(|id| !id.trim().is_empty())+ .map(str::to_string),+ timeout_ms,+ })+ }+}++// The unit battery lives in the child module (factory_host::tests).+#[cfg(test)]+mod tests;diff --git a/crates/pa-core/src/session_engine/factory_host/tests.rs b/crates/pa-core/src/session_engine/factory_host/tests.rsnew file mode 100644index 0000000000..1ff4fd826f--- /dev/null+++ b/crates/pa-core/src/session_engine/factory_host/tests.rs@@ -0,0 +1,714 @@+//! The factory host bridge battery: the declared-selector extraction, the+//! `run` preflight (catalog resolution, the allowlist pin, request auth, the+//! session-model fallback), and the request validation (#3184 battery+//! style).++use std::path::Path;++use serde_json::{json, Map};++use crate::refinement::{empty_harness_state, save_harness_state, HarnessEntry, RefinementKind};++use super::{FactoryActivityRequest, FactoryHost, FactoryHostConfig};++const MODELS_JSON: &str = r#"{+ "providers": {+ "testprov": {+ "baseUrl": "http://localhost:9",+ "apiKey": "bridge-key",+ "api": "openai-completions",+ "models": [+ { "id": "declared-model", "name": "Declared Model", "contextWindow": 128000 },+ { "id": "shared-id", "name": "Shared One", "contextWindow": 128000 },+ { "id": "other-model", "name": "Other Model", "contextWindow": 128000 }+ ]+ },+ "otherprov": {+ "baseUrl": "http://localhost:10",+ "apiKey": "other-key",+ "api": "openai-completions",+ "models": [+ { "id": "shared-id", "name": "Shared Two", "contextWindow": 128000 }+ ]+ },+ }+}"#;++fn write_catalog(dir: &Path) {+ std::fs::create_dir_all(dir).unwrap();+ std::fs::write(dir.join("models.json"), MODELS_JSON).unwrap();+}++fn session_model() -> pa_agent::types::Model {+ serde_json::from_value(json!({+ "id": "session-model", "name": "Session Model", "api": "openai-completions",+ "provider": "testprov", "base_url": "http://localhost:9", "reasoning": false,+ "cost": { "input": 1.5, "output": 2.5, "cacheRead": 0, "cacheWrite": 0 },+ "contextWindow": 128_000, "maxTokens": 4096+ }))+ .unwrap()+}++fn harness_entry(id: &str, kind: RefinementKind, arguments: &serde_json::Value) -> HarnessEntry {+ let reference = Map::new();+ let mut metadata = Map::new();+ if kind == RefinementKind::Subagent {+ metadata.insert("model".to_string(), json!("testprov/declared-model"));+ }+ HarnessEntry {+ id: id.to_string(),+ kind,+ title: id.to_string(),+ content: "content".to_string(),+ path: String::new(),+ scope: None,+ reference,+ arguments: arguments.as_object().cloned().unwrap_or_default(),+ metadata,+ source: "test".to_string(),+ created_at: "2026-01-01T00:00:00Z".to_string(),+ updated_at: "2026-01-01T00:00:00Z".to_string(),+ version: 1,+ }+}++/// Write one harness state file: global entries in `agent_dir/harness`, an+/// optional local overlay in `<dir>/local`.+fn write_harness_state(+ agent_dir: &Path,+ global_entries: &[HarnessEntry],+ local_entries: &[HarnessEntry],+) {+ let global_dir = crate::refinement::get_global_harness_state_dir(agent_dir);+ let mut global = empty_harness_state();+ global.schema = 1;+ for entry in global_entries {+ global+ .entries+ .get_mut(&entry.kind)+ .unwrap()+ .insert(entry.id.clone(), entry.clone());+ }+ save_harness_state(&global_dir, &global).unwrap();+ if !local_entries.is_empty() {+ let local_dir = agent_dir.join("local-harness");+ let mut local = empty_harness_state();+ local.schema = 1;+ for entry in local_entries {+ local+ .entries+ .get_mut(&entry.kind)+ .unwrap()+ .insert(entry.id.clone(), entry.clone());+ }+ save_harness_state(&local_dir, &local).unwrap();+ }+}++fn factory_entry(spec_id: &str, spec: &serde_json::Value) -> HarnessEntry {+ harness_entry(spec_id, RefinementKind::Factory, spec)+}++/// One factory entry's on-disk shape: the spec rides under `machine` (the+/// dag sugar under `dag`), exactly like `create_factory` stores it.+fn machine_entry(spec_id: &str, spec: &serde_json::Value) -> HarnessEntry {+ factory_entry(spec_id, &json!({ "machine": spec }))+}++fn dag_entry(spec_id: &str, spec: &serde_json::Value) -> HarnessEntry {+ factory_entry(spec_id, &json!({ "dag": spec }))+}++fn inline_machine(model: &str) -> serde_json::Value {+ json!({+ "run": { "max_parallel": 2 },+ "states": [+ { "id": "research", "entry": true,+ "subagent": { "prompt": "Do the work.", "model": model } }+ ]+ })+}++fn host(+ dir: &Path,+ session_model: Option<pa_agent::types::Model>,+ allowed_models: Option<Vec<String>>,+ local: bool,+) -> FactoryHost {+ FactoryHost::new(FactoryHostConfig {+ agent_dir: dir.to_path_buf(),+ global_harness_dir: crate::refinement::get_global_harness_state_dir(dir),+ local_harness_dir: local.then(|| dir.join("local-harness")),+ session_model,+ allowed_models,+ })+}++/// The declared selectors: an inline subagent object's `model`, and a+/// referenced harness subagent entry's `metadata.model`, from both spec+/// forms, deduped.++#[test]+fn declared_model_selectors_cover_both_subagent_forms_and_spec_forms() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ harness_entry("researcher", RefinementKind::Subagent, &json!({})),+ machine_entry(+ "inline",+ &json!({+ "states": [+ { "id": "a", "entry": true,+ "subagent": { "prompt": "p", "model": "testprov/declared-model" } },+ { "id": "b", "subagent": { "prompt": "p" } }+ ]+ }),+ ),+ machine_entry(+ "byref",+ &json!({+ "states": [{ "id": "a", "entry": true, "subagent": "researcher" }]+ }),+ ),+ dag_entry(+ "dag",+ &json!({+ "nodes": [+ { "id": "a", "subagent": "researcher" },+ { "id": "b", "subagent": { "prompt": "p", "model": "otherprov/shared-id" } }+ ]+ }),+ ),+ ],+ &[],+ );+ let bridge = host(dir.path(), None, None, false);+ assert_eq!(+ bridge.spec_model_selectors("inline").unwrap(),+ vec!["testprov/declared-model".to_string()]+ );+ assert_eq!(+ bridge.spec_model_selectors("byref").unwrap(),+ vec!["testprov/declared-model".to_string()]+ );+ assert_eq!(+ bridge.spec_model_selectors("dag").unwrap(),+ vec![+ "testprov/declared-model".to_string(),+ "otherprov/shared-id".to_string()+ ]+ );+ // An unknown spec reads as None: the preflight passes through (the+ // kernel's own `run()` reports unknown specs).+ assert!(bridge.spec_model_selectors("missing").is_none());+}++/// A stored `"machine": null` beside a `dag` is the dag form — the+/// null-is-absent read every settled seam makes — so the preflight must+/// fall through to the dag's declared models, never read the null as an+/// empty machine (which exempted the dag's inline model selections from+/// the allowlist and auth checks before any child spawned).+#[test]+fn a_null_machine_falls_through_to_the_dag_spec() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ // The poisoned shape only the /refine writer can store: the+ // kernel's Python `create_factory` writes exactly one of the+ // two keys; the planner's null-is-absent validation accepts+ // the dag form with an explicit null machine.+ factory_entry(+ "swept",+ &json!({+ "dag": {+ "nodes": [+ { "id": "a",+ "subagent": { "prompt": "p", "model": "testprov/declared-model" } }+ ]+ },+ "machine": serde_json::Value::Null,+ }),+ ),+ // The bare null-dag mirror: the machine form wins, the null+ // dag must not shadow it.+ factory_entry(+ "machined",+ &json!({+ "machine": {+ "states": [+ { "id": "a", "entry": true,+ "subagent": { "prompt": "p", "model": "testprov/declared-model" } }+ ]+ },+ "dag": serde_json::Value::Null,+ }),+ ),+ ],+ &[],+ );+ let bridge = host(dir.path(), None, None, false);+ assert_eq!(+ bridge.spec_model_selectors("swept").unwrap(),+ vec!["testprov/declared-model".to_string()],+ "the null machine falls through to the dag's declared models"+ );+ assert_eq!(+ bridge.spec_model_selectors("machined").unwrap(),+ vec!["testprov/declared-model".to_string()],+ "the null dag never shadows the machine form"+ );+ // End to end: the allowlist blocks the dag's declared model, so the+ // preflight must refuse the run (before the fix the read answered no+ // declared models and the preflight passed).+ let gated = host(+ dir.path(),+ None,+ Some(vec!["otherprov/allowed".to_string()]),+ false,+ );+ let refused = gated.preflight_run("swept");+ assert!(+ refused.is_err(),+ "the allowlist gate sees the dag form's declared model: {refused:?}"+ );+}++/// One subagent entry with an explicit title and model (the shared+/// helper hard-codes both to the id).+fn titled_subagent(id: &str, title: &str, model: &str) -> HarnessEntry {+ let mut metadata = Map::new();+ metadata.insert("model".to_string(), json!(model));+ HarnessEntry {+ id: id.to_string(),+ kind: RefinementKind::Subagent,+ title: title.to_string(),+ content: "Do the work.".to_string(),+ path: String::new(),+ scope: None,+ reference: Map::new(),+ arguments: Map::new(),+ metadata,+ source: "test".to_string(),+ created_at: "2026-01-01T00:00:00Z".to_string(),+ updated_at: "2026-01-01T00:00:00Z".to_string(),+ version: 1,+ }+}++/// The kernel's own resolution order, tier by tier — the id, then the+/// title, within a tier before the next tier — so a local TITLED+/// subagent wins over a global ID of the same name: the old id-first+/// sweep matched the global id while the kernel's harness `get` ++/// title scan spawns the local titled subagent, so the preflight+/// validated (and allowlisted) the wrong model.+#[test]+fn a_local_title_wins_over_a_global_id_of_the_same_name() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ // Global: the id "researcher", a model the allowlist would+ // happily allow while the kernel spawns another.+ &[+ titled_subagent("researcher", "g-titled", "testprov/other-model"),+ machine_entry(+ "spec",+ &json!({+ "states": [{ "id": "a", "entry": true, "subagent": "researcher" }]+ }),+ ),+ ],+ // Local: the TITLE "researcher" under a different id, the model+ // the kernel's tier order actually spawns — and the SAME spec+ // entry the run names, because the kernel's unprefixed spec+ // lookup reads one store (its harness `get` has no+ // local-then-global fall-through): a spec stored only globally+ // is an UNKNOWN SPEC to the kernel, so the run the end-to-end+ // allowlist pins judge would reject before any spawn — the+ // bypass scenario must run a spec the kernel actually accepts.+ &[+ titled_subagent("titled-researcher", "researcher", "testprov/declared-model"),+ machine_entry(+ "spec",+ &json!({+ "states": [{ "id": "a", "entry": true, "subagent": "researcher" }]+ }),+ ),+ ],+ );+ let bridge = host(dir.path(), None, None, true);+ assert_eq!(+ bridge.spec_model_selectors("spec").unwrap(),+ vec!["testprov/declared-model".to_string()],+ "the local titled subagent's model is the one the preflight reads"+ );+ // End to end, the allowlist pins the model the kernel actually+ // spawns (the local-title model): a gate that allows only the+ // global-id model must REFUSE the run — the exact bypass the old+ // id-first sweep produced, letting a blocked model spawn — and a+ // gate that allows the local-title model passes it.+ let allows_only_global_id = host(+ dir.path(),+ None,+ Some(vec!["testprov/other-model".to_string()]),+ true,+ );+ assert!(+ allows_only_global_id.preflight_run("spec").is_err(),+ "the allowlist gate must judge the model the run actually spawns"+ );+ let allows_actual = host(+ dir.path(),+ None,+ Some(vec!["testprov/declared-model".to_string()]),+ true,+ );+ assert!(+ allows_actual.preflight_run("spec").is_ok(),+ "the allowed actual model passes the gate"+ );+}++/// Among duplicate titles within a tier, the kernel's title scan reads+/// `harness.list` — sorted by (kind, path, title, id) — so it picks the+/// (path, id)-least entry; the preflight must read the same one, not+/// whichever entry the harness map's iteration order happens to offer.+#[test]+fn a_duplicate_title_resolves_the_kernel_list_order() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ let spec = json!({+ "states": [{ "id": "a", "entry": true, "subagent": "researcher" }]+ });+ write_harness_state(+ dir.path(),+ &[+ machine_entry("spec", &spec),+ // Two same-title locals; the kernel's sorted title scan picks+ // the (path, id)-least: path "", id "aaa-worker".+ titled_subagent("zzz-worker", "researcher", "testprov/other-model"),+ ],+ &[+ titled_subagent("aaa-worker", "researcher", "testprov/declared-model"),+ titled_subagent("mmm-worker", "researcher", "testprov/shared-id"),+ ],+ );+ let bridge = host(dir.path(), None, None, true);+ assert_eq!(+ bridge.spec_model_selectors("spec").unwrap(),+ vec!["testprov/declared-model".to_string()],+ "the (path, id)-least same-title entry is the one the preflight reads"+ );+}++/// The local overlay shadows the global spec by id (the merge's `local:`+/// rule keeps the shadowed global reachable under its own id).+#[test]+fn local_state_shadows_the_global_spec() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ harness_entry("researcher", RefinementKind::Subagent, &json!({})),+ machine_entry("spec", &inline_machine("testprov/other-model")),+ ],+ &[machine_entry(+ "spec",+ &inline_machine("missingprov/model-x"),+ )],+ );+ // The bridge without the local dir sees the global spec.+ let global_only = host(dir.path(), None, None, false);+ global_only.preflight_run("spec").unwrap();+ // With the local dir, the shadowed spec's unresolvable model fails+ // the preflight loudly.+ let with_local = host(dir.path(), None, None, true);+ let error = with_local.preflight_run("spec").unwrap_err().to_string();+ assert!(+ error.starts_with("Requested factory model \"missingprov/model-x\" is unavailable"),+ "{error}"+ );+}++/// An unresolvable subagent reference skips only its own state's read+/// (the kernel's `run()` owns the unknown-reference error): every other+/// state's declared models still preflight — one unknown reference must+/// not exempt a spec's declared models from the catalog, allowlist, and+/// auth checks (the mutation check on the best-effort read: the whole-spec+/// `None` read would pass both specs through untouched).+#[test]+fn an_unknown_reference_skips_only_its_own_state() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ harness_entry("researcher", RefinementKind::Subagent, &json!({})),+ machine_entry(+ "mixed",+ &json!({+ "states": [+ { "id": "ghosted", "entry": true, "subagent": "ghost" },+ { "id": "declared",+ "subagent": { "prompt": "p", "model": "missingprov/model-x" } }+ ]+ }),+ ),+ machine_entry(+ "allghost",+ &json!({ "states": [{ "id": "a", "entry": true, "subagent": "ghost" }] }),+ ),+ ],+ &[],+ );+ let bridge = host(dir.path(), None, None, false);+ // The sibling state's declared model still preflights loudly.+ assert_eq!(+ bridge.spec_model_selectors("mixed").unwrap(),+ vec!["missingprov/model-x".to_string()]+ );+ let error = bridge.preflight_run("mixed").unwrap_err().to_string();+ assert!(+ error.starts_with("Requested factory model \"missingprov/model-x\" is unavailable"),+ "{error}"+ );+ // A spec whose only reference is unknown stays best-effort clean: the+ // kernel's own `run()` owns the unknown-reference error.+ assert_eq!(+ bridge.spec_model_selectors("allghost").unwrap(),+ Vec::<String>::new()+ );+ bridge.preflight_run("allghost").unwrap();+}++/// Scoped ids (`local:`/`global:`) resolve their own store, exactly like+/// the kernel harness's `_strip_scope_prefix`: a scoped run preflights+/// against the exact entry it will execute (the mutation check: raw-map+/// lookups miss scoped ids entirely, so a scoped run would skip the+/// whole preflight).+#[test]+fn scoped_ids_preflight_their_own_store() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ harness_entry("researcher", RefinementKind::Subagent, &json!({})),+ machine_entry("global-scoped", &inline_machine("missingprov/model-x")),+ machine_entry(+ "byref-scoped",+ &json!({+ "states": [+ { "id": "a", "entry": true, "subagent": "global:researcher" }+ ]+ }),+ ),+ ],+ &[machine_entry(+ "local-scoped",+ &inline_machine("testprov/other-model"),+ )],+ );+ let bridge = host(dir.path(), None, None, true);+ // The global-scoped id preflights the GLOBAL spec's declared model.+ let error = bridge+ .preflight_run("global:global-scoped")+ .unwrap_err()+ .to_string();+ assert!(+ error.starts_with("Requested factory model \"missingprov/model-x\" is unavailable"),+ "{error}"+ );+ // The local-scoped id resolves the LOCAL store's spec.+ assert_eq!(+ bridge.spec_model_selectors("local:local-scoped").unwrap(),+ vec!["testprov/other-model".to_string()]+ );+ bridge.preflight_run("local:local-scoped").unwrap();+ // A scoped subagent reference resolves its own store's entry.+ assert_eq!(+ bridge.spec_model_selectors("byref-scoped").unwrap(),+ vec!["testprov/declared-model".to_string()],+ "the global: reference resolves the global researcher entry"+ );+}++/// The `run` preflight: a declared model resolves through the catalog+/// (exact form and the TS short form) and passes with request auth.+#[test]+fn preflight_resolves_exact_and_short_form_selectors() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ machine_entry("exact", &inline_machine("testprov/declared-model")),+ machine_entry("short", &inline_machine("declared-model")),+ machine_entry("ambiguous", &inline_machine("shared-id")),+ ],+ &[],+ );+ let bridge = host(dir.path(), None, None, false);+ bridge.preflight_run("exact").unwrap();+ bridge.preflight_run("short").unwrap();+ // A bare id naming two models stays unresolved.+ let error = bridge.preflight_run("ambiguous").unwrap_err().to_string();+ assert!(+ error.starts_with("Requested factory model \"shared-id\" is unavailable"),+ "{error}"+ );+}++/// The allowlist pin refuses a resolved declared model outside the pin,+/// exactly like the #3184 router handler.+#[test]+fn the_allowlist_pin_refuses_a_resolved_declared_model() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[machine_entry(+ "spec",+ &inline_machine("testprov/declared-model"),+ )],+ &[],+ );+ let bridge = host(dir.path(), None, Some(vec!["other/*".to_string()]), false);+ let error = bridge.preflight_run("spec").unwrap_err().to_string();+ assert_eq!(+ error,+ "Requested factory model \"testprov/declared-model\" is blocked by the model allowlist"+ );+ // A selector inside the pin resolves.+ let bridge = host(+ dir.path(),+ None,+ Some(vec!["testprov/*".to_string()]),+ false,+ );+ bridge.preflight_run("spec").unwrap();+}++/// The session-model fallback: a declared selector naming the session's own+/// model (which the catalog does not carry) passes unless its provider is+/// stale or expired — the #3184 gate.+#[test]+fn the_session_model_fallback_gates_on_the_stale_provider() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[+ machine_entry("named", &inline_machine("testprov/session-model")),+ machine_entry("foreign", &inline_machine("testprov/other-model")),+ ],+ &[],+ );+ let bridge = host(dir.path(), Some(session_model()), None, false);+ bridge.preflight_run("named").unwrap();+ // A declared selector the catalog carries never reaches the fallback.+ bridge.preflight_run("foreign").unwrap();+ // Without a session model, the catalog-miss selector fails loudly.+ let bridge = host(dir.path(), None, None, false);+ let error = bridge.preflight_run("named").unwrap_err().to_string();+ assert!(+ error.starts_with("Requested factory model \"testprov/session-model\" is unavailable"),+ "{error}"+ );+}++/// A spec whose states declare no models passes: every state rides the+/// spawn path's default chain, resolved per spawn.+#[test]+fn a_spec_without_declared_models_preflights_cleanly() {+ let dir = tempfile::tempdir().unwrap();+ write_catalog(dir.path());+ write_harness_state(+ dir.path(),+ &[machine_entry(+ "spec",+ &json!({"states": [{ "id": "a", "entry": true, "subagent": { "prompt": "p" } }]}),+ )],+ &[],+ );+ let bridge = host(dir.path(), None, None, false);+ bridge.preflight_run("spec").unwrap();+ // An unknown spec passes through: the kernel's `run()` owns the+ // unknown-spec error.+ bridge.preflight_run("missing").unwrap();+}++/// The request validation: known actions, required targets per action, and+/// the bounded watch timeout.+#[test]+fn factory_activity_requests_validate_like_the_kernel_frame() {+ let parse =+ |action: &str, run_id: Option<&str>, spec_id: Option<&str>, timeout_ms: Option<u64>| {+ FactoryActivityRequest::parse(action, run_id, spec_id, timeout_ms)+ };+ // the happy shapes+ assert_eq!(+ parse("graph", None, None, None).unwrap(),+ FactoryActivityRequest {+ action: "graph",+ run_id: None,+ spec_id: None,+ timeout_ms: None,+ }+ );+ assert_eq!(+ parse("graph", Some(" "), None, None).unwrap().run_id,+ None,+ "whitespace-only targets read as absent"+ );+ assert_eq!(+ parse("watch", Some("run-1"), None, Some(2_000))+ .unwrap()+ .timeout_ms,+ Some(2_000)+ );+ assert_eq!(+ parse("run", None, Some("spec-1"), None)+ .unwrap()+ .spec_id+ .as_deref(),+ Some("spec-1")+ );+ // unknown action+ assert_eq!(+ parse("bogus", None, None, None).unwrap_err().to_string(),+ "unknown factory activity action"+ );+ // required targets+ assert_eq!(+ parse("status", None, None, None).unwrap_err().to_string(),+ "factory activity status requires runId"+ );+ assert_eq!(+ parse("watch", None, None, None).unwrap_err().to_string(),+ "factory activity watch requires runId"+ );+ assert_eq!(+ parse("stop", None, None, None).unwrap_err().to_string(),+ "factory activity stop requires runId"+ );+ assert_eq!(+ parse("resume", None, None, None).unwrap_err().to_string(),+ "factory activity resume requires runId"+ );+ assert_eq!(+ parse("run", None, None, None).unwrap_err().to_string(),+ "factory activity run requires specId"+ );+ // the watch bound+ assert!(parse("watch", Some("r"), None, Some(60_000)).is_ok());+ let error = parse("watch", Some("r"), None, Some(60_001))+ .unwrap_err()+ .to_string();+ assert_eq!(error, "factory activity timeoutMs must be at most 60000");+}diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rsindex 7b121a73c6..405c33b9d3 100644--- a/crates/pa-core/src/session_engine/mod.rs+++ b/crates/pa-core/src/session_engine/mod.rs@@ -19,6 +19,7 @@ pub mod compaction_trace;pub mod compaction_utils;pub mod engine;pub mod error_classify;+pub mod factory_host;pub mod goal_boundary;pub mod goal_driver;pub mod harness_digest;diff --git a/crates/pa-core/src/settings/interactive_settings.rs b/crates/pa-core/src/settings/interactive_settings.rsindex 5382574158..892b70f4af 100644--- a/crates/pa-core/src/settings/interactive_settings.rs+++ b/crates/pa-core/src/settings/interactive_settings.rs@@ -354,6 +354,38 @@ impl SettingsManager {self.save_global_scope()}+ /// `factory.enabled` (the agent factory's opt-in gate): unset reads+ /// as disabled — the factory stays off until the user runs+ /// `/factory on`. The read is GLOBAL SCOPE ONLY, exactly the agent-dir+ /// document `set_factory_enabled` writes and the kernel's factory gate+ /// reads, so no project-scope override can flip the gate out from+ /// under the kernel (a project `.prime/agent/settings.json` with+ /// `factory.enabled` never diverges the daemon's lane advertisement+ /// or the client's `/factory status` from what the kernel will do).+ #[must_use]+ pub fn get_factory_enabled(&self) -> bool {+ self.global_settings()+ .factory+ .as_ref()+ .and_then(|factory| factory.enabled)+ .unwrap_or(false)+ }++ /// `factory.enabled` setter: persists the opt-in gate to the global+ /// scope (the same shared settings key the daemon's lane advertisement+ /// and the kernel's factory gate read).+ ///+ /// # Errors+ ///+ /// Returns an error when the global settings scope cannot be saved.+ pub fn set_factory_enabled(&mut self, enabled: bool) -> Result<()> {+ self.global_mut()+ .factory+ .get_or_insert_with(Default::default)+ .enabled = Some(enabled);+ self.save_global_scope()+ }+/// `enabledModels` (TS `getEnabledModels`/`setEnabledModels`): the/// persisted model-scope patterns (`None` is no filter).#[must_use]diff --git a/crates/pa-core/src/settings/load.rs b/crates/pa-core/src/settings/load.rsindex 01d554a811..45aea7b510 100644--- a/crates/pa-core/src/settings/load.rs+++ b/crates/pa-core/src/settings/load.rs@@ -27,6 +27,7 @@ const KNOWN_FIELDS: &[&str] = &["compaction","autoRefine","agentTraces",+ "factory","telemetry","branchSummary","retry",diff --git a/crates/pa-core/src/settings/manager.rs b/crates/pa-core/src/settings/manager.rsindex 1fc5f57f0e..6dc1b7f986 100644--- a/crates/pa-core/src/settings/manager.rs+++ b/crates/pa-core/src/settings/manager.rs@@ -1092,6 +1092,50 @@ mod tests {assert_eq!(manager.get_default_model(), Some("z-ai/glm-5.3"));}+ /// `factory.enabled` reads the GLOBAL scope only (the agent-dir+ /// document the kernel's factory gate and `set_factory_enabled` use):+ /// a project-scope override can never flip the gate out from under the+ /// kernel — a project `.prime/agent/settings.json` with `enabled: true`+ /// leaves the factory disabled while the global setting says nothing+ /// (Macroscope review finding: the merged read could diverge the+ /// daemon's lane advertisement and the client's `/factory status`+ /// from what the kernel would do).+ #[test]+ fn factory_enabled_reads_the_global_scope_only() {+ let dir = tempfile::tempdir().unwrap();+ let cwd = dir.path().join("cwd");+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(cwd.join(".prime/agent")).unwrap();+ std::fs::create_dir_all(&agent_dir).unwrap();+ std::fs::write(+ cwd.join(".prime/agent/settings.json"),+ r#"{ "factory": { "enabled": true } }"#,+ )+ .unwrap();++ let mut manager = SettingsManager::create(&cwd, &agent_dir);+ assert!(+ !manager.get_factory_enabled(),+ "a project-scope override never enables the gate"+ );++ manager+ .set_factory_enabled(true)+ .expect("set factory enabled");+ assert!(manager.get_factory_enabled());+ let content =+ std::fs::read_to_string(agent_dir.join("settings.json")).expect("global file");+ assert!(+ content.contains(r#""enabled": true"#),+ "the write lands in the global document the kernel gate reads: {content}"+ );++ manager+ .set_factory_enabled(false)+ .expect("set factory disabled");+ assert!(!manager.get_factory_enabled());+ }+#[test]fn reopen_keeps_the_runtime_overrides_in_the_merged_settings() {let mut manager = SettingsManager::in_memory(&Settings::default());diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rsindex b58ba6706a..d8b1d3e615 100644--- a/crates/pa-core/src/settings/types.rs+++ b/crates/pa-core/src/settings/types.rs@@ -228,6 +228,16 @@ pub struct AgentTracesSettings {pub enabled: Option<bool>,}+/// `factory` (the agent factory's opt-in gate): `factory.enabled` is+/// unset/false by default, and the `/factory on` client command persists+/// it. Both the daemon's `factory_activity` lane advertisement and the+/// kernel's factory gate read the same shared settings key.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FactorySettings {+ pub enabled: Option<bool>,+}+#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TelemetrySettings {@@ -315,6 +325,7 @@ pub struct Settings {pub compaction: Option<CompactionSettings>,pub auto_refine: Option<AutoRefineSettings>,pub agent_traces: Option<AgentTracesSettings>,+ pub factory: Option<FactorySettings>,pub telemetry: Option<TelemetrySettings>,pub branch_summary: Option<BranchSummarySettings>,pub retry: Option<RetrySettings>,diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex 90544c7b6c..97adf46ff3 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -883,6 +883,32 @@ impl AgentSessionEngine {engine.bash_activity(action, activity_id, lines).await}+ /// One factory activity over this session's kernel (the `/factory`+ /// view's lane); never builds a new session/kernel.+ ///+ /// # Errors+ ///+ /// Returns an error when no session kernel is running ("Kernel is+ /// not running"), the preflight fails, or the kernel's own factory+ /// activity call fails.+ pub async fn factory_activity(+ &self,+ action: &str,+ run_id: Option<&str>,+ spec_id: Option<&str>,+ timeout_ms: Option<u64>,+ ) -> anyhow::Result<Value> {+ let engine = self+ .session+ .lock()+ .await+ .clone()+ .ok_or_else(|| anyhow::anyhow!(pa_types::daemon::KERNEL_NOT_RUNNING_MESSAGE))?;+ engine+ .factory_activity(action, run_id, spec_id, timeout_ms)+ .await+ }+/// Build the core session once (same once-only rule as `session_agent`),/// through the same guarded funnel.pub(crate) fn ensure_core_session(&self, model: &Model) -> anyhow::Result<()> {diff --git a/crates/pa-daemon/src/boot_reap.rs b/crates/pa-daemon/src/boot_reap.rsindex 2ff28fc93e..573c8efcc9 100644--- a/crates/pa-daemon/src/boot_reap.rs+++ b/crates/pa-daemon/src/boot_reap.rs@@ -476,6 +476,7 @@ fn socket_spelling_of(pid: u32, value: &str) -> String {/// tool server) never qualifies, whatever it inherited./// Unix only: the same linux/unix callers as [`is_worker_argv`].#[cfg(unix)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]pub(crate) fn is_product_binary(exe: &str) -> bool {matches!(Path::new(exe).file_name().and_then(|name| name.to_str()),@@ -491,6 +492,7 @@ pub(crate) fn is_product_binary(exe: &str) -> bool {/// same-socket command that happens to carry a `worker` argument./// Unix only: the linux census and the unix tests are its users.#[cfg(unix)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]pub(crate) fn is_worker_argv(argv: &[String]) -> bool {argv.first().is_some_and(|exe| is_product_binary(exe))&& argv.get(1).map(String::as_str) == Some("worker")@@ -537,7 +539,12 @@ fn proc_environ_names_active_session(pid: u32, active_session: &str) -> bool {})}+/// The non-linux unix stub: the only caller is the linux worker census,+/// so it stays compiled for the signature's parity and is inert+/// everywhere else (`allow(dead_code)` is the honest parity mark — the+/// linux side owns the real read).#[cfg(all(unix, not(target_os = "linux")))]+#[allow(dead_code)]fn proc_environ_names_active_session(_pid: u32, _active_session: &str) -> bool {false}@@ -620,6 +627,7 @@ fn resolve_relative_socket_tokens(pid: u32, argv: &mut [String]) {/// compares against is the unix socket spelling, and every caller (the/// linux supervisor census, the unix tests) sits behind a unix gate.#[cfg(unix)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]pub(crate) fn supervisor_argv_names_socket(argv: &[String], socket: &str) -> bool {let Some(exe) = argv.first() else {return false;@@ -761,6 +769,7 @@ fn protected_worker_pids(agent_dir: &Path, socket_path: &Path) -> HashSet<u32> {/// darwin included, which `supervisor_argv_names_socket` (the argv-only/// view the supervisor census normalizes with) requires.#[cfg(unix)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]pub(crate) fn normalize_socket_spelling(path: &Path) -> String {if let Ok(canonical) = path.canonicalize() {return canonical.to_string_lossy().to_string();@@ -848,9 +857,12 @@ mod tests {/// Kills and reaps the child on any exit path (a failed assertion in/// between would otherwise leak the `sleep` into the test machine: the- /// std child kills nothing on drop).+ /// std child kills nothing on drop). Linux only: the guard exists for+ /// the /proc census tests, which never compile elsewhere.+ #[cfg(target_os = "linux")]struct ReapOnDrop(Option<std::process::Child>);+ #[cfg(target_os = "linux")]impl Drop for ReapOnDrop {fn drop(&mut self) {if let Some(mut child) = self.0.take() {diff --git a/crates/pa-daemon/src/factory_activity.rs b/crates/pa-daemon/src/factory_activity.rsnew file mode 100644index 0000000000..57eb172f8c--- /dev/null+++ b/crates/pa-daemon/src/factory_activity.rs@@ -0,0 +1,138 @@+//! The `factory_activity` worker arm: the `/factory` view's daemon lane.++//! One session-addressed command reaches this session's kernel factory+//! executor (the bridge registered by the pa-core session engine): the+//! payload's `action` rides the out-of-band kernel frame, and the kernel's+//! reply returns verbatim (the run registry stays kernel-owned). The+//! `run` action's model preflight (the allowlist pin, request auth)+//! happens in the session engine before the frame — a doomed run fails+//! before any child spawns.++use std::path::Path;++use serde_json::Value;++use crate::protocol::{response_failure, response_success, DaemonResponse};+use crate::worker::Worker;++/// The `factory_activity` capability's advertisement gate: the factory is+/// opt-in (`factory.enabled` in the shared settings file, default off),+/// so a disabled factory never surfaces its lane — no capability, no+/// dock group, no page. Both hello surfaces (the supervisor's and the+/// worker's) advertise the lane only while the setting reads enabled.+pub(crate) fn factory_lane_enabled(agent_dir: &Path) -> bool {+ pa_core::settings::SettingsManager::create(+ std::env::current_dir().unwrap_or_default(),+ agent_dir,+ )+ .get_factory_enabled()+}++/// The capabilities a hello advertises: the default set, minus the+/// `factory_activity` lane while the factory stays disabled (the opt-in+/// gate; the settings read is fresh per connection, so a `/factory on`+/// toggle surfaces on the next client start).+pub(crate) fn advertised_server_capabilities(agent_dir: &Path) -> Vec<String> {+ let mut capabilities = crate::protocol::default_server_capabilities();+ if !factory_lane_enabled(agent_dir) {+ capabilities.retain(|capability| capability != "factory_activity");+ }+ capabilities+}++impl Worker {+ /// `factory_activity`: one factory action over this session's kernel.+ /// The arm mirrors `handle_kernel_bash_activity`: the engine owns the+ /// kernel scope, and a missing session answers with the same "Kernel+ /// is not running" refusal.+ pub(crate) async fn handle_factory_activity(&self, payload: &Value) -> DaemonResponse {+ if let Err(response) = self.require_created("factory_activity") {+ return response;+ }+ let action = payload+ .get("action")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ if action.is_empty() {+ return response_failure(None, "factory_activity", "action is required", None);+ }+ let run_id = payload+ .get("runId")+ .and_then(Value::as_str)+ .map(str::to_string);+ let spec_id = payload+ .get("specId")+ .and_then(Value::as_str)+ .map(str::to_string);+ let timeout_ms = payload.get("timeoutMs").and_then(Value::as_u64);+ let Some(engine) = &self.agent_engine else {+ return response_failure(+ None,+ "factory_activity",+ pa_types::daemon::KERNEL_NOT_RUNNING_MESSAGE,+ None,+ );+ };+ match engine+ .factory_activity(&action, run_id.as_deref(), spec_id.as_deref(), timeout_ms)+ .await+ {+ Ok(result) => response_success(None, "factory_activity", Some(result)),+ Err(error) => response_failure(None, "factory_activity", &format!("{error:#}"), None),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The opt-in default: no settings file, no factory lane.+ #[test]+ fn the_factory_lane_stays_unadvertised_until_enabled() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");++ let disabled = advertised_server_capabilities(&agent_dir);+ assert!(+ !disabled+ .iter()+ .any(|capability| capability == "factory_activity"),+ "the default factory gate stays off: {disabled:?}"+ );++ // `/factory on` persists `factory.enabled` in the settings file —+ // the exact shared key the lane advertisement reads.+ let settings = serde_json::json!({ "factory": { "enabled": true } });+ std::fs::write(+ agent_dir.join("settings.json"),+ serde_json::to_string(&settings).expect("serialize"),+ )+ .expect("write settings");+ let enabled = advertised_server_capabilities(&agent_dir);+ assert!(+ enabled+ .iter()+ .any(|capability| capability == "factory_activity"),+ "the enabled factory advertises its lane: {enabled:?}"+ );++ // `/factory off` re-reads as disabled: the lane leaves the+ // advertisement again.+ let off = serde_json::json!({ "factory": { "enabled": false } });+ std::fs::write(+ agent_dir.join("settings.json"),+ serde_json::to_string(&off).expect("serialize"),+ )+ .expect("write settings");+ let disabled_again = advertised_server_capabilities(&agent_dir);+ assert!(+ !disabled_again+ .iter()+ .any(|capability| capability == "factory_activity"),+ "the disabled factory lane leaves the advertisement: {disabled_again:?}"+ );+ }+}diff --git a/crates/pa-daemon/src/lib.rs b/crates/pa-daemon/src/lib.rsindex f2154553db..06da59fa1c 100644--- a/crates/pa-daemon/src/lib.rs+++ b/crates/pa-daemon/src/lib.rs@@ -53,6 +53,7 @@ pub(crate) mod context_tree_children;pub(crate) mod create_reuse;pub mod descriptor;pub mod engine;+pub(crate) mod factory_activity;pub mod framing;mod goal_continuation;pub(crate) mod goal_state_persist;diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rsindex fe138ec163..a828d0cbbe 100644--- a/crates/pa-daemon/src/protocol.rs+++ b/crates/pa-daemon/src/protocol.rs@@ -320,6 +320,7 @@ pub fn default_server_capabilities() -> Vec<DaemonServerCapability> {"side_question_transcript","transient_bash","kernel_bash_activity",+ "factory_activity","session_input_admission","prompt_admission_cancellation","owned_prompt_cancellation",@@ -676,6 +677,9 @@ pub fn command_active_session_id(command: &DaemonCommand) -> Option<&str> {| DaemonCommand::CancelRlmChild {active_session_id, ..}+ | DaemonCommand::FactoryActivity {+ active_session_id, ..+ }| DaemonCommand::DeleteRlmSubagent {active_session_id, ..}@@ -970,6 +974,7 @@ pub fn command_type_name(command: &DaemonCommand) -> &'static str {DaemonCommand::TailKernelBash { .. } => "tail_kernel_bash",DaemonCommand::KillKernelBash { .. } => "kill_kernel_bash",DaemonCommand::CancelRlmChild { .. } => "cancel_rlm_child",+ DaemonCommand::FactoryActivity { .. } => "factory_activity",DaemonCommand::DeleteRlmSubagent { .. } => "delete_rlm_subagent",DaemonCommand::WaitForIdle { .. } => "wait_for_idle",DaemonCommand::WaitForHeadlessCompletion { .. } => "wait_for_headless_completion",@@ -1081,6 +1086,61 @@ mod tests {assert!(default_server_capabilities().contains(&"kernel_bash_activity".to_string()));}+ #[test]+ fn factory_activity_commands_are_session_scoped() {+ for (command, action, run_id, spec_id, timeout_ms) in [+ (+ serde_json::json!({"type":"factory_activity","activeSessionId":"session","action":"graph"}),+ "graph",+ None::<&str>,+ None::<&str>,+ None::<u64>,+ ),+ (+ serde_json::json!({"type":"factory_activity","activeSessionId":"session","action":"watch","runId":"run-1","timeoutMs":2000}),+ "watch",+ Some("run-1"),+ None,+ Some(2000),+ ),+ (+ serde_json::json!({"type":"factory_activity","activeSessionId":"session","action":"run","specId":"review-loop"}),+ "run",+ None,+ Some("review-loop"),+ None,+ ),+ (+ serde_json::json!({"type":"factory_activity","activeSessionId":"session","action":"stop","runId":"run-1"}),+ "stop",+ Some("run-1"),+ None,+ None,+ ),+ ] {+ let line = serde_json::json!({"type":"command","id":"c1", "protocol":current_protocol_info(), "command":command}).to_string();+ let parsed = parse_daemon_command_line(&line).unwrap();+ assert_eq!(command_type_name(&parsed.command), "factory_activity");+ assert_eq!(command_active_session_id(&parsed.command), Some("session"));+ match &parsed.command {+ DaemonCommand::FactoryActivity {+ action: parsed_action,+ run_id: parsed_run,+ spec_id: parsed_spec,+ timeout_ms: parsed_timeout,+ ..+ } => {+ assert_eq!(parsed_action.as_str(), action);+ assert_eq!(parsed_run.as_deref(), run_id);+ assert_eq!(parsed_spec.as_deref(), spec_id);+ assert_eq!(*parsed_timeout, timeout_ms);+ }+ _ => panic!("expected FactoryActivity"),+ }+ }+ assert!(default_server_capabilities().contains(&"factory_activity".to_string()));+ }+#[test]fn envelope_round_trips() {let line = r#"{"type":"command","id":"c1","protocol":{"name":"prime-agent.daemon","version":7},"command":{"type":"list","all":true}}"#;diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rsindex 8e0243241e..a3bff131ce 100644--- a/crates/pa-daemon/src/supervisor.rs+++ b/crates/pa-daemon/src/supervisor.rs@@ -97,9 +97,9 @@ use crate::paths;use crate::prompt_admission::input_admission_id;use crate::protocol::{command_active_session_id, command_type_name, current_protocol_info,- default_server_capabilities, parse_supervisor_command_line, response_failure, response_line,- response_success, DaemonResponse, DaemonRuntimeIdentity, EnvelopeParseError,- TypedCreateRejection, DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,+ parse_supervisor_command_line, response_failure, response_line, response_success,+ DaemonResponse, DaemonRuntimeIdentity, EnvelopeParseError, TypedCreateRejection,+ DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,};use crate::registry::{ResidentWorker, SessionRegistry, WorkerRegistration, WorkerReply, WorkerRequest,diff --git a/crates/pa-daemon/src/supervisor/clients.rs b/crates/pa-daemon/src/supervisor/clients.rsindex 15b081de62..cf81e3bf31 100644--- a/crates/pa-daemon/src/supervisor/clients.rs+++ b/crates/pa-daemon/src/supervisor/clients.rs@@ -2,13 +2,12 @@//! and the parsed-command execution surface.use super::{broadcast, command_type_name, current_protocol_info, daemon_closing_shutdown_event,- default_server_capabilities, input_admission_id, json, parse_supervisor_command_line,- response_failure, response_line, response_success, salvage_command_type, salvage_id,- subscribers, update_gate_refuses, util, Arc, AsyncBufReadExt, AsyncWriteExt, BufReader,- ClientRouting, DaemonCommand, DaemonOutbound, DaemonRuntimeIdentity, EnvelopeParseError, Map,- Ordering, Outbound, Result, RouteAdmission, Supervisor, TransportStream, TypedCreateRejection,- Value, DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION, ROUTE_TIMEOUT_MS,- UPDATE_PREPARING_MESSAGE,+ input_admission_id, json, parse_supervisor_command_line, response_failure, response_line,+ response_success, salvage_command_type, salvage_id, subscribers, update_gate_refuses, util,+ Arc, AsyncBufReadExt, AsyncWriteExt, BufReader, ClientRouting, DaemonCommand, DaemonOutbound,+ DaemonRuntimeIdentity, EnvelopeParseError, Map, Ordering, Outbound, Result, RouteAdmission,+ Supervisor, TransportStream, TypedCreateRejection, Value, DAEMON_APP_VERSION, DAEMON_SCHEMA_ID,+ DAEMON_SCHEMA_REVISION, ROUTE_TIMEOUT_MS, UPDATE_PREPARING_MESSAGE,};async fn write_line<W: AsyncWriteExt + Unpin>(writer: &mut W, value: &Value) -> Result<usize> {@@ -78,6 +77,17 @@ impl Supervisor {) -> Result<()> {let (reader, mut writer) = stream.split();let client_id = util::new_display_id();+ // The factory lane's advertisement gate reads the settings file+ // (metadata plus a locked read on a cache miss) — off the+ // executor thread, the same spawn_blocking posture as the daemon's+ // other settings reads. The read stays fresh per connection, so a+ // `/factory on` toggle surfaces on the next client start.+ let agent_dir = self.options.agent_dir.clone();+ let factory_capabilities = tokio::task::spawn_blocking(move || {+ crate::factory_activity::advertised_server_capabilities(&agent_dir)+ })+ .await+ .map_err(|error| anyhow::anyhow!("the factory settings read failed: {error:#}"))?;let hello = DaemonOutbound::DaemonHello {socket_path: self.options.socket_path.to_string_lossy().to_string(),protocol: current_protocol_info(),@@ -99,7 +109,7 @@ impl Supervisor {supervisor_socket_path: Some(self.options.socket_path.to_string_lossy().to_string()),update_resume: Some(self.restore.hello_resume()),client_id: client_id.clone(),- server_capabilities: default_server_capabilities(),+ server_capabilities: factory_capabilities,rest: Map::default(),};write_line(&mut writer, &serde_json::to_value(&hello)?).await?;diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 1c0bec0474..0f807d1a52 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -92,9 +92,9 @@ use crate::peer::{};use crate::protocol::{create_daemon_event_meta, create_daemon_replay_info, current_protocol_info,- default_client_capabilities, default_server_capabilities, normalize_client_capabilities,- response_failure, response_success, DaemonOutbound, DaemonResponse, DaemonResumeCursor,- DaemonSessionClosedReason, DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,+ default_client_capabilities, normalize_client_capabilities, response_failure, response_success,+ DaemonOutbound, DaemonResponse, DaemonResumeCursor, DaemonSessionClosedReason,+ DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,};use crate::registration::RegistrationHandle;use crate::session_store::{session_file_name, SessionFile};diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rsindex fa5d17e243..ac0cbc9fbd 100644--- a/crates/pa-daemon/src/worker/commands.rs+++ b/crates/pa-daemon/src/worker/commands.rs@@ -149,6 +149,7 @@ impl Worker {"export_jsonl" => self.exports.export_jsonl(payload),"mutate_queued_message" => self.handle_mutate_queued_message(payload),"resume_queue" => self.handle_resume_queue(),+ "factory_activity" => self.handle_factory_activity(payload).await,"execute_bash" => self.handle_execute_bash(payload),"execute_bash_and_wait" => self.handle_execute_bash_and_wait(payload).await,"abort_bash" => self.handle_abort_bash().await,diff --git a/crates/pa-daemon/src/worker/connection.rs b/crates/pa-daemon/src/worker/connection.rsindex be64e44a3b..d3d1ac2bfa 100644--- a/crates/pa-daemon/src/worker/connection.rs+++ b/crates/pa-daemon/src/worker/connection.rs@@ -293,7 +293,17 @@ impl Worker {// fan-out flush position (response writes wait on it; see// `ConnectionSink`).let sink = Arc::new(ConnectionSink::new(Arc::clone(&writer), entry_seq));- // daemon_hello goes out immediately on every connection.+ // daemon_hello goes out immediately on every connection. The+ // factory lane's advertisement gate reads the settings file+ // (metadata plus a locked read on a cache miss) — off the+ // executor thread, the same spawn_blocking posture as the+ // daemon's other settings reads, and the same fresh-per-connection+ // read the supervisor's hello does.+ let agent_dir = self.config.agent_dir.clone();+ let factory_capabilities =+ tokio::task::spawn_blocking(move || worker_server_capabilities(&agent_dir))+ .await+ .map_err(|error| anyhow::anyhow!("the factory settings read failed: {error:#}"))?;let hello = DaemonOutbound::DaemonHello {socket_path: self.config.socket_path.to_string_lossy().to_string(),protocol: current_protocol_info(),@@ -310,7 +320,7 @@ impl Worker {// supervisor owns the boot restore pass).update_resume: None,client_id: crate::util::new_display_id(),- server_capabilities: worker_server_capabilities(),+ server_capabilities: factory_capabilities,rest: Map::default(),};let hello_bytes = serde_json::to_vec(&hello)?;diff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rsindex 53543ab199..dc9d05b81d 100644--- a/crates/pa-daemon/src/worker/create.rs+++ b/crates/pa-daemon/src/worker/create.rs@@ -1,9 +1,9 @@//! Session creation and reuse on the worker: the create command's//! construction of the live session.use super::{- default_server_capabilities, json, paths, response_failure, response_success,- restore_queue_snapshot, session_file_name, Arc, EngineModelSelection, Result,- RlmSessionIdentity, SessionEngine, SessionFile, VecDeque, Worker,+ json, paths, response_failure, response_success, restore_queue_snapshot, session_file_name,+ Arc, EngineModelSelection, Result, RlmSessionIdentity, SessionEngine, SessionFile, VecDeque,+ Worker,};use serde::Deserialize as _;@@ -830,8 +830,10 @@ pub(super) fn active_session_id_of(payload: &[u8]) -> String {.unwrap_or_default()}-pub(super) fn worker_server_capabilities() -> Vec<String> {- default_server_capabilities()+pub(super) fn worker_server_capabilities(agent_dir: &std::path::Path) -> Vec<String> {+ // The factory lane advertises only while its opt-in gate reads+ // enabled (`factory.enabled`, default off).+ crate::factory_activity::advertised_server_capabilities(agent_dir)}/// RLM depth fields of a create payload: `(depth, max_depth)`. Values mustdiff --git a/crates/pa-tui/src/chrome.rs b/crates/pa-tui/src/chrome.rsindex ff7d7f9003..b3251aac21 100644--- a/crates/pa-tui/src/chrome.rs+++ b/crates/pa-tui/src/chrome.rs@@ -110,6 +110,12 @@ pub enum ActivityGroup {Subagents,Heartbeats,Bash,+ /// The factory page: live factory runs. Its group renders exactly+ /// while the daemon advertises the `factory_activity` lane (the+ /// opt-in gate; an advertised empty one reads its zero count) and+ /// opens the factory page over the lane — the same navigation family+ /// as the subagents, heartbeats, and shells pages.+ Factory,/// The active goal: its group is mounted while a goal is being/// pursued and opens the read-only goal panel (the objective and/// its facts); a goal that ended unmounts the row with it.@@ -147,6 +153,18 @@ pub struct ActivityDock {/// kernel registry only): finished runs never inflate the indicator/// — they stay as rows inside the bash view.pub bash_running: usize,+ /// Factory runs actively live right now (a live state — running,+ /// stopping, or paused — or a terminal run whose children are still+ /// in flight, the residents teardown; the current session's kernel+ /// registry only): fully terminal runs never inflate the indicator,+ /// exactly like the bash group's running-only count.+ pub factory_runs: usize,+ /// 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+ /// mounts no factory group anywhere: no row, no traversal, no+ /// click, no page.+ pub factory_group: bool,/// The active goal's dock label — `Pursuing goal (12m 05s)`-style,/// the elapsed-time form (the operator's 2026-09-24 directive: the/// row reads the time, the token budget lives inside the goal@@ -161,8 +179,9 @@ impl ActivityDock {/// The groups this dock renders, left to right — the arrow/// traversal order. The subagents, heartbeats, and shells groups/// always render (an empty one reads its zero count and stays- /// traversable); the goal group renders exactly while a live goal- /// keeps its row mounted.+ /// traversable); the factory group renders exactly while the daemon+ /// advertises the `factory_activity` lane (the opt-in gate), and the+ /// goal group exactly while a live goal keeps its row mounted.#[must_use]pub fn groups(&self) -> Vec<ActivityGroup> {let mut groups = vec![@@ -170,6 +189,9 @@ impl ActivityDock {ActivityGroup::Heartbeats,ActivityGroup::Bash,];+ if self.factory_group {+ groups.push(ActivityGroup::Factory);+ }if self.goal_label.is_some() {groups.push(ActivityGroup::Goal);}@@ -691,10 +713,10 @@ fn land_marker(out: &mut Vec<crate::Span>, width: usize) {////// The row color-codes live activity (the operator's 2026-09-24/// directive): every count-holding segment goes green while its count-/// is above zero (subagents, heartbeats, shells, the active goal) and-/// stays neutral at zero. The subagents segment is one consolidated-/// item — `◆ x subagents` (the operator's 2026-09-25 consolidation:-/// the separate running cluster was redundant).+/// is above zero (subagents, heartbeats, shells, factory, the active+/// goal) and stays neutral at zero. The subagents segment is one+/// consolidated item — `◆ x subagents` (the operator's 2026-09-25+/// consolidation: the separate running cluster was redundant).#[must_use]pub fn render_activity_dock(dock: &ActivityDock, theme: &Theme, width: usize) -> Vec<Line> {render_activity_dock_segments(dock, theme, width).0@@ -797,6 +819,13 @@ pub fn render_activity_dock_segments(if dock.bash_running == 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 => vec![theme.fg_span(+ running_color(dock.factory_runs),+ format!("⚙ {} factory", dock.factory_runs),+ )],// The goal row carries the dock's activity convention: an// actively pursued goal reads green, and the paused and// budget-limited states read amber (the paused heartbeatdiff --git a/crates/pa-tui/src/chrome/tests.rs b/crates/pa-tui/src/chrome/tests.rsindex 5e0157488e..fc578db257 100644--- a/crates/pa-tui/src/chrome/tests.rs+++ b/crates/pa-tui/src/chrome/tests.rs@@ -11,6 +11,7 @@ fn the_dock_segments_cover_each_groups_own_cells() {heartbeats: 3,heartbeats_paused: 1,bash_running: 1,+ factory_group: true,..ActivityDock::default()};let (frame, segments) = render_activity_dock_segments(&dock, &theme, 120);@@ -20,7 +21,7 @@ fn the_dock_segments_cover_each_groups_own_cells() {.collect::<String>();assert_eq!(text,- " ◆ 2 subagents · ◷ 3 heartbeats · ◐ 1 paused · ▸ 1 shell"+ " ◆ 2 subagents · ◷ 3 heartbeats · ◐ 1 paused · ▸ 1 shell · ⚙ 0 factory");let ordered: Vec<ActivityGroup> = segments.iter().map(|segment| segment.group).collect();assert_eq!(@@ -28,7 +29,8 @@ fn the_dock_segments_cover_each_groups_own_cells() {vec![ActivityGroup::Subagents,ActivityGroup::Heartbeats,- ActivityGroup::Bash+ ActivityGroup::Bash,+ ActivityGroup::Factory,],"the segments follow the row's group order");@@ -135,6 +137,7 @@ fn activity_dock_frames_one_row_with_running_paused_and_goal_counts() {heartbeats: 3,heartbeats_paused: 1,bash_running: 1,+ factory_group: true,goal_label: Some("Pursuing goal (0s)".to_string()),..ActivityDock::default()};@@ -154,7 +157,7 @@ fn activity_dock_frames_one_row_with_running_paused_and_goal_counts() {.collect::<String>();assert_eq!(text,- " ◆ 2 subagents · ◷ 3 heartbeats · ◐ 1 paused · ▸ 1 shell · Pursuing goal (0s)"+ " ◆ 2 subagents · ◷ 3 heartbeats · ◐ 1 paused · ▸ 1 shell · ⚙ 0 factory · Pursuing goal (0s)");// The color-coding (the operator's 2026-09-24 directive): every// above-zero count segment and the active goal render green.@@ -172,6 +175,7 @@ fn activity_dock_frames_one_row_with_running_paused_and_goal_counts() {// the warning color — every live goal state keeps a surface.let dock = ActivityDock {goal_label: Some("Goal paused (0s)".to_string()),+ factory_group: true,..ActivityDock::default()};let frame = render_activity_dock(&dock, &theme, 100);@@ -195,6 +199,7 @@ fn activity_dock_frames_one_row_with_running_paused_and_goal_counts() {// go neutral at zero.let dock = ActivityDock {heartbeats: 1,+ factory_group: true,..ActivityDock::default()};let frame = render_activity_dock(&dock, &theme, 100);@@ -202,17 +207,26 @@ fn activity_dock_frames_one_row_with_running_paused_and_goal_counts() {.iter().map(|span| span.content.as_str()).collect::<String>();- assert_eq!(text, " ◆ 0 subagents · ◷ 1 heartbeat · ▸ 0 shells");+ assert_eq!(+ text,+ " ◆ 0 subagents · ◷ 1 heartbeat · ▸ 0 shells · ⚙ 0 factory"+ );// The all-zero dock renders its own empty state — the zero- // readout — and the zero segments stay neutral, never green.- let frame = render_activity_dock(&ActivityDock::default(), &theme, 100);+ // readout — and the zero segments stay neutral, never green. The+ // factory lane is advertised here (the unadvertised lane's row is+ // the pin of its own).+ let advertised = ActivityDock {+ factory_group: true,+ ..ActivityDock::default()+ };+ let frame = render_activity_dock(&advertised, &theme, 100);let text = frame[1].iter().map(|span| span.content.as_str()).collect::<String>();assert_eq!(text,- " \u{25c6} 0 subagents \u{b7} \u{25f7} 0 heartbeats \u{b7} \u{25b8} 0 shells"+ " \u{25c6} 0 subagents \u{b7} \u{25f7} 0 heartbeats \u{b7} \u{25b8} 0 shells \u{b7} \u{2699} 0 factory");assert!(frame[1].iter()@@ -274,6 +288,7 @@ fn prompt_bar_subagent_segment_is_the_running_count_only() {let dock = ActivityDock {subagents_running_direct: 2,subagents_running_nested: 0,+ factory_group: true,..ActivityDock::default()};let frame = render_activity_dock(&dock, &theme, 80);@@ -281,13 +296,17 @@ fn prompt_bar_subagent_segment_is_the_running_count_only() {.iter().map(|span| span.content.as_str()).collect::<String>();- assert_eq!(text, " ◆ 2 subagents · ◷ 0 heartbeats · ▸ 0 shells");+ assert_eq!(+ text,+ " ◆ 2 subagents · ◷ 0 heartbeats · ▸ 0 shells · ⚙ 0 factory"+ );// Two running children plus seven running descendants: ONE// number — the summed total, never the pair, never the// descendant total, and no category breakdown.let dock = ActivityDock {subagents_running_direct: 2,subagents_running_nested: 7,+ factory_group: true,..ActivityDock::default()};let frame = render_activity_dock(&dock, &theme, 80);@@ -295,7 +314,10 @@ fn prompt_bar_subagent_segment_is_the_running_count_only() {.iter().map(|span| span.content.as_str()).collect::<String>();- assert_eq!(text, " ◆ 9 subagents · ◷ 0 heartbeats · ▸ 0 shells");+ assert_eq!(+ text,+ " ◆ 9 subagents · ◷ 0 heartbeats · ▸ 0 shells · ⚙ 0 factory"+ );assert!(!text.contains("2,"), "no direct/nested pair: {text}");assert!(!text.contains("idle"), "no category breakdown: {text}");assert!(@@ -306,6 +328,7 @@ fn prompt_bar_subagent_segment_is_the_running_count_only() {let dock = ActivityDock {subagents_running_direct: 0,subagents_running_nested: 1,+ factory_group: true,..ActivityDock::default()};let frame = render_activity_dock(&dock, &theme, 80);@@ -313,7 +336,10 @@ fn prompt_bar_subagent_segment_is_the_running_count_only() {.iter().map(|span| span.content.as_str()).collect::<String>();- assert_eq!(text, " ◆ 1 subagents · ◷ 0 heartbeats · ▸ 0 shells");+ assert_eq!(+ text,+ " ◆ 1 subagents · ◷ 0 heartbeats · ▸ 0 shells · ⚙ 0 factory"+ );}/// The focused dock's selection reads as the ONE shared selection@@ -331,6 +357,8 @@ fn activity_dock_selection_is_the_hover_colored_band() {heartbeats: 3,heartbeats_paused: 1,bash_running: 1,+ factory_runs: 1,+ factory_group: true,goal_label: Some("Pursuing goal (0s)".to_string()),selected: ActivityGroup::Heartbeats,focused: true,@@ -394,15 +422,20 @@ fn activity_dock_selection_is_the_hover_colored_band() {/// in both directions and N groups take exactly N presses to cycle.#[test]fn dock_arrows_visit_every_group_even_when_empty() {- // The all-zero dock: the heartbeats and shells groups are empty- // and stay in the cycle.- let dock = ActivityDock::default();+ // The all-zero dock with the factory lane advertised: the+ // heartbeats, shells, and factory groups are empty and stay in+ // the cycle.+ let dock = ActivityDock {+ factory_group: true,+ ..ActivityDock::default()+ };assert_eq!(dock.groups(),vec![ActivityGroup::Subagents,ActivityGroup::Heartbeats,ActivityGroup::Bash,+ ActivityGroup::Factory,]);// Right: the neighbors in order, the empty groups included,@@ -417,15 +450,23 @@ fn dock_arrows_visit_every_group_even_when_empty() {);assert_eq!(dock.step(ActivityGroup::Bash, ActivityDirection::Next),+ ActivityGroup::Factory+ );+ assert_eq!(+ dock.step(ActivityGroup::Factory, ActivityDirection::Next),ActivityGroup::Subagents,"the cycle wraps past the last group");// Left: the same groups in reverse, wrapping past the first.assert_eq!(dock.step(ActivityGroup::Subagents, ActivityDirection::Prev),- ActivityGroup::Bash,+ ActivityGroup::Factory,"the cycle wraps past the first group");+ assert_eq!(+ dock.step(ActivityGroup::Factory, ActivityDirection::Prev),+ ActivityGroup::Bash+ );assert_eq!(dock.step(ActivityGroup::Bash, ActivityDirection::Prev),ActivityGroup::Heartbeats@@ -462,6 +503,7 @@ fn dock_arrows_visit_the_same_groups_with_items() {heartbeats: 2,heartbeats_paused: 1,bash_running: 1,+ factory_group: true,goal_label: Some("Pursuing goal (0s)".to_string()),..ActivityDock::default()};@@ -471,15 +513,17 @@ fn dock_arrows_visit_the_same_groups_with_items() {ActivityGroup::Subagents,ActivityGroup::Heartbeats,ActivityGroup::Bash,+ ActivityGroup::Factory,ActivityGroup::Goal,]);// The full cycle right: every group in order, the goal group- // included, back to the start in four presses.+ // included, back to the start in five presses.let mut walked = ActivityGroup::Subagents;for expected in [ActivityGroup::Heartbeats,ActivityGroup::Bash,+ ActivityGroup::Factory,ActivityGroup::Goal,ActivityGroup::Subagents,] {@@ -490,6 +534,7 @@ fn dock_arrows_visit_the_same_groups_with_items() {let mut walked = ActivityGroup::Subagents;for expected in [ActivityGroup::Goal,+ ActivityGroup::Factory,ActivityGroup::Bash,ActivityGroup::Heartbeats,ActivityGroup::Subagents,@@ -506,17 +551,21 @@ fn dock_arrows_visit_the_same_groups_with_items() {fn dock_goal_group_unmounts_with_its_row() {let with_goal = ActivityDock {goal_label: Some("Goal paused (0s)".to_string()),+ factory_group: true,..ActivityDock::default()};assert!(with_goal.groups().contains(&ActivityGroup::Goal));- let ended = ActivityDock::default();+ let ended = ActivityDock {+ factory_group: true,+ ..ActivityDock::default()+ };assert!(!ended.groups().contains(&ActivityGroup::Goal),"the goal group leaves the cycle when its row unmounts");assert_eq!(ended.step(ActivityGroup::Goal, ActivityDirection::Prev),- ActivityGroup::Bash,+ ActivityGroup::Factory,"a stale goal selection lands on the row's last group");assert_eq!(@@ -526,6 +575,49 @@ fn dock_goal_group_unmounts_with_its_row() {);}+/// The factory group is the lane's opt-in surface: an unadvertised+/// `factory_activity` lane mounts no factory group anywhere — no row+/// segment, no traversal, no click region (the factory's default-off+/// gate; the dock's factory group renders exactly while the daemon+/// advertises the lane).+#[test]+fn an_unadvertised_factory_lane_mounts_no_factory_group() {+ let theme = Theme::builtin("prime", ColorMode::TrueColor);+ // The default dock is the unadvertised lane (the opt-in default).+ let dock = ActivityDock::default();+ assert!(+ !dock.groups().contains(&ActivityGroup::Factory),+ "the unadvertised lane stays out of the traversal cycle"+ );+ let (frame, segments) = render_activity_dock_segments(&dock, &theme, 120);+ let text = frame[1]+ .iter()+ .map(|span| span.content.as_str())+ .collect::<String>();+ assert_eq!(+ text, " ◆ 0 subagents · ◷ 0 heartbeats · ▸ 0 shells",+ "no factory segment renders: {text}"+ );+ assert!(+ segments+ .iter()+ .all(|segment| segment.group != ActivityGroup::Factory),+ "no factory click region records"+ );+ // The arrows wrap the remaining groups exactly: a stale Factory+ // selection steps to the row's real ends, never a hidden group.+ assert_eq!(+ dock.step(ActivityGroup::Bash, ActivityDirection::Next),+ ActivityGroup::Subagents,+ "the cycle wraps past the shells group"+ );+ assert_eq!(+ dock.step(ActivityGroup::Subagents, ActivityDirection::Prev),+ ActivityGroup::Bash,+ "the reverse cycle wraps past the subagents group"+ );+}+/// Entering an empty group still renders it: the focused selection's/// band — the ONE shared selection style — rides the group's/// zero-count segment on the row — the dock-level empty state is@@ -537,6 +629,7 @@ fn dock_renders_the_focused_empty_group() {let dock = ActivityDock {selected: ActivityGroup::Heartbeats,focused: true,+ factory_group: true,..ActivityDock::default()};let frame = render_activity_dock(&dock, &theme, 100);@@ -544,7 +637,10 @@ fn dock_renders_the_focused_empty_group() {.iter().map(|span| span.content.as_str()).collect::<String>();- assert_eq!(text, " ◆ 0 subagents · ◷ 0 heartbeats · ▸ 0 shells");+ assert_eq!(+ text,+ " ◆ 0 subagents · ◷ 0 heartbeats · ▸ 0 shells · ⚙ 0 factory"+ );// The selection's band rides exactly the entered empty group's// zero readout, which keeps its own muted color (the selection// never repaints the text).diff --git a/crates/pa-tui/src/client_settings.rs b/crates/pa-tui/src/client_settings.rsindex 47bc14b9ef..f1b6dd96c9 100644--- a/crates/pa-tui/src/client_settings.rs+++ b/crates/pa-tui/src/client_settings.rs@@ -158,6 +158,18 @@ pub trait ClientSettings: Send + Sync {/// Returns `Err` when the tier name is not a known service tier or/// opening or persisting the settings store fails.fn set_default_service_tier(&self, tier: &str) -> Result<()>;+ /// `factory.enabled` (the agent factory's opt-in gate; unset reads+ /// as disabled).+ fn factory_enabled(&self) -> bool;+ /// Persists `factory.enabled` to the global scope — the same shared+ /// settings key the daemon's `factory_activity` lane advertisement+ /// and the kernel's factory gate read.+ ///+ /// # Errors+ ///+ /// Returns an error when opening or persisting the settings store+ /// fails.+ fn set_factory_enabled(&self, enabled: bool) -> Result<()>;/// `chatDetail` (`overview`/`details`/`all`; TS #2709 default/// `details`): the conversation-detail level the chat starts at./// `chatDetail` (`overview`/`details`/`all`; the default reads asdiff --git a/crates/pa-tui/src/daemon_client.rs b/crates/pa-tui/src/daemon_client.rsindex a754b7dc1b..ec724fa5e2 100644--- a/crates/pa-tui/src/daemon_client.rs+++ b/crates/pa-tui/src/daemon_client.rs@@ -32,8 +32,8 @@ mod tests;use errors::{command_type_debug, response_data_or_error, DirectRequestError};pub use errors::{- is_daemon_rejection, is_daemon_timeout, is_daemon_unreachable, is_update_restarting_rejection,- rejected_provider_unauthenticated, RequestRejected,+ is_daemon_rejection, is_daemon_timeout, is_daemon_unreachable, is_kernel_not_running,+ is_update_restarting_rejection, rejected_provider_unauthenticated, RequestRejected,};/// Default response timeout (TS `DEFAULT_DAEMON_REQUEST_TIMEOUT_MS`).diff --git a/crates/pa-tui/src/daemon_client/errors.rs b/crates/pa-tui/src/daemon_client/errors.rsindex 8df56535e7..53a1706c9d 100644--- a/crates/pa-tui/src/daemon_client/errors.rs+++ b/crates/pa-tui/src/daemon_client/errors.rs@@ -1,5 +1,7 @@use anyhow::Result;-use pa_types::daemon::{DaemonCommand, DaemonErrorInfo, DaemonResponse};+use pa_types::daemon::{+ DaemonCommand, DaemonErrorInfo, DaemonResponse, KERNEL_NOT_RUNNING_MESSAGE,+};use serde_json::Value;/// Why a direct request failed: `NotSent` never reached the worker (safe to/// fall back to the supervisor), `Wait` did and must not be retried.@@ -105,6 +107,22 @@ pub fn is_daemon_unreachable(error: &anyhow::Error) -> bool {})}+/// Whether the error is the daemon's kernel-not-running refusal+/// (`KERNEL_NOT_RUNNING_MESSAGE`: the session-addressed lanes answer+/// with it while the session's kernel is not built — the lane never+/// boots an idle kernel): a DEFINITIVE answer, not a transient+/// failure — the kernel owns its run registry in memory, so a session+/// without a kernel carries no live runs and a caller reading the+/// count can take zero instead of an unknown.+#[must_use]+pub fn is_kernel_not_running(error: &anyhow::Error) -> bool {+ error.chain().any(|cause| {+ cause+ .downcast_ref::<RequestRejected>()+ .is_some_and(|rejected| rejected.message == KERNEL_NOT_RUNNING_MESSAGE)+ })+}+/// Unwrap a settled response into its `data`, surfacing the daemon/// refusal as a typed [`RequestRejected`] on failure.pub(super) fn response_data_or_error(name: &str, response: DaemonResponse) -> Result<Value> {diff --git a/crates/pa-tui/src/daemon_client/tests.rs b/crates/pa-tui/src/daemon_client/tests.rsindex f4d3690203..c5aaf1da44 100644--- a/crates/pa-tui/src/daemon_client/tests.rs+++ b/crates/pa-tui/src/daemon_client/tests.rs@@ -362,6 +362,43 @@ fn update_restarting_rejection_round_trips_the_wire() {assert!(!is_update_restarting_rejection(&error));}+/// The session-addressed lanes' kernel-not-running refusal (the+/// `/factory off` guard's definitive-zero class): the exact wire string+/// classifies through the plain-message predicate, and no other refusal+/// does — the guard's zero read must not fire on an unknown-command or+/// initializing refusal, which stay unreadable and fail closed.+#[test]+fn kernel_not_running_refusal_round_trips_the_wire() {+ let line = serde_json::from_str::<DaemonResponse>(+ r#"{"type":"response","command":"factory_activity","success":false,"error":"Kernel is not running"}"#,+ )+ .expect("refusal parses");+ let error = response_data_or_error("factory_activity", line).unwrap_err();+ assert!(is_kernel_not_running(&error));+ // A refusal that merely embeds the phrase is not the class.+ let wrapped = serde_json::from_str::<DaemonResponse>(+ r#"{"type":"response","command":"factory_activity","success":false,"error":"the session reports: Kernel is not running for this lane"}"#,+ )+ .expect("unrelated refusal parses");+ let error = response_data_or_error("factory_activity", wrapped).unwrap_err();+ assert!(!is_kernel_not_running(&error));+ // The adjacent unreadable classes never classify as the zero read.+ for message in [+ "Session is still initializing",+ "Unknown worker command: factory_activity",+ ] {+ let unrelated = serde_json::from_str::<DaemonResponse>(&format!(+ r#"{{"type":"response","command":"factory_activity","success":false,"error":"{message}"}}"#+ ))+ .expect("unrelated refusal parses");+ let error = response_data_or_error("factory_activity", unrelated).unwrap_err();+ assert!(!is_kernel_not_running(&error), "{message}");+ }+ // A transport failure is not a refusal at all.+ let plain = anyhow!("the daemon connection is closed");+ assert!(!is_kernel_not_running(&plain));+}+#[test]fn fail_pending_resolves_a_transport_failure_not_a_refusal() {// The reader task's dead-connection failure must stay on thediff --git a/crates/pa-tui/src/factory_view.rs b/crates/pa-tui/src/factory_view.rsnew file mode 100644index 0000000000..8da9ccfb04--- /dev/null+++ b/crates/pa-tui/src/factory_view.rs@@ -0,0 +1,944 @@+//! The `/factory` view: one panel per live factory run — the machine+//! diagram with live highlighting, the run's state, the instances+//! running and queued, the budget consumed, and the milestone tail — on+//! the activity pages' picker keyset (arrows + Enter + Esc): the arrows+//! move the run selection over the NEWEST-FIRST feed (a run created+//! after an existing one renders above it, and the page opens with the+//! newest run selected), Enter opens the selected run's in-page action+//! rows (stop/resume — the heartbeats picker's drill-in shape), and Esc+//! backs out of the open action rows or closes the page.+//!+//! The view is pure presentation and selection: the session UI owns the+//! refresh cadence (the run's collect cycle: a bounded watch on the+//! selected run, then the graph list), executes the actions through the+//! daemon's `factory_activity` lane, and repaints on the snapshot+//! signatures' hysteresis (a per-transition repaint never spams: only a+//! notice-worthy run-shape change flips the changed marker).+//!+//! The diagram is the honest in-terminal machine graph: every state as a+//! status-glyphed row in the machine's declared order — the row's label+//! carrying the stage's agent occupancy (`reviewing (3 run · 2 queued)`:+//! how many agents run at the node, how many queue behind them) — its+//! outgoing transitions as connector rows underneath (joins rendered+//! once, back edges marked), active nodes bright, pending nodes dim, and+//! the last-fired edges marked.++use serde_json::Value;++use crate::keybindings::{format_key_text, KeybindingsManager};+use crate::theme::{Theme, ThemeColor};+use crate::width::truncate_line;+use crate::{Line, Span};++mod diagram;+#[cfg(test)]+mod tests;++use diagram::{+ edge_marker, node_glyph, run_state_color, FactoryEdge, FactoryNodeState, FactoryState,+ FactoryTransition, FactoryUsage,+};++/// The refresh cadence's watch bound (ms): the kernel's own collect poll+/// slice (`POLL_TIMEOUT_MS`), so a change repaints at the run's pace.+pub const FACTORY_WATCH_TICK_MS: u64 = 2_000;++/// How many trailing milestone labels a panel shows.+pub const MILESTONE_TAIL: usize = 3;++/// One run's fused snapshot (the kernel `factory.graph` shape).+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryRunSnapshot {+ pub run_id: String,+ pub spec_id: String,+ pub name: Option<String>,+ pub state: Option<String>,+ pub elapsed_ms: u64,+ pub budget_limit_ms: Option<u64>,+ pub usage: Option<FactoryUsage>,+ pub states: Vec<FactoryState>,+ pub transitions: Vec<FactoryTransition>,+ pub last_fired: Vec<FactoryEdge>,+ pub milestones: Vec<String>,+ pub nodes: std::collections::HashMap<String, FactoryNodeState>,+}++impl FactoryRunSnapshot {+ /// The panel header's display name: the run's name, else the spec id,+ /// else the run id's head.+ #[must_use]+ pub fn display_name(&self) -> String {+ self.name+ .clone()+ .filter(|name| !name.trim().is_empty())+ .unwrap_or_else(|| self.spec_id.clone())+ }++ /// The hysteresis signature: the run's notice-worthy shape (the run+ /// state, every node's entry/instance statuses, and the fired-edge+ /// set). Two snapshots with the same signature paint the same panel.+ /// The clock never trips the signature: `elapsed_ms` advances on every+ /// poll, so including it would light the changed marker on every+ /// refresh and the marker would never decay (the elapsed display+ /// repaints on the refresh cadence; only a run-shape change is+ /// notice-worthy).+ #[must_use]+ pub fn signature(&self) -> String {+ let mut parts = vec![self.state.clone().unwrap_or_default()];+ for state in &self.states {+ let node = self.nodes.get(&state.id);+ parts.push(state.id.clone());+ parts.push(node.map_or_else(|| "pending".to_string(), FactoryNodeState::signature));+ }+ for edge in &self.last_fired {+ parts.push(format!("{}->{}", edge.edge_label(), edge.to));+ }+ parts.join("|")+ }++ /// The states with an in-flight entry or live instances (the+ /// diagram's bright rows).+ #[must_use]+ pub fn active_state_ids(&self) -> Vec<String> {+ self.states+ .iter()+ .filter(|state| {+ self.nodes+ .get(&state.id)+ .is_some_and(FactoryNodeState::is_active)+ })+ .map(|state| state.id.clone())+ .collect()+ }++ /// Whether the run still holds running children (admitted residents,+ /// or any in-flight instance a terminal state can carry — a `done`+ /// run whose residents still run stays actionable).+ #[must_use]+ pub fn children_in_flight(&self) -> bool {+ self.usage.as_ref().is_some_and(|usage| usage.running > 0)+ }++ /// Whether the run is LIVE in the dock/page sense: a live state+ /// (running/stopping/paused), or children still in flight — the+ /// kernel's own unscoped-list liveness rule (`state in live_states+ /// or running > 0`): a `done`/`failed` run whose resident children+ /// still run keeps its panel, its dock count, and its stop control+ /// while any child runs, and a fully terminal run offers nothing.+ #[must_use]+ pub fn is_live(&self) -> bool {+ matches!(+ self.state.as_deref(),+ Some("running" | "stopping" | "paused")+ ) || self.children_in_flight()+ }+}++/// One run-level action the page offers on a live run (the heartbeats+/// picker's action-row grammar): the stop that tears the run and its+/// children down, and the pause complement's resume.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FactoryAction {+ Stop,+ Resume,+}++impl FactoryAction {+ /// The action row's label.+ #[must_use]+ pub fn label(self) -> &'static str {+ match self {+ Self::Stop => "Stop the run",+ Self::Resume => "Resume the run",+ }+ }+}++/// Parse the daemon `factory_activity` graph reply: `{"runs": [...]}` in+/// the kernel's compact snapshot shape. Malformed rows drop (a truncated+/// panel never renders), and an unknown shape answers an empty view.+///+/// The reply carries the registry's start order, oldest run first (the+/// kernel's documented polling order — `FactoryExecutor.graph` in+/// `rlm/factory.py`); the view reads NEWEST-FIRST, like a live activity+/// feed, so this seam reverses the list exactly once and every view path+/// (the mount and the refresh fold) receives the same reading order. The+/// wire contract stays stable: the kernel reply and the agent+/// conversation API keep their oldest-first order — the reading order is+/// presentation. Reversal, never an `elapsedMs` sort: the elapsed clock+/// grows live, truncates to whole milliseconds, and each row snapshots+/// at its own tick, so two close-start runs could flip between+/// refreshes; the reply's start order is total and stable.+#[must_use]+pub fn parse_factory_runs(data: &Value) -> Vec<FactoryRunSnapshot> {+ let Some(runs) = data.get("runs").and_then(Value::as_array) else {+ return Vec::new();+ };+ let mut parsed: Vec<FactoryRunSnapshot> = runs.iter().filter_map(parse_run).collect();+ parsed.reverse();+ parsed+}++/// Whether a reply is the graph list shape at all: a reply without the+/// `runs` LIST (absent, or present but not an array) is a malformed+/// lane, not zero runs — the session UI reports it on the open page's+/// error line instead of painting a fake empty state (the emptiness the+/// view shows is real).+#[must_use]+pub fn factory_reply_lists_runs(data: &Value) -> bool {+ data.get("runs").is_some_and(Value::is_array)+}++/// The malformed-lane error line (one message for the mount and the+/// fold): a reply without the runs list is a malformed lane, never+/// zero runs.+pub const MALFORMED_REPLY_ERROR: &str = "malformed factory reply (no runs list)";++fn opt_string(value: Option<&Value>) -> Option<String> {+ value+ .and_then(Value::as_str)+ .map(str::to_string)+ .filter(|text| !text.is_empty())+}++/// One daemon-provided DISPLAY string, scrubbed: control bytes never+/// reach a styled span (`scrub_controls`, the bash activity lane's+/// rule — a run name or milestone carrying an OSC sequence can never+/// drive the terminal, e.g. overwrite the operator's clipboard via+/// OSC 52). The scrub lands at this parse seam, so every paint path+/// (the panel header, the diagram rows, the milestone tail, the+/// Mermaid copy) sees terminal-safe text; the run id stays raw — it+/// never reaches a span and must round-trip the kernel's registry as+/// the stop/resume/watch identity.+fn scrubbed_string(value: Option<&Value>) -> Option<String> {+ opt_string(value).map(|text| crate::menu_panel::scrub_controls(&text))+}++/// One field read that tolerates both spellings: the kernel's+/// conversation shape (`snake_case`) and the activity lane's wire shape+/// (`camelCase` — `_wire_payload` re-keys the reply before it travels).+/// The two spellings never coexist in one reply; either resolves.+fn get_either<'a>(value: &'a Value, snake: &str, camel: &str) -> Option<&'a Value> {+ value.get(snake).or_else(|| value.get(camel))+}++/// Parse one run row: the kernel's compact snapshot shape+/// (`_graph_snapshot` in `rlm/factory.py`) with `run_id`/`spec_id`+/// carrying the identity, `elapsed_ms`/`budget.limit_ms` the clock and+/// budget, `usage` the counters, and `machine`/`nodes`/`last_fired`/+/// `events` the fused structure and live overlay. Every key read+/// tolerates both spellings: the activity wire carries the `camelCase`+/// form (`_wire_payload` converts the reply before it travels) and the+/// kernel's conversation shape stays `snake_case`. Every DISPLAY string+/// scrubs its control bytes ([`scrubbed_string`]) — daemon-provided+/// text never drives the terminal — and the run id stays raw (the+/// stop/resume/watch identity must round-trip the kernel's registry).+fn parse_run(run: &Value) -> Option<FactoryRunSnapshot> {+ let run_id = opt_string(get_either(run, "run_id", "runId")).unwrap_or_default();+ let spec_id = scrubbed_string(get_either(run, "spec_id", "specId")).unwrap_or_default();+ if run_id.is_empty() && spec_id.is_empty() {+ return None;+ }+ let machine = run.get("machine")?;+ let states = machine+ .get("states")+ .and_then(Value::as_array)+ .map(|states| states.iter().filter_map(FactoryState::parse).collect())+ .unwrap_or_default();+ let transitions = machine+ .get("transitions")+ .and_then(Value::as_array)+ .map(|rows| rows.iter().filter_map(FactoryTransition::parse).collect())+ .unwrap_or_default();+ let last_fired = get_either(run, "last_fired", "lastFired")+ .and_then(Value::as_array)+ .map(|rows| rows.iter().filter_map(FactoryEdge::parse).collect())+ .unwrap_or_default();+ let mut nodes = std::collections::HashMap::new();+ for node in run+ .get("nodes")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ {+ if let (Some(id), Some(node)) = (+ scrubbed_string(node.get("id")),+ FactoryNodeState::parse(node),+ ) {+ nodes.insert(id, node);+ }+ }+ let milestones = run+ .get("events")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter(|event| event.get("kind").and_then(Value::as_str) == Some("milestone"))+ .filter_map(|event| scrubbed_string(event.get("milestone")))+ .collect();+ Some(FactoryRunSnapshot {+ run_id,+ spec_id,+ name: scrubbed_string(run.get("name")),+ state: scrubbed_string(run.get("state")),+ elapsed_ms: get_either(run, "elapsed_ms", "elapsedMs")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ budget_limit_ms: run+ .get("budget")+ .and_then(|budget| get_either(budget, "limit_ms", "limitMs"))+ .and_then(Value::as_u64),+ usage: FactoryUsage::parse(run.get("usage")),+ states,+ transitions,+ last_fired,+ milestones,+ nodes,+ })+}++/// One key press while the `/factory` view is open, resolved by the view's+/// own key loop (the session UI executes the returned action).+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum FactoryViewAction {+ None,+ /// Stop the selected run.+ Stop {+ run_id: String,+ },+ /// Resume the selected (paused) run.+ Resume {+ run_id: String,+ },+ Close,+}++/// The page's mode: the run feed, or the selected run's open action rows+/// (the heartbeats picker's list/detail drill-in shape, one level — the+/// feed stays mounted behind the action rows; there is no separate detail+/// page to paint).+#[derive(Debug, Clone, PartialEq, Eq)]+enum Mode {+ /// The run feed: the arrows walk the run selection.+ Feed,+ /// The open run's action rows: the arrows walk the offered actions.+ /// The tracked action rides by IDENTITY, not index — a fold may+ /// change the run's state (and with it the offered set) while the+ /// rows are open, and a tracked index would silently rename the+ /// selection to a different action (the feed's same-run lesson, one+ /// level up).+ Actions {+ run_id: String,+ action: FactoryAction,+ },+}++/// The `/factory` view's state: the parsed run panels, the selection, the+/// open action rows, and the hysteresis bookkeeping.+#[derive(Debug)]+pub struct FactoryView {+ runs: Vec<FactoryRunSnapshot>,+ /// Per-run recent-change markers: set by [`Self::apply_runs`] when the+ /// signature changed, decayed on the next cycle (no per-transition+ /// repaint spam — one marker per notice-worthy change).+ recent_change: Vec<bool>,+ selected: usize,+ mode: Mode,+ error: Option<String>,+ viewport_rows: usize,+}++impl FactoryView {+ /// Build the view from the first snapshot batch. The batch arrives+ /// newest-first ([`parse_factory_runs`]'s reading order), so the+ /// default selection — index 0 — is the newest run: the page opens on+ /// the feed's live head.+ #[must_use]+ pub fn new(runs: Vec<FactoryRunSnapshot>, viewport_rows: usize) -> Self {+ let recent_change = vec![false; runs.len()];+ Self {+ runs,+ recent_change,+ selected: 0,+ mode: Mode::Feed,+ error: None,+ viewport_rows,+ }+ }++ /// The actions the page offers on one run (the heartbeats picker's+ /// `availableActions` grammar): the pause complement first — resume+ /// on a paused run — then stop, exactly while the run is live (a+ /// `done` run with residents still in flight keeps its stop; a+ /// fully terminal run offers nothing). The offered set is derived+ /// from the run's CURRENT snapshot everywhere — the render, the+ /// arrow walk, the Enter confirmation — so a fold's state change+ /// can never leave a stale action offered.+ #[must_use]+ pub fn available_actions(run: &FactoryRunSnapshot) -> Vec<FactoryAction> {+ let mut actions = Vec::with_capacity(2);+ if run.run_id.is_empty() {+ return actions;+ }+ if run.state.as_deref() == Some("paused") {+ actions.push(FactoryAction::Resume);+ }+ if run.is_live() {+ actions.push(FactoryAction::Stop);+ }+ actions+ }++ /// Mount the view from the poll cache (the open path's builder): the+ /// parsed panels, and — when the cached reply is a malformed lane (no+ /// runs list) — the malformed-reply error set at once. A malformed+ /// cache can never mount as a silent fake empty state: the fold's+ /// malformed-reply contract holds at mount too, so the page's first+ /// frame already says why the list is empty instead of waiting a+ /// poll cycle for the fold to say it.+ #[must_use]+ pub fn from_reply(data: &Value, viewport_rows: usize) -> Self {+ let mut view = Self::new(parse_factory_runs(data), viewport_rows);+ if !factory_reply_lists_runs(data) {+ view.set_error(Some(MALFORMED_REPLY_ERROR.to_string()));+ }+ view+ }++ /// Apply one refreshed snapshot batch: keep the selection on the same+ /// run, and light the changed marker exactly on the runs whose+ /// signature changed this cycle (the marker decays when the run goes+ /// quiet — the repaint hysteresis, no per-transition spam). Returns+ /// whether any run changed.+ pub fn apply_runs(&mut self, runs: Vec<FactoryRunSnapshot>) -> bool {+ let mut changed = false;+ let mut recent_change = Vec::with_capacity(runs.len());+ for run in &runs {+ let is_new = self+ .runs+ .iter()+ .find(|old| old.run_id == run.run_id)+ .is_some_and(|old| old.signature() != run.signature());+ recent_change.push(is_new);+ if is_new {+ changed = true;+ }+ }+ // Keep the selection on the same run id, never the same index:+ // the list reads newest-first, so a newer run folding in moves+ // the selected run down without stealing the selection. A run+ // that left the batch (the wire cap's oldest-end trim, a+ // cleared registry) returns the selection to the feed's head —+ // the newest run — because the same slot names a different run+ // in the reversed order.+ let selected_id = self.runs.get(self.selected).map(|run| run.run_id.clone());+ self.runs = runs;+ self.recent_change = recent_change;+ self.selected = match selected_id {+ Some(selected_id) => self+ .runs+ .iter()+ .position(|run| run.run_id == selected_id)+ .unwrap_or(0),+ None => 0,+ };+ // The open action rows ride the same fold discipline as the+ // feed's selection: a run that left the batch closes the rows,+ // and a state change under them re-reads the offered set — a+ // paused run that stopped mid-menu no longer offers resume,+ // and the tracked action clamps to what the run still offers+ // (never a stale target: the rows confirm against the folded+ // snapshot, not the one they opened on).+ if let Mode::Actions { run_id, action } = self.mode.clone() {+ let offered = self+ .runs+ .iter()+ .find(|run| run.run_id == run_id)+ .map(Self::available_actions)+ .unwrap_or_default();+ match offered.first().copied() {+ None => self.mode = Mode::Feed,+ Some(first) if !offered.contains(&action) => {+ self.mode = Mode::Actions {+ run_id,+ action: first,+ };+ }+ Some(_) => {}+ }+ }+ changed+ }++ /// The selected run's snapshot, when any run is live.+ #[must_use]+ pub fn selected_run(&self) -> Option<&FactoryRunSnapshot> {+ self.runs.get(self.selected)+ }++ /// Record one fetch/error line from the session UI's refresh. The+ /// message is daemon-provided text painted on the chrome line, so it+ /// scrubs — an OSC sequence in a reply's error reason can never+ /// drive the terminal.+ pub fn set_error(&mut self, error: Option<String>) {+ self.error = error.map(|text| crate::menu_panel::scrub_controls(&text));+ }++ /// One key press on the activity pages' picker keyset (arrows ++ /// Enter + Esc — the heartbeats/bash pages' family): the arrows+ /// move the selection (the feed's run, or the open action rows'+ /// action), Enter opens the selected run's action rows or runs the+ /// selected action, and Esc/ctrl+c back out of the open action rows+ /// or close the page. Every binding reads the keybinding manager+ /// (`tui.select.up`/`down`/`confirm`/`cancel`), so a user's remap+ /// reaches this page exactly like its siblings.+ #[must_use]+ pub fn handle_key(&mut self, key: &str, kb: &KeybindingsManager) -> FactoryViewAction {+ if key == "ctrl+c" || kb.matches(key, "tui.select.cancel") {+ // Esc backs out of the open action rows before it closes+ // the page — the drill-in's back, on the one close key the+ // page carries (the keyset stays arrows + Enter + Esc).+ if self.mode != Mode::Feed {+ self.mode = Mode::Feed;+ return FactoryViewAction::None;+ }+ return FactoryViewAction::Close;+ }+ if kb.matches(key, "tui.select.up") || kb.matches(key, "tui.select.down") {+ let delta: isize = if kb.matches(key, "tui.select.up") {+ -1+ } else {+ 1+ };+ self.move_selection(delta);+ return FactoryViewAction::None;+ }+ if kb.matches(key, "tui.select.confirm") {+ return self.confirm_selection();+ }+ FactoryViewAction::None+ }++ /// One arrow step: the feed walks the run selection (newest-first —+ /// down the feed reads OLDER), the open action rows walk their+ /// offered set. A run that left the batch under open rows closes+ /// them (the fold's own hand-back, reached from the key path too).+ fn move_selection(&mut self, delta: isize) {+ match self.mode.clone() {+ Mode::Feed => {+ if self.runs.is_empty() {+ return;+ }+ let next = (self.selected as isize + delta).clamp(0, self.runs.len() as isize - 1)+ as usize;+ self.selected = next;+ }+ Mode::Actions { run_id, action } => {+ let Some(run) = self.runs.iter().find(|run| run.run_id == run_id) else {+ self.mode = Mode::Feed;+ return;+ };+ let actions = Self::available_actions(run);+ let Some(current) = actions.iter().position(|candidate| *candidate == action)+ else {+ return;+ };+ let next = (current as isize + delta).clamp(0, actions.len() as isize - 1) as usize;+ self.mode = Mode::Actions {+ run_id,+ action: actions[next],+ };+ }+ }+ }++ /// Enter: the feed opens the selected run's action rows (when the+ /// run offers any — a terminal run answers nothing), the open rows+ /// run the selected action and return to the feed. The+ /// confirmation re-resolves the run and its offered set against+ /// the CURRENT batch — a fold may have changed the run's state, or+ /// dropped the run, while the rows were open — so the action lands+ /// on the folded truth, never a stale target.+ fn confirm_selection(&mut self) -> FactoryViewAction {+ match self.mode.clone() {+ Mode::Feed => {+ if let Some(run) = self.selected_run() {+ if let Some(action) = Self::available_actions(run).first().copied() {+ self.mode = Mode::Actions {+ run_id: run.run_id.clone(),+ action,+ };+ }+ }+ FactoryViewAction::None+ }+ Mode::Actions { run_id, action } => {+ let offered = self+ .runs+ .iter()+ .find(|run| run.run_id == run_id)+ .map(Self::available_actions)+ .unwrap_or_default();+ self.mode = Mode::Feed;+ if offered.contains(&action) {+ match action {+ FactoryAction::Stop => FactoryViewAction::Stop { run_id },+ FactoryAction::Resume => FactoryViewAction::Resume { run_id },+ }+ } else {+ FactoryViewAction::None+ }+ }+ }+ }++ /// Render the view: one panel per live run (the machine diagram with+ /// live highlighting), the empty state when nothing runs, and the+ /// trailing key hint.+ #[must_use]+ pub fn render(&self, theme: &Theme, width: usize, kb: &KeybindingsManager) -> Vec<Line> {+ // The panel area: one panel per run, each panel's row range+ // recorded for the budget window below.+ let mut panels: Vec<Line> = Vec::new();+ let mut panel_ranges: Vec<(usize, usize)> = Vec::new();+ if self.runs.is_empty() {+ panels.push(vec![Span::raw("")]);+ panels.push(vec![+ Span::raw(" "),+ theme.fg_span(ThemeColor::Text, "No live factory runs."),+ ]);+ panels.push(vec![+ Span::raw(" "),+ theme.fg_span(+ ThemeColor::Muted,+ "Start one from the conversation: await rlm.factory.run('<spec_id>')",+ ),+ ]);+ }+ for (index, run) in self.runs.iter().enumerate() {+ if index > 0 {+ panels.push(vec![Span::raw("")]);+ }+ let panel_start = panels.len();+ self.render_panel(theme, width, run, index, &mut panels);+ panel_ranges.push((panel_start, panels.len()));+ }+ // The chrome area: the open action rows, the error line from the+ // last failed refresh, and the trailing key hint. The chrome+ // always renders — the hint is the view's only key legend, and+ // the action rows are the page's only action surface.+ let action_rows = self.action_block(theme);+ let mut chrome_rows = 2 + action_rows.len();+ if self.error.is_some() {+ chrome_rows += 2;+ }+ // The dock's frame budget owns the final trim; the view never+ // renders more rows than the viewport asked for. A tall view+ // windows over the panel area: the leading window keeps the top+ // of the feed (the newest panels — the oldest panels drop+ // first), and when the focused run's panel falls below it the+ // window slides to it (the focused run is the actionable one —+ // the feed's selection, or the run whose action rows are+ // open — so a stop/resume target never hides behind the+ // budget); the chrome stays pinned at the end either way.+ let focus = match &self.mode {+ Mode::Actions { run_id, .. } => self+ .runs+ .iter()+ .position(|run| &run.run_id == run_id)+ .unwrap_or(self.selected),+ Mode::Feed => self.selected,+ };+ let budget = self.viewport_rows.max(1);+ let panel_budget = budget.saturating_sub(chrome_rows);+ if panels.len() > panel_budget {+ let mut start = 0;+ if let Some((focus_start, _)) = panel_ranges.get(focus) {+ if *focus_start >= panel_budget {+ start = *focus_start;+ }+ }+ if start > 0 {+ panels.drain(..start);+ }+ panels.truncate(panel_budget);+ }+ let mut rows = panels;+ rows.extend(action_rows);+ if let Some(error) = &self.error {+ rows.push(vec![Span::raw("")]);+ rows.push(vec![+ Span::raw(" "),+ theme.fg_span(ThemeColor::Error, format!("Error: {error}")),+ ]);+ }+ rows.push(vec![Span::raw("")]);+ let hint = match self.mode {+ Mode::Feed => Self::feed_hint(kb),+ Mode::Actions { .. } => Self::actions_hint(kb),+ };+ rows.push(vec![Span::raw(" "), theme.fg_span(ThemeColor::Dim, hint)]);+ // A degenerate budget (a sub-chrome viewport on a short terminal)+ // tail-clips: the hint is the chrome's last row and always survives.+ if rows.len() > budget {+ rows.drain(..rows.len() - budget);+ }+ rows.into_iter()+ .map(|row| truncate_line(&row, width, ""))+ .collect()+ }++ /// The feed's bottom hint line (the heartbeats/bash pages' grammar):+ /// the arrows move, Enter opens the selected run's action rows, Esc+ /// closes.+ fn feed_hint(kb: &KeybindingsManager) -> String {+ let key = |binding: &str, fallback: &str| {+ kb.first_key(binding)+ .map_or_else(|| fallback.to_string(), |key| format_key_text(&key))+ };+ format!(+ "{}/{} move \u{b7} {} actions \u{b7} {} close",+ key("tui.select.up", "\u{2191}"),+ key("tui.select.down", "\u{2193}"),+ key("tui.select.confirm", "Enter"),+ key("tui.select.cancel", "Esc"),+ )+ }++ /// The open action rows' hint line: the arrows walk the actions,+ /// Enter runs the tracked one, Esc backs out to the feed.+ fn actions_hint(kb: &KeybindingsManager) -> String {+ let key = |binding: &str, fallback: &str| {+ kb.first_key(binding)+ .map_or_else(|| fallback.to_string(), |key| format_key_text(&key))+ };+ format!(+ "{}/{} action \u{b7} {} run \u{b7} {} back",+ key("tui.select.up", "\u{2191}"),+ key("tui.select.down", "\u{2193}"),+ key("tui.select.confirm", "Enter"),+ key("tui.select.cancel", "Esc"),+ )+ }++ /// The open action rows (the heartbeats picker's drill-in, one+ /// level): a blank, a header naming the run, one row per offered+ /// action with the tracked one marked. The block rides the+ /// trailing chrome — the panel window's budget keeps it and the+ /// hint painted together.+ fn action_block(&self, theme: &Theme) -> Vec<Line> {+ let Mode::Actions { run_id, action } = &self.mode else {+ return Vec::new();+ };+ let Some(run) = self.runs.iter().find(|run| &run.run_id == run_id) else {+ return Vec::new();+ };+ let mut rows = vec![vec![Span::raw("")]];+ let mut header: Line = vec![Span::raw(" ")];+ header.push(theme.fg_span(ThemeColor::ToolTitle, "actions: "));+ header.push(theme.fg_span(ThemeColor::Text, run.display_name()));+ rows.push(header);+ for offered in Self::available_actions(run) {+ let tracked = offered == *action;+ let mut row: Line = vec![Span::raw(" ")];+ row.push(Span::raw(if tracked { "▸ " } else { " " }));+ row.push(theme.fg_span(+ if tracked {+ ThemeColor::Text+ } else {+ ThemeColor::Muted+ },+ offered.label().to_string(),+ ));+ rows.push(row);+ }+ rows+ }++ /// One run panel: the header (name, state, changed marker), the stats+ /// line (budget consumed, parallel, instances), the machine diagram,+ /// and the milestone tail.+ fn render_panel(+ &self,+ theme: &Theme,+ width: usize,+ run: &FactoryRunSnapshot,+ index: usize,+ rows: &mut Vec<Line>,+ ) {+ let selected = index == self.selected;+ let changed = self.recent_change.get(index).copied().unwrap_or(false);+ // The header: the selection marker, the run's name, its state.+ let mut header: Line = vec![Span::raw(if selected { "▸ " } else { " " })];+ header.push(theme.fg_span(ThemeColor::ToolTitle, "factory: "));+ header.push(theme.fg_span(ThemeColor::Text, run.display_name()));+ let state_text = match run.state.as_deref() {+ Some(state) => format!(" — {state}"),+ None => " — not running".to_string(),+ };+ header.push(theme.fg_span(run_state_color(run.state.as_deref()), state_text));+ if changed {+ header.push(theme.fg_span(ThemeColor::Accent, " ● changed"));+ }+ // The stats tail: elapsed, budget, parallel, instances.+ let running = run+ .usage+ .as_ref()+ .map(|usage| usage.running)+ .unwrap_or_default();+ let stats = vec![+ Span::raw(" "),+ theme.fg_span(ThemeColor::Muted, Self::stats_line(run, running)),+ ];+ rows.push(header);+ rows.push(truncate_line(&stats, width, ""));+ rows.push(vec![Span::raw("")]);+ Self::render_diagram(theme, run, rows);+ if !run.milestones.is_empty() {+ let tail = run+ .milestones+ .iter()+ .rev()+ .take(MILESTONE_TAIL)+ .rev()+ .cloned()+ .collect::<Vec<_>>()+ .join(" · ");+ rows.push(vec![+ Span::raw(" "),+ theme.fg_span(ThemeColor::MdQuote, "milestones: "),+ theme.fg_span(ThemeColor::Muted, tail),+ ]);+ }+ }++ fn stats_line(run: &FactoryRunSnapshot, running: u64) -> String {+ let elapsed = format_duration(run.elapsed_ms);+ let budget = match run.budget_limit_ms {+ Some(limit) => format!("budget {}/{}", elapsed, format_duration(limit)),+ None => format!("elapsed {elapsed}"),+ };+ let mut parts = vec![budget];+ if let Some(usage) = &run.usage {+ parts.push(format!(+ "{}/{} parallel",+ running.min(usage.max_parallel),+ usage.max_parallel+ ));+ parts.push(format!("{} settled", usage.settled));+ parts.push(format!("{} transitions", usage.transitions_fired));+ }+ let queued = run+ .nodes+ .values()+ .map(FactoryNodeState::queued_agents)+ .sum::<u64>();+ parts.push(format!("{running} running · {queued} queued"));+ parts.join(" · ")+ }++ /// The machine diagram: every state in the machine's declared order as+ /// a status-glyphed row, its outgoing transitions as connector rows+ /// (joins once, back edges marked, the last-fired edges marked and+ /// colored).+ fn render_diagram(theme: &Theme, run: &FactoryRunSnapshot, rows: &mut Vec<Line>) {+ let order: Vec<&str> = run.states.iter().map(|state| state.id.as_str()).collect();+ let position = |id: &str| order.iter().position(|candidate| *candidate == id);+ for state in &run.states {+ let node = run.nodes.get(&state.id);+ // The row paints by the NODE's live activity, not the aggregate+ // status: a multi-entry state whose latest entry settled while+ // an earlier one still runs stays bright (is_active covers+ // every entry's status, not just the newest).+ let (glyph, color) = match node {+ Some(node) if node.is_active() => ("●", ThemeColor::Accent),+ Some(node) => node_glyph(&node.status),+ None => ("○", ThemeColor::Dim),+ };+ let mut row: Line = vec![+ Span::raw(" "),+ theme.fg_span(color, glyph.to_string()),+ Span::raw(" "),+ // The whole row paints in the node's status color: active+ // nodes bright (accent), pending dim, done muted, errors+ // red — the diagram's live highlighting.+ theme.fg_span(color, state.id.clone()),+ ];+ // The stage's agent occupancy rides the label — `reviewing+ // (3 run · 2 queued)` — so the diagram reads as a page of+ // machines with per-stage headcounts; a stage at rest+ // carries no fragment. The counts come from the kernel's+ // per-state report (the instance rows are the older-kernel+ // fallback), and the row's status color is unchanged.+ if let Some(node) = node {+ let occupancy = node.occupancy_label();+ if !occupancy.is_empty() {+ row.push(theme.fg_span(color, format!(" ({occupancy})")));+ }+ }+ if let Some(subagent) = &state.subagent {+ row.push(theme.fg_span(ThemeColor::Dim, format!(" ({subagent})")));+ }+ let status_text =+ node.map_or_else(|| "pending".to_string(), |node| node.status_line(state));+ row.push(theme.fg_span(color, format!(" {status_text}")));+ if state.entry {+ row.push(theme.fg_span(ThemeColor::Dim, " [entry]".to_string()));+ }+ rows.push(row);+ // The outgoing edges under the source: single-source transitions+ // render once; a join (a multi-source from list) renders once+ // under its last source with the join label.+ let mut edges: Vec<FactoryTransition> = Vec::new();+ edges.extend(+ run.transitions+ .iter()+ .filter(|transition| {+ transition.from.last().is_some_and(|from| from == &state.id)+ })+ .cloned(),+ );+ for edge in &edges {+ let fired = run+ .last_fired+ .iter()+ .any(|candidate| candidate.matches(edge));+ let (marker, marker_color) = edge_marker(edge, &order, position);+ let mut row: Line = vec![Span::raw(" "), Span::raw("│ ")];+ if fired {+ row.push(theme.fg_span(ThemeColor::Success, "»".to_string()));+ }+ row.push(theme.fg_span(+ if fired {+ ThemeColor::Success+ } else {+ marker_color+ },+ format!("{marker}▶ "),+ ));+ row.push(theme.fg_span(ThemeColor::MdLink, edge.to.clone()));+ if edge.from.len() > 1 {+ row.push(+ theme.fg_span(ThemeColor::Dim, format!(" (join: {})", edge.edge_label())),+ );+ }+ if let Some(guard) = &edge.when {+ row.push(theme.fg_span(ThemeColor::Dim, format!(" when {guard}")));+ }+ rows.push(row);+ }+ }+ }+}++/// A compact duration: seconds under a minute, minutes under an hour.+fn format_duration(ms: u64) -> String {+ let seconds = ms / 1_000;+ if seconds < 60 {+ format!("{seconds}s")+ } else if seconds < 3_600 {+ format!("{}m{:02}s", seconds / 60, seconds % 60)+ } else {+ format!("{}h{:02}m", seconds / 3_600, (seconds % 3_600) / 60)+ }+}diff --git a/crates/pa-tui/src/factory_view/diagram.rs b/crates/pa-tui/src/factory_view/diagram.rsnew file mode 100644index 0000000000..4e8a53dfc1--- /dev/null+++ b/crates/pa-tui/src/factory_view/diagram.rs@@ -0,0 +1,418 @@+//! The `/factory` view's diagram model: the snapshot shapes (states,+//! transitions, live nodes, usage — including each stage's agent+//! occupancy counts), the status glyphs and colors, and the compact+//! guard rendering. One graph model feeds the ASCII diagram, so the+//! in-terminal highlighting and the per-stage occupancy labels are the+//! same statement. Every daemon-provided string the model keeps scrubs+//! its control bytes at the parse seam (`scrubbed`): wire text can+//! never drive the terminal.++use serde_json::Value;++use super::get_either;+use crate::theme::ThemeColor;++/// One daemon-provided string scrubbed for the terminal+/// (`crate::menu_panel::scrub_controls`, the bash activity lane's rule):+/// the diagram's rows paint wire-provided ids, subagent names, guard+/// labels, statuses, and errors — none of them may carry a control byte+/// into a styled span (an OSC sequence in that text could otherwise+/// drive the terminal, e.g. overwrite the operator's clipboard via+/// OSC 52). The scrub lands at this parse seam, so every diagram row+/// paints terminal-safe text.+fn scrubbed(text: &str) -> String {+ crate::menu_panel::scrub_controls(text)+}++/// One machine state's declared shape.+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryState {+ pub id: String,+ pub entry: bool,+ pub lifecycle: String,+ pub max_entries: u64,+ pub subagent: Option<String>,+}++impl FactoryState {+ pub fn parse(value: &Value) -> Option<Self> {+ Some(Self {+ id: scrubbed(value.get("id")?.as_str()?),+ entry: value.get("entry").and_then(Value::as_bool).unwrap_or(false),+ lifecycle: value+ .get("lifecycle")+ .and_then(Value::as_str)+ .map_or_else(|| "task".to_string(), scrubbed),+ max_entries: get_either(value, "max_entries", "maxEntries")+ .and_then(Value::as_u64)+ .unwrap_or(1),+ subagent: value+ .get("subagent")+ .and_then(Value::as_str)+ .map(scrubbed)+ .filter(|text| !text.is_empty()),+ })+ }+}++/// One declared transition: a join carries every source in `from`.+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryTransition {+ pub from: Vec<String>,+ pub to: String,+ pub when: Option<String>,+}++impl FactoryTransition {+ pub fn parse(value: &Value) -> Option<Self> {+ let from = match value.get("from") {+ Some(Value::Array(sources)) => sources+ .iter()+ .filter_map(|source| source.as_str())+ .map(scrubbed)+ .collect::<Vec<_>>(),+ Some(Value::String(source)) => vec![scrubbed(source)],+ _ => return None,+ };+ if from.is_empty() {+ return None;+ }+ Some(Self {+ from,+ to: scrubbed(value.get("to")?.as_str()?),+ when: value+ .get("when")+ .and_then(format_guard)+ .map(|guard| scrubbed(&guard))+ .filter(|guard| !guard.is_empty()),+ })+ }++ /// The compact edge label: `a + b` for a join, the source id otherwise.+ pub fn edge_label(&self) -> String {+ self.from.join(" + ")+ }+}++/// One last-fired edge from the snapshot's trailing window. The optional+/// `when` carries the guard that fired — two guarded transitions may+/// share one from+to pair, so the guard is the identity that tells the+/// diagram WHICH of them fired.+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryEdge {+ pub from: Vec<String>,+ pub to: String,+ pub when: Option<String>,+}++impl FactoryEdge {+ pub fn parse(value: &Value) -> Option<Self> {+ let from = match value.get("from") {+ Some(Value::Array(sources)) => sources+ .iter()+ .filter_map(|source| source.as_str())+ .map(scrubbed)+ .collect::<Vec<_>>(),+ Some(Value::String(source)) => vec![scrubbed(source)],+ _ => return None,+ };+ if from.is_empty() {+ return None;+ }+ Some(Self {+ from,+ to: scrubbed(value.get("to")?.as_str()?),+ when: value+ .get("when")+ .and_then(format_guard)+ .map(|guard| scrubbed(&guard))+ .filter(|guard| !guard.is_empty()),+ })+ }++ /// The compact edge label, matching the transition's form.+ pub fn edge_label(&self) -> String {+ self.from.join(" + ")+ }++ /// Whether this fired edge is the given transition (the same+ /// sources, the same target, and the same guard — the snapshot's+ /// `from` may arrive in either order for a join, so the source+ /// comparison is order-free; a shared from+to pair with different+ /// guards never cross-marks).+ pub fn matches(&self, transition: &FactoryTransition) -> bool {+ self.to == transition.to+ && self.from.len() == transition.from.len()+ && self+ .from+ .iter()+ .all(|source| transition.from.contains(source))+ && self.when == transition.when+ }+}++/// One live node's runtime state (the `status()` node shape, compact+/// lane). `running`/`queued` are the kernel's per-stage agent counts —+/// how many agents run at the stage and how many queue behind them —+/// and both are single-word keys, so the wire's two spellings carry+/// them identically. `None` on an older kernel's reply, where the+/// accessors derive the counts from the instance rows.+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryNodeState {+ pub status: String,+ pub entries_used: u64,+ pub max_entries: u64,+ pub entries: Vec<String>,+ pub instances: Vec<String>,+ pub error: Option<String>,+ pub running: Option<u64>,+ pub queued: Option<u64>,+}++impl FactoryNodeState {+ pub fn parse(value: &Value) -> Option<Self> {+ let entries = value+ .get("entries")+ .and_then(Value::as_array)+ .map(|rows| {+ rows.iter()+ .filter_map(|entry| entry.get("status").and_then(Value::as_str))+ .map(scrubbed)+ .collect()+ })+ .unwrap_or_default();+ Some(Self {+ status: scrubbed(value.get("status")?.as_str()?),+ entries,+ entries_used: get_either(value, "entries_used", "entriesUsed")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ max_entries: get_either(value, "max_entries", "maxEntries")+ .and_then(Value::as_u64)+ .unwrap_or(1),+ instances: value+ .get("instances")+ .and_then(Value::as_array)+ .map(|instances| {+ instances+ .iter()+ .filter_map(|instance| instance.get("status").and_then(Value::as_str))+ .map(scrubbed)+ .collect()+ })+ .unwrap_or_default(),+ error: value.get("error").and_then(Value::as_str).map(scrubbed),+ running: value.get("running").and_then(Value::as_u64),+ queued: value.get("queued").and_then(Value::as_u64),+ })+ }++ /// The hysteresis signature's node part: the status, entries, and+ /// per-instance statuses.+ pub fn signature(&self) -> String {+ format!(+ "{}/{}:{}[{}]",+ self.status,+ self.entries_used,+ self.max_entries,+ self.instances.join(",")+ )+ }++ /// Whether the node is in flight: an entry pending (awaiting its+ /// inputs) or running, an instance still running or queued, or — for+ /// snapshots without entry rows — the derived `running` status. The+ /// instance arm is the occupancy contract: a foreach entry that failed+ /// permanently is terminal at the entry layer while its admitted+ /// siblings still run, so the row stays bright exactly while its+ /// occupancy label can be nonzero. A never-entered node (no entries)+ /// is not active: the diagram paints it dim, not bright.+ pub fn is_active(&self) -> bool {+ if self.entries.is_empty() {+ return self.status == "running";+ }+ self.entries+ .iter()+ .any(|status| status == "pending" || status == "running")+ || self.status == "running"+ || self.running_agents() > 0+ || self.queued_agents() > 0+ }++ /// Agents at this stage in flight (admitted children still+ /// running): the kernel's per-stage count when the reply carries+ /// it, else derived from the instance rows (an older kernel's+ /// reply).+ #[must_use]+ pub fn running_agents(&self) -> u64 {+ self.running+ .unwrap_or_else(|| self.instance_count("running"))+ }++ /// Agents at this stage queued (prepared, never admitted): the+ /// kernel's per-stage count when the reply carries it, else derived+ /// from the instance rows (an older kernel's reply).+ #[must_use]+ pub fn queued_agents(&self) -> u64 {+ self.queued+ .unwrap_or_else(|| self.instance_count("pending"))+ }++ fn instance_count(&self, status: &str) -> u64 {+ self.instances.iter().filter(|row| *row == status).count() as u64+ }++ /// The stage's occupancy label — `3 run · 2 queued` — when agents+ /// sit at this stage; a stage at rest carries no fragment. The+ /// ASCII row renders the stage's live headcount.+ #[must_use]+ pub fn occupancy_label(&self) -> String {+ let running = self.running_agents();+ let queued = self.queued_agents();+ if running == 0 && queued == 0 {+ String::new()+ } else {+ format!("{running} run · {queued} queued")+ }+ }++ /// The row's status text: the status, the entry count, and the error+ /// when one settled badly.+ #[must_use]+ pub fn status_line(&self, state: &FactoryState) -> String {+ let mut text = self.status.clone();+ if state.max_entries > 1 {+ text.push(' ');+ text.push_str(&self.entries_used.min(state.max_entries).to_string());+ text.push('/');+ text.push_str(&state.max_entries.to_string());+ }+ if let Some(error) = &self.error {+ text.push_str(" (");+ text.push_str(error);+ text.push(')');+ }+ text+ }+}++/// The run's usage block.+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryUsage {+ pub running: u64,+ pub settled: u64,+ pub spawns: u64,+ pub tool_uses: u64,+ pub max_parallel: u64,+ pub transitions_fired: u64,+}++impl FactoryUsage {+ pub fn parse(value: Option<&Value>) -> Option<Self> {+ let value = value?;+ Some(Self {+ running: value+ .get("running")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ settled: value+ .get("settled")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ spawns: value+ .get("spawns")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ tool_uses: get_either(value, "tool_uses", "toolUses")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ max_parallel: get_either(value, "max_parallel", "maxParallel")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ transitions_fired: get_either(value, "transitions_fired", "transitionsFired")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ })+ }+}++/// The status glyph and color for one node row: active nodes bright,+/// pending dim, done muted, errors red (the diagram's highlighting).+#[must_use]+pub fn node_glyph(status: &str) -> (&'static str, ThemeColor) {+ match status {+ "running" => ("●", ThemeColor::Accent),+ "pending" => ("◐", ThemeColor::Dim),+ "done" => ("✓", ThemeColor::Muted),+ "error" => ("✗", ThemeColor::Error),+ "cancelled" => ("⊘", ThemeColor::Muted),+ _ => ("○", ThemeColor::Dim),+ }+}++/// The run-state color for the panel header.+#[must_use]+pub fn run_state_color(state: Option<&str>) -> ThemeColor {+ match state {+ Some("running" | "stopping") => ThemeColor::Accent,+ Some("paused") => ThemeColor::Warning,+ Some("done") => ThemeColor::Success,+ Some("failed" | "stopped") => ThemeColor::Error,+ _ => ThemeColor::Muted,+ }+}++/// The connector marker for one transition row: the last edge under a+/// source uses the elbow (`└`), joins use the crossbar (`╪`), and a back+/// edge (re-entry, a target earlier in the machine's declared order)+/// carries the return marker (`↩`).+#[must_use]+pub fn edge_marker(+ transition: &FactoryTransition,+ order: &[&str],+ position: impl Fn(&str) -> Option<usize>,+) -> (&'static str, ThemeColor) {+ let back_edge = position(&transition.to)+ .zip(transition.from.first().map(String::as_str))+ .is_some_and(|(target, source)| {+ position(source).is_some_and(|source_position| target < source_position)+ });+ let color = if back_edge {+ ThemeColor::Muted+ } else {+ ThemeColor::BorderMuted+ };+ let marker = if transition.from.len() > 1 {+ "├╪"+ } else if back_edge {+ "├↩"+ } else if order.last().is_some_and(|last| *last == transition.from[0]) {+ "└"+ } else {+ "├"+ };+ (marker, color)+}++/// The compact guard rendering: `verdict.approved eq false`.+#[must_use]+pub fn format_guard(when: &Value) -> Option<String> {+ let object = when.as_object()?;+ let output = object.get("output").and_then(Value::as_str)?;+ let path = object+ .get("path")+ .and_then(Value::as_str)+ .map(|path| format!(".{path}"))+ .unwrap_or_default();+ let op = object.get("op").and_then(Value::as_str).unwrap_or("eq");+ match object.get("value") {+ Some(value) => Some(format!(+ "{output}{path} {op} {}",+ serde_json::to_string(value).ok()?+ )),+ // The valueless form reads `output.path op` (the same shape as the+ // valued form minus the comparison target — `verdict exists`, not+ // `verdictexists`).+ None => Some(format!("{output}{path} {op}")),+ }+}diff --git a/crates/pa-tui/src/factory_view/tests.rs b/crates/pa-tui/src/factory_view/tests.rsnew file mode 100644index 0000000000..eb3b2ef939--- /dev/null+++ b/crates/pa-tui/src/factory_view/tests.rs@@ -0,0 +1,1953 @@+//! The `/factory` view's battery: the snapshot parsing, the diagram's+//! highlighted rendering (asserted per span, so removing the active-node+//! marking fails the test — the mutation check), the picker keyset (the+//! arrows + Enter + Esc loop and the in-page action rows), the repaint+//! hysteresis, and the scale battery (the complex machine and the+//! fifteen-run world: selection stability, the dock's liveness count,+//! the render window, the refresh markers, and the churn discipline).++use super::*;+use crate::keybindings::KeybindingsManager;+use crate::theme::{ColorMode, Theme};+use serde_json::json;++fn theme() -> Theme {+ Theme::builtin("prime", ColorMode::TrueColor)+}++fn kb() -> KeybindingsManager {+ KeybindingsManager::new()+}++/// Rendered rows as trimmed plain text (tmux-capture shape).+fn frame_text(view: &mut FactoryView) -> Vec<String> {+ view.render(&theme(), 110, &kb())+ .iter()+ .map(|line| {+ line.iter()+ .map(|span| span.content.as_str())+ .collect::<String>()+ })+ .map(|row| row.trim_end().to_string())+ .collect()+}++/// One span row's styles, for the highlighting assertions.+fn frame_spans(view: &mut FactoryView) -> Vec<Vec<crate::Span>> {+ view.render(&theme(), 110, &kb())+}++/// A scripted run in the ACTIVITY LANE's wire shape — derived from a+/// real `factory_activity` graph reply (the kernel's `_graph_snapshot`+/// rows converted by `_wire_payload` in `rlm/factory.py`: the reply+/// keys are camelCase end to end, matching the protocol's request+/// frame): the review-loop machine mid-flight — collect done, reviewing+/// running (its first entry settled, so the collect edge fired), fixing+/// pending — plus the usage and milestone tail. Every node row carries+/// the kernel's per-stage agent counts (`running`/`queued`, single-word+/// keys both wire spellings carry identically).+fn scripted_snapshot() -> serde_json::Value {+ json!({+ "runId": "run-abc12345",+ "specId": "review-loop",+ "name": "review-loop",+ "state": "running",+ "pauseReason": null,+ "elapsedMs": 45_000,+ "machine": {+ "run": { "maxParallel": 4, "maxTransitions": 40, "failurePolicy": "continue", "budgetMs": 600_000 },+ "states": [+ { "id": "collect", "entry": true, "lifecycle": "task", "maxEntries": 1, "retries": 0, "subagent": "researcher" },+ { "id": "reviewing", "entry": false, "lifecycle": "task", "maxEntries": 4, "retries": 1 },+ { "id": "fixing", "entry": false, "lifecycle": "task", "maxEntries": 3, "retries": 0 }+ ],+ "transitions": [+ { "from": "collect", "to": "reviewing", "on": "settled" },+ { "from": "reviewing", "to": "fixing", "on": "settled",+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": false } },+ { "from": "reviewing", "to": "reviewing", "on": "settled", "when": { "output": "verdict", "op": "exists" } },+ { "from": "fixing", "to": "reviewing", "on": "settled" }+ ],+ "order": ["collect", "reviewing", "fixing"]+ },+ "nodes": [+ { "id": "collect", "status": "done", "lifecycle": "task", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 1,+ "entries": [ { "index": 0, "status": "done", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "done", "attempt": 1, "child": "child-1", "durationMs": 5, "error": null } ],+ "running": 0, "queued": 0 },+ { "id": "reviewing", "status": "running", "lifecycle": "task", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 4,+ "entries": [ { "index": 0, "status": "running", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "running", "attempt": 1, "child": "child-2", "durationMs": 0, "error": null } ],+ "running": 1, "queued": 0 },+ { "id": "fixing", "status": "pending", "lifecycle": "task", "attempts": 0,+ "entriesUsed": 0, "maxEntries": 3, "entries": [], "instances": [],+ "running": 0, "queued": 0 }+ ],+ "activeNodes": ["reviewing"],+ "lastFired": [ { "from": "collect", "to": "reviewing", "seq": 7 } ],+ "events": [+ { "seq": 1, "kind": "milestone", "stage": "shown", "milestone": "started" },+ { "seq": 7, "kind": "transition_fired", "stage": "recorded", "from": "collect", "to": "reviewing" }+ ],+ "usage": { "spawns": 2, "settled": 1, "toolUses": 5, "maxParallel": 4,+ "running": 1, "transitionsFired": 1 },+ "budget": { "limitMs": 600_000, "consumedMs": 45_000 }+ })+}++/// The same reply in the KERNEL's conversation shape (the wire fixture+/// with every key re-spelled `snake_case`): the parser tolerates both+/// spellings, so this fixture must parse to the identical struct.+fn kernel_shape_snapshot() -> serde_json::Value {+ rekey_snake(&scripted_snapshot())+}++/// Re-spell a wire fixture's keys `snake_case` (`runId` -> `run_id`),+/// the mechanical mirror of the kernel's `_wire_payload` so the two+/// fixtures can never drift.+fn rekey_snake(value: &serde_json::Value) -> serde_json::Value {+ fn snake(key: &str) -> String {+ let mut out = String::with_capacity(key.len() + 4);+ for character in key.chars() {+ if character.is_ascii_uppercase() {+ out.push('_');+ out.push(character.to_ascii_lowercase());+ } else {+ out.push(character);+ }+ }+ out+ }+ match value {+ serde_json::Value::Object(object) => object+ .iter()+ .map(|(key, item)| (snake(key), rekey_snake(item)))+ .collect(),+ serde_json::Value::Array(rows) => rows.iter().map(rekey_snake).collect(),+ other => other.clone(),+ }+}++fn runs_response(snapshot: &serde_json::Value) -> serde_json::Value {+ json!({ "runs": [snapshot] })+}++/// Two live runs for the battery, in the reply's start order (oldest+/// first — the kernel's documented polling order): review-loop started+/// first, second-run after it, so second-run is the NEWEST run and+/// renders on top. The name differs so the header rows tell the runs+/// apart, and the elapsed clocks match on purpose — a same-clock pair+/// is exactly where an elapsed sort would be ambiguous and the reply's+/// start order is not.+fn two_run_response() -> serde_json::Value {+ let mut response = runs_response(&scripted_snapshot());+ let second = scripted_snapshot();+ response["runs"].as_array_mut().unwrap().push(second);+ response["runs"][1]["runId"] = json!("run-def67890");+ response["runs"][1]["name"] = json!("second-run");+ response+}++/// Three live runs, again in the reply's start order (oldest first):+/// the third row is a run created after both — the fold battery's+/// "a newer run appears on top" case.+fn three_run_response() -> serde_json::Value {+ let mut response = two_run_response();+ let third = scripted_snapshot();+ response["runs"].as_array_mut().unwrap().push(third);+ response["runs"][2]["runId"] = json!("run-ghi13579");+ response["runs"][2]["name"] = json!("third-run");+ response+}++/// The two newer runs remain after the oldest leaves the reply (the wire+/// cap's oldest-end trim), still in the reply's start order.+fn later_pair_response() -> serde_json::Value {+ let mut response = runs_response(&scripted_snapshot());+ response["runs"][0]["runId"] = json!("run-def67890");+ response["runs"][0]["name"] = json!("second-run");+ let third = scripted_snapshot();+ response["runs"].as_array_mut().unwrap().push(third);+ response["runs"][1]["runId"] = json!("run-ghi13579");+ response["runs"][1]["name"] = json!("third-run");+ response+}++/// The same wire reply with a full per-stage occupancy: reviewing runs+/// a five-instance entry under the run's three-slot cap — three+/// admitted (running), two queued — with the kernel's counts and the+/// instance rows agreeing (`maxParallel` drops to 3: the cap is why+/// two instances queue).+fn occupied_snapshot() -> serde_json::Value {+ let mut snapshot = scripted_snapshot();+ snapshot["machine"]["run"]["maxParallel"] = json!(3);+ snapshot["usage"]["maxParallel"] = json!(3);+ snapshot["usage"]["spawns"] = json!(3);+ snapshot["usage"]["running"] = json!(3);+ snapshot["nodes"][1]["running"] = json!(3);+ snapshot["nodes"][1]["queued"] = json!(2);+ snapshot["nodes"][1]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "running", "attempt": 1, "child": "child-2", "durationMs": 0, "error": null },+ { "index": 1, "entry": 0, "status": "running", "attempt": 1, "child": "child-3", "durationMs": 0, "error": null },+ { "index": 2, "entry": 0, "status": "running", "attempt": 1, "child": "child-4", "durationMs": 0, "error": null },+ { "index": 3, "entry": 0, "status": "pending", "attempt": 0, "child": null, "durationMs": null, "error": null },+ { "index": 4, "entry": 0, "status": "pending", "attempt": 0, "child": null, "durationMs": null, "error": null }+ ]);+ snapshot+}++/// The occupied reply without the kernel's count keys: an older+/// kernel's shape, where the occupancy derives from the instance rows.+fn occupied_snapshot_without_counts() -> serde_json::Value {+ let mut snapshot = occupied_snapshot();+ for node in snapshot["nodes"].as_array_mut().unwrap().iter_mut() {+ let object = node.as_object_mut().expect("node rows are objects");+ object.remove("running");+ object.remove("queued");+ }+ snapshot+}++/// The parser fuses the structure and the live overlay from the wire+/// reply's `camelCase` keys (a wrong-spelling read defaults every field,+/// so each field below is the mutation check on its key).+#[test]+fn parsing_fuses_structure_and_live_state() {+ let runs = parse_factory_runs(&runs_response(&scripted_snapshot()));+ assert_eq!(runs.len(), 1);+ let run = &runs[0];+ assert_eq!(run.run_id, "run-abc12345");+ assert_eq!(run.spec_id, "review-loop");+ assert_eq!(run.state.as_deref(), Some("running"));+ assert_eq!(run.elapsed_ms, 45_000, "elapsedMs (the wire spelling)");+ assert_eq!(run.budget_limit_ms, Some(600_000), "budget.limitMs");+ assert_eq!(run.states.len(), 3);+ assert!(run.states[0].entry);+ assert_eq!(run.states[1].max_entries, 4, "state maxEntries");+ assert_eq!(run.transitions.len(), 4);+ assert_eq!(run.nodes["reviewing"].status, "running");+ assert_eq!(run.nodes["reviewing"].entries_used, 1, "node entriesUsed");+ assert_eq!(run.nodes["reviewing"].max_entries, 4, "node maxEntries");+ assert_eq!(+ run.nodes["reviewing"].running,+ Some(1),+ "the per-state running count"+ );+ assert_eq!(+ run.nodes["reviewing"].queued,+ Some(0),+ "the per-state queued count"+ );+ assert_eq!(run.last_fired[0].to, "reviewing");+ assert_eq!(run.milestones, vec!["started".to_string()]);+ let usage = run.usage.as_ref().expect("usage parses");+ assert_eq!(usage.running, 1);+ assert_eq!(usage.tool_uses, 5, "usage toolUses");+ assert_eq!(usage.max_parallel, 4, "usage maxParallel");+ assert_eq!(usage.transitions_fired, 1, "usage transitionsFired");+ assert_eq!(+ run.active_state_ids(),+ vec!["reviewing".to_string()],+ "the running node is the active one"+ );+}++/// Both spellings parse: the activity wire's `camelCase` reply and the+/// kernel's `snake_case` conversation shape fuse to the identical+/// struct (the tolerance pin — a single-spelling parser drops the other+/// side's rows, which is exactly the always-empty-view bug).+#[test]+fn parsing_tolerates_both_wire_spellings() {+ let wire = parse_factory_runs(&runs_response(&scripted_snapshot()));+ let kernel = parse_factory_runs(&runs_response(&kernel_shape_snapshot()));+ assert_eq!(kernel.len(), 1, "the snake_case conversation shape parses");+ assert_eq!(kernel[0].run_id, "run-abc12345");+ assert_eq!(kernel[0].usage.as_ref().unwrap().tool_uses, 5);+ assert_eq!(wire.len(), 1, "the camelCase wire shape parses");+ assert_eq!(wire[0], kernel[0], "both spellings fuse to the same run");+}++/// The diagram renders the machine's rows and connectors, with the fired+/// edge marked.+#[test]+fn the_diagram_renders_states_edges_and_the_fired_marker() {+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&scripted_snapshot())), 40);+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(+ joined.contains("factory: review-loop — running"),+ "{joined}"+ );+ assert!(joined.contains("✓ collect"), "the done row: {joined}");+ assert!(joined.contains("reviewing"), "{joined}");+ assert!(joined.contains("fixing"), "{joined}");+ assert!(joined.contains("collect"), "{joined}");+ assert!(joined.contains("»"), "the last-fired marker: {joined}");+ assert!(+ joined.contains("when verdict.approved eq false"),+ "the guard label: {joined}"+ );+ assert!(+ joined.contains("when verdict exists"),+ "the valueless guard label: {joined}"+ );+ assert!(joined.contains("milestones: started"), "{joined}");+ assert!(joined.contains("1 running"), "{joined}");+ assert!(+ joined.contains("1/4 parallel"),+ "the max_parallel stat: {joined}"+ );+ assert!(+ joined.contains("1 transitions"),+ "the transitions_fired stat: {joined}"+ );+}++/// The per-stage agent occupancy (the UX ask): a stage's label carries+/// how many agents sit at it — `reviewing (3 run · 2 queued)` — read+/// from the kernel's per-state counts, with the instance rows as the+/// fallback for an older kernel's reply; a stage at rest carries no+/// fragment (the mutation checks: removing the label render empties+/// the row of the counts, and dropping the kernel-count parse or the+/// instance-row fallback fails the count assertions below).+#[test]+fn the_diagram_renders_per_stage_agent_occupancy() {+ let runs = parse_factory_runs(&runs_response(&occupied_snapshot()));+ assert_eq!(+ runs[0].nodes["reviewing"].running,+ Some(3),+ "the kernel's running count parses"+ );+ assert_eq!(+ runs[0].nodes["reviewing"].queued,+ Some(2),+ "the kernel's queued count parses"+ );+ let mut view = FactoryView::new(runs, 40);+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(+ joined.contains("reviewing (3 run · 2 queued)"),+ "the occupied stage's label carries its agent counts: {joined}"+ );+ assert!(+ !joined.contains("(0 run"),+ "a stage at rest carries no occupancy fragment: {joined}"+ );+ // An older kernel's reply (no count keys) derives the same counts+ // from the instance rows.+ let runs = parse_factory_runs(&runs_response(&occupied_snapshot_without_counts()));+ assert_eq!(+ runs[0].nodes["reviewing"].running, None,+ "no count keys ride the older reply"+ );+ assert_eq!(+ runs[0].nodes["reviewing"].running_agents(),+ 3,+ "running derives from the instance rows"+ );+ assert_eq!(+ runs[0].nodes["reviewing"].queued_agents(),+ 2,+ "queued derives from the instance rows"+ );+ let mut view = FactoryView::new(runs, 40);+ let rows = frame_text(&mut view);+ assert!(+ rows.join("\n").contains("reviewing (3 run · 2 queued)"),+ "the fallback renders the same occupancy"+ );+}++/// The highlighting: the active node's row paints in the accent (bright)+/// color and the pending node in the dim color — removing the marking+/// fails this test (the mutation check on the diagram's highlighting).+#[test]+fn active_nodes_paint_bright_and_pending_paints_dim() {+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&scripted_snapshot())), 40);+ let rows = frame_spans(&mut view);+ let accent = theme().fg_style(ThemeColor::Accent);+ let dim = theme().fg_style(ThemeColor::Dim);+ let styled = |rows: &Vec<crate::Span>, style: crate::Style, text: &str| {+ rows.iter()+ .any(|span| span.content.contains(text) && span.style == style)+ };+ // The active node's id is accent-bright.+ let reviewing_bright = rows.iter().any(|row| styled(row, accent, "reviewing"));+ assert!(reviewing_bright, "reviewing must paint accent");+ // The never-entered node paints dim.+ let fixing_dim = rows.iter().any(|row| styled(row, dim, "fixing"));+ assert!(fixing_dim, "fixing must paint dim");+ // The last-fired edge's marker paints success.+ let success = theme().fg_style(ThemeColor::Success);+ let fired_marked = rows.iter().any(|row| {+ row.iter()+ .any(|span| span.content.contains("»") && span.style == success)+ });+ assert!(fired_marked, "the fired marker must paint success");+}++/// The instance layer paints the row too: a foreach entry that failed+/// permanently is terminal at the entry layer while its admitted+/// siblings still run (the continue policy), so the occupancy label+/// keeps showing agents at the stage and the row stays bright (the+/// mutation check: keying on the entry rows alone paints a stage with+/// live children settled).+#[test]+fn a_terminal_entry_with_running_instances_stays_bright() {+ let mut snapshot = scripted_snapshot();+ // `reviewing`'s single foreach entry failed permanently; its second+ // instance is still in flight, so the occupancy keeps one agent.+ snapshot["nodes"][1]["status"] = json!("error");+ snapshot["nodes"][1]["entries"] = json!([+ { "index": 0, "status": "error", "error": "boom" },+ ]);+ snapshot["nodes"][1]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "error", "attempt": 1, "child": "child-2", "durationMs": 5, "error": "boom" },+ { "index": 1, "entry": 0, "status": "running", "attempt": 1, "child": "child-3", "durationMs": 0, "error": null }+ ]);+ snapshot["nodes"][1]["running"] = json!(1);+ snapshot["nodes"][1]["queued"] = json!(0);+ snapshot["usage"]["running"] = json!(1);+ snapshot["activeNodes"] = json!(["reviewing"]);+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&snapshot)), 40);+ let rows = frame_spans(&mut view);+ let accent = theme().fg_style(ThemeColor::Accent);+ let bright = rows.iter().any(|row| {+ row.iter()+ .any(|span| span.content.contains("reviewing") && span.style == accent)+ });+ assert!(+ bright,+ "the running sibling keeps the failed entry's row bright"+ );+ let text = frame_text(&mut view);+ assert!(+ text.join("\n").contains("reviewing (1 run · 0 queued)"),+ "the occupancy label still shows the in-flight sibling"+ );+}++/// The node's live activity paints the row, not the aggregate status: a+/// multi-entry state whose latest entry settled while an earlier one+/// still runs stays bright in the terminal diagram (the mutation check:+/// keying on `status` alone paints the in-flight state settled).+#[test]+fn a_multi_entry_state_with_an_in_flight_entry_stays_bright() {+ let mut snapshot = scripted_snapshot();+ // `reviewing` has maxEntries 4: its latest entry settled (status+ // "done") while an earlier entry still runs.+ snapshot["nodes"][1]["status"] = json!("done");+ snapshot["nodes"][1]["entries"] = json!([+ { "index": 0, "status": "running", "error": null },+ { "index": 1, "status": "done", "error": null },+ ]);+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&snapshot)), 40);+ let rows = frame_spans(&mut view);+ let accent = theme().fg_style(ThemeColor::Accent);+ let bright = rows.iter().any(|row| {+ row.iter()+ .any(|span| span.content.contains("reviewing") && span.style == accent)+ });+ assert!(bright, "the in-flight earlier entry keeps the row accent");+}++/// The reply-shape contract: a graph reply without the runs list is a+/// malformed lane, never zero runs (the empty state reflects real+/// emptiness — the mutation check on the malformed-reply guard).+#[test]+fn a_reply_without_the_runs_list_is_malformed_not_empty() {+ assert!(+ factory_reply_lists_runs(&json!({ "runs": [] })),+ "the empty runs list IS the real empty state"+ );+ assert!(+ !factory_reply_lists_runs(&json!({})),+ "a missing runs list is a malformed lane"+ );+ assert!(+ !factory_reply_lists_runs(&json!({ "machine": {} })),+ "a wrong-shape reply is a malformed lane"+ );+ assert!(+ !factory_reply_lists_runs(&json!("runs")),+ "a non-object reply is a malformed lane"+ );+ assert!(+ !factory_reply_lists_runs(&json!({ "runs": {} })),+ "a present non-array runs value is a malformed lane"+ );+ assert!(+ !factory_reply_lists_runs(&json!({ "runs": "x" })),+ "a string runs value is a malformed lane"+ );+}++/// The terminal-safety pin (the daemon-text scrub): every string the+/// view paints comes from the daemon's reply, and a reply carrying an+/// OSC 52 payload — or any ANSI/OSC sequence — must never drive the+/// terminal (e.g. overwrite the operator's clipboard). The parse seam+/// scrubs control bytes to spaces (`scrub_controls`, the bash activity+/// lane's rule); the run id alone stays raw — it never paints and must+/// round-trip the kernel's registry as the stop/resume/watch identity+/// (the mutation checks: an unscrubbed name, state id, or error line+/// fails the assertions here).+#[test]+fn daemon_text_never_carries_terminal_control_sequences() {+ let mut snapshot = scripted_snapshot();+ // The OSC 52 clipboard-overwrite payload and an ANSI SGR sequence,+ // in every display string the view paints.+ snapshot["name"] = json!("run\x1b]52;c;dGVzdA==\x07name");+ snapshot["specId"] = json!("spec\x1b[31mid");+ snapshot["machine"]["states"][0]["id"] = json!("col\x1b]52;c;evil\x07lect");+ snapshot["nodes"][0]["id"] = json!("col\x1b]52;c;evil\x07lect");+ snapshot["machine"]["states"][0]["subagent"] = json!("sub\x1b[31magent");+ snapshot["machine"]["transitions"][0]["when"] = json!({+ "output": "ver\x1b]52;c;evil\x07dict", "op": "eq", "value": false+ });+ snapshot["nodes"][0]["error"] = json!("err\x1b]52;c;evil\x07or");+ snapshot["events"][0]["milestone"] = json!("mile\x1b[31mstone");+ let has_control = |text: &str| text.chars().any(|c| c.is_control() && c != '\n');+ let runs = parse_factory_runs(&runs_response(&snapshot));+ assert!(+ runs.iter().all(|run| !has_control(&run.display_name())+ && !has_control(&run.states[0].id)+ && run.milestones.iter().all(|m| !has_control(m))),+ "the parsed display strings carry no control byte"+ );+ // The run id stays raw: it never paints, and the kernel's registry+ // answers it verbatim.+ assert_eq!(runs[0].run_id, "run-abc12345");+ // The painted frame carries no control byte either — scrubbed+ // text is the only thing that reaches a span.+ let mut view = FactoryView::new(runs, 40);+ view.set_error(Some("boom\x1b]52;c;evil\x07".to_string()));+ let rows = frame_text(&mut view);+ for row in &rows {+ assert!(+ !has_control(row),+ "a rendered row carries no control byte: {row:?}"+ );+ }+ assert!(+ rows.iter().any(|row| row.contains("Error: boom")),+ "the scrubbed error text still paints: {rows:?}"+ );+}++/// The mount contract (the open path's malformed cache): a cached reply+/// without the runs list is a malformed lane, not zero runs — mounting+/// from it sets the malformed-reply error at once instead of painting a+/// silent fake empty state for a poll cycle until the first fold+/// reports the lane (the fold's contract, held at mount; the mutation+/// check: mounting without the check paints no error line).+#[test]+fn a_malformed_cached_reply_mounts_with_the_error_not_a_silent_empty() {+ // A malformed cache mounts with the error line painted.+ let mut view = FactoryView::from_reply(&json!({ "machine": {} }), 40);+ let joined = frame_text(&mut view).join("\n");+ assert!(+ joined.contains("Error: malformed factory reply (no runs list)"),+ "the malformed cache reports itself at mount: {joined}"+ );+ // A real empty reply (the runs list present) mounts clean: the+ // genuine empty state, no error line.+ let mut view = FactoryView::from_reply(&json!({ "runs": [] }), 40);+ let joined = frame_text(&mut view).join("\n");+ assert!(+ joined.contains("No live factory runs."),+ "an empty runs list is the real empty state: {joined}"+ );+ assert!(+ !joined.contains("Error:"),+ "a real empty state never reports a malformed lane: {joined}"+ );+ // A good cache mounts its runs with no error line.+ let mut view = FactoryView::from_reply(&two_run_response(), 40);+ let joined = frame_text(&mut view).join("\n");+ assert!(+ joined.contains("factory: second-run"),+ "the cached runs mount newest-first: {joined}"+ );+ assert!(+ !joined.contains("Error:"),+ "a good cache mounts clean: {joined}"+ );+}++/// The fired-edge identity includes the guard: two transitions may share+/// one from+to pair with different guards, so the fired marking must+/// light only the one that fired (the mutation check: matching on+/// from+to alone cross-marks the sibling).+#[test]+fn the_fired_edge_identity_includes_the_guard() {+ let mut snapshot = scripted_snapshot();+ snapshot["machine"]["transitions"] = json!([+ { "from": "collect", "to": "reviewing", "on": "settled" },+ { "from": "reviewing", "to": "fixing", "on": "settled",+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": false } },+ { "from": "reviewing", "to": "fixing", "on": "settled",+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": true } }+ ]);+ // Only the first guard fired; the edge carries its guard.+ snapshot["lastFired"] = json!([+ { "from": "reviewing", "to": "fixing", "seq": 9,+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": false } }+ ]);+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&snapshot)), 40);+ let rows = frame_text(&mut view);+ // Both sibling edges render; the fired `»` sits ONLY on the row of+ // the guard that fired — the sibling row with the same from+to+ // carries no marker.+ let fired_row = rows+ .iter()+ .find(|row| row.contains("\u{bb}"))+ .expect("the fired marker renders");+ assert!(+ fired_row.contains("verdict.approved eq false"),+ "the fired marker sits on the fired guard's edge: {fired_row}"+ );+ let sibling = rows+ .iter()+ .find(|row| row.contains("verdict.approved eq true"))+ .expect("the sibling guard's edge renders");+ assert!(+ !sibling.contains("\u{bb}"),+ "the sibling guard with the same from+to never cross-marks: {sibling}"+ );+}++/// The empty state and the key hint.+#[test]+fn the_empty_state_names_the_surface() {+ let mut view = FactoryView::new(Vec::new(), 40);+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(joined.contains("No live factory runs."), "{joined}");+ assert!(joined.contains("await rlm.factory.run"), "{joined}");+ assert!(+ joined.contains("move"),+ "the hint names the arrows: {joined}"+ );+ assert!(joined.contains("actions"), "{joined}");+ assert!(joined.contains("close"), "{joined}");+}++/// The picker keyset (arrows + Enter + Esc — the heartbeats/bash pages'+/// family): the arrows move the run selection, Enter opens the selected+/// run's in-page action rows (stop/resume, the offered set derived from+/// the run's state) and runs the tracked action, Esc backs out of the+/// action rows before it closes the page.+#[test]+fn the_key_loop_resolves_the_orchestration_actions() {+ let runs = parse_factory_runs(&two_run_response());+ let mut view = FactoryView::new(runs, 40);+ // The feed: the newest run is selected, the arrows walk the feed —+ // down reads older, up reads newer, and both ends clamp.+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-def67890".to_string())+ );+ let _ = view.handle_key("down", &kb());+ assert_eq!(view.selected, 1);+ let _ = view.handle_key("down", &kb());+ assert_eq!(view.selected, 1, "down clamps at the oldest run");+ let _ = view.handle_key("up", &kb());+ assert_eq!(view.selected, 0);+ let _ = view.handle_key("up", &kb());+ assert_eq!(view.selected, 0, "up clamps at the newest run");+ // The letters are not page keys (the keyset is arrows + Enter + Esc):+ // j/k/s/r move nothing and act on nothing (the mutation check: a+ // restored j/k arm moves the selection and fails this pin).+ for letter in ["j", "k", "s", "r", "m"] {+ assert_eq!(view.handle_key(letter, &kb()), FactoryViewAction::None);+ assert_eq!(view.selected, 0, "{letter} moved nothing");+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-def67890".to_string()),+ "no letter changed the focused run"+ );+ // Enter opens the selected run's action rows: a running run offers+ // exactly stop, the block names the run, and the hint flips to the+ // action grammar.+ assert_eq!(view.handle_key("enter", &kb()), FactoryViewAction::None);+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(joined.contains("actions: second-run"), "{joined}");+ assert!(joined.contains("▸ Stop the run"), "{joined}");+ assert!(joined.contains("action · Enter run · Esc back"), "{joined}");+ // Enter runs the tracked action: the stop rides the SELECTED run.+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-def67890".to_string()+ }+ );+ // Esc backs out of the action rows to the feed, then closes.+ let _ = view.handle_key("enter", &kb());+ assert_eq!(view.handle_key("escape", &kb()), FactoryViewAction::None);+ assert!(+ frame_text(&mut view).join("\n").contains("Enter actions"),+ "Esc returns the feed's hint"+ );+ // The real key id for the Escape key is "escape" (`key_event_to_id`)+ // — the page must close on it (the mutation check: matching only+ // "esc" strands the Escape key).+ assert_eq!(+ view.handle_key("escape", &kb()),+ FactoryViewAction::Close,+ "the Escape key closes the page"+ );+ assert_eq!(view.handle_key("esc", &kb()), FactoryViewAction::Close);+ assert_eq!(view.handle_key("ctrl+c", &kb()), FactoryViewAction::Close);+ // A paused run offers the pause complement first — resume — then+ // stop; the arrows walk the offered set, Enter runs the tracked+ // one.+ let mut paused = parse_factory_runs(&runs_response(&scripted_snapshot()));+ paused[0].state = Some("paused".to_string());+ let mut view = FactoryView::new(paused, 40);+ let _ = view.handle_key("enter", &kb());+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(joined.contains("▸ Resume the run"), "{joined}");+ assert!(joined.contains("Stop the run"), "{joined}");+ // The tracked action is resume (the complement first); walking down+ // lands on stop, and Enter runs stop.+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Resume {+ run_id: "run-abc12345".to_string()+ }+ );+ let _ = view.handle_key("enter", &kb());+ let _ = view.handle_key("down", &kb());+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-abc12345".to_string()+ }+ );+ // A fully terminal run offers nothing: Enter answers no rows.+ let mut terminal = parse_factory_runs(&runs_response(&scripted_snapshot()));+ terminal[0].state = Some("done".to_string());+ terminal[0].usage.as_mut().unwrap().running = 0;+ let mut view = FactoryView::new(terminal, 40);+ assert_eq!(view.handle_key("enter", &kb()), FactoryViewAction::None);+ assert!(+ !frame_text(&mut view).join("\n").contains("actions: "),+ "a terminal run opens no action rows"+ );+}++/// The repaint hysteresis: an unchanged snapshot applies without a+/// changed marker, a state/instance change lights it exactly for that+/// run, the marker decays once quiescent, and the clock never trips it+/// (elapsed-only movement is not notice-worthy — the mutation check on+/// the signature).+#[test]+fn apply_runs_lights_the_marker_only_on_notice_worthy_changes() {+ let runs = parse_factory_runs(&runs_response(&scripted_snapshot()));+ let mut view = FactoryView::new(runs, 40);+ // The same snapshot: no change.+ let changed = view.apply_runs(parse_factory_runs(&runs_response(&scripted_snapshot())));+ assert!(!changed, "an identical snapshot changes nothing");+ let rows = frame_text(&mut view);+ assert!(+ !rows.join("\n").contains("changed"),+ "the marker stays off for an identical snapshot"+ );+ // The instance settles: a notice-worthy change.+ let mut settled = scripted_snapshot();+ settled["nodes"][1]["status"] = json!("done");+ settled["nodes"][1]["instances"][0]["status"] = json!("done");+ let changed = view.apply_runs(parse_factory_runs(&runs_response(&settled)));+ assert!(changed, "a state/instance change is notice-worthy");+ let rows = frame_text(&mut view);+ assert!(+ rows.join("\n").contains("changed"),+ "the changed marker lights on the state change"+ );+ // The marker decays on the next unchanged cycle.+ let changed = view.apply_runs(parse_factory_runs(&runs_response(&settled)));+ assert!(!changed);+ let rows = frame_text(&mut view);+ assert!(+ !rows.join("\n").contains("changed"),+ "the marker decays once quiescent"+ );+ // The clock never trips the marker: an elapsed-only bump repaints the+ // stats line but is not a notice-worthy run-shape change.+ let mut older = settled;+ older["elapsed_ms"] = json!(120_000);+ let changed = view.apply_runs(parse_factory_runs(&runs_response(&older)));+ assert!(+ !changed,+ "an elapsed-only bump is not a notice-worthy change"+ );+ let rows = frame_text(&mut view);+ assert!(+ !rows.join("\n").contains("changed"),+ "the clock keeps the changed marker off"+ );+}++/// The reading order (the UX pin): the reply carries the registry's+/// start order, oldest run first, and the view reads it NEWEST-FIRST+/// like a live activity feed — a run created after an existing one+/// renders ABOVE it, and the page opens with the newest run selected+/// (the mutation check: rendering the reply's insertion order instead+/// fails every assertion here).+#[test]+fn the_runs_list_reads_newest_first_and_opens_on_the_newest_run() {+ // The reply's order is start order: review-loop started first,+ // second-run after it.+ let runs = parse_factory_runs(&two_run_response());+ assert_eq!(+ runs.iter()+ .map(|run| run.run_id.as_str())+ .collect::<Vec<_>>(),+ vec!["run-def67890", "run-abc12345"],+ "the parsed list reads newest-first"+ );+ // The page opens with the newest run selected.+ let mut view = FactoryView::new(runs, 40);+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-def67890".to_string()),+ "the newest run is the default selection"+ );+ // The rendered frame: the newest run's panel is the first panel and+ // the older run renders below it.+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ let first_header = rows+ .iter()+ .find(|row| row.contains("factory: "))+ .expect("the panels render");+ assert!(+ first_header.contains("second-run"),+ "the newest run's panel renders first: {joined}"+ );+ let newest = rows+ .iter()+ .position(|row| row.contains("factory: second-run"))+ .expect("the newest run's header renders");+ let older = rows+ .iter()+ .position(|row| row.contains("factory: review-loop"))+ .expect("the older run's header renders");+ assert!(+ newest < older,+ "a run created after an existing one appears above it: {joined}"+ );+}++/// Two runs: the selection moves down the feed, and a refresh keeps+/// the selection on the SAME RUN, never the same index — a newer run+/// folding in on top moves the selected run down the list without+/// stealing the selection, and a run that left the batch returns the+/// selection to the feed's head (the mutation check: index-tracking+/// jumps to the new newest run and fails the fold assertions).+#[test]+fn multiple_runs_keep_the_selection_on_the_same_run() {+ let runs = parse_factory_runs(&two_run_response());+ let mut view = FactoryView::new(runs, 40);+ // The page opens on the newest run.+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-def67890".to_string())+ );+ // The down arrow moves the selection down the feed, to the older run.+ let _ = view.handle_key("down", &kb());+ assert_eq!(view.selected, 1);+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-abc12345".to_string())+ );+ // An unchanged refresh keeps the selection on the same run id.+ view.apply_runs(parse_factory_runs(&two_run_response()));+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-abc12345".to_string())+ );+ // A run created after both folds in on top: the selected run moves+ // down the list (index 1 becomes index 2) and the selection stays+ // on the same run — the same index would be the new newest run.+ view.apply_runs(parse_factory_runs(&three_run_response()));+ assert_eq!(view.selected, 2);+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-abc12345".to_string()),+ "the selection stays on the same run, not the same index"+ );+ // The selected run leaves the batch (the wire cap's oldest-end trim+ // dropped it): the selection returns to the feed's head, the newest+ // run.+ view.apply_runs(parse_factory_runs(&later_pair_response()));+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-ghi13579".to_string()),+ "a run that left the batch returns the selection to the head"+ );+}++/// The degenerate budget (a sub-chrome viewport on a short terminal):+/// the render still never exceeds what the viewport asked for, and the+/// tail-clip keeps the hint (the chrome's last row) — a 1-row viewport+/// shows the hint, never six rows (the mutation check: the old+/// `.max(6)` floor overflowed the dock on short terminals).+#[test]+fn the_degenerate_budget_still_honors_the_viewport() {+ let mut one_row = FactoryView::new(parse_factory_runs(&runs_response(&scripted_snapshot())), 1);+ let rows = frame_text(&mut one_row);+ assert_eq!(rows.len(), 1, "a 1-row viewport renders exactly one row");+ assert!(+ rows[0].contains("close"),+ "the tail-clip keeps the hint: {:?}",+ rows[0]+ );+ let mut two_rows = FactoryView::new(parse_factory_runs(&two_run_response()), 2);+ let rows = frame_text(&mut two_rows);+ assert_eq!(rows.len(), 2, "a 2-row viewport renders exactly two rows");+ assert!(+ rows[1].contains("close"),+ "the hint is the last row: {:?}",+ rows[1]+ );+}++/// The render budget window (a tall view at a small viewport): the view+/// never renders more rows than the viewport asked for, the trailing key+/// hint always stays painted, and the selected run's panel header stays+/// visible even when the selection sits below the top window — a+/// stop/resume target never hides behind the budget. The window keeps+/// the TOP of the newest-first feed (the newest panels render first,+/// the oldest panels drop first) and slides to the selection when it+/// falls below (the mutation check: a window without the slide hides+/// the selected run's header).+#[test]+fn the_budget_window_keeps_the_hint_and_the_selected_panel() {+ let mut view = FactoryView::new(parse_factory_runs(&two_run_response()), 8);+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ // The budget contract: never more than the viewport asked for.+ assert!(+ rows.len() <= 8,+ "the view stays inside the budget: {joined}"+ );+ // The key hint stays painted (the trailing chrome never truncates).+ assert!(+ joined.contains("Enter actions"),+ "the key hint stays painted: {joined}"+ );+ // The default selection is the newest run: its header stays visible+ // with its marker, and the older panel drops first.+ assert!(+ joined.contains("▸ factory: second-run — running"),+ "the newest (selected) run's header stays visible: {joined}"+ );+ assert!(+ !joined.contains("factory: review-loop"),+ "the older panel drops instead of the chrome: {joined}"+ );++ // The selection moved down the feed (the older run): the window+ // follows the selection, keeps the hint, and drops the newest+ // panel instead.+ let mut selected_older = FactoryView::new(parse_factory_runs(&two_run_response()), 8);+ let _ = selected_older.handle_key("down", &kb());+ let rows = frame_text(&mut selected_older);+ let joined = rows.join("\n");+ assert!(+ rows.len() <= 8,+ "the view stays inside the budget: {joined}"+ );+ assert!(+ joined.contains("Enter actions"),+ "the key hint stays painted: {joined}"+ );+ assert!(+ joined.contains("▸ factory: review-loop — running"),+ "the selected run's header stays visible: {joined}"+ );+ assert!(+ !joined.contains("factory: second-run"),+ "the unselected newest panel drops instead of the chrome: {joined}"+ );+}++// ---------------------------------------------------------------------------+// The scale battery's scenario data: the complex machine (the seed+// pr-manager shape) and the synthetic many-run world.+// ---------------------------------------------------------------------------++/// One pr-manager-shaped run (the machine-library seed's shape, the wire+/// lane's camelCase): SEVEN states — the `triage` entry, the bounded+/// review loop (`review` ⇄ `fix` on the verdict's two guarded branches),+/// the `verify` pass, the `merge`, the resident `watchdog` (admitted+/// once triage settles, running until stop), and the `report` behind the+/// fan-in join `[merge, verify]` — mid-flight: triage settled (both its+/// edges fired), the review entry in flight, the watchdog resident+/// running.+fn pr_manager_run(run_id: &str, name: &str) -> serde_json::Value {+ json!({+ "runId": run_id,+ "specId": "pr-manager",+ "name": name,+ "state": "running",+ "pauseReason": null,+ "elapsedMs": 120_000,+ "machine": {+ "run": { "maxParallel": 4, "maxTransitions": 40, "failurePolicy": "continue", "budgetMs": 900_000 },+ "states": [+ { "id": "triage", "entry": true, "lifecycle": "task", "maxEntries": 1, "retries": 0, "subagent": "triager" },+ { "id": "review", "entry": false, "lifecycle": "task", "maxEntries": 4, "retries": 1, "subagent": "reviewer" },+ { "id": "fix", "entry": false, "lifecycle": "task", "maxEntries": 3, "retries": 0, "subagent": "fixer" },+ { "id": "verify", "entry": false, "lifecycle": "task", "maxEntries": 1, "retries": 0, "subagent": "verifier" },+ { "id": "merge", "entry": false, "lifecycle": "task", "maxEntries": 1, "retries": 0, "subagent": "merger" },+ { "id": "watchdog", "entry": false, "lifecycle": "resident", "maxEntries": 1, "retries": 0, "subagent": "watchdog" },+ { "id": "report", "entry": false, "lifecycle": "task", "maxEntries": 1, "retries": 0, "subagent": "reporter" }+ ],+ "transitions": [+ { "from": "triage", "to": "review", "on": "settled" },+ { "from": "triage", "to": "watchdog", "on": "settled" },+ { "from": "review", "to": "fix", "on": "settled",+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": false } },+ { "from": "review", "to": "merge", "on": "settled",+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": true } },+ { "from": "fix", "to": "review", "on": "settled" },+ { "from": "fix", "to": "verify", "on": "settled" },+ { "from": "verify", "to": "merge", "on": "settled" },+ { "from": ["merge", "verify"], "to": "report", "on": "settled" }+ ],+ "order": ["triage", "review", "fix", "verify", "merge", "watchdog", "report"]+ },+ "nodes": [+ { "id": "triage", "status": "done", "lifecycle": "task", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 1,+ "entries": [ { "index": 0, "status": "done", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "done", "attempt": 1, "child": "child-t1", "durationMs": 8, "error": null } ],+ "running": 0, "queued": 0 },+ { "id": "review", "status": "running", "lifecycle": "task", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 4,+ "entries": [ { "index": 0, "status": "running", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "running", "attempt": 1, "child": "child-r1", "durationMs": 0, "error": null } ],+ "running": 1, "queued": 0 },+ { "id": "fix", "status": "pending", "lifecycle": "task", "attempts": 0,+ "entriesUsed": 0, "maxEntries": 3, "entries": [], "instances": [],+ "running": 0, "queued": 0 },+ { "id": "verify", "status": "pending", "lifecycle": "task", "attempts": 0,+ "entriesUsed": 0, "maxEntries": 1, "entries": [], "instances": [],+ "running": 0, "queued": 0 },+ { "id": "merge", "status": "pending", "lifecycle": "task", "attempts": 0,+ "entriesUsed": 0, "maxEntries": 1, "entries": [], "instances": [],+ "running": 0, "queued": 0 },+ { "id": "watchdog", "status": "running", "lifecycle": "resident", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 1,+ "entries": [ { "index": 0, "status": "running", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "running", "attempt": 1, "child": "child-w1", "durationMs": 0, "error": null } ],+ "running": 1, "queued": 0 },+ { "id": "report", "status": "pending", "lifecycle": "task", "attempts": 0,+ "entriesUsed": 0, "maxEntries": 1, "entries": [], "instances": [],+ "running": 0, "queued": 0 }+ ],+ "activeNodes": ["review", "watchdog"],+ "lastFired": [+ { "from": "triage", "to": "review", "seq": 2 },+ { "from": "triage", "to": "watchdog", "seq": 3 }+ ],+ "events": [+ { "seq": 1, "kind": "milestone", "stage": "shown", "milestone": "started" },+ { "seq": 2, "kind": "transition_fired", "stage": "recorded", "from": "triage", "to": "review" },+ { "seq": 3, "kind": "transition_fired", "stage": "recorded", "from": "triage", "to": "watchdog" },+ { "seq": 4, "kind": "milestone", "stage": "shown", "milestone": "triaged" }+ ],+ "usage": { "spawns": 2, "settled": 1, "toolUses": 12, "maxParallel": 4,+ "running": 2, "transitionsFired": 2 },+ "budget": { "limitMs": 900_000, "consumedMs": 120_000 }+ })+}++/// The review node's many-instance variant (the occupied stage): one+/// entry holding four prepared instances — three admitted under the+/// run's four-slot cap (the resident watchdog holds the fourth), one+/// queued; with `queued_too`, two more queue behind the cap.+fn occupied_review_node(run: &mut serde_json::Value, queued_too: bool) {+ let mut instances = vec![+ json!({ "index": 0, "entry": 0, "status": "running", "attempt": 1, "child": "child-r1", "durationMs": 0, "error": null }),+ json!({ "index": 1, "entry": 0, "status": "running", "attempt": 1, "child": "child-r2", "durationMs": 0, "error": null }),+ json!({ "index": 2, "entry": 0, "status": "running", "attempt": 1, "child": "child-r3", "durationMs": 0, "error": null }),+ ];+ let mut queued = 0;+ if queued_too {+ instances.push(json!({ "index": 3, "entry": 0, "status": "pending", "attempt": 0, "child": null, "durationMs": null, "error": null }));+ instances.push(json!({ "index": 4, "entry": 0, "status": "pending", "attempt": 0, "child": null, "durationMs": null, "error": null }));+ queued = 2;+ }+ run["nodes"][1]["instances"] = json!(instances);+ run["nodes"][1]["running"] = json!(3);+ run["nodes"][1]["queued"] = json!(queued);+ run["usage"]["spawns"] = json!(4 + queued);+ run["usage"]["running"] = json!(4);+}++/// One world run at its scripted stage: the orchestrated page's varied+/// world — eight live (two carrying many instances at a stage), one+/// stopping, two paused, two done-with-residents (the resident still+/// running), one failed (torn down), one stopped (the residents+/// teardown's terminal state, no child in flight).+fn world_run(index: usize) -> serde_json::Value {+ let mut run = pr_manager_run(&format!("run-w{index:02}"), &format!("world-run-{index}"));+ match index % 15 {+ 2 => occupied_review_node(&mut run, false),+ 5 => occupied_review_node(&mut run, true),+ 8 => {+ // The stop was issued mid-review: the transitional state, the+ // children still in flight while they tear down.+ run["state"] = json!("stopping");+ }+ 9 | 10 => {+ run["state"] = json!("paused");+ }+ 11 | 12 => {+ // The machine completed with the resident still watching: a+ // `done` run whose children are in flight stays live.+ run["state"] = json!("done");+ run["nodes"][1] = json!({+ "id": "review", "status": "done", "lifecycle": "task", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 4,+ "entries": [ { "index": 0, "status": "done", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "done", "attempt": 1, "child": "child-r1", "durationMs": 30, "error": null } ],+ "running": 0, "queued": 0+ });+ for (node, status) in [(3, "done"), (4, "done"), (6, "done")] {+ run["nodes"][node]["status"] = json!(status);+ run["nodes"][node]["attempts"] = json!(1);+ run["nodes"][node]["entriesUsed"] = json!(1);+ run["nodes"][node]["entries"] =+ json!([ { "index": 0, "status": "done", "error": null } ]);+ run["nodes"][node]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "done", "attempt": 1, "child": "child-x1", "durationMs": 5, "error": null }+ ]);+ }+ run["activeNodes"] = json!(["watchdog"]);+ run["lastFired"] = json!([+ { "from": ["merge", "verify"], "to": "report", "seq": 9 },+ { "from": "verify", "to": "merge", "seq": 8 },+ { "from": "review", "to": "merge", "seq": 7,+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": true } },+ { "from": "triage", "to": "review", "seq": 2 },+ { "from": "triage", "to": "watchdog", "seq": 3 }+ ]);+ run["usage"] = json!({ "spawns": 5, "settled": 5, "toolUses": 41, "maxParallel": 4,+ "running": 1, "transitionsFired": 5 });+ }+ 13 => {+ // The failure policy failed the run: the review error, the+ // residents torn down, no child in flight.+ run["state"] = json!("failed");+ run["nodes"][1]["status"] = json!("error");+ run["nodes"][1]["error"] = json!("the reviewer rejected the diff: malformed patch");+ run["nodes"][5]["status"] = json!("cancelled");+ run["nodes"][5]["entries"] =+ json!([ { "index": 0, "status": "cancelled", "error": null } ]);+ run["nodes"][5]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "cancelled", "attempt": 1, "child": "child-w1", "durationMs": 12, "error": null }+ ]);+ run["nodes"][5]["running"] = json!(0);+ run["activeNodes"] = json!([]);+ run["usage"]["running"] = json!(0);+ run["usage"]["settled"] = json!(2);+ }+ 14 => {+ // The operator stopped it mid-review: the terminal teardown+ // state, no child in flight.+ run["state"] = json!("stopped");+ run["nodes"][1]["status"] = json!("cancelled");+ run["nodes"][1]["entries"] =+ json!([ { "index": 0, "status": "cancelled", "error": null } ]);+ run["nodes"][1]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "cancelled", "attempt": 1, "child": "child-r1", "durationMs": 9, "error": null }+ ]);+ run["nodes"][1]["running"] = json!(0);+ run["nodes"][5]["status"] = json!("cancelled");+ run["nodes"][5]["entries"] =+ json!([ { "index": 0, "status": "cancelled", "error": null } ]);+ run["nodes"][5]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "cancelled", "attempt": 1, "child": "child-w1", "durationMs": 9, "error": null }+ ]);+ run["nodes"][5]["running"] = json!(0);+ run["activeNodes"] = json!([]);+ run["usage"]["running"] = json!(0);+ run["usage"]["settled"] = json!(2);+ }+ _ => {}+ }+ run+}++/// The many-run world's first fold: fifteen runs in the reply's start+/// order (oldest first — the kernel's documented order), every stage+/// the page must read at once.+fn world_response() -> serde_json::Value {+ let runs: Vec<serde_json::Value> = (0..15).map(world_run).collect();+ json!({ "runs": runs })+}++/// The done-with-residents pair settles: their residents stopped, the+/// runs now fully terminal (no child in flight).+fn stop_residents(run: &mut serde_json::Value) {+ run["state"] = json!("stopped");+ run["nodes"][5]["status"] = json!("cancelled");+ run["nodes"][5]["entries"] = json!([ { "index": 0, "status": "cancelled", "error": null } ]);+ run["nodes"][5]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "cancelled", "attempt": 1, "child": "child-w1", "durationMs": 40, "error": null }+ ]);+ run["nodes"][5]["running"] = json!(0);+ run["usage"]["running"] = json!(0);+}++/// Fold two: the two OLDEST runs left the batch (the wire cap's+/// oldest-end trim), three brand-new runs folded in on top (w15-w17),+/// the done-with-residents pair settled to fully terminal, and one+/// paused run resumed — one refresh tick's worth of a busy world.+fn world_fold_two() -> serde_json::Value {+ let mut runs: Vec<serde_json::Value> = Vec::new();+ for index in 2..15 {+ let mut run = world_run(index);+ match index {+ 11 | 12 => stop_residents(&mut run),+ 9 => run["state"] = json!("running"),+ _ => {}+ }+ runs.push(run);+ }+ for index in 15..18 {+ runs.push(world_run(index));+ }+ json!({ "runs": runs })+}++/// Fold three: fold two's shape minus the selected run w07 — it left+/// the batch mid-orchestration.+fn world_fold_three() -> serde_json::Value {+ let mut reply = world_fold_two();+ reply["runs"]+ .as_array_mut()+ .expect("the world reply carries runs")+ .retain(|run| run["runId"] != json!("run-w07"));+ reply+}++/// Run w02's review entry one instance deeper (the settle script: 3+/// run -> 2 run -> 1 run), the instance counts kept consistent with the+/// kernel's per-stage report.+fn w02_settled(review_running: u64) -> serde_json::Value {+ let mut reply = world_response();+ settle_w02_run(+ &mut reply["runs"].as_array_mut().expect("runs")[2],+ review_running,+ );+ reply+}++/// One run's review entry `review_running` instances still in flight+/// (the earliest instances settled first, exactly how the kernel+/// reports a draining entry).+fn settle_w02_run(run: &mut serde_json::Value, review_running: u64) {+ let done = 3 - review_running;+ let mut instances = Vec::new();+ for index in 0..3 {+ instances.push(json!({+ "index": index, "entry": 0,+ "status": if (index as u64) < done { "done" } else { "running" },+ "attempt": 1, "child": format!("child-r{}", index + 1),+ "durationMs": if (index as u64) < done { 5 } else { 0 }, "error": null+ }));+ }+ run["nodes"][1]["instances"] = json!(instances);+ run["nodes"][1]["running"] = json!(review_running);+ run["usage"]["running"] = json!(review_running + 1);+ run["usage"]["settled"] = json!(1 + done);+}++/// Run w02's review entry fully settled with the verdict's+/// disapproval: the guarded loop edge fired, `fix` entered, the review+/// node drained — the folded snapshot one transition deeper.+fn w02_entry_fired() -> serde_json::Value {+ let mut reply = w02_settled(0);+ let run = &mut reply["runs"].as_array_mut().expect("runs")[2];+ run["nodes"][1]["status"] = json!("done");+ run["nodes"][1]["entries"] = json!([ { "index": 0, "status": "done", "error": null } ]);+ run["nodes"][2] = json!({+ "id": "fix", "status": "running", "lifecycle": "task", "attempts": 1,+ "entriesUsed": 1, "maxEntries": 3,+ "entries": [ { "index": 0, "status": "running", "error": null } ],+ "instances": [ { "index": 0, "entry": 0, "status": "running", "attempt": 1, "child": "child-f1", "durationMs": 0, "error": null } ],+ "running": 1, "queued": 0+ });+ run["activeNodes"] = json!(["fix", "watchdog"]);+ run["lastFired"] = json!([+ { "from": "review", "to": "fix", "seq": 5,+ "when": { "output": "verdict", "path": "approved", "op": "eq", "value": false } },+ { "from": "triage", "to": "review", "seq": 2 },+ { "from": "triage", "to": "watchdog", "seq": 3 }+ ]);+ run["usage"]["running"] = json!(2);+ run["usage"]["settled"] = json!(5);+ run["usage"]["transitionsFired"] = json!(3);+ reply+}++/// The world with every run's elapsed clock bumped one tick — the+/// clock-only fold: nothing is notice-worthy, no marker may fire.+fn world_clock_tick() -> serde_json::Value {+ let mut reply = world_response();+ for run in reply["runs"].as_array_mut().expect("runs") {+ run["elapsedMs"] = json!(run["elapsedMs"].as_u64().unwrap_or_default() + 2_000);+ }+ reply+}++/// The world with run w07's stop landed: the transitional state, its+/// panel now reads stopping.+fn world_w07_stopping() -> serde_json::Value {+ let mut reply = world_response();+ reply["runs"].as_array_mut().expect("runs")[7]["state"] = json!("stopping");+ reply+}++/// The world with run w09 resumed (it was paused).+fn world_w09_resumed() -> serde_json::Value {+ let mut reply = world_response();+ reply["runs"].as_array_mut().expect("runs")[9]["state"] = json!("running");+ reply+}++/// A burst of five brand-new runs folded in on top of the world (the+/// newest runs render first, the feed grows by five in one tick).+fn world_with_burst() -> serde_json::Value {+ let mut reply = world_response();+ for index in 15..20 {+ reply["runs"]+ .as_array_mut()+ .expect("runs")+ .push(world_run(index));+ }+ reply+}++/// One busy tick at once (the churn script): the five-run burst folds in+/// on top, w02's review entry settles one deeper, w09 resumes, and the+/// done-with-residents pair's residents stop — many notice-worthy+/// changes landing in a single fold, the page's rapid-change world.+fn world_churn_tick() -> serde_json::Value {+ let mut reply = world_with_burst();+ for run in reply["runs"].as_array_mut().expect("runs").iter_mut() {+ match run["runId"].as_str() {+ Some("run-w02") => settle_w02_run(run, 2),+ Some("run-w09") => run["state"] = json!("running"),+ Some("run-w11" | "run-w12") => stop_residents(run),+ _ => {}+ }+ }+ reply+}++/// One run's panel rows from the rendered frame: its header through the+/// row before the next run's header (the frame's own reading order).+fn panel_rows<'a>(rows: &'a [String], name: &str) -> &'a [String] {+ let start = rows+ .iter()+ .position(|row| row.contains(name))+ .unwrap_or_else(|| panic!("the panel for {name} renders"));+ let end = rows[start + 1..]+ .iter()+ .position(|row| row.contains("factory: "))+ .map_or(rows.len(), |offset| start + 1 + offset);+ &rows[start..end]+}++/// The complex machine's whole shape renders: the seven states in the+/// declared order (entry marker, resident, guarded branches with their+/// guards, the loop's back edge, the fan-in join rendered once), the+/// fired markers on the fired edges, and the live highlighting on the+/// in-flight and resident nodes.+#[test]+fn a_complex_machine_renders_its_whole_shape() {+ let mut view = FactoryView::new(+ parse_factory_runs(&runs_response(&pr_manager_run("run-pm1", "pr run"))),+ 60,+ );+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(+ joined.contains("factory: pr run — running"),+ "the run header: {joined}"+ );+ // The declared order's rows, the entry and resident markers.+ assert!(joined.contains("triage"), "{joined}");+ assert!(+ joined.contains("[entry]"),+ "the entry state's marker: {joined}"+ );+ assert!(joined.contains("watchdog"), "{joined}");+ assert!(+ panel_rows(&rows, "factory: pr run")+ .iter()+ .any(|row| row.contains("✓ triage")),+ "the settled entry state: {joined}"+ );+ // The two guarded branches carry their guards.+ assert!(+ joined.contains("when verdict.approved eq false"),+ "the loop's guard: {joined}"+ );+ assert!(+ joined.contains("when verdict.approved eq true"),+ "the merge branch's guard: {joined}"+ );+ // The loop's back edge renders with the return marker; the fan-in+ // join renders ONCE with its join label (not once per source).+ let panel = panel_rows(&rows, "factory: pr run");+ let back_edge = panel+ .iter()+ .find(|row| row.contains("↩"))+ .expect("the loop's back edge renders");+ assert!(+ back_edge.contains("review"),+ "the back edge returns to the loop head: {back_edge}"+ );+ let joins = panel+ .iter()+ .filter(|row| row.contains("join: merge + verify"))+ .count();+ assert_eq!(joins, 1, "the fan-in join renders once: {joined}");+ // The fired markers sit on the fired edges (both of triage's).+ let fired = panel.iter().filter(|row| row.contains("»")).count();+ assert_eq!(fired, 2, "both fired edges carry the marker: {joined}");+ // The live highlighting: the in-flight review and the resident+ // watchdog paint accent; the never-entered states paint dim.+ let spans = frame_spans(&mut view);+ let accent = theme().fg_style(ThemeColor::Accent);+ let dim = theme().fg_style(ThemeColor::Dim);+ let accent_span = |text: &str| {+ spans.iter().any(|row| {+ row.iter()+ .any(|span| span.content == text && span.style == accent)+ })+ };+ let dim_span = |text: &str| {+ spans.iter().any(|row| {+ row.iter()+ .any(|span| span.content == text && span.style == dim)+ })+ };+ assert!(accent_span("review"), "the in-flight state paints accent");+ assert!(+ accent_span("watchdog"),+ "the resident state paints accent while its child runs"+ );+ assert!(dim_span("fix"), "the never-entered state paints dim");+ assert!(dim_span("report"), "{joined}");+}++/// The dock's factory count reads ONE liveness rule across the whole+/// world: the live states count (running/stopping/paused), the+/// done-with-residents pair counts (children still in flight — their+/// stop control is live), and the fully terminal runs never count (the+/// mutation check: the state-only filter drops the two resident pairs).+#[test]+fn the_dock_count_reads_one_liveness_rule_across_many_runs() {+ let runs = parse_factory_runs(&world_response());+ assert_eq!(runs.len(), 15, "the whole world parses");+ let live = runs.iter().filter(|run| run.is_live()).count();+ assert_eq!(+ live, 13,+ "eight live + one stopping + two paused + two done-with-residents"+ );+ let find = |id: &str| {+ runs.iter()+ .find(|run| run.run_id == id)+ .unwrap_or_else(|| panic!("run {id} parses"))+ };+ // The done-with-residents pair: state says done, the children say+ // live — the panel and its stop control must stay.+ for id in ["run-w11", "run-w12"] {+ let run = find(id);+ assert_eq!(run.state.as_deref(), Some("done"));+ assert!(run.children_in_flight(), "{id}'s resident still runs");+ assert!(run.is_live(), "{id} stays live while its children run");+ assert!(+ !FactoryView::available_actions(run).is_empty(),+ "{id} keeps its stop control"+ );+ }+ // The fully terminal runs never count.+ for id in ["run-w13", "run-w14"] {+ assert!(!find(id).is_live(), "{id} is fully terminal");+ assert!(+ FactoryView::available_actions(find(id)).is_empty(),+ "{id} offers nothing"+ );+ }+ // The stopping and paused runs count.+ assert!(find("run-w08").is_live());+ assert!(find("run-w09").is_live());+ assert!(find("run-w10").is_live());+}++/// Selection stability across many runs: selecting run #7 among fifteen+/// and folding a busy world — new runs folding in ON TOP (newest-first),+/// runs finishing and leaving above, the oldest-end trim dropping runs+/// below — the selection stays on the SAME RUN, never the same index;+/// when the selected run itself leaves the batch the trim hands the+/// selection back to the feed's head (the mutation check:+/// index-tracking jumps to the wrong run on every fold here).+#[test]+fn selection_stays_on_the_same_run_across_a_many_run_churn() {+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);+ // The head is the newest run; seven downs walk to run #7 among+ // fifteen.+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w14".to_string()),+ "the page opens on the feed's head"+ );+ for _ in 0..7 {+ let _ = view.handle_key("down", &kb());+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w07".to_string())+ );+ // Fold two: three new runs folded in on top, the two oldest left+ // the batch, the done-with-residents pair settled. The selection+ // stays on run w07 — at a NEW index (the same index would name a+ // different run).+ view.apply_runs(parse_factory_runs(&world_fold_two()));+ assert_eq!(view.selected, 10, "the fold moved the run down the feed");+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w07".to_string()),+ "the selection stays on the same run, not the same index"+ );+ // Fold three: the selected run itself left the batch — the trim+ // hands the selection back to the feed's head, the newest run.+ view.apply_runs(parse_factory_runs(&world_fold_three()));+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w17".to_string()),+ "a selected run that left the batch hands back to the head"+ );+}++/// Render windowing at scale: fifteen panels on a small viewport never+/// exceed the budget, the trailing hint always paints, and the leading+/// window slides to the focused panel (the walk target) without+/// clipping the chrome — the degenerate budgets still honor the+/// viewport (the mutation check: a window without the slide hides the+/// focused run's header).+#[test]+fn fifteen_panels_window_to_the_focus_on_a_small_viewport() {+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 26);+ let rows = frame_text(&mut view);+ assert!(+ rows.len() <= 26,+ "fifteen panels never exceed the viewport: {:?}",+ rows.len()+ );+ assert!(+ rows.last().is_some_and(|row| row.contains("close")),+ "the hint paints as the chrome's last row: {:?}",+ rows.last()+ );+ // The leading window keeps the feed's head: the newest panel+ // renders first.+ assert!(+ rows.iter().any(|row| row.contains("factory: world-run-14")),+ "the newest panel renders first: {}",+ rows.join("\n")+ );+ // Seven downs: the window slides to the focused run — its header+ // paints, the head panel drops instead, and the hint survives.+ for _ in 0..7 {+ let _ = view.handle_key("down", &kb());+ }+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(rows.len() <= 26, "the windowed frame stays in budget");+ assert!(+ joined.contains("▸ factory: world-run-7 — running"),+ "the focused panel's header paints after the slide: {joined}"+ );+ assert!(+ !joined.contains("factory: world-run-14"),+ "the head panel dropped instead of the chrome: {joined}"+ );+ assert!(+ rows.last().is_some_and(|row| row.contains("close")),+ "the hint still paints after the slide"+ );+ // Degenerate budgets honor the viewport exactly.+ let mut one_row = FactoryView::new(parse_factory_runs(&world_response()), 1);+ let rows = frame_text(&mut one_row);+ assert_eq!(rows.len(), 1);+ assert!(rows[0].contains("close"), "{:?}", rows[0]);+ let mut three_rows = FactoryView::new(parse_factory_runs(&world_response()), 3);+ let rows = frame_text(&mut three_rows);+ assert_eq!(rows.len(), 3);+ assert!(rows[2].contains("close"), "{:?}", rows[2]);+}++/// The refresh tick across the fifteen-run world: the changed marker+/// fires only on notice-worthy changes — never on the elapsed clock,+/// never on identical structural replies, exactly on the runs that+/// changed — and the changed shape paints: the fired-edge marker moves+/// to the newly fired transition, the per-stage occupancy counts update+/// as instances settle (3 run -> 2 run -> 1 run), and the active-node+/// highlighting follows the settling states.+#[test]+fn the_refresh_tick_lights_only_notice_worthy_changes_across_many_runs() {+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);+ let changed_headers = |view: &mut FactoryView| {+ frame_text(view)+ .iter()+ .filter(|row| row.contains("● changed"))+ .count()+ };+ // An identical structural reply applies nothing.+ assert!(!view.apply_runs(parse_factory_runs(&world_response())));+ assert_eq!(changed_headers(&mut view), 0, "no run changed");+ // The clock tick across the whole world lights nothing.+ assert!(!view.apply_runs(parse_factory_runs(&world_clock_tick())));+ assert_eq!(+ changed_headers(&mut view),+ 0,+ "the elapsed clock is not notice-worthy, at any scale"+ );+ // The settle script on run w02: one instance settles — the marker+ // lights on THAT run alone, and its occupancy label drops to+ // 2 run.+ assert!(view.apply_runs(parse_factory_runs(&w02_settled(2))));+ let rows = frame_text(&mut view);+ assert_eq!(changed_headers(&mut view), 1, "exactly one run changed");+ let panel = panel_rows(&rows, "factory: world-run-2");+ assert!(+ panel.iter().any(|row| row.contains("● changed")),+ "the changed run is w02: {}",+ rows.join("\n")+ );+ assert!(+ panel+ .iter()+ .any(|row| row.contains("review (2 run · 0 queued)")),+ "the occupancy label drops to 2 run: {panel:?}"+ );+ // One instance deeper: 1 run, still exactly one marker.+ assert!(view.apply_runs(parse_factory_runs(&w02_settled(1))));+ let rows = frame_text(&mut view);+ assert_eq!(changed_headers(&mut view), 1);+ assert!(+ panel_rows(&rows, "factory: world-run-2")+ .iter()+ .any(|row| row.contains("review (1 run · 0 queued)")),+ "the occupancy label drops to 1 run"+ );+ // The entry settles and the guarded loop edge fires: the marker+ // moves to the newly fired transition, the review stage drains+ // (no occupancy fragment), and the active node moves to fix.+ assert!(view.apply_runs(parse_factory_runs(&w02_entry_fired())));+ let rows = frame_text(&mut view);+ assert_eq!(changed_headers(&mut view), 1, "still exactly one run");+ let panel = panel_rows(&rows, "factory: world-run-2");+ let fired_edge = panel+ .iter()+ .find(|row| row.contains("»") && row.contains("fix"))+ .expect("the newly fired edge carries the marker");+ assert!(+ fired_edge.contains("verdict.approved eq false"),+ "the fired marker sits on the loop's guarded edge: {fired_edge}"+ );+ assert!(+ !panel.iter().any(|row| row.contains("review (1 run")),+ "the drained stage carries no occupancy fragment: {panel:?}"+ );+ // The active-node highlighting follows the settling: the entered+ // fix stage paints accent, the settled review stage does not.+ let spans = frame_spans(&mut view);+ let accent = theme().fg_style(ThemeColor::Accent);+ let accent_ids: Vec<String> = spans+ .iter()+ .flat_map(|row| {+ row.iter()+ .filter(|span| span.style == accent)+ .map(|span| span.content.clone())+ })+ .collect();+ assert!(+ accent_ids.iter().any(|id| id == "fix"),+ "the entered fix stage paints accent: {accent_ids:?}"+ );+ let rows = frame_text(&mut view);+ let panel = panel_rows(&rows, "factory: world-run-2");+ let panel_start = rows+ .iter()+ .position(|row| row.contains("factory: world-run-2"))+ .expect("the panel renders");+ let panel_end = panel_start + panel.len();+ let review_accent = spans[panel_start..panel_end].iter().any(|row| {+ row.iter()+ .any(|span| span.content == "review" && span.style == accent)+ });+ assert!(+ !review_accent,+ "the settled review stage loses the accent: {accent_ids:?}"+ );+}++/// Orchestration at scale: the Enter path targets THE FOCUSED run among+/// fifteen — no cross-run leakage — and the stop's immediate refresh+/// updates its panel to stopping without losing the selection. The+/// offered set reads the run's state: a paused run offers the resume+/// complement first, a done-with-residents run keeps its stop (the+/// residents teardown), a terminal run offers nothing. The open action+/// rows stay honest across a fold: a state change under them clamps+/// the tracked action to what the run still offers, and a run that+/// leaves the batch closes them (the mutation check: confirming a+/// blindly tracked action would fire a stale resume here).+#[test]+fn orchestration_targets_the_focused_run_among_many() {+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);+ // Walk to run #7 and stop it through the action rows.+ for _ in 0..7 {+ let _ = view.handle_key("down", &kb());+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w07".to_string())+ );+ let _ = view.handle_key("enter", &kb());+ let rows = frame_text(&mut view);+ assert!(+ rows.join("\n").contains("actions: world-run-7"),+ "the action rows name the focused run"+ );+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-w07".to_string()+ },+ "the stop rides the focused run, none other"+ );+ // The stop landed: the immediate refresh folds the stopping state+ // — the panel updates, the selection never moves.+ view.apply_runs(parse_factory_runs(&world_w07_stopping()));+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w07".to_string()),+ "stopping a run never loses the selection"+ );+ let rows = frame_text(&mut view);+ assert!(+ panel_rows(&rows, "factory: world-run-7")+ .iter()+ .any(|row| row.contains("— stopping")),+ "the stopped run's panel reads stopping"+ );+ // A paused run offers the resume complement first: walk to w09+ // (two up from w07) and resume it.+ for _ in 0..2 {+ let _ = view.handle_key("up", &kb());+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w09".to_string())+ );+ let _ = view.handle_key("enter", &kb());+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(joined.contains("actions: world-run-9"), "{joined}");+ assert!(joined.contains("▸ Resume the run"), "{joined}");+ assert!(joined.contains("Stop the run"), "{joined}");+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Resume {+ run_id: "run-w09".to_string()+ }+ );+ // The action rows stay honest across a fold: reopen w09's rows+ // (paused, resume tracked), fold the world where w09 already+ // resumed — resume is no longer offered, the tracked action clamps+ // to stop, and Enter runs stop, never a stale resume.+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);+ for _ in 0..5 {+ let _ = view.handle_key("down", &kb());+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w09".to_string())+ );+ let _ = view.handle_key("enter", &kb());+ view.apply_runs(parse_factory_runs(&world_w09_resumed()));+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(+ joined.contains("actions: world-run-9"),+ "the rows stay open on the run: {joined}"+ );+ assert!(+ !joined.contains("Resume the run"),+ "the clamped rows offer only what the run still offers: {joined}"+ );+ assert!(joined.contains("▸ Stop the run"), "{joined}");+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-w09".to_string()+ },+ "the confirmation runs the offered action, never a stale resume"+ );+ // A done-with-residents run keeps its stop (the residents+ // teardown): w11 sits two up from w09.+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);+ for _ in 0..3 {+ let _ = view.handle_key("down", &kb());+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w11".to_string())+ );+ let _ = view.handle_key("enter", &kb());+ let rows = frame_text(&mut view);+ let joined = rows.join("\n");+ assert!(joined.contains("actions: world-run-11"), "{joined}");+ assert!(+ !joined.contains("Resume the run"),+ "a done run never offers resume: {joined}"+ );+ assert!(joined.contains("▸ Stop the run"), "{joined}");+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-w11".to_string()+ }+ );+ // A terminal run offers nothing.+ let _ = view.handle_key("up", &kb());+ let _ = view.handle_key("up", &kb());+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w13".to_string())+ );+ assert_eq!(view.handle_key("enter", &kb()), FactoryViewAction::None);+ assert!(+ !frame_text(&mut view).join("\n").contains("actions: "),+ "a terminal run opens no action rows"+ );+}++/// Rapid-change churn (the serialized fold discipline at scale): one+/// busy tick settles runs in quick succession, bursts new runs in,+/// resumes, and stops residents — the folded page stays coherent: the+/// markers light exactly on the runs whose shape changed (never the+/// new runs, never the untouched), the selection tracks the same run+/// through the burst, a selected run that vanishes hands back to the+/// head, and every keypress between folds resolves against the folded+/// batch (no dropped key, no stale-index action).+#[test]+fn rapid_churn_keeps_the_folded_page_coherent() {+ let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);+ for _ in 0..7 {+ let _ = view.handle_key("down", &kb());+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w07".to_string())+ );+ // The busy tick: a five-run burst folds in on top while four runs+ // change shape underneath.+ assert!(view.apply_runs(parse_factory_runs(&world_churn_tick())));+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w07".to_string()),+ "the selection tracks the same run through the burst"+ );+ assert_eq!(view.selected, 12, "five new runs folded in on top");+ // Exactly the four changed runs light the marker — the burst's new+ // runs paint none, the untouched runs none.+ let rows = frame_text(&mut view);+ let marked: Vec<&String> = rows+ .iter()+ .filter(|row| row.contains("● changed"))+ .collect();+ assert_eq!(marked.len(), 4, "exactly the changed runs: {marked:?}");+ for name in ["world-run-2", "world-run-9", "world-run-11", "world-run-12"] {+ assert!(+ marked.iter().any(|row| row.contains(name)),+ "{name}'s panel carries the changed marker: {marked:?}"+ );+ }+ for name in [+ "world-run-19",+ "world-run-15",+ "world-run-5",+ "world-run-14",+ ] {+ assert!(+ !marked.iter().any(|row| row.contains(name)),+ "{name} never carries a marker: {marked:?}"+ );+ }+ // The page stays coherent: the burst's panels render, the focused+ // panel paints, the hint paints.+ let joined = rows.join("\n");+ assert!(joined.contains("factory: world-run-19"), "{joined}");+ assert!(+ joined.contains("▸ factory: world-run-7 — running"),+ "{joined}"+ );+ assert!(joined.contains("Enter actions"), "{joined}");+ // The focused run vanishes mid-orchestration: the selection hands+ // back to the head, and the very next keypress resolves against+ // the folded batch — never a stale index.+ let mut vanished = world_churn_tick();+ vanished["runs"]+ .as_array_mut()+ .expect("runs")+ .retain(|run| run["runId"] != json!("run-w07"));+ view.apply_runs(parse_factory_runs(&vanished));+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w19".to_string()),+ "the vanished run hands the selection back to the head"+ );+ let _ = view.handle_key("enter", &kb());+ assert!(+ frame_text(&mut view)+ .join("\n")+ .contains("actions: world-run-19"),+ "the keypress after the fold opens the head's rows"+ );+ assert_eq!(+ view.handle_key("enter", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-w19".to_string()+ }+ );+ // Interleaved folds never drop a key: a walk with a fold between+ // every press lands exactly where an unfolded walk would.+ let mut view = FactoryView::new(parse_factory_runs(&world_churn_tick()), 400);+ for _ in 0..3 {+ let _ = view.handle_key("down", &kb());+ let _ = view.apply_runs(parse_factory_runs(&world_churn_tick()));+ }+ assert_eq!(+ view.selected_run().map(|run| run.run_id.clone()),+ Some("run-w16".to_string()),+ "every keypress resolved against the folded batch"+ );+}diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rsindex b04a79e9b4..fe5af5ee99 100644--- a/crates/pa-tui/src/interactive/run.rs+++ b/crates/pa-tui/src/interactive/run.rs@@ -263,6 +263,11 @@ async fn run_interactive_surface(let (auth_panel_tx, mut auth_panel_rx) =mpsc::unbounded_channel::<crate::auth_panel::AuthPanelRequest>();let (bash_tx, mut bash_rx) = mpsc::unbounded_channel::<crate::session_ui::BashActivityUpdate>();+ // Background factory refreshes (the factory page's watch+graph+ // cadence and the dock count's poll) report here; the loop folds them+ // into the session — the open page's panels and the dock's count.+ let (factory_tx, mut factory_rx) =+ mpsc::unbounded_channel::<crate::session_ui::FactoryUpdate>();// Background slash-command-catalog refreshes (`get_commands`) report// here; the loop folds the session's skill commands into the// autocomplete provider.@@ -386,6 +391,7 @@ async fn run_interactive_surface(let auth_panel_tx = auth_panel_tx.clone();let heartbeats_tx = heartbeats_tx.clone();let bash_tx = bash_tx.clone();+ let factory_tx = factory_tx.clone();let commands_tx = commands_tx.clone();async move {let (client, events) = match first {@@ -409,6 +415,7 @@ async fn run_interactive_surface(crate::session_ui::ActivityUpdates {heartbeats: heartbeats_tx,bash: bash_tx,+ factory: factory_tx,commands: commands_tx,},)@@ -660,6 +667,7 @@ async fn run_interactive_surface(let mut pending: VecDeque<UiInput> = VecDeque::new();let mut last_bash_refresh = Instant::now();+ let mut last_factory_refresh = Instant::now();// The enhanced-key modes settle once (kitty answer or fallback) and// report one adoption event; headless runs hold pipes and never probe.let mut enhanced_keys_pending = renderer.is_terminal();@@ -1314,6 +1322,7 @@ async fn run_interactive_surface(let autocomplete_pending = view.editor.has_pending_autocomplete();let auto_scroll_armed = session.selection_auto_scroll_armed();let bash_refresh_wanted = session.kernel_bash_supported();+ let factory_refresh_wanted = session.factory_activity_supported();// A settle waiting out a member is pending work like the// autocomplete park: the gate runs at the loop top, so its// re-check (and the settle bound's expiry) needs this arm's@@ -1626,6 +1635,11 @@ async fn run_interactive_surface(session.apply_bash_activity(update, &mut view);}}+ maybe_factory = factory_rx.recv() => {+ if let Some(update) = maybe_factory {+ session.apply_factory_update(update, &mut view);+ }+ }maybe_commands = commands_rx.recv() => {if let Some(update) = maybe_commands {session.apply_command_catalog(update, &mut view);@@ -1986,6 +2000,24 @@ async fn run_interactive_surface(last_bash_refresh = Instant::now();session.spawn_bash_activity_refresh();}+ () = async {+ // The factory lane's 2s poll: the bash poll's cadence+ // and gate, armed on daemons that advertise the+ // factory lane. The poll runs whether or not the page+ // is open (the dock's factory count stays live); an+ // open page adds its selected run's watch ahead of the+ // graph inside the same serialized cycle.+ if !factory_refresh_wanted {+ std::future::pending::<()>().await;+ }+ tokio::time::sleep_until(+ tokio::time::Instant::from_std(last_factory_refresh + Duration::from_secs(2)),+ )+ .await;+ } => {+ last_factory_refresh = Instant::now();+ session.spawn_factory_refresh();+ }_frame = async {match render_deadline {Some(deadline) => {diff --git a/crates/pa-tui/src/interactive/tests.rs b/crates/pa-tui/src/interactive/tests.rsindex 56fb821aae..a8b75fcc82 100644--- a/crates/pa-tui/src/interactive/tests.rs+++ b/crates/pa-tui/src/interactive/tests.rs@@ -325,7 +325,9 @@ fn the_headless_settle_names_every_stuck_member() {/// The pre-attach placeholder (painted for a NEW chat before the attach/// lands) carries the zero dock the fresh session mounts: the landed/// frame keeps the placeholder's geometry, so the splash never reflows-/// two rows when the session attaches.+/// two rows when the session attaches. The factory group stays off the+/// placeholder (the opt-in gate: the group mounts only after the+/// daemon's hello advertises the `factory_activity` lane).#[test]fn the_startup_placeholder_carries_the_dock_a_fresh_session_mounts() {let mut view = AgentView::new(crate::theme::Theme::builtin(diff --git a/crates/pa-tui/src/lib.rs b/crates/pa-tui/src/lib.rsindex bb4d84dc36..43ad4c51b9 100644--- a/crates/pa-tui/src/lib.rs+++ b/crates/pa-tui/src/lib.rs@@ -66,6 +66,7 @@ pub mod exit_guard;pub(crate) mod exit_restore;pub mod export_share;mod external_editor;+pub mod factory_view;pub mod fuzzy;pub mod goal_surface;pub mod heartbeats_picker;diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rsindex f2d6230226..5da5cfc4ba 100644--- a/crates/pa-tui/src/session_ui.rs+++ b/crates/pa-tui/src/session_ui.rs@@ -7,6 +7,7 @@ mod apply;mod auth;mod bash;mod commands;+mod factory;mod heartbeats;mod keys;mod lifecycle;@@ -24,6 +25,7 @@ pub(crate) use apply::CompactionAbortNote;use auth::{McpAuthIntent, PendingModelSignIn, SetModelOutcome};pub(crate) use bash::BashActivityUpdate;use bash::{ResyncBash, SideBashRun};+pub(crate) use factory::FactoryUpdate;use heartbeats::paused_heartbeat_count;pub(crate) use heartbeats::HeartbeatsUpdate;use keys::SelectionAutoScroll;@@ -412,6 +414,32 @@ pub(crate) struct SessionUi {/// response from an older request must not repaint a newer snapshot.bash_list_epoch: u64,bash_updates: mpsc::UnboundedSender<BashActivityUpdate>,+ /// The last `factory_activity` graph reply (the dock count's cache and+ /// the page open's mount, the `bash_activities` pattern): the+ /// always-on 2s poll keeps it current whether or not the page is+ /// open.+ factory_graph: serde_json::Value,+ /// The durable session id the open `/factory` view was mounted on: the+ /// rebind fold keeps the view across a same-session reattach (`Unknown+ /// active session` recovery) and closes it only when a different+ /// session actually takes the view's place.+ factory_view_session: Option<String>,+ /// Whether one factory refresh is still in flight (the heartbeat+ /// refresh's serialization: the tick is only a cadence floor, so it+ /// queues behind the in-flight cycle instead of minting a newer epoch+ /// the in-flight reply could never match).+ factory_refresh_in_flight: bool,+ /// A tick that fired while a refresh was in flight: the fold launches+ /// this trailing refresh once the in-flight cycle delivers.+ factory_refresh_queued: bool,+ /// Monotonic id of the latest issued factory refresh; an older+ /// response never repaints a newer snapshot.+ factory_list_epoch: u64,+ /// Where background factory refreshes deliver the run graph (the run+ /// loop folds them into the open view).+ factory_updates: mpsc::UnboundedSender<FactoryUpdate>,+ /// The open view's selected run id: the refresh's watch target.+ factory_selected_run: Option<String>,/// The subagent summary line holds keyboard focus.subagents_focused: bool,activity_group: crate::chrome::ActivityGroup,diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rsindex f84b497d5e..31b01e80d6 100644--- a/crates/pa-tui/src/session_ui/commands.rs+++ b/crates/pa-tui/src/session_ui/commands.rs@@ -413,6 +413,116 @@ impl SessionUi {view,);}+ // `/factory [on|off|status]`: the factory's opt-in gate (the+ // operator's directive: the factory is disabled until the+ // user turns it on). The toggle persists `factory.enabled` —+ // the shared settings key the daemon's `factory_activity`+ // advertisement and the kernel's factory gate read — so the+ // factory surfaces on the next client start (the running+ // connection keeps the advertisement its hello was built+ // with).+ "factory" => {+ let arg = resolved.args.trim().to_lowercase();+ match arg.as_str() {+ "on" => {+ let Some(settings) = &self.client_settings else {+ self.note("/factory is not available in this client yet", view);+ return Ok(());+ };+ if let Err(error) = settings.set_factory_enabled(true) {+ self.error_row(&format!("{error:#}"), view);+ return Ok(());+ }+ self.note(+ "The factory is enabled. Restart the client to surface the factory group (the factory page and the agent-side factory API follow the same gate).",+ view,+ );+ }+ "off" => {+ // The lifecycle guard (the review round's finding):+ // the kernel's control loop is not gated by the+ // setting, so `off` while runs are live would keep+ // admitting and collecting children while every+ // factory surface — the namespace, the activity+ // lane, and the page after the next client start —+ // refuses: a running factory loses its stop and+ // visibility path until the gate is enabled again.+ // The write refuses while the session's kernel+ // reports live runs, naming the count the dock+ // shows; the runs stop first (the page's stop+ // action or `rlm.factory.stop`). An unreadable+ // count fails closed on the lane-advertised client+ // (the only state where the guard matters): the+ // count's own failure classes — a timed-out or+ // malformed lane reply — cannot prove zero live+ // runs, and an unknown liveness must not open the+ // gate; the client retries once the lane answers.+ // The kernel-not-running refusal never reaches the+ // unreadable arm: the lane never builds a kernel+ // and the kernel owns its run registry in memory,+ // so that class reads as a definitive zero+ // (`live_factory_runs`), not an unknown liveness —+ // the off proceeds for a session with no kernel.+ // A client whose hello never advertised the lane+ // keeps the fail-open read: an older daemon has no+ // executor to protect, and a client started before+ // `/factory on` already sees the frozen hello the+ // settled surfaces rule describes.+ let lane_advertised = self.factory_activity_supported();+ match self.live_factory_runs().await {+ Some(live) if live > 0 => {+ let runs = if live == 1 { "run is" } else { "runs are" };+ let them = if live == 1 { "it" } else { "them" };+ self.error_row(+ &format!(+ "Cannot disable the factory while {live} {runs} still live — stop {them} first (the factory page's stop action or rlm.factory.stop), then /factory off."+ ),+ view,+ );+ return Ok(());+ }+ None if lane_advertised => {+ self.error_row(+ "Cannot disable the factory: the live-run count could not be read from the factory lane — try /factory off again once it answers.",+ view,+ );+ return Ok(());+ }+ Some(_) | None => {}+ }+ let Some(settings) = &self.client_settings else {+ self.note("/factory is not available in this client yet", view);+ return Ok(());+ };+ if let Err(error) = settings.set_factory_enabled(false) {+ self.error_row(&format!("{error:#}"), view);+ return Ok(());+ }+ self.note(+ "The factory is disabled. The factory group and page disappear on the next client start.",+ view,+ );+ }+ "" | "status" => {+ let Some(settings) = &self.client_settings else {+ self.note("/factory is not available in this client yet", view);+ return Ok(());+ };+ if settings.factory_enabled() {+ self.note(+ "The factory is enabled. Run /factory off to disable it.",+ view,+ );+ } else {+ self.note(+ "The factory is disabled (off by default). Run /factory on to enable it (takes effect on the next client start).",+ view,+ );+ }+ }+ _ => self.error_row("Usage: /factory [on|off|status]", view),+ }+ }// `/telemetry [status|on|off]`: the report (on/off and why, the// endpoint, the installation id), or the persisted switch the// running telemetry clients re-read at their next send.diff --git a/crates/pa-tui/src/session_ui/factory.rs b/crates/pa-tui/src/session_ui/factory.rsnew file mode 100644index 0000000000..172e41b546--- /dev/null+++ b/crates/pa-tui/src/session_ui/factory.rs@@ -0,0 +1,437 @@+//! The factory page's session surface: the page open (the activity+//! dock's factory group's destination), the view's key loop, the+//! refresh cadence, and the daemon `factory_activity` lane the page's+//! actions ride.++use std::time::Duration;++use anyhow::Result;+use serde_json::{Map, Value};++use pa_types::daemon::DaemonCommand;++use super::AgentView;++use crate::factory_view::{+ factory_reply_lists_runs, parse_factory_runs, FactoryView, FactoryViewAction,+ FACTORY_WATCH_TICK_MS,+};+use crate::session_ui::{picker_viewport_rows, UI_REQUEST_TIMEOUT_MS};++/// One background factory refresh's delivery: the session the request+/// asked about (a late reply from a previous session never repaints the+/// newly attached one), the epoch it was issued under (an older response+/// never overwrites a newer snapshot), and the graph list (or the error+/// that replaced it).+pub(crate) enum FactoryUpdate {+ Snapshot {+ session: String,+ epoch: u64,+ data: Value,+ },+ Error {+ session: String,+ epoch: u64,+ message: String,+ },+}++impl super::SessionUi {+ /// Whether the daemon advertises the factory lane (older daemons never+ /// see the command): the open and every refresh tick key on the same+ /// gate, so an unsupported daemon spends no wakeups.+ pub(crate) fn factory_activity_supported(&self) -> bool {+ self.client+ .hello()+ .get("serverCapabilities")+ .and_then(Value::as_array)+ .is_some_and(|caps| {+ caps.iter()+ .any(|cap| cap.as_str() == Some("factory_activity"))+ })+ }++ /// Open the factory page: the activity dock's factory group's+ /// destination (the subagents/heartbeats/shells pages' navigation+ /// family — the dock's Enter and the click both dispatch here). The+ /// keypress never waits on the daemon (the heartbeats/bash page+ /// pattern): the poll cycle's cached graph mounts at once and the+ /// refresh cadence keeps it current; a daemon without the lane+ /// reports exactly that instead of mounting nothing silently.+ pub(crate) fn open_factory_page(&mut self, view: &mut AgentView) {+ if !self.factory_activity_supported() {+ self.note(+ "The factory page needs a daemon that advertises the factory lane",+ view,+ );+ return;+ }+ // The mounted view belongs to this durable session: a later+ // rebind fold keeps it only across the SAME session's reattach.+ self.factory_view_session = Some(self.session_id.clone());+ // The mount holds the fold's malformed-reply contract: a cached+ // malformed lane mounts with its error line, never as a silent+ // fake empty state waiting for the first fold.+ view.factory_view = Some(FactoryView::from_reply(+ &self.factory_graph,+ picker_viewport_rows(view.terminal_rows()),+ ));+ self.sync_factory_selection(view);+ self.dirty = true;+ self.spawn_factory_refresh();+ }++ /// One key press while the view is open: the view resolves the key;+ /// stop/resume ride the daemon lane (bounded, with the outcome+ /// reported), and Esc closes.+ pub(crate) async fn handle_factory_view_key(+ &mut self,+ key: crossterm::event::KeyEvent,+ view: &mut AgentView,+ ) -> Result<()> {+ let Some(id) = super::key_event_to_id(&key) else {+ return Ok(());+ };+ if id == "ctrl+c" {+ self.exit_guard.note_ctrl_c_handled();+ }+ let action = view+ .factory_view+ .as_mut()+ .map(|factory_view| factory_view.handle_key(&id, view.editor.keybindings()));+ self.sync_factory_selection(view);+ match action {+ Some(FactoryViewAction::None) | None => {}+ Some(FactoryViewAction::Close) => {+ self.factory_selected_run = None;+ self.factory_view_session = None;+ view.factory_view = None;+ self.dirty = true;+ }+ Some(FactoryViewAction::Stop { run_id }) => {+ self.factory_control(view, "stop", run_id).await?;+ }+ Some(FactoryViewAction::Resume { run_id }) => {+ self.factory_control(view, "resume", run_id).await?;+ }+ }+ Ok(())+ }++ /// One orchestration action (stop/resume): bounded request, the+ /// outcome reported on the view's error line, then an immediate+ /// refresh (the state change repaints without waiting a full cycle).+ async fn factory_control(+ &mut self,+ view: &mut AgentView,+ action: &str,+ run_id: String,+ ) -> Result<()> {+ match self+ .bounded_request(+ Duration::from_millis(UI_REQUEST_TIMEOUT_MS),+ DaemonCommand::FactoryActivity {+ id: None,+ active_session_id: self.active_session_id.clone(),+ action: action.to_string(),+ run_id: Some(run_id.clone()),+ spec_id: None,+ timeout_ms: None,+ rest: Map::default(),+ },+ )+ .await+ {+ Ok(data) => {+ // The reply's state is daemon-provided text painted by+ // the toast, so it scrubs (`scrub_controls`, the factory+ // view's parse-seam rule): a control byte can never ride+ // the toast to the terminal.+ let state = data+ .get("state")+ .and_then(Value::as_str)+ .map_or_else(|| action.to_string(), crate::menu_panel::scrub_controls);+ self.toast(&format!("Factory run {run_id} is now {state}"), view);+ }+ Err(error) => {+ if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.set_error(Some(format!("{error:#}")));+ } else {+ self.error_row(&format!("{error:#}"), view);+ }+ }+ }+ self.spawn_factory_refresh();+ Ok(())+ }++ /// The session's live factory-run count, the `/factory off` lifecycle+ /// guard's read: the same lane request and the same liveness rule the+ /// dock's count reads (`is_live` — a live state, or children still in+ /// flight), so the refusal names exactly what the dock shows. The+ /// request rides regardless of the hello's advertisement: a client+ /// started before `/factory on` keeps its unadvertised hello, but the+ /// kernel gate reads the settings live, so runs started after the+ /// toggle are live in that same client — the guard must see them.+ /// `Some(0)` also answers the kernel-not-running refusal: the lane+ /// never builds a kernel, and the kernel owns its run registry in+ /// memory, so a session without a kernel cannot host live runs — a+ /// definitive zero, never an unreadable count (the lane answers the+ /// same refusal until some other action boots the kernel, so leaving+ /// it unreadable would pin the lane-advertised client's off behind a+ /// retry that never resolves). `None` when the count cannot be read:+ /// the request failed (an older daemon answers the unknown command+ /// with a failure), or the reply is not the runs list.+ pub(crate) async fn live_factory_runs(&mut self) -> Option<usize> {+ let reply = match self+ .bounded_request(+ Duration::from_millis(UI_REQUEST_TIMEOUT_MS),+ DaemonCommand::FactoryActivity {+ id: None,+ active_session_id: self.active_session_id.clone(),+ action: "graph".to_string(),+ run_id: None,+ spec_id: None,+ timeout_ms: None,+ rest: Map::default(),+ },+ )+ .await+ {+ Ok(reply) => reply,+ // The no-kernel class: the count is exactly zero (nothing+ // can host live runs), so the guard proceeds.+ Err(error) if crate::daemon_client::is_kernel_not_running(&error) => {+ return Some(0);+ }+ // Every other failure class stays unreadable: a timed-out or+ // malformed lane reply cannot prove zero live runs, and the+ // lane-advertised client fails closed on it.+ Err(_) => return None,+ };+ if !factory_reply_lists_runs(&reply) {+ return None;+ }+ Some(+ parse_factory_runs(&reply)+ .iter()+ .filter(|run| run.is_live())+ .count(),+ )+ }++ /// The refresh cadence (the run's collect cycle): a bounded watch on+ /// the selected run — the kernel returns as soon as it changed —+ /// then the full graph list. The cycle runs on the bash poll's+ /// always-on 2-second cadence (the dock's factory count stays live+ /// while the page is closed); an open page adds its selected run's+ /// watch ahead of the graph. At most one refresh runs in flight with+ /// one queued trailing refresh (the heartbeat refresh's+ /// serialization): a tick that fires while the watch/graph pair is+ /// still in flight queues behind it instead of minting a newer epoch+ /// the in-flight reply could never match (the watch alone can span a+ /// whole tick, so overlapping cycles would leave the view+ /// permanently stale). Every request stamps the epoch it was issued+ /// under, and only the latest issued request's response lands.+ pub(crate) fn spawn_factory_refresh(&mut self) {+ if !self.factory_activity_supported() {+ return;+ }+ if self.factory_refresh_in_flight {+ self.factory_refresh_queued = true;+ return;+ }+ self.factory_refresh_in_flight = true;+ self.factory_list_epoch += 1;+ let epoch = self.factory_list_epoch;+ let client = self.client.clone();+ let active_session_id = self.active_session_id.clone();+ let selected_run = self.factory_selected_run.clone();+ let tx = self.factory_updates.clone();+ tokio::spawn(async move {+ // The watch first: the selected run's change wakes the refresh+ // at the run's own pace instead of a fixed poll interval; a+ // failed or unsupported watch degrades to the plain cadence.+ // The whole cycle sits inside the shared request bound so the+ // refresh slot always frees (a hung request must never pin+ // the cadence), exactly like the heartbeat refresh.+ let cycle = async {+ if let Some(run_id) = selected_run {+ let _ = client+ .request_ok(DaemonCommand::FactoryActivity {+ id: None,+ active_session_id: active_session_id.clone(),+ action: "watch".to_string(),+ run_id: Some(run_id),+ spec_id: None,+ timeout_ms: Some(FACTORY_WATCH_TICK_MS),+ rest: Map::default(),+ })+ .await;+ }+ client+ .request_ok(DaemonCommand::FactoryActivity {+ id: None,+ active_session_id: active_session_id.clone(),+ action: "graph".to_string(),+ run_id: None,+ spec_id: None,+ timeout_ms: None,+ rest: Map::default(),+ })+ .await+ };+ let fetched =+ tokio::time::timeout(Duration::from_millis(UI_REQUEST_TIMEOUT_MS), cycle).await;+ match fetched {+ Ok(Ok(data)) => {+ let _ = tx.send(FactoryUpdate::Snapshot {+ session: active_session_id,+ epoch,+ data,+ });+ }+ Ok(Err(error)) => {+ let _ = tx.send(FactoryUpdate::Error {+ session: active_session_id,+ epoch,+ message: format!("{error:#}"),+ });+ }+ Err(_) => {+ let _ = tx.send(FactoryUpdate::Error {+ session: active_session_id,+ epoch,+ message: "timed out waiting for the Prime Agent daemon response"+ .to_string(),+ });+ }+ }+ });+ }++ /// The fold's cache decision (the Cursor review finding: a malformed+ /// batch used to clobber the dock's cached reply anyway): a+ /// well-formed batch replaces the cache and parses; a malformed one+ /// keeps the last good reply, so the dock's live-run count and a+ /// later remount never paint a fake empty state (the malformed+ /// contract the view's mount already carries).+ fn fold_factory_reply(+ cache: &mut Value,+ incoming: Value,+ ) -> Option<Vec<crate::factory_view::FactoryRunSnapshot>> {+ if !crate::factory_view::factory_reply_lists_runs(&incoming) {+ return None;+ }+ let runs = parse_factory_runs(&incoming);+ *cache = incoming;+ Some(runs)+ }++ /// Fold one refresh delivery into the session: the dock's count+ /// cache always absorbs the snapshot, the open view applies it, and+ /// a stale epoch (a newer request already landed) or a foreign+ /// session drops. The refresh slot frees whether the response+ /// landed, failed, or timed out, and a tick's queued refresh runs+ /// next (the heartbeat fold's shape). The changed markers land with+ /// the snapshot (the repaint hysteresis — only a notice-worthy+ /// run-shape change repaints the diagram). A reply without the+ /// runs list is a malformed lane, not zero runs: the open view+ /// reports it on its error line instead of painting a fake empty+ /// state (the emptiness the view shows is real).+ pub(crate) fn apply_factory_update(&mut self, update: FactoryUpdate, view: &mut AgentView) {+ // The slot frees on every delivery path; a queued tick fires next.+ self.factory_refresh_in_flight = false;+ let queued = std::mem::take(&mut self.factory_refresh_queued);+ let (session, epoch, payload) = match update {+ FactoryUpdate::Snapshot {+ session,+ epoch,+ data,+ } => (session, epoch, Ok(data)),+ FactoryUpdate::Error {+ session,+ epoch,+ message,+ } => (session, epoch, Err(message)),+ };+ if session != self.active_session_id || epoch != self.factory_list_epoch {+ if queued {+ self.spawn_factory_refresh();+ }+ return;+ }+ match payload {+ Ok(data) => match Self::fold_factory_reply(&mut self.factory_graph, data) {+ Some(runs) => {+ if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.set_error(None);+ factory_view.apply_runs(runs);+ }+ }+ None => {+ if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.set_error(Some(+ crate::factory_view::MALFORMED_REPLY_ERROR.to_string(),+ ));+ }+ }+ },+ Err(message) => {+ if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.set_error(Some(message));+ }+ }+ }+ self.sync_factory_selection(view);+ self.sync_activity_dock(view);+ self.dirty = true;+ if queued {+ self.spawn_factory_refresh();+ }+ }++ /// Record the view's selected run id (the watch target for the next+ /// refresh tick): the view owns the selection, the session UI owns+ /// the spawned refresh.+ pub(crate) fn sync_factory_selection(&mut self, view: &AgentView) {+ self.factory_selected_run = view+ .factory_view+ .as_ref()+ .and_then(|factory_view| factory_view.selected_run())+ .map(|run| run.run_id.clone())+ .filter(|run_id| !run_id.is_empty());+ }+}++#[cfg(test)]+mod fold_tests {+ use super::super::SessionUi;+ use serde_json::json;++ /// The malformed fold keeps the dock's cached reply (the Cursor+ /// review finding): a bad batch never replaces the last good reply,+ /// so the dock's live-run count and a later remount keep reading it+ /// instead of painting a fake empty state.+ #[test]+ fn a_malformed_batch_never_replaces_the_cached_reply() {+ let mut cache = json!({"runs": [{"runId": "r1", "machine": {}}]});+ let taken = SessionUi::fold_factory_reply(&mut cache, json!({"boom": true}));+ assert!(+ taken.is_none(),+ "a reply without the runs list is not taken"+ );+ assert_eq!(+ cache["runs"][0]["runId"], "r1",+ "the last good reply survives the malformed fold"+ );+ // ...and a well-formed batch replaces the cache and parses.+ let taken = SessionUi::fold_factory_reply(+ &mut cache,+ json!({"runs": [{"runId": "r2", "machine": {}}]}),+ );+ let runs = taken.expect("the well-formed batch is taken");+ assert_eq!(runs.len(), 1);+ assert_eq!(cache["runs"][0]["runId"], "r2");+ }+}diff --git a/crates/pa-tui/src/session_ui/keys.rs b/crates/pa-tui/src/session_ui/keys.rsindex d1a45d2948..e4b82797f2 100644--- a/crates/pa-tui/src/session_ui/keys.rs+++ b/crates/pa-tui/src/session_ui/keys.rs@@ -127,6 +127,7 @@ impl SessionUi {|| view.fork_selector.is_some()|| view.share_loader.is_some()|| view.mcp_view.is_some()+ || view.factory_view.is_some()|| view.onboarding.is_some();// TS records the press state before the dispatch: a drag report// marks the press, a plain press remembers the link under it.@@ -423,6 +424,10 @@ impl SessionUi {if view.mcp_view.is_some() {return self.handle_mcp_view_key(key, view);}+ // The factory page owns the frame the same way.+ if view.factory_view.is_some() {+ return self.handle_factory_view_key(key, view).await;+ }// The `/heartbeats` view owns the frame the same way.if view.heartbeats_picker.is_some() {return self.handle_heartbeats_picker_key(key, view).await;diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rsindex e34a87fe7e..59265f8694 100644--- a/crates/pa-tui/src/session_ui/lifecycle.rs+++ b/crates/pa-tui/src/session_ui/lifecycle.rs@@ -148,6 +148,13 @@ impl SessionUi {bash_activities: serde_json::json!({"activities": []}),bash_list_epoch: 0,bash_updates: activity_updates.bash,+ factory_graph: serde_json::json!({"runs": []}),+ factory_view_session: None,+ factory_refresh_in_flight: false,+ factory_refresh_queued: false,+ factory_list_epoch: 0,+ factory_updates: activity_updates.factory,+ factory_selected_run: None,subagents_focused: false,activity_group: crate::chrome::ActivityGroup::Subagents,subagent_counts: crate::subagents::SubagentCounts::default(),@@ -511,6 +518,11 @@ impl SessionUi {match dock_fold {DockFold::FirstFrame | DockFold::Fresh => {self.bash_activities = serde_json::json!({"activities": []});+ // The factory lane's cache dies with the previous+ // session too: the dock count and the page mount must+ // never show another session's runs (the 2s poll+ // refills; the spawn below asks for the first frame).+ self.factory_graph = serde_json::json!({"runs": []});}// The held dock keeps its registry for the same reason it// keeps the heartbeat catalog above.@@ -521,6 +533,10 @@ impl SessionUi {DockFold::FirstFrame => self.fetch_bash_activities().await,DockFold::Fresh | DockFold::Held => self.spawn_bash_activity_refresh(),}+ // The refilled factory cache is a background refresh away on+ // every fold (the poll's serialization makes an immediate+ // request safe — the in-flight slot frees on its own cycle).+ self.spawn_factory_refresh();self.pending_model = reconstructed.model_id;self.pending_model_provider = reconstructed.model_provider;self.pending_thinking_suffix = reconstructed.thinking_suffix;@@ -630,6 +646,33 @@ impl SessionUi {// stats and clears the readout left over from the previous session.if matches!(kind, RebuildKind::Rebind) {view.bash_view = None;+ // The factory view dies the same death — it snapshots the+ // previous session's kernel runs, and its refresh lane must+ // not keep polling the new session's kernel for a view+ // nobody mounted — but ONLY when a different session actually+ // took the view's place. A same-session rebind (the `Unknown+ // active session` reattach in `prompt.rs` replays over the+ // same durable session) keeps the view mounted: the user+ // neither switched sessions nor closed the view, and its+ // refresh lane re-targets the reattached session's kernel on+ // the next tick.+ // The page dies only when it was mounted under a DIFFERENT+ // session: a same-session rebind (the `Unknown active session`+ // reattach) keeps the page and its count — the kernel and its+ // runs did not change. A page that was never mounted owns no+ // state here; the attach fold owns the cache's cross-session+ // reset (every rebind path attaches first, so a switch's+ // stale cache is cleared before the rebuild lands).+ if self+ .factory_view_session+ .as_deref()+ .is_some_and(|session| session != self.session_id)+ {+ view.factory_view = None;+ self.factory_selected_run = None;+ self.factory_view_session = None;+ self.factory_graph = serde_json::json!({"runs": []});+ }// The goal panel dies with the old session too: it is a// snapshot of the previous session's goal state, and until// the new session's own `goal_update` lands it would keepdiff --git a/crates/pa-tui/src/session_ui/panels.rs b/crates/pa-tui/src/session_ui/panels.rsindex c9de093552..06e8b56398 100644--- a/crates/pa-tui/src/session_ui/panels.rs+++ b/crates/pa-tui/src/session_ui/panels.rs@@ -4,13 +4,15 @@use super::{key_event_to_id, mpsc, paused_heartbeat_count, picker_viewport_rows, tray_goal_label,- AgentView, BashActivityUpdate, CommandCatalogUpdate, DaemonCommand, DockFocusSource, GoalPanel,- HeartbeatsUpdate, InfoContent, InfoPanelAction, KeyEvent, Map, Result, SessionUi, Value,+ AgentView, BashActivityUpdate, CommandCatalogUpdate, DaemonCommand, DockFocusSource,+ FactoryUpdate, GoalPanel, HeartbeatsUpdate, InfoContent, InfoPanelAction, KeyEvent, Map,+ Result, SessionUi, Value,};pub(crate) struct ActivityUpdates {pub heartbeats: mpsc::UnboundedSender<HeartbeatsUpdate>,pub bash: mpsc::UnboundedSender<BashActivityUpdate>,+ pub factory: mpsc::UnboundedSender<FactoryUpdate>,pub commands: mpsc::UnboundedSender<CommandCatalogUpdate>,}@@ -129,6 +131,17 @@ impl SessionUi {.iter().filter(|activity| activity.running()).count();+ // The dock's factory indicator counts live runs only — the+ // view's one liveness rule (`FactoryRunSnapshot::is_live`: a+ // live state, or children still in flight — a `done` run whose+ // resident children still run keeps its count like its panel+ // and its stop control). Fully terminal runs stay as panels+ // inside the factory page, never in the indicator — the bash+ // group's running-only scoping, one lane over.+ let factory_runs = crate::factory_view::parse_factory_runs(&self.factory_graph)+ .iter()+ .filter(|run| run.is_live())+ .count();// 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 indicator — they render in the@@ -139,6 +152,11 @@ impl SessionUi {heartbeats: self.heartbeat_catalog.len(),heartbeats_paused: paused_heartbeat_count(&self.heartbeat_catalog),bash_running,+ factory_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).+ factory_group: self.factory_activity_supported(),goal_label,selected: self.activity_group,focused: self.subagents_focused,@@ -275,6 +293,10 @@ impl SessionUi {self.emit_activity_opened("bash");self.open_bash_view(view);}+ crate::chrome::ActivityGroup::Factory => {+ self.emit_activity_opened("factory");+ self.open_factory_page(view);+ }crate::chrome::ActivityGroup::Goal => {self.emit_activity_opened("goal");self.open_goal_panel(view);diff --git a/crates/pa-tui/src/view.rs b/crates/pa-tui/src/view.rsindex 5b8788653b..8be2c22e11 100644--- a/crates/pa-tui/src/view.rs+++ b/crates/pa-tui/src/view.rs@@ -116,6 +116,10 @@ pub struct AgentView {/// picker): while set, it owns the editor dock like the model/// picker.pub mcp_view: Option<crate::mcp_view::McpView>,+ /// The factory page: while set, it owns the editor dock like the+ /// inline pickers (one panel per live factory run) — the activity+ /// dock's factory group's destination.+ pub factory_view: Option<crate::factory_view::FactoryView>,/// The `/heartbeats` inline management view (TS/// `HeartbeatManagerComponent`, inline-picker style): while set, it/// owns the editor dock like the `/model` and `/effort` pickers.@@ -408,6 +412,7 @@ impl AgentView {fork_selector: None,effort_picker: None,mcp_view: None,+ factory_view: None,heartbeats_picker: None,goal_panel: None,bash_view: None,diff --git a/crates/pa-tui/src/view/frame.rs b/crates/pa-tui/src/view/frame.rsindex 99cfa5971f..6f4b04f0f4 100644--- a/crates/pa-tui/src/view/frame.rs+++ b/crates/pa-tui/src/view/frame.rs@@ -87,6 +87,10 @@ impl AgentView {let mut dock = prompt_context;dock.extend(mcp_view.render(&self.theme, width, self.editor.keybindings()));Some(dock)+ } else if let Some(factory_view) = self.factory_view.as_ref() {+ let mut dock = prompt_context;+ dock.extend(factory_view.render(&self.theme, width, self.editor.keybindings()));+ Some(dock)} else if let Some(picker) = &self.heartbeats_picker {let mut dock = prompt_context;dock.extend(picker.render(&self.theme, width, self.editor.keybindings()));@@ -336,6 +340,7 @@ impl AgentView {|| self.auth_panel.is_some()|| self.reload_box.is_some()|| self.settings_menu.is_some()+ || self.factory_view.is_some(){return None;}diff --git a/crates/pa-tui/src/view/tests.rs b/crates/pa-tui/src/view/tests.rsindex b33e3465d8..679593614d 100644--- a/crates/pa-tui/src/view/tests.rs+++ b/crates/pa-tui/src/view/tests.rs@@ -12,6 +12,29 @@ fn view() -> AgentView {AgentView::new(Theme::builtin("prime", ColorMode::TrueColor))}+/// The hardware caret never sits over the factory page: the page is an+/// input-less replacement view, so `frame_cursor` suppresses the stale+/// editor dock position while it is open (the settings menu's guard+/// family — Macroscope review finding: the factory page left the caret+/// parked at the previous editor position over the panel).+#[test]+fn the_factory_page_suppresses_the_stale_editor_cursor() {+ let mut v = view();+ v.dock_cursor = Some((10, 3));+ v.factory_view = Some(crate::factory_view::FactoryView::from_reply(+ &serde_json::json!({ "runs": [] }),+ 12,+ ));+ assert!(+ v.frame_cursor().is_none(),+ "the open factory page is an input-less overlay"+ );+ // ...and the editor's position reports again once the page closes+ // (`frame_cursor` maps the dock row through the window offset).+ v.factory_view = None;+ assert_eq!(v.frame_cursor(), Some((11, 3)));+}+/// A paste never reaches the editor behind an overlay (the key/// dispatch's frame owners): the input-bearing pickers take it, the/// input-less overlays consume it, and only the bare dock's editordiff --git a/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs b/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rsindex 59579e22a9..844ffc3190 100644--- a/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs+++ b/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs@@ -340,6 +340,12 @@ impl pa_tui::client_settings::ClientSettings for StubSettings {fn set_chat_detail(&self, _detail: &str) -> Result<()> {Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {self.anthropic_extra_usage}diff --git a/crates/pa-tui/tests/chat_detail_persist_headless.rs b/crates/pa-tui/tests/chat_detail_persist_headless.rsindex 51a963894a..7382252420 100644--- a/crates/pa-tui/tests/chat_detail_persist_headless.rs+++ b/crates/pa-tui/tests/chat_detail_persist_headless.rs@@ -302,6 +302,12 @@ impl pa_tui::client_settings::ClientSettings for StubSettings {*self.chat_detail.lock().expect("chat detail lock") = Some(detail.to_string());Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {true}diff --git a/crates/pa-tui/tests/esc_repeat_ladder_headless.rs b/crates/pa-tui/tests/esc_repeat_ladder_headless.rsindex d7d7c02194..63a0f3b7cc 100644--- a/crates/pa-tui/tests/esc_repeat_ladder_headless.rs+++ b/crates/pa-tui/tests/esc_repeat_ladder_headless.rs@@ -355,6 +355,12 @@ impl pa_tui::client_settings::ClientSettings for StubSettings {fn set_chat_detail(&self, _detail: &str) -> Result<()> {Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {true}diff --git a/crates/pa-tui/tests/factory_command_headless.rs b/crates/pa-tui/tests/factory_command_headless.rsnew file mode 100644index 0000000000..d71e7aa5cd--- /dev/null+++ b/crates/pa-tui/tests/factory_command_headless.rs@@ -0,0 +1,883 @@+//! Headless e2e for the `/factory` command (the factory's opt-in gate):+//! the status arm reports the disabled default, `on`/`off` persist the+//! gate through the settings seam (a stub seam: the write lands in+//! memory; the persisted settings-file shape is covered by the pa-cli+//! seam round-trip test), and a bad argument gets the usage error. The+//! harness daemon advertises no `factory_activity` lane, so the dock+//! mounts no factory group anywhere while it stays unadvertised (the+//! opt-in contract's off surface). The lane-advertised battery below+//! drives the off guard end to end, and the page battery opens the+//! dock's factory group into the live page and pins the picker keys'+//! repaint contract (the input loop paints every dispatched input — the+//! moved selection lands on the arrow's own repaint, never waiting for+//! the refresh poll).+#![cfg(unix)]+// Pedantic-gate exceptions (every other pedantic warning in this crate is+// fixed in place; each exception carries its one-line justification):+// - the casts: terminal-layout arithmetic narrows structurally bounded+// values (screen coordinates, byte counts, timestamps); guarded+// conversions would add panic paths the bounds guarantee away.+#![allow(+ clippy::cast_possible_truncation,+ clippy::cast_possible_wrap,+ clippy::cast_sign_loss,+ clippy::cast_precision_loss+)]+// - the render routes are flat tables (one arm per route); splitting them+// would add indirection without changing the flow.+#![allow(clippy::too_many_lines)]+// - widget state structs carry independent flag bits; a nested struct+// would add indirection without changing the shape.+#![allow(clippy::struct_excessive_bools, clippy::fn_params_excessive_bools)]+// - the futures are bounded by the surface's lifetime; boxing them would+// add an allocation to the steady-state loop.+#![allow(clippy::large_futures)]+// - the wrappers preserve a uniform Result-returning API surface; unwrap+// removals would ripple through the callers without changing behavior.+#![allow(clippy::unnecessary_wraps)]++use std::io::{BufRead, BufReader, Write};+use std::os::unix::net::{UnixListener, UnixStream};+use std::path::PathBuf;++use anyhow::Result;+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+use pa_tui::interactive::{+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,+ SessionSelection, UiMode,+};+use serde_json::{json, Value};++struct MockSupervisor {+ listener: UnixListener,+ /// The hello's advertised capabilities (the default hello advertises+ /// none, so the factory lane stays unadvertised).+ server_capabilities: Vec<String>,+ /// The `factory_activity` graph reply the mock answers while the+ /// lane is advertised: `None` answers every action with empty data.+ factory_graph: Option<Value>,+ /// The daemon refusal the mock answers the `graph` action with+ /// (`None` keeps the success path): the worker arm's exact wire+ /// shape for a session whose kernel is not built.+ factory_graph_error: Option<String>,+}++impl MockSupervisor {+ fn bind_with(+ socket: &std::path::Path,+ server_capabilities: Vec<String>,+ factory_graph: Option<Value>,+ factory_graph_error: Option<String>,+ ) -> Self {+ MockSupervisor {+ listener: UnixListener::bind(socket).expect("bind mock socket"),+ server_capabilities,+ factory_graph,+ factory_graph_error,+ }+ }++ /// Serve one connection: attach an empty session, then answer the+ /// loop's requests.+ fn serve(self) {+ let MockSupervisor {+ listener,+ server_capabilities,+ factory_graph,+ factory_graph_error,+ } = self;+ let (stream, _) = listener.accept().expect("accept");+ let write_stream = stream.try_clone().expect("clone mock socket");+ let mut writer = write_stream;+ let mut reader = BufReader::new(stream);++ let hello = json!({+ "type": "daemon_hello",+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "serverCapabilities": server_capabilities,+ "clientId": "mock",+ });+ write_json(&mut writer, &hello);++ let mut line = String::new();+ loop {+ line.clear();+ match reader.read_line(&mut line) {+ Ok(0) | Err(_) => break,+ Ok(_) => {}+ }+ let Ok(envelope) = serde_json::from_str::<Value>(line.trim()) else {+ continue;+ };+ let id = envelope.get("id").and_then(Value::as_str).unwrap_or("");+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);+ let command_type = command+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ match command_type.as_str() {+ "create" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "create",+ "success": true,+ "data": {+ "activeSessionId": "s1",+ "id": "s1",+ "sessionId": "sess-1",+ "sessionFile": "/tmp/sess-1.jsonl",+ },+ }),+ );+ }+ "attach" => {+ write_json(&mut writer, &attach_data(id));+ }+ "get_session_stats" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "get_session_stats",+ "success": true,+ "data": {+ "contextUsage": { "tokens": 1200, "contextWindow": 200_000 },+ "cost": 0.01,+ },+ }),+ );+ }+ "detach" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "detach",+ "success": true,+ }),+ );+ }+ "factory_activity" => {+ // The lane's mock: a graph action answers the+ // configured refusal (the worker arm's exact+ // kernel-not-running wire shape) or the configured+ // runs reply; every other action answers empty data+ // (the guard reads the graph list only).+ if command.get("action").and_then(Value::as_str) == Some("graph") {+ if let Some(error) = factory_graph_error.as_ref() {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "factory_activity",+ "success": false,+ "error": error,+ }),+ );+ continue;+ }+ }+ let data = match (+ factory_graph.as_ref(),+ command.get("action").and_then(Value::as_str),+ ) {+ (Some(runs), Some("graph")) => runs.clone(),+ _ => json!({}),+ };+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "factory_activity",+ "success": true,+ "data": data,+ }),+ );+ }+ _ => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": command_type,+ "success": true,+ "data": {},+ }),+ );+ }+ }+ }+ }+}++fn write_json(writer: &mut UnixStream, value: &Value) {+ let mut line = serde_json::to_string(value).expect("serialize mock frame");+ line.push('\n');+ writer.write_all(line.as_bytes()).expect("write mock frame");+ writer.flush().expect("flush mock frame");+}++/// The slim attach result: one empty session.+fn attach_data(id: &str) -> Value {+ json!({+ "type": "response",+ "id": id,+ "command": "attach",+ "success": true,+ "data": {+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "activeSessionId": "s1",+ "snapshot": {+ "activeSessionId": "s1",+ "summary": { "id": "s1", "cwd": "/tmp" },+ "state": {+ "activeSessionId": "s1",+ "cwd": "/tmp",+ "sessionId": "sess-1",+ "sessionName": "factory session",+ "model": null,+ "isStreaming": false,+ "isCompacting": false,+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },+ },+ "messages": [],+ "lastEventSequence": 0,+ "lastEventCursor": null,+ },+ "client": { "id": "mock", "capabilities": [] },+ "lastEventSequence": 0,+ "lastEventCursor": null,+ },+ })+}++/// A minimal settings seam for the harness: the factory gate reads and+/// writes through a recording cell (the opt-in default is disabled), and+/// every other getter returns its TS default with no-op writes.+#[derive(Default)]+struct RecordingSettings {+ factory_enabled: std::sync::Mutex<bool>,+}++impl pa_tui::client_settings::ClientSettings for RecordingSettings {+ fn theme(&self) -> Option<String> {+ None+ }+ fn set_theme(&self, _theme: &str) -> Result<()> {+ Ok(())+ }+ fn show_images(&self) -> bool {+ true+ }+ fn set_show_images(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn clear_on_shrink(&self) -> bool {+ false+ }+ fn set_clear_on_shrink(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn show_terminal_progress(&self) -> bool {+ false+ }+ fn set_show_terminal_progress(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn image_auto_resize(&self) -> bool {+ true+ }+ fn set_image_auto_resize(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn block_images(&self) -> bool {+ false+ }+ fn set_block_images(&self, _blocked: bool) -> Result<()> {+ Ok(())+ }+ fn image_model(&self) -> Option<String> {+ None+ }+ fn enable_skill_commands(&self) -> bool {+ true+ }+ fn set_enable_skill_commands(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn enable_builtin_skills(&self) -> bool {+ true+ }+ fn set_enable_builtin_skills(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn show_hardware_cursor(&self) -> bool {+ false+ }+ fn set_show_hardware_cursor(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn editor_padding_x(&self) -> u64 {+ 0+ }+ fn set_editor_padding_x(&self, _padding: u64) -> Result<()> {+ Ok(())+ }+ fn autocomplete_max_visible(&self) -> u64 {+ 5+ }+ fn set_autocomplete_max_visible(&self, _max: u64) -> Result<()> {+ Ok(())+ }+ fn quiet_startup(&self) -> bool {+ false+ }+ fn set_quiet_startup(&self, _quiet: bool) -> Result<()> {+ Ok(())+ }+ fn idle_eviction_minutes(&self) -> String {+ "90".to_string()+ }+ fn set_idle_eviction_minutes(&self, _value: &str) -> Result<()> {+ Ok(())+ }+ fn mermaid_rendering_mode(&self) -> String {+ "streaming".to_string()+ }+ fn set_mermaid_rendering_mode(&self, _mode: &str) -> Result<()> {+ Ok(())+ }+ fn tree_filter_mode(&self) -> String {+ "user-only".to_string()+ }+ fn set_tree_filter_mode(&self, _mode: &str) -> Result<()> {+ Ok(())+ }+ fn default_service_tier(&self) -> String {+ "default".to_string()+ }+ fn set_default_service_tier(&self, _tier: &str) -> Result<()> {+ Ok(())+ }+ fn chat_detail(&self) -> String {+ "details".to_string()+ }+ fn set_chat_detail(&self, _detail: &str) -> Result<()> {+ Ok(())+ }+ fn factory_enabled(&self) -> bool {+ *self.factory_enabled.lock().expect("factory gate lock")+ }+ fn set_factory_enabled(&self, enabled: bool) -> Result<()> {+ *self.factory_enabled.lock().expect("factory gate lock") = enabled;+ Ok(())+ }+ fn telemetry_status(&self) -> String {+ "telemetry enabled".to_string()+ }+ fn set_telemetry_enabled(&self, _enabled: bool) -> Result<String> {+ Ok("telemetry enabled".to_string())+ }+ fn warnings_anthropic_extra_usage(&self) -> bool {+ true+ }+ fn set_warnings_anthropic_extra_usage(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }+ fn update_channel(&self) -> Option<String> {+ None+ }+ fn set_update_channel(&self, _channel: &str) -> Result<()> {+ Ok(())+ }+ fn effective_update_channel(&self, _version: &str) -> String {+ "stable".to_string()+ }+}++fn options(socket: PathBuf) -> InteractiveOptions {+ InteractiveOptions {+ models: None,+ socket_path: socket,+ cwd: PathBuf::from("/tmp"),+ session_dir: None,+ script_path: None,+ model_selection: ModelSelection::default(),+ model_catalog: Vec::new(),+ model_configured_providers: std::collections::HashSet::default(),+ model_recent_models: Vec::new(),+ default_thinking_level: None,+ no_session: false,+ session: SessionSelection::New,+ initial_message: None,+ show_images: true,+ fullscreen_mouse: true,+ theme: "prime".to_string(),+ code_block_indent: " ".to_string(),+ tree_filter_mode: String::new(),+ branch_summary_skip_prompt: false,+ version: "0.0.0".to_string(),+ onboarding: None,+ telemetry_disabled: None,+ client_auth: None,+ traces: None,+ provider_auth: None,+ update_commands: None,+ telemetry: None,+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),+ session_rlm_depth: None,+ prompt_stash: std::sync::Arc::default(),+ session_has_children: false,+ restore_dock_focus: false,+ client_settings: Some(std::sync::Arc::new(RecordingSettings::default())),+ }+}++fn run_plan(steps: Vec<HeadlessStep>) -> Vec<String> {+ run_plan_config(Vec::new(), None, steps)+}++/// The harness entry with a configured mock daemon: the hello's+/// advertised capabilities and the `factory_activity` graph reply (the+/// `/factory off` lifecycle guard's lane).+fn run_plan_config(+ server_capabilities: Vec<String>,+ factory_graph: Option<Value>,+ steps: Vec<HeadlessStep>,+) -> Vec<String> {+ run_plan_config_with_graph_error(server_capabilities, factory_graph, None, steps)+}++/// The full mock configuration: the graph action can also answer a daemon+/// refusal (the kernel-not-running wire shape) instead of a runs reply.+fn run_plan_config_with_graph_error(+ server_capabilities: Vec<String>,+ factory_graph: Option<Value>,+ factory_graph_error: Option<String>,+ steps: Vec<HeadlessStep>,+) -> Vec<String> {+ std::env::remove_var("TMUX");+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("tui.sock");+ let supervisor = MockSupervisor::bind_with(+ &socket,+ server_capabilities,+ factory_graph,+ factory_graph_error,+ );+ let handle = std::thread::spawn(move || supervisor.serve());++ let runtime = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .build()+ .expect("tokio runtime");+ let plan = HeadlessPlan {+ steps,+ width: 100,+ height: 30,+ };+ let outcome = runtime+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))+ .expect("interactive run");+ handle.join().expect("mock supervisor finished");+ outcome.frames+}++/// The frames wrap notes to the frame width, so an assertion reads the+/// rendered text with the wraps collapsed.+fn flat_text(frames: &[String]) -> String {+ frames+ .join("\n")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+}++/// `/factory status` (and a bare `/factory`) report the disabled default,+/// and the dock never mounts a factory group while the daemon's hello+/// advertises no `factory_activity` lane: no `⚙` segment renders anywhere+/// (the opt-in contract's off surface).+#[test]+fn factory_status_reports_the_disabled_default_without_a_factory_group() {+ let steps = vec![+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory".to_string()),+ HeadlessStep::WaitMs(200),+ ];+ let frames = run_plan(steps);+ assert!(!frames.is_empty(), "frames were captured");+ let all = flat_text(&frames);+ assert!(+ all.contains(+ "The factory is disabled (off by default). Run /factory on to enable it (takes effect on the next client start)."+ ),+ "the disabled status note rendered:\n{all}"+ );+ assert!(+ !frames.join("\n").contains('⚙'),+ "no factory group renders while the lane is unadvertised:\n{all}"+ );+}++/// `/factory on` persists the gate and the status arm reads the new state+/// back; `/factory off` disables it again, and a bad argument keeps the+/// usage error.+#[test]+fn factory_on_and_off_round_trip_the_gate_through_the_seam() {+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory maybe".to_string()),+ HeadlessStep::WaitMs(200),+ ];+ let frames = run_plan(steps);+ let all = flat_text(&frames);+ assert!(+ all.contains(+ "The factory is enabled. Restart the client to surface the factory group (the factory page and the agent-side factory API follow the same gate)."+ ),+ "the enabled note rendered:\n{all}"+ );+ assert!(+ all.contains("The factory is enabled. Run /factory off to disable it."),+ "the enabled status read back:\n{all}"+ );+ assert!(+ all.contains(+ "The factory is disabled. The factory group and page disappear on the next client start."+ ),+ "the off note rendered:\n{all}"+ );+ assert!(+ all.contains(+ "The factory is disabled (off by default). Run /factory on to enable it (takes effect on the next client start)."+ ),+ "the disabled status read back:\n{all}"+ );+ assert!(+ all.contains("Usage: /factory [on|off|status]"),+ "the usage error rendered:\n{all}"+ );+}++/// One factory run row in the wire shape the kernel's graph lane sends+/// (camelCase): the state a `running` row counts as live, a `done` row+/// with `running` children in flight counts (the resident lifecycle —+/// the dock's own liveness rule), and a terminal `done` row with none+/// does not.+fn factory_run_row(id: &str, state: &str, running_children: u64) -> Value {+ json!({+ "runId": id,+ "specId": "sw",+ "state": state,+ "elapsedMs": 100,+ "machine": { "states": [], "transitions": [] },+ "nodes": [],+ "usage": { "running": running_children },+ })+}++/// `/factory off` refuses while the session's kernel reports live runs+/// (the lifecycle guard, end to end through the daemon lane): the+/// refusal names the live count, and the gate stays enabled — the runs+/// keep their stop and visibility path (the page, `rlm.factory.stop`)+/// until the user stops them. The live count reads the dock's own+/// liveness rule: a `running` run and a `done` run with children still+/// in flight both count; a fully terminal run never does.+#[test]+fn factory_off_refuses_while_runs_are_live() {+ let graph = json!({+ "runs": [+ factory_run_row("terminal", "done", 0),+ factory_run_row("resident", "done", 2),+ factory_run_row("live", "running", 1),+ ]+ });+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(400),+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ ];+ let frames = run_plan_config(vec!["factory_activity".to_string()], Some(graph), steps);+ let all = flat_text(&frames);+ assert!(+ all.contains(+ "Cannot disable the factory while 2 runs are still live — stop them first (the factory page's stop action or rlm.factory.stop), then /factory off."+ ),+ "the refusal names the live count:\n{all}"+ );+ assert!(+ all.contains("The factory is enabled. Run /factory off to disable it."),+ "the gate stayed enabled after the refused off:\n{all}"+ );+ assert!(+ !all.contains("The factory is disabled. The factory group and page disappear on the next client start."),+ "the off note never rendered:\n{all}"+ );+}++/// The complement: once no run is live (a fully terminal history), the+/// off write proceeds — the guard refuses only while the kernel reports+/// runs that still need their stop path.+#[test]+fn factory_off_proceeds_once_no_runs_are_live() {+ let graph = json!({+ "runs": [factory_run_row("terminal", "done", 0)]+ });+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(400),+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ ];+ let frames = run_plan_config(vec!["factory_activity".to_string()], Some(graph), steps);+ let all = flat_text(&frames);+ assert!(+ all.contains("The factory is disabled. The factory group and page disappear on the next client start."),+ "the off proceeded with only terminal runs:\n{all}"+ );+ assert!(+ all.contains("The factory is disabled (off by default). Run /factory on to enable it (takes effect on the next client start)."),+ "the disabled status read back:\n{all}"+ );+}++/// The same refusal on a client whose hello predates the gate: a client+/// started while the factory was off keeps its unadvertised hello (the+/// running connection never re-reads the advertisement), but `/factory+/// on` opens the kernel gate immediately — runs started after the toggle+/// are live in that same client, so the off guard must read the lane even+/// without the advertisement and refuse while they run.+#[test]+fn factory_off_refuses_on_a_client_whose_hello_predates_the_gate() {+ let graph = json!({+ "runs": [factory_run_row("live", "running", 1)]+ });+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(400),+ ];+ // The hello advertises nothing; the daemon still answers the lane.+ let frames = run_plan_config(Vec::new(), Some(graph), steps);+ let all = flat_text(&frames);+ assert!(+ all.contains(+ "Cannot disable the factory while 1 run is still live — stop it first (the factory page's stop action or rlm.factory.stop), then /factory off."+ ),+ "the unadvertised-lane guard still refused:\n{all}"+ );+}++/// The None path never blocks the client whose hello predates the lane+/// (the fail-open half of the unreadable-count rule): a daemon that+/// cannot report runs — an older daemon answers the unknown command with+/// a failure, a session without a kernel refuses — carries no live runs,+/// so the write proceeds; only the lane-advertised client fails closed+/// (the pin below).+#[test]+fn factory_off_proceeds_when_the_lane_cannot_report() {+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(400),+ ];+ // The mock answers every factory action with empty data: no runs list.+ let frames = run_plan_config(Vec::new(), None, steps);+ let all = flat_text(&frames);+ assert!(+ all.contains("The factory is disabled. The factory group and page disappear on the next client start."),+ "the unreadable count never blocked off:\n{all}"+ );+ assert!(+ !all.contains("Cannot disable the factory"),+ "no refusal without a readable count:\n{all}"+ );+}++/// The advertised lane fails closed on an unreadable count: a timed-out+/// or malformed graph reply cannot prove zero live runs, so the off write+/// refuses (an unknown liveness never opens the gate) and names the+/// unreadable count; the gate stays enabled for the retry.+#[test]+fn factory_off_refuses_when_the_advertised_lane_cannot_count() {+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(400),+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ ];+ // The lane is advertised; the mock answers every factory action with+ // empty data (a malformed reply the guard reads as an unreadable count).+ let frames = run_plan_config(vec!["factory_activity".to_string()], None, steps);+ let all = flat_text(&frames);+ assert!(+ all.contains(+ "Cannot disable the factory: the live-run count could not be read from the factory lane — try /factory off again once it answers."+ ),+ "the unreadable count refused the off:\n{all}"+ );+ assert!(+ all.contains("The factory is enabled. Run /factory off to disable it."),+ "the gate stayed enabled after the refused off:\n{all}"+ );+}++/// The kernel-not-running class never fails closed: the lane never+/// builds a kernel, and the kernel owns its run registry in memory, so a+/// session without a kernel cannot host live runs — the count reads as a+/// definitive zero even on the lane-advertised client (the refusal's+/// "try again once it answers" would never resolve otherwise: the lane+/// answers the same refusal until some other action boots the kernel,+/// so the advertised client could never disable an idle factory).+#[test]+fn factory_off_proceeds_when_the_kernel_is_not_running() {+ let steps = vec![+ HeadlessStep::Submit("/factory on".to_string()),+ HeadlessStep::WaitMs(200),+ HeadlessStep::Submit("/factory off".to_string()),+ HeadlessStep::WaitMs(400),+ HeadlessStep::Submit("/factory status".to_string()),+ HeadlessStep::WaitMs(200),+ ];+ // The lane is advertised; the mock answers the graph read with the+ // worker arm's exact kernel-not-running refusal.+ let frames = run_plan_config_with_graph_error(+ vec!["factory_activity".to_string()],+ None,+ Some("Kernel is not running".to_string()),+ steps,+ );+ let all = flat_text(&frames);+ assert!(+ all.contains("The factory is disabled. The factory group and page disappear on the next client start."),+ "the no-kernel count never blocked off:\n{all}"+ );+ assert!(+ all.contains("The factory is disabled (off by default). Run /factory on to enable it (takes effect on the next client start)."),+ "the disabled status read back:\n{all}"+ );+ assert!(+ !all.contains("Cannot disable the factory"),+ "no refusal without a kernel to host live runs:\n{all}"+ );+}++/// One live named run row for the page battery (the wire shape the+/// kernel's graph lane sends): the name the panel header paints.+fn factory_page_run(id: &str, name: &str) -> Value {+ json!({+ "runId": id,+ "specId": "sw",+ "name": name,+ "state": "running",+ "elapsedMs": 100,+ "machine": { "states": [], "transitions": [] },+ "nodes": [],+ "usage": { "running": 0 },+ })+}++/// One alt+a key event (the dock's focus hand-off).+fn alt_a() -> KeyEvent {+ KeyEvent::new(KeyCode::Char('a'), KeyModifiers::ALT)+}++/// One right-arrow key event (the dock's next-section step).+fn dock_right() -> KeyEvent {+ KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)+}++/// One down-arrow key event (the page's `tui.select.down`).+fn down() -> KeyEvent {+ KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)+}++/// One plain Enter key event (the dock's focused-section open).+fn enter() -> KeyEvent {+ KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)+}++/// One Esc key event (`tui.select.cancel`: the open page closes).+fn escape() -> KeyEvent {+ KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)+}++/// The page's picker keys repaint on the key itself, never waiting for+/// the 2-second refresh poll (the input loop's render contract: every+/// dispatched input paints — the same TS `handleInput` parity that+/// carries the dock's arrows and every other picker key). The pin closes+/// the page on the input right after the arrow, so no poll window can+/// sit between the move and the paint: the moved selection marker must+/// land in a captured frame on the arrow's own repaint — and the poll+/// alone could never produce it, because a fold preserves the selected+/// run id, so a picker key that skipped its repaint would leave the+/// marker on the old run forever (the fold repaints the same unmoved+/// selection).+#[test]+fn factory_page_picker_keys_paint_the_moved_selection_on_the_key() {+ // Oldest first on the wire; the page reads newest-first, so+ // second-run is the opening selection and first-run is one Down away.+ let graph = json!({+ "runs": [+ factory_page_run("run-old", "first-run"),+ factory_page_run("run-new", "second-run"),+ ]+ });+ let steps = vec![+ // Focus the dock and step to the factory group (subagents ->+ // heartbeats -> shells -> factory); Enter opens the page.+ HeadlessStep::Key(alt_a()),+ HeadlessStep::Key(dock_right()),+ HeadlessStep::Key(dock_right()),+ HeadlessStep::Key(dock_right()),+ HeadlessStep::Key(enter()),+ // The page opens on the feed's live head: the newest run.+ HeadlessStep::WaitRender {+ needle: "factory: second-run".to_string(),+ timeout_ms: 5_000,+ },+ // Down moves the selection to the older run, and Esc closes the+ // page on the very next input — no poll cycle can land between+ // the two, so the moved marker below can only be the arrow's own+ // repaint.+ HeadlessStep::Key(down()),+ HeadlessStep::Key(escape()),+ HeadlessStep::WaitMs(200),+ ];+ let frames = run_plan_config(vec!["factory_activity".to_string()], Some(graph), steps);+ let all = flat_text(&frames);+ assert!(+ all.contains("factory: second-run"),+ "the page mounted on the newest run:\n{all}"+ );+ assert!(+ all.contains("\u{25b8} factory: first-run"),+ "the arrow's own repaint painted the moved selection before the page closed:\n{all}"+ );+}diff --git a/crates/pa-tui/tests/nightly_command_headless.rs b/crates/pa-tui/tests/nightly_command_headless.rsindex 1f60e2c1e5..2ab9427daf 100644--- a/crates/pa-tui/tests/nightly_command_headless.rs+++ b/crates/pa-tui/tests/nightly_command_headless.rs@@ -303,6 +303,12 @@ impl pa_tui::client_settings::ClientSettings for StubSettings {fn set_chat_detail(&self, _detail: &str) -> Result<()> {Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {true}diff --git a/crates/pa-tui/tests/settings_menu_headless.rs b/crates/pa-tui/tests/settings_menu_headless.rsindex fcbd9920b7..4eafeb1a2d 100644--- a/crates/pa-tui/tests/settings_menu_headless.rs+++ b/crates/pa-tui/tests/settings_menu_headless.rs@@ -362,6 +362,12 @@ impl pa_tui::client_settings::ClientSettings for RecordingSettings {fn set_chat_detail(&self, _detail: &str) -> Result<()> {Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {true}diff --git a/crates/pa-tui/tests/skills_menu_headless.rs b/crates/pa-tui/tests/skills_menu_headless.rsindex 9bb01e2896..84bbbc91d6 100644--- a/crates/pa-tui/tests/skills_menu_headless.rs+++ b/crates/pa-tui/tests/skills_menu_headless.rs@@ -399,6 +399,12 @@ impl pa_tui::client_settings::ClientSettings for StubSettings {fn set_chat_detail(&self, _detail: &str) -> Result<()> {Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {true}diff --git a/crates/pa-tui/tests/telemetry_command_headless.rs b/crates/pa-tui/tests/telemetry_command_headless.rsindex cde1cb549c..c89ebc5a6b 100644--- a/crates/pa-tui/tests/telemetry_command_headless.rs+++ b/crates/pa-tui/tests/telemetry_command_headless.rs@@ -319,6 +319,12 @@ impl pa_tui::client_settings::ClientSettings for StubSettings {fn set_chat_detail(&self, _detail: &str) -> Result<()> {Ok(())}+ fn factory_enabled(&self) -> bool {+ false+ }+ fn set_factory_enabled(&self, _enabled: bool) -> Result<()> {+ Ok(())+ }fn warnings_anthropic_extra_usage(&self) -> bool {true}diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rsindex 5cad672d75..b456ad540e 100644--- a/crates/pa-types/src/daemon/command.rs+++ b/crates/pa-types/src/daemon/command.rs@@ -549,6 +549,23 @@ pub enum DaemonCommand {#[serde(flatten)]rest: JsonMap,},+ /// The `/factory` view's bridge lane over the session kernel's factory+ /// executor (`graph`/`status`/`watch`/`run`/`stop`/`resume`).+ /// Rust-native extension, advertised by the `factory_activity` capability.+ FactoryActivity {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ id: Option<String>,+ active_session_id: String,+ action: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ run_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ spec_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ timeout_ms: Option<u64>,+ #[serde(flatten)]+ rest: JsonMap,+ },CancelRlmChild {#[serde(default, skip_serializing_if = "Option::is_none")]id: Option<String>,diff --git a/crates/pa-types/src/daemon/mod.rs b/crates/pa-types/src/daemon/mod.rsindex 2916395a1d..e18f3131d3 100644--- a/crates/pa-types/src/daemon/mod.rs+++ b/crates/pa-types/src/daemon/mod.rs@@ -124,7 +124,7 @@ pub use outbound::{DaemonClosingReason, DaemonErrorInfo, DaemonEventEnvelope, DaemonOutbound,DaemonPeerTransportTicket, DaemonResponse, DaemonRuntimeIdentity, DaemonSavedSessionInfo,DaemonSessionClosedReason, DaemonSessionSnapshot, SnapshotPurpose, SocketIdentity,- UPDATE_RESTART_PREPARING_MESSAGE,+ KERNEL_NOT_RUNNING_MESSAGE, UPDATE_RESTART_PREPARING_MESSAGE,};pub use plane::{command_plane, is_daemon_mutating_command, is_session_plane_daemon_command,diff --git a/crates/pa-types/src/daemon/outbound.rs b/crates/pa-types/src/daemon/outbound.rsindex c842a6e2ce..318c555d39 100644--- a/crates/pa-types/src/daemon/outbound.rs+++ b/crates/pa-types/src/daemon/outbound.rs@@ -36,6 +36,14 @@ pub struct DaemonResponse {/// clients that wait through the restart (TS #2391).pub const UPDATE_RESTART_PREPARING_MESSAGE: &str = "Daemon is preparing an update restart";+/// The session-addressed lanes' refusal when the session's kernel is not+/// running (the lane never builds one: `factory_activity` answers without+/// booting an idle kernel). A definitive answer, not a transient failure —+/// the kernel owns its run registry in memory, so a session without a+/// kernel carries no live runs; clients read it as such (the TUI's+/// `/factory off` guard counts zero instead of an unreadable count).+pub const KERNEL_NOT_RUNNING_MESSAGE: &str = "Kernel is not running";+/// Structured failure info carried on error responses, tagged by `code`.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(diff --git a/crates/pa-types/src/slash_commands.rs b/crates/pa-types/src/slash_commands.rsindex 574bc31aa0..589872d588 100644--- a/crates/pa-types/src/slash_commands.rs+++ b/crates/pa-types/src/slash_commands.rs@@ -84,6 +84,7 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: &[BuiltinSlashCommand] = &[BuiltinSlashCommand { name: "rlm-max-depth", description: "Set/view the per-chat persistent RLM max depth immediately; never interrupts or queues the running turn", execution: SlashCommandExecution::Client, argument_hint: Some("[<int> [--global]]"), aliases: &[], takes_argument: true },BuiltinSlashCommand { name: "heartbeat", description: "Set or view a persistent heartbeat; delivery defaults to steer, use --follow-up to queue; supports pause, resume, stop, and clear", execution: SlashCommandExecution::Client, argument_hint: Some("[status|pause|resume|stop|[every <duration>] [--steer|--follow-up] <instruction>]"), aliases: &[], takes_argument: true },BuiltinSlashCommand { name: "heartbeats", description: "View and manage all user and agent heartbeats", execution: SlashCommandExecution::Client, argument_hint: None, aliases: &[], takes_argument: false },+ BuiltinSlashCommand { name: "factory", description: "Show or set the agent factory opt-in gate (off by default)", execution: SlashCommandExecution::Client, argument_hint: Some("[on|off|status]"), aliases: &[], takes_argument: true },BuiltinSlashCommand { name: "resume", description: "Open the agents view, or resume a session by id or path", execution: SlashCommandExecution::Client, argument_hint: Some("[id|path]"), aliases: &[], takes_argument: true },BuiltinSlashCommand { name: "reload", description: "Reload keybindings, skills, prompts, and themes", execution: SlashCommandExecution::Client, argument_hint: None, aliases: &[], takes_argument: false },BuiltinSlashCommand { name: "speed", description: "Toggle footer readout of model output tok/sec (latest response and session average)", execution: SlashCommandExecution::Client, argument_hint: Some("[on|off]"), aliases: &[], takes_argument: true },diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 05fd634014..5181c950eb 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -9,7 +9,15 @@ from pathlib import Pathfrom typing import Anyfrom .bash import BashHandle, BashResult, bash-from .factory import FACTORY_HELP, resume_factory, run_factory, status_factory, stop_factory+from .factory import (+ FACTORY_HELP,+ graph_factory,+ resume_factory,+ run_factory,+ status_factory,+ stop_factory,+ watch_factory,+)from .harness import HarnessEntry, HarnessScope, HarnessState, RefinementEvent, get_harness_state_NOT_CALLABLE_MESSAGE = "'rlm' is not callable; spawn a child with: handle = await rlm.spawn('sub-task', name='worker')"@@ -529,7 +537,8 @@ _harness_state = _HarnessProxy()class _RLMFactoryNamespace:- """Run stored state-machine factories: rlm.factory.run/status/stop/resume.+ """Run stored state-machine factories: rlm.factory.run/status/stop/resume,+ plus graph/watch for live monitoring.``run('<spec_id>')`` validates a stored factory entry (machine form, ordag sugar that compiles to one), enters the entry states up to the@@ -547,6 +556,15 @@ class _RLMFactoryNamespace:broken machine names its exact errors; a missing one lists what thelibrary has).+ ``graph()`` returns the machine structure fused with live runtime state+ (``status()``'s data plus the static graph): pass a live run id for one+ run's snapshot, a stored spec id for the static structure, or nothing+ for every live run. ``watch('<run_id>', timeout)`` blocks until the+ run's state/instance shape changes or the timeout elapses (bounded),+ then returns the same snapshot with ``changed`` — an agent can stream+ progress and drive orchestration programmatically, and the emitted+ graph model renders as ASCII or genuine Mermaid from one shape.+The factory is opt-in: while the ``factory.enabled`` setting is off (thedefault; the user turns it on with ``/factory on``), every call aboverefuses with one clean message and only ``help()`` answers, so the@@ -569,6 +587,12 @@ class _RLMFactoryNamespace:async def resume(self, run_id: str) -> dict[str, Any]:return await resume_factory(run_id)+ async def graph(self, ref: str | None = None) -> dict[str, Any]:+ return graph_factory(ref)++ async def watch(self, run_id: str, timeout: float = 0.0) -> dict[str, Any]:+ return await watch_factory(run_id, timeout)+def help(self) -> str:"""Return the embedded factory authoring reference and API guide."""return FACTORY_HELPdiff --git a/prime-agent-runtime/src/rlm/factory.py b/prime-agent-runtime/src/rlm/factory.pyindex e49bcb6d81..411e756640 100644--- a/prime-agent-runtime/src/rlm/factory.py+++ b/prime-agent-runtime/src/rlm/factory.py@@ -44,6 +44,7 @@ import copyimport hashlibimport heapqimport json+import mathimport osimport reimport time@@ -102,6 +103,70 @@ def _is_positive_int(value: Any) -> bool:return _is_int(value) and value > 0+MAX_GUARD_VALUE_DEPTH = 256+"""Nesting bound on one guard comparison value (``when.value``). Every+seam the value rides recurses per level — the traversal itself, the+snapshot's ``deepcopy``, the wire conversion, the reply frames' JSON+encoder — so a value deeper than this bound cannot ride any of them and+would exhaust the interpreter's stack on the way to finding out. A+container nested beyond the bound rejects as part of the same+finite-JSON-data rule, with the validation answer instead of the crash."""+++def _value_is_finite(+ value: Any, _seen: "frozenset[int] | None" = None, _depth: int = 0+) -> bool:+ """True when a guard comparison value is JSON clean: every nested+ float finite, every object key a string, every leaf a JSON scalar,+ and no cycle.+ JSON carries no NaN/Infinity tokens, so a non-finite float would+ serialize as the non-JSON ``NaN``/``Infinity`` tokens and break every+ strict consumer of the reply frames (the host bridge's parser+ included) — a machine declaring one is invalid at the source. Object+ keys must be strings for the same reason at both ends: a non-finite+ float key carries the token into the frame the same way, and a+ non-string key (an int, a tuple) is either coerced by the encoder —+ so the wire object no longer matches the machine's declared one —+ or rejected by it; either way it is not the declared comparison.+ Leaves outside JSON's scalar set reject the same way: a tuple (or a+ set, bytes, any other container the JSON grammar has no spelling+ for) serializes as something other than the declared shape if the+ encoder accepts it at all, and the non-finite floats it can carry+ would ride that path past this check. A self-referential container+ is rejected too — the encoder refuses circular references outright,+ so it can never be a valid comparison value — and the traversal+ stops at the cycle instead of exhausting the interpreter's stack+ chasing it. ``_seen`` threads the per-branch ancestry (a+ shared-but-acyclic reference appearing twice stays valid: each+ branch checks it independently). Depth bounds the nesting the same+ way: a container nested beyond ``MAX_GUARD_VALUE_DEPTH`` levels+ cannot ride any of the value's downstream seams (the snapshot's+ deep copy, the wire conversion, the reply frames' encoder are each+ recursive per level), so it rejects here with the validation answer+ instead of exhausting the interpreter's stack further down the+ write path.+ """+ if _depth > MAX_GUARD_VALUE_DEPTH:+ return False+ seen = _seen or frozenset()+ if isinstance(value, (list, dict)):+ if id(value) in seen:+ return False+ seen = seen | {id(value)}+ if isinstance(value, float):+ return math.isfinite(value)+ if isinstance(value, (bool, int, str)) or value is None:+ return True+ if isinstance(value, list):+ return all(_value_is_finite(item, seen, _depth + 1) for item in value)+ if isinstance(value, dict):+ return all(+ isinstance(key, str) and _value_is_finite(item, seen, _depth + 1)+ for key, item in value.items()+ )+ return False++def _is_nonempty_str(value: Any) -> bool:return isinstance(value, str) and value != ""@@ -410,6 +475,13 @@ def _validate_guard(errors.append(f"transitions[{index}] when.op 'contains' requires a non-empty list value")elif op in ("eq", "ne") and not _is_scalar(value):errors.append(f"transitions[{index}] when.op {op!r} requires a scalar value")+ if not _value_is_finite(value):+ errors.append(+ f"transitions[{index}] when.value must be finite JSON data "+ "(JSON carries no NaN or Infinity, and only JSON shapes "+ "serialize: lists, objects, strings, numbers, booleans, null, "+ f"and no container nests deeper than {MAX_GUARD_VALUE_DEPTH} levels)"+ )def validate_factory_machine(machine: Any) -> list[str]:@@ -953,6 +1025,34 @@ parent or replay checker reads.POLL_TIMEOUT_MS = 2000"""How long each control-loop ``rlm.collect`` waits for unsettled children."""+WATCH_TIMEOUT_CAP_SECONDS = 60.0+"""Upper bound on one ``factory.watch`` timeout (seconds), the agent-side+streaming monitor's ceiling. The host bridge caps its own lane lower+(``FACTORY_HOST_WATCH_TIMEOUT_MS``); this is the kernel-side bound."""++LAST_FIRED_WINDOW = 10+# The unscoped graph's terminal-history window: the newest terminal runs+# the all-runs reply carries (every live run reports regardless).+GRAPH_RUNS_WINDOW = 20+"""Trailing fired transitions the graph snapshot reports for edge marking."""++GRAPH_EVENTS_TAIL = 40+"""Trailing ledger events a compact (host-lane) graph snapshot carries."""++FACTORY_FRAME_CAP = 262_144+"""Serialized byte cap on one factory_activity reply frame. A graph for the+full 1024-state machine cap fits; a snapshot that cannot shrink under the+cap fails loudly instead of being silently truncated."""++ACTIVITY_ACTIONS = ("graph", "status", "watch", "run", "stop", "resume")+"""The host bridge's actions over one factory run, the ``factory_activity``+frame's action vocabulary (the kernel namespace is the same surface plus+``graph``/``watch`` for agents)."""++ACTIVITY_TIMEOUT_MS_CAP = int(WATCH_TIMEOUT_CAP_SECONDS * 1000)+"""Upper bound on one factory_activity frame's timeoutMs (the watch wait+bound on the wire); the host bridge pins its own lower bound."""+BACKOFF_MAX_ATTEMPTS = 5"""Spawn admissions per node before a persistent rate limit fails the node."""@@ -1279,9 +1379,12 @@ class FactoryRun:run_id: strspec_id: strname: str | None- # The canonicalized machine this run executes: a stored entry's spec or a- # library machine's template, kept so export_machine can serialize the- # exact machine a run is running (byte-pretty, stable formatting).+ # The canonicalized machine this run executes: a stored entry's spec or+ # a library machine's template, kept read-only. The graph snapshot's+ # static structure (states, transitions, run block) reads it, so+ # agents and the TUI see the machine the run validated, and+ # export_machine serializes the exact machine a run is running+ # (byte-pretty, stable formatting).machine: "dict[str, Any]" = field(default_factory=dict)state: str = "running" # running | stopping | paused | done | failed | stoppedstarted_at: float = 0.0@@ -1318,6 +1421,12 @@ class FactoryRun:# sources settle in one collect batch fires once, not once per source# settle, and re-fires only when a source settles again.join_fired: dict[tuple[int, str], frozenset[tuple[str, int]]] = field(default_factory=dict)+ # Watch bookkeeping: bumped on every ledger event (every observable+ # mutation emits one), and every registered watch future resolves with+ # the new revision. ``factory.watch`` compares signatures, so a bump+ # that leaves the run's state/instance shape unchanged just re-arms.+ revision: int = 0+ watchers: list = field(default_factory=list)class FactoryExecutor:@@ -1459,42 +1568,7 @@ class FactoryExecutor:Raises ``ValueError`` for an unknown run id."""run = self._require_run(run_id)- nodes: list[dict[str, Any]] = []- for state_id in run.order:- state = run.states[state_id]- entry_report: dict[str, Any] = {- "id": state.state_id,- "status": state.status,- "lifecycle": state.lifecycle,- "attempts": sum(- instance.attempt for entry in state.entries for instance in entry.instances- ),- "entries_used": state.entries_used,- "max_entries": state.max_entries,- "entries": [- {"index": entry.index, "status": entry.status, "error": entry.error}- for entry in state.entries- ],- "instances": [- {- "index": instance.index,- "entry": entry.index,- "status": instance.status,- "attempt": instance.attempt,- "child": instance.child_id,- "duration_ms": instance.duration_ms,- "error": instance.error,- }- for entry in state.entries- for instance in entry.instances- ],- }- latest = state.latest_settle()- if latest is not None and latest.answer:- entry_report["answer_preview"] = latest.answer- if state.error is not None:- entry_report["error"] = state.error- nodes.append(entry_report)+ nodes = [self._state_report(run.states[state_id]) for state_id in run.order]for event in run.events:if event["stage"] in ("recorded", "arrived"):event["stage"] = "delivered"@@ -1506,15 +1580,7 @@ class FactoryExecutor:"nodes": nodes,"events": [dict(event) for event in run.events[-EVENT_WINDOW:]],"elapsed_ms": int((self._now_fn() - run.started_at) * 1000),- "usage": {- "spawns": run.spawn_count,- "settled": run.settle_count,- "tool_uses": run.tool_use_total,- "max_parallel": run.max_parallel,- "max_children": run.max_children,- "running": self._running_instance_count(run),- "transitions_fired": run.transitions_fired,- },+ "usage": self._usage_report(run),}async def stop(self, run_id: str) -> dict[str, Any]:@@ -1534,6 +1600,7 @@ class FactoryExecutor:if run.state in ("stopping", "stopped"):return {"run_id": run.run_id, "state": run.state, "cancelled": []}run.state = "stopping"+ self._touch(run)stopped = await self._halt_nonterminal(run, "run stopped")run.state = "stopped"self._event(run, "run_stopped", detail=f"stopped; {len(stopped)} state(s) cancelled")@@ -1557,6 +1624,7 @@ class FactoryExecutor:run.loop_generation += 1run.state = "running"run.pause_reason = None+ self._touch(run)self._event(run, "resumed", detail="resumed by caller")# Evaluate settles first: paused runs may still carry transitions to# fire (escalate) before anything can be admitted.@@ -1575,6 +1643,394 @@ class FactoryExecutor:"pending": self._pending_state_ids(run),}+ # -- graph, watch, host activity ------------------------------------------++ def _state_report(+ self, state: _StateRun, *, include_answer: bool = True+ ) -> dict[str, Any]:+ """One state's live report, the exact ``status()`` node shape.++ The graph snapshot reuses it verbatim so the fused view is+ ``status()``'s data plus the static graph (``include_answer=False``+ drops the settle answer preview on the compact host lane, where+ nothing renders answers). The report carries the stage's agent+ occupancy — ``running`` (admitted children in flight) and+ ``queued`` (prepared instances waiting for a parallel slot) —+ so every surface reads "how many agents are at this stage"+ without re-deriving it from the instance rows; both keys are+ single words, so the wire's camelCase conversion carries them+ unchanged.+ """+ report: dict[str, Any] = {+ "id": state.state_id,+ "status": state.status,+ "lifecycle": state.lifecycle,+ "attempts": sum(+ instance.attempt for entry in state.entries for instance in entry.instances+ ),+ "entries_used": state.entries_used,+ "max_entries": state.max_entries,+ "entries": [+ {"index": entry.index, "status": entry.status, "error": entry.error}+ for entry in state.entries+ ],+ "instances": [+ {+ "index": instance.index,+ "entry": entry.index,+ "status": instance.status,+ "attempt": instance.attempt,+ "child": instance.child_id,+ "duration_ms": instance.duration_ms,+ "error": instance.error,+ }+ for entry in state.entries+ for instance in entry.instances+ ],+ "running": sum(+ 1+ for entry in state.entries+ for instance in entry.instances+ if instance.status == "running"+ ),+ "queued": sum(+ 1+ for entry in state.entries+ for instance in entry.instances+ if instance.status == "pending"+ ),+ }+ if include_answer:+ latest = state.latest_settle()+ if latest is not None and latest.answer:+ report["answer_preview"] = latest.answer+ if state.error is not None:+ report["error"] = state.error+ return report++ def _usage_report(self, run: FactoryRun) -> dict[str, Any]:+ """The usage block ``status()`` returns; the graph snapshot reuses it."""+ return {+ "spawns": run.spawn_count,+ "settled": run.settle_count,+ "tool_uses": run.tool_use_total,+ "max_parallel": run.max_parallel,+ "max_children": run.max_children,+ "running": self._running_instance_count(run),+ "transitions_fired": run.transitions_fired,+ }++ def _last_fired(self, run: FactoryRun) -> list[dict[str, Any]]:+ """The trailing fired transitions (newest firing first, at most+ ``LAST_FIRED_WINDOW`` edges) for the diagram's edge marking. The+ ledger is the authority: an edge that fired twice keeps its latest+ firing only."""+ latest: dict[str, dict[str, Any]] = {}+ for event in run.events:+ if event.get("kind") != "transition_fired":+ continue+ from_field = event.get("from")+ # The guard rides the edge's identity: two guarded transitions+ # may share one from+to pair, and the diagram's fired marking+ # needs the one that actually fired (the event's ``when``).+ edge = {+ "from": from_field,+ "to": event.get("to"),+ "seq": event.get("seq"),+ "when": event.get("when"),+ }+ latest[+ f"{json.dumps(from_field, sort_keys=True)}->{event.get('to')}"+ f"@{json.dumps(event.get('when'), sort_keys=True, default=str)}"+ ] = edge+ ordered = sorted(latest.values(), key=lambda edge: edge["seq"], reverse=True)+ return ordered[:LAST_FIRED_WINDOW]++ def _graph_events(self, run: FactoryRun, *, compact: bool) -> list[dict[str, Any]]:+ """The trailing event window. The compact host lane sheds answer+ payloads (the ``answer_captured`` rows) and carries the shorter+ ``GRAPH_EVENTS_TAIL`` tail; the agent lane sees ``status()``'s full+ ``EVENT_WINDOW`` window with stages untouched (``graph`` is a pure+ read; only ``status()`` marks events delivered)."""+ window = run.events[-(GRAPH_EVENTS_TAIL if compact else EVENT_WINDOW) :]+ events = [dict(event) for event in window]+ if compact:+ events = [event for event in events if event.get("kind") != "answer_captured"]+ return events++ def _graph_snapshot(self, run: FactoryRun, *, compact: bool) -> dict[str, Any]:+ """One live run's fused snapshot: the machine structure plus the+ live overlay (nodes, active nodes, last-fired edges, events tail,+ usage, budget consumed)."""+ elapsed_ms = int((self._now_fn() - run.started_at) * 1000)+ return {+ "run_id": run.run_id,+ "spec_id": run.spec_id,+ "name": run.name,+ "state": run.state,+ "pause_reason": run.pause_reason,+ "elapsed_ms": elapsed_ms,+ "machine": _machine_structure(+ run.machine,+ {+ state_id: (run.states[state_id].model, run.states[state_id].thinking)+ for state_id in run.order+ },+ ),+ "nodes": [+ self._state_report(run.states[state_id], include_answer=not compact)+ for state_id in run.order+ ],+ # Activity is children-shaped, not entry-shaped alone: a+ # foreach entry that failed permanently (failure_policy+ # continue) is terminal at the entry layer while its+ # admitted siblings still run -- the quiescence contract+ # (_run_complete) counts those instances, and the node report+ # carries them as the stage's occupancy, so a stage with+ # live children stays in the overlay exactly while its+ # occupancy label can be nonzero.+ "active_nodes": [+ state_id+ for state_id in run.order+ if any(+ entry.status in ("pending", "running")+ or any(+ instance.status in ("pending", "running")+ for instance in entry.instances+ )+ for entry in run.states[state_id].entries+ )+ ],+ "last_fired": self._last_fired(run),+ "events": self._graph_events(run, compact=compact),+ "usage": self._usage_report(run),+ "budget": {"limit_ms": run.run_budget_ms, "consumed_ms": elapsed_ms},+ }++ def _spec_snapshot(+ self, spec_id: str, canonical: dict[str, Any], *, compact: bool+ ) -> dict[str, Any]:+ """A stored spec's static graph: no live run exists, so the overlay+ reports the shape a fresh run starts from (nothing entered, nothing+ consumed). The compact flag is accepted for lane symmetry; a spec+ graph carries no answers to shed."""+ run_block = canonical["run"]+ return {+ "run_id": None,+ "spec_id": spec_id,+ "name": None,+ "state": None,+ "pause_reason": None,+ "elapsed_ms": 0,+ "machine": _machine_structure(canonical),+ "nodes": [],+ "active_nodes": [],+ "last_fired": [],+ "events": [],+ "usage": None,+ "budget": {"limit_ms": run_block.get("budget_ms"), "consumed_ms": 0},+ }++ def graph(self, ref: str | None = None, *, compact: bool = False) -> dict[str, Any]:+ """One machine's structure fused with live runtime state.++ ``ref`` naming a live run id returns that run's fused snapshot+ (``status()``'s data plus the static graph and the diagram overlay);+ ``ref`` naming a stored factory spec id returns the static+ structure with no live overlay. ``ref=None`` returns every live+ run's snapshot, oldest run first, as ``{"runs": [...]}`` (the view+ lane's polling shape). Raises ``ValueError`` when ``ref`` names+ neither a live run nor a stored spec, or a stored spec fails its+ own validation.+ """+ if ref is None:+ # Insertion order is start order (runs append to the registry),+ # so the oldest run reports first; a clock tie between two+ # starts never shuffles the panels. The unscoped list is+ # BOUNDED: every live run reports (the dock's count and the+ # view's panels stay exact), and the terminal history keeps+ # at most the newest ``GRAPH_RUNS_WINDOW`` runs — the wire cap+ # would drop older terminal runs anyway, and the bound keeps+ # one polling reply's construction O(window), not+ # O(registry) (the registry retains every run it ever+ # hosted; by-ref snapshots stay available for all of them).+ # Liveness is children-shaped, not state-shaped alone: a+ # ``done``/``failed`` run whose instances are still in+ # flight (the resident lifecycle — admitted residents never+ # block completion, and the finished milestone tells the+ # operator to ``rlm.factory.stop()`` them) is LIVE, so the+ # page keeps the run and its stop control while any child+ # runs; the terminal history window holds only runs with no+ # child in flight.+ live_states = ("running", "stopping", "paused")+ # The registry's insertion order is start order, so the list's+ # tail is the newest terminal history.+ terminal_ids = [+ run.run_id+ for run in self._runs.values()+ if run.state not in live_states and self._running_instance_count(run) == 0+ ]+ newest_terminal_ids = set(terminal_ids[-GRAPH_RUNS_WINDOW:])+ return {+ "runs": [+ self._graph_snapshot(run, compact=compact)+ for run in self._runs.values()+ if run.state in live_states+ or self._running_instance_count(run) > 0+ or run.run_id in newest_terminal_ids+ ]+ }+ run = self._runs.get(ref)+ if run is not None:+ return self._graph_snapshot(run, compact=compact)+ harness = self._resolve_harness()+ entry = harness.get("factory", ref)+ if entry is None:+ raise ValueError(f"unknown factory run or spec {ref!r}")+ arguments = entry.arguments if isinstance(entry.arguments, dict) else {}+ spec = arguments.get("machine")+ if spec is None:+ spec = arguments.get("dag")+ try:+ canonical = canonicalize_factory_spec(spec)+ except ValueError as exc:+ raise ValueError(f"factory spec {ref!r} does not validate: {exc}") from exc+ return self._spec_snapshot(entry.id, canonical, compact=compact)++ def _signature(self, run: FactoryRun) -> tuple[Any, ...]:+ """The run's live shape a watch treats as a change: the run state,+ every state's entries and per-instance statuses, and the transition+ counter. Ledger-only movement (backoff notices, repeated+ milestones) leaves the shape unchanged, so the wait re-arms instead+ of waking the caller with an identical graph (no per-transition+ spam at the watch surface either).+ """++ def state_shape(state: _StateRun) -> tuple[Any, ...]:+ return (+ state.status,+ state.entries_used,+ tuple(+ (entry.index, entry.status, tuple(i.status for i in entry.instances))+ for entry in state.entries+ ),+ )++ return (+ run.state,+ run.pause_reason,+ run.transitions_fired,+ tuple((state_id, state_shape(run.states[state_id])) for state_id in run.order),+ )++ async def watch(+ self, run_id: str, timeout: float = 0.0, *, compact: bool = False+ ) -> dict[str, Any]:+ """Block until the run's state/instance shape changes or the bounded+ ``timeout`` (seconds, capped at ``WATCH_TIMEOUT_CAP_SECONDS``)+ elapses, then return the same fused snapshot ``graph()`` returns+ with one extra ``changed`` key: whether a change ended the wait or+ the deadline did. An already-changed run returns immediately; the+ clock and sleep are the executor's injected pair, so the wait is+ testable and bounded on the same lane the control loop uses.+ Raises ``ValueError`` for an unknown run id or a negative or+ non-numeric timeout.+ """+ import asyncio++ run = self._require_run(run_id)+ # NaN passes every arithmetic check (every comparison is false), so+ # it must be rejected by identity: a NaN deadline would reach+ # asyncio.sleep, which raises instead of returning the bounded+ # snapshot (a NaN timeout is not a number here).+ if not _is_number(timeout) or math.isnan(float(timeout)):+ raise ValueError("timeout must be a non-negative number of seconds")+ if timeout < 0:+ raise ValueError("timeout must be a non-negative number of seconds")+ timeout = min(float(timeout), WATCH_TIMEOUT_CAP_SECONDS)+ deadline = self._now_fn() + timeout+ baseline = self._signature(run)+ changed = False+ while True:+ if self._signature(run) != baseline:+ changed = True+ break+ remaining = deadline - self._now_fn()+ if remaining <= 0:+ break+ waiter = asyncio.get_running_loop().create_future()+ run.watchers.append(waiter)+ sleeper = asyncio.ensure_future(self._sleep_fn(remaining))+ try:+ await asyncio.wait({sleeper, waiter}, return_when=asyncio.FIRST_COMPLETED)+ finally:+ if waiter in run.watchers:+ run.watchers.remove(waiter)+ sleeper.cancel()+ try:+ await sleeper+ except asyncio.CancelledError:+ pass+ snapshot = self._graph_snapshot(run, compact=compact)+ return {"changed": changed, **snapshot}++ async def activity(self, request: dict[str, Any]) -> Any:+ """Handle one out-of-band ``factory_activity`` request frame (the+ host bridge's lane): route the action to ``graph``/``status``/+ ``watch``/``run``/``stop``/``resume`` and return the reply's result+ payload. Raises ``ValueError`` for malformed requests and unknown+ runs/specs (the reply carries it as the error reason). ``graph``+ and ``watch`` answer with the compact snapshots (the host lane+ renders diagrams, not answers); ``run`` is the lane that starts a+ run from the daemon or TUI, so it rides the full ``run()``+ validation. The reply's result payload carries the WIRE's+ camelCase keys (``_wire_payload`` re-keys the snake_case rows: the+ protocol's request frame is camelCase end to end) — the+ conversation API (``rlm.factory.graph()`` in-kernel) stays+ snake_case.+ """+ # The lane rides the same opt-in gate as the namespace: while+ # ``factory.enabled`` is off, every activity action -- ``run``+ # included, which would otherwise bypass the namespace's gate --+ # refuses with the one refusal message.+ require_factory_enabled()+ action = request.get("action")+ if action not in ACTIVITY_ACTIONS:+ raise ValueError(f"unknown factory activity action {action!r}")+ run_id = request.get("runId")+ spec_id = request.get("specId")+ for key, value in (("runId", run_id), ("specId", spec_id)):+ if value is not None and not isinstance(value, str):+ raise ValueError(f"factory activity {key} must be a string when provided")+ timeout_ms = request.get("timeoutMs")+ if timeout_ms is None:+ timeout_ms = 0+ if not _is_int(timeout_ms) or not 0 <= timeout_ms <= ACTIVITY_TIMEOUT_MS_CAP:+ raise ValueError(+ f"factory activity timeoutMs must be an integer between 0 and {ACTIVITY_TIMEOUT_MS_CAP}"+ )+ if action == "graph":+ return _wire_payload(self.graph(run_id or spec_id, compact=True))+ if action == "status":+ if not run_id:+ raise ValueError("factory activity status requires runId")+ return _wire_payload(await self.status(run_id))+ if action == "watch":+ if not run_id:+ raise ValueError("factory activity watch requires runId")+ return _wire_payload(+ await self.watch(run_id, timeout_ms / 1000.0, compact=True)+ )+ if action == "run":+ if not spec_id:+ raise ValueError("factory activity run requires specId")+ return _wire_payload(await self.run(spec_id))+ if not run_id:+ raise ValueError(f"factory activity {action} requires runId")+ if action == "stop":+ return _wire_payload(await self.stop(run_id))+ return _wire_payload(await self.resume(run_id))+# -- setup --------------------------------------------------------------def _resolve_harness(self) -> Any:@@ -1711,8 +2167,22 @@ class FactoryExecutor:event["detail"] = detailevent.update(extra)run.events.append(event)+ # Every ledger event is an observable mutation, so the watch+ # bookkeeping rides the same seam: bump the revision and resolve+ # every registered watcher. ``watch`` re-checks its signature, so+ # an event that leaves the state/instance shape unchanged (a+ # backoff notice, a repeated milestone) just re-arms the wait.+ self._touch(run)return event+ def _touch(self, run: FactoryRun) -> None:+ """Bump the run's watch revision and wake every registered watcher."""+ run.revision += 1+ for waiter in run.watchers:+ if not waiter.done():+ waiter.set_result(run.revision)+ run.watchers = []+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).@@ -1846,11 +2316,19 @@ class FactoryExecutor:if join_signature is not None:run.join_fired[join_signature[0]] = join_signature[1]run.transitions_fired += 1+ # The guard rides the fired event (and the ``last_fired``+ # edge the graph overlay reads): two guarded transitions may+ # share one from+to pair, so the guard is the only identity+ # that tells the diagram WHICH of them fired.+ when = transition.get("when")+ fired_fields: dict[str, Any] = {"from": from_field, "to": target.state_id}+ if when is not None:+ fired_fields["when"] = copy.deepcopy(when)self._event(run,"transition_fired",detail=f"{from_field!r} -> {target.state_id!r}",- **{"from": from_field, "to": target.state_id},+ **fired_fields,)self._enter_state(run, target, from_state=state_id)@@ -2885,6 +3363,234 @@ async def resume_factory(run_id: str) -> dict[str, Any]:return await default_factory_executor().resume(run_id)+def graph_factory(ref: str | None = None, *, compact: bool = False) -> dict[str, Any]:+ """Return one machine's structure fused with live state (see+ ``FactoryExecutor.graph``): a live run id, a stored spec id, or no ref+ for every live run."""+ require_factory_enabled()+ return default_factory_executor().graph(ref, compact=compact)+++async def watch_factory(+ run_id: str, timeout: float = 0.0, *, compact: bool = False+) -> dict[str, Any]:+ """Block until the run's state/instance shape changes or the bounded+ timeout elapses, then return the same fused snapshot ``graph()``+ returns plus ``changed``."""+ require_factory_enabled()+ return await default_factory_executor().watch(run_id, timeout, compact=compact)+++def _machine_structure(+ machine: dict[str, Any],+ resolved: "dict[str, tuple[str | None, str | None]] | None" = None,+) -> dict[str, Any]:+ """One canonical machine's static graph structure: the run block, every+ state's declared shape (id, entry, lifecycle, caps, spawn settings), the+ transitions with their guards, and the declared state order. Live runs+ pass their resolved spawn settings (``resolved``); spec graphs pass none+ and surface the inline-declared ones only. The diagram layers read the+ declared order, and edge identity pairs ``from`` (a state id, or a join's+ id list) with ``to``.+ """+ run_block = machine.get("run") if isinstance(machine.get("run"), dict) else {}+ run_out: dict[str, Any] = {+ "max_parallel": run_block.get("max_parallel", RUN_MAX_PARALLEL_DEFAULT),+ "max_transitions": run_block.get("max_transitions", MAX_TRANSITIONS_CAP),+ "failure_policy": run_block.get("failure_policy", RUN_FAILURE_POLICY_DEFAULT),+ "max_children": run_block.get("max_children", RUN_MAX_CHILDREN_DEFAULT),+ }+ if "budget_ms" in run_block:+ run_out["budget_ms"] = run_block["budget_ms"]+ states_out: list[dict[str, Any]] = []+ for state in machine["states"]:+ row: dict[str, Any] = {+ "id": state["id"],+ "entry": bool(state.get("entry", STATE_ENTRY_DEFAULT)),+ "lifecycle": state.get("lifecycle", NODE_LIFECYCLE_DEFAULT),+ "max_entries": state.get("max_entries", STATE_MAX_ENTRIES_DEFAULT),+ "retries": state.get("retries", NODE_RETRIES_DEFAULT),+ }+ model, thinking = (resolved or {}).get(state["id"], (None, None))+ subagent = state.get("subagent")+ if isinstance(subagent, dict):+ # A resolved live run carries the executor's spawn settings for+ # both subagent forms; a spec graph surfaces the inline-declared+ # ones only (a reference form's settings resolve at run time).+ if model is None and subagent.get("model") is not None:+ model = subagent["model"]+ if thinking is None and subagent.get("thinking") is not None:+ thinking = subagent["thinking"]+ if subagent.get("name"):+ row["subagent"] = subagent["name"]+ else:+ row["subagent"] = subagent+ if model is not None:+ row["model"] = model+ if thinking is not None:+ row["thinking"] = thinking+ states_out.append(row)+ transitions_out: list[dict[str, Any]] = []+ for transition in machine.get("transitions") or []:+ # The snapshot owns its mutable rows: a join's ``from`` list is+ # deep-copied like ``when`` so a consumer mutating the snapshot+ # (appending an unknown source) can never corrupt the active run's+ # machine — a corrupted join would wait for a state that never+ # settles and the transition would never fire.+ row_transition: dict[str, Any] = {+ "from": copy.deepcopy(transition["from"]),+ "to": transition["to"],+ "on": transition.get("on", TRANSITION_ON_KINDS[0]),+ }+ if "when" in transition:+ row_transition["when"] = copy.deepcopy(transition["when"])+ transitions_out.append(row_transition)+ return {+ "run": run_out,+ "states": states_out,+ "transitions": transitions_out,+ "order": [state["id"] for state in machine["states"]],+ }+++def _wire_keys(key: str) -> str:+ """snake_case -> the wire's camelCase (``run_id`` -> ``runId``)."""+ head, *rest = key.split("_")+ return head + "".join(part.capitalize() for part in rest)+++def _wire_payload(value: Any) -> Any:+ """The activity lane's wire conversion: the ``factory_activity``+ protocol is camelCase end to end (the request frame's ``runId``/+ ``specId``/``timeoutMs``), so the reply's result payload re-keys its+ own snake_case rows to the same wire spelling. Only dict KEYS convert+ (values ride verbatim: state ids, milestone text). A guard dict+ (``output`` + ``op`` — the validated guard signature) rides the wire+ VERBATIM: its structure keys are single words already, and its+ comparison ``value`` mirrors the executor's declared condition+ exactly, so re-keying it would display a condition that no longer+ matches the machine. The in-kernel conversation API+ (``rlm.factory.graph()`` and friends) stays snake_case.+ """+ if isinstance(value, dict):+ if "output" in value and "op" in value:+ return copy.deepcopy(value)+ return {_wire_keys(key): _wire_payload(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_wire_payload(item) for item in value]+ return value+++def schedule_activity(request: dict[str, Any]) -> None:+ """Schedule one out-of-band ``factory_activity`` request on the running+ loop. The kernel's reader thread calls this (the frame bypasses the+ cell FIFO like ``bash_activity``); the activity runs as a loop task so+ a busy cell never delays the host bridge, and the reply frame lands+ when the activity settles."""+ import asyncio++ asyncio.get_running_loop().create_task(_run_activity(request))+++async def _run_activity(request: dict[str, Any]) -> None:+ """Run one factory_activity request to completion and emit its reply."""+ from .repl import _send++ rid = request["id"]+ try:+ result = await default_factory_executor().activity(request)+ except Exception as exc: # noqa: BLE001 - the reply lane must never hang+ # An internal executor error still answers: a dropped reply would+ # leave the host waiter on its timeout instead of the reason. The+ # error frame rides the same wire cap as the success frame — a+ # multi-megabyte reason (an unknown id carrying a huge value) must+ # never exceed the transport bound; the cap's fallback replaces it+ # with the loud wire-cap message when it cannot fit.+ frame: dict[str, Any] = {"event": "done", "id": rid, "status": "error", "reason": str(exc)}+ _cap_factory_frame(frame)+ _send(frame)+ return+ frame: dict[str, Any] = {"event": "done", "id": rid, "status": "ok", "result": result}+ _cap_factory_frame(frame)+ _send(frame)+++_WIRE_LIVE_RUN_STATES = ("running", "stopping", "paused")+++def _wire_run_row_is_live(row: Any) -> bool:+ """Whether a wire run row is LIVE in the dock/page sense — the same+ rule the TUI's ``is_live`` reads and the unscoped list builds (a live+ state, or children still in flight): the wire cap's eviction must+ never silently drop a row the dock counts and the ``/factory off``+ guard trusts (every live run reports — the live-exactness contract)."""+ if not isinstance(row, dict):+ return False+ if row.get("state") in _WIRE_LIVE_RUN_STATES:+ return True+ usage = row.get("usage")+ return isinstance(usage, dict) and usage.get("running", 0) > 0+++def _shed_runs_frame(runs: list[Any]) -> bool:+ """One shed step for an all-runs reply under the wire cap, newest data+ kept longest: a run row's event tail trims from its oldest end first+ (the by-ref reply's own trim rule, applied per row, oldest row first),+ then the oldest DROPPABLE row drops — a live row never silently drops+ (the count and panels read it; the honest answer for a frame only+ live rows cannot fit is the loud failure). At least one row always+ stays, so a reply never claims a registry it did not read. Returns+ whether one step shed; ``False`` means only unsheddable rows remain."""+ for row in runs:+ if not isinstance(row, dict):+ continue+ tail = row.get("events")+ if isinstance(tail, list) and len(tail) > 1:+ tail.pop(0)+ return True+ if len(runs) > 1:+ for index, row in enumerate(runs):+ if not _wire_run_row_is_live(row):+ runs.pop(index)+ return True+ return False+++def _cap_factory_frame(frame: dict[str, Any]) -> None:+ """Keep one reply under the ``FACTORY_FRAME_CAP`` wire cap. Compacted+ snapshots already shed answer payloads, so the events tail trims from+ the oldest end first; an all-runs reply sheds the same way — each+ row's event tail floors before any whole row drops, and the drop+ takes the oldest DROPPABLE row (a live row never silently drops: the+ dock's count, the page's panels, and the ``/factory off`` guard read+ this list, and every live run reports). A frame that still cannot fit+ fails loudly (a graph must never truncate silently)."""+ while len(json.dumps(frame)) > FACTORY_FRAME_CAP:+ result = frame.get("result")+ events = result.get("events") if isinstance(result, dict) else None+ if isinstance(events, list) and len(events) > 1:+ events.pop(0)+ continue+ runs = result.get("runs") if isinstance(result, dict) else None+ if isinstance(runs, list) and _shed_runs_frame(runs):+ continue+ frame.pop("result", None)+ frame["status"] = "error"+ frame["reason"] = "factory activity reply exceeds the wire cap"+ return+ # A non-finite float anywhere in the frame would serialize as the+ # non-JSON tokens NaN/Infinity and break every strict consumer of+ # the reply (the host bridge's parser included) — validation blocks+ # them at the machine's source; this belt fails loudly if one ever+ # slips through, instead of emitting the token.+ try:+ json.dumps(frame, allow_nan=False)+ except ValueError:+ frame.pop("result", None)+ frame["status"] = "error"+ frame["reason"] = "factory activity reply contains non-finite values"++# ---------------------------------------------------------------------------# Machine library: MACHINE.md files (import, export, share).#@@ -3934,25 +4640,48 @@ status["usage"] # spawns, settled, tool_uses, max_parallel, max_children, run# transitions_fired```-The live monitoring views (`graph()` and a bounded `watch()`) arrive-with the stacked live-view PR; `status()` covers the run state, node-detail, and the event ledger until then.+`graph()` and `watch()` are the live monitoring views this namespace+ships alongside the stacked live-view PR's TUI page:++```python+graph = await rlm.factory.graph(result["run_id"])+# {"run_id": "...", "spec_id": "pr-manager", "state": "running",+# "machine": {"order": [...], "states": [...],+# "transitions": [...], "run": {...}},+# "nodes": [...], "active_nodes": [...], "last_fired": [...],+# "events": [...], "usage": {...}, "budget": {"limit_ms": ...,+# "consumed_ms": ...}} — structure fused with live state.++every = await rlm.factory.graph() # every live run ({"runs": [...]})+spec = await rlm.factory.graph("pr-manager") # a stored spec's static graph++watched = await rlm.factory.watch(result["run_id"], 30)+# the same fused snapshot plus "changed" — the call blocks until the+# run's state/instance shape changes or the bounded timeout elapses,+# so one call streams a run's progress without polling `status()`.+```++- `graph(ref)` fuses the machine's structure (states, guarded+ transitions, the declared order) with the live run's overlay (the+ node reports, active nodes, recently fired edges, the event tail,+ usage, budget consumed); a stored spec id answers the static+ structure, and no ref answers every live run.+- `watch(run_id, timeout)` returns immediately with the snapshot when+ nothing changed, blocks until the run's state/instance shape changes,+ and answers `"changed": false` on the bounded timeout.- `run` re-validates the spec and resolves every subagent reference first,reporting all failures in one `ValueError` and starting nothing on anyfailure; `name=` labels the run in status and the TUI.-- Pause and failure milestones (escalate, budget, max_transitions,- max_children, failed, finished) are recorded in the run's event- ledger, every repeat included, the pause milestones with the resume- call spelled out — read `status()`'s trailing events to see them.- Quiet conversation notices for the milestones (one per kind per run)- arrive with the stacked live-view PR, which adds the host side that- renders them.+- 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.- `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.-- The activity lane the daemon and TUI speak arrives with the stacked- live-view PR, camelCase on the wire (`runId`, `specId`, `timeoutMs`);- the kernel API here (`rlm.factory.*`) is snake_case.+- The activity lane the daemon and TUI speak is camelCase on the wire+ (`runId`, `specId`, `timeoutMs`); the kernel API here+ (`rlm.factory.*`) is snake_case.## Discovering machines@@ -3973,9 +4702,11 @@ detail, and the event ledger until then.`builder`, `pr-manager`, and `review-sweep`; the worked examples abovederive from their shapes.- The TUI factory page: the activity dock's `⚙ N factory` group (Enter or- click) opens one live diagram per run, newest run first. `j`/`k` move the- selection, `s` stops the selected run, `r` resumes it, `m` copies it as- Mermaid source, Esc closes.+ click) opens one live diagram per run, newest run first. The up/down+ arrows move the run selection, Enter opens the selected run's action+ rows (stop, or resume first while the run is paused — the arrows walk+ the rows, Enter runs the tracked action), and Esc backs out of the rows+ before it closes the page.## Safetydiff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.pyindex 6a30bacd7e..5fd0cdaa9d 100644--- a/prime-agent-runtime/src/rlm/repl.py+++ b/prime-agent-runtime/src/rlm/repl.py@@ -31,6 +31,7 @@ import uuidfrom collections.abc import Awaitable, Callablefrom typing import Any+from . import factory as factory_modulefrom .bash import _kill_live_handlesPROTOCOL_VERSION = 3@@ -1383,6 +1384,7 @@ _REQUIRED_FIELDS = {# string-required field; the handler validates the list itself."mcp_status": ("id",),"bash_activity": ("id", "action"),+ "factory_activity": ("id", "action"),"shutdown": (),}@@ -1436,6 +1438,34 @@ def _handle_request_line(raw: bytes, queue: asyncio.Queue[dict[str, Any]]) -> No# by the runtime, not by an arbitrary PID supplied by the client._handle_bash_activity(req)return+ if rtype == "factory_activity":+ from .factory import ACTIVITY_ACTIONS, ACTIVITY_TIMEOUT_MS_CAP++ if req["action"] not in ACTIVITY_ACTIONS:+ _protocol_error(f"unknown factory activity action: {req['action']!r}")+ return+ for field in ("runId", "specId"):+ value = req.get(field)+ if value is not None and not isinstance(value, str):+ _protocol_error(f"factory activity {field} must be a string when provided")+ return+ timeout_ms = req.get("timeoutMs")+ if timeout_ms is not None and (+ not isinstance(timeout_ms, int) or isinstance(timeout_ms, bool)+ or not 0 <= timeout_ms <= ACTIVITY_TIMEOUT_MS_CAP+ ):+ _protocol_error(+ f"factory activity timeoutMs must be an integer between 0 and {ACTIVITY_TIMEOUT_MS_CAP}"+ )+ return+ if len(req["id"]) > 256:+ _protocol_error("factory activity ids must stay under 256 characters")+ return+ # Like bash_activity, this bypasses the cell FIFO: the factory view+ # must answer while a cell runs. The handler schedules the async+ # activity on this loop and replies when it settles.+ _loop.call_soon_threadsafe(factory_module.schedule_activity, req)+ returnif rtype in ("execute", "snapshot", "restore"):with _interrupt_lock:# A reused in-flight id would corrupt interrupt/finish bookkeeping.diff --git a/prime-agent-runtime/test/test_factory.py b/prime-agent-runtime/test/test_factory.pyindex 2ad221ec1f..6a8dde9be1 100644--- a/prime-agent-runtime/test/test_factory.py+++ b/prime-agent-runtime/test/test_factory.py@@ -68,6 +68,8 @@ from rlm.factory import (MACHINE_FILE_NAME,MACHINE_SPEC_FENCE,POLL_TIMEOUT_MS,+ RUN_MAX_CHILDREN_DEFAULT,+ RUN_MAX_PARALLEL_DEFAULT,SUBAGENT_NAME_MAX_LENGTH,FactoryExecutor,MachineFile,@@ -1704,6 +1706,150 @@ class ValidateFactoryMachineTest(unittest.TestCase):self.assertEqual(validate_factory_machine(machine), [])self.assertEqual(validate_factory_spec(machine), [])+ def test_guard_values_must_be_finite(self) -> None:+ # Regression (bot review): a non-finite float in a guard comparison+ # value serializes as the non-JSON NaN/Infinity tokens and breaks+ # every strict consumer of the activity reply frames (the host+ # bridge's parser included) — validation rejects them at the+ # machine's source, deeply (a contains needle list carries the+ # same rule).+ def machine_with(when: Any) -> dict[str, Any]:+ return {+ "states": [+ state("a", entry=True, outputs=[{"name": "verdict", "type": "json"}]),+ state("b"),+ ],+ "transitions": [{"from": "a", "to": "b", "when": when}],+ }++ for bad in (float("nan"), float("inf"), float("-inf")):+ self.assertEqual(+ validate_factory_machine(+ machine_with({"output": "verdict", "op": "eq", "value": bad})+ ),+ ["transitions[0] when.value must be finite JSON data (JSON carries no NaN or Infinity, and only JSON shapes serialize: lists, objects, strings, numbers, booleans, null, and no container nests deeper than 256 levels)"],+ repr(bad),+ )+ nested = machine_with(+ {"output": "verdict", "op": "contains", "value": ["ok", {"x": float("nan")}]}+ )+ self.assertEqual(+ validate_factory_machine(nested),+ ["transitions[0] when.value must be finite JSON data (JSON carries no NaN or Infinity, and only JSON shapes serialize: lists, objects, strings, numbers, booleans, null, and no container nests deeper than 256 levels)"],+ )++ def test_guard_value_object_keys_must_be_strings(self) -> None:+ # The same wire-cleanliness rule at the object's keys: a+ # non-finite float key serializes as the non-JSON ``NaN`` token+ # and breaks the strict consumers, and a non-string key is either+ # coerced by the encoder (the wire object no longer matches the+ # declared machine) or rejected by it — a guard declaring one+ # never survives the reply frames.+ def machine_with(value: Any) -> dict[str, Any]:+ return {+ "states": [+ state("a", entry=True, outputs=[{"name": "verdict", "type": "json"}]),+ state("b"),+ ],+ "transitions": [+ {"from": "a", "to": "b", "when": {"output": "verdict", "op": "contains", "value": value}}+ ],+ }++ for bad in (+ {float("nan"): 1},+ {1: "x"},+ {"ok": {("tuple",): 2}},+ # Non-JSON container leaves reject at the source: a tuple+ # serializes as something other than the declared shape (an+ # array) if the encoder accepts it at all, and the floats it+ # carries would ride past the finiteness traversal.+ (float("nan"),),+ ("plain", "tuple"),+ {"set", "of", "strings"},+ b"bytes",+ ):+ self.assertEqual(+ validate_factory_machine(machine_with(["ok", bad])),+ ["transitions[0] when.value must be finite JSON data (JSON carries no NaN or Infinity, and only JSON shapes serialize: lists, objects, strings, numbers, booleans, null, and no container nests deeper than 256 levels)"],+ repr(bad),+ )+ # String keys with finite values stay valid.+ self.assertEqual(+ validate_factory_machine(machine_with(["ok", {"flag": True, "nested": {"count": 2}}])),+ [],+ )++ def test_guard_value_cycles_reject_without_exhausting_the_stack(self) -> None:+ # A self-referential container can never serialize (the encoder+ # refuses circular references outright), so it is not a valid+ # comparison value: the traversal must reject it at the cycle+ # instead of chasing it to a RecursionError, and the write path+ # must answer the validation error, not crash.+ def machine_with(value: Any) -> dict[str, Any]:+ return {+ "states": [+ state("a", entry=True, outputs=[{"name": "verdict", "type": "json"}]),+ state("b"),+ ],+ "transitions": [+ {"from": "a", "to": "b", "when": {"output": "verdict", "op": "contains", "value": value}}+ ],+ }++ cycle: list[Any] = ["ok"]+ cycle.append(cycle)+ self.assertEqual(+ validate_factory_machine(machine_with(cycle)),+ ["transitions[0] when.value must be finite JSON data (JSON carries no NaN or Infinity, and only JSON shapes serialize: lists, objects, strings, numbers, booleans, null, and no container nests deeper than 256 levels)"],+ )+ nested: dict[str, Any] = {"flag": True}+ nested["self"] = nested+ self.assertEqual(+ validate_factory_machine(machine_with([nested])),+ ["transitions[0] when.value must be finite JSON data (JSON carries no NaN or Infinity, and only JSON shapes serialize: lists, objects, strings, numbers, booleans, null, and no container nests deeper than 256 levels)"],+ )+ # A shared-but-acyclic reference is NOT a cycle: the same object+ # appearing twice (a diamond) stays a valid comparison value.+ shared = {"flag": True}+ self.assertEqual(validate_factory_machine(machine_with([shared, shared])), [])++ def test_guard_value_depth_rejects_without_exhausting_the_stack(self) -> None:+ # Deep-but-ACYCLIC nesting is the cycle rule's other half: the+ # traversal descends one level per recursion, so a value nested+ # past the interpreter's stack would raise RecursionError on the+ # write path instead of answering the validation error. Every+ # downstream seam recurses per level the same way (the snapshot's+ # deep copy, the wire conversion, the reply frames' encoder), so+ # the nesting rejects at the bound with the same message — and a+ # value under the bound (realistic guard values nest a handful of+ # levels) stays valid.+ def machine_with(value: Any) -> dict[str, Any]:+ return {+ "states": [+ state("a", entry=True, outputs=[{"name": "verdict", "type": "json"}]),+ state("b"),+ ],+ "transitions": [+ {"from": "a", "to": "b", "when": {"output": "verdict", "op": "contains", "value": value}}+ ],+ }++ deep: list[Any] = []+ node = deep+ for _ in range(factory_module.MAX_GUARD_VALUE_DEPTH + 50):+ child: list[Any] = []+ node.append(child)+ node = child+ self.assertEqual(+ validate_factory_machine(machine_with(deep)),+ ["transitions[0] when.value must be finite JSON data (JSON carries no NaN or Infinity, and only JSON shapes serialize: lists, objects, strings, numbers, booleans, null, and no container nests deeper than 256 levels)"],+ )+ within: list[Any] = ["verdict"]+ for _ in range(10):+ within = [within]+ self.assertEqual(validate_factory_machine(machine_with(within)), [])+def test_guard_rules(self) -> None:def machine_with(when: Any) -> dict[str, Any]:return {@@ -2361,15 +2507,15 @@ class FactoryHelpTest(unittest.TestCase):missing = [name for name in advertised if not hasattr(namespace, name)]self.assertEqual(missing, [])# The core calls stay advertised (dotted examples) and the whole- # namespace surface stays implemented.- for name in ("run", "status", "stop"):+ # namespace surface stays implemented. This branch IS the stacked+ # live-view PR: it ships the graph()/watch() implementations, so+ # the guide teaches them as call examples and the namespace+ # carries them (the same invariant the core pins on its own tree,+ # which trims them because its namespace stops at resume()).+ for name in ("run", "status", "stop", "graph", "watch"):self.assertIn(name, advertised)- for name in ("run", "status", "stop", "resume", "help"):+ for name in ("run", "status", "stop", "resume", "help", "graph", "watch"):self.assertTrue(hasattr(namespace, name), name)- # The not-yet-shipped views are named as roadmap prose, never as- # call examples.- self.assertNotRegex(doc, r"rlm\.factory\.(graph|watch)\(")- self.assertIn("(`graph()` and a bounded `watch()`) arrive with the stacked live-view PR", flat)# ---------------------------------------------------------------------------@@ -2504,6 +2650,13 @@ class ClockSleep:self.clock.advance(seconds)+async def turn_sleep(seconds: float) -> None:+ """Injectable sleep that really waits (10ms slices, never advancing the+ injected clock): a watch's re-arm loop yields to the event loop between+ slices, so a concurrent mutation lands mid-wait."""+ await asyncio.sleep(0.01)++class GatedSleep:"""Injectable sleep that suspends every call until released."""@@ -2848,6 +3001,43 @@ class FactoryOptInGateTest(_ExecutorTestCase):await callself.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)+ @async_test+ async def test_graph_and_watch_refuse_with_the_exact_message(self) -> None:+ self.store_factory({"nodes": [self.node("a")]}, spec_id="sw")+ result = await self.start()+ run_id = result["run_id"]+ self.disable_factory()+ for call in (+ rlm_module.rlm.factory.graph(run_id),+ rlm_module.rlm.factory.graph(),+ rlm_module.rlm.factory.graph("sw"),+ rlm_module.rlm.factory.watch(run_id, 0.5),+ ):+ with self.assertRaises(ValueError) as raised:+ await call+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)++ @async_test+ async def test_the_activity_lane_refuses_while_disabled(self) -> None:+ # The daemon stops advertising the lane while the factory is off;+ # the kernel seam fails closed behind the advertisement: a stale+ # client that still speaks the lane gets the one refusal on every+ # action -- run included, which would otherwise bypass the+ # namespace's gate.+ self.store_factory({"nodes": [self.node("a")]}, spec_id="sw")+ result = await self.start()+ run_id = result["run_id"]+ self.disable_factory()+ for action in ("graph", "watch", "status", "run", "stop", "resume"):+ request: dict[str, Any] = {"action": action}+ if action in ("graph", "watch", "status", "stop", "resume"):+ request["runId"] = run_id+ if action == "run":+ request["specId"] = "sw"+ with self.assertRaises(ValueError) as raised:+ await self.executor.activity(request)+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)+def test_help_answers_while_disabled(self) -> None:self.disable_factory()doc = rlm_module.rlm.factory.help()@@ -4590,6 +4780,21 @@ class FactoryExecutorTest(_ExecutorTestCase):self.assertEqual(right["status"], "pending")self.assertEqual(self.host.spawn_calls("right"), [])self.assertEqual(status["usage"]["transitions_fired"], 1)+ # The fired event and the last_fired edge carry the guard that+ # fired: two guarded transitions may share one from+to pair, so+ # the guard is the identity the diagram's fired marking reads.+ fired = self.all_events_of(result, "transition_fired")+ self.assertEqual(len(fired), 1)+ self.assertEqual(+ fired[0]["when"],+ {"output": "pick", "path": "choice", "op": "eq", "value": "left"},+ )+ graph = await rlm_module.rlm.factory.graph(result["run_id"])+ self.assertEqual(len(graph["last_fired"]), 1)+ self.assertEqual(+ graph["last_fired"][0]["when"],+ {"output": "pick", "path": "choice", "op": "eq", "value": "left"},+ )@async_testasync def test_machine_fan_out_from_one_settle_fires_all(self) -> None:@@ -5579,6 +5784,873 @@ class FactoryExecutorTest(_ExecutorTestCase):self.assertEqual(self.node_status(status, "collect-findings-pass-two")["status"], "done")+# ---------------------------------------------------------------------------+# Graph and watch (the fused machine view + the bounded wait)+# ---------------------------------------------------------------------------+++class FactoryGraphWatchTest(_ExecutorTestCase):+ """The graph snapshot (structure fused with live state), the bounded+ watch, and the host bridge's out-of-band activity handler. The shared+ executor setUp isolates the agent dir and writes the enabled setting,+ so every graph/watch/activity test runs through the live opt-in gate."""++ def setUp(self) -> None:+ super().setUp()+ self.harness.create_subagent("Researcher", "Collect the findings.", id="researcher")+ self.harness.create_factory("Factory", "Factory content", id="sw", machine=valid_machine())++ # -- helpers -------------------------------------------------------------++ async def settle(self, run_result: dict[str, Any], *, max_polls: int = 50_000) -> dict[str, Any]:+ run_id = run_result["run_id"]+ for _ in range(max_polls):+ run = self.executor._runs[run_id]+ if run.state != "running":+ return await rlm_module.rlm.factory.status(run_id)+ await yield_loop_turn()+ self.fail(f"run {run_id} never left the running state")++ # -- graph: structure fusion ---------------------------------------------++ @async_test+ async def test_graph_fuses_structure_and_live_state(self) -> None:+ result = await self.start()+ run_id = result["run_id"]+ self.clock.advance(12.0)+ graph = await rlm_module.rlm.factory.graph(run_id)+ # identity + live run state+ self.assertEqual(graph["run_id"], run_id)+ self.assertEqual(graph["spec_id"], "sw")+ self.assertEqual(graph["state"], "running")+ self.assertEqual(graph["elapsed_ms"], 12_000)+ self.assertEqual(graph["budget"], {"limit_ms": 600_000, "consumed_ms": 12_000})+ # the static structure: states, transitions, order, run block+ machine = graph["machine"]+ self.assertEqual(machine["order"], ["collect", "reviewing", "fixing"])+ collect = next(s for s in machine["states"] if s["id"] == "collect")+ self.assertTrue(collect["entry"])+ self.assertEqual(collect["lifecycle"], "task")+ self.assertEqual(machine["run"]["max_parallel"], 4)+ self.assertEqual(machine["run"]["failure_policy"], "continue")+ self.assertEqual(machine["run"]["budget_ms"], 600_000)+ # the machine block is the validated configuration: the declared+ # run limits ride it (the fixture declares none, so the canonical+ # default surfaces).+ self.assertEqual(machine["run"]["max_transitions"], 40)+ self.assertEqual(machine["run"]["max_children"], RUN_MAX_CHILDREN_DEFAULT)+ guarded = next(+ t for t in machine["transitions"] if t["to"] == "fixing"+ )+ self.assertEqual(guarded["from"], "reviewing")+ self.assertEqual(guarded["when"]["output"], "verdict")+ # the live overlay rides the status() node shape+ self.assertEqual([n["id"] for n in graph["nodes"]], ["collect", "reviewing", "fixing"])+ self.assertIn("collect", graph["active_nodes"])+ self.assertEqual(graph["usage"]["spawns"], len(result["started"]))+ self.assertTrue(graph["events"], "the ledger tail rides the snapshot")++ @async_test+ async def test_graph_machine_carries_the_declared_run_limits(self) -> None:+ # Macroscope review finding: the machine block omitted the+ # canonical `run.max_children` — the total-admission limit that+ # governs execution — so a consumer could not reconstruct the+ # validated configuration from the graph. The declared value+ # rides beside max_parallel/max_transitions.+ self.store_machine(+ {+ "run": {"max_children": 2},+ "states": [+ {"id": "a", "entry": True, "subagent": "worker"},+ {"id": "b", "subagent": "worker"},+ ],+ "transitions": [{"from": "a", "to": "b"}],+ },+ spec_id="limits",+ )+ result = await self.start("limits")+ graph = await rlm_module.rlm.factory.graph(result["run_id"])+ self.assertEqual(graph["machine"]["run"]["max_children"], 2)+ self.assertEqual(+ graph["machine"]["run"]["max_parallel"], RUN_MAX_PARALLEL_DEFAULT+ )++ @async_test+ async def test_graph_nodes_carry_per_stage_agent_counts(self) -> None:+ # The factory page reads as a page of machine diagrams with+ # PER-STAGE AGENT COUNTS (how many agents run at each stage and+ # how many queue behind them), so the graph reply's node rows+ # carry the stage occupancy at the seam: ``running`` (admitted+ # children in flight) and ``queued`` (prepared instances+ # waiting for a parallel slot). Both keys are single words, so+ # the activity lane's camelCase conversion carries them+ # unchanged, and ``status()`` shares the same node shape.+ self.host.outcomes["collect"] = {"status": "running"}+ result = await self.start()+ run_id = result["run_id"]+ graph = await rlm_module.rlm.factory.graph(run_id)+ nodes = {node["id"]: node for node in graph["nodes"]}+ self.assertEqual(nodes["collect"]["running"], 1, "the admitted instance is in flight")+ self.assertEqual(nodes["collect"]["queued"], 0)+ self.assertEqual(nodes["reviewing"]["running"], 0)+ self.assertEqual(+ nodes["reviewing"]["queued"], 0, "the state waits on its input; nothing is prepared"+ )+ # The wire lane carries the same counts under the same keys.+ listed = await factory_module.default_factory_executor().activity({"action": "graph"})+ wire_nodes = {node["id"]: node for node in listed["runs"][0]["nodes"]}+ self.assertEqual(wire_nodes["collect"]["running"], 1, "the count rides the wire")+ self.assertEqual(wire_nodes["collect"]["queued"], 0)+ # A saturated run leaves prepared instances queued: two entry+ # states under a one-slot cap admit one and queue the other.+ self.harness.create_factory(+ "Saturated",+ "Two entry states under a one-slot cap.",+ id="sat",+ machine={+ "run": {"max_parallel": 1},+ "states": [+ {"id": "a", "entry": True, "subagent": "worker"},+ {"id": "b", "entry": True, "subagent": "worker"},+ ],+ },+ )+ self.host.outcomes["a"] = {"status": "running"}+ self.host.outcomes["b"] = {"status": "running"}+ sat = await rlm_module.rlm.factory.run("sat")+ sat_id = sat["run_id"]+ graph = await rlm_module.rlm.factory.graph(sat_id)+ nodes = {node["id"]: node for node in graph["nodes"]}+ self.assertEqual(nodes["a"]["running"], 1, "the single slot runs a's instance")+ self.assertEqual(nodes["a"]["queued"], 0)+ self.assertEqual(nodes["b"]["running"], 0)+ self.assertEqual(nodes["b"]["queued"], 1, "b's prepared instance waits for the slot")+ # Stopping the run drains every stage: no agent stays at a node.+ await rlm_module.rlm.factory.stop(sat_id)+ graph = await rlm_module.rlm.factory.graph(sat_id)+ nodes = {node["id"]: node for node in graph["nodes"]}+ for node in nodes.values():+ self.assertEqual(node["running"], 0, "a stopped run has no agent at any stage")+ self.assertEqual(node["queued"], 0)++ @async_test+ async def test_graph_transition_from_lists_are_snapshot_owned(self) -> None:+ # Regression (bot review): ``graph()`` exposed each transition's+ # ``from`` list by reference, so a consumer mutating the snapshot's+ # join row corrupted the active run's machine — an appended source+ # made the join wait for a state that never settles, so the+ # transition never fired. The snapshot owns its ``from``, exactly+ # like the already-copied ``when`` guard.+ self.harness.create_factory(+ "Join",+ "Join content",+ id="join",+ machine={+ "run": {"failure_policy": "continue"},+ "states": [+ {"id": "a", "entry": True, "subagent": "worker"},+ {"id": "b", "entry": True, "subagent": "worker"},+ {"id": "c", "subagent": "worker"},+ ],+ "transitions": [{"from": ["a", "b"], "to": "c"}],+ },+ )+ result = await self.start("join")+ run_id = result["run_id"]+ graph = await rlm_module.rlm.factory.graph(run_id)+ join = next(t for t in graph["machine"]["transitions"] if t["to"] == "c")+ self.assertEqual(join["from"], ["a", "b"])+ # A consumer corrupting the snapshot never touches the run.+ join["from"].append("ghost")+ self.assertEqual(+ self.executor._runs[run_id].machine["transitions"][0]["from"], ["a", "b"]+ )+ graph_again = await rlm_module.rlm.factory.graph(run_id)+ join_again = next(+ t for t in graph_again["machine"]["transitions"] if t["to"] == "c"+ )+ self.assertEqual(join_again["from"], ["a", "b"])++ @async_test+ async def test_graph_is_status_data_plus_the_static_graph(self) -> None:+ result = await self.start()+ run_id = result["run_id"]+ status = await self.settle(result)+ graph = await rlm_module.rlm.factory.graph(run_id)+ # the fused snapshot reports exactly the status() node reports+ self.assertEqual(graph["nodes"], status["nodes"])+ self.assertEqual(graph["usage"], status["usage"])+ self.assertEqual(graph["state"], status["state"])+ # ...but graph is a pure read: status() marks recorded events+ # delivered, and a graph call must not consume that marking.+ self.executor._runs[run_id].events[0]["stage"] = "recorded"+ graph_again = await rlm_module.rlm.factory.graph(run_id)+ self.assertEqual(graph_again["events"][0]["stage"], "recorded")+ marked = await rlm_module.rlm.factory.status(run_id)+ self.assertEqual(marked["events"][0]["stage"], "delivered")++ @async_test+ async def test_graph_lists_every_live_run_and_marks_active_nodes(self) -> None:+ first = await self.start()+ await self.settle(first)+ second = await self.start()+ listing = await rlm_module.rlm.factory.graph()+ self.assertEqual([run["run_id"] for run in listing["runs"]], [first["run_id"], second["run_id"]])+ # the settled run has no active nodes; the fresh one has its entry+ # state in flight+ self.assertEqual(listing["runs"][0]["active_nodes"], [])+ self.assertIn("collect", listing["runs"][1]["active_nodes"])++ @async_test+ async def test_graph_keeps_a_failed_foreach_entrys_stage_active_while_siblings_run(self) -> None:+ # Macroscope review finding: active_nodes keyed on the aggregate+ # entry status, so a foreach entry that failed permanently+ # (failure_policy continue) while sibling instances still run+ # dropped the stage from the overlay -- the snapshot claimed no+ # node was active while its own node report carried the in-flight+ # sibling (the occupancy keys) and the run stayed live to collect+ # it. Activity rides the INSTANCE layer too, exactly like the+ # occupancy counts, so a stage with a terminal entry but live+ # children stays active.+ self.host.outcomes["src"] = {"status": "done", "answer": '{"items": ["a", "b", "c", "d", "e"]}'}+ self.store_machine(+ {+ "run": {"failure_policy": "continue", "max_parallel": 2},+ "states": [+ {+ "id": "src",+ "entry": True,+ "subagent": "worker",+ "outputs": [{"name": "items", "type": "json"}],+ },+ {+ "id": "fan",+ "subagent": "worker",+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],+ "foreach": {"over": "items", "max": 5},+ },+ ],+ "transitions": [{"from": "src", "to": "fan"}],+ },+ spec_id="fan",+ )+ result = await self.start("fan")+ run = self.executor._runs[result["run_id"]]+ # src is child-1; the two parallel slots admit fan's child-2 (fails+ # permanently) and child-3 (stays running), leaving three queued+ # behind the cap.+ self.host.child_outcomes["child-2"] = {"status": "error", "error": "boom"}+ self.host.child_outcomes["child-3"] = {"status": "running"}+ for _ in range(50_000):+ if any(entry.status == "error" for entry in run.states["fan"].entries):+ break+ await yield_loop_turn()+ else:+ self.fail("the fan entry never failed")+ graph = await rlm_module.rlm.factory.graph(result["run_id"])+ fan = next(node for node in graph["nodes"] if node["id"] == "fan")+ self.assertEqual([entry["status"] for entry in fan["entries"]], ["error"])+ self.assertEqual(fan["running"], 1, "the sibling instance is still in flight")+ self.assertEqual(fan["queued"], 0)+ self.assertEqual(graph["state"], "running")+ self.assertEqual(graph["usage"]["running"], 1)+ # the stage with only a terminal entry but live children is active+ self.assertIn("fan", graph["active_nodes"])++ @async_test+ async def test_graph_of_a_stored_spec_returns_the_static_structure(self) -> None:+ graph = await rlm_module.rlm.factory.graph("sw")+ self.assertIsNone(graph["run_id"])+ self.assertEqual(graph["spec_id"], "sw")+ self.assertIsNone(graph["state"])+ self.assertEqual(graph["machine"]["order"], ["collect", "reviewing", "fixing"])+ self.assertEqual(graph["nodes"], [])+ self.assertEqual(graph["active_nodes"], [])+ self.assertEqual(graph["budget"], {"limit_ms": 600_000, "consumed_ms": 0})+ # a dag spec compiles to machine form for the graph too+ self.harness.create_factory("Dag factory", "content", id="dag", dag=valid_dag())+ dag_graph = await rlm_module.rlm.factory.graph("dag")+ self.assertEqual(dag_graph["machine"]["order"], ["collect", "fan-out", "review"])+ # unknown refs fail loudly; a corrupt spec names itself+ with self.assertRaisesRegex(ValueError, "unknown factory run or spec 'missing'"):+ await rlm_module.rlm.factory.graph("missing")+ self.harness.create_factory("Broken", "content", id="broken", dag={"nodes": [node("a")]})+ self.corrupt_spec("broken", {"nodes": []})+ with self.assertRaisesRegex(ValueError, "does not validate"):+ await rlm_module.rlm.factory.graph("broken")++ @async_test+ async def test_compact_snapshot_sheds_answers_and_carries_the_short_tail(self) -> None:+ result = await self.start()+ run_id = result["run_id"]+ await self.settle(result)+ run = self.executor._runs[run_id]+ self.assertGreaterEqual(len(run.events), 3)+ full = self.executor.graph(run_id)+ compact = self.executor.graph(run_id, compact=True)+ self.assertLessEqual(len(compact["events"]), factory_module.GRAPH_EVENTS_TAIL)+ self.assertNotIn("answer_captured", [e["kind"] for e in compact["events"]])+ self.assertIn(+ "answer_captured", [e["kind"] for e in full["events"]]+ )+ self.assertFalse(+ any("answer_preview" in node for node in compact["nodes"])+ )+ self.assertTrue(+ any("answer_preview" in node for node in full["nodes"])+ )++ @async_test+ async def test_last_fired_marks_the_recently_fired_edges(self) -> None:+ result = await self.start()+ run_id = result["run_id"]+ await self.settle(result)+ graph = await rlm_module.rlm.factory.graph(run_id)+ fired = {(tuple(e["from"]) if isinstance(e["from"], list) else e["from"], e["to"]) for e in graph["last_fired"]}+ self.assertIn(("collect", "reviewing"), fired)+ # the window bounds the report at LAST_FIRED_WINDOW edges+ self.assertLessEqual(len(graph["last_fired"]), factory_module.LAST_FIRED_WINDOW)++ # -- watch: bounded change detection --------------------------------------++ @async_test+ async def test_watch_returns_the_snapshot_when_nothing_changes(self) -> None:+ result = await self.start()+ run_id = result["run_id"]+ await self.settle(result) # the run settles while no watcher waits+ watched = await rlm_module.rlm.factory.watch(run_id, 0)+ # the baseline is captured at watch entry, so an unchanged run+ # reports changed=False and still returns the full snapshot+ self.assertFalse(watched["changed"])+ self.assertEqual(watched["run_id"], run_id)+ self.assertIn("machine", watched)+ self.assertIn("nodes", watched)+ graph = await rlm_module.rlm.factory.graph(run_id)+ del watched["changed"]+ self.assertEqual(watched, graph)+++ @async_test+ async def test_watch_blocks_until_the_run_changes(self) -> None:+ # A sleep that really waits (10ms slices, no clock advance): the+ # watch's re-arm loop yields to the loop, so the stop lands mid-wait+ # and the waiter resolves before the deadline could matter.+ self.executor._sleep_fn = turn_sleep+ result = await self.start_held_run()+ run_id = result["run_id"]+ # a real change: stop the running child while the watch waits.+ async def stopper() -> None:+ for _ in range(5):+ await yield_loop_turn()+ await rlm_module.rlm.factory.stop(run_id)++ stop_task = asyncio.ensure_future(stopper())+ watched = await rlm_module.rlm.factory.watch(run_id, 30.0)+ await stop_task+ self.assertTrue(watched["changed"])+ self.assertEqual(watched["state"], "stopped")++ @async_test+ async def test_watch_times_out_without_a_change(self) -> None:+ result = await self.start_held_run()+ run_id = result["run_id"]+ # The injected sleep advances the injected clock, so the bounded+ # timeout expires on the test lane without a wall-clock wait.+ watched = await rlm_module.rlm.factory.watch(run_id, 0.05)+ self.assertFalse(watched["changed"])+ self.assertEqual(watched["run_id"], run_id)+ self.assertEqual(watched["state"], "running")++ async def start_held_run(self) -> dict[str, Any]:+ """A run whose single child never settles (the FakeHost keeps it+ `running`), so the machine stays in flight until the test acts. The+ state id carries no dash: the fake host routes outcomes by the+ dash-split spawn name."""+ self.harness.create_subagent("Sleeper", "Never settles.", id="sleeper")+ self.harness.create_factory(+ "Held",+ "content",+ id="held",+ machine={"states": [{"id": "heldstate", "entry": True, "subagent": "sleeper"}]},+ )+ self.host.outcomes["heldstate"] = {"status": "running"}+ return await rlm_module.rlm.factory.run("held")++ @async_test+ async def test_watch_rejects_unknown_runs_and_bad_timeouts(self) -> None:+ with self.assertRaisesRegex(ValueError, "unknown factory run 'nope'"):+ await rlm_module.rlm.factory.watch("nope", 1.0)+ result = await self.start()+ with self.assertRaisesRegex(ValueError, "timeout must be a non-negative number"):+ await rlm_module.rlm.factory.watch(result["run_id"], -1)+ with self.assertRaisesRegex(ValueError, "timeout must be a non-negative number"):+ await rlm_module.rlm.factory.watch(result["run_id"], "soon")+ # NaN passes every comparison (the arithmetic checks never trip),+ # so it must be rejected by identity: a NaN deadline would reach+ # asyncio.sleep, which raises instead of returning the bounded+ # snapshot.+ with self.assertRaisesRegex(ValueError, "timeout must be a non-negative number"):+ await rlm_module.rlm.factory.watch(result["run_id"], float("nan"))++ # -- the host bridge's activity handler ------------------------------------++ @async_test+ async def test_activity_routes_every_action(self) -> None:+ result = await self.start()+ run_id = result["run_id"]+ # graph (all runs) / graph (one run) / graph (spec) — the reply+ # carries the wire's camelCase keys (_wire_payload's contract)+ listed = await factory_module.default_factory_executor().activity(+ {"action": "graph"}+ )+ self.assertEqual([run["runId"] for run in listed["runs"]], [run_id])+ one = await factory_module.default_factory_executor().activity(+ {"action": "graph", "runId": run_id}+ )+ self.assertEqual(one["runId"], run_id)+ spec_graph = await factory_module.default_factory_executor().activity(+ {"action": "graph", "specId": "sw"}+ )+ self.assertEqual(spec_graph["specId"], "sw")+ # status+ status = await factory_module.default_factory_executor().activity(+ {"action": "status", "runId": run_id}+ )+ self.assertEqual(status["runId"], run_id)+ await self.settle(result)+ # a fresh run through the activity lane, then stop it and prove+ # resume's paused-only contract from the same lane+ second = await factory_module.default_factory_executor().activity(+ {"action": "run", "specId": "sw"}+ )+ self.assertIn("runId", second)+ stopped = await factory_module.default_factory_executor().activity(+ {"action": "stop", "runId": second["runId"]}+ )+ self.assertEqual(stopped["state"], "stopped")+ with self.assertRaisesRegex(ValueError, "not paused"):+ await factory_module.default_factory_executor().activity(+ {"action": "resume", "runId": second["runId"]}+ )+ # watch through the activity lane answers with `changed` + snapshot+ watched = await factory_module.default_factory_executor().activity(+ {"action": "watch", "runId": second["runId"], "timeoutMs": 5}+ )+ self.assertIn("changed", watched)+ self.assertEqual(watched["runId"], second["runId"])++ @async_test+ async def test_activity_reply_carries_the_wire_keys(self) -> None:+ # Regression (live probe): the activity lane's replies once+ # carried the conversation API's snake_case keys while the TUI+ # parsed camelCase wire keys, so every run row dropped at the+ # identity guard and the factory view stayed empty regardless of+ # live runs. The factory_activity protocol is camelCase end to+ # end (the request frame's runId/specId/timeoutMs): the reply's+ # result payload converts every nested key to the wire spelling,+ # while the in-kernel conversation API stays snake_case.+ result = await self.start()+ run_id = result["run_id"]+ self.clock.advance(3.0)+ listed = await factory_module.default_factory_executor().activity(+ {"action": "graph"}+ )+ row = listed["runs"][0]+ self.assertEqual(row["runId"], run_id, "the wire row key is runId")+ self.assertEqual(row["specId"], "sw")+ self.assertEqual(row["state"], "running")+ self.assertEqual(row["elapsedMs"], 3_000, "elapsed_ms -> elapsedMs")+ self.assertEqual(row["budget"]["limitMs"], 600_000, "limit_ms -> limitMs")+ self.assertIn("toolUses", row["usage"], "tool_uses -> toolUses")+ self.assertIn("maxParallel", row["usage"], "max_parallel -> maxParallel")+ self.assertIn(+ "transitionsFired", row["usage"], "transitions_fired -> transitionsFired"+ )+ node = row["nodes"][0]+ self.assertIn("entriesUsed", node, "entries_used -> entriesUsed")+ self.assertIn("maxEntries", node, "max_entries -> maxEntries")+ self.assertEqual(+ row["machine"]["run"]["maxParallel"],+ 4,+ "the machine run block rides the wire too",+ )+ self.assertNotIn("run_id", row, "no snake_case keys ride the wire")+ self.assertNotIn("elapsed_ms", row)+ self.assertNotIn("tool_uses", row["usage"])+ # watch and status answers ride the same wire conversion.+ watched = await factory_module.default_factory_executor().activity(+ {"action": "watch", "runId": run_id, "timeoutMs": 0}+ )+ self.assertIn("changed", watched)+ self.assertEqual(watched["runId"], run_id)+ self.assertNotIn("run_id", watched)+ status = await factory_module.default_factory_executor().activity(+ {"action": "status", "runId": run_id}+ )+ self.assertEqual(status["runId"], run_id)+ self.assertNotIn("run_id", status)+ # The conversation API keeps its snake_case keys: only the wire+ # lane converts.+ graph = await rlm_module.rlm.factory.graph(run_id)+ self.assertEqual(graph["run_id"], run_id)+ self.assertEqual(graph["elapsed_ms"], 3_000)+ self.assertIn("tool_uses", graph["usage"])+ self.assertNotIn("runId", graph)++ @async_test+ async def test_run_activity_caps_the_error_reply(self) -> None:+ # The error lane's reply rides the same wire cap as the success+ # lane: a validation error joining thousands of rows (a stored spec+ # corrupted the way a hand-edited store would be) must never+ # exceed the transport bound — the cap's fallback names the wire+ # cap (the mutation check: an uncapped error frame would carry+ # the multi-hundred-kilobyte reason raw).+ self.harness.create_factory(+ "Good", "content", id="big-spec", machine=valid_machine()+ )+ entry = self.harness.get("factory", "big-spec")+ entry.arguments["machine"] = {+ "run": {"failure_policy": "continue"},+ "states": [{"id": "a", "entry": True, "subagent": "worker"}],+ "transitions": [{"from": "a", "to": f"missing{i}"} for i in range(6_000)],+ }+ sent: list[dict[str, Any]] = []+ patcher = patch("rlm.repl._send", sent.append)+ patcher.start()+ self.addCleanup(patcher.stop)+ await factory_module._run_activity(+ {"id": "big", "action": "run", "specId": "big-spec"}+ )+ self.assertEqual(len(sent), 1)+ frame = sent[0]+ self.assertEqual(frame["status"], "error")+ self.assertLess(+ len(json.dumps(frame)),+ factory_module.FACTORY_FRAME_CAP,+ "the error reply stays under the wire cap",+ )+ self.assertIn("wire cap", frame["reason"])++ @async_test+ async def test_activity_reply_carries_guards_verbatim(self) -> None:+ # Regression (bot review): the wire conversion re-keyed EVERY dict,+ # including a guard's comparison value — `when: {"value":+ # {"snake_key": 1}}` came back as `{"snakeKey": 1}`, displaying a+ # condition that no longer matches the executor's declared one. A+ # guard dict (``output`` + ``op``) rides the wire verbatim.+ self.harness.create_factory(+ "Guarded",+ "Guarded content",+ id="guarded",+ machine={+ "run": {"failure_policy": "continue"},+ "states": [+ {+ "id": "a",+ "entry": True,+ "subagent": "worker",+ "outputs": [{"name": "verdict", "type": "json"}],+ },+ {"id": "b", "subagent": "worker"},+ ],+ "transitions": [+ {+ "from": "a",+ "to": "b",+ "when": {+ "output": "verdict",+ "op": "contains",+ "value": [{"snake_key": 1}],+ },+ },+ ],+ },+ )+ result = await self.start("guarded")+ reply = await factory_module.default_factory_executor().activity(+ {"action": "graph", "runId": result["run_id"]}+ )+ transition = reply["machine"]["transitions"][0]+ self.assertEqual(+ transition["when"],+ {"output": "verdict", "op": "contains", "value": [{"snake_key": 1}]},+ "the guard's comparison value rides the wire verbatim",+ )++ @async_test+ async def test_unscoped_graph_bounds_the_terminal_history(self) -> None:+ # Regression (bot review): the all-runs reply once constructed a+ # snapshot for EVERY run the registry retained — completed runs+ # accumulate forever, so one polling reply built an unbounded+ # payload before the wire cap could trim it. Every live run+ # reports; the terminal history keeps the newest+ # GRAPH_RUNS_WINDOW runs (by-ref snapshots stay available for+ # all of them).+ self.harness.create_factory(+ "Solo",+ "Solo content",+ id="solo",+ machine={+ "run": {"failure_policy": "continue"},+ "states": [{"id": "a", "entry": True, "subagent": "worker"}],+ "transitions": [],+ },+ )+ started = [await self.start("solo") for _ in range(25)]+ for result in started:+ await self.settle(result)+ listed = await factory_module.default_factory_executor().activity({"action": "graph"})+ ids = [run["runId"] for run in listed["runs"]]+ self.assertEqual(len(ids), factory_module.GRAPH_RUNS_WINDOW)+ newest = {run["run_id"] for run in started[-factory_module.GRAPH_RUNS_WINDOW:]}+ self.assertEqual(set(ids), newest, "the newest terminal runs report")+ # A live run reports regardless of the terminal window's bound.+ self.host.outcomes["a"] = {"status": "running"}+ live = await self.start("solo")+ listed = await factory_module.default_factory_executor().activity({"action": "graph"})+ ids = [run["runId"] for run in listed["runs"]]+ self.assertIn(live["run_id"], ids, "every live run reports")+ self.assertEqual(len(ids), factory_module.GRAPH_RUNS_WINDOW + 1)++ @async_test+ async def test_a_done_run_with_children_in_flight_reports_live(self) -> None:+ # Regression (bot review): liveness in the unscoped graph was+ # state-shaped alone, so a ``done`` run whose resident child is+ # still in flight (residents never block completion — the+ # finished milestone tells the operator to ``rlm.factory.stop()``+ # them) dropped out of the reply once it left the terminal-history+ # window: the page lost the run and its stop control while the+ # child kept running. A run with a child in flight is live: it+ # reports regardless of the window, and the window holds only+ # runs with no child in flight.+ self.harness.create_factory(+ "Resident",+ "One resident entry state.",+ id="resident",+ machine={+ "states": [+ {"id": "watcher", "entry": True, "subagent": "worker", "lifecycle": "resident"},+ ],+ "transitions": [],+ },+ )+ self.host.outcomes["watcher"] = {"status": "running"}+ resident = await self.start("resident")+ resident_id = resident["run_id"]+ status = await self.settle(resident)+ self.assertEqual(status["state"], "done", "the resident never blocks completion")+ nodes = {node["id"]: node for node in status["nodes"]}+ self.assertEqual(nodes["watcher"]["running"], 1, "the resident child is still in flight")+ # GRAPH_RUNS_WINDOW newer drained runs push the done run outside+ # the terminal-history window; the in-flight child keeps it live.+ self.harness.create_factory(+ "Solo",+ "Solo content",+ id="solo",+ machine={+ "run": {"failure_policy": "continue"},+ "states": [{"id": "a", "entry": True, "subagent": "worker"}],+ "transitions": [],+ },+ )+ for _ in range(factory_module.GRAPH_RUNS_WINDOW):+ await self.settle(await self.start("solo"))+ listed = await factory_module.default_factory_executor().activity({"action": "graph"})+ ids = [run["runId"] for run in listed["runs"]]+ self.assertIn(resident_id, ids, "a run with a child in flight reports regardless of the window")+ self.assertEqual(len(ids), factory_module.GRAPH_RUNS_WINDOW + 1)+ resident_row = next(run for run in listed["runs"] if run["runId"] == resident_id)+ self.assertEqual(resident_row["state"], "done")+ wire_nodes = {node["id"]: node for node in resident_row["nodes"]}+ self.assertEqual(wire_nodes["watcher"]["running"], 1, "the in-flight count rides the wire")+ # Stopping drains the run: no child in flight, so the genuinely+ # terminal run (older than the window's runs) leaves the reply.+ await rlm_module.rlm.factory.stop(resident_id)+ listed = await factory_module.default_factory_executor().activity({"action": "graph"})+ ids = [run["runId"] for run in listed["runs"]]+ self.assertNotIn(resident_id, ids, "a drained run outside the window leaves the reply")+ self.assertEqual(len(ids), factory_module.GRAPH_RUNS_WINDOW)++ @async_test+ async def test_activity_validates_its_request_shape(self) -> None:+ for bad in (+ {"action": "bogus"},+ {"action": "status"},+ {"action": "watch", "runId": 5},+ {"action": "watch"},+ {"action": "graph", "specId": 5},+ {"action": "watch", "runId": "x", "timeoutMs": -1},+ {"action": "watch", "runId": "x", "timeoutMs": "soon"},+ {"action": "watch", "runId": "x", "timeoutMs": 10**9},+ {"action": "run"},+ ):+ with self.assertRaises(ValueError, msg=repr(bad)):+ await factory_module.default_factory_executor().activity(bad)++ def corrupt_spec(self, spec_id: str, spec: Any) -> None:+ entry = self.harness.get("factory", spec_id)+ entry.arguments = {"dag": spec}+++# ---------------------------------------------------------------------------+# Out-of-band frame plumbing+# ---------------------------------------------------------------------------+++class FactoryFrameCapTest(unittest.TestCase):+ """The reply frame's wire cap: event tails trim from the oldest end+ first (one reply's tail, or each run row's), the all-runs drop takes+ the oldest DROPPABLE row — never a live one — and a frame that cannot+ fit fails loudly."""++ def test_a_non_finite_frame_fails_loudly(self) -> None:+ # The belt: validation blocks non-finite guard values at the+ # machine's source; a frame that ever carries one anyway fails+ # loudly instead of emitting the non-JSON NaN/Infinity tokens+ # (every strict consumer of the reply would choke on them).+ frame = {+ "event": "done",+ "id": "r",+ "status": "ok",+ "result": {+ "machine": {+ "transitions": [{"when": {"op": "eq", "value": float("nan")}}]+ }+ },+ }+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "error")+ self.assertIn("non-finite", frame["reason"])+ clean = {"event": "done", "id": "r", "status": "ok", "result": {"runs": []}}+ factory_module._cap_factory_frame(clean)+ self.assertEqual(clean["status"], "ok")++ def test_an_oversized_error_frame_fails_loudly(self) -> None:+ # The error lane rides the same wire cap: a multi-megabyte reason+ # (an unknown id carrying a huge value) never exceeds the+ # transport bound; the cap's fallback names the wire cap, and a+ # small reason passes through untouched.+ huge_reason = "unknown factory run '" + "x" * 300_000 + "'"+ frame = {"event": "done", "id": "r", "status": "error", "reason": huge_reason}+ factory_module._cap_factory_frame(frame)+ self.assertLess(len(frame["reason"]), 10_000)+ self.assertIn("wire cap", frame["reason"])+ small = {"event": "done", "id": "r", "status": "error", "reason": "boom"}+ factory_module._cap_factory_frame(small)+ self.assertEqual(small["reason"], "boom")++ def test_an_oversized_reply_is_trimmed_then_failed(self) -> None:+ events = [+ {"kind": "settled", "seq": i, "stage": "recorded", "big": "y" * 12_000}+ for i in range(50)+ ]+ frame = {"event": "done", "id": "r", "status": "ok", "result": {"events": list(events)}}+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "ok")+ self.assertLess(len(frame["result"]["events"]), 50)+ self.assertEqual(frame["result"]["events"][-1]["seq"], 49)+ # a single run that cannot fit under the cap keeps exactly one+ # event before failing loudly (never a silent graph truncation)+ single = {"events": [{"big": "y" * 300_000}]}+ frame = {"event": "done", "id": "r", "status": "ok", "result": dict(single)}+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "error")+ self.assertIn("wire cap", frame["reason"])+ # a single-run graph that cannot fit under the cap fails loudly+ huge = {"result": {"machine": {"states": [{"id": "x" * 200}] * 2000}}}+ frame = {"event": "done", "id": "r", "status": "ok", **huge}+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "error")+ self.assertIn("wire cap", frame["reason"])+ # the all-runs reply sheds its own ladder: every row's event tail+ # floors from the oldest end BEFORE any whole row drops (the+ # by-ref trim rule applied per row), so this frame keeps all 40+ # rows with their newest event instead of losing the oldest runs+ run = {"run_id": "r1", "events": [{"big": "y" * 4000}] * 20, "machine": {}}+ frame = {+ "event": "done",+ "id": "r",+ "status": "ok",+ "result": {"runs": [dict(run, run_id=f"r{i}") for i in range(40)]},+ }+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "ok")+ rows = frame["result"]["runs"]+ self.assertEqual(len(rows), 40)+ self.assertEqual(rows[-1]["run_id"], "r39")+ self.assertTrue(all(len(row["events"]) == 1 for row in rows))++ def test_the_cap_drops_terminal_rows_before_live_ones(self) -> None:+ # The live-exactness contract under the wire cap: the oldest row+ # is LIVE (a resident run with children in flight, started before+ # the terminal history), and the bulk is structural (the machine+ # payload, not the event tail), so the tail lever cannot save the+ # frame — the drop must take terminal rows oldest-first and keep+ # the live row, never the blind oldest-first drop that would+ # strand the live run's dock count, panel, and off-guard read.+ live = {+ "runId": "r-live",+ "state": "running",+ "usage": {"running": 1},+ "events": [{"kind": "settled"}],+ "machine": {},+ }+ terminal = {+ "runId": "t1",+ "state": "done",+ "usage": {"running": 0},+ "events": [{"kind": "settled"}],+ "machine": {"states": [{"id": "s" * 2000}] * 8},+ }+ frame = {+ "event": "done",+ "id": "r",+ "status": "ok",+ "result": {+ "runs": [live] + [+ dict(terminal, runId=f"t{i}") for i in range(1, 31)+ ]+ },+ }+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "ok")+ rows = frame["result"]["runs"]+ self.assertEqual(rows[0]["runId"], "r-live", "the live row survived the cap")+ self.assertEqual(rows[-1]["runId"], "t30", "the newest terminal row survived")+ self.assertLess(len(rows), 31, "terminal rows dropped oldest-first to fit")++ def test_a_live_row_never_silently_drops(self) -> None:+ # The endgame: only live rows remain and the frame still cannot+ # fit — the cap fails loudly instead of silently dropping a live+ # row (a trimmed success would undercount the dock and lie to the+ # `/factory off` guard; the honest answer is the loud failure).+ live_big = {+ "runId": "r-big",+ "state": "running",+ "usage": {"running": 2},+ "events": [{"big": "y" * 300_000}],+ "machine": {},+ }+ live_small = {+ "runId": "r-small",+ "state": "paused",+ "usage": {"running": 1},+ "events": [{"kind": "settled"}],+ "machine": {},+ }+ frame = {+ "event": "done",+ "id": "r",+ "status": "ok",+ "result": {"runs": [live_big, live_small]},+ }+ factory_module._cap_factory_frame(frame)+ self.assertEqual(frame["status"], "error")+ self.assertIn("wire cap", frame["reason"])+ self.assertNotIn("result", frame)+++if __name__ == "__main__":unittest.main()diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.pyindex 1657cd0d36..117fccc973 100644--- a/prime-agent-runtime/test/test_repl.py+++ b/prime-agent-runtime/test/test_repl.py@@ -128,6 +128,21 @@ class ReplTest(unittest.TestCase):self.addCleanup(self.repl.close)self.ready_event, self.ready_ms = self.repl.ready()+ def enabled_factory_repl(self) -> ReplProcess:+ """One repl whose kernel runs with the factory opt-in gate enabled:+ the agent dir points at a temp dir whose settings.json carries the+ enabled setting in the real shape (the same file `/factory on`+ writes and the daemon's lane advertisement reads), so the+ out-of-band lane answers through the live gate instead of reading+ whatever the host machine's settings happen to say."""+ temp = tempfile.TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ with open(os.path.join(temp.name, "settings.json"), "w", encoding="utf-8") as handle:+ json.dump({"factory": {"enabled": True}}, handle)+ repl = ReplProcess(env={"PRIME_AGENT_CODING_AGENT_DIR": temp.name})+ self.addCleanup(repl.close)+ return repl+def test_bash_activity_is_available_while_cell_is_running(self):self.repl.send({"type": "execute", "id": "cell", "code": "from rlm import bash\nimport asyncio\nh = bash('echo ready; sleep 20'); await asyncio.sleep(20)"})# Wait for the activity start display before requesting list.@@ -167,6 +182,39 @@ class ReplTest(unittest.TestCase):self.assertEqual(event["ename"], "ProtocolError")self.assertIn("256", event["evalue"])+ def test_factory_activity_is_available_while_cell_is_running(self):+ repl = self.enabled_factory_repl()+ repl.send({"type": "execute", "id": "cell", "code": "import asyncio\nawait asyncio.sleep(20)"})+ # The factory graph answers out of band while the cell runs: no+ # live runs exist yet, so the graph action lists the empty registry.+ repl.send({"type": "factory_activity", "id": "g", "action": "graph"})+ listed = repl.until_done("g")[-1]+ self.assertEqual(listed["status"], "ok")+ self.assertEqual(listed["result"]["runs"], [])+ # unknown-run watch answers with the error reply (not a hang)+ repl.send({"type": "factory_activity", "id": "w", "action": "watch", "runId": "nope", "timeoutMs": 100})+ missing = repl.until_done("w")[-1]+ self.assertEqual(missing["status"], "error")+ self.assertIn("unknown factory run", missing["reason"])+ repl.send({"type": "interrupt", "id": "cell"})+ repl.until_done("cell")++ def test_factory_activity_rejects_malformed_frames(self):+ for frame, fragment in (+ ({"type": "factory_activity", "id": "b", "action": "bogus"}, "unknown factory activity action"),+ ({"type": "factory_activity", "id": "x" * 300, "action": "graph"}, "256"),+ (+ {"type": "factory_activity", "id": "t", "action": "watch", "runId": "r", "timeoutMs": "soon"},+ "timeoutMs",+ ),+ ({"type": "factory_activity", "id": "n", "action": "graph", "runId": 5}, "runId"),+ ):+ self.repl.send(frame)+ event = self.repl.read_event()+ self.assertEqual(event["event"], "error", frame)+ self.assertEqual(event["ename"], "ProtocolError")+ self.assertIn(fragment, event["evalue"], frame)+def test_ready_handshake_and_startup_time(self):self.assertEqual(self.ready_event["event"], "ready")self.assertEqual(self.ready_event["protocol"], 3)diff --git a/skills/factory/SKILL.md b/skills/factory/SKILL.mdnew file mode 100644index 0000000000..74bac188e4--- /dev/null+++ b/skills/factory/SKILL.md@@ -0,0 +1,57 @@+---+name: factory+description: Run state-machine workflows of spawned child agents: store a validated machine or dag spec as a continual-harness factory entry (rlm.harness.create_factory), then run, watch, stop, and resume it through rlm.factory. For the full authoring reference and API guide, call rlm.factory.help() in the kernel.+---++# Factory++The factory runs state-machine workflows of spawned child agents. A stored+factory entry — harness kind `factory`, written with+`rlm.harness.create_factory` — declares the machine: states, each backed by+a subagent spec, plus guarded transitions between them. The spec validates+at write time (machine form, or `dag` sugar that compiles to one; pass+exactly one), and an invalid spec is never stored.+`await rlm.factory.run('<spec_id>')` then spawns each state's subagent as an+ordinary child, feeds captured outputs into the successors' prompts, and+drives the run to quiescence in a background kernel task — the call+returns immediately and the run continues after the model turn ends. Use+it when a workflow needs shape: fan-out, bounded loops (review/fix until a+verdict approves), joins, or one child per list item.++**For the full authoring reference and API guide — states, ports, guards,+joins, foreach, residents, budgets and policies, and the `rlm.factory`+run/status/stop/resume/graph/watch calls with worked examples — call+`rlm.factory.help()` in the kernel.** The guide lands with the factory-core+PR; on builds without it, the module docstring in+`prime-agent-runtime/src/rlm/factory.py` is the source of truth.++## The opt-in gate++The factory ships disabled. `rlm.factory.help()` answers while it is off+(the authoring guide stays readable before opting in), but every other+`rlm.factory` call and every factory harness write refuses with one+message: `the factory is disabled; run /factory on to enable it`. The+user turns it on with `/factory on` in the client (`/factory off`+disables it again — refused while the session still has live runs, and+on a lane-advertising client while the live-run count cannot be read, so+an active factory never loses its stop path, `/factory status` reports+it), which persists the+`factory.enabled` setting in the agent dir's settings.json — the same+setting the daemon's `factory_activity` lane advertisement reads, so the+TUI's factory dock group and page surface only on a client started while+the factory is enabled. If a call refuses with that message, tell the+user to run `/factory on` and restart the client.++## Discovering machines++- The machine library: machines are `MACHINE.md` files, one directory+ per machine — the bundled seeds ship inside the runtime package (wheel+ package data, `rlm/machines/<name>/MACHINE.md`; `PRIME_AGENT_MACHINES_DIR`+ redirects that level at a team directory), and the personal library+ lives under the agent dir. `prime-agent factory list | import | export`+ manages them. The seeds are `builder`, `pr-manager`, and `review-sweep`.+- The TUI factory page: the activity dock's `⚙ N factory` group (Enter or+ click) opens one live diagram per run, newest run first. The up/down+ arrows move the selection, Enter opens the selected run's action rows+ (stop, or resume while it is paused — arrows to walk, Enter to run),+ Esc closes.