Skip to content

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

Rust

Rust port of #2397 + #2401: factory state-machine specs, validator, DAG compiler, executor (#3199)

Seth Kartene38702160795
diff --git a/crates/pa-core/src/refinement/executor.rs b/crates/pa-core/src/refinement/executor.rs
index c9bad0d432..95504dabd4 100644
--- a/crates/pa-core/src/refinement/executor.rs
+++ b/crates/pa-core/src/refinement/executor.rs
@@ -165,6 +165,7 @@ fn kind_name(kind: RefinementKind) -> &'static str {
RefinementKind::Memory => "memory",
RefinementKind::Skill => "skill",
RefinementKind::Subagent => "subagent",
+ RefinementKind::Factory => "factory",
}
}
@@ -173,6 +174,7 @@ fn kind_value(name: &str) -> RefinementKind {
"prompt" => RefinementKind::Prompt,
"memory" => RefinementKind::Memory,
"skill" => RefinementKind::Skill,
+ "factory" => RefinementKind::Factory,
_ => RefinementKind::Subagent,
}
}
@@ -287,12 +289,19 @@ fn assistant_text(reply: &AssistantMessage) -> String {
.join("\n")
}
-/// Apply a plan to the (re-read) harness state.
+/// Apply a plan to the (re-read) harness state. `factory_enabled` is the
+/// `factory.enabled` opt-in (default off), resolved by the caller
+/// immediately before this call — after the planning request — so the
+/// synchronous apply always decides on the current setting, never a
+/// pre-request snapshot: while it is off, factory create/update edits
+/// refuse with the one disabled message, the same gate the kernel-side
+/// factory writers raise.
pub fn apply_refinement_plan(
state: &mut HarnessState,
plan: RefinementPlan,
options: &RefineOptions,
baseline_state: Option<HarnessState>,
+ factory_enabled: bool,
) -> RefinementResult {
let scope = plan.rollback_scope.unwrap_or(if options.global {
HarnessScope::Global
@@ -307,6 +316,7 @@ pub fn apply_refinement_plan(
rollback_of: plan.rollback_of,
scope: Some(scope),
baseline_state,
+ factory_enabled,
},
)
}
@@ -556,6 +566,7 @@ mod tests {
rollback_of: None,
scope: Some(HarnessScope::Local),
baseline_state: None,
+ factory_enabled: false,
},
);
let rollback = plan_refinement(
diff --git a/crates/pa-core/src/refinement/mod.rs b/crates/pa-core/src/refinement/mod.rs
index c2a32f8e74..780cd56bda 100644
--- a/crates/pa-core/src/refinement/mod.rs
+++ b/crates/pa-core/src/refinement/mod.rs
@@ -8,7 +8,7 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
/// Refinement entry kinds (the continual harness component set).
-pub const REFINEMENT_KINDS: [&str; 4] = ["prompt", "memory", "skill", "subagent"];
+pub const REFINEMENT_KINDS: [&str; 5] = ["prompt", "memory", "skill", "subagent", "factory"];
/// Directory name under the agent dir (or session artifact dir).
pub const HARNESS_STATE_DIR_NAME: &str = "harness";
@@ -28,6 +28,7 @@ pub enum RefinementKind {
Memory,
Skill,
Subagent,
+ Factory,
}
/// Edit action against a harness entry.
@@ -108,6 +109,7 @@ pub fn empty_harness_state() -> HarnessState {
(RefinementKind::Memory, BTreeMap::new()),
(RefinementKind::Skill, BTreeMap::new()),
(RefinementKind::Subagent, BTreeMap::new()),
+ (RefinementKind::Factory, BTreeMap::new()),
]
.into_iter()
.collect(),
@@ -120,6 +122,7 @@ fn kind_from_name(name: &str) -> RefinementKind {
"prompt" => RefinementKind::Prompt,
"memory" => RefinementKind::Memory,
"skill" => RefinementKind::Skill,
+ "factory" => RefinementKind::Factory,
_ => RefinementKind::Subagent,
}
}
@@ -139,6 +142,39 @@ pub fn get_harness_state_path(harness_state_dir: &Path) -> PathBuf {
harness_state_dir.join("harness_state.json")
}
+/// The settings file the factory opt-in gate reads: the agent dir's
+/// settings.json, the same document the kernel-side gate resolves through
+/// `PRIME_AGENT_CODING_AGENT_DIR` (the host exports the session's agent
+/// dir to the kernel, so both sides read one setting).
+pub const FACTORY_SETTINGS_FILE_NAME: &str = "settings.json";
+
+/// The one refusal every gated factory surface raises while the opt-in is
+/// off. Byte-identical to the kernel's `FACTORY_DISABLED_MESSAGE`
+/// (`prime-agent-runtime/src/rlm/factory.py`), so one exact message pins
+/// both sides of the gate.
+pub const FACTORY_DISABLED_MESSAGE: &str = "the factory is disabled; run /factory on to enable it";
+
+/// The `factory.enabled` opt-in setting (default off), read leniently from
+/// the agent dir's settings.json exactly like the kernel-side
+/// `rlm.factory.factory_enabled()`: a missing file or key, a wrong-typed
+/// value, or a corrupt document all read as the fail-closed disabled
+/// default, so an unreadable setting refuses the factory instead of
+/// silently enabling it.
+#[must_use]
+pub fn factory_enabled(agent_dir: &Path) -> bool {
+ let Ok(raw) = std::fs::read_to_string(agent_dir.join(FACTORY_SETTINGS_FILE_NAME)) else {
+ return false;
+ };
+ let Ok(document) = serde_json::from_str::<serde_json::Value>(&raw) else {
+ return false;
+ };
+ document
+ .get("factory")
+ .and_then(|factory| factory.get("enabled"))
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false)
+}
+
/// Load harness state; a corrupt or unreadable file degrades to empty rather
/// than throwing (prompt builds run on every turn).
///
@@ -498,6 +534,7 @@ fn kind_name(kind: RefinementKind) -> &'static str {
RefinementKind::Memory => "memory",
RefinementKind::Skill => "skill",
RefinementKind::Subagent => "subagent",
+ RefinementKind::Factory => "factory",
}
}
@@ -540,6 +577,50 @@ mod tests {
}
}
+ #[test]
+ fn factory_opt_in_reads_leniently_and_fails_closed() {
+ let tmp = tempfile::tempdir().unwrap();
+ // No settings file: the opt-in default is disabled.
+ assert!(!factory_enabled(tmp.path()));
+ // The enabled shape the settings surface writes.
+ std::fs::write(
+ tmp.path().join(FACTORY_SETTINGS_FILE_NAME),
+ r#"{"factory": {"enabled": true}, "compaction": {"enabled": true}}"#,
+ )
+ .unwrap();
+ assert!(factory_enabled(tmp.path()));
+ // An explicit false stays disabled.
+ std::fs::write(
+ tmp.path().join(FACTORY_SETTINGS_FILE_NAME),
+ r#"{"factory": {"enabled": false}}"#,
+ )
+ .unwrap();
+ assert!(!factory_enabled(tmp.path()));
+ // A wrong-typed value reads as unset, which means disabled.
+ std::fs::write(
+ tmp.path().join(FACTORY_SETTINGS_FILE_NAME),
+ r#"{"factory": {"enabled": "yes"}, "factory.enabled": true}"#,
+ )
+ .unwrap();
+ assert!(!factory_enabled(tmp.path()));
+ // A missing key is unset.
+ std::fs::write(
+ tmp.path().join(FACTORY_SETTINGS_FILE_NAME),
+ r#"{"compaction": {}}"#,
+ )
+ .unwrap();
+ assert!(!factory_enabled(tmp.path()));
+ // A corrupt document reads as the disabled default, never a crash.
+ std::fs::write(tmp.path().join(FACTORY_SETTINGS_FILE_NAME), "{ not json").unwrap();
+ assert!(!factory_enabled(tmp.path()));
+ // The refusal is the one exact message, byte-identical to the
+ // kernel-side FACTORY_DISABLED_MESSAGE (rlm/factory.py).
+ assert_eq!(
+ FACTORY_DISABLED_MESSAGE,
+ "the factory is disabled; run /factory on to enable it"
+ );
+ }
+
#[test]
fn state_round_trips_and_degrades_gracefully() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/pa-core/src/refinement/planner.rs b/crates/pa-core/src/refinement/planner.rs
index 9fd653fac6..fd029ea517 100644
--- a/crates/pa-core/src/refinement/planner.rs
+++ b/crates/pa-core/src/refinement/planner.rs
@@ -8,7 +8,7 @@ use super::{
RefinementAction, RefinementKind,
};
-pub const REFINEMENT_SYSTEM_PROMPT: &str = "You are Prime Agent's /refine continual harness subsystem.\n\nYour job is to improve the editable continual harness state from the current trajectory.\nThis is similar in spirit to context compaction, but instead of summarizing the\nconversation you emit precise Create, Update, or Delete edits to reusable state.\nThe continual harness is the persistent, editable set of prompt notes, memories,\nskills, and subagent specs that lets Prime Agent improve reusable behavior\noutside the token history.\nUse \"continual harness\" for that persistent artifact layer; keep \"RLM\" for the\nruntime, Python REPL kernel, and native call interface that executes those artifacts.\n\nContinual harness components:\n- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.\n- memory: durable facts, decisions, failures, preferences, and outcomes.\n- skill: installed Python REPL skill. Skill create/update edits MUST include a `reference` object with `{\"type\":\"python\"}`, a Python import, and a callable or call pattern; they also MUST include an `arguments` object describing accepted inputs, required fields, defaults, and constraints. Use `{}` for `arguments` only when the Python callable truly needs no external inputs. Include the RLM-native call form `await <skill_import>(...)`.\n- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: compose a concise task prompt and spawn with `handle = await rlm.spawn(\"sub-task\", name=\"worker\")`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role=\"parent\")`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role=\"child\", receiver_name=handle.name)` for follow-ups. Do not invent wrappers like `run_subagent(...)`.\n\nScope and persistence policy:\n- The default editable continual harness store is local to the current Prime Agent session. Use it for session-specific progress, active task state, current-run coordination notes, temporary blockers, and project facts that should not affect other sessions.\n- A caller may explicitly request global refinement. Global edits must be stable cross-session lessons, durable user preferences, reusable skills/subagents, or tool/environment facts that should affect future sessions.\n- Entry ids in the harness overview may carry a display-only `local:` or `global:` prefix. Always use the bare id (no prefix) in edits.\n- All edits in one refinement apply only to the requested scope's store. During a local refinement, global entries are read-only context: never propose update or delete edits for them; create a local entry instead when a session-specific override is genuinely needed.\n- Project/workspace-specific lessons may be persisted globally only when the title, path, or content explicitly names the project/workspace and the lesson is likely to be reused in future sessions for that project. Prefer local edits when the lesson only belongs in the current conversation.\n- Use memory for declarative facts and preferences, skill for repeatable procedures exposed as Python calls, prompt for narrow behavioral policy addendums, and subagent for reusable delegation roles.\n- Create or update the smallest relevant component: repeated delegation roles should become subagent specs, repeated procedures should become skills, durable facts/preferences should become memories, and narrow behavioral policies should become prompt addendums.\n- When an edit is persisted, include metadata such as `{\"scope\":\"local\"}` or `{\"scope\":\"global\"}` when that helps future review understand the intended blast radius.\n\nUse the trajectory, current continual harness state, and prior refinement history. Prefer\nsmall evidence-backed edits. If prior refinements caused issues, rollback or\nreplace the faulty editable entries. Never edit source files directly. Output\nJSON only with this exact shape:\n\n{\n \"summary\": \"one sentence\",\n \"rationale\": \"why these edits are justified by trajectory evidence\",\n \"expectedOutcome\": \"what should improve and how to validate it\",\n \"edits\": [\n {\n \"action\": \"create|update|delete\",\n \"kind\": \"prompt|memory|skill|subagent\",\n \"id\": \"stable id for update/delete, optional for create\",\n \"title\": \"required for create/update except delete\",\n \"content\": \"required for create/update except delete\",\n \"path\": \"optional grouping path\",\n \"reference\": {\"type\": \"python\", \"import\": \"package.module\", \"callable\": \"function_name\", \"call_pattern\": \"await function_name(...)\"},\n \"arguments\": {\"name\": {\"type\": \"string\", \"required\": true, \"description\": \"accepted input\"}},\n \"metadata\": {},\n \"reason\": \"why this edit is useful\"\n }\n ]\n}";
+pub const REFINEMENT_SYSTEM_PROMPT: &str = "You are Prime Agent's /refine continual harness subsystem.\n\nYour job is to improve the editable continual harness state from the current trajectory.\nThis is similar in spirit to context compaction, but instead of summarizing the\nconversation you emit precise Create, Update, or Delete edits to reusable state.\nThe continual harness is the persistent, editable set of prompt notes, memories,\nskills, and subagent specs that lets Prime Agent improve reusable behavior\noutside the token history.\nUse \"continual harness\" for that persistent artifact layer; keep \"RLM\" for the\nruntime, Python REPL kernel, and native call interface that executes those artifacts.\n\nContinual harness components:\n- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.\n- memory: durable facts, decisions, failures, preferences, and outcomes.\n- skill: installed Python REPL skill. Skill create/update edits MUST include a `reference` object with `{\"type\":\"python\"}`, a Python import, and a callable or call pattern; they also MUST include an `arguments` object describing accepted inputs, required fields, defaults, and constraints. Use `{}` for `arguments` only when the Python callable truly needs no external inputs. Include the RLM-native call form `await <skill_import>(...)`.\n- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: compose a concise task prompt and spawn with `handle = await rlm.spawn(\"sub-task\", name=\"worker\")`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role=\"parent\")`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role=\"child\", receiver_name=handle.name)` for follow-ups. Do not invent wrappers like `run_subagent(...)`.\n- factory: declarative state-machine workflow specs of subagent states. The spec lives in `arguments.machine` (the original DAG sugar in `arguments.dag` compiles to machine form; pass exactly one form). The kernel validator (`rlm.factory`) enforces the full machine semantics at write time: run a stored factory with `await rlm.factory.run('<id>')`, watch with `await rlm.factory.status(run_id)`, stop with `await rlm.factory.stop(run_id)`, and resume an escalate-paused run with `await rlm.factory.resume(run_id)`.\n\nScope and persistence policy:\n- The default editable continual harness store is local to the current Prime Agent session. Use it for session-specific progress, active task state, current-run coordination notes, temporary blockers, and project facts that should not affect other sessions.\n- A caller may explicitly request global refinement. Global edits must be stable cross-session lessons, durable user preferences, reusable skills/subagents, or tool/environment facts that should affect future sessions.\n- Entry ids in the harness overview may carry a display-only `local:` or `global:` prefix. Always use the bare id (no prefix) in edits.\n- All edits in one refinement apply only to the requested scope's store. During a local refinement, global entries are read-only context: never propose update or delete edits for them; create a local entry instead when a session-specific override is genuinely needed.\n- Project/workspace-specific lessons may be persisted globally only when the title, path, or content explicitly names the project/workspace and the lesson is likely to be reused in future sessions for that project. Prefer local edits when the lesson only belongs in the current conversation.\n- Use memory for declarative facts and preferences, skill for repeatable procedures exposed as Python calls, prompt for narrow behavioral policy addendums, and subagent for reusable delegation roles.\n- Create or update the smallest relevant component: repeated delegation roles should become subagent specs, repeated procedures should become skills, durable facts/preferences should become memories, and narrow behavioral policies should become prompt addendums.\n- When an edit is persisted, include metadata such as `{\"scope\":\"local\"}` or `{\"scope\":\"global\"}` when that helps future review understand the intended blast radius.\n\nUse the trajectory, current continual harness state, and prior refinement history. Prefer\nsmall evidence-backed edits. If prior refinements caused issues, rollback or\nreplace the faulty editable entries. Never edit source files directly. Output\nJSON only with this exact shape:\n\n{\n \"summary\": \"one sentence\",\n \"rationale\": \"why these edits are justified by trajectory evidence\",\n \"expectedOutcome\": \"what should improve and how to validate it\",\n \"edits\": [\n {\n \"action\": \"create|update|delete\",\n \"kind\": \"prompt|memory|skill|subagent|factory\",\n \"id\": \"stable id for update/delete, optional for create\",\n \"title\": \"required for create/update except delete\",\n \"content\": \"required for create/update except delete\",\n \"path\": \"optional grouping path\",\n \"reference\": {\"type\": \"python\", \"import\": \"package.module\", \"callable\": \"function_name\", \"call_pattern\": \"await function_name(...)\"},\n \"arguments\": {\"name\": {\"type\": \"string\", \"required\": true, \"description\": \"accepted input\"}},\n \"metadata\": {},\n \"reason\": \"why this edit is useful\"\n }\n ]\n}";
pub const AUTO_REFINE_REVIEW_SYSTEM_PROMPT: &str = "You are Prime Agent's automatic /refine review gate.\n\nDecide whether this checkpoint should run /refine. Auto /refine writes local continual harness state by default, so approve when the trajectory contains evidence useful to this session's future turns.\nReject one-off noise, unsupported hypotheses, and transient tool outputs. Ask for global refinement only for durable cross-session lessons or explicitly project-qualified lessons likely to be reused in future sessions.\n\nReturn JSON only:\n{\n \"shouldRefine\": true|false,\n \"rationale\": \"short reason\",\n \"instructions\": \"optional concise instructions for /refine if shouldRefine is true\"\n}";
@@ -209,7 +209,8 @@ fn validate_edit(edit: &RefinementEdit, computed_id: Option<&str>) -> Option<Str
RefinementKind::Prompt
| RefinementKind::Memory
| RefinementKind::Skill
- | RefinementKind::Subagent => {}
+ | RefinementKind::Subagent
+ | RefinementKind::Factory => {}
}
if kind == RefinementKind::Prompt
&& (edit.id.as_deref() == Some("base_system_prompt")
@@ -258,6 +259,33 @@ fn validate_edit(edit: &RefinementEdit, computed_id: Option<&str>) -> Option<Str
);
}
}
+ if action != RefinementAction::Delete
+ && kind == RefinementKind::Factory
+ && (action == RefinementAction::Create || edit.arguments.is_some())
+ {
+ // Structural check only: the kernel validator (`rlm.factory`) enforces
+ // the full machine semantics at write time; do not reimplement it here.
+ // A create requires its spec; an update may omit `arguments` entirely
+ // and keep the stored spec (apply preserves `before.arguments`),
+ // exactly like update_factory treats dag/machine.
+ let arguments = edit.arguments.as_ref();
+ // JSON null is treated as absent, exactly like the kernel's Python
+ // writers (arguments.get("machine") returning None): a supplied
+ // "machine": null never counts as the machine form.
+ let dag = arguments
+ .and_then(|args| args.get("dag"))
+ .filter(|value| !value.is_null());
+ let machine = arguments
+ .and_then(|args| args.get("machine"))
+ .filter(|value| !value.is_null());
+ if dag.is_some() && machine.is_some() {
+ return Some("pass either dag or machine form, not both".to_string());
+ }
+ let spec = machine.or(dag);
+ if !matches!(spec, Some(serde_json::Value::Object(_))) {
+ return Some("factory entry requires a dag or machine object in arguments".to_string());
+ }
+ }
None
}
@@ -273,6 +301,11 @@ pub struct ApplyOptions {
/// Target-scope state captured before planning; edits whose entry changed
/// since the baseline are rejected.
pub baseline_state: Option<HarnessState>,
+ /// The resolved `factory.enabled` opt-in (default off). While it is off,
+ /// factory create/update edits refuse with the one disabled message, the
+ /// same gate the kernel-side factory writers raise
+ /// (`rlm.factory.require_factory_enabled`).
+ pub factory_enabled: bool,
}
/// Apply a proposal to the state (mutating entries and recording the event).
@@ -345,6 +378,23 @@ pub fn apply_refinement_proposal(
applied_edits.push(row);
continue;
}
+ // The opt-in gate, the host-side mirror of the kernel writers'
+ // one refusal (`require_factory_enabled`): while `factory.enabled`
+ // is off, a refinement cannot author or re-author factory entries,
+ // exactly like every kernel factory write. The refusal precedes
+ // the create/update existence checks, so the disabled message is
+ // unconditional while off. A delete is not authoring: cleanup
+ // stays available, the gate's documented split.
+ if kind == RefinementKind::Factory
+ && action != RefinementAction::Delete
+ && !options.factory_enabled
+ {
+ let mut row = AppliedRefinementEdit::planned(edit, action, kind, id.clone());
+ row.before = before;
+ row.error = Some(super::FACTORY_DISABLED_MESSAGE.to_string());
+ applied_edits.push(row);
+ continue;
+ }
if action == RefinementAction::Delete {
if before.is_none() {
let mut row = AppliedRefinementEdit::planned(edit, action, kind, id.clone());
@@ -518,6 +568,7 @@ fn kind_name(kind: RefinementKind) -> &'static str {
RefinementKind::Memory => "memory",
RefinementKind::Skill => "skill",
RefinementKind::Subagent => "subagent",
+ RefinementKind::Factory => "factory",
}
}
@@ -680,6 +731,82 @@ mod tests {
prompt_edit.id = Some("x".to_string());
}
+ #[test]
+ fn factory_edits_accept_exactly_one_spec_form() {
+ // Structural check only (TS shape): the kernel validator enforces
+ // the full machine semantics at write time.
+ let machine = serde_json::json!({
+ "states": [{ "id": "collect", "entry": true, "subagent": "worker" }],
+ "transitions": []
+ });
+ let dag = serde_json::json!({ "nodes": [{ "id": "collect", "subagent": "worker" }] });
+ let mut edit = RefinementEdit {
+ action: Some(RefinementAction::Create),
+ kind: Some(RefinementKind::Factory),
+ id: Some("sweep".to_string()),
+ title: Some("Factory".into()),
+ content: Some("Sweep review across changed files.".into()),
+ ..Default::default()
+ };
+ // A dag object passes.
+ edit.arguments = Some(serde_json::from_value(serde_json::json!({ "dag": dag })).unwrap());
+ assert_eq!(validate_edit(&edit, None), None);
+ // A machine object passes.
+ edit.arguments =
+ Some(serde_json::from_value(serde_json::json!({ "machine": machine })).unwrap());
+ assert_eq!(validate_edit(&edit, None), None);
+ // Both forms at once are rejected with the kernel wording.
+ edit.arguments = Some(
+ serde_json::from_value(serde_json::json!({ "dag": dag, "machine": machine })).unwrap(),
+ );
+ assert_eq!(
+ validate_edit(&edit, None),
+ Some("pass either dag or machine form, not both".to_string())
+ );
+ // Neither form (or a non-object spec) is rejected.
+ edit.arguments = Some(serde_json::Map::default());
+ assert_eq!(
+ validate_edit(&edit, None),
+ Some("factory entry requires a dag or machine object in arguments".to_string())
+ );
+ edit.arguments = Some(
+ serde_json::from_value(serde_json::json!({ "machine": "not an object" })).unwrap(),
+ );
+ assert_eq!(
+ validate_edit(&edit, None),
+ Some("factory entry requires a dag or machine object in arguments".to_string())
+ );
+ edit.arguments = None;
+ assert!(validate_edit(&edit, None)
+ .unwrap()
+ .contains("requires a dag or machine object"));
+ // Delete edits carry no spec requirement.
+ edit.action = Some(RefinementAction::Delete);
+ assert_eq!(validate_edit(&edit, None), None);
+ // An update that omits `arguments` keeps the stored spec (apply
+ // preserves `before.arguments`), exactly like update_factory.
+ edit.action = Some(RefinementAction::Update);
+ edit.arguments = None;
+ assert_eq!(validate_edit(&edit, None), None);
+ // An update that does supply arguments gets the same shape checks.
+ edit.arguments =
+ Some(serde_json::from_value(serde_json::json!({ "machine": machine })).unwrap());
+ assert_eq!(validate_edit(&edit, None), None);
+ // JSON null is absent, exactly like the kernel's Python writers: a
+ // valid dag with "machine": null is a dag-form edit, not both forms.
+ edit.arguments = Some(
+ serde_json::from_value(serde_json::json!({ "dag": dag, "machine": null })).unwrap(),
+ );
+ assert_eq!(validate_edit(&edit, None), None);
+ edit.arguments = Some(
+ serde_json::from_value(serde_json::json!({ "dag": dag, "machine": machine })).unwrap(),
+ );
+ assert_eq!(
+ validate_edit(&edit, None),
+ Some("pass either dag or machine form, not both".to_string())
+ );
+ }
+
#[test]
fn apply_create_update_delete() {
let mut state = empty_harness_state();
@@ -697,6 +824,7 @@ mod tests {
rollback_of: None,
scope: Some(HarnessScope::Local),
baseline_state: None,
+ factory_enabled: false,
},
);
assert_eq!(result.applied_edits.len(), 1);
@@ -719,6 +847,7 @@ mod tests {
rollback_of: None,
scope: None,
baseline_state: None,
+ factory_enabled: false,
},
);
assert!(!duplicate.applied_edits[0].applied);
@@ -742,6 +871,7 @@ mod tests {
rollback_of: None,
scope: None,
baseline_state: None,
+ factory_enabled: false,
},
);
assert_eq!(state.entries[&RefinementKind::Memory]["m1"].version, 2);
@@ -755,10 +885,155 @@ mod tests {
rollback_of: Some("r1".to_string()),
scope: None,
baseline_state: None,
+ factory_enabled: false,
},
);
assert!(rolled.applied_edits[0].applied);
// r1 created m1 with no before snapshot, so the rollback deletes it.
assert!(!state.entries[&RefinementKind::Memory].contains_key("m1"));
}
+
+ #[test]
+ fn factory_edits_refuse_while_the_opt_in_is_disabled() {
+ // The opt-in gate on the apply path: while `factory.enabled` is
+ // off, a refinement cannot author or re-author factory entries —
+ // the same refusal, byte for byte, the kernel-side factory
+ // writers raise (`rlm.factory.require_factory_enabled`).
+ let machine = serde_json::json!({
+ "states": [{ "id": "collect", "entry": true, "subagent": "worker" }],
+ "transitions": []
+ });
+ let factory_edit = |action: RefinementAction, id: &str| RefinementEdit {
+ action: Some(action),
+ kind: Some(RefinementKind::Factory),
+ id: Some(id.to_string()),
+ title: Some("Factory".into()),
+ content: Some("Sweep review across changed files.".into()),
+ arguments: Some(
+ serde_json::from_value(serde_json::json!({ "machine": machine })).unwrap(),
+ ),
+ ..Default::default()
+ };
+ let mut state = empty_harness_state();
+ let proposal = |edits: Vec<RefinementEdit>| RefinementProposal {
+ summary: "sweep".to_string(),
+ rationale: String::new(),
+ expected_outcome: String::new(),
+ edits,
+ };
+ let disabled = apply_refinement_proposal(
+ &mut state,
+ &proposal(vec![factory_edit(RefinementAction::Create, "sweep")]),
+ ApplyOptions {
+ id: "r1".to_string(),
+ rollback_of: None,
+ scope: Some(HarnessScope::Local),
+ baseline_state: None,
+ factory_enabled: false,
+ },
+ );
+ assert!(!disabled.applied_edits[0].applied);
+ assert_eq!(
+ disabled.applied_edits[0].error.as_deref(),
+ Some(super::super::FACTORY_DISABLED_MESSAGE)
+ );
+ assert!(state.entries[&RefinementKind::Factory].is_empty());
+ // An update of a stored entry refuses too: cleanup is not
+ // authoring, but re-authoring while disabled is.
+ state
+ .entries
+ .get_mut(&RefinementKind::Factory)
+ .unwrap()
+ .insert(
+ "sweep".to_string(),
+ HarnessEntry {
+ id: "sweep".to_string(),
+ kind: RefinementKind::Factory,
+ title: "Factory".to_string(),
+ content: "Sweep.".to_string(),
+ path: "general".to_string(),
+ scope: Some(HarnessScope::Local),
+ reference: serde_json::Map::default(),
+ arguments: serde_json::Map::default(),
+ metadata: serde_json::Map::default(),
+ source: "refine".to_string(),
+ created_at: String::new(),
+ updated_at: String::new(),
+ version: 1,
+ },
+ );
+ let refused_update = apply_refinement_proposal(
+ &mut state,
+ &proposal(vec![factory_edit(RefinementAction::Update, "sweep")]),
+ ApplyOptions {
+ id: "r2".to_string(),
+ rollback_of: None,
+ scope: None,
+ baseline_state: None,
+ factory_enabled: false,
+ },
+ );
+ assert!(!refused_update.applied_edits[0].applied);
+ assert_eq!(
+ refused_update.applied_edits[0].error.as_deref(),
+ Some(super::super::FACTORY_DISABLED_MESSAGE)
+ );
+ // A delete is not authoring: cleanup stays available while
+ // disabled (the gate's documented split).
+ let cleanup = apply_refinement_proposal(
+ &mut state,
+ &proposal(vec![{
+ let mut edit = factory_edit(RefinementAction::Delete, "sweep");
+ edit.arguments = None;
+ edit
+ }]),
+ ApplyOptions {
+ id: "r3".to_string(),
+ rollback_of: None,
+ scope: None,
+ baseline_state: None,
+ factory_enabled: false,
+ },
+ );
+ assert!(cleanup.applied_edits[0].applied);
+ assert!(state.entries[&RefinementKind::Factory].is_empty());
+ }
+
+ #[test]
+ fn factory_edits_apply_when_the_opt_in_is_enabled() {
+ let machine = serde_json::json!({
+ "states": [{ "id": "collect", "entry": true, "subagent": "worker" }],
+ "transitions": []
+ });
+ let mut state = empty_harness_state();
+ let result = apply_refinement_proposal(
+ &mut state,
+ &RefinementProposal {
+ summary: "sweep".to_string(),
+ rationale: String::new(),
+ expected_outcome: String::new(),
+ edits: vec![RefinementEdit {
+ action: Some(RefinementAction::Create),
+ kind: Some(RefinementKind::Factory),
+ id: Some("sweep".to_string()),
+ title: Some("Factory".into()),
+ content: Some("Sweep review across changed files.".into()),
+ arguments: Some(
+ serde_json::from_value(serde_json::json!({ "machine": machine })).unwrap(),
+ ),
+ ..Default::default()
+ }],
+ },
+ ApplyOptions {
+ id: "r1".to_string(),
+ rollback_of: None,
+ scope: Some(HarnessScope::Local),
+ baseline_state: None,
+ factory_enabled: true,
+ },
+ );
+ assert!(result.applied_edits[0].applied);
+ assert!(result.applied_edits[0].error.is_none());
+ assert!(state.entries[&RefinementKind::Factory].contains_key("sweep"));
+ }
}
diff --git a/crates/pa-core/src/refinement/ranking.rs b/crates/pa-core/src/refinement/ranking.rs
index d556b95aca..3b8933971a 100644
--- a/crates/pa-core/src/refinement/ranking.rs
+++ b/crates/pa-core/src/refinement/ranking.rs
@@ -269,6 +269,11 @@ pub fn format_harness_state_for_prompt(
let kind_name = kind;
if kind_name == "subagent" && !entries.is_empty() && include_ipython {
lines.push(format!("{kind_name}: {} (invoke a spec by turning it into a concise task prompt and spawning with `await rlm.spawn('<task>', name='<worker>')`; admission returns a child handle, never the answer)", entries.len()));
+ } else if kind_name == "factory" && !entries.is_empty() && include_ipython {
+ lines.push(format!(
+ "{kind_name}: {} (state-machine workflow specs; run one with `await rlm.factory.run('<id>')`; watch with `await rlm.factory.status(run_id)`, stop with `await rlm.factory.stop(run_id)`, resume a paused run with `await rlm.factory.resume(run_id)`)",
+ entries.len()
+ ));
} else {
lines.push(format!("{kind_name}: {}", entries.len()));
}
@@ -397,6 +402,7 @@ fn refinement_kind_name(kind: RefinementKind) -> &'static str {
RefinementKind::Memory => "memory",
RefinementKind::Skill => "skill",
RefinementKind::Subagent => "subagent",
+ RefinementKind::Factory => "factory",
}
}
@@ -539,6 +545,7 @@ fn kind_for(name: &str) -> RefinementKind {
"prompt" => RefinementKind::Prompt,
"memory" => RefinementKind::Memory,
"skill" => RefinementKind::Skill,
+ "factory" => RefinementKind::Factory,
_ => RefinementKind::Subagent,
}
}
@@ -658,6 +665,78 @@ mod tests {
assert!(rendered.contains("+1 more memory entries"));
}
+ #[test]
+ fn factory_digest_line_renders_with_the_run_watch_stop_hint() {
+ // TS shape: the factory line renders only when entries exist and
+ // IPython examples are on (the await forms follow the accepted
+ // review fix for the coroutine-object pitfall).
+ let mut state = empty_harness_state();
+ let mut factory = make_entry("sweep", "PR review sweep", "Sweep review.", "review");
+ factory.kind = RefinementKind::Factory;
+ state
+ .entries
+ .get_mut(&RefinementKind::Factory)
+ .unwrap()
+ .insert("sweep".to_string(), factory);
+ let rendered = format_harness_state_for_prompt(
+ &state,
+ &HarnessStatePromptOptions {
+ max_entries_per_kind: Some(40),
+ query_terms: None,
+ include_ipython_examples: Some(true),
+ ..Default::default()
+ },
+ );
+ assert!(rendered.contains(
+ "factory: 1 (state-machine workflow specs; run one with `await rlm.factory.run('<id>')`; watch with `await rlm.factory.status(run_id)`, stop with `await rlm.factory.stop(run_id)`, resume a paused run with `await rlm.factory.resume(run_id)`)"
+ ));
+ assert!(rendered.contains("- [global:sweep] PR review sweep (review, v1): Sweep review."));
+ // Without IPython examples the hint line stays a plain count.
+ let plain = format_harness_state_for_prompt(
+ &state,
+ &HarnessStatePromptOptions {
+ max_entries_per_kind: Some(40),
+ query_terms: None,
+ include_ipython_examples: Some(false),
+ ..Default::default()
+ },
+ );
+ assert!(plain.contains("\nfactory: 1\n"));
+ // An empty factory section renders no invoke hint.
+ let empty = empty_harness_state();
+ let rendered_empty = format_harness_state_for_prompt(
+ &empty,
+ &HarnessStatePromptOptions {
+ max_entries_per_kind: Some(40),
+ query_terms: None,
+ include_ipython_examples: Some(true),
+ ..Default::default()
+ },
+ );
+ assert!(rendered_empty.contains("\nfactory: 0\n"));
+ assert!(!rendered_empty.contains("rlm.factory.run"));
+ // Fingerprint stability: a factory entry participates like any
+ // other kind; its content change re-fingerprints (arguments render
+ // only for skills, so an arguments-only change stays inert, exactly
+ // like the TS fingerprint material).
+ let flags = HarnessDigestRenderFlags {
+ include_ipython_examples: true,
+ include_shell_examples: false,
+ include_refine_examples: false,
+ };
+ let baseline = harness_digest_fingerprint(&state, flags);
+ let mut changed = state.clone();
+ changed
+ .entries
+ .get_mut(&RefinementKind::Factory)
+ .unwrap()
+ .get_mut("sweep")
+ .unwrap()
+ .content
+ .push_str(" more");
+ assert_ne!(harness_digest_fingerprint(&changed, flags), baseline);
+ }
+
#[test]
fn fingerprint_is_stable_across_entry_order_and_ignores_query_terms() {
let mut state = empty_harness_state();
diff --git a/crates/pa-core/src/session_engine/compaction_arms.rs b/crates/pa-core/src/session_engine/compaction_arms.rs
index 59a8044cf1..4ca830de35 100644
--- a/crates/pa-core/src/session_engine/compaction_arms.rs
+++ b/crates/pa-core/src/session_engine/compaction_arms.rs
@@ -397,6 +397,16 @@ impl AgentSession {
} = parts.await?;
let (result, context_row_ids) = {
let mut session = self.session.lock().await;
+ // The factory opt-in resolves at apply time, not here: the
+ // agent dir (the same settings.json the kernel-side factory
+ // gate reads) rides down to the refinement, which re-reads
+ // `factory.enabled` immediately before applying the plan, off
+ // the async worker (`spawn_blocking`). The arm performs no
+ // synchronous settings read while holding this session lock,
+ // and the long planning request can no longer leave the gate
+ // deciding on a snapshot the request made stale. A session
+ // without a wired agent dir keeps the fail-closed disabled
+ // default.
refine::execute_refinement_with_rows(
&mut session,
refine::RefinementTranscript {
@@ -408,6 +418,7 @@ impl AgentSession {
options,
source,
refine_call,
+ self.agent_dir.as_deref(),
)
.await?
};
diff --git a/crates/pa-core/src/session_engine/compaction_outcome_tests.rs b/crates/pa-core/src/session_engine/compaction_outcome_tests.rs
index e5cac45a99..98e64630df 100644
--- a/crates/pa-core/src/session_engine/compaction_outcome_tests.rs
+++ b/crates/pa-core/src/session_engine/compaction_outcome_tests.rs
@@ -522,6 +522,58 @@ async fn sequential_refines_push_exactly_their_own_rows() {
);
}
+/// A plan whose one edit creates a factory entry (a stored state-machine
+/// workflow spec): valid shape, so only the opt-in gate decides it.
+const FACTORY_PLAN: &str = r#"{"summary":"sweep","edits":[{"action":"create","kind":"factory","id":"sweep","title":"Factory","content":"Sweep review.","arguments":{"machine":{"states":[{"id":"collect","entry":true,"subagent":"worker"}],"transitions":[]}}}]}"#;
+
+#[tokio::test]
+async fn refine_factory_edits_follow_the_agent_dir_opt_in_setting() {
+ // The host /refine flow reads `factory.enabled` live from the session's
+ // agent dir on every run — the same settings.json the kernel-side
+ // factory gate reads — so a refinement cannot author factories the
+ // user has not opted into. Without a wired agent dir (or with the
+ // setting off), the factory create refuses with the one exact
+ // disabled message; opted in, the same proposal applies.
+ let (mut session, tmp) = refine_test_session().await;
+ let global_dir = tmp.path().join("harness");
+ let refused = session
+ .refine_with_refiner(
+ &refine::RefineOptions::default(),
+ refine::RefinementSource::User,
+ &session_ai_model(),
+ refine_plan_call(FACTORY_PLAN),
+ global_dir.clone(),
+ )
+ .await
+ .unwrap();
+ assert!(!refused.applied_edits[0].applied);
+ assert_eq!(
+ refused.applied_edits[0].error.as_deref(),
+ Some(crate::refinement::FACTORY_DISABLED_MESSAGE)
+ );
+ // The user opts in: the next run of the same proposal applies.
+ let agent_dir = tmp.path().join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ std::fs::write(
+ agent_dir.join("settings.json"),
+ r#"{"factory": {"enabled": true}}"#,
+ )
+ .unwrap();
+ session.set_agent_dir(agent_dir);
+ let applied = session
+ .refine_with_refiner(
+ &refine::RefineOptions::default(),
+ refine::RefinementSource::User,
+ &session_ai_model(),
+ refine_plan_call(FACTORY_PLAN),
+ global_dir,
+ )
+ .await
+ .unwrap();
+ assert!(applied.applied_edits[0].applied);
+ assert!(applied.applied_edits[0].error.is_none());
+}
+
#[tokio::test]
async fn refine_keeps_the_retry_drop_instead_of_resurrecting_the_error_row() {
let (session, tmp) = refine_test_session().await;
diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rs
index cd4ff084eb..ea07196afb 100644
--- a/crates/pa-core/src/session_engine/engine.rs
+++ b/crates/pa-core/src/session_engine/engine.rs
@@ -675,6 +675,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S
)
.await?;
session.set_auto_refine(auto_refine_allowed, auto_refine_gates);
+ session.set_agent_dir(config.agent_dir.clone());
// Every compaction path reads the session's resolved compaction
// settings (TS `getCompactionSettings`): `/compact` matches the
// `compact.*` turn-boundary tool's `keepRecentTokens`/`reserveTokens`.
diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rs
index eb8a413162..ee987e4955 100644
--- a/crates/pa-core/src/session_engine/mod.rs
+++ b/crates/pa-core/src/session_engine/mod.rs
@@ -204,6 +204,14 @@ pub struct AgentSession {
/// summarizer completion — no deltas, no broadcast, no behavior
/// change.
compaction_summary_sink: std::sync::Mutex<Option<compaction_exec::SummaryDeltaSink>>,
+ /// The session's agent dir (the settings root): the refine flow
+ /// resolves the `factory.enabled` opt-in from its settings.json on
+ /// every run, immediately before the plan applies, mirroring the
+ /// kernel-side factory gate that reads the same file through
+ /// `PRIME_AGENT_CODING_AGENT_DIR`. `None` until the engine wiring
+ /// resolves it (verification harnesses building the session directly
+ /// keep `None`, which reads as the fail-closed disabled default).
+ agent_dir: Option<std::path::PathBuf>,
}
impl AgentSession {
@@ -269,6 +277,7 @@ impl AgentSession {
skill_telemetry: None,
image_model_router: None,
compaction_summary_sink: std::sync::Mutex::new(None),
+ agent_dir: None,
};
this.ensure_harness_digest_context().await?;
Ok(this)
diff --git a/crates/pa-core/src/session_engine/refine.rs b/crates/pa-core/src/session_engine/refine.rs
index cbbb9d15f4..a2954251d3 100644
--- a/crates/pa-core/src/session_engine/refine.rs
+++ b/crates/pa-core/src/session_engine/refine.rs
@@ -276,6 +276,10 @@ pub struct RefinementTranscript<'a> {
/// session, when the refinement plan (LLM or rollback) fails, when applying
/// or persisting the refined harness state fails, or when appending the
/// audit, outcome, or notice entries fails.
+// One refine funnel: the transcript, the store dirs, the model seam, the
+// options, the source, and the resolved gates ride the same call
+// (same style as the daemon's too_many_arguments seams).
+#[allow(clippy::too_many_arguments)]
pub async fn execute_refinement(
session: &mut SessionManager,
transcript: RefinementTranscript<'_>,
@@ -284,6 +288,7 @@ pub async fn execute_refinement(
options: &RefineOptions,
source: RefinementSource,
refine_call: crate::refinement::executor::RefinerFn,
+ agent_dir: Option<&Path>,
) -> anyhow::Result<RefinementResult> {
Ok(execute_refinement_with_rows(
session,
@@ -293,6 +298,7 @@ pub async fn execute_refinement(
options,
source,
refine_call,
+ agent_dir,
)
.await?
.0)
@@ -306,6 +312,17 @@ pub async fn execute_refinement(
/// # Errors
///
/// Returns the same errors as [`execute_refinement`].
+///
+/// `agent_dir` is the session's settings root: its settings.json holds
+/// the `factory.enabled` opt-in (default off), re-read immediately before
+/// the plan applies — after the (long) model request, never snapshotted
+/// before it — so the gate decides on the CURRENT setting. While it is
+/// off, factory create/update edits refuse with the one disabled message —
+/// the same gate the kernel-side factory writers raise
+/// (`rlm.factory.require_factory_enabled`), so a refinement cannot
+/// author factories the user has not opted into. `None` (a session
+/// without a wired agent dir) keeps the fail-closed disabled default.
+#[allow(clippy::too_many_arguments)]
pub async fn execute_refinement_with_rows(
session: &mut SessionManager,
transcript: RefinementTranscript<'_>,
@@ -314,6 +331,7 @@ pub async fn execute_refinement_with_rows(
options: &RefineOptions,
source: RefinementSource,
refine_call: crate::refinement::executor::RefinerFn,
+ agent_dir: Option<&Path>,
) -> anyhow::Result<(RefinementResult, Vec<String>)> {
let RefinementTranscript {
messages,
@@ -386,7 +404,31 @@ pub async fn execute_refinement_with_rows(
HarnessScope::Local => local_harness_dir.clone(),
};
let mut state = load_harness_state(&target_dir, target_scope);
- let mut result = apply_refinement_plan(&mut state, plan, &core_options, Some(baseline_state));
+ // The factory opt-in resolves HERE — immediately before the apply,
+ // after the planning request — so a setting that changed during the
+ // request (`/factory off` mid-plan) decides, not a snapshot captured
+ // before it. The read rides `spawn_blocking` so the settings I/O
+ // never blocks the async runtime worker (the refine arm holds the
+ // session lock across this whole call). A session without a wired
+ // agent dir keeps the fail-closed disabled default, and a panicked
+ // read task reads as disabled — the same fail-closed leniency as
+ // `factory_enabled` itself.
+ let factory_enabled = match agent_dir {
+ Some(agent_dir) => {
+ let agent_dir = agent_dir.to_path_buf();
+ tokio::task::spawn_blocking(move || crate::refinement::factory_enabled(&agent_dir))
+ .await
+ .unwrap_or(false)
+ }
+ None => false,
+ };
+ let mut result = apply_refinement_plan(
+ &mut state,
+ plan,
+ &core_options,
+ Some(baseline_state),
+ factory_enabled,
+ );
result.harness_state_path = save_harness_state(&target_dir, &state)?
.to_string_lossy()
.to_string();
@@ -663,6 +705,17 @@ mod tests {
})
}
+ /// A refiner seam that rewrites the factory settings file mid-request
+ /// (the `/factory` flip during the model request), then returns the
+ /// plan authored under the pre-flip value.
+ fn flip_seam(settings: &Path, flipped: &'static str, reply: &'static str) -> RefinerFn {
+ let settings = settings.to_path_buf();
+ Box::new(move |_model, _system, _prompt| {
+ std::fs::write(&settings, flipped).unwrap();
+ Box::pin(async move { Ok(text_assistant(reply)) })
+ })
+ }
+
fn test_model() -> Model {
Model {
id: "test".to_string(),
@@ -786,6 +839,135 @@ Reviewer instructions: record it"
);
}
+ #[tokio::test]
+ async fn factory_edits_in_a_refinement_respect_the_opt_in_gate() {
+ // The host /refine flow funnels factory create edits through the
+ // same opt-in gate as the kernel writers: while `factory.enabled`
+ // is off, the edit refuses with the one exact disabled message
+ // and nothing persists; enabled, the same proposal applies.
+ let dir = TempDir::new().unwrap();
+ let mut session = persisted_session(&dir);
+ let global_dir = dir.path().join("harness");
+ let reply = r#"{"summary":"sweep","edits":[{"action":"create","kind":"factory","id":"sweep","title":"Factory","content":"Sweep review.","arguments":{"machine":{"states":[{"id":"collect","entry":true,"subagent":"worker"}],"transitions":[]}}}]}"#;
+ let disabled = execute_refinement(
+ &mut session,
+ RefinementTranscript {
+ messages: &[user_message("do a thing twice")],
+ refinement_history: &[],
+ },
+ &global_dir,
+ &test_model(),
+ &RefineOptions::default(),
+ RefinementSource::User,
+ seam(reply),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(!disabled.applied_edits[0].applied);
+ assert_eq!(
+ disabled.applied_edits[0].error.as_deref(),
+ Some(crate::refinement::FACTORY_DISABLED_MESSAGE)
+ );
+ let harness_dir =
+ crate::refinement::get_local_harness_state_dir(Some(session.get_session_dir()))
+ .unwrap();
+ let state = load_harness_state(&harness_dir, HarnessScope::Local);
+ assert!(state.entries[&crate::refinement::RefinementKind::Factory].is_empty());
+ // The user opts in: the same proposal applies, read live from the
+ // agent dir's settings.json.
+ let agent_dir = dir.path().join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ std::fs::write(
+ agent_dir.join(crate::refinement::FACTORY_SETTINGS_FILE_NAME),
+ r#"{"factory": {"enabled": true}}"#,
+ )
+ .unwrap();
+ let enabled = execute_refinement(
+ &mut session,
+ RefinementTranscript {
+ messages: &[user_message("do a thing twice")],
+ refinement_history: &[],
+ },
+ &global_dir,
+ &test_model(),
+ &RefineOptions::default(),
+ RefinementSource::User,
+ seam(reply),
+ Some(&agent_dir),
+ )
+ .await
+ .unwrap();
+ assert!(enabled.applied_edits[0].applied);
+ assert!(enabled.applied_edits[0].error.is_none());
+ let state = load_harness_state(&harness_dir, HarnessScope::Local);
+ assert!(state.entries[&crate::refinement::RefinementKind::Factory].contains_key("sweep"));
+ }
+
+ #[tokio::test]
+ async fn factory_gate_decides_on_the_apply_time_setting_not_a_planning_snapshot() {
+ // The opt-in re-reads immediately before the apply — after the
+ // planning request — so a `/factory` flip during the model request
+ // decides, not the value the plan was authored under: a plan
+ // authored while enabled that lands after the setting turned off
+ // refuses with the one exact disabled message and nothing
+ // persists, and a plan authored while disabled that lands after
+ // the opt-in applies.
+ let dir = TempDir::new().unwrap();
+ let mut session = persisted_session(&dir);
+ let global_dir = dir.path().join("harness");
+ let agent_dir = dir.path().join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ let settings = agent_dir.join(crate::refinement::FACTORY_SETTINGS_FILE_NAME);
+ let reply = r#"{"summary":"sweep","edits":[{"action":"create","kind":"factory","id":"sweep","title":"Factory","content":"Sweep review.","arguments":{"machine":{"states":[{"id":"collect","entry":true,"subagent":"worker"}],"transitions":[]}}}]}"#;
+ // Authored while enabled; the request flips the setting off.
+ std::fs::write(&settings, r#"{"factory": {"enabled": true}}"#).unwrap();
+ let turned_off = execute_refinement(
+ &mut session,
+ RefinementTranscript {
+ messages: &[user_message("do a thing twice")],
+ refinement_history: &[],
+ },
+ &global_dir,
+ &test_model(),
+ &RefineOptions::default(),
+ RefinementSource::User,
+ flip_seam(&settings, r#"{"factory": {"enabled": false}}"#, reply),
+ Some(&agent_dir),
+ )
+ .await
+ .unwrap();
+ assert!(!turned_off.applied_edits[0].applied);
+ assert_eq!(
+ turned_off.applied_edits[0].error.as_deref(),
+ Some(crate::refinement::FACTORY_DISABLED_MESSAGE)
+ );
+ let harness_dir =
+ crate::refinement::get_local_harness_state_dir(Some(session.get_session_dir()))
+ .unwrap();
+ let state = load_harness_state(&harness_dir, HarnessScope::Local);
+ assert!(state.entries[&crate::refinement::RefinementKind::Factory].is_empty());
+ // Authored while disabled; the request opts in.
+ std::fs::write(&settings, r#"{"factory": {"enabled": false}}"#).unwrap();
+ let turned_on = execute_refinement(
+ &mut session,
+ RefinementTranscript {
+ messages: &[user_message("do a thing twice")],
+ refinement_history: &[],
+ },
+ &global_dir,
+ &test_model(),
+ &RefineOptions::default(),
+ RefinementSource::User,
+ flip_seam(&settings, r#"{"factory": {"enabled": true}}"#, reply),
+ Some(&agent_dir),
+ )
+ .await
+ .unwrap();
+ assert!(turned_on.applied_edits[0].applied);
+ assert!(turned_on.applied_edits[0].error.is_none());
+ }
+
#[tokio::test]
async fn execute_refinement_persists_state_and_entries() {
let dir = TempDir::new().unwrap();
@@ -806,6 +988,7 @@ Reviewer instructions: record it"
&RefineOptions::default(),
RefinementSource::User,
seam(reply),
+ None,
)
.await
.unwrap();
@@ -866,6 +1049,7 @@ Reviewer instructions: record it"
&RefineOptions::default(),
RefinementSource::User,
seam(reply),
+ None,
)
.await
.unwrap_err();
@@ -982,6 +1166,7 @@ Reviewer instructions: record it"
let reply = reply;
Box::pin(async move { Ok(text_assistant(&reply)) })
}),
+ None,
)
.await
.unwrap_or_else(|error| panic!("'{leg}' leg failed: {error:#}"));
@@ -1059,6 +1244,7 @@ Reviewer instructions: record it"
},
RefinementSource::SelfRefine,
seam(reply),
+ None,
)
.await
.unwrap();
@@ -1087,6 +1273,7 @@ Reviewer instructions: record it"
},
RefinementSource::User,
seam("unused"),
+ None,
)
.await
.unwrap();
diff --git a/crates/pa-core/src/session_engine/wiring.rs b/crates/pa-core/src/session_engine/wiring.rs
index cd53733577..9ad3423ba5 100644
--- a/crates/pa-core/src/session_engine/wiring.rs
+++ b/crates/pa-core/src/session_engine/wiring.rs
@@ -135,6 +135,15 @@ impl AgentSession {
self.auto_refine = gates;
}
+ /// Bind the session's agent dir (the settings root). The refine flow
+ /// reads the `factory.enabled` opt-in from the agent dir's
+ /// settings.json on every run — the same live read the kernel-side
+ /// factory gate performs — so a session without a wired agent dir
+ /// keeps the fail-closed disabled default.
+ pub fn set_agent_dir(&mut self, agent_dir: std::path::PathBuf) {
+ self.agent_dir = Some(agent_dir);
+ }
+
/// Bind the kernel-state probe behind the post-compaction
/// `ipython_state` notice (the engine wiring hands over the session's
/// kernel provisioner, TS `AgentSession._ipythonKernelProvisioner`).
diff --git a/crates/pa-tui/src/custom_message/injected_prompt.rs b/crates/pa-tui/src/custom_message/injected_prompt.rs
index f30cee5526..7a6474eb47 100644
--- a/crates/pa-tui/src/custom_message/injected_prompt.rs
+++ b/crates/pa-tui/src/custom_message/injected_prompt.rs
@@ -3,14 +3,14 @@
//! Decode maps each custom type to its kind (TS `isInjectedPromptMessage`);
//! the render ports each header shape and the expand contract.
//!
-//! Divergence (Kevin directive 2026-09-23, product improvement beyond the
-//! TS binary): the RLM child rows render the `◆ Subagent <name>
-//! finished|failed|cancelled` diamond rows — the diamond and the label in
-//! the row's semantic color (the marker icon follows the message text's
-//! color: success green, error red, cancelled yellow), the failure error
-//! and the cancellation reason as the expandable body — where the TS
-//! binary still shows the generic muted `RLM child status` label over the
-//! full content markdown. The TS side is expected to adopt the same rows.
+//! The RLM child status notices left this class (the operator's 2026-10-01
+//! directive: "the factory child status notices should be like subagent
+//! messages not user messages" — a spawned child's exit status is
+//! child-originated mail, so those rows render in the `agent_message`
+//! class now, superseding the 2026-09-23 diamond-row divergence): the
+//! kinds here are the engine-injected turn prompts only — the heartbeat
+//! prompt, the goal context, the kernel-state restore, and the
+//! skills-unavailable report.
//!
//! Second divergence (operator directive 2026-09-23): the heartbeat prompt
//! row renders the `◷` clock glyph — the unified activity dock's
@@ -22,7 +22,6 @@ use super::render::{spacer, text_rows, truncate_text};
use super::{
custom_content_text, GOAL_CONTEXT_CUSTOM_TYPE, HEARTBEAT_PROMPT_CUSTOM_TYPE,
IPYTHON_STATE_RESTORED_CUSTOM_TYPE, PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
- RLM_CHILD_FAILURE_CUSTOM_TYPE, RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
};
use crate::chat::Detail;
use crate::theme::{Theme, ThemeColor};
@@ -55,26 +54,6 @@ pub enum InjectedPromptKind {
/// names; TS PR #2381's header — no marker glyph), expandable to the
/// full report.
PythonSkillsUnavailable { skills: Vec<String> },
- /// `◆ Subagent <name> finished|failed|cancelled` (the diamond and the
- /// label share the row's semantic color; failed/cancelled rows expand
- /// to the reason).
- RlmChildStatus {
- outcome: RlmChildOutcome,
- session_name: String,
- },
-}
-
-/// How a spawned child run ended (the `rlm_child_failure` /
-/// `rlm_child_terminal_notice` details kinds).
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RlmChildOutcome {
- /// The run finished its task (the `completed_without_reply` terminal
- /// notice; a child that replied explicitly never lands in this row).
- Finished,
- /// The run errored out.
- Failed,
- /// The parent deleted a still-running child.
- Cancelled,
}
/// One injected-prompt row (TS `isInjectedPromptMessage` kinds).
@@ -117,79 +96,24 @@ pub(crate) fn injected_prompt_row(
})
.unwrap_or_default(),
},
- RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE => InjectedPromptKind::RlmChildStatus {
- outcome: if details.get("kind").and_then(Value::as_str) == Some("cancelled") {
- RlmChildOutcome::Cancelled
- } else {
- RlmChildOutcome::Finished
- },
- session_name: rlm_child_session_name(details, &content),
- },
- RLM_CHILD_FAILURE_CUSTOM_TYPE => InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Failed,
- session_name: rlm_child_session_name(details, &content),
- },
- _ => InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Finished,
- session_name: rlm_child_session_name(details, &content),
- },
+ // The dispatch routes only this module's four kinds here; every
+ // other custom type (the RLM child status notices included — they
+ // render in the `agent_message` class now) owns its own dispatch
+ // arm, and an unknown type never reaches this function.
+ _ => unreachable!("injected_prompt_row sees only its four kinds"),
};
let body = match &kind {
// The kernel-state row stays header-only (TS keeps
- // `ipython_state_restored` header-only); a finished child carries
- // no reason to expand.
+ // `ipython_state_restored` header-only).
InjectedPromptKind::KernelRestored { .. } => None,
- InjectedPromptKind::RlmChildStatus { outcome, .. } => match outcome {
- RlmChildOutcome::Finished => None,
- RlmChildOutcome::Failed => rlm_child_reason(details, "error", &content),
- RlmChildOutcome::Cancelled => rlm_child_reason(details, "reason", &content),
- },
_ => Some(content),
};
InjectedPromptRow { kind, body }
}
-/// The child's session name: the `sessionName` details key, falling back to
-/// the `child:<name>]` token of the content header (the pre-details wire
-/// rows).
-fn rlm_child_session_name(details: &Value, content: &str) -> String {
- details
- .get("sessionName")
- .and_then(Value::as_str)
- .filter(|name| !name.is_empty())
- .map(str::to_string)
- .or_else(|| {
- content
- .split_once("child:")
- .and_then(|(_, rest)| rest.split(']').next())
- .map(str::trim)
- .filter(|name| !name.is_empty())
- .map(str::to_string)
- })
- .unwrap_or_default()
-}
-
-/// The expandable reason body of a failed/cancelled row: the details field
-/// (`error` / `reason`), falling back to the content after the
-/// `[child-...]` header (the pre-details wire rows).
-fn rlm_child_reason(details: &Value, field: &str, content: &str) -> Option<String> {
- details
- .get(field)
- .and_then(Value::as_str)
- .filter(|reason| !reason.is_empty())
- .map(str::to_string)
- .or_else(|| {
- content
- .split_once("\n\n")
- .map(|(_, reason)| reason.trim().to_string())
- .filter(|reason| !reason.is_empty())
- })
-}
-
/// One injected-prompt row (TS `InjectedPromptMessageComponent`): a leading
/// blank, the kind's header, then the guttered markdown body below it when
-/// expanded (the kernel-state and finished-child rows stay header-only in
-/// both states).
+/// expanded (the kernel-state row stays header-only in both states).
pub(crate) fn render_injected_prompt(
row: &InjectedPromptRow,
detail: Detail,
@@ -259,31 +183,6 @@ fn prompt_header(row: &InjectedPromptRow, theme: &Theme) -> Line {
}
spans
}
- InjectedPromptKind::RlmChildStatus {
- outcome,
- session_name,
- } => {
- // One color source of truth: the diamond marker carries the
- // row's semantic color (the same style the label renders in),
- // so the icon follows the message text instead of the fixed
- // accent (operator directive 2026-09-23).
- let (label, color) = match outcome {
- RlmChildOutcome::Finished => ("finished", ThemeColor::Success),
- RlmChildOutcome::Failed => ("failed", ThemeColor::Error),
- RlmChildOutcome::Cancelled => ("cancelled", ThemeColor::Warning),
- };
- let label = if session_name.is_empty() {
- format!("Subagent {label}")
- } else {
- format!("Subagent {session_name} {label}")
- };
- let color = theme.fg_style(color);
- vec![
- Span::styled("\u{25c6}".to_string(), color),
- Span::raw(" "),
- Span::styled(label, color),
- ]
- }
};
header
}
@@ -370,16 +269,6 @@ mod tests {
row.iter().map(|s| s.content.as_str()).collect()
}
- fn decoded_row(value: &serde_json::Value) -> InjectedPromptRow {
- let entry = super::super::custom_message_entries(value)
- .pop()
- .expect("one entry");
- match entry {
- crate::chat::ChatEntry::InjectedPrompt(boxed) => *boxed,
- other => panic!("not an injected prompt: {other:?}"),
- }
- }
-
#[test]
fn heartbeat_header_and_schedule_forms() {
assert_eq!(heartbeat_schedule(Some("every 10m")), "every 10m");
@@ -531,170 +420,4 @@ mod tests {
assert_eq!(flat(&rows[1]).trim_end(), format!(" \u{25c6} {label}"));
}
}
-
- #[test]
- fn rlm_child_rows_decode_the_outcome_and_name() {
- // The failure row: Failed outcome, the error as the body.
- let row = decoded_row(&serde_json::json!({
- "role": "custom",
- "customType": RLM_CHILD_FAILURE_CUSTOM_TYPE,
- "content": "[child-failed child:boom-worker]\n\nthe model stream died",
- "display": true,
- "details": { "childId": "sub-1", "sessionName": "boom-worker", "error": "the model stream died" },
- }));
- assert_eq!(
- row.kind,
- InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Failed,
- session_name: "boom-worker".to_string(),
- }
- );
- assert_eq!(row.body.as_deref(), Some("the model stream died"));
- // The cancelled terminal notice: Warning outcome, the reason body.
- let row = decoded_row(&serde_json::json!({
- "role": "custom",
- "customType": RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
- "content": "[child-exited: cancelled child:cancel-worker]\n\nDeleted by parent",
- "display": true,
- "details": {
- "kind": "cancelled", "childId": "sub-2", "sessionName": "cancel-worker",
- "reason": "Deleted by parent",
- },
- }));
- assert_eq!(
- row.kind,
- InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Cancelled,
- session_name: "cancel-worker".to_string(),
- }
- );
- assert_eq!(row.body.as_deref(), Some("Deleted by parent"));
- // The finished terminal notice: no body, no reply preview (the
- // last-assistant-text preview stays out of the row).
- let row = decoded_row(&serde_json::json!({
- "role": "custom",
- "customType": RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
- "content": "[child-exited: no-reply child:lane]\n\nLast assistant text: done",
- "display": true,
- "details": {
- "kind": "completed_without_reply", "childId": "sub-3", "sessionName": "lane",
- "lastAssistantTextPreview": "done",
- },
- }));
- assert_eq!(
- row.kind,
- InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Finished,
- session_name: "lane".to_string(),
- }
- );
- assert_eq!(row.body, None);
- // A cancellation without a reason stays header-only.
- let row = decoded_row(&serde_json::json!({
- "role": "custom",
- "customType": RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
- "content": "[child-exited: cancelled child:quiet]",
- "display": true,
- "details": {
- "kind": "cancelled", "childId": "sub-4", "sessionName": "quiet", "reason": null,
- },
- }));
- assert_eq!(row.body, None);
- }
-
- #[test]
- fn rlm_child_rows_fall_back_to_the_content_header() {
- // Pre-details wire rows: the name comes from the `child:<name>]`
- // content token, the reason from the content after the header.
- let row = decoded_row(&serde_json::json!({
- "role": "custom",
- "customType": RLM_CHILD_FAILURE_CUSTOM_TYPE,
- "content": "[child-failed child:legacy-worker]\n\nspawn failed",
- "display": true,
- "details": serde_json::Value::Null,
- }));
- assert_eq!(
- row.kind,
- InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Failed,
- session_name: "legacy-worker".to_string(),
- }
- );
- assert_eq!(row.body.as_deref(), Some("spawn failed"));
- }
-
- #[test]
- fn rlm_child_rows_render_the_diamond_labels() {
- let theme = theme();
- for (outcome, session_name, label, color) in [
- (
- RlmChildOutcome::Finished,
- "lane",
- "Subagent lane finished",
- ThemeColor::Success,
- ),
- (
- RlmChildOutcome::Failed,
- "boom-worker",
- "Subagent boom-worker failed",
- ThemeColor::Error,
- ),
- (
- RlmChildOutcome::Cancelled,
- "cancel-worker",
- "Subagent cancel-worker cancelled",
- ThemeColor::Warning,
- ),
- ] {
- let row = InjectedPromptRow {
- kind: InjectedPromptKind::RlmChildStatus {
- outcome,
- session_name: session_name.to_string(),
- },
- body: None,
- };
- let rows = render_injected_prompt(&row, Detail::Overview, &theme, 60);
- assert_eq!(rows.len(), 2, "{rows:?}");
- assert_eq!(flat(&rows[1]).trim_end(), format!(" \u{25c6} {label}"));
- // The diamond and the label share the row's semantic color:
- // the icon follows the message text (operator directive
- // 2026-09-23), never the fixed accent.
- let color = theme.fg_style(color);
- assert_eq!(rows[1][1], Span::styled("\u{25c6}".to_string(), color));
- assert_eq!(rows[1][3], Span::styled(label, color));
- assert_ne!(color, theme.fg_style(ThemeColor::Accent));
- }
- }
-
- #[test]
- fn rlm_child_status_expand_contract() {
- // The finished row stays header-only in both states.
- let row = InjectedPromptRow {
- kind: InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Finished,
- session_name: "lane".to_string(),
- },
- body: None,
- };
- let expanded = render_injected_prompt(&row, Detail::All, &theme(), 60);
- assert_eq!(expanded.len(), 2, "header-only expanded: {expanded:?}");
- assert_eq!(
- flat(&expanded[1]).trim_end(),
- " \u{25c6} Subagent lane finished"
- );
- // The failed row keeps the header and renders the error body.
- let row = InjectedPromptRow {
- kind: InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Failed,
- session_name: "boom-worker".to_string(),
- },
- body: Some("the model stream died".to_string()),
- };
- let expanded = render_injected_prompt(&row, Detail::All, &theme(), 60);
- assert!(expanded.len() > 2, "body renders expanded: {expanded:?}");
- assert_eq!(
- flat(&expanded[1]).trim_end(),
- " \u{25c6} Subagent boom-worker failed"
- );
- }
}
diff --git a/crates/pa-tui/src/custom_message/mod.rs b/crates/pa-tui/src/custom_message/mod.rs
index 6e5f9b05df..421cc6ea57 100644
--- a/crates/pa-tui/src/custom_message/mod.rs
+++ b/crates/pa-tui/src/custom_message/mod.rs
@@ -20,6 +20,15 @@
//! `[<customType>]` panel. (The TS replay path `buildConversationComponents`
//! drops unknown types instead; the live interactive path is the TUI ground
//! truth, and the Rust engine persists those types with `display: false`.)
+//!
+//! Divergence (the operator's 2026-10-01 directive: "the factory child
+//! status notices should be like subagent messages not user messages"): the
+//! RLM child status notices (`rlm_child_terminal_notice` /
+//! `rlm_child_failure`) render in the `agent_message` component's class —
+//! child-originated mail, attributed to the exited subagent — where the TS
+//! dispatch classes them as injected-prompt rows (turn prompts). The
+//! notices still drive their turn (the daemon's `followUp` notice action is
+//! unchanged); only the transcript row's class moves.
pub(crate) mod geometry;
pub(crate) use geometry::agent_message_body_count;
@@ -31,7 +40,7 @@ pub mod skill_invocation;
pub use skill_invocation::{skill_invocation_entries, SkillInvocationRow};
use injected_prompt::injected_prompt_row;
-pub use injected_prompt::{InjectedPromptKind, InjectedPromptRow, RlmChildOutcome};
+pub use injected_prompt::{InjectedPromptKind, InjectedPromptRow};
use crate::chat::{ChatEntry, StatusKind};
use crate::theme::ThemeColor;
@@ -171,8 +180,9 @@ pub struct CustomPanelRow {
/// The transcript entries for one `custom`-role message, mirroring the TS
/// dispatch order: slash rows, compaction and refinement outcomes, agent
-/// messages, shell completions, injected prompts, then the generic panel.
-/// Non-display rows render nothing.
+/// messages (the received agent-message rows and the RLM child status
+/// notices, the same class), shell completions, injected prompts, then the
+/// generic panel. Non-display rows render nothing.
pub fn custom_message_entries(message: &Value) -> Vec<ChatEntry> {
use pa_types::slash_commands::{
SESSION_SLASH_COMMAND_CUSTOM_TYPE, SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE,
@@ -219,15 +229,26 @@ pub fn custom_message_entries(message: &Value) -> Vec<ChatEntry> {
HEARTBEAT_PROMPT_CUSTOM_TYPE
| GOAL_CONTEXT_CUSTOM_TYPE
| IPYTHON_STATE_RESTORED_CUSTOM_TYPE
- | PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE
- | RLM_CHILD_FAILURE_CUSTOM_TYPE
- | RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE => {
+ | PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE => {
vec![ChatEntry::InjectedPrompt(Box::new(injected_prompt_row(
custom_type,
message,
details,
)))]
}
+ // The RLM child status notices are child-originated mail — the
+ // spawned subagent's exit status (a factory's children included) —
+ // so they render in the same quiet, counterpart-attributed
+ // `Agent message` class the children's own `agent_message` rows
+ // use (the operator's 2026-10-01 directive: "the factory child
+ // status notices should be like subagent messages not user
+ // messages"), not as turn-prompt rows. The notice text rides as
+ // the row body, so nothing is lost.
+ RLM_CHILD_FAILURE_CUSTOM_TYPE | RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE => {
+ vec![ChatEntry::AgentMessage(Box::new(rlm_child_status_row(
+ message, details,
+ )))]
+ }
// Everything else - engine bookkeeping (`harness_digest`,
// `refinement_notice`, worker recovery) and unknown types - renders
// the generic panel, exactly like the TS live dispatch fallthrough
@@ -354,6 +375,39 @@ fn agent_message_entry(details: &Value) -> Option<ChatEntry> {
})))
}
+/// One RLM child status notice (`rlm_child_terminal_notice` /
+/// `rlm_child_failure`) as the subagent-mail row: the child that exited is
+/// the mail's counterpart, the notice text is the body (the full content,
+/// header included, so the outcome wording rides intact).
+fn rlm_child_status_row(message: &Value, details: &Value) -> AgentMessageRow {
+ let content = custom_content_text(message);
+ AgentMessageRow {
+ direction: AgentMessageDirection::Received,
+ counterpart: rlm_child_session_name(details, &content),
+ message: content,
+ }
+}
+
+/// The child's session name: the `sessionName` details key, falling back to
+/// the `child:<name>]` token of the content header (the pre-details wire
+/// rows), then the agent-message row's `unknown`.
+fn rlm_child_session_name(details: &Value, content: &str) -> String {
+ details
+ .get("sessionName")
+ .and_then(Value::as_str)
+ .filter(|name| !name.is_empty())
+ .map(str::to_string)
+ .or_else(|| {
+ content
+ .split_once("child:")
+ .and_then(|(_, rest)| rest.split(']').next())
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ .map(str::to_string)
+ })
+ .unwrap_or_else(|| "unknown".to_string())
+}
+
/// TS `readShellCompletion` + `ShellCompletionComponent.render`: a valid
/// completion needs an object details block with a positive-integer `pid`,
/// a string `command`, and an integer `exitCode`; anything else renders the
@@ -608,56 +662,78 @@ mod tests {
));
}
- /// The RLM child rows decode the outcome and the session name (the
- /// render shapes live with the kind, in `injected_prompt`).
+ /// The RLM child status notices decode to the subagent-mail class
+ /// (the operator's 2026-10-01 directive: "the factory child status
+ /// notices should be like subagent messages not user messages"): the
+ /// row carries the child as its counterpart and the notice text as
+ /// the body, and it never renders as a turn-prompt (injected) or
+ /// user row — the class assertion is the mutation pin (routing the
+ /// types back through the injected-prompt arm fails it).
#[test]
- fn rlm_child_and_unavailable_rows_decode() {
- let failed = decoded(&json!({
- "role": "custom",
- "customType": RLM_CHILD_FAILURE_CUSTOM_TYPE,
- "content": "[child-failed child:lane]\n\nboom",
- "display": true,
- "details": { "childId": "sub-1", "sessionName": "lane", "error": "boom" },
- }));
- assert!(matches!(
- failed.as_slice(),
- [ChatEntry::InjectedPrompt(boxed)]
- if matches!(
- &boxed.kind,
- InjectedPromptKind::RlmChildStatus {
- outcome: RlmChildOutcome::Failed,
- session_name,
- } if session_name == "lane"
- ) && boxed.body.as_deref() == Some("boom")
- ));
- for (kind, outcome) in [
- ("completed_without_reply", RlmChildOutcome::Finished),
- ("cancelled", RlmChildOutcome::Cancelled),
- ] {
- let row = decoded(&json!({
+ fn rlm_child_notice_rows_decode_to_the_agent_message_class() {
+ let notices = [
+ (
+ RLM_CHILD_FAILURE_CUSTOM_TYPE,
+ "[child-failed child:lane]\n\nboom",
+ json!({ "childId": "sub-1", "sessionName": "lane", "error": "boom" }),
+ ),
+ (
+ RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
+ "[child-exited: no-reply child:lane]\n\nLast assistant text: done",
+ json!({ "childId": "sub-2", "sessionName": "lane", "kind": "completed_without_reply" }),
+ ),
+ (
+ RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
+ "[child-exited: cancelled child:cancel-worker]\n\nDeleted by parent",
+ json!({ "childId": "sub-3", "sessionName": "cancel-worker", "kind": "cancelled", "reason": "Deleted by parent" }),
+ ),
+ ];
+ for (custom_type, content, details) in notices {
+ let entries = decoded(&json!({
"role": "custom",
- "customType": RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
- "content": "[child-exited: no-reply child:lane]",
+ "customType": custom_type,
+ "content": content,
"display": true,
- "details": { "childId": "sub-2", "sessionName": "lane", "kind": kind },
+ "details": details,
}));
- // Neither fixture carries a reason, so both stay
- // header-only.
+ let row = match entries.as_slice() {
+ [ChatEntry::AgentMessage(row)] => row,
+ other => panic!("{custom_type} must decode to the agent-message class: {other:?}"),
+ };
+ assert_eq!(row.direction, AgentMessageDirection::Received);
+ assert_eq!(row.counterpart, details["sessionName"]);
+ // The content rides intact as the body (outcome wording and
+ // the child's last text included).
+ assert_eq!(row.message, content);
assert!(
- matches!(
- row.as_slice(),
- [ChatEntry::InjectedPrompt(boxed)]
- if matches!(
- &boxed.kind,
- InjectedPromptKind::RlmChildStatus { outcome: decoded_outcome, .. }
- if decoded_outcome == &outcome
- ) && boxed.body.is_none()
+ !matches!(
+ entries.as_slice(),
+ [ChatEntry::InjectedPrompt(_) | ChatEntry::User { .. }]
),
- "outcome {outcome:?} of kind {kind:?} did not decode"
+ "{custom_type} must not render as a turn-prompt/user row"
);
}
- // The unavailable-skills row decodes the failed names and keeps
- // the full report as its expandable body.
+ // The pre-details wire rows keep their identity: the name comes
+ // from the `child:<name>]` content token.
+ let entries = decoded(&json!({
+ "role": "custom",
+ "customType": RLM_CHILD_FAILURE_CUSTOM_TYPE,
+ "content": "[child-failed child:legacy-worker]\n\nspawn failed",
+ "display": true,
+ "details": serde_json::Value::Null,
+ }));
+ assert!(matches!(
+ entries.as_slice(),
+ [ChatEntry::AgentMessage(row)]
+ if row.counterpart == "legacy-worker"
+ && row.message == "[child-failed child:legacy-worker]\n\nspawn failed"
+ ));
+ }
+
+ /// The unavailable-skills row decodes the failed names and keeps the
+ /// full report as its expandable body.
+ #[test]
+ fn python_skills_unavailable_row_decodes() {
let unavailable = decoded(&json!({
"role": "custom",
"customType": PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
diff --git a/crates/pa-tui/src/view/geometry.rs b/crates/pa-tui/src/view/geometry.rs
index 00c2969ec9..8dbf6231b7 100644
--- a/crates/pa-tui/src/view/geometry.rs
+++ b/crates/pa-tui/src/view/geometry.rs
@@ -305,20 +305,6 @@ mod tests {
any::<bool>().prop_map(|restored| InjectedPromptKind::KernelRestored { restored }),
prop::collection::vec("[a-z 数据]{1,12}", 0..4)
.prop_map(|skills| InjectedPromptKind::PythonSkillsUnavailable { skills }),
- (
- prop::sample::select(vec![
- RlmChildOutcome::Finished,
- RlmChildOutcome::Failed,
- RlmChildOutcome::Cancelled,
- ]),
- "[a-z 数据]{1,12}",
- )
- .prop_map(|(outcome, session_name)| {
- InjectedPromptKind::RlmChildStatus {
- outcome,
- session_name,
- }
- }),
]
}
diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py
index ec62243a10..0836e9513c 100644
--- a/prime-agent-runtime/src/rlm/__init__.py
+++ b/prime-agent-runtime/src/rlm/__init__.py
@@ -9,6 +9,7 @@ from pathlib import Path
from typing import Any
from .bash import BashHandle, BashResult, bash
+from .factory import FACTORY_HELP, resume_factory, run_factory, status_factory, stop_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')"
@@ -527,6 +528,43 @@ class _HarnessProxy:
_harness_state = _HarnessProxy()
+class _RLMFactoryNamespace:
+ """Run stored state-machine factories: rlm.factory.run/status/stop/resume.
+
+ ``run('<spec_id>')`` validates a stored factory entry (machine form, or
+ dag sugar that compiles to one), enters the entry states up to the
+ spec's max_parallel, and returns immediately; a kernel asyncio task
+ continues the run (nonblocking control loop). Runs live in kernel
+ memory only; children stay supervisor-owned. Every call is async, so
+ always await it: ``await rlm.factory.run('<id>')``.
+
+ The factory is opt-in: while the ``factory.enabled`` setting is off (the
+ default; the user turns it on with ``/factory on``), every call above
+ refuses with one clean message and only ``help()`` answers, so the
+ guide stays readable before opting in.
+
+ ``help()`` returns the full embedded authoring reference and API guide
+ (states, ports, guards, joins, foreach, budgets, and the API with
+ worked examples): ``rlm.factory.help()``.
+ """
+
+ async def run(self, spec_id: str, *, name: str | None = None) -> dict[str, Any]:
+ return await run_factory(spec_id, name=name)
+
+ async def status(self, run_id: str) -> dict[str, Any]:
+ return await status_factory(run_id)
+
+ async def stop(self, run_id: str) -> dict[str, Any]:
+ return await stop_factory(run_id)
+
+ async def resume(self, run_id: str) -> dict[str, Any]:
+ return await resume_factory(run_id)
+
+ def help(self) -> str:
+ """Return the embedded factory authoring reference and API guide."""
+ return FACTORY_HELP
+
+
class _RLMNamespace:
harness = _harness_state
get_harness_state = staticmethod(get_harness_state)
@@ -566,6 +604,8 @@ class _RLMNamespace:
async def collect(self, targets: Any = None, *, timeout_ms: int = 0) -> list[RLMChildResult]:
return await collect(targets, timeout_ms=timeout_ms)
+ factory = _RLMFactoryNamespace()
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
raise TypeError(_NOT_CALLABLE_MESSAGE)
diff --git a/prime-agent-runtime/src/rlm/factory.py b/prime-agent-runtime/src/rlm/factory.py
new file mode 100644
index 0000000000..2bfc2e86ee
--- /dev/null
+++ b/prime-agent-runtime/src/rlm/factory.py
@@ -0,0 +1,3111 @@
+"""Validation and compilation for factory specifications.
+
+A continual-harness ``factory`` entry stores a declarative state machine of
+subagent states in ``arguments["machine"]``: entry states (which declare
+no inputs), guarded transitions between states, and bounded re-entry
+(``max_entries``). The original DAG form in ``arguments["dag"]`` stays as
+sugar: it compiles to machine form (each node becomes a state entered
+once; a node's full effective dependency set compiles to ONE join
+transition that waits for every predecessor, so fan-in nodes never start
+after a single parent settles with a blocked second transition). Wait
+states are specified for the communication series but gated here:
+the watch host handlers (``rlm.watch.*``) do not exist yet, so a state
+carrying a ``wait`` block is rejected at write time.
+
+This module implements the write-time dry run for both forms -- the machine
+validator, the dag-to-machine compiler, the unified entry point
+(``validate_factory_spec`` detects the form), and a canonicalizer that
+applies defaults and returns the canonical MACHINE form -- plus the
+executor (``FactoryExecutor`` and the ``rlm.factory`` namespace:
+run/status/stop/resume) that runs canonicalized machines through the
+existing RLM supervisor: states are admitted with ``rlm.spawn``, settled
+through ``rlm.collect``, and cancelled with ``rlm.delete_subagent``. The
+supervisor owns the children; the executor owns the run state in kernel
+memory. Runs do not survive a kernel restart (the registry lives in this
+module's state); children are supervisor-owned and keep running, so
+``rlm.list_subagents`` can still see them after a restart.
+
+The full agent-facing reference — authoring rules, guards/joins/cycles,
+foreach, budgets, stall detectors, and the ``rlm.factory`` API with worked
+examples — is embedded in this module as ``FACTORY_HELP``;
+``rlm.factory.help()`` returns it with no filesystem resolution, so
+packaged kernels (where the repo layout is not adjacent) see the same
+guide.
+
+The namespace is opt-in: while the ``factory.enabled`` setting is off (the
+default; the user turns it on with ``/factory on``), every ``rlm.factory``
+call except ``help()`` and every factory harness write refuses with one
+clean message (``FACTORY_DISABLED_MESSAGE``), never a crash.
+"""
+
+from __future__ import annotations
+
+import copy
+import hashlib
+import heapq
+import json
+import re
+import time
+from dataclasses import dataclass, field
+from typing import Any, Callable
+from uuid import uuid4
+
+FAILURE_POLICIES: tuple[str, ...] = ("fail_fast", "continue", "escalate")
+PORT_TYPES: tuple[str, ...] = ("text", "json")
+LIFECYCLES: tuple[str, ...] = ("task", "resident")
+TRANSITION_ON_KINDS: tuple[str, ...] = ("settled",)
+GUARD_OPS: tuple[str, ...] = ("eq", "ne", "gt", "gte", "lt", "lte", "exists", "contains")
+MAX_NODES = 1024
+MAX_STATES = MAX_NODES
+MAX_RETRIES = 10
+MAX_PARALLEL_MIN = 1
+MAX_PARALLEL_MAX = 64
+FOREACH_MAX_MIN = 1
+FOREACH_MAX_MAX = 256
+MAX_TRANSITIONS_CAP = 10_000
+MAX_CHILDREN_CAP = 1_000_000
+TRANSITIONS_PER_STATE_DEFAULT = 10
+RUN_FAILURE_POLICY_DEFAULT = "escalate"
+RUN_MAX_PARALLEL_DEFAULT = 8
+RUN_MAX_CHILDREN_DEFAULT = 10_000
+NODE_LIFECYCLE_DEFAULT = "task"
+NODE_RETRIES_DEFAULT = 0
+STATE_ENTRY_DEFAULT = False
+STATE_MAX_ENTRIES_DEFAULT = 1
+#: An inline subagent ``name`` labels the spawned children; the host caps
+#: subagent session names at 64 characters (the same limit the generated
+#: label stays under), so a longer configured name is rejected at write
+#: time instead of failing every spawn admission.
+SUBAGENT_NAME_MAX_LENGTH = 64
+
+_NODE_ID_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{0,63}")
+
+
+def _is_int(value: Any) -> bool:
+ """True for real integers; booleans are not accepted as ints."""
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def _is_number(value: Any) -> bool:
+ """True for real numbers; booleans are not accepted as numbers."""
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _is_scalar(value: Any) -> bool:
+ """True for JSON scalars (str, int, float, bool, None); lists and objects are not."""
+ return value is None or isinstance(value, (str, int, float, bool))
+
+
+def _is_positive_int(value: Any) -> bool:
+ return _is_int(value) and value > 0
+
+
+def _is_nonempty_str(value: Any) -> bool:
+ return isinstance(value, str) and value != ""
+
+
+def _valid_node_id(value: Any) -> bool:
+ return _is_nonempty_str(value) and _NODE_ID_PATTERN.fullmatch(value) is not None
+
+
+def _port_list(node: dict[str, Any], key: str) -> list[Any]:
+ """Return the node's inputs/outputs list, or [] when absent or malformed."""
+ raw = node.get(key)
+ return raw if isinstance(raw, list) else []
+
+
+def _declared_port_types(node: dict[str, Any], key: str) -> dict[str, str]:
+ """Map port name to type for well-formed entries of the node's port list."""
+ ports: dict[str, str] = {}
+ for entry in _port_list(node, key):
+ if isinstance(entry, dict):
+ name, port_type = entry.get("name"), entry.get("type")
+ if _is_nonempty_str(name) and port_type in PORT_TYPES:
+ ports[name] = port_type
+ return ports
+
+
+def _effective_output_types(state: dict[str, Any]) -> dict[str, str]:
+ """Output ports readable from a state: its declared outputs."""
+ return _declared_port_types(state, "outputs")
+
+
+def _input_sources(node: dict[str, Any]) -> list[str]:
+ """Source node ids referenced by the node's inputs."""
+ sources: list[str] = []
+ for inp in _port_list(node, "inputs"):
+ if not isinstance(inp, dict):
+ continue
+ source = inp.get("from")
+ if isinstance(source, str) and "." in source:
+ sources.append(source.partition(".")[0])
+ return sources
+
+
+def _is_machine_form(spec: Any) -> bool:
+ """Machine form wins whenever a states/transitions key is present."""
+ return isinstance(spec, dict) and ("states" in spec or "transitions" in spec)
+
+
+# ---------------------------------------------------------------------------
+# Shared field checks (used by both the dag compiler and the machine validator).
+# ---------------------------------------------------------------------------
+
+
+def _validate_run_fields(run: Any, errors: list[str]) -> int | None:
+ """Shared run-block checks. Returns the run budget when valid, else None.
+
+ ``run`` must already be a dict or None; the caller reports "run must be
+ an object" for other shapes.
+ """
+ if not isinstance(run, dict):
+ return None
+ # Typed fields are validated by PRESENCE, not by "is not None": an
+ # explicit JSON null (run.max_parallel: null) must be rejected with the
+ # field's own message, never silently treated as an omitted default
+ # (a null that survived canonicalization reached the executor without a
+ # usable typed limit).
+ if "budget_ms" in run and not _is_positive_int(run.get("budget_ms")):
+ errors.append("run budget_ms must be a positive integer")
+ run_budget = run.get("budget_ms") if _is_positive_int(run.get("budget_ms")) else None
+ if "failure_policy" in run and run.get("failure_policy") not in FAILURE_POLICIES:
+ errors.append(f"run failure_policy must be one of {list(FAILURE_POLICIES)}, got {run.get('failure_policy')!r}")
+ max_parallel = run.get("max_parallel")
+ if "max_parallel" in run and not (
+ _is_int(max_parallel) and MAX_PARALLEL_MIN <= max_parallel <= MAX_PARALLEL_MAX
+ ):
+ errors.append(f"run max_parallel must be an integer between {MAX_PARALLEL_MIN} and {MAX_PARALLEL_MAX}")
+ max_transitions = run.get("max_transitions")
+ if "max_transitions" in run and not (
+ _is_positive_int(max_transitions) and max_transitions <= MAX_TRANSITIONS_CAP
+ ):
+ errors.append(f"run max_transitions must be a positive integer no greater than {MAX_TRANSITIONS_CAP}")
+ max_children = run.get("max_children")
+ if "max_children" in run and not (
+ _is_positive_int(max_children) and max_children <= MAX_CHILDREN_CAP
+ ):
+ errors.append(f"run max_children must be a positive integer no greater than {MAX_CHILDREN_CAP}")
+ return run_budget
+
+
+def _validate_state_fields(
+ state: dict[str, Any],
+ *,
+ run_budget: int | None,
+ states_by_id: dict[str, dict[str, Any]],
+ noun: str,
+ errors: list[str],
+) -> None:
+ """Field rules shared by dag nodes (noun="node") and machine states
+ (noun="state"): subagent forms, lifecycle, budgets, retries, failure
+ policies, port lists, foreach, and the resident exclusions."""
+ ref = state["id"]
+ # Presence-based checks like the run block: an explicit JSON null on a
+ # typed field is rejected with the field's own message instead of
+ # surviving canonicalization as None.
+ lifecycle = state.get("lifecycle", NODE_LIFECYCLE_DEFAULT)
+ if "lifecycle" in state and lifecycle not in LIFECYCLES:
+ errors.append(f"{noun} {ref} lifecycle must be 'task' or 'resident', got {lifecycle!r}")
+ is_resident = lifecycle == "resident"
+
+ if state.get("wait") is not None:
+ # Gated: the watch host handlers (rlm.watch.*) arrive with the
+ # communication series; a wait block would silently no-op until then.
+ errors.append(
+ f"{noun} {ref}: wait states require the watch host handlers (rlm.watch.*); "
+ "they arrive with the communication series - remove the wait block until then"
+ )
+
+ subagent = state.get("subagent")
+ if _is_nonempty_str(subagent):
+ pass # Harness subagent entry id or title; resolved at run time.
+ elif isinstance(subagent, dict):
+ # Runtime resolution strips these fields (_resolve_subagents /
+ # _validate_spawn_settings), so whitespace-only values are rejected
+ # here too: a persistable factory must be spawnable.
+ if not isinstance(subagent.get("prompt"), str) or not subagent.get("prompt").strip():
+ errors.append(f"{noun} {ref} inline subagent requires a non-empty prompt")
+ for key in ("name", "model", "thinking"):
+ value = subagent.get(key)
+ if value is not None and (not isinstance(value, str) or not value.strip()):
+ errors.append(f"{noun} {ref} inline subagent {key} must be a non-empty string when provided")
+ configured_name = subagent.get("name")
+ if isinstance(configured_name, str) and len(configured_name.strip()) > SUBAGENT_NAME_MAX_LENGTH:
+ errors.append(
+ f"{noun} {ref} inline subagent name must be at most "
+ f"{SUBAGENT_NAME_MAX_LENGTH} characters, got {len(configured_name.strip())}"
+ )
+ else:
+ errors.append(
+ f"{noun} {ref} requires a subagent: a harness subagent id/title string "
+ "or an inline object with a prompt"
+ )
+
+ if "budget_ms" in state:
+ budget = state.get("budget_ms")
+ if not _is_positive_int(budget):
+ errors.append(f"{noun} {ref} budget_ms must be a positive integer")
+ elif run_budget is not None and budget > run_budget:
+ errors.append(f"{noun} {ref} budget_ms {budget} exceeds the run budget_ms {run_budget}")
+
+ if "retries" in state and not (_is_int(state.get("retries")) and 0 <= state.get("retries") <= MAX_RETRIES):
+ errors.append(f"{noun} {ref} retries must be an integer between 0 and {MAX_RETRIES}")
+
+ if "failure_policy" in state and state.get("failure_policy") not in FAILURE_POLICIES:
+ errors.append(
+ f"{noun} {ref} failure_policy must be one of {list(FAILURE_POLICIES)}, got {state.get('failure_policy')!r}"
+ )
+
+ outputs = state.get("outputs")
+ if outputs is not None and not isinstance(outputs, list):
+ errors.append(f"{noun} {ref} outputs must be a list")
+ elif is_resident and isinstance(outputs, list) and outputs:
+ errors.append(f"resident {noun} {ref} cannot declare outputs")
+ # Duplicate ports are tracked with seen sets (one pass over the list):
+ # a rebuild-and-count scan is quadratic in the port count, and a state
+ # with tens of thousands of ports would block write-time validation.
+ seen_output_names: set[Any] = set()
+ reported_duplicate_outputs: set[Any] = set()
+ for index, out in enumerate(_port_list(state, "outputs")):
+ if not isinstance(out, dict):
+ errors.append(f"{noun} {ref} outputs[{index}] must be an object")
+ continue
+ name, port_type = out.get("name"), out.get("type")
+ if not _is_nonempty_str(name):
+ errors.append(f"{noun} {ref} outputs[{index}] requires a non-empty name")
+ elif name in seen_output_names:
+ if name not in reported_duplicate_outputs:
+ reported_duplicate_outputs.add(name)
+ errors.append(f"{noun} {ref} declares duplicate output name {name!r}")
+ else:
+ seen_output_names.add(name)
+ if port_type not in PORT_TYPES:
+ errors.append(f"{noun} {ref} output {name!r} type must be 'text' or 'json'")
+
+ inputs = state.get("inputs")
+ if inputs is not None and not isinstance(inputs, list):
+ errors.append(f"{noun} {ref} inputs must be a list")
+ seen_input_names: set[Any] = set()
+ reported_duplicate_inputs: set[Any] = set()
+ # One output-type map per source state (a rebuild per input line would
+ # make validating many inputs from one source quadratic in the source's
+ # output count).
+ output_types_by_source: dict[str, dict[str, str]] = {}
+ for index, inp in enumerate(_port_list(state, "inputs")):
+ if not isinstance(inp, dict):
+ errors.append(f"{noun} {ref} inputs[{index}] must be an object")
+ continue
+ name, port_type, source = inp.get("name"), inp.get("type"), inp.get("from")
+ optional = inp.get("optional")
+ if optional is not None and not isinstance(optional, bool):
+ errors.append(f"{noun} {ref} input {name!r} optional must be a boolean when provided")
+ if not _is_nonempty_str(name):
+ errors.append(f"{noun} {ref} inputs[{index}] requires a non-empty name")
+ elif name in seen_input_names:
+ if name not in reported_duplicate_inputs:
+ reported_duplicate_inputs.add(name)
+ errors.append(f"{noun} {ref} declares duplicate input name {name!r}")
+ else:
+ seen_input_names.add(name)
+ if port_type not in PORT_TYPES:
+ errors.append(f"{noun} {ref} input {name!r} type must be 'text' or 'json'")
+ if not isinstance(source, str) or "." not in source:
+ errors.append(
+ f"{noun} {ref} input {name!r} requires a 'from' reference of the form '<node_id>.<output_name>'"
+ )
+ continue
+ src_id, _, src_output = source.partition(".")
+ if src_id not in states_by_id:
+ errors.append(f"{noun} {ref} input {name!r} references unknown {noun} {src_id!r}")
+ continue
+ src = states_by_id[src_id]
+ if src.get("lifecycle", NODE_LIFECYCLE_DEFAULT) == "resident":
+ errors.append(f"{noun} {ref} input {name!r} cannot read from resident {noun} {src_id!r}")
+ continue
+ if src_id not in output_types_by_source:
+ output_types_by_source[src_id] = _effective_output_types(src)
+ src_output_types = output_types_by_source[src_id]
+ if src_output not in src_output_types:
+ errors.append(
+ f"{noun} {ref} input {name!r} references output {src_output!r} "
+ f"that {noun} {src_id!r} does not declare"
+ )
+ elif port_type in PORT_TYPES and src_output_types[src_output] != port_type:
+ errors.append(
+ f"{noun} {ref} input {name!r} of type {port_type!r} cannot read from "
+ f"output {src_output!r} of type {src_output_types[src_output]!r}"
+ )
+
+ foreach = state.get("foreach")
+ if foreach is not None:
+ if is_resident:
+ errors.append(f"resident {noun} {ref} cannot use foreach")
+ if not isinstance(foreach, dict):
+ errors.append(f"{noun} {ref} foreach must be an object")
+ else:
+ over = foreach.get("over")
+ if not _is_nonempty_str(over):
+ errors.append(f"{noun} {ref} foreach.over must be a non-empty input name")
+ else:
+ declared_inputs = _declared_port_types(state, "inputs")
+ if over not in declared_inputs:
+ errors.append(
+ f"{noun} {ref} foreach.over must name one of this {noun}'s inputs, got {over!r}"
+ )
+ elif declared_inputs[over] != "json":
+ errors.append(f"{noun} {ref} foreach.over input {over!r} must have type 'json'")
+ foreach_max = foreach.get("max")
+ if not (_is_int(foreach_max) and FOREACH_MAX_MIN <= foreach_max <= FOREACH_MAX_MAX):
+ errors.append(
+ f"{noun} {ref} foreach.max must be an integer between {FOREACH_MAX_MIN} and {FOREACH_MAX_MAX}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Machine-form validation.
+# ---------------------------------------------------------------------------
+
+
+def _validate_guard(
+ when: Any,
+ index: int,
+ src_state: dict[str, Any],
+ errors: list[str],
+) -> None:
+ if not isinstance(when, dict):
+ errors.append(f"transitions[{index}] when must be an object")
+ return
+ output = when.get("output")
+ src_types = _effective_output_types(src_state)
+ if not _is_nonempty_str(output):
+ errors.append(f"transitions[{index}] when requires a non-empty output")
+ elif output not in src_types:
+ errors.append(
+ f"transitions[{index}] when.output {output!r} is not a declared "
+ f"output of state {src_state.get('id')!r}"
+ )
+ else:
+ path = when.get("path")
+ if path is not None:
+ if not _is_nonempty_str(path):
+ errors.append(f"transitions[{index}] when.path must be a non-empty dotted path")
+ elif src_types[output] != "json":
+ errors.append(
+ f"transitions[{index}] when.path requires a json output, got text output {output!r}"
+ )
+ op = when.get("op")
+ if op not in GUARD_OPS:
+ errors.append(f"transitions[{index}] when.op must be one of {list(GUARD_OPS)}, got {op!r}")
+ return
+ if op == "exists":
+ return # existence carries no value
+ value = when.get("value")
+ if op in ("gt", "gte", "lt", "lte"):
+ if not _is_number(value):
+ errors.append(f"transitions[{index}] when.op {op!r} requires a numeric value")
+ elif op == "contains":
+ if not isinstance(value, list) or not value:
+ 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")
+
+
+def validate_factory_machine(machine: Any) -> list[str]:
+ """Dry-run validation for a machine-form factory spec.
+
+ Returns a list of human-readable error sentences; an empty list means
+ the machine is valid. Rules: states are 1..1024 with unique slug ids and
+ at least one entry state; every state requires a subagent and entry
+ states declare no inputs; resident states declare no outputs, foreach,
+ or outgoing transitions; wait blocks are rejected (the watch host
+ handlers arrive with the communication series); transitions reference
+ existing states (self-loops are legal re-entry) and may carry one guard
+ over the from-state's latest settle output; a transition with a LIST of
+ from-states is a join that fires once every source settled (guards are
+ single-source only). There is no acyclicity requirement: arbitrary
+ state machines, including cycles, validate.
+ """
+ if not isinstance(machine, dict):
+ return ["factory machine must be a JSON object"]
+ errors: list[str] = []
+ run = machine.get("run")
+ if run is not None and not isinstance(run, dict):
+ errors.append("run must be an object")
+ run = None
+ run_budget = _validate_run_fields(run, errors)
+
+ states = machine.get("states")
+ if not isinstance(states, list):
+ errors.append("factory machine requires a states list")
+ return errors
+ if not 1 <= len(states) <= MAX_STATES:
+ errors.append(f"factory machine must declare between 1 and {MAX_STATES} states, got {len(states)}")
+ return errors
+
+ seen_ids: set[str] = set()
+ states_by_id: dict[str, dict[str, Any]] = {}
+ for index, state in enumerate(states):
+ if not isinstance(state, dict):
+ errors.append(f"states[{index}] must be an object")
+ continue
+ state_id = state.get("id")
+ if not _is_nonempty_str(state_id):
+ errors.append(f"states[{index}] requires a non-empty id")
+ elif not _valid_node_id(state_id):
+ errors.append(f"states[{index}] id must match ^[a-z0-9][a-z0-9-]{{0,63}}$, got {state_id!r}")
+ elif state_id in seen_ids:
+ errors.append(f"states[{index}] duplicates state id {state_id!r}")
+ else:
+ seen_ids.add(state_id)
+ states_by_id[state_id] = state
+
+ # Configured inline subagent names label the spawned children verbatim,
+ # so two states sharing one name would collide on the supervisor's
+ # unique sibling-name requirement at spawn time; reject the duplicate at
+ # write time instead (the same reason duplicate state ids are rejected).
+ seen_subagent_names: dict[str, str] = {}
+ for state_id, state in states_by_id.items():
+ _validate_state_fields(
+ state, run_budget=run_budget, states_by_id=states_by_id, noun="state", errors=errors
+ )
+ subagent = state.get("subagent")
+ if isinstance(subagent, dict) and _is_nonempty_str(subagent.get("name")):
+ configured_name = subagent["name"].strip()
+ base_seen = next(
+ (seen for seen in seen_subagent_names if _suffixed_spawn_form(seen, configured_name)),
+ None,
+ )
+ base_current = (
+ None
+ if base_seen is not None
+ else next(
+ (seen for seen in seen_subagent_names if _suffixed_spawn_form(configured_name, seen)),
+ None,
+ )
+ )
+ if configured_name in seen_subagent_names:
+ errors.append(
+ f"state {state_id} subagent name {configured_name!r} is already configured "
+ f"by state {seen_subagent_names[configured_name]!r}"
+ )
+ elif base_seen is not None:
+ # One state's suffixed labels are another state's verbatim
+ # name (foo vs foo-i1): the supervisor would reject the
+ # duplicate sibling name at spawn time, so reject the
+ # shadowing name at write time. The seen name generates the
+ # labels here.
+ errors.append(
+ f"state {state_id} subagent name {configured_name!r} collides with the "
+ f"suffixed spawn labels of state {seen_subagent_names[base_seen]!r} "
+ f"(configured {base_seen!r}): re-entry, foreach, and retries name children "
+ f"{base_seen!r}-i<n> and {base_seen!r}-a<n>"
+ )
+ elif base_current is not None:
+ # The reverse direction: THIS state's name generates the
+ # suffixed labels, and an earlier state's name is one of
+ # them.
+ errors.append(
+ f"state {state_id} subagent name {configured_name!r} suffixed by re-entry, "
+ f"foreach, and retries ({configured_name!r}-i<n>, {configured_name!r}-a<n>) "
+ f"collides with state {seen_subagent_names[base_current]!r} "
+ f"(configured {base_current!r})"
+ )
+ else:
+ seen_subagent_names[configured_name] = state_id
+ if "entry" in state and not isinstance(state.get("entry"), bool):
+ errors.append(f"state {state_id} entry must be a boolean")
+ if "max_entries" in state and not (
+ _is_int(state.get("max_entries")) and state.get("max_entries") >= STATE_MAX_ENTRIES_DEFAULT
+ ):
+ errors.append(f"state {state_id} max_entries must be an integer >= {STATE_MAX_ENTRIES_DEFAULT}")
+ if state.get("entry") is True and _port_list(state, "inputs"):
+ errors.append(f"entry state {state_id} cannot declare inputs")
+ # A REQUIRED self-input can never bind: the state's first entry needs
+ # its own prior settle, and no settle exists before an entry settles.
+ # Optional self-inputs are the loop form (the first entry binds the
+ # null sentinel, re-entries re-bind the previous settle), so only the
+ # required variant is rejected -- the machine-form mirror of the dag
+ # compiler's "node b cannot depend on itself" rule.
+ for inp in _port_list(state, "inputs"):
+ if not isinstance(inp, dict) or inp.get("optional"):
+ continue
+ source = inp.get("from")
+ if isinstance(source, str) and "." in source and source.partition(".")[0] == state_id:
+ errors.append(
+ f"state {state_id} input {inp.get('name')!r} cannot require itself: "
+ "mark the self-input optional - a required one can never bind on the state's first entry"
+ )
+
+ # The entry check needs at least one well-formed state: a machine whose
+ # only state failed its id check reports that problem alone, and a flag
+ # that is not a boolean never counts as declaring an entry.
+ if states_by_id and not any(state.get("entry") is True for state in states_by_id.values()):
+ errors.append("factory machine requires at least one entry state")
+
+ transitions = machine.get("transitions")
+ if transitions is None:
+ transitions = []
+ if not isinstance(transitions, list):
+ errors.append("factory machine transitions must be a list")
+ return errors
+ for index, transition in enumerate(transitions):
+ if not isinstance(transition, dict):
+ errors.append(f"transitions[{index}] must be an object")
+ continue
+ raw_src = transition.get("from")
+ dst = transition.get("to")
+ # ``from`` is one state id, or a list of them: a JOIN transition that
+ # fires only once every source state has settled (the compiled dag
+ # fan-in shape; a join may not carry a guard -- a guard needs exactly
+ # one from-state's latest settle output to compare against).
+ if isinstance(raw_src, list):
+ sources = raw_src
+ if not sources:
+ errors.append(f"transitions[{index}] from must name at least one state")
+ elif not all(_is_nonempty_str(src) for src in sources):
+ # Type-check BEFORE the set() dedupe: a malformed entry (a
+ # dict, a list) is unhashable and would raise a raw TypeError
+ # instead of reporting a validation error.
+ errors.append(f"transitions[{index}] from entries must be non-empty state id strings")
+ elif len(set(sources)) != len(sources):
+ errors.append(f"transitions[{index}] from must not repeat a state")
+ elif not all(src in states_by_id for src in sources):
+ missing = next(src for src in sources if src not in states_by_id)
+ errors.append(f"transitions[{index}] references unknown from-state {missing!r}")
+ if transition.get("when") is not None:
+ errors.append(
+ f"transitions[{index}] with multiple from-states cannot carry a when guard; "
+ "use single-state transitions for guards"
+ )
+ elif _is_nonempty_str(raw_src):
+ sources = [raw_src]
+ if raw_src not in states_by_id:
+ errors.append(f"transitions[{index}] references unknown from-state {raw_src!r}")
+ else:
+ sources = []
+ errors.append(f"transitions[{index}] requires a non-empty from")
+ if not _is_nonempty_str(dst):
+ errors.append(f"transitions[{index}] requires a non-empty to")
+ elif dst not in states_by_id:
+ errors.append(f"transitions[{index}] references unknown to-state {dst!r}")
+ on = transition.get("on", TRANSITION_ON_KINDS[0])
+ if on not in TRANSITION_ON_KINDS:
+ errors.append(f"transitions[{index}] on must be one of {list(TRANSITION_ON_KINDS)}, got {on!r}")
+ for src in sources:
+ # Malformed sources already reported their own error above; a
+ # non-string entry is unhashable and must never reach the dict
+ # lookup (validation reports errors; it never raises).
+ if _is_nonempty_str(src) and src in states_by_id:
+ src_state = states_by_id[src]
+ if src_state.get("lifecycle", NODE_LIFECYCLE_DEFAULT) == "resident":
+ errors.append(f"transitions[{index}] cannot leave resident state {src!r}")
+ if len(sources) == 1:
+ when = transition.get("when")
+ if when is not None:
+ _validate_guard(when, index, src_state, errors)
+ return errors
+
+
+# ---------------------------------------------------------------------------
+# Dag compatibility: compile the V1 dag form to machine form.
+# ---------------------------------------------------------------------------
+
+
+def _effective_dag_edges(node: dict[str, Any]) -> list[str]:
+ """Effective dependency edges: depends_on plus every inputs[].from source,
+ deduplicated in first-seen order."""
+ edges: list[str] = []
+ for dep in _port_list(node, "depends_on"):
+ if isinstance(dep, str) and dep and dep not in edges:
+ edges.append(dep)
+ for source in _input_sources(node):
+ if source not in edges:
+ edges.append(source)
+ return edges
+
+
+def compile_factory_dag(dag: Any) -> "tuple[dict[str, Any] | None, list[str]]":
+ """Compile a dag-form spec into machine form.
+
+ Returns ``(machine, errors)``: on success the machine is a spec-shaped
+ dict (defaults are applied later by ``canonicalize_factory_spec``) and the
+ error list is empty; on any dag-level error the machine is ``None`` and
+ the errors carry the V1 dag wording. Each node becomes a state with
+ ``entry`` set when it has no effective dependencies and ``max_entries``
+ 1; the node's full effective dependency set becomes ONE guard-less join
+ transition (a single dependency stays a plain ``from`` string; several
+ become a ``from`` list). Wait blocks are rejected by the shared field
+ check (they are gated until the communication series); the compiler
+ itself has no wait support.
+ """
+ if not isinstance(dag, dict):
+ return None, ["factory dag must be a JSON object"]
+ errors: list[str] = []
+ run = dag.get("run")
+ if run is not None and not isinstance(run, dict):
+ errors.append("run must be an object")
+ run = None
+ run_budget = _validate_run_fields(run, errors)
+
+ nodes = dag.get("nodes")
+ if not isinstance(nodes, list):
+ return None, errors + ["factory dag requires a nodes list"]
+ if not 1 <= len(nodes) <= MAX_NODES:
+ return None, errors + [f"factory dag must declare between 1 and {MAX_NODES} nodes, got {len(nodes)}"]
+
+ seen_ids: set[str] = set()
+ nodes_by_id: dict[str, dict[str, Any]] = {}
+ for index, node in enumerate(nodes):
+ if not isinstance(node, dict):
+ errors.append(f"nodes[{index}] must be an object")
+ continue
+ node_id = node.get("id")
+ if not _is_nonempty_str(node_id):
+ errors.append(f"nodes[{index}] requires a non-empty id")
+ elif not _valid_node_id(node_id):
+ errors.append(f"nodes[{index}] id must match ^[a-z0-9][a-z0-9-]{{0,63}}$, got {node_id!r}")
+ elif node_id in seen_ids:
+ errors.append(f"nodes[{index}] duplicates node id {node_id!r}")
+ else:
+ seen_ids.add(node_id)
+ nodes_by_id[node_id] = node
+
+ for node_id, node in nodes_by_id.items():
+ _validate_state_fields(
+ node, run_budget=run_budget, states_by_id=nodes_by_id, noun="node", errors=errors
+ )
+ # The self-dependency rule covers the EFFECTIVE edge set, not only
+ # depends_on: a node that reads its own output would compile to a
+ # never-reachable self-loop state, so reject it here like
+ # depends_on: [self].
+ if node_id in _input_sources(node):
+ errors.append(f"node {node_id} cannot depend on itself")
+ depends_on = node.get("depends_on")
+ if depends_on is not None:
+ if not isinstance(depends_on, list):
+ errors.append(f"node {node_id} depends_on must be a list of node ids")
+ else:
+ for dep in depends_on:
+ if not _is_nonempty_str(dep):
+ errors.append(f"node {node_id} depends_on entries must be non-empty node id strings")
+ elif dep == node_id:
+ errors.append(f"node {node_id} cannot depend on itself")
+ elif dep not in nodes_by_id:
+ errors.append(f"node {node_id} depends on unknown node {dep!r}")
+ elif nodes_by_id[dep].get("lifecycle", NODE_LIFECYCLE_DEFAULT) == "resident":
+ errors.append(f"node {node_id} cannot depend on resident node {dep!r}")
+ if errors:
+ return None, errors
+
+ machine: dict[str, Any] = {"states": [], "transitions": []}
+ if run is not None:
+ machine["run"] = copy.deepcopy(run)
+ for node in nodes:
+ edges = _effective_dag_edges(node)
+ state: dict[str, Any] = {"id": node["id"], "entry": not edges, "max_entries": STATE_MAX_ENTRIES_DEFAULT}
+ for key in ("subagent", "lifecycle", "budget_ms", "retries", "failure_policy", "inputs", "outputs", "foreach"):
+ if key in node:
+ state[key] = copy.deepcopy(node[key])
+ machine["states"].append(state)
+ # ONE join transition per node with dependencies (not one per
+ # edge): a fan-in node waits for ALL its effective predecessors
+ # before entering, so it can never start after just one parent
+ # settles and then block the other parent's transition at
+ # max_entries with a missing input. A single dependency stays a
+ # plain ``from`` string; dependency-free nodes are entry states and
+ # emit no transition at all.
+ if edges:
+ machine["transitions"].append({"from": edges[0] if len(edges) == 1 else edges, "to": node["id"]})
+ return machine, []
+
+
+# ---------------------------------------------------------------------------
+# Unified entry points.
+# ---------------------------------------------------------------------------
+
+
+def validate_factory_spec(spec: Any) -> list[str]:
+ """Dry-run validation for a factory spec in either form.
+
+ Detects the form first: a spec carrying "states" or "transitions" is
+ machine form; anything else is dag form and compiles to machine form
+ first. A spec carrying both dag and machine keys is rejected outright.
+ Returns a list of human-readable error sentences; an empty list means
+ the specification is valid. Every rule is enforced before a factory entry
+ is stored, so an invalid spec never reaches the store.
+ """
+ if not isinstance(spec, dict):
+ return ["factory dag must be a JSON object"]
+ if _is_machine_form(spec) and "nodes" in spec:
+ return ["pass either dag or machine form, not both"]
+ if _is_machine_form(spec):
+ return validate_factory_machine(spec)
+ machine, errors = compile_factory_dag(spec)
+ if errors:
+ return errors
+ # Defense in depth: a compiled dag must produce a valid machine.
+ return validate_factory_machine(machine)
+
+
+def _canonicalize_machine(machine: dict[str, Any]) -> dict[str, Any]:
+ """Apply defaults to a validated machine and normalize it into a clean dict.
+
+ Defaults: run failure_policy 'escalate', run max_parallel 8, run
+ max_transitions 10 per state capped at 10000, run max_children 10000,
+ state entry False, state max_entries 1, state lifecycle 'task', state
+ retries 0, state failure_policy copied from the run policy, and
+ transition on 'settled'.
+ """
+ run_in = machine.get("run") if isinstance(machine.get("run"), dict) else {}
+ run_policy = run_in.get("failure_policy", RUN_FAILURE_POLICY_DEFAULT)
+ states_count = len(machine.get("states") or [])
+ run: dict[str, Any] = {
+ "failure_policy": run_policy,
+ "max_parallel": run_in.get("max_parallel", RUN_MAX_PARALLEL_DEFAULT),
+ "max_transitions": run_in.get(
+ "max_transitions",
+ min(TRANSITIONS_PER_STATE_DEFAULT * states_count, MAX_TRANSITIONS_CAP),
+ ),
+ "max_children": run_in.get("max_children", RUN_MAX_CHILDREN_DEFAULT),
+ }
+ if "budget_ms" in run_in:
+ run["budget_ms"] = run_in["budget_ms"]
+ states_out: list[dict[str, Any]] = []
+ for state in machine["states"]:
+ state_out: dict[str, Any] = {
+ "id": state["id"],
+ "entry": bool(state.get("entry", STATE_ENTRY_DEFAULT)),
+ "max_entries": state.get("max_entries", STATE_MAX_ENTRIES_DEFAULT),
+ "lifecycle": state.get("lifecycle", NODE_LIFECYCLE_DEFAULT),
+ "retries": state.get("retries", NODE_RETRIES_DEFAULT),
+ "failure_policy": state.get("failure_policy", run_policy),
+ "subagent": copy.deepcopy(state["subagent"]),
+ }
+ for key in ("budget_ms", "inputs", "outputs", "foreach"):
+ if key in state:
+ state_out[key] = copy.deepcopy(state[key])
+ states_out.append(state_out)
+ transitions_out: list[dict[str, Any]] = []
+ for transition in machine.get("transitions") or []:
+ transition_out: dict[str, Any] = {
+ "from": transition["from"],
+ "to": transition["to"],
+ "on": transition.get("on", TRANSITION_ON_KINDS[0]),
+ }
+ if "when" in transition:
+ transition_out["when"] = copy.deepcopy(transition["when"])
+ transitions_out.append(transition_out)
+ return {"run": run, "states": states_out, "transitions": transitions_out}
+
+
+def canonicalize_factory_spec(spec: Any) -> dict[str, Any]:
+ """Validate a spec in either form and return the canonical MACHINE form.
+
+ Raises ``ValueError`` with the joined error list when the spec is
+ invalid (including the both-forms rejection). Dag specs compile to
+ machine form first, so the executor sees one shape:
+ ``{"run": ..., "states": [...], "transitions": [...]}``.
+ """
+ errors = validate_factory_spec(spec)
+ if errors:
+ raise ValueError("; ".join(errors))
+ assert isinstance(spec, dict) # validated above
+ if _is_machine_form(spec):
+ machine = spec
+ else:
+ machine, compile_errors = compile_factory_dag(spec)
+ assert machine is not None and not compile_errors # validated above
+ return _canonicalize_machine(machine)
+
+
+def topological_order(nodes: list[dict[str, Any]]) -> list[str]:
+ """Return node ids in a dependency-respecting order.
+
+ Edges are the effective dependencies: ``depends_on`` plus every
+ ``inputs[].from`` source node. Raises ``ValueError`` on a duplicate id,
+ an unknown dependency, or a cycle. The order is stable: among ready
+ nodes, input order wins. Retained as a public helper for inspecting
+ dag-form specs; the machine form has no acyclicity requirement.
+ """
+ if not isinstance(nodes, list):
+ raise ValueError("nodes must be a list")
+ index_of: dict[str, int] = {}
+ for index, node in enumerate(nodes):
+ if not isinstance(node, dict):
+ raise ValueError(f"nodes[{index}] must be an object")
+ node_id = node.get("id")
+ if not isinstance(node_id, str) or not node_id:
+ raise ValueError(f"nodes[{index}] requires a non-empty id")
+ if node_id in index_of:
+ raise ValueError(f"duplicate node id {node_id!r}")
+ index_of[node_id] = index
+
+ deps: dict[str, set[str]] = {}
+ for node in nodes:
+ node_id = node["id"]
+ edges: set[str] = set()
+ depends_on = node.get("depends_on")
+ if depends_on is not None:
+ if not isinstance(depends_on, list):
+ raise ValueError(f"node {node_id!r} depends_on must be a list of node ids")
+ for dep in depends_on:
+ if not isinstance(dep, str) or not dep:
+ raise ValueError(f"node {node_id!r} depends_on entries must be non-empty node id strings")
+ edges.add(dep)
+ inputs = node.get("inputs")
+ if inputs is not None:
+ if not isinstance(inputs, list):
+ raise ValueError(f"node {node_id!r} inputs must be a list")
+ for inp in inputs:
+ if not isinstance(inp, dict):
+ raise ValueError(f"node {node_id!r} inputs entries must be objects")
+ source = inp.get("from")
+ if not isinstance(source, str) or "." not in source:
+ raise ValueError(
+ f"node {node_id!r} inputs require a 'from' reference of the form '<node_id>.<output_name>'"
+ )
+ edges.add(source.partition(".")[0])
+ deps[node_id] = edges
+
+ for node_id, edges in deps.items():
+ for dep in edges:
+ if dep not in index_of:
+ raise ValueError(f"node {node_id!r} depends on unknown node {dep!r}")
+
+ remaining = {node_id: len(edges) for node_id, edges in deps.items()}
+ dependents: dict[str, list[str]] = {node_id: [] for node_id in index_of}
+ for node_id, edges in deps.items():
+ for dep in edges:
+ dependents[dep].append(node_id)
+ ready = [(index_of[node_id], node_id) for node_id, count in remaining.items() if count == 0]
+ heapq.heapify(ready)
+ order: list[str] = []
+ while ready:
+ _, current = heapq.heappop(ready)
+ order.append(current)
+ for dependent in dependents[current]:
+ remaining[dependent] -= 1
+ if remaining[dependent] == 0:
+ heapq.heappush(ready, (index_of[dependent], dependent))
+ if len(order) != len(index_of):
+ stuck = sorted(node_id for node_id, count in remaining.items() if count > 0)
+ raise ValueError(f"the factory graph contains a cycle involving nodes: {', '.join(stuck)}")
+ return order
+
+
+__all__ = [
+ "FACTORY_DISABLED_MESSAGE",
+ "FACTORY_HELP",
+ "FactoryExecutor",
+ "FactoryRun",
+ "canonicalize_factory_spec",
+ "compile_factory_dag",
+ "default_factory_executor",
+ "factory_enabled",
+ "require_factory_enabled",
+ "resume_factory",
+ "run_factory",
+ "status_factory",
+ "stop_factory",
+ "topological_order",
+ "validate_factory_machine",
+ "validate_factory_spec",
+]
+
+
+# Executor: run a canonicalized machine through the RLM supervisor.
+# ---------------------------------------------------------------------------
+
+ANSWER_CAPTURE_CAP = 200
+"""Local safety cap for captured answers.
+
+``rlm.collect`` already returns previews: the host caps them at 160
+characters (``compactRlmText``). Input binding and every rendered prompt
+therefore work on capped preview text; full child outputs stay in the
+child's own session and are never seen by the executor.
+"""
+
+EVENT_WINDOW = 200
+"""Number of trailing ledger events returned by ``status()``.
+
+200 (not 50): a state-machine run's ledger grows fast — the pr-manager
+happy path alone is ~43 events, and retries or rate-limit backoff would
+otherwise push early evidence (a round-1 fix answer) out of the window a
+parent or replay checker reads.
+"""
+
+POLL_TIMEOUT_MS = 2000
+"""How long each control-loop ``rlm.collect`` waits for unsettled children."""
+
+BACKOFF_MAX_ATTEMPTS = 5
+"""Spawn admissions per node before a persistent rate limit fails the node."""
+
+BACKOFF_BASE_SECONDS = 1.0
+BACKOFF_CAP_SECONDS = 60.0
+_RATE_LIMIT_MARKERS = (
+ "rate limit",
+ "rate-limit",
+ "ratelimit",
+ "429",
+ "too many requests",
+ "throttled",
+ "quota",
+ "usage limit",
+)
+
+_FENCED_JSON_RE = re.compile(r"```json\s*(.*?)\s*```", re.DOTALL)
+TERMINAL_ENTRY_STATUSES = ("done", "error", "cancelled")
+
+
+def _is_rate_limit_error(message: str) -> bool:
+ """Heuristic: the host reports admission failures as error strings."""
+ lowered = message.lower()
+ return any(marker in lowered for marker in _RATE_LIMIT_MARKERS)
+
+
+def _child_name(run_id: str, state_id: str, instance_index: int, attempt: int) -> str:
+ """Unique, readable sibling name for one spawned instance (host caps names at 64).
+
+ A long state id is truncated but always disambiguated with a digest of
+ the full id: two states sharing a 20-character prefix would otherwise
+ produce the same sibling name, and the second admission would fail the
+ supervisor's unique-name requirement. The digest is 64-bit (16 hex
+ characters), so even a pathological 1024-state run sharing one prefix
+ has a negligible collision chance; the longest name stays under the
+ host's 64-character cap.
+ """
+ if len(state_id) <= 20:
+ token = state_id
+ else:
+ digest = hashlib.sha256(state_id.encode("utf-8")).hexdigest()[:16]
+ token = f"{state_id[:20]}-{digest}"
+ parts = ["sw", token, run_id[:6]]
+ if instance_index >= 0:
+ parts.append(f"i{instance_index}")
+ if attempt > 1:
+ parts.append(f"a{attempt}")
+ return "-".join(parts)
+
+
+def _spawn_label(
+ configured: str | None, run_id: str, state_id: str, instance_index: int, attempt: int
+) -> str:
+ """Sibling label for one spawned instance: the state's configured inline
+ subagent ``name`` when it has one, else the generated label.
+
+ The configured name is used verbatim for the state's first instance on
+ its first attempt (agents message the child by exactly this label); the
+ SAME disambiguation suffixes as the generated label -- ``i<n>`` for
+ later instances (re-entry, foreach fan-out), ``a<n>`` for retries --
+ keep every admission unique: the supervisor rejects duplicate sibling
+ names, and one state's settled children stay registered for the
+ run's life, so a re-entering state (``max_entries`` > 1) would collide
+ with its own earlier child on a verbatim name.
+
+ A suffixed label never exceeds the host's 64-character spawn-name cap:
+ an overflowing base shrinks to a digest-suffixed token of the full
+ name, exactly like the generated label's state-id token.
+ """
+ if configured is None:
+ return _child_name(run_id, state_id, instance_index, attempt)
+ suffix_parts = [f"i{instance_index}"] if instance_index > 0 else []
+ if attempt > 1:
+ suffix_parts.append(f"a{attempt}")
+ suffix = "".join(f"-{part}" for part in suffix_parts)
+ base = configured
+ if len(base) + len(suffix) > SUBAGENT_NAME_MAX_LENGTH:
+ # The host caps spawn names at 64 characters, so a suffixed label
+ # that would exceed it shrinks its base first -- and a bare
+ # truncation could collide (two long configured names sharing the
+ # truncated prefix), so the base keeps a digest of the full name
+ # exactly like the generated label's state-id token: distinct
+ # names stay distinct, and every admission fits the cap.
+ digest = hashlib.sha256(base.encode("utf-8")).hexdigest()[:16]
+ room = max(SUBAGENT_NAME_MAX_LENGTH - len(suffix) - len(digest) - 1, 0)
+ base = f"{base[:room]}-{digest}"
+ return base + suffix
+
+
+def _suffixed_spawn_form(base: str, candidate: str) -> bool:
+ """True when ``candidate`` is a spawn label ``base`` can produce.
+
+ A state configured as ``base`` names its later children ``base-i<n>``
+ (re-entry, foreach fan-out) and ``base-a<n>`` (retries, ``n`` >= 2);
+ the never-generated ``-i0`` and ``-a1`` do not count, so a candidate
+ carrying them cannot collide and stays valid.
+ """
+ if not candidate.startswith(base + "-"):
+ return False
+ remainder = candidate[len(base) + 1 :]
+ for part in remainder.split("-"):
+ if len(part) < 2 or part[0] not in "ia" or not part[1:].isdigit():
+ return False
+ if part[0] == "i" and int(part[1:]) < 1:
+ return False
+ if part[0] == "a" and int(part[1:]) < 2:
+ return False
+ return True
+
+
+def _parse_json_output(answer: str, output_name: str) -> tuple[Any, str | None]:
+ """Extract one named JSON output from an upstream answer.
+
+ Prefers the fenced `````json`` block whose object contains the output
+ name, scanning trailing blocks first (an answer with several fences,
+ e.g. a verdict block followed by a summary block, binds from whichever
+ block carries the port), then falls back to parsing the whole answer.
+ Returns ``(value, None)`` or ``(None, error_sentence)``.
+ """
+ candidates: list[str] = list(reversed(_FENCED_JSON_RE.findall(answer)))
+ candidates.append(answer.strip())
+ for candidate in candidates:
+ try:
+ parsed = json.loads(candidate)
+ except (ValueError, TypeError):
+ continue
+ if isinstance(parsed, dict) and output_name in parsed:
+ return parsed[output_name], None
+ return None, f"no JSON object containing output {output_name!r} in the upstream answer"
+
+
+def _render_prompt(template: str, values: dict[str, str]) -> str:
+ """Render bound input values into a prompt template.
+
+ Each ``{input_name}`` placeholder is replaced in a single pass (a value
+ that itself looks like a placeholder is never re-substituted). Inputs
+ without a placeholder are appended in a trailing ``## Inputs`` section,
+ so no bound value is dropped.
+ """
+ if not values:
+ return template
+ pattern = re.compile("|".join(re.escape("{" + name + "}") for name in values))
+ used: set[str] = set()
+
+ def _substitute(match: "re.Match[str]") -> str:
+ name = match.group(0)[1:-1]
+ used.add(name)
+ return values[name]
+
+ rendered = pattern.sub(_substitute, template)
+ unplaced = [(name, value) for name, value in values.items() if name not in used]
+ if unplaced:
+ rendered += "\n\n## Inputs\n" + "".join(f"- {name}: {value}\n" for name, value in unplaced)
+ return rendered
+
+
+def _json_equal(actual: Any, expected: Any) -> bool:
+ """JSON-strict equality for eq/ne guards: a boolean never equals a
+ number (true != 1, false != 0), numbers compare numerically (1 == 1.0),
+ and everything else compares within its own type."""
+ if isinstance(actual, bool) or isinstance(expected, bool):
+ return isinstance(actual, bool) and isinstance(expected, bool) and actual is expected
+ if actual is None or expected is None:
+ return actual is None and expected is None
+ if _is_number(actual) and _is_number(expected):
+ # Exact: Python compares int/int, int/float, and float/float
+ # mathematically (no lossy float conversion), so distinct large
+ # JSON integers never compare equal (9007199254740993 != 9007199254740992).
+ return actual == expected
+ if isinstance(actual, str) and isinstance(expected, str):
+ return actual == expected
+ return False
+
+
+def _guard_passes(when: dict[str, Any], outputs: dict[str, Any]) -> bool:
+ """Evaluate one transition guard over a settle's captured outputs.
+
+ A missing or unparseable port fails every op except ``exists`` (which is
+ explicitly false then); ``ne`` needs a found value to compare against.
+ ``eq``/``ne`` compare JSON-strictly (bools never equal numbers); an
+ empty ``contains`` needle is defensively false.
+ """
+ port = when.get("output")
+ value: Any = None
+ found = False
+ path = when.get("path")
+ if path:
+ current = outputs.get(port)
+ if isinstance(current, dict):
+ found = True
+ for part in path.split("."):
+ if isinstance(current, dict) and part in current:
+ current = current[part]
+ else:
+ found = False
+ break
+ value = current
+ elif port in outputs:
+ found = True
+ value = outputs[port]
+ op = when.get("op")
+ if op == "exists":
+ return found
+ if not found:
+ return False
+ if op == "eq":
+ return _json_equal(value, when.get("value"))
+ if op == "ne":
+ return not _json_equal(value, when.get("value"))
+ if op in ("gt", "gte", "lt", "lte"):
+ bound = when.get("value")
+ if not _is_number(value) or not _is_number(bound):
+ return False
+ if op == "gt":
+ return value > bound
+ if op == "gte":
+ return value >= bound
+ if op == "lt":
+ return value < bound
+ return value <= bound
+ if op == "contains":
+ needle = when.get("value")
+ if not isinstance(needle, list) or not needle:
+ return False
+ if isinstance(value, list):
+ return all(item in value for item in needle)
+ if isinstance(value, str):
+ return all(isinstance(item, str) and item in value for item in needle)
+ return False
+ return False
+
+
+def _validate_spawn_settings(model: Any, thinking: Any) -> str | None:
+ for key, value in (("model", model), ("thinking", thinking)):
+ if value is not None and (not isinstance(value, str) or not value.strip()):
+ return f"subagent {key} must be a non-empty string when provided"
+ return None
+
+
+@dataclass
+class _NodeInstance:
+ """One spawned child of one state entry (a foreach entry has one per item)."""
+
+ index: int # per-state running counter; unique within the state
+ prompt: str # fully rendered; re-spawns reuse it verbatim
+ status: str = "pending" # pending | running | done | error | cancelled
+ attempt: int = 0 # spawn admissions tried for this instance; a rate-limit
+ # deferral counts here too, and ``retries`` compares against this same
+ # counter, so one transient 429 admission consumes one declared retry.
+ rate_limit_streak: int = 0 # consecutive rate-limited admissions in the
+ # control loop's backoff path; a successful spawn resets it, and
+ # BACKOFF_MAX_ATTEMPTS in a row fails the node. An admission-phase
+ # deferral (run()/resume(), allow_backoff=False) consumes an attempt
+ # but never counts toward the backoff episode.
+ child_id: str | None = None
+ spawned_at: float | None = None
+ duration_ms: int | None = None
+ answer: str | None = None # capped collect preview (ANSWER_CAPTURE_CAP)
+ error: str | None = None
+ tool_uses: int = 0
+
+
+@dataclass
+class _StateEntry:
+ """One entry (activation) of a state; re-entry creates a fresh entry.
+
+ An entry settles when all of its instances settle done; the settle
+ captures the state's declared outputs, and
+ the control loop then evaluates the outgoing transitions once
+ (``consumed`` marks that evaluation done).
+ """
+
+ index: int # per-state entry index, 0-based
+ status: str = "pending" # pending | running | done | error | cancelled
+ instances: list[_NodeInstance] = field(default_factory=list)
+ error: str | None = None
+ answer: str | None = None # joined captured answers of this entry
+ outputs: dict[str, Any] | None = None # captured settle outputs (port name -> value)
+ output_errors: dict[str, str] | None = None # ports whose json capture failed
+ is_settle: bool = False # True once the entry settled (done or error)
+ consumed: bool = False # True once the settle's transitions were evaluated
+
+
+@dataclass
+class _StateRun:
+ """Executor-side state for one machine state of one run."""
+
+ state_id: str
+ spec: dict[str, Any] # canonical state spec
+ position: int # stable list position for deterministic ordering
+ prompt_template: str | None = None
+ name: str | None = None # configured inline subagent name; labels children
+ model: str | None = None
+ thinking: str | None = None
+ max_entries: int = STATE_MAX_ENTRIES_DEFAULT
+ entries_used: int = 0
+ entries: list[_StateEntry] = field(default_factory=list)
+ instance_counter: int = 0
+ error: str | None = None
+ cancelled: bool = False # set by stop()/fail_fast for never-entered states
+
+ @property
+ def lifecycle(self) -> str:
+ return self.spec.get("lifecycle", NODE_LIFECYCLE_DEFAULT)
+
+ @property
+ def status(self) -> str:
+ if self.entries:
+ return self.entries[-1].status
+ return "cancelled" if self.cancelled else "pending"
+
+ def latest_settle(self) -> _StateEntry | None:
+ for entry in reversed(self.entries):
+ if entry.is_settle:
+ return entry
+ return None
+
+
+@dataclass
+class FactoryRun:
+ """Executor-side state for one run. Kernel memory only: it does not
+ survive a kernel restart; the children (supervisor-owned) keep running."""
+
+ run_id: str
+ spec_id: str
+ name: str | None
+ state: str = "running" # running | stopping | paused | done | failed | stopped
+ started_at: float = 0.0
+ max_parallel: int = RUN_MAX_PARALLEL_DEFAULT
+ max_transitions: int = MAX_TRANSITIONS_CAP
+ max_children: int = RUN_MAX_CHILDREN_DEFAULT
+ max_transitions_reported: bool = False
+ max_children_reported: bool = False
+ run_budget_ms: int | None = None
+ budget_reported: bool = False
+ pause_reason: str | None = None
+ states: dict[str, _StateRun] = field(default_factory=dict)
+ order: list[str] = field(default_factory=list)
+ transitions_from: dict[str, list[dict[str, Any]]] = field(default_factory=dict)
+ pending_evaluations: list[tuple[str, int, int]] = field(default_factory=list)
+ events: list[dict[str, Any]] = field(default_factory=list)
+ milestones: set[str] = field(default_factory=set)
+ spawn_count: int = 0
+ settle_count: int = 0
+ transitions_fired: int = 0
+ tool_use_total: int = 0
+ task: "Any | None" = None
+ # The control loop's generation: resume() bumps it so a pause-path task
+ # that is still winding down (an in-flight milestone await) can never
+ # continue as a second concurrent control loop. The task captures its
+ # generation at start and re-checks it after every await.
+ loop_generation: int = 0
+ # Rate-limit backoff deadline (seconds on the injected clock): admission
+ # defers instead of sleeping inside the loop, so the loop can keep
+ # collecting children while admission waits out the deadline.
+ admission_backoff_until: float | None = None
+ # Join-transition bookkeeping: the last-fired (source id, settle index)
+ # signature per join (keyed by the transition object), so a join whose
+ # 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)
+
+
+class FactoryExecutor:
+ """Runs canonicalized state-machine factories through the existing RLM supervisor.
+
+ Ownership split: the supervisor owns the children (admission via
+ ``rlm.spawn``, settlement via ``rlm.collect``, cancellation via
+ ``rlm.delete_subagent``); this executor owns the run state in kernel
+ memory. Every host call resolves through the module-level ``rlm``
+ functions and ``host_request`` at call time, so tests can patch
+ ``rlm.host_request``. ``now`` (default ``time.monotonic``) and ``sleep``
+ (default ``asyncio.sleep``) are injectable: budgets measure admission
+ to settlement and rate-limit backoff is testable with fake sleeps.
+
+ Machine semantics: admission enters every entry state; each settle is
+ queued and its outgoing transitions evaluated once -- every guard that
+ passes fires (fan-out is legal), a fire enters the target unless it is
+ out of ``max_entries`` (recorded as ``transition_blocked``), and a
+ self-loop or back-edge re-enters its target with freshly re-bound
+ inputs. A run completes at quiescence: no state entry in flight
+ (pending/running/waiting) and no unevaluated settle.
+
+ Runs do not survive a kernel restart (the registry lives in kernel
+ memory); children are supervisor-owned and keep running, so
+ ``rlm.list_subagents`` can still see and stop them after a restart.
+ """
+
+ def __init__(
+ self,
+ *,
+ now: "Callable[[], float] | None" = None,
+ sleep: "Callable[[float], Any] | None" = None,
+ harness: Any = None,
+ ) -> None:
+ import asyncio
+
+ self._now_fn: Callable[[], float] = now or time.monotonic
+ self._sleep_fn: Callable[[float], Any] = sleep or asyncio.sleep
+ self._harness = harness
+ self._runs: dict[str, FactoryRun] = {}
+
+ # -- public API ---------------------------------------------------------
+
+ async def run(self, spec_id: str, *, name: str | None = None) -> dict[str, Any]:
+ """Validate a stored factory spec and start a run of it.
+
+ The dry run happens in two halves. Write time (``create_factory``)
+ validated the machine; here ``run`` re-validates and canonicalizes
+ it (dag sugar compiles to machine form), then resolves every state's
+ subagent reference, reporting ALL failures in one ``ValueError`` and
+ starting nothing on any failure. The resolved state count and
+ ``max_parallel`` are reported in the result; actual admission limits
+ (concurrency, tree depth, provider rate limits) are enforced at
+ spawn time through the backoff path. Admission enters every entry
+ state up to ``max_parallel``, records handles, and returns; a
+ background asyncio task continues the run, so the calling model turn
+ ends immediately (nonblocking).
+ """
+ harness = self._resolve_harness()
+ entry = harness.get("factory", spec_id)
+ if entry is None:
+ raise ValueError(f"unknown factory spec {spec_id!r}")
+ arguments = entry.arguments if isinstance(entry.arguments, dict) else {}
+ spec = arguments.get("machine")
+ if spec is None:
+ spec = arguments.get("dag")
+ canonical = canonicalize_factory_spec(spec)
+ resolved, reference_errors = self._resolve_subagents(harness, canonical)
+ if reference_errors:
+ raise ValueError("; ".join(reference_errors))
+ run = self._create_run(entry.id, canonical, resolved, name=name)
+ self._runs[run.run_id] = run
+ self._event(
+ run, "run_started", detail=f"{len(run.states)} states, max_parallel {run.max_parallel}"
+ )
+ for state_id in run.order:
+ state = run.states[state_id]
+ if state.spec.get("entry"):
+ self._enter_state(run, state, from_state=None)
+ started = await self._spawn_ready(run, generation=run.loop_generation, allow_backoff=False)
+ if self._run_complete(run):
+ await self._finalize(run)
+ elif run.state == "running":
+ # A budget pause during the initial admission leaves the run
+ # paused with no loop: resuming is the operator's decision.
+ self._start_loop(run)
+ return {
+ "run_id": run.run_id,
+ "spec_id": entry.id,
+ "name": name,
+ "nodes": len(run.states),
+ "max_parallel": run.max_parallel,
+ "started": started,
+ "pending": self._pending_state_ids(run),
+ }
+
+ async def status(self, run_id: str) -> dict[str, Any]:
+ """State states, the trailing event window, elapsed time, and usage.
+
+ Each call marks the events the parent has not seen yet
+ (``recorded``/``arrived``) ``delivered``; ``shown`` events keep their
+ stage because their notice already reached the parent conversation,
+ so the stage taxonomy stays observable. The returned window is the
+ last ``EVENT_WINDOW`` events.
+ 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)
+ for event in run.events:
+ if event["stage"] in ("recorded", "arrived"):
+ event["stage"] = "delivered"
+ return {
+ "run_id": run.run_id,
+ "spec_id": run.spec_id,
+ "name": run.name,
+ "state": run.state,
+ "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,
+ },
+ }
+
+ async def stop(self, run_id: str) -> dict[str, Any]:
+ """Cancel every running child of the run and mark it stopped.
+
+ Sets the transitional ``stopping`` state before the first await so
+ the control loop cannot admit new children or finalize the run while
+ the cancellations are in flight. Idempotent: a second stop returns
+ the same result without another ledger event.
+ """
+ run = self._require_run(run_id)
+ # The transitional "stopping" state is guarded as well: two
+ # concurrent stop() calls would otherwise both pass a bare
+ # "stopped" check, both enter the cancellation pass, and issue
+ # duplicate delete_subagent requests plus a second run_stopped
+ # ledger event.
+ if run.state in ("stopping", "stopped"):
+ return {"run_id": run.run_id, "state": run.state, "cancelled": []}
+ run.state = "stopping"
+ stopped = await self._halt_nonterminal(run, "run stopped")
+ run.state = "stopped"
+ self._event(run, "run_stopped", detail=f"stopped; {len(stopped)} state(s) cancelled")
+ return {"run_id": run.run_id, "state": "stopped", "cancelled": stopped}
+
+ async def resume(self, run_id: str) -> dict[str, Any]:
+ """Resume a paused run (escalate, budget, or max_transitions pause).
+
+ A budget or max_transitions pause is reported once per run:
+ resuming after it is an explicit operator decision and no further
+ budget pauses fire. Raises ``ValueError`` when the run is not paused.
+ """
+ run = self._require_run(run_id)
+ if run.state != "paused":
+ raise ValueError(f"factory run {run_id!r} is {run.state!r}, not paused")
+ # Bump the loop generation FIRST: the pause-path control-loop task
+ # may still be winding down (an in-flight milestone await). Its
+ # state re-checks would otherwise see "running" again and continue
+ # as a SECOND loop, admitting and settling the same instances
+ # alongside the loop started below.
+ run.loop_generation += 1
+ run.state = "running"
+ run.pause_reason = None
+ 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.
+ await self._evaluate_settles(run)
+ # allow_backoff=False: like run(), resume() must never sleep inside
+ # the calling model turn; rate-limited admissions defer to the loop.
+ started = await self._spawn_ready(run, generation=run.loop_generation, allow_backoff=False)
+ if self._run_complete(run):
+ await self._finalize(run)
+ elif run.state == "running":
+ self._start_loop(run)
+ return {
+ "run_id": run.run_id,
+ "state": run.state,
+ "started": started,
+ "pending": self._pending_state_ids(run),
+ }
+
+ # -- setup --------------------------------------------------------------
+
+ def _resolve_harness(self) -> Any:
+ if self._harness is not None:
+ return self._harness
+ from . import rlm as rlm_namespace
+
+ return rlm_namespace.harness
+
+ def _require_run(self, run_id: str) -> FactoryRun:
+ run = self._runs.get(run_id)
+ if run is None:
+ raise ValueError(f"unknown factory run {run_id!r}")
+ return run
+
+ def _resolve_subagents(
+ self, harness: Any, canonical: dict[str, Any]
+ ) -> tuple[dict[str, tuple[str, str | None, str | None, str | None]], list[str]]:
+ """Resolve every state's subagent reference; collect ALL failures.
+
+ A string reference is a harness subagent entry id or title: its
+ content is the prompt template and ``metadata.model``/``metadata.thinking``
+ carry optional spawn settings. An inline object uses its own fields;
+ its ``name`` (stripped the way the host strips spawn names) labels
+ the spawned children.
+ """
+ resolved: dict[str, tuple[str, str | None, str | None, str | None]] = {}
+ errors: list[str] = []
+ for state_spec in canonical["states"]:
+ state_id = state_spec["id"]
+ reference = state_spec["subagent"]
+ if isinstance(reference, dict):
+ prompt = reference.get("prompt")
+ raw_name = reference.get("name")
+ name = raw_name.strip() if isinstance(raw_name, str) else None
+ model = reference.get("model")
+ thinking = reference.get("thinking")
+ else:
+ entry = harness.get("subagent", reference)
+ if entry is None:
+ entry = next((row for row in harness.list("subagent") if row.title == reference), None)
+ if entry is None:
+ errors.append(f"state {state_id!r} references unknown subagent {reference!r}")
+ continue
+ prompt = entry.content
+ name = None
+ metadata = entry.metadata if isinstance(entry.metadata, dict) else {}
+ model = metadata.get("model")
+ thinking = metadata.get("thinking")
+ if not isinstance(prompt, str) or not prompt.strip():
+ errors.append(f"state {state_id!r} has an empty subagent prompt")
+ continue
+ settings_error = _validate_spawn_settings(model, thinking)
+ if settings_error is not None:
+ errors.append(f"state {state_id!r} {settings_error}")
+ continue
+ resolved[state_id] = (prompt, name or None, model, thinking)
+ return resolved, errors
+
+ def _create_run(
+ self,
+ spec_id: str,
+ canonical: dict[str, Any],
+ resolved: dict[str, tuple[str, str | None, str | None, str | None]],
+ *,
+ name: str | None,
+ ) -> FactoryRun:
+ run_spec = canonical["run"]
+ run = FactoryRun(
+ run_id=uuid4().hex,
+ spec_id=spec_id,
+ name=name,
+ started_at=self._now_fn(),
+ max_parallel=run_spec["max_parallel"],
+ max_transitions=run_spec["max_transitions"],
+ max_children=run_spec["max_children"],
+ run_budget_ms=run_spec.get("budget_ms"),
+ )
+ position_of: dict[str, int] = {}
+ for position, state_spec in enumerate(canonical["states"]):
+ position_of[state_spec["id"]] = position
+ state_id = state_spec["id"]
+ prompt, name, model, thinking = resolved.get(state_id, (None, None, None, None))
+ run.states[state_id] = _StateRun(
+ state_id=state_id,
+ spec=state_spec,
+ position=position,
+ prompt_template=prompt,
+ name=name,
+ model=model,
+ thinking=thinking,
+ max_entries=state_spec.get("max_entries", STATE_MAX_ENTRIES_DEFAULT),
+ )
+ run.order.append(state_id)
+ for transition in canonical.get("transitions") or []:
+ raw_from = transition["from"]
+ # A join (from is a list) is visible from EVERY source state's
+ # settle evaluation; a single-source transition registers once.
+ sources = raw_from if isinstance(raw_from, list) else [raw_from]
+ for source in sources:
+ run.transitions_from.setdefault(source, []).append(transition)
+ return run
+
+ # -- event ledger -------------------------------------------------------
+
+ def _event(
+ self,
+ run: FactoryRun,
+ kind: str,
+ *,
+ node: str | None = None,
+ entry: int | None = None,
+ instance: int | None = None,
+ detail: str | None = None,
+ stage: str = "recorded",
+ **extra: Any,
+ ) -> dict[str, Any]:
+ """Append one ledger entry.
+
+ Stages follow the spec: ``arrived`` (a child answer settled and was
+ captured), ``recorded`` (everything else), ``shown`` (a milestone
+ notice was injected into the parent conversation), and ``delivered``
+ (the parent read the ledger via ``status()``).
+ """
+ event: dict[str, Any] = {"seq": len(run.events) + 1, "kind": kind, "stage": stage}
+ if node is not None:
+ event["node"] = node
+ if entry is not None:
+ event["entry"] = entry
+ if instance is not None:
+ event["instance"] = instance
+ if detail is not None:
+ event["detail"] = detail
+ event.update(extra)
+ run.events.append(event)
+ return event
+
+ async def _milestone(self, run: FactoryRun, kind: str, detail: str, *, node: str | None = None) -> None:
+ """Record a run milestone and inject one quiet notice (one per kind).
+
+ Every milestone lands in the ledger, repeats included: a run that
+ pauses twice must still show the second pause to the parent reading
+ ``status()``. Only the parent-visible notice is deduped per kind.
+ """
+ event = self._event(run, "milestone", milestone=kind, detail=detail, node=node)
+ if kind in run.milestones:
+ return # the kind was announced once; the ledger keeps this repeat
+ run.milestones.add(kind)
+ try:
+ from . import host_request
+
+ payload: dict[str, Any] = {"run_id": run.run_id, "kind": kind, "detail": detail}
+ if node is not None:
+ payload["node"] = node
+ await host_request("factory.progress", payload)
+ event["stage"] = "shown"
+ except Exception:
+ # A dead bridge cannot be told; the ledger keeps the milestone and
+ # status() still surfaces it to the parent.
+ pass
+
+ # -- entries, transitions -------------------------------------------------
+
+ def _enter_state(self, run: FactoryRun, state: _StateRun, *, from_state: str | None) -> _StateEntry:
+ """Create one new entry of a state (bounded by max_entries upstream)."""
+ entry = _StateEntry(index=len(state.entries))
+ state.entries.append(entry)
+ state.entries_used += 1
+ detail = "entry state" if from_state is None else f"entered from {from_state}"
+ self._event(run, "state_entry", node=state.state_id, entry=entry.index, detail=detail)
+ return entry
+
+ def _queue_settle(self, run: FactoryRun, state: _StateRun, entry: _StateEntry) -> None:
+ entry.is_settle = True
+ # The third element is the transition index to resume from: 0 for a
+ # fresh settle, or the paused index after a max_transitions pause.
+ run.pending_evaluations.append((state.state_id, entry.index, 0))
+
+ async def _evaluate_settles(self, run: FactoryRun) -> None:
+ """Evaluate every queued settle's outgoing transitions once.
+
+ ALL transitions whose guards pass fire (fan-out is legal); a join
+ transition (from is a list) fires once per source-settle completion;
+ a fire enters the target unless it is out of max_entries (recorded
+ as transition_blocked). Exceeding max_transitions pauses the run once
+ (max_transitions_exceeded milestone, resume-able) with the settle
+ left unconsumed AND the transition index where the pause landed, so
+ a resume continues after the transitions that already fired instead
+ of re-firing them.
+ """
+ while run.pending_evaluations and run.state == "running":
+ state_id, entry_index, resume_from = run.pending_evaluations.pop(0)
+ state = run.states[state_id]
+ entry = state.entries[entry_index]
+ if entry.consumed or not entry.is_settle:
+ continue
+ entry.consumed = True
+ outputs = entry.outputs or {}
+ for transition_index, transition in enumerate(run.transitions_from.get(state_id, [])):
+ if transition_index < resume_from:
+ continue # already fired before the pause; do not re-fire
+ raw_from = transition["from"]
+ join_signature: "frozenset[tuple[str, int]] | None" = None
+ if isinstance(raw_from, list):
+ # A join fires from this settle only when every source
+ # state has a settle, and only once per source-settle
+ # combination: both sources settling in one collect
+ # batch must produce ONE entry of the target, not two.
+ sources = raw_from
+ signature_parts = []
+ for source_id in sources:
+ source_state = run.states.get(source_id)
+ latest = source_state.latest_settle() if source_state is not None else None
+ if latest is None:
+ signature_parts = None
+ break
+ signature_parts.append((source_id, latest.index))
+ if signature_parts is None:
+ continue # a join source never settled yet; not firable
+ signature = frozenset(signature_parts)
+ # Keyed by the transition object's identity: duplicate
+ # transitions (same sources, same target) are legal
+ # machine syntax and stay independent.
+ key = (id(transition), transition["to"])
+ if run.join_fired.get(key) == signature:
+ continue # this completion already fired (or was blocked)
+ # The signature is CLAIMED only below, when the
+ # transition actually fires or is blocked: a
+ # max_transitions pause that re-queues this transition
+ # must not leave a stale mark, or the resume would skip
+ # the join forever.
+ join_signature = (key, signature)
+ else:
+ sources = [raw_from]
+ when = transition.get("when")
+ if when is not None and not _guard_passes(when, outputs):
+ continue
+ target = run.states[transition["to"]]
+ from_field = transition["from"]
+ if target.entries_used >= target.max_entries:
+ if join_signature is not None:
+ # Blocked: this source-settle combination is consumed
+ # even though the target had no entries left.
+ run.join_fired[join_signature[0]] = join_signature[1]
+ self._event(
+ run,
+ "transition_blocked",
+ detail=(
+ f"state {target.state_id!r} is at max_entries "
+ f"{target.max_entries}; transition {from_field!r} -> {target.state_id!r} blocked"
+ ),
+ **{"from": from_field, "to": target.state_id},
+ )
+ continue
+ if run.transitions_fired >= run.max_transitions and not run.max_transitions_reported:
+ run.max_transitions_reported = True
+ entry.consumed = False
+ run.pending_evaluations.insert(0, (state_id, entry_index, transition_index))
+ run.state = "paused"
+ run.pause_reason = "max_transitions exceeded"
+ await self._milestone(
+ run,
+ "max_transitions_exceeded",
+ f"max_transitions {run.max_transitions} exceeded; no new entries; "
+ f"resume with await rlm.factory.resume('{run.run_id}')",
+ )
+ return
+ if join_signature is not None:
+ run.join_fired[join_signature[0]] = join_signature[1]
+ run.transitions_fired += 1
+ self._event(
+ run,
+ "transition_fired",
+ detail=f"{from_field!r} -> {target.state_id!r}",
+ **{"from": from_field, "to": target.state_id},
+ )
+ self._enter_state(run, target, from_state=state_id)
+
+ # -- readiness, binding, admission --------------------------------------
+
+ async def _spawn_ready(self, run: FactoryRun, *, generation: int, allow_backoff: bool) -> list[str]:
+ """Prepare ready entries and admit pending instances up to max_parallel.
+
+ The run budget is enforced BEFORE each admission (this phase runs
+ from run() and resume() too, not only the control loop): a slow
+ initial admission must not keep launching instances after
+ run_budget_ms expired. The run-wide child budget (max_children:
+ every admission over the run's life, foreach expansions and retry
+ re-spawns included) is enforced the same way — the next admission
+ over it pauses the run instead of launching the child.
+ Admission is also skipped while a
+ rate-limit backoff deadline is outstanding. Returns the state ids
+ that had at least one instance admitted here.
+ """
+ started: list[str] = []
+ while self._loop_alive(run, generation):
+ await self._prepare_ready_entries(run)
+ if not self._loop_alive(run, generation):
+ break
+ if self._run_budget_exceeded(run):
+ await self._pause_for_budget(run)
+ break
+ if run.admission_backoff_until is not None and self._now_fn() < run.admission_backoff_until:
+ break # the loop waits out the deadline in bounded slices
+ if self._running_instance_count(run) >= run.max_parallel:
+ break
+ pair = self._next_pending_instance(run)
+ if pair is None:
+ break
+ if self._children_budget_exceeded(run):
+ await self._pause_for_children(run)
+ break
+ state, entry, instance = pair
+ outcome = await self._admit(run, state, entry, instance, allow_backoff=allow_backoff)
+ if outcome == "admitted" and state.state_id not in started:
+ started.append(state.state_id)
+ if outcome == "stopped":
+ break # the run left "running" mid-admission; nothing to admit
+ if outcome == "deferred":
+ # A rate limit is usually global, so stop admitting in this
+ # phase; the control loop waits out the deadline and retries.
+ break
+ # "failed": the failure policy owns the run state now; the
+ # loop condition re-checks it before the next admission.
+ return started
+
+ def _loop_alive(self, run: FactoryRun, generation: int) -> bool:
+ """One control-lane pass is current: the run is running AND its
+ generation still owns the state (a resume bumped it)."""
+ return run.state == "running" and run.loop_generation == generation
+
+ def _run_budget_exceeded(self, run: FactoryRun) -> bool:
+ if run.run_budget_ms is None or run.budget_reported:
+ return False
+ return (self._now_fn() - run.started_at) * 1000 > run.run_budget_ms
+
+ async def _pause_for_budget(self, run: FactoryRun) -> None:
+ """Pause the run at the budget boundary (milestone fires once).
+
+ Children already in flight keep running; they settle normally once
+ the run resumes. Resuming after the milestone is an explicit operator
+ decision, so no further budget pauses fire (budget_reported)."""
+ elapsed_ms = (self._now_fn() - run.started_at) * 1000
+ run.state = "paused"
+ run.pause_reason = "run budget exceeded"
+ run.budget_reported = True
+ await self._milestone(
+ run,
+ "budget_exceeded",
+ f"run budget_ms {run.run_budget_ms} exceeded after {int(elapsed_ms)}ms; no new spawns; "
+ f"resume with await rlm.factory.resume('{run.run_id}')",
+ )
+
+ def _children_budget_exceeded(self, run: FactoryRun) -> bool:
+ if run.max_children_reported:
+ return False
+ return run.spawn_count >= run.max_children
+
+ async def _pause_for_children(self, run: FactoryRun) -> None:
+ """Pause the run at the child-budget boundary (milestone fires once).
+
+ max_children is the TOTAL-admission budget over the run's life:
+ spawn_count counts every admission, foreach expansions and retry
+ re-spawns included (max_parallel bounds concurrency only, and
+ max_transitions bounds transitions — neither bounds children).
+ Children already in flight keep running. Resuming after the
+ milestone is an explicit operator decision, so no further
+ child-budget pauses fire (max_children_reported)."""
+ run.state = "paused"
+ run.pause_reason = "max_children exceeded"
+ run.max_children_reported = True
+ await self._milestone(
+ run,
+ "max_children_exceeded",
+ f"run max_children {run.max_children} exceeded after {run.spawn_count} children; "
+ f"no new spawns; resume with await rlm.factory.resume('{run.run_id}')",
+ )
+
+ async def _prepare_ready_entries(self, run: FactoryRun) -> None:
+ """Bind inputs and create instances for every entry whose input
+ sources have settles."""
+ for state_id in run.order:
+ state = run.states[state_id]
+ for entry in state.entries:
+ if entry.status != "pending":
+ continue
+ instances, reason = self._prepare_entry(run, state, entry)
+ if reason is not None:
+ await self._apply_entry_failure_policy(run, state, entry, reason)
+ if run.state != "running":
+ return
+ continue
+ if instances is None:
+ continue # an input source has not settled yet; stay pending
+ entry.instances = instances
+ if instances:
+ entry.status = "running"
+ self._event(
+ run, "node_ready", node=state_id, entry=entry.index,
+ detail=f"{len(instances)} instance(s) prepared",
+ )
+ else:
+ entry.status = "done"
+ self._event(
+ run, "node_ready", node=state_id, entry=entry.index,
+ detail="foreach expanded to zero items; nothing to run",
+ )
+ self._queue_settle(run, state, entry)
+
+ def _prepare_entry(
+ self, run: FactoryRun, state: _StateRun, entry: _StateEntry
+ ) -> "tuple[list[_NodeInstance] | None, str | None]":
+ """Bind inputs, expand foreach, and render one prompt per instance.
+
+ Returns ``(instances, None)`` on success, ``(None, None)`` while an
+ input source has not settled yet (the entry stays pending), or
+ ``(None, reason)`` on a binding failure. Binding failures never
+ retry: a deterministic binding error would recur on every re-render,
+ so the entry fails and its failure_policy applies directly.
+ """
+ values: dict[str, str] = {}
+ foreach = state.spec.get("foreach")
+ items: list[Any] | None = None
+ for inp in state.spec.get("inputs") or []:
+ name, port_type, source = inp["name"], inp["type"], inp["from"]
+ src_id, _, src_output = source.partition(".")
+ source_state = run.states.get(src_id)
+ latest = source_state.latest_settle() if source_state is not None else None
+ value: Any = None
+ failure: str | None = None
+ if latest is not None:
+ # One settled source classifies into a captured value or a
+ # binding failure. An errored settle, a port whose JSON
+ # capture failed, and a declared port the settle captured
+ # no value for are all no-value conditions of a source
+ # that HAS settled -- the dependent sees none of them as a
+ # value.
+ if latest.status == "error":
+ failure = f"input {name!r} from state {src_id!r} is unavailable (latest settle status 'error')"
+ else:
+ outputs = latest.outputs or {}
+ output_errors = latest.output_errors or {}
+ if src_output in output_errors:
+ failure = f"input {name!r}: {output_errors[src_output]}"
+ elif src_output not in outputs:
+ failure = f"input {name!r} from state {src_id!r} has no captured output {src_output!r}"
+ else:
+ value = outputs[src_output]
+ if latest is None or failure is not None:
+ if inp.get("optional"):
+ # Optional inputs bind a null sentinel whenever their
+ # source offers no value -- never settled, errored
+ # settle, or a settled source that captured nothing
+ # for the port -- so loop states can re-enter before
+ # their upstream partner has run and after it failed
+ # or produced nothing usable (a compiled dag never
+ # sets optional: its input edges are transitions, so
+ # the wait-for-the-source semantics stay V1-exact).
+ # Only a REQUIRED input over a settled-but-valueless
+ # source fails the dependent: the guard-less
+ # transition still fires from the error settle, and
+ # the authoring reference pins the required form as
+ # the failing one. The foreach.over input is the one
+ # optional that cannot bind a sentinel: expansion
+ # would hit "did not resolve its over input" -- a
+ # hard failure where the required form only waits --
+ # so a value-less optional over expands to zero items
+ # (the same done-with-no-instances path as a settled
+ # empty list) and a later re-entry binds the real
+ # list.
+ if foreach is not None and foreach.get("over") == name:
+ items = []
+ continue
+ values[name] = "null" if port_type == "json" else "None"
+ continue
+ if latest is None:
+ return None, None # wait for the source's first settle
+ return None, failure
+ if port_type == "text":
+ values[name] = value if isinstance(value, str) else json.dumps(value)
+ continue
+ if foreach is not None and foreach.get("over") == name:
+ if not isinstance(value, list):
+ return None, f"foreach.over input {name!r} is not a JSON list"
+ items = value
+ continue
+ values[name] = json.dumps(value)
+ if foreach is None:
+ assert state.prompt_template is not None
+ instance = _NodeInstance(index=state.instance_counter, prompt=_render_prompt(state.prompt_template, values))
+ state.instance_counter += 1
+ return [instance], None
+ if items is None:
+ return None, "foreach entry did not resolve its over input"
+ instances = []
+ for item in items[: foreach["max"]]:
+ instance_value = item if isinstance(item, str) else json.dumps(item)
+ instances.append(
+ _NodeInstance(
+ index=state.instance_counter + len(instances),
+ prompt=_render_prompt(state.prompt_template, {**values, foreach["over"]: instance_value}),
+ )
+ )
+ state.instance_counter += len(instances)
+ return instances, None
+
+ def _next_pending_instance(self, run: FactoryRun) -> "tuple[_StateRun, _StateEntry, _NodeInstance] | None":
+ # Pending instances are admitted ONLY for running entries: a foreach
+ # entry that already failed (continue/escalate) must never run its
+ # queued siblings -- that would spend max_parallel slots on child
+ # work for an entry that is already terminal.
+ for state_id in run.order:
+ state = run.states[state_id]
+ for entry in state.entries:
+ if entry.status != "running":
+ continue
+ for instance in entry.instances:
+ if instance.status == "pending":
+ return state, entry, instance
+ return None
+
+ async def _admit(
+ self, run: FactoryRun, state: _StateRun, entry: _StateEntry, instance: _NodeInstance, *, allow_backoff: bool
+ ) -> str:
+ """Spawn one instance. Returns "admitted", "deferred", "failed", or
+ "stopped".
+
+ Rate-limited admissions never sleep inside this call: the loop path
+ records an exponential backoff deadline on the run (doubling delays
+ capped at 60s) and defers; the control loop waits out the deadline
+ in bounded slices capped at the collect poll timeout, so children
+ keep being collected and budgets keep being checked while admission
+ backs off -- a rate-limit retry never blocks the sole control lane
+ (a blocking backoff starved collection for the whole sleep). In the
+ admission phase (``allow_backoff=False``, run()/resume()) a rate
+ limit defers without recording a deadline: the loop's own retry
+ records it. At most ``BACKOFF_MAX_ATTEMPTS`` consecutive rate-limited
+ admissions of one instance fail the node through its failure_policy;
+ a successful admission resets the streak. Any other admission error
+ fails the entry immediately.
+
+ Every await re-checks the run state: a spawn that lands after
+ ``stop()`` is retracted (deleted and cancelled) instead of
+ registered running.
+ """
+ from . import spawn
+
+ instance.attempt += 1
+ child_name = _spawn_label(state.name, run.run_id, state.state_id, instance.index, instance.attempt)
+ try:
+ handle = await spawn(
+ instance.prompt, name=child_name, model=state.model, thinking=state.thinking
+ )
+ except RuntimeError as exc:
+ last_error = str(exc)
+ if _is_rate_limit_error(last_error):
+ if allow_backoff:
+ instance.rate_limit_streak += 1
+ if instance.rate_limit_streak >= BACKOFF_MAX_ATTEMPTS:
+ await self._apply_instance_failure(
+ run, state, entry, instance, f"spawn admission failed: {last_error}", retry=False
+ )
+ return "failed"
+ delay = min(
+ BACKOFF_BASE_SECONDS * (2 ** (instance.rate_limit_streak - 1)),
+ BACKOFF_CAP_SECONDS,
+ )
+ deadline = self._now_fn() + delay
+ if run.admission_backoff_until is None or deadline > run.admission_backoff_until:
+ run.admission_backoff_until = deadline
+ self._event(
+ run,
+ "spawn_backoff",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ detail=f"rate limited; retrying in {delay:g}s",
+ )
+ else:
+ self._event(
+ run,
+ "spawn_deferred",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ detail=f"rate limited at admission: {last_error}",
+ )
+ return "deferred"
+ await self._apply_instance_failure(
+ run, state, entry, instance, f"spawn admission failed: {last_error}", retry=False
+ )
+ return "failed"
+ if run.state != "running":
+ # stop() ran while the spawn was in flight: its cancellation
+ # pass could not see this child yet, so retract it here or it
+ # would outlive the stopped run under the supervisor.
+ instance.child_id = handle.rlm_child_id
+ await self._retract_admission(run, state, entry, instance)
+ return "stopped"
+ instance.child_id = handle.rlm_child_id
+ instance.spawned_at = self._now_fn()
+ instance.status = "running"
+ instance.rate_limit_streak = 0
+ run.spawn_count += 1
+ self._event(
+ run,
+ "spawned",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ attempt=instance.attempt,
+ child=handle.rlm_child_id,
+ name=child_name,
+ )
+ return "admitted"
+
+ # -- settlement, retries, policies ---------------------------------------
+
+ async def _apply_settlement(
+ self, run: FactoryRun, state: _StateRun, entry: _StateEntry, instance: _NodeInstance, result: Any
+ ) -> None:
+ if instance.status != "running":
+ return # cancelled (stop/fail_fast) while the collect was in flight
+ instance.duration_ms = result.duration_ms
+ instance.tool_uses = result.tool_use_count or 0
+ run.settle_count += 1
+ run.tool_use_total += instance.tool_uses
+ child_reason: str | None = None
+ if result.status == "error":
+ child_reason = result.error or f"child settled with status {result.status!r}"
+ elif result.status == "cancelled":
+ child_reason = "child was cancelled"
+ elif result.status != "done":
+ child_reason = f"child settled with unexpected status {result.status!r}"
+ if child_reason is not None:
+ # Child failures retry (same rendered prompt, attempts+1) while
+ # attempts remain; then the entry failure_policy applies.
+ await self._apply_instance_failure(run, state, entry, instance, child_reason, retry=True)
+ return
+ budget_ms = state.spec.get("budget_ms")
+ if budget_ms is not None and instance.spawned_at is not None:
+ elapsed_ms = (self._now_fn() - instance.spawned_at) * 1000
+ if elapsed_ms > budget_ms:
+ # Wall-clock budget (admission to settlement) exceeded: the
+ # budget is spent, so no retry; the failure_policy applies.
+ await self._apply_instance_failure(
+ run,
+ state,
+ entry,
+ instance,
+ f"state budget_ms {budget_ms} exceeded ({int(elapsed_ms)}ms from admission to settlement)",
+ retry=False,
+ )
+ return
+ instance.status = "done"
+ instance.answer = (result.answer_preview or "")[:ANSWER_CAPTURE_CAP] or None
+ self._event(
+ run,
+ "settled",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ status="done",
+ duration_ms=instance.duration_ms,
+ )
+ if instance.answer:
+ self._event(
+ run,
+ "answer_captured",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ answer=instance.answer,
+ stage="arrived",
+ )
+ if entry.status == "running" and entry.instances and all(i.status == "done" for i in entry.instances):
+ entry.status = "done"
+ entry.answer = self._entry_answer(entry)
+ self._capture_outputs(state, entry)
+ self._queue_settle(run, state, entry)
+
+ def _entry_answer(self, entry: _StateEntry) -> str | None:
+ """Captured answer for binding: one preview, or all instances joined."""
+ answers = [instance.answer for instance in entry.instances if instance.status == "done" and instance.answer]
+ if not answers:
+ return None
+ return "\n\n".join(answers)
+
+ def _capture_outputs(self, state: _StateRun, entry: _StateEntry) -> None:
+ """Capture the state's declared output ports from the entry's answer.
+
+ Text ports keep the captured string; json ports parse as in V1
+ binding, with the parse error recorded on the settle so a reader
+ (guard or input binding) fails deterministically instead of
+ re-parsing.
+ """
+ outputs: dict[str, Any] = {}
+ errors: dict[str, str] = {}
+ for out in state.spec.get("outputs") or []:
+ name, port_type = out.get("name"), out.get("type")
+ if port_type == "text":
+ if entry.answer is not None:
+ outputs[name] = entry.answer
+ continue
+ if entry.answer is None:
+ continue
+ parsed, error = _parse_json_output(entry.answer, name)
+ if error is None:
+ outputs[name] = parsed
+ else:
+ errors[name] = error
+ entry.outputs = outputs
+ entry.output_errors = errors
+
+ async def _apply_instance_failure(
+ self, run: FactoryRun, state: _StateRun, entry: _StateEntry, instance: _NodeInstance, reason: str, *, retry: bool
+ ) -> None:
+ instance.status = "error"
+ instance.error = reason
+ self._event(
+ run,
+ "settled",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ status="error",
+ error=reason,
+ duration_ms=instance.duration_ms,
+ )
+ retries = state.spec.get("retries", NODE_RETRIES_DEFAULT)
+ # A retry is only queued when the entry can re-admit it: a foreach
+ # sibling failing with retries left after its entry already went
+ # terminal (a sibling failed it permanently first) would otherwise
+ # sit pending forever -- _next_pending_instance serves running
+ # entries only, while _run_complete and the stall detector both
+ # count the pending instance as in-flight, so the control loop
+ # would never finish the run. The failed instance settles as an
+ # error instead; the policy call below is a no-op on a terminal
+ # entry.
+ if retry and instance.attempt <= retries and entry.status == "running":
+ instance.status = "pending"
+ instance.error = None
+ self._event(
+ run,
+ "retry",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ detail=f"attempt {instance.attempt} failed; re-spawning (retries {retries})",
+ )
+ return
+ # The instance failed permanently, so the entry fails NOW. A foreach
+ # entry does not wait for its remaining instances: without this, a
+ # failure that settles before its siblings leaves the entry stuck in
+ # running with every instance terminal, and fail_fast could never
+ # cancel in-flight siblings. The policy guard makes the second and
+ # later permanent failures no-ops.
+ await self._apply_entry_failure_policy(run, state, entry, reason)
+
+ async def _apply_entry_failure_policy(
+ self, run: FactoryRun, state: _StateRun, entry: _StateEntry, reason: str
+ ) -> None:
+ if entry.status in TERMINAL_ENTRY_STATUSES:
+ return # the policy already ran for this entry
+ policy = state.spec.get("failure_policy", RUN_FAILURE_POLICY_DEFAULT)
+ entry.status = "error"
+ entry.error = reason
+ state.error = reason
+ self._event(run, "node_error", node=state.state_id, entry=entry.index, error=reason, detail=f"failure_policy {policy}")
+ # The entry is terminal: its prepared-but-never-admitted instances
+ # (a foreach queue behind max_parallel, or a rate-limit deferral)
+ # can never run now, so mark them cancelled with their own ledger
+ # event instead of leaving them pending forever.
+ for instance in entry.instances:
+ if instance.status == "pending":
+ instance.status = "cancelled"
+ self._event(
+ run,
+ "cancelled",
+ node=state.state_id,
+ entry=entry.index,
+ instance=instance.index,
+ detail="entry failed before admission",
+ )
+ # The failed entry settles too: guard-less transitions (the compiled
+ # dag's depends_on edges) fire from error settles so dependents run.
+ self._queue_settle(run, state, entry)
+ if run.state != "running":
+ # stop() (or another transition) owns the run state now; keep the
+ # entry's error but do not overwrite the final state.
+ return
+ if policy == "fail_fast":
+ await self._halt_nonterminal(run, "run failed (fail_fast)")
+ if run.state != "running":
+ return # stop() landed during the cancellations; it wins
+ cancelled_children = sum(
+ 1
+ for other in run.states.values()
+ for other_entry in other.entries
+ for i in other_entry.instances
+ if i.status == "cancelled"
+ )
+ run.state = "failed"
+ await self._milestone(
+ run,
+ "failed",
+ f"state {state.state_id} failed: {reason}; cancelled {cancelled_children} in-flight child(ren)",
+ node=state.state_id,
+ )
+ elif policy == "continue":
+ pass # the entry stays error; dependents see the error settle at binding
+ else: # escalate (default)
+ run.state = "paused"
+ run.pause_reason = reason
+ await self._milestone(
+ run,
+ "paused",
+ f"state {state.state_id} failed: {reason}; resume with await rlm.factory.resume('{run.run_id}')",
+ node=state.state_id,
+ )
+
+ async def _halt_nonterminal(self, run: FactoryRun, reason: str) -> list[str]:
+ """Delete every running child and cancel every non-terminal entry;
+ never-entered states are marked cancelled.
+
+ A state participates when ANY entry is non-terminal, not only the
+ latest one: a re-entered state can keep an earlier entry in flight
+ while its latest entry settled, and that entry must be cancelled too
+ (state.status reports the latest entry only).
+ """
+ stopped = [
+ state_id
+ for state_id in run.order
+ if any(entry.status in ("pending", "running") for entry in run.states[state_id].entries)
+ or (not run.states[state_id].entries and run.states[state_id].status == "pending")
+ ]
+ await self._cancel_running(run)
+ for state_id in stopped:
+ state = run.states[state_id]
+ if any(entry.status in ("pending", "running") for entry in state.entries) or not state.entries:
+ state.cancelled = True
+ for entry in state.entries:
+ if entry.status in ("pending", "running"):
+ entry.status = "cancelled"
+ self._event(run, "node_cancelled", node=state_id, entry=entry.index, detail=reason)
+ for instance in entry.instances:
+ if instance.status == "pending":
+ # Prepared but never admitted (or still in
+ # flight inside _admit): the cancelled entry
+ # owns it, so it reads cancelled, not pending,
+ # in the stopped/failed ledger.
+ instance.status = "cancelled"
+ self._event(
+ run,
+ "cancelled",
+ node=state_id,
+ entry=entry.index,
+ instance=instance.index,
+ detail="cancelled before admission",
+ )
+ return stopped
+
+ async def _retract_admission(
+ self, run: FactoryRun, state: _StateRun, entry: _StateEntry, instance: _NodeInstance
+ ) -> None:
+ """Cancel an admission that landed after the run left "running".
+
+ ``stop()`` cancels every child it can see before it returns; a spawn
+ that was still in flight during that pass is invisible to it, so the
+ just-returned child is deleted here and the instance is marked
+ cancelled instead of registered running. Without this the child
+ would keep running under the supervisor after a "stopped" run.
+ """
+ from . import delete_subagent
+
+ child_id = instance.child_id or ""
+ try:
+ await delete_subagent(child_id)
+ except Exception as exc:
+ self._event(run, "cancel_failed", node=state.state_id, entry=entry.index, instance=instance.index, child=child_id, error=str(exc))
+ # The slot is released either way, so the ledger must record the
+ # cancellation next to the failure (the eval replay checker keys
+ # off cancelled events, and the instance below reads cancelled).
+ self._event(run, "cancelled", node=state.state_id, entry=entry.index, instance=instance.index, child=child_id, detail="slot released despite the failed delete")
+ else:
+ self._event(run, "cancelled", node=state.state_id, entry=entry.index, instance=instance.index, child=child_id)
+ # The child is supervisor-owned; a failed delete leaves it running
+ # there, but the executor treats its slot as released.
+ instance.status = "cancelled"
+
+ async def _cancel_running(self, run: FactoryRun) -> None:
+ from . import delete_subagent
+
+ for state_id in run.order:
+ state = run.states[state_id]
+ for entry in state.entries:
+ for instance in entry.instances:
+ if instance.status != "running" or instance.child_id is None:
+ continue
+ child_id = instance.child_id
+ # Claim the instance BEFORE the await: a concurrent
+ # cancellation pass (stop() racing fail_fast's cascade, or a
+ # repeated stop) must never issue a duplicate delete for a
+ # child this pass already owns. A failed delete still
+ # releases the slot, so the terminal status is the same
+ # either way, and a settle landing inside the delete window
+ # is dropped instead of applying to a child being torn down.
+ instance.status = "cancelled"
+ try:
+ await delete_subagent(child_id)
+ except Exception as exc:
+ self._event(run, "cancel_failed", node=state_id, entry=entry.index, instance=instance.index, child=child_id, error=str(exc))
+ # The slot is released either way, so the ledger also
+ # records the cancellation next to the failure (the
+ # eval replay checker keys off cancelled events, and
+ # the instance above already reads cancelled).
+ self._event(run, "cancelled", node=state_id, entry=entry.index, instance=instance.index, child=child_id, detail="slot released despite the failed delete")
+ else:
+ self._event(run, "cancelled", node=state_id, entry=entry.index, instance=instance.index, child=child_id)
+ # The child is supervisor-owned; a failed delete leaves it
+ # running there, but the executor treats its slot as released.
+
+ # -- completion ----------------------------------------------------------
+
+ def _run_complete(self, run: FactoryRun) -> bool:
+ """Quiescence: no unevaluated settle, no entry in flight, and no
+ instance still queued for admission or awaiting settlement.
+
+ The INSTANCE layer matters too: a failed foreach entry whose
+ siblings are still running (continue policy) is terminal at the
+ entry layer, but the run is not quiescent until those children
+ settle -- finalizing earlier orphaned them under the supervisor
+ with no collector. Admitted resident instances are the one
+ exception: they stay alive under the parent session until
+ rlm.factory.stop() or session teardown, so a resident entry's
+ running instances never block completion -- but its still-queued
+ (pending) instances do: the admission queue must drain before the
+ run can end, or a resident left pending by max_parallel was
+ misreported as quiescent and never admitted."""
+ if run.pending_evaluations:
+ return False
+ for state in run.states.values():
+ resident = state.lifecycle == "resident"
+ for entry in state.entries:
+ if entry.status in ("pending", "running"):
+ if not (resident and entry.status == "running"):
+ return False
+ for instance in entry.instances:
+ if instance.status == "pending":
+ return False
+ if instance.status == "running" and not (resident and entry.status == "running"):
+ return False
+ return True
+
+ async def _finalize(self, run: FactoryRun) -> None:
+ if run.state != "running":
+ return # stop() or a failure policy owns the final state
+ errors = [
+ state
+ for state in run.states.values()
+ if any(entry.status == "error" for entry in state.entries)
+ ]
+ if errors:
+ run.state = "failed"
+ await self._milestone(
+ run,
+ "failed",
+ "completed with state error(s): " + ", ".join(state.state_id for state in errors),
+ )
+ return
+ run.state = "done"
+ residents = [
+ state
+ for state in run.states.values()
+ if state.lifecycle == "resident"
+ and any(entry.status == "running" for entry in state.entries)
+ ]
+ detail = f"run complete: {len(run.states)} state(s), {run.transitions_fired} transition(s) fired"
+ if residents:
+ detail += f"; {len(residents)} resident state(s) still running (stop with await rlm.factory.stop('{run.run_id}'))"
+ await self._milestone(run, "finished", detail)
+
+ # -- control loop --------------------------------------------------------
+
+ def _start_loop(self, run: FactoryRun) -> None:
+ # Called only from run()/resume(), both awaited inside a running
+ # asyncio loop, so get_running_loop() always finds it.
+ import asyncio
+
+ run.task = asyncio.get_running_loop().create_task(
+ self._control_loop(run, run.loop_generation)
+ )
+
+ async def _control_loop(self, run: FactoryRun, generation: int) -> None:
+ import asyncio
+
+ try:
+ await self._loop_body(run, generation)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ # A dead bridge or host failure must not wedge the run silently;
+ # children stay alive under the supervisor either way. A stop()
+ # that landed concurrently keeps ownership of the final state.
+ self._event(run, "executor_error", error=f"{type(exc).__name__}: {exc}")
+ if run.state == "running":
+ run.state = "failed"
+ try:
+ await self._milestone(run, "failed", f"executor error: {exc}")
+ except Exception:
+ pass
+
+ async def _loop_body(self, run: FactoryRun, generation: int) -> None:
+ import asyncio
+
+ from . import collect
+
+ # The generation re-checks after every await are the resume-race
+ # fix: a resume() that lands while this task is suspended at an
+ # await (an in-flight collect or milestone) bumps the generation,
+ # so this task exits at its next check instead of continuing as a
+ # second concurrent control loop.
+ while self._loop_alive(run, generation):
+ in_flight = [
+ (run.states[state_id], entry, instance)
+ for state_id in run.order
+ for entry in run.states[state_id].entries
+ for instance in entry.instances
+ if instance.status == "running" and instance.child_id is not None
+ ]
+ if in_flight:
+ results = await collect(
+ [instance.child_id for _, _, instance in in_flight], timeout_ms=POLL_TIMEOUT_MS
+ )
+ settled = {entry.rlm_child_id: entry for entry in results if entry.settled}
+ for state, entry, instance in in_flight:
+ # A GENERATION bump mid-batch drops this collect's
+ # results: the resumed loop re-collects the children
+ # (they stay running supervisor-side), so no settle is
+ # applied by two lanes. A pause or stop that this very
+ # batch triggered does NOT drop the rest of the batch:
+ # the old design (and its tests) finish applying the
+ # batch's settlements, and a policy pause must not
+ # strand the siblings' statuses.
+ if run.loop_generation != generation:
+ return
+ result = settled.get(instance.child_id or "")
+ if result is not None:
+ await self._apply_settlement(run, state, entry, instance, result)
+ # Re-check state before completion: stop() (or a policy transition)
+ # can land while the collect above was in flight, and a run that
+ # was stopped must never finalize as done.
+ if not self._loop_alive(run, generation):
+ return
+ await self._evaluate_settles(run)
+ if not self._loop_alive(run, generation):
+ return
+ if self._run_complete(run):
+ await self._finalize(run)
+ return
+ if self._run_budget_exceeded(run):
+ await self._pause_for_budget(run)
+ return
+ started = await self._spawn_ready(run, generation=generation, allow_backoff=True)
+ if not self._loop_alive(run, generation):
+ return
+ if run.admission_backoff_until is not None and self._now_fn() < run.admission_backoff_until:
+ # Admission is backed off: wait out the deadline in bounded
+ # slices (capped at the collect poll timeout) instead of
+ # hot-spinning -- and instead of blocking the lane with one
+ # long sleep: children that settle during the slice are
+ # collected on the next iteration, within the same bound a
+ # normal collect wait already has.
+ remaining = run.admission_backoff_until - self._now_fn()
+ await self._sleep_fn(min(remaining, POLL_TIMEOUT_MS / 1000))
+ continue
+ if not run.pending_evaluations and self._resident_cap_starved(run):
+ # Residents never settle, so a max_parallel cap held entirely
+ # by resident instances never frees a slot: the queued work
+ # would wait forever, and the no-in-flight stall check below
+ # never fires because the residents keep children in flight.
+ # End the run instead of polling a dead end; stop() still
+ # tears the resident children down.
+ reason = (
+ f"control loop stalled: resident instances hold every max_parallel {run.max_parallel} slot; "
+ "queued instances can never be admitted"
+ )
+ self._event(run, "executor_error", error=reason)
+ run.state = "failed"
+ try:
+ await self._milestone(run, "failed", reason)
+ except Exception:
+ pass
+ return
+ resident_only_in_flight = all(
+ state.lifecycle == "resident" for state, _, _ in in_flight
+ )
+ if (
+ (not in_flight or resident_only_in_flight)
+ and not started
+ and not self._has_pending_instance(run)
+ and not run.pending_evaluations
+ ):
+ # Defensive: nothing in flight, nothing admitted, nothing
+ # pending -- or only resident instances in flight, which
+ # never settle and can never unblock anything (residents
+ # declare no outputs and no outgoing transitions, so a
+ # pending entry's input source can only stay unsettled).
+ # The one reachable shape is a pending entry whose input
+ # source never settled; end the run instead of spinning.
+ stuck = [
+ state_id
+ for state_id in run.order
+ for entry in run.states[state_id].entries
+ if entry.status == "pending" and not entry.instances
+ ]
+ if stuck:
+ reason = (
+ "control loop stalled: pending entry of state "
+ + ", ".join(repr(state_id) for state_id in stuck)
+ + " is waiting for an input source that never settled"
+ )
+ else:
+ reason = "control loop stalled: no in-flight or pending work"
+ self._event(run, "executor_error", error=reason)
+ run.state = "failed"
+ try:
+ await self._milestone(run, "failed", reason)
+ except Exception:
+ pass
+ return
+ # Yield once per iteration. A real collect already waits up to
+ # POLL_TIMEOUT_MS, but an instantly-settling host (tests, a fast
+ # supervisor) must not hot-spin the loop and starve other tasks.
+ await asyncio.sleep(0)
+
+ # -- small helpers --------------------------------------------------------
+
+ def _running_instance_count(self, run: FactoryRun) -> int:
+ return sum(
+ 1
+ for state in run.states.values()
+ for entry in state.entries
+ for instance in entry.instances
+ if instance.status == "running"
+ )
+
+ def _resident_cap_starved(self, run: FactoryRun) -> bool:
+ """True when queued instances can never be admitted: every
+ ``max_parallel`` slot is held by a never-settling resident instance.
+
+ Residents stay running until ``stop()`` tears them down, so a cap
+ held entirely by resident instances never frees a slot and pending
+ instances behind that cap would wait forever. One task instance in
+ flight means a slot can still open on its settle, so that is not a
+ dead end.
+ """
+ running = [
+ state.lifecycle == "resident"
+ for state in run.states.values()
+ for entry in state.entries
+ for instance in entry.instances
+ if instance.status == "running"
+ ]
+ if len(running) < run.max_parallel or not self._has_pending_instance(run):
+ return False
+ return all(running)
+
+ def _has_pending_instance(self, run: FactoryRun) -> bool:
+ return any(
+ instance.status == "pending"
+ for state in run.states.values()
+ for entry in state.entries
+ for instance in entry.instances
+ )
+
+ def _pending_state_ids(self, run: FactoryRun) -> list[str]:
+ return [state_id for state_id in run.order if run.states[state_id].status == "pending"]
+
+
+# ---------------------------------------------------------------------------
+# The opt-in gate: `factory.enabled` in the agent-dir settings file.
+# ---------------------------------------------------------------------------
+
+#: The single refusal every gated factory call raises while the setting is
+#: off. One exact message, so agents and tests can pin the refusal.
+FACTORY_DISABLED_MESSAGE = "the factory is disabled; run /factory on to enable it"
+
+_SETTINGS_FILE_NAME = "settings.json"
+
+
+def factory_enabled() -> bool:
+ """Read the ``factory.enabled`` opt-in setting (default off).
+
+ The factory is opt-in: it ships disabled, and the user turns it on with
+ ``/factory on`` (the persisted setting is ``factory.enabled`` in the
+ agent dir's ``settings.json`` -- the same nested-camelCase document the
+ daemon and TUI settings surface write, e.g. ``{"factory": {"enabled":
+ true}}`` beside ``compaction``/``agentTraces``). The read mirrors the
+ lenient settings loading on the Rust side: a missing file or key, a
+ wrong-typed value, or a corrupt document all read as unset, and unset
+ means disabled -- the opt-in default is fail-closed, so an unreadable
+ settings file refuses the factory instead of silently enabling it.
+ """
+ # One home for the agent-dir resolution (harness.py owns it); imported
+ # lazily because harness imports this module at its own top.
+ from .harness import _agent_dir
+
+ path = _agent_dir() / _SETTINGS_FILE_NAME
+ try:
+ with open(path, encoding="utf-8") as handle:
+ document = json.load(handle)
+ except (OSError, ValueError):
+ return False
+ if not isinstance(document, dict):
+ return False
+ factory = document.get("factory")
+ if not isinstance(factory, dict):
+ return False
+ return factory.get("enabled") is True
+
+
+def require_factory_enabled() -> None:
+ """Refuse with one clean error while the factory is disabled.
+
+ Every gated surface funnels through here -- the ``rlm.factory``
+ namespace calls (``run``/``status``/``stop``/``resume``, and the later
+ ``graph``/``watch``) and the factory harness writes -- so the refusal is
+ one message at every seam. ``help()`` is deliberately exempt: the
+ authoring reference must stay readable before opting in.
+ """
+ if not factory_enabled():
+ raise ValueError(FACTORY_DISABLED_MESSAGE)
+
+
+_DEFAULT_EXECUTOR: FactoryExecutor | None = None
+
+
+def default_factory_executor() -> FactoryExecutor:
+ """The process-wide executor behind the ``rlm.factory`` namespace.
+
+ Tests that need an injected clock or sleep assign their own
+ ``FactoryExecutor`` to ``factory._DEFAULT_EXECUTOR``; the namespace then
+ routes through it.
+ """
+ global _DEFAULT_EXECUTOR
+ if _DEFAULT_EXECUTOR is None:
+ _DEFAULT_EXECUTOR = FactoryExecutor()
+ return _DEFAULT_EXECUTOR
+
+
+async def run_factory(spec_id: str, *, name: str | None = None) -> dict[str, Any]:
+ """Validate a stored factory spec and start a nonblocking run of it."""
+ require_factory_enabled()
+ return await default_factory_executor().run(spec_id, name=name)
+
+
+async def status_factory(run_id: str) -> dict[str, Any]:
+ """Return state states, the event window, elapsed time, and usage."""
+ require_factory_enabled()
+ return await default_factory_executor().status(run_id)
+
+
+async def stop_factory(run_id: str) -> dict[str, Any]:
+ """Cancel every running child of the run and mark it stopped."""
+ require_factory_enabled()
+ return await default_factory_executor().stop(run_id)
+
+
+async def resume_factory(run_id: str) -> dict[str, Any]:
+ """Resume a paused run (escalate, budget, or max_transitions pause)."""
+ require_factory_enabled()
+ return await default_factory_executor().resume(run_id)
+
+
+FACTORY_HELP: str = r"""# Factory
+
+The factory runs state-machine workflows of spawned child agents. A stored
+factory entry declares the machine — states, each backed by a subagent
+spec, plus guarded transitions between them. `await rlm.factory.run('<spec_id>')`
+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.
+
+The factory is opt-in: it ships disabled, and the user turns it on with
+`/factory on` (`/factory off` disables it again, `/factory status` reports
+it; the persisted setting is `factory.enabled` in the agent dir's
+settings.json). While it is disabled, every `rlm.factory` call except
+`help()` — run, status, stop, and resume — plus every factory harness
+write (`create_factory` and updates of factory entries) refuses with one
+clean error:
+"the factory is disabled; run /factory on to enable it". `help()` answers
+while disabled, so this guide stays readable before opting in.
+
+## Store the spec
+
+A factory spec is a continual-harness entry of kind `factory`.
+`rlm.harness.create_factory(...)` validates at write time; an invalid spec
+is never stored (generic `create`/`update` funnel through the same check).
+The spec rides `machine=` (the native form) or `dag=` (sugar that compiles
+to machine form) — pass exactly one. This review/fix loop is the shipped
+pr-manager shape:
+
+```python
+rlm.harness.create_factory(
+ "pr-manager",
+ "Drive a PR through review/fix cycles, then keep a resident watcher on it.",
+ id="pr-manager",
+ machine={
+ "run": {"budget_ms": 1_800_000, "max_parallel": 8, "max_transitions": 24},
+ "states": [
+ {
+ "id": "entry", "entry": True,
+ "subagent": {"prompt": (
+ "Identify the pull request for the current branch with "
+ "`gh pr view --json url`. Return a fenced json block of the form "
+ '{"pr_url": "https://github.com/owner/repo/pull/N"}. '
+ "Output only the json block.")},
+ "outputs": [{"name": "pr_url", "type": "json"}],
+ },
+ {
+ "id": "reviewing",
+ "subagent": {"prompt": (
+ "Review the pull request at {pr_url} for merge-blocking "
+ "defects with `gh pr diff`. When a fix report is bound below, "
+ "verify the described fixes landed. Return a fenced json block "
+ 'of the form {"verdict": {"approved": <true|false>, '
+ '"findings": ["at most three one-line findings"]}}. '
+ "Output only the json block.")},
+ "inputs": [
+ {"name": "pr_url", "type": "json", "from": "entry.pr_url"},
+ {"name": "fix_report", "type": "json", "from": "fixing.fix_report", "optional": True},
+ ],
+ "outputs": [{"name": "verdict", "type": "json"}],
+ "max_entries": 4,
+ },
+ {
+ "id": "fixing",
+ "subagent": {"prompt": (
+ "Address the review findings in the verdict below. Make the "
+ "smallest targeted fixes, run the relevant tests, and return a "
+ "fenced json block of the form "
+ '{"fix_report": {"fixed": ["finding that was addressed"], '
+ '"skipped": ["finding left alone and why"]}}. '
+ "Output only the json block.\n\n{verdict}")},
+ "inputs": [{"name": "verdict", "type": "json", "from": "reviewing.verdict"}],
+ "outputs": [{"name": "fix_report", "type": "json"}],
+ "max_entries": 3,
+ },
+ {
+ "id": "monitoring",
+ "subagent": {"prompt": "Stay resident as the watcher for {pr_url}: "
+ "report the `gh pr checks` state once, then remain available for "
+ "follow-up questions."},
+ "inputs": [{"name": "pr_url", "type": "json", "from": "entry.pr_url"}],
+ "lifecycle": "resident",
+ },
+ ],
+ "transitions": [
+ {"from": "entry", "to": "reviewing"},
+ {"from": "reviewing", "to": "fixing",
+ "when": {"output": "verdict", "path": "approved", "op": "eq", "value": False}},
+ {"from": "reviewing", "to": "monitoring",
+ "when": {"output": "verdict", "path": "approved", "op": "eq", "value": True}},
+ {"from": "fixing", "to": "reviewing"},
+ ],
+ },
+)
+```
+
+The example exercises the core forms: `entry` is an entry state; the two
+guards select the next state from the reviewer's `verdict`; `fix_report` is
+optional, so the reviewer's first entry binds a null sentinel before the
+fixer ever runs and its re-entry re-binds the real report; `max_entries`
+bounds the loop; `monitoring` is a `resident` that stays alive under the
+parent session after the run ends. Both worked examples bound their
+emitted payloads in the prompt — a capped findings list here, a capped
+file list in the review-sweep example — because captured answers are
+capped previews: an unbounded payload truncates at the cap and fails to
+bind.
+
+## Authoring reference
+
+- **States**: 1 to 1024, unique ids matching `^[a-z0-9][a-z0-9-]{0,63}$`; at
+ least one state carries `"entry": true`, and entry states declare no
+ inputs. A state's `subagent` is a harness subagent entry id or title (its
+ content is the prompt template; `metadata.model`/`metadata.thinking` are
+ spawn settings) or an inline `{"prompt": ...}` object with optional
+ `name`/`model`/`thinking`. The optional `name` labels the spawned
+ children (at most 64 characters, unique across the machine's states —
+ a name another state's name can suffix onto, `foo` vs `foo-i1`, is
+ rejected at write time): the first instance is named exactly `name` —
+ the label to message the child by — and re-entries, foreach fan-out,
+ and retries disambiguate with the same `-i<n>`/`-a<n>` suffixes the
+ generated labels use; a suffixed label that would pass the host's
+ 64-character cap shrinks its base with a digest of the full name, like
+ the generated labels do.
+- **Ports**: inputs and outputs of type `text` or `json`. An input binds
+ `"from": "<state_id>.<output_name>"`; types must match, duplicates are
+ rejected, and nothing can read from a resident. Bound values render into
+ `{input_name}` placeholders (one pass; inputs without a placeholder are
+ appended in a trailing `## Inputs` section). A required input whose source
+ has not settled yet keeps the entry pending; over a settled source that
+ offers no value (an errored settle, a port the settle captured no value
+ for, or a JSON capture failure) it fails the dependent entry, while
+ `"optional": true` binds a null sentinel in every no-value case (a
+ source that offers no value is not a value, so the dependent that
+ declared the input optional proceeds). A required self-input is
+ rejected at validation —
+ `state X input 'name' cannot require itself: mark the self-input optional
+ - a required one can never bind on the state's first entry` — while an
+ optional self-input is the designed self-loop form (first entry binds
+ null, re-entries bind the previous settle).
+- **Transitions**: `{"from": ..., "to": ..., "on": "settled", "when": ...}`.
+ Each settle is evaluated exactly once and every guard that passes fires
+ (fan-out is legal); a fire onto a state at `max_entries` is recorded as a
+ blocked transition. `from` may be a list of states: a join that fires
+ once every source settled — once per source-settle combination — and may
+ not carry a guard. Guards are `{"output": ..., "path": ..., "op": ...,
+ "value": ...}` over the from-state's latest settle: `op` is one of `eq`,
+ `ne`, `gt`, `gte`, `lt`, `lte`, `exists`, `contains`; `path` drills a
+ dotted path into a `json` output; `eq`/`ne` compare JSON-strictly (a
+ boolean never equals a number), comparison ops need a numeric value,
+ `contains` a non-empty list, `exists` no value, and a missing or
+ unparseable port fails every op except `exists`. A failed settle still
+ fires guard-less transitions, so dependents under `continue` run; their
+ required input over the failed source then fails the dependent entry,
+ while an optional input over the failed source binds the null sentinel
+ and the dependent proceeds.
+- **Cycles are legal**: there is no acyclicity requirement — self-loops and
+ back edges validate. The one rule is an entry state somewhere; a dag
+ whose every node depends on another compiles to no entry states and is
+ rejected.
+- **foreach**: `{"over": "<input>", "max": 1..256}` expands one entry into
+ one child per item of the named `json` input (clamped at `max`), each
+ child rendered with its item bound as that input; an empty list settles
+ the entry with no children.
+- **Residents**: `"lifecycle": "resident"` states declare no outputs, no
+ foreach, and no outgoing transitions, nothing reads from them, and their
+ instance stays alive under the parent session after the run completes
+ (stop the run to retire it).
+- **Bounds and policies**: `run.max_parallel` (1..64, default 8) is the
+ run's global budget of simultaneously running instances — not a
+ per-node limit. `run.max_children` (default 10,000, capped at
+ 1,000,000) is the run's global budget of total admissions over its
+ life — foreach expansions and retry re-spawns included (neither
+ `max_parallel` nor `max_transitions` bounds children); reaching it
+ pauses the run once, and `resume` continues past it as an explicit
+ operator decision. `run.max_transitions` (default 10 per state, capped
+ at 10,000) pauses the run once at the boundary, mid-settle; `resume`
+ continues after the transitions that already fired without re-firing
+ them. `run.budget_ms` pauses the run once when exceeded (in-flight
+ children keep running). Per state: `max_entries` (default 1), `retries`
+ (0..10, same rendered prompt), `budget_ms` (admission to settlement;
+ exceeding it fails the attempt without a retry), and `failure_policy` —
+ `fail_fast` (cancel every child, run failed), `continue` (entry stays
+ errored; the run finishes and reports failed if any state errored), or
+ `escalate` (the default: pause the run; resuming is the operator's
+ decision).
+- **Dead configurations fail loudly, never wedge**: a pending entry whose
+ input source never settled, a `max_parallel` cap held entirely by
+ never-settling residents with work queued, or nothing in flight and
+ nothing pending each end the run as failed with the reason in the
+ ledger. `wait` blocks on states are rejected at validation (not
+ supported yet).
+
+## Dag form
+
+Sugar, not a second semantics: each node becomes a state entered once, a
+node with no effective dependencies becomes an entry state, and the full
+dependency set — `depends_on` plus every `inputs[].from` source — compiles
+to ONE join transition, so a fan-in node waits for every parent. The
+shipped review-sweep shape:
+
+```python
+rlm.harness.create_factory(
+ "review-sweep",
+ "Sweep the branch's changed files for findings, then merge them into one list.",
+ id="review-sweep",
+ dag={
+ "run": {"budget_ms": 900_000, "max_parallel": 8},
+ "nodes": [
+ {
+ "id": "files",
+ "subagent": {"prompt": (
+ "List the files the current branch changes relative to the "
+ "base branch, capped at the eight most relevant. Return "
+ 'a fenced json block of the form {"files": ["path/to/file", ...]}. '
+ "Output only the json block.")},
+ "outputs": [{"name": "files", "type": "json"}],
+ },
+ {
+ "id": "review",
+ "subagent": {"prompt": (
+ "Review the changed file {files} for merge-blocking defects: "
+ "correctness bugs, regressions, unhandled error paths, missing "
+ "tests. Reply one short line: `<path>: <the most serious "
+ "problem, or 'clean'>`.")},
+ "inputs": [{"name": "files", "type": "json", "from": "files.files"}],
+ "outputs": [{"name": "found", "type": "text"}],
+ "foreach": {"over": "files", "max": 8},
+ },
+ {
+ "id": "report",
+ "subagent": {"prompt": (
+ "Merge the review lines below into one fenced json block of "
+ 'the form {"issues": [{"file": "path", "finding": "..."}]} '
+ "listing every file that is not clean. Output only the json "
+ "block.\n\n{found}")},
+ "inputs": [{"name": "found", "type": "text", "from": "review.found"}],
+ },
+ ],
+ },
+)
+```
+
+## Run and steer
+
+```python
+result = await rlm.factory.run("pr-manager")
+# {"run_id": "...", "spec_id": "pr-manager", "nodes": 4, "max_parallel": 8,
+# "started": ["entry"], "pending": []} — returns immediately.
+
+status = await rlm.factory.status(result["run_id"])
+status["state"] # running | stopping | paused | done | failed | stopped
+status["nodes"] # per state: status, entries_used/max_entries, instances,
+ # latest answer_preview, error
+status["events"] # trailing ledger: spawned, settled, answer_captured,
+ # transition_fired, node_error, milestone, ...
+status["usage"] # spawns, settled, tool_uses, max_parallel, max_children, running,
+ # 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.
+
+- `run` re-validates the spec and resolves every subagent reference first,
+ reporting all failures in one `ValueError` and starting nothing on any
+ failure; `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.
+- `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.
+
+## Discovering machines
+
+- The machine library (arriving on the stacked machine-library PR):
+ machines are `MACHINE.md` files, one directory per machine under the
+ repository's `machines/` and a personal `machines/` library under the
+ agent dir; `prime-agent factory list | import | export` manages them. The
+ seeds are `builder`, `pr-manager`, and `review-sweep`; the worked
+ examples above derive 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.
+
+## Safety
+
+- Every state spawns real children that spend budget. Bound loops with
+ `max_entries`, `max_transitions`, and `run.max_children` (total
+ admissions); the default `escalate` policy pauses
+ instead of failing, so read `status` (or the notice) before resuming.
+- Captured answers are capped previews (about 160 characters) and outputs
+ bind from them: keep declared outputs compact — a small fenced json
+ block or one short line — and let the full answer live in the child's
+ session.
+- Run registries live in kernel memory: a kernel restart loses `status`
+ for old runs, but the children keep running under the supervisor
+ (`rlm.list_subagents` sees them). Stop runs before restarting, or
+ delete the children by hand afterwards.
+- Residents outlive their run; stop the run (or tear down the session) to
+ retire them. Prefer `rlm.factory.stop(run_id)` over deleting a factory
+ child by hand — the executor claims and cancels children itself, and a
+ hand deletion surfaces as a child failure through the state's policy.
+"""
\ No newline at end of file
diff --git a/prime-agent-runtime/src/rlm/harness.py b/prime-agent-runtime/src/rlm/harness.py
index 03dabfaf2e..4d399da3a6 100644
--- a/prime-agent-runtime/src/rlm/harness.py
+++ b/prime-agent-runtime/src/rlm/harness.py
@@ -9,6 +9,7 @@ Execution still belongs to Prime Agent's TypeScript host and the existing
from __future__ import annotations
+import copy
import json
import math
import os
@@ -21,12 +22,14 @@ from pathlib import Path
from uuid import uuid4
from typing import Any, Literal
-HarnessKind = Literal["prompt", "memory", "skill", "subagent"]
+from .factory import require_factory_enabled, validate_factory_spec
+
+HarnessKind = Literal["prompt", "memory", "skill", "subagent", "factory"]
HarnessScope = Literal["local", "global"]
_DEFAULT_FILE_NAME = "harness_state.json"
_DEFAULT_HARNESS_DIR_NAME = "harness"
-_KINDS: tuple[HarnessKind, ...] = ("prompt", "memory", "skill", "subagent")
+_KINDS: tuple[HarnessKind, ...] = ("prompt", "memory", "skill", "subagent", "factory")
_state_cache: dict[tuple[Path, HarnessScope], "HarnessState"] = {}
@@ -257,6 +260,44 @@ def _require_optional_record(kind: str, entry_name: str, field: str, value: Any)
)
+def _factory_spec_argument(
+ dag: Any, machine: Any
+) -> "tuple[Any, Literal['dag', 'machine']]":
+ """Pick the factory spec payload and its arguments key from the call.
+
+ Supplying both forms at once is an error. A bare ``dag=None,
+ machine=None`` passes ``None`` through in the dag slot so the write-time
+ validation rejects it with the standard wording.
+ """
+ if dag is not None and machine is not None:
+ raise ValueError("pass either dag or machine, not both")
+ if machine is not None:
+ return machine, "machine"
+ return dag, "dag"
+
+
+def _validate_factory_arguments(entry_name: str, arguments: dict[str, Any]) -> None:
+ """Shared-path dry run for every factory write.
+
+ ``create_factory``/``update_factory`` validate their own spec, but a
+ generic ``create``/``update`` (or a refinement edit) writes
+ ``arguments`` directly; an invalid spec must never reach the store
+ through any writer, so the spec found in ``arguments`` is validated
+ here too.
+ """
+ dag, machine = arguments.get("dag"), arguments.get("machine")
+ if dag is not None and machine is not None:
+ raise ValueError(f"factory entry {entry_name!r} rejected: pass either dag or machine, not both")
+ spec = machine if machine is not None else dag
+ if not isinstance(spec, dict):
+ raise ValueError(
+ f"factory entry {entry_name!r} rejected: factory entries require a dag or machine object in arguments"
+ )
+ errors = validate_factory_spec(spec)
+ if errors:
+ raise ValueError(f"factory entry {entry_name!r} rejected: {'; '.join(errors)}")
+
+
def _validate_entry_shape(
kind: str,
entry_id: Any,
@@ -294,6 +335,24 @@ def _validate_entry_shape(
raise ValueError(f"skill entry {entry_name!r} rejected: skill entries require a Python reference")
else:
_validate_python_skill_reference(reference, entry_name)
+ if kind == "factory":
+ # Every factory writer funnels through here, so the opt-in gate and
+ # the spec dry run cover them all: create_factory validates, and the
+ # generic create/update path (a refinement edit) gets the same
+ # treatment. The gate comes first: while `factory.enabled` is off
+ # (the default) every factory write refuses with the one disabled
+ # message, before any spec work. A
+ # NEW factory requires its spec (an arguments-less factory would
+ # store an unusable entry that run() later rejects); an update that
+ # omits arguments (None) preserves the stored spec and skips
+ # validation, exactly like update_skill treats reference.
+ require_factory_enabled()
+ if arguments is None and existing is None:
+ raise ValueError(
+ f"factory entry {entry_name!r} rejected: factory entries require a dag or machine object in arguments"
+ )
+ if arguments is not None:
+ _validate_factory_arguments(entry_name, arguments)
def _validate_refinement_event(trigger: Any, changes: Any, *, evidence: Any, outcome: Any) -> None:
@@ -588,7 +647,10 @@ class HarnessState:
if reference is not None:
existing.reference = dict(reference)
if arguments is not None:
- existing.arguments = dict(arguments)
+ # Factory specs are deep-copied: the nested dag/machine object
+ # is caller-owned, and a later mutation must never change the
+ # stored (validated) spec without a write-time dry run.
+ existing.arguments = copy.deepcopy(arguments) if kind == "factory" else dict(arguments)
if metadata is not None:
existing.metadata = dict(metadata)
existing.source = source
@@ -604,7 +666,7 @@ class HarnessState:
path=path if path is not None else "general",
scope=self.scope,
reference=dict(reference or {}),
- arguments=dict(arguments or {}),
+ arguments=copy.deepcopy(arguments or {}) if kind == "factory" else dict(arguments or {}),
metadata=dict(metadata or {}),
source=source,
)
@@ -892,6 +954,85 @@ class HarnessState:
def delete_subagent(self, id: str, *, global_: bool = False, **kwargs: Any) -> bool:
return self.delete("subagent", id, global_=global_, **kwargs)
+ def create_factory(
+ self,
+ title: str,
+ content: str,
+ *,
+ id: str | None = None,
+ path: str = "general",
+ dag: dict[str, Any] | None = None,
+ machine: dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
+ global_: bool = False,
+ **kwargs: Any,
+ ) -> HarnessEntry:
+ # The opt-in gate precedes the dry run, so a disabled factory
+ # refuses with the one disabled message whatever the spec looks like.
+ require_factory_enabled()
+ # Write-time dry run: an invalid spec (either form) never reaches the
+ # store. The spec is deep-copied before storing: mutating the caller's
+ # dict after creation must not change the live entry (a later update
+ # that omits both forms would preserve the mutated, unvalidated spec).
+ spec, key = _factory_spec_argument(dag, machine)
+ errors = validate_factory_spec(spec)
+ if errors:
+ raise ValueError("; ".join(errors))
+ return self.create(
+ "factory",
+ title,
+ content,
+ id=id,
+ path=path,
+ arguments={key: copy.deepcopy(spec)},
+ metadata=metadata,
+ global_=global_,
+ **kwargs,
+ )
+
+ def update_factory(
+ self,
+ id: str,
+ title: str,
+ content: str,
+ *,
+ path: str | None = None,
+ dag: dict[str, Any] | None = None,
+ machine: dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
+ global_: bool = False,
+ **kwargs: Any,
+ ) -> HarnessEntry:
+ # The opt-in gate precedes the spec and existence checks, so a
+ # disabled factory refuses with the one disabled message whatever the
+ # update carries.
+ require_factory_enabled()
+ # Only validate a spec when one is supplied; omitting both preserves the
+ # stored arguments (see _upsert) rather than forcing every title/content
+ # update to re-send the full spec, exactly like update_skill treats reference.
+ if dag is not None or machine is not None:
+ spec, key = _factory_spec_argument(dag, machine)
+ errors = validate_factory_spec(spec)
+ if errors:
+ raise ValueError("; ".join(errors))
+ arguments = {key: copy.deepcopy(spec)}
+ else:
+ arguments = None
+ return self.update(
+ "factory",
+ id,
+ title,
+ content,
+ path=path,
+ arguments=arguments,
+ metadata=metadata,
+ global_=global_,
+ **kwargs,
+ )
+
+ def delete_factory(self, id: str, *, global_: bool = False, **kwargs: Any) -> bool:
+ return self.delete("factory", id, global_=global_, **kwargs)
+
def record_refinement(
self,
trigger: str,
@@ -956,6 +1097,12 @@ class HarnessState:
"files; children reply with await agent_message.send(message, receiver_role='parent'). Use "
"await rlm.list_subagents() to recover direct child handles and await agent_message.send(..., "
"receiver_role='child', receiver_name=handle.name) for follow-ups.",
+ "Factory entries declare validated state-machine workflows of subagent states in arguments['machine'] "
+ "(the original DAG sugar in arguments['dag'] compiles to machine form): manage them with "
+ "create_factory/update_factory/delete_factory (create_factory validates either form at write time); run "
+ "them with await rlm.factory.run(\"<id>\"), watch with await rlm.factory.status(run_id), stop with "
+ "await rlm.factory.stop(run_id), and resume an escalate-paused run with "
+ "await rlm.factory.resume(run_id).",
]
for kind in _KINDS:
records = self.list(kind)[:max_entries_per_kind]
diff --git a/prime-agent-runtime/test/test_factory.py b/prime-agent-runtime/test/test_factory.py
new file mode 100644
index 0000000000..deb45b3a0e
--- /dev/null
+++ b/prime-agent-runtime/test/test_factory.py
@@ -0,0 +1,5530 @@
+"""Factory harness entry kind: spec validation, dag compilation, and executor.
+
+Consolidated port of TS-era PRs #2397 (factory entry kind, validator, dag
+compiler) and #2401 (the executor: run/status/stop/resume, guarded
+transitions, re-entry, failure policies, budgets, rate-limit backoff, stop
+races) plus the accepted review findings from both:
+
+- a fan-in dag node's full dependency set compiles to ONE join transition
+ (never per-edge transitions that would let the node start after a single
+ parent settles);
+- a node reading its own output is rejected like depends_on: [self];
+- explicit JSON null on typed fields (run.max_parallel, state.retries,
+ state.max_entries, ...) is rejected with the field's own message instead
+ of surviving canonicalization as None;
+- port validation is linear in the port count (seen-sets and one
+ output-type map per source), so thousands of ports stay write-time cheap;
+- quiescence counts the INSTANCE layer: a failed foreach entry's still
+ running siblings are collected before the run ends, and a resident
+ entry's queued instances are admitted before completion is reported;
+ admitted resident instances alone never block completion;
+- queued siblings of a terminal (failed/cancelled) entry are never
+ admitted (_next_pending_instance serves running entries only);
+- the run budget is enforced before each admission, including run()'s and
+ resume()'s admission phase;
+- rate-limit backoff never blocks the sole control lane: admission defers
+ to a deadline and the loop waits it out in bounded slices while children
+ keep being collected;
+- concurrent stop() calls run one cancellation pass (the transitional
+ "stopping" state is guarded too);
+- resume() bumps the control-loop generation so the pause-path loop can
+ never continue as a second concurrent control loop;
+- long state ids disambiguate their spawn names with a digest, so two
+ states sharing a 20-character prefix never collide on the supervisor's
+ unique sibling-name requirement;
+- a configured inline subagent name labels the spawned children verbatim
+ (the first instance), with the generated label's -i<n>/-a<n> suffixes on
+ re-entry, foreach fan-out, and retries; over-length names and names
+ duplicated across states are rejected at write time (Macroscope review
+ finding: the name was dropped, so children always got the generated
+ label);
+- milestone notices go to the host as validated "factory.progress"
+ payloads exactly once per kind per run, and a dead bridge leaves the
+ milestone in the ledger instead of wedging the run.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import os
+import re
+import time
+import unittest
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from typing import Any
+from unittest.mock import patch
+
+import rlm as rlm_module
+from rlm import factory as factory_module
+from rlm.factory import (
+ ANSWER_CAPTURE_CAP,
+ BACKOFF_MAX_ATTEMPTS,
+ EVENT_WINDOW,
+ POLL_TIMEOUT_MS,
+ SUBAGENT_NAME_MAX_LENGTH,
+ FactoryExecutor,
+ _child_name,
+ _guard_passes,
+ _parse_json_output,
+ _spawn_label,
+ canonicalize_factory_spec,
+ compile_factory_dag,
+ topological_order,
+ validate_factory_machine,
+ validate_factory_spec,
+)
+from rlm.harness import HarnessState
+
+
+# ---------------------------------------------------------------------------
+# Spec fixtures
+# ---------------------------------------------------------------------------
+
+
+def state(state_id: str, **overrides: Any) -> dict[str, Any]:
+ base: dict[str, Any] = {"id": state_id, "subagent": "worker"}
+ base.update(overrides)
+ return base
+
+
+def valid_machine() -> dict[str, Any]:
+ """Review-loop machine: collect -> reviewing (max 4 entries) with a
+ guarded switch to fixing (max 3 entries) and a self-loop, fixing re-enters
+ reviewing."""
+ return {
+ "run": {"budget_ms": 600_000, "failure_policy": "continue", "max_parallel": 4, "max_transitions": 40},
+ "states": [
+ {
+ "id": "collect",
+ "entry": True,
+ "subagent": "researcher",
+ "outputs": [{"name": "findings", "type": "text"}],
+ },
+ {
+ "id": "reviewing",
+ "subagent": {"prompt": "Review the draft."},
+ "inputs": [{"name": "draft", "type": "text", "from": "collect.findings"}],
+ "outputs": [{"name": "verdict", "type": "json"}],
+ "max_entries": 4,
+ "retries": 1,
+ },
+ {"id": "fixing", "subagent": {"prompt": "Fix the findings."}, "max_entries": 3},
+ ],
+ "transitions": [
+ {"from": "collect", "to": "reviewing"},
+ {
+ "from": "reviewing",
+ "to": "fixing",
+ "when": {"output": "verdict", "path": "approved", "op": "eq", "value": False},
+ },
+ {"from": "reviewing", "to": "reviewing", "when": {"output": "verdict", "op": "exists"}},
+ {"from": "fixing", "to": "reviewing"},
+ ],
+ }
+
+
+def node(node_id: str, **overrides: Any) -> dict[str, Any]:
+ base: dict[str, Any] = {"id": node_id, "subagent": "worker"}
+ base.update(overrides)
+ return base
+
+
+def valid_dag() -> dict[str, Any]:
+ return {
+ "run": {"budget_ms": 600_000, "failure_policy": "continue", "max_parallel": 4},
+ "nodes": [
+ {
+ "id": "collect",
+ "subagent": "researcher",
+ "outputs": [{"name": "findings", "type": "text"}],
+ },
+ {
+ "id": "fan-out",
+ "subagent": {"prompt": "Expand each item.", "name": "expander", "model": "m1", "thinking": "low"},
+ "depends_on": ["collect"],
+ "inputs": [{"name": "items", "type": "text", "from": "collect.findings"}],
+ },
+ {
+ "id": "review",
+ "subagent": {"prompt": "Review the fan-out."},
+ "depends_on": ["collect", "fan-out"],
+ "inputs": [{"name": "draft", "type": "text", "from": "collect.findings"}],
+ "retries": 2,
+ "budget_ms": 100_000,
+ "failure_policy": "fail_fast",
+ },
+ ],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Dag-form validation (write-time dry run)
+# ---------------------------------------------------------------------------
+
+
+class ValidateFactorySpecTest(unittest.TestCase):
+ def test_valid_spec_has_no_errors(self) -> None:
+ self.assertEqual(validate_factory_spec(valid_dag()), [])
+
+ def test_dag_must_be_an_object(self) -> None:
+ for bad in (None, [], "nodes", 42):
+ errors = validate_factory_spec(bad)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("factory dag must be a JSON object", errors[0])
+
+ def test_nodes_required_and_must_be_a_list(self) -> None:
+ self.assertEqual(
+ validate_factory_spec({"nodes": "nope"}),
+ ["factory dag requires a nodes list"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"run": "bad", "nodes": "nope"}),
+ ["run must be an object", "factory dag requires a nodes list"],
+ )
+
+ def test_node_cap(self) -> None:
+ at_cap = {"nodes": [node(f"n{i}") for i in range(1024)]}
+ self.assertEqual(validate_factory_spec(at_cap), [])
+ over_cap = {"nodes": [node(f"n{i}") for i in range(1025)]}
+ errors = validate_factory_spec(over_cap)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("between 1 and 1024 nodes", errors[0])
+
+ def test_node_ids(self) -> None:
+ for good in ("a", "node-1", "1st-node", "a" * 64):
+ self.assertEqual(validate_factory_spec({"nodes": [node(good)]}), [], good)
+ for bad in ("-abc", "ABC", "a_b", "a.b", "a" * 65):
+ errors = validate_factory_spec({"nodes": [{"id": bad, "subagent": "w"}]})
+ self.assertEqual(len(errors), 1, bad)
+ self.assertIn("id must match", errors[0])
+ for bad in ("", None, 5):
+ errors = validate_factory_spec({"nodes": [{"id": bad, "subagent": "w"}]})
+ self.assertEqual(errors, ["nodes[0] requires a non-empty id"], repr(bad))
+
+ def test_duplicate_node_ids(self) -> None:
+ errors = validate_factory_spec({"nodes": [node("dup"), node("dup")]})
+ self.assertEqual(len(errors), 1)
+ self.assertIn("duplicates node id 'dup'", errors[0])
+
+ def test_subagent_forms(self) -> None:
+ by_ref = {"nodes": [node("a", subagent="reviewer")]}
+ self.assertEqual(validate_factory_spec(by_ref), [])
+ inline = {"nodes": [node("a", subagent={"prompt": "Do work."})]}
+ self.assertEqual(validate_factory_spec(inline), [])
+ inline_full = {
+ "nodes": [
+ node("a", subagent={"prompt": "Do work.", "name": "w", "model": "m", "thinking": "high"})
+ ]
+ }
+ self.assertEqual(validate_factory_spec(inline_full), [])
+
+ missing = {"nodes": [{"id": "a"}]}
+ errors = validate_factory_spec(missing)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a subagent", errors[0])
+
+ empty_ref = {"nodes": [node("a", subagent="")]}
+ errors = validate_factory_spec(empty_ref)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a subagent", errors[0])
+
+ empty_prompt = {"nodes": [node("a", subagent={"prompt": ""})]}
+ errors = validate_factory_spec(empty_prompt)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a non-empty prompt", errors[0])
+
+ bad_name = {"nodes": [node("a", subagent={"prompt": "p", "model": 5})]}
+ errors = validate_factory_spec(bad_name)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("model must be a non-empty string", errors[0])
+
+ bad_thinking = {"nodes": [node("a", subagent={"prompt": "p", "thinking": ""})]}
+ errors = validate_factory_spec(bad_thinking)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("thinking must be a non-empty string", errors[0])
+
+ # Whitespace-only values are rejected at write time: runtime
+ # resolution strips them (_resolve_subagents /
+ # _validate_spawn_settings), so a whitespace-only field is a
+ # persistable factory that can never spawn.
+ whitespace_prompt = {"nodes": [node("a", subagent={"prompt": " \t "})]}
+ errors = validate_factory_spec(whitespace_prompt)
+ self.assertEqual(errors, ["node a inline subagent requires a non-empty prompt"])
+ for key in ("name", "model", "thinking"):
+ whitespace_field = {"nodes": [node("a", subagent={"prompt": "p", key: " \t "})]}
+ errors = validate_factory_spec(whitespace_field)
+ self.assertEqual(
+ errors, [f"node a inline subagent {key} must be a non-empty string when provided"], key
+ )
+
+ # The dag form compiles to machine form first, so the name rules
+ # (length, cross-state uniqueness) apply to nodes too.
+ dag_duplicate = {
+ "nodes": [
+ node("a", subagent={"prompt": "p", "name": "w"}),
+ node("b", subagent={"prompt": "p", "name": "w"}, depends_on=["a"]),
+ ]
+ }
+ errors = validate_factory_spec(dag_duplicate)
+ self.assertEqual(errors, ["state b subagent name 'w' is already configured by state 'a'"])
+
+ def test_lifecycle(self) -> None:
+ for good in ("task", "resident"):
+ self.assertEqual(validate_factory_spec({"nodes": [node("a", lifecycle=good)]}), [])
+ errors = validate_factory_spec({"nodes": [node("a", lifecycle="daemon")]})
+ self.assertEqual(len(errors), 1)
+ self.assertIn("lifecycle must be 'task' or 'resident'", errors[0])
+
+ def test_run_budget_and_node_budget(self) -> None:
+ ok = {
+ "run": {"budget_ms": 1000},
+ "nodes": [node("a", budget_ms=1000)],
+ }
+ self.assertEqual(validate_factory_spec(ok), [])
+
+ over = {
+ "run": {"budget_ms": 1000},
+ "nodes": [node("a", budget_ms=1001)],
+ }
+ errors = validate_factory_spec(over)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("exceeds the run budget_ms", errors[0])
+
+ for bad in (0, -5, 1.5, "10", True):
+ errors = validate_factory_spec({"run": {"budget_ms": bad}, "nodes": [node("a")]})
+ self.assertEqual(errors, ["run budget_ms must be a positive integer"], bad)
+ errors = validate_factory_spec({"nodes": [node("a", budget_ms=bad)]})
+ self.assertEqual(errors, ["node a budget_ms must be a positive integer"], bad)
+
+ # No run budget set: any positive node budget is fine.
+ self.assertEqual(validate_factory_spec({"nodes": [node("a", budget_ms=999_999)]}), [])
+
+ def test_run_budget_invalid(self) -> None:
+ errors = validate_factory_spec({"run": "bad", "nodes": [node("a")]})
+ self.assertEqual(errors, ["run must be an object"])
+
+ def test_run_failure_policy(self) -> None:
+ for good in ("fail_fast", "continue", "escalate"):
+ self.assertEqual(validate_factory_spec({"run": {"failure_policy": good}, "nodes": [node("a")]}), [])
+ errors = validate_factory_spec({"run": {"failure_policy": "stop"}, "nodes": [node("a")]})
+ self.assertEqual(len(errors), 1)
+ self.assertIn("run failure_policy must be one of", errors[0])
+
+ def test_run_max_parallel(self) -> None:
+ for good in (1, 8, 64):
+ self.assertEqual(validate_factory_spec({"run": {"max_parallel": good}, "nodes": [node("a")]}), [])
+ for bad in (0, 65, -1, 1.5, "8", True):
+ errors = validate_factory_spec({"run": {"max_parallel": bad}, "nodes": [node("a")]})
+ self.assertEqual(errors, ["run max_parallel must be an integer between 1 and 64"], bad)
+
+ def test_run_max_transitions(self) -> None:
+ for good in (1, 40, 10_000):
+ self.assertEqual(validate_factory_spec({"run": {"max_transitions": good}, "nodes": [node("a")]}), [])
+ for bad in (0, -1, 10_001, 1.5, "5", True):
+ errors = validate_factory_spec({"run": {"max_transitions": bad}, "nodes": [node("a")]})
+ self.assertEqual(errors, ["run max_transitions must be a positive integer no greater than 10000"], bad)
+
+ def test_run_max_children(self) -> None:
+ # The run-wide child budget: total admissions over the run's life.
+ for good in (1, 40, 1_000_000):
+ self.assertEqual(validate_factory_spec({"run": {"max_children": good}, "nodes": [node("a")]}), [])
+ for bad in (0, -1, 1_000_001, 1.5, "5", True):
+ errors = validate_factory_spec({"run": {"max_children": bad}, "nodes": [node("a")]})
+ self.assertEqual(errors, ["run max_children must be a positive integer no greater than 1000000"], bad)
+
+ def test_node_failure_policy(self) -> None:
+ for good in ("fail_fast", "continue", "escalate"):
+ self.assertEqual(validate_factory_spec({"nodes": [node("a", failure_policy=good)]}), [])
+ errors = validate_factory_spec({"nodes": [node("a", failure_policy="retry")]})
+ self.assertEqual(len(errors), 1)
+ self.assertIn("node a failure_policy must be one of", errors[0])
+
+ def test_retries(self) -> None:
+ for good in (0, 5, 10):
+ self.assertEqual(validate_factory_spec({"nodes": [node("a", retries=good)]}), [])
+ for bad in (-1, 11, 1.5, "2", True):
+ errors = validate_factory_spec({"nodes": [node("a", retries=bad)]})
+ self.assertEqual(errors, ["node a retries must be an integer between 0 and 10"], bad)
+
+ def test_depends_on(self) -> None:
+ ok = {"nodes": [node("a"), node("b", depends_on=["a"])]}
+ self.assertEqual(validate_factory_spec(ok), [])
+
+ self_dep = {"nodes": [node("a", depends_on=["a"])]}
+ errors = validate_factory_spec(self_dep)
+ self.assertEqual(errors, ["node a cannot depend on itself"])
+
+ unknown = {"nodes": [node("a", depends_on=["ghost"])]}
+ errors = validate_factory_spec(unknown)
+ self.assertEqual(errors, ["node a depends on unknown node 'ghost'"])
+
+ not_list = {"nodes": [node("a", depends_on="b")]}
+ errors = validate_factory_spec(not_list)
+ self.assertEqual(errors, ["node a depends_on must be a list of node ids"])
+
+ bad_entry = {"nodes": [node("a", depends_on=[5])]}
+ errors = validate_factory_spec(bad_entry)
+ self.assertEqual(errors, ["node a depends_on entries must be non-empty node id strings"])
+
+ def test_self_input_edge_is_rejected_like_a_self_dependency(self) -> None:
+ # Review finding: a node reading its own output would compile to a
+ # never-reachable self-loop state, so the self-dependency rule covers
+ # the EFFECTIVE edge set (depends_on union inputs[].from), not only
+ # depends_on.
+ self_output = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", inputs=[{"name": "i", "type": "text", "from": "b.o"}]),
+ ]
+ }
+ errors = validate_factory_spec(self_output)
+ self.assertIn("node b cannot depend on itself", errors)
+ machine, compile_errors = compile_factory_dag(self_output)
+ self.assertIsNone(machine)
+ self.assertIn("node b cannot depend on itself", compile_errors)
+
+ # A cross-node input edge is of course fine.
+ ok = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", inputs=[{"name": "i", "type": "text", "from": "a.o"}]),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(ok), [])
+
+ def test_explicit_null_typed_fields_are_rejected_not_defaulted(self) -> None:
+ # Review finding: explicit JSON null on a typed field used to survive
+ # canonicalization as None and reach the executor without a usable
+ # limit. Presence-based checks reject null with the field's own
+ # message instead of treating it as an omitted default.
+ self.assertEqual(
+ validate_factory_spec({"run": {"max_parallel": None}, "nodes": [node("a")]}),
+ ["run max_parallel must be an integer between 1 and 64"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"run": {"max_transitions": None}, "nodes": [node("a")]}),
+ ["run max_transitions must be a positive integer no greater than 10000"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"run": {"max_children": None}, "nodes": [node("a")]}),
+ ["run max_children must be a positive integer no greater than 1000000"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"run": {"budget_ms": None}, "nodes": [node("a")]}),
+ ["run budget_ms must be a positive integer"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"run": {"failure_policy": None}, "nodes": [node("a")]}),
+ ["run failure_policy must be one of ['fail_fast', 'continue', 'escalate'], got None"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"nodes": [node("a", retries=None)]}),
+ ["node a retries must be an integer between 0 and 10"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"nodes": [node("a", budget_ms=None)]}),
+ ["node a budget_ms must be a positive integer"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"nodes": [node("a", failure_policy=None)]}),
+ ["node a failure_policy must be one of ['fail_fast', 'continue', 'escalate'], got None"],
+ )
+ self.assertEqual(
+ validate_factory_spec({"nodes": [node("a", lifecycle=None)]}),
+ ["node a lifecycle must be 'task' or 'resident', got None"],
+ )
+ machine_nulls = {
+ "states": [
+ {
+ "id": "a",
+ "entry": True,
+ "subagent": "w",
+ "max_entries": None,
+ "retries": None,
+ }
+ ],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(machine_nulls),
+ [
+ "state a retries must be an integer between 0 and 10",
+ "state a max_entries must be an integer >= 1",
+ ],
+ )
+ self.assertEqual(
+ validate_factory_machine({"states": [{"id": "a", "entry": None, "subagent": "w"}], "transitions": []}),
+ [
+ "state a entry must be a boolean",
+ "factory machine requires at least one entry state",
+ ],
+ )
+
+ def test_data_edges(self) -> None:
+ ok = {
+ "nodes": [
+ node("a", outputs=[{"name": "out", "type": "text"}]),
+ node("b", inputs=[{"name": "in", "type": "text", "from": "a.out"}]),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(ok), [])
+
+ # A data edge implies ordering even without depends_on.
+ no_declared_dep = {
+ "nodes": [
+ node("a", outputs=[{"name": "out", "type": "json"}]),
+ node("b", inputs=[{"name": "in", "type": "json", "from": "a.out"}]),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(no_declared_dep), [])
+
+ unknown_source = {
+ "nodes": [node("b", inputs=[{"name": "in", "type": "text", "from": "ghost.out"}])]
+ }
+ errors = validate_factory_spec(unknown_source)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("references unknown node 'ghost'", errors[0])
+
+ undeclared_output = {
+ "nodes": [
+ node("a"),
+ node("b", inputs=[{"name": "in", "type": "text", "from": "a.missing"}]),
+ ]
+ }
+ errors = validate_factory_spec(undeclared_output)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("does not declare", errors[0])
+
+ type_mismatch = {
+ "nodes": [
+ node("a", outputs=[{"name": "out", "type": "text"}]),
+ node("b", inputs=[{"name": "in", "type": "json", "from": "a.out"}]),
+ ]
+ }
+ errors = validate_factory_spec(type_mismatch)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("cannot read from output", errors[0])
+ self.assertIn("of type 'text'", errors[0])
+
+ malformed_from = {
+ "nodes": [
+ node("a", outputs=[{"name": "out", "type": "text"}]),
+ node("b", inputs=[{"name": "in", "type": "text", "from": "no-dot"}]),
+ ]
+ }
+ errors = validate_factory_spec(malformed_from)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a 'from' reference", errors[0])
+
+ def test_input_output_ports(self) -> None:
+ ok = {
+ "nodes": [
+ node(
+ "a",
+ outputs=[{"name": "o1", "type": "text"}, {"name": "o2", "type": "json"}],
+ )
+ ]
+ }
+ self.assertEqual(validate_factory_spec(ok), [])
+
+ bad_output_type = {"nodes": [node("a", outputs=[{"name": "o", "type": "yaml"}])]}
+ errors = validate_factory_spec(bad_output_type)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("output 'o' type must be 'text' or 'json'", errors[0])
+
+ dup_output = {
+ "nodes": [node("a", outputs=[{"name": "o", "type": "text"}, {"name": "o", "type": "json"}])]
+ }
+ errors = validate_factory_spec(dup_output)
+ self.assertEqual(errors, ["node a declares duplicate output name 'o'"])
+
+ bad_input_type = {
+ "nodes": [
+ node("b", outputs=[{"name": "o", "type": "text"}]),
+ node("a", inputs=[{"name": "i", "type": "yaml", "from": "b.o"}]),
+ ]
+ }
+ errors = validate_factory_spec(bad_input_type)
+ self.assertEqual(errors, ["node a input 'i' type must be 'text' or 'json'"])
+
+ dup_input = {
+ "nodes": [
+ node(
+ "a",
+ inputs=[
+ {"name": "i", "type": "text", "from": "b.o1"},
+ {"name": "i", "type": "text", "from": "b.o2"},
+ ],
+ ),
+ node("b", outputs=[{"name": "o1", "type": "text"}, {"name": "o2", "type": "text"}]),
+ ]
+ }
+ errors = validate_factory_spec(dup_input)
+ self.assertEqual(errors, ["node a declares duplicate input name 'i'"])
+
+ missing_name = {"nodes": [node("a", outputs=[{"type": "text"}])]}
+ errors = validate_factory_spec(missing_name)
+ self.assertEqual(errors, ["node a outputs[0] requires a non-empty name"])
+
+ not_a_list = {"nodes": [node("a", outputs="nope")]}
+ errors = validate_factory_spec(not_a_list)
+ self.assertEqual(errors, ["node a outputs must be a list"])
+ not_a_list = {"nodes": [node("a", inputs="nope")]}
+ errors = validate_factory_spec(not_a_list)
+ self.assertEqual(errors, ["node a inputs must be a list"])
+
+ def test_resident_rules(self) -> None:
+ resident_ok = {"nodes": [node("watcher", lifecycle="resident")]}
+ self.assertEqual(validate_factory_spec(resident_ok), [])
+
+ depended_on = {
+ "nodes": [node("watcher", lifecycle="resident"), node("task", depends_on=["watcher"])]
+ }
+ errors = validate_factory_spec(depended_on)
+ self.assertEqual(errors, ["node task cannot depend on resident node 'watcher'"])
+
+ read_from = {
+ "nodes": [
+ node("watcher", lifecycle="resident"),
+ node("task", inputs=[{"name": "i", "type": "text", "from": "watcher.o"}]),
+ ]
+ }
+ errors = validate_factory_spec(read_from)
+ self.assertEqual(errors, ["node task input 'i' cannot read from resident node 'watcher'"])
+
+ declares_outputs = {"nodes": [node("watcher", lifecycle="resident", outputs=[{"name": "o", "type": "text"}])]}
+ errors = validate_factory_spec(declares_outputs)
+ self.assertEqual(errors, ["resident node watcher cannot declare outputs"])
+
+ uses_foreach = {
+ "nodes": [
+ node("src", outputs=[{"name": "items", "type": "json"}]),
+ node(
+ "watcher",
+ lifecycle="resident",
+ inputs=[{"name": "items", "type": "json", "from": "src.items"}],
+ foreach={"over": "items", "max": 4},
+ ),
+ ]
+ }
+ errors = validate_factory_spec(uses_foreach)
+ self.assertEqual(errors, ["resident node watcher cannot use foreach"])
+
+ # Empty outputs list on a resident node is fine: nothing is declared.
+ empty_outputs = {"nodes": [node("watcher", lifecycle="resident", outputs=[])]}
+ self.assertEqual(validate_factory_spec(empty_outputs), [])
+
+ def test_foreach(self) -> None:
+ ok = {
+ "nodes": [
+ node("a", outputs=[{"name": "items", "type": "json"}]),
+ node(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "items", "max": 16},
+ ),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(ok), [])
+
+ for good_max in (1, 256):
+ ok_max = {
+ "nodes": [
+ node("a", outputs=[{"name": "items", "type": "json"}]),
+ node(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "items", "max": good_max},
+ ),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(ok_max), [])
+
+ for bad_max in (0, 257, -1, 1.5, "8", True):
+ bad = {
+ "nodes": [
+ node("a", outputs=[{"name": "items", "type": "json"}]),
+ node(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "items", "max": bad_max},
+ ),
+ ]
+ }
+ errors = validate_factory_spec(bad)
+ self.assertEqual(errors, ["node b foreach.max must be an integer between 1 and 256"], bad_max)
+
+ wrong_port = {
+ "nodes": [
+ node("a", outputs=[{"name": "items", "type": "json"}]),
+ node(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "not-an-input", "max": 4},
+ ),
+ ]
+ }
+ errors = validate_factory_spec(wrong_port)
+ self.assertEqual(
+ errors, ["node b foreach.over must name one of this node's inputs, got 'not-an-input'"]
+ )
+
+ text_port = {
+ "nodes": [
+ node("a", outputs=[{"name": "draft", "type": "text"}]),
+ node(
+ "b",
+ inputs=[{"name": "draft", "type": "text", "from": "a.draft"}],
+ foreach={"over": "draft", "max": 4},
+ ),
+ ]
+ }
+ errors = validate_factory_spec(text_port)
+ self.assertEqual(errors, ["node b foreach.over input 'draft' must have type 'json'"])
+
+ not_object = {"nodes": [node("a", foreach=["bad"])]}
+ errors = validate_factory_spec(not_object)
+ self.assertEqual(errors, ["node a foreach must be an object"])
+
+ def test_cycles_are_legal_when_an_entry_state_exists(self) -> None:
+ # A cycle that does not cover the whole dag compiles to a machine with
+ # an entry state; cycles are legal in machine form, so this validates.
+ cycle_with_entry = {
+ "nodes": [
+ node("a"),
+ node("b", depends_on=["c"]),
+ node("c", depends_on=["b"]),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(cycle_with_entry), [])
+
+ data_cycle_with_entry = {
+ "nodes": [
+ node("a"),
+ node("b", depends_on=["a"], outputs=[{"name": "o", "type": "json"}]),
+ node("c", inputs=[{"name": "i", "type": "json", "from": "b.o"}]),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(data_cycle_with_entry), [])
+
+ def test_fully_cyclic_dag_compiles_to_a_machine_without_entry_states(self) -> None:
+ depends_cycle = {
+ "nodes": [
+ node("a", depends_on=["b"]),
+ node("b", depends_on=["a"]),
+ ]
+ }
+ self.assertEqual(
+ validate_factory_spec(depends_cycle),
+ ["factory machine requires at least one entry state"],
+ )
+
+ data_cycle = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "json"}], inputs=[
+ {"name": "i", "type": "json", "from": "b.o"}
+ ]),
+ node("b", outputs=[{"name": "o", "type": "json"}], inputs=[
+ {"name": "i", "type": "json", "from": "a.o"}
+ ]),
+ ]
+ }
+ self.assertEqual(
+ validate_factory_spec(data_cycle),
+ ["factory machine requires at least one entry state"],
+ )
+
+ three_cycle = {
+ "nodes": [
+ node("a", depends_on=["c"]),
+ node("b", depends_on=["a"]),
+ node("c", depends_on=["b"]),
+ ]
+ }
+ self.assertEqual(
+ validate_factory_spec(three_cycle),
+ ["factory machine requires at least one entry state"],
+ )
+
+ def test_collects_multiple_errors(self) -> None:
+ dag = {
+ "run": {"max_parallel": 99, "failure_policy": "nope"},
+ "nodes": [
+ node("a", depends_on=["ghost"]),
+ node("b", retries=99),
+ node("c", failure_policy="retry"),
+ ],
+ }
+ errors = validate_factory_spec(dag)
+ self.assertEqual(
+ errors,
+ [
+ "run failure_policy must be one of ['fail_fast', 'continue', 'escalate'], got 'nope'",
+ "run max_parallel must be an integer between 1 and 64",
+ "node a depends on unknown node 'ghost'",
+ "node b retries must be an integer between 0 and 10",
+ "node c failure_policy must be one of ['fail_fast', 'continue', 'escalate'], got 'retry'",
+ ],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Canonicalization
+# ---------------------------------------------------------------------------
+
+
+class CanonicalizeFactorySpecTest(unittest.TestCase):
+ def test_applies_defaults(self) -> None:
+ dag = {"nodes": [{"id": "a", "subagent": "worker"}]}
+ self.assertEqual(
+ canonicalize_factory_spec(dag),
+ {
+ "run": {
+ "failure_policy": "escalate",
+ "max_parallel": 8,
+ "max_transitions": 10,
+ "max_children": 10_000,
+ },
+ "states": [
+ {
+ "id": "a",
+ "entry": True,
+ "max_entries": 1,
+ "subagent": "worker",
+ "lifecycle": "task",
+ "retries": 0,
+ "failure_policy": "escalate",
+ }
+ ],
+ "transitions": [],
+ },
+ )
+
+ def test_preserves_explicit_values(self) -> None:
+ dag = {
+ "run": {
+ "budget_ms": 5000,
+ "failure_policy": "continue",
+ "max_parallel": 2,
+ "max_transitions": 7,
+ "max_children": 5,
+ },
+ "nodes": [
+ {
+ "id": "a",
+ "subagent": {"prompt": "Work."},
+ "lifecycle": "task",
+ "retries": 3,
+ "failure_policy": "fail_fast",
+ "budget_ms": 4000,
+ "depends_on": [],
+ "outputs": [{"name": "o", "type": "text"}],
+ }
+ ],
+ }
+ self.assertEqual(
+ canonicalize_factory_spec(dag),
+ {
+ "run": {
+ "failure_policy": "continue",
+ "max_parallel": 2,
+ "max_transitions": 7,
+ "max_children": 5,
+ "budget_ms": 5000,
+ },
+ "states": [
+ {
+ "id": "a",
+ "entry": True,
+ "max_entries": 1,
+ "subagent": {"prompt": "Work."},
+ "lifecycle": "task",
+ "retries": 3,
+ "failure_policy": "fail_fast",
+ "budget_ms": 4000,
+ "outputs": [{"name": "o", "type": "text"}],
+ }
+ ],
+ "transitions": [],
+ },
+ )
+
+ def test_state_failure_policy_defaults_to_run_policy(self) -> None:
+ dag = {
+ "run": {"failure_policy": "continue"},
+ "nodes": [{"id": "a", "subagent": "w"}, {"id": "b", "subagent": "w", "failure_policy": "escalate"}],
+ }
+ result = canonicalize_factory_spec(dag)
+ self.assertEqual(result["states"][0]["failure_policy"], "continue")
+ self.assertEqual(result["states"][1]["failure_policy"], "escalate")
+
+ def test_max_transitions_defaults_to_ten_per_state_capped(self) -> None:
+ ten_states = {"nodes": [node(f"n{i}") for i in range(10)]}
+ self.assertEqual(canonicalize_factory_spec(ten_states)["run"]["max_transitions"], 100)
+ many_states = {"nodes": [node(f"n{i}") for i in range(1024)]}
+ self.assertEqual(canonicalize_factory_spec(many_states)["run"]["max_transitions"], 10_000)
+
+ def test_deduplicates_depends_on_into_one_transition(self) -> None:
+ dag = {
+ "nodes": [
+ {"id": "a", "subagent": "w"},
+ {"id": "b", "subagent": "w", "depends_on": ["a", "a", "a"]},
+ ]
+ }
+ result = canonicalize_factory_spec(dag)
+ self.assertEqual(result["transitions"], [{"from": "a", "to": "b", "on": "settled"}])
+
+ def test_machine_form_canonicalization(self) -> None:
+ machine = {
+ "run": {"failure_policy": "continue", "max_parallel": 2, "budget_ms": 5000},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": {"prompt": "Seed."}, "outputs": [{"name": "o", "type": "json"}]},
+ {
+ "id": "act",
+ "subagent": {"prompt": "Act."},
+ "inputs": [{"name": "data", "type": "json", "from": "seed.o"}],
+ "max_entries": 2,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "act", "when": {"output": "o", "path": "ready", "op": "eq", "value": False}},
+ ],
+ }
+ self.assertEqual(
+ canonicalize_factory_spec(machine),
+ {
+ "run": {
+ "failure_policy": "continue",
+ "max_parallel": 2,
+ "max_transitions": 20,
+ "max_children": 10_000,
+ "budget_ms": 5000,
+ },
+ "states": [
+ {
+ "id": "seed",
+ "entry": True,
+ "max_entries": 1,
+ "lifecycle": "task",
+ "retries": 0,
+ "failure_policy": "continue",
+ "subagent": {"prompt": "Seed."},
+ "outputs": [{"name": "o", "type": "json"}],
+ },
+ {
+ "id": "act",
+ "entry": False,
+ "max_entries": 2,
+ "subagent": {"prompt": "Act."},
+ "lifecycle": "task",
+ "retries": 0,
+ "failure_policy": "continue",
+ "inputs": [{"name": "data", "type": "json", "from": "seed.o"}],
+ }
+ ],
+ "transitions": [
+ {
+ "from": "seed",
+ "to": "act",
+ "on": "settled",
+ "when": {"output": "o", "path": "ready", "op": "eq", "value": False},
+ }
+ ],
+ },
+ )
+
+ def test_raises_with_joined_errors_on_invalid_input(self) -> None:
+ with self.assertRaises(ValueError) as ctx:
+ canonicalize_factory_spec({"nodes": [node("a", depends_on=["ghost"])]})
+ message = str(ctx.exception)
+ self.assertIn("depends on unknown node", message)
+
+ with self.assertRaises(ValueError) as ctx:
+ canonicalize_factory_spec("not a dag")
+ self.assertIn("factory dag must be a JSON object", str(ctx.exception))
+
+ with self.assertRaises(ValueError) as ctx:
+ canonicalize_factory_spec({"states": [state("a")], "transitions": [{"from": "a", "to": "ghost"}]})
+ self.assertIn("references unknown to-state", str(ctx.exception))
+
+ def test_does_not_mutate_input(self) -> None:
+ dag = {"nodes": [{"id": "a", "subagent": {"prompt": "p"}, "outputs": [{"name": "o", "type": "json"}]}]}
+ snapshot = {"nodes": [dict(dag["nodes"][0])]}
+ result = canonicalize_factory_spec(dag)
+ result["states"][0]["subagent"]["prompt"] = "mutated"
+ result["states"][0]["outputs"][0]["type"] = "text"
+ self.assertEqual(dag["nodes"][0]["subagent"]["prompt"], "p")
+ self.assertEqual(dag["nodes"][0]["outputs"][0]["type"], "json")
+ self.assertEqual(snapshot["nodes"][0]["id"], "a")
+
+ machine = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "o", "type": "json"}]),
+ state("b", inputs=[{"name": "i", "type": "json", "from": "a.o"}]),
+ ],
+ "transitions": [{"from": "a", "to": "b", "when": {"output": "o", "op": "exists"}}],
+ }
+ result = canonicalize_factory_spec(machine)
+ result["states"][0]["outputs"][0]["type"] = "mutated"
+ result["transitions"][0]["when"]["output"] = "mutated"
+ self.assertEqual(machine["states"][0]["outputs"][0]["type"], "json")
+ self.assertEqual(machine["transitions"][0]["when"]["output"], "o")
+
+
+# ---------------------------------------------------------------------------
+# Machine-form validation
+# ---------------------------------------------------------------------------
+
+
+class ValidateFactoryMachineTest(unittest.TestCase):
+ """Every machine-form validator rule, valid and invalid."""
+
+ def test_valid_machine_has_no_errors(self) -> None:
+ # Includes an entry state, a guard switch, a self-loop, re-entry
+ # bounds, and a reviewing<->fixing cycle: all legal in machine form.
+ self.assertEqual(validate_factory_spec(valid_machine()), [])
+ self.assertEqual(validate_factory_machine(valid_machine()), [])
+
+ def test_machine_must_be_an_object(self) -> None:
+ for bad in (None, [], "states", 42):
+ self.assertEqual(validate_factory_machine(bad), ["factory machine must be a JSON object"], repr(bad))
+
+ def test_states_required_and_must_be_a_list(self) -> None:
+ self.assertEqual(
+ validate_factory_machine({"transitions": []}),
+ ["factory machine requires a states list"],
+ )
+ self.assertEqual(
+ validate_factory_machine({"states": "nope"}),
+ ["factory machine requires a states list"],
+ )
+ self.assertEqual(
+ validate_factory_machine({"run": "bad", "states": "nope"}),
+ ["run must be an object", "factory machine requires a states list"],
+ )
+
+ def test_state_cap(self) -> None:
+ at_cap = {"states": [state(f"s{i}") for i in range(1024)], "transitions": []}
+ at_cap["states"][0]["entry"] = True
+ self.assertEqual(validate_factory_machine(at_cap), [])
+ over_cap = {"states": [state(f"s{i}") for i in range(1025)], "transitions": []}
+ over_cap["states"][0]["entry"] = True
+ self.assertEqual(
+ validate_factory_machine(over_cap),
+ [f"factory machine must declare between 1 and 1024 states, got 1025"],
+ )
+ empty = {"states": [], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(empty),
+ ["factory machine must declare between 1 and 1024 states, got 0"],
+ )
+
+ def test_state_ids(self) -> None:
+ for good in ("a", "state-1", "1st-state", "a" * 64):
+ machine = {"states": [{"id": good, "entry": True, "subagent": "w"}], "transitions": []}
+ self.assertEqual(validate_factory_machine(machine), [], good)
+ for bad in ("-abc", "ABC", "a_b", "a.b", "a" * 65):
+ machine = {"states": [{"id": bad, "entry": True, "subagent": "w"}], "transitions": []}
+ errors = validate_factory_machine(machine)
+ self.assertEqual(len(errors), 1, bad)
+ self.assertIn("id must match", errors[0])
+ for bad in ("", None, 5):
+ machine = {"states": [{"id": bad, "subagent": "w"}], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(machine),
+ ["states[0] requires a non-empty id"],
+ repr(bad),
+ )
+
+ def test_duplicate_state_ids(self) -> None:
+ machine = {"states": [state("dup"), state("dup")], "transitions": []}
+ machine["states"][0]["entry"] = True
+ errors = validate_factory_machine(machine)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("duplicates state id 'dup'", errors[0])
+
+ def test_entry_state_required(self) -> None:
+ no_entry = {"states": [state("a"), state("b")], "transitions": [{"from": "a", "to": "b"}]}
+ self.assertEqual(
+ validate_factory_machine(no_entry),
+ ["factory machine requires at least one entry state"],
+ )
+ explicit_false = {"states": [state("a", entry=False)], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(explicit_false),
+ ["factory machine requires at least one entry state"],
+ )
+ bad_flag = {"states": [state("a", entry="yes")], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(bad_flag),
+ ["state a entry must be a boolean", "factory machine requires at least one entry state"],
+ )
+
+ def test_optional_input_flag(self) -> None:
+ ok = {
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "w", "outputs": [{"name": "o", "type": "json"}]},
+ {
+ "id": "loop",
+ "subagent": "w",
+ "inputs": [{"name": "o", "type": "json", "from": "seed.o", "optional": True}],
+ },
+ ],
+ "transitions": [{"from": "seed", "to": "loop"}],
+ }
+ self.assertEqual(validate_factory_machine(ok), [])
+ for bad in ("yes", 1, []):
+ machine = {
+ "states": [
+ state("seed", entry=True, outputs=[{"name": "o", "type": "json"}]),
+ {
+ "id": "loop",
+ "subagent": "w",
+ "inputs": [{"name": "o", "type": "json", "from": "seed.o", "optional": bad}],
+ },
+ ],
+ "transitions": [{"from": "seed", "to": "loop"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(machine),
+ ["state loop input 'o' optional must be a boolean when provided"],
+ repr(bad),
+ )
+
+ def test_required_self_input_is_rejected_optional_stays_the_loop_form(self) -> None:
+ # A required self-input can never bind: the first entry waits for its
+ # own prior settle, which cannot exist yet -- the entry stays pending
+ # until the stall detector fails the run naming the state. Optional
+ # self-inputs are the designed loop form (first entry binds the null
+ # sentinel) and stay valid; the rule is the machine-form mirror of
+ # the dag compiler's "cannot depend on itself" rejection.
+ absent = object() # sentinel: the optional key is omitted entirely
+
+ def machine(optional: Any = absent) -> dict[str, Any]:
+ loop_inputs: list[dict[str, Any]] = [{"name": "last", "type": "text", "from": "loop.last"}]
+ if optional is not absent:
+ loop_inputs[0]["optional"] = optional
+ return {
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "w", "outputs": [{"name": "go", "type": "text"}]},
+ {
+ "id": "loop",
+ "subagent": "w",
+ "inputs": loop_inputs,
+ "outputs": [{"name": "last", "type": "text"}],
+ "max_entries": 3,
+ },
+ ],
+ "transitions": [{"from": "seed", "to": "loop"}, {"from": "loop", "to": "loop"}],
+ }
+
+ self.assertEqual(validate_factory_machine(machine(True)), [])
+ for required in (False, absent):
+ self.assertEqual(
+ validate_factory_machine(machine(required)),
+ [
+ "state loop input 'last' cannot require itself: mark the self-input optional - "
+ "a required one can never bind on the state's first entry"
+ ],
+ repr(required),
+ )
+
+ def test_entry_states_cannot_declare_inputs(self) -> None:
+ with_inputs = {
+ "states": [
+ state("src", entry=True, inputs=[{"name": "i", "type": "text", "from": "peer.o"}]),
+ state("peer", outputs=[{"name": "o", "type": "text"}]),
+ ],
+ "transitions": [{"from": "peer", "to": "src"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(with_inputs),
+ ["entry state src cannot declare inputs"],
+ )
+ entry_without_inputs = {"states": [state("a", entry=True)], "transitions": []}
+ self.assertEqual(validate_factory_machine(entry_without_inputs), [])
+ # Compiled dags only mark dep-free nodes as entry states, so the rule
+ # never fires on the dag path.
+ dag = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", depends_on=["a"], inputs=[{"name": "i", "type": "text", "from": "a.o"}]),
+ ]
+ }
+ self.assertEqual(validate_factory_spec(dag), [])
+
+ def test_max_entries(self) -> None:
+ for good in (1, 2, 99):
+ machine = {"states": [state("a", entry=True, max_entries=good)], "transitions": []}
+ self.assertEqual(validate_factory_machine(machine), [], good)
+ for bad in (0, -1, 1.5, "2", True):
+ machine = {"states": [state("a", entry=True, max_entries=bad)], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(machine),
+ ["state a max_entries must be an integer >= 1"],
+ repr(bad),
+ )
+
+ def test_subagent_required(self) -> None:
+ missing = {"states": [{"id": "a", "entry": True}], "transitions": []}
+ errors = validate_factory_machine(missing)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a subagent", errors[0])
+ self.assertIn("state a", errors[0])
+
+ empty_ref = {"states": [state("a", entry=True, subagent="")], "transitions": []}
+ errors = validate_factory_machine(empty_ref)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a subagent", errors[0])
+
+ empty_prompt = {"states": [state("a", entry=True, subagent={"prompt": ""})], "transitions": []}
+ errors = validate_factory_machine(empty_prompt)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a non-empty prompt", errors[0])
+
+ bad_model = {"states": [state("a", entry=True, subagent={"prompt": "p", "model": 5})], "transitions": []}
+ errors = validate_factory_machine(bad_model)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("model must be a non-empty string", errors[0])
+
+ # Whitespace-only inline fields are write-time invalid in machine
+ # form too (the shared state validation strips like the runtime
+ # resolvers do), so no persistable machine can be unspawnable.
+ whitespace = {
+ "states": [state("a", entry=True, subagent={"prompt": " ", "model": " \t "})],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(whitespace),
+ [
+ "state a inline subagent requires a non-empty prompt",
+ "state a inline subagent model must be a non-empty string when provided",
+ ],
+ )
+
+ inline_ok = {
+ "states": [state("a", entry=True, subagent={"prompt": "Do work.", "name": "w", "thinking": "high"})],
+ "transitions": [],
+ }
+ self.assertEqual(validate_factory_machine(inline_ok), [])
+
+ def test_inline_subagent_name_length_and_uniqueness(self) -> None:
+ # The configured name labels spawned children, and the host caps
+ # subagent session names at 64 characters: reject an over-length
+ # name at write time (a persistable factory must be spawnable)
+ # instead of failing every spawn admission.
+ too_long = {
+ "states": [state("a", entry=True, subagent={"prompt": "p", "name": "x" * (SUBAGENT_NAME_MAX_LENGTH + 1)})],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(too_long),
+ [
+ f"state a inline subagent name must be at most {SUBAGENT_NAME_MAX_LENGTH} characters, "
+ f"got {SUBAGENT_NAME_MAX_LENGTH + 1}"
+ ],
+ )
+
+ # Two states configured with one name would collide on the
+ # supervisor's unique sibling-name requirement at spawn time: reject
+ # the duplicate at write time, like duplicate state ids.
+ duplicate = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": {"prompt": "p", "name": "reviewer"}},
+ {"id": "b", "subagent": {"prompt": "p", "name": "reviewer"}},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(duplicate),
+ ["state b subagent name 'reviewer' is already configured by state 'a'"],
+ )
+ # Distinct configured names are fine, and string references never
+ # carry a name.
+ distinct = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": {"prompt": "p", "name": "reviewer"}},
+ {"id": "b", "subagent": {"prompt": "p", "name": "fixer"}},
+ {"id": "c", "subagent": "worker"},
+ ],
+ "transitions": [{"from": "a", "to": "b"}, {"from": "b", "to": "c"}],
+ }
+ self.assertEqual(validate_factory_machine(distinct), [])
+
+ # A name another state's name can suffix onto (Macroscope review
+ # finding: foo's later instances spawn foo-i1, so a state configured
+ # foo-i1 collides at spawn time) is rejected at write time, in
+ # either order; the attempt chain form is caught too.
+ shadowing = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": {"prompt": "p", "name": "foo"}},
+ {"id": "b", "subagent": {"prompt": "p", "name": "foo-i1"}},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ errors = validate_factory_machine(shadowing)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("collides with the suffixed spawn labels of state 'a'", errors[0])
+ self.assertIn("re-entry, foreach, and retries name children 'foo'-i<n> and 'foo'-a<n>", errors[0])
+ # Reversed declaration order: the CURRENT state's name generates the
+ # suffixed labels, and the message must attribute them to it, not to
+ # the earlier state (Cursor review finding).
+ reversed_shadowing = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": {"prompt": "p", "name": "foo-i1"}},
+ {"id": "b", "subagent": {"prompt": "p", "name": "foo"}},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ errors = validate_factory_machine(reversed_shadowing)
+ self.assertEqual(len(errors), 1)
+ self.assertEqual(
+ errors[0],
+ "state b subagent name 'foo' suffixed by re-entry, foreach, and retries "
+ "('foo'-i<n>, 'foo'-a<n>) collides with state 'a' (configured 'foo-i1')",
+ )
+ for shadowed_name in ("foo-a2", "foo-i1-a2", "foo-i9"):
+ machine = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": {"prompt": "p", "name": "foo"}},
+ {"id": "b", "subagent": {"prompt": "p", "name": shadowed_name}},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(len(validate_factory_machine(machine)), 1, shadowed_name)
+ # The never-generated -i0/-a1 do not shadow, and unrelated names pass.
+ no_shadow = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": {"prompt": "p", "name": "foo"}},
+ {"id": "b", "subagent": {"prompt": "p", "name": "foo-i0"}},
+ {"id": "c", "subagent": {"prompt": "p", "name": "foo-a1"}},
+ {"id": "d", "subagent": {"prompt": "p", "name": "bar-i1"}},
+ ],
+ "transitions": [{"from": "a", "to": "b"}, {"from": "b", "to": "c"}, {"from": "c", "to": "d"}],
+ }
+ self.assertEqual(validate_factory_machine(no_shadow), [])
+
+ def test_wait_states_are_gated_until_the_communication_series(self) -> None:
+ # The rlm.watch.* host handlers do not exist on this stack, so wait
+ # blocks are rejected outright (machine form and dag form alike).
+ machine = {
+ "states": [
+ {"id": "watch", "entry": True, "subagent": "w", "wait": {"kind": "path", "target": "/tmp/x", "timeout_ms": 5}},
+ state("act"),
+ ],
+ "transitions": [{"from": "watch", "to": "act"}],
+ }
+ errors = validate_factory_machine(machine)
+ self.assertEqual(
+ errors,
+ [
+ "state watch: wait states require the watch host handlers (rlm.watch.*); "
+ "they arrive with the communication series - remove the wait block until then"
+ ],
+ )
+ self.assertEqual(validate_factory_spec(machine), errors)
+
+ dag_wait = {"nodes": [node("a", wait={"kind": "path", "target": "t", "timeout_ms": 5})]}
+ errors = validate_factory_spec(dag_wait)
+ self.assertEqual(
+ errors,
+ [
+ "node a: wait states require the watch host handlers (rlm.watch.*); "
+ "they arrive with the communication series - remove the wait block until then"
+ ],
+ )
+
+ def test_resident_states(self) -> None:
+ resident_ok = {
+ "states": [
+ {"id": "entry", "entry": True, "subagent": "w", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "watcher", "subagent": "w", "lifecycle": "resident"},
+ ],
+ "transitions": [{"from": "entry", "to": "watcher"}],
+ }
+ self.assertEqual(validate_factory_machine(resident_ok), [])
+
+ declares_outputs = {
+ "states": [state("watcher", entry=True, lifecycle="resident", outputs=[{"name": "o", "type": "text"}])],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(declares_outputs),
+ ["resident state watcher cannot declare outputs"],
+ )
+ uses_foreach = {
+ "states": [
+ state("src", entry=True, outputs=[{"name": "items", "type": "json"}]),
+ {
+ "id": "watcher",
+ "subagent": "w",
+ "lifecycle": "resident",
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 4},
+ },
+ ],
+ "transitions": [{"from": "src", "to": "watcher"}],
+ }
+ self.assertEqual(validate_factory_machine(uses_foreach), ["resident state watcher cannot use foreach"])
+ leaves_resident = {
+ "states": [
+ {"id": "entry", "entry": True, "subagent": "w"},
+ {"id": "watcher", "subagent": "w", "lifecycle": "resident"},
+ ],
+ "transitions": [{"from": "watcher", "to": "entry"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(leaves_resident),
+ ["transitions[0] cannot leave resident state 'watcher'"],
+ )
+
+ def test_input_cannot_read_from_resident_state(self) -> None:
+ machine = {
+ "states": [
+ state("watcher", lifecycle="resident"),
+ state("task", inputs=[{"name": "i", "type": "text", "from": "watcher.o"}]),
+ state("seed", entry=True),
+ ],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(machine),
+ ["state task input 'i' cannot read from resident state 'watcher'"],
+ )
+
+ def test_port_rules(self) -> None:
+ dup_output = {"states": [state("a", entry=True, outputs=[{"name": "o", "type": "text"}, {"name": "o", "type": "json"}])], "transitions": []}
+ self.assertEqual(validate_factory_machine(dup_output), ["state a declares duplicate output name 'o'"])
+ bad_type = {"states": [state("a", entry=True, outputs=[{"name": "o", "type": "yaml"}])], "transitions": []}
+ self.assertEqual(validate_factory_machine(bad_type), ["state a output 'o' type must be 'text' or 'json'"])
+ unknown_source = {
+ "states": [state("a", entry=True), state("b", inputs=[{"name": "i", "type": "text", "from": "ghost.o"}])],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(unknown_source),
+ ["state b input 'i' references unknown state 'ghost'"],
+ )
+ undeclared_output = {
+ "states": [
+ state("a", entry=True),
+ state("b", inputs=[{"name": "i", "type": "text", "from": "a.missing"}]),
+ ],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(undeclared_output),
+ ["state b input 'i' references output 'missing' that state 'a' does not declare"],
+ )
+ type_mismatch = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "o", "type": "text"}]),
+ state("b", inputs=[{"name": "i", "type": "json", "from": "a.o"}]),
+ ],
+ "transitions": [],
+ }
+ errors = validate_factory_machine(type_mismatch)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("cannot read from output", errors[0])
+ malformed = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "o", "type": "text"}]),
+ state("b", inputs=[{"name": "i", "type": "text", "from": "nodot"}]),
+ ],
+ "transitions": [],
+ }
+ errors = validate_factory_machine(malformed)
+ self.assertEqual(len(errors), 1)
+ self.assertIn("requires a 'from' reference", errors[0])
+
+ def test_budgets_and_retries_and_policies(self) -> None:
+ over = {
+ "run": {"budget_ms": 1000},
+ "states": [state("a", entry=True, budget_ms=1001)],
+ "transitions": [],
+ }
+ self.assertEqual(
+ validate_factory_machine(over),
+ ["state a budget_ms 1001 exceeds the run budget_ms 1000"],
+ )
+ for bad in (0, -5, 1.5, "10", True):
+ machine = {"run": {"budget_ms": bad}, "states": [state("a", entry=True)], "transitions": []}
+ self.assertEqual(validate_factory_machine(machine), ["run budget_ms must be a positive integer"], bad)
+ machine = {"states": [state("a", entry=True, budget_ms=bad)], "transitions": []}
+ self.assertEqual(validate_factory_machine(machine), ["state a budget_ms must be a positive integer"], bad)
+ for bad in (-1, 11, 1.5, "2", True):
+ machine = {"states": [state("a", entry=True, retries=bad)], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(machine),
+ ["state a retries must be an integer between 0 and 10"],
+ bad,
+ )
+ bad_policy = {"states": [state("a", entry=True, failure_policy="retry")], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(bad_policy),
+ ["state a failure_policy must be one of ['fail_fast', 'continue', 'escalate'], got 'retry'"],
+ )
+ bad_lifecycle = {"states": [state("a", entry=True, lifecycle="daemon")], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(bad_lifecycle),
+ ["state a lifecycle must be 'task' or 'resident', got 'daemon'"],
+ )
+
+ def test_run_max_transitions(self) -> None:
+ for good in (1, 40, 10_000):
+ machine = {"run": {"max_transitions": good}, "states": [state("a", entry=True)], "transitions": []}
+ self.assertEqual(validate_factory_machine(machine), [], good)
+ for bad in (0, -1, 10_001, 1.5, "5", True):
+ machine = {"run": {"max_transitions": bad}, "states": [state("a", entry=True)], "transitions": []}
+ self.assertEqual(
+ validate_factory_machine(machine),
+ ["run max_transitions must be a positive integer no greater than 10000"],
+ bad,
+ )
+
+ def test_foreach_rules(self) -> None:
+ ok = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "items", "type": "json"}]),
+ state(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "items", "max": 16},
+ ),
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(validate_factory_machine(ok), [])
+ wrong_port = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "items", "type": "json"}]),
+ state(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "not-an-input", "max": 4},
+ ),
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(wrong_port),
+ ["state b foreach.over must name one of this state's inputs, got 'not-an-input'"],
+ )
+ text_port = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "draft", "type": "text"}]),
+ state(
+ "b",
+ inputs=[{"name": "draft", "type": "text", "from": "a.draft"}],
+ foreach={"over": "draft", "max": 4},
+ ),
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(validate_factory_machine(text_port), ["state b foreach.over input 'draft' must have type 'json'"])
+ bad_max = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "items", "type": "json"}]),
+ state(
+ "b",
+ inputs=[{"name": "items", "type": "json", "from": "a.items"}],
+ foreach={"over": "items", "max": 257},
+ ),
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(validate_factory_machine(bad_max), ["state b foreach.max must be an integer between 1 and 256"])
+ not_object = {"states": [state("a", entry=True, foreach=["bad"])], "transitions": []}
+ self.assertEqual(validate_factory_machine(not_object), ["state a foreach must be an object"])
+
+ def test_transitions_reference_existing_states(self) -> None:
+ unknown_from = {
+ "states": [state("a", entry=True)],
+ "transitions": [{"from": "ghost", "to": "a"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(unknown_from),
+ ["transitions[0] references unknown from-state 'ghost'"],
+ )
+ unknown_to = {"states": [state("a", entry=True)], "transitions": [{"from": "a", "to": "ghost"}]}
+ self.assertEqual(
+ validate_factory_machine(unknown_to),
+ ["transitions[0] references unknown to-state 'ghost'"],
+ )
+ not_object = {"states": [state("a", entry=True)], "transitions": ["bad"]}
+ self.assertEqual(validate_factory_machine(not_object), ["transitions[0] must be an object"])
+ not_a_list = {"states": [state("a", entry=True)], "transitions": "bad"}
+ self.assertEqual(validate_factory_machine(not_a_list), ["factory machine transitions must be a list"])
+ bad_on = {"states": [state("a", entry=True)], "transitions": [{"from": "a", "to": "a", "on": "manual"}]}
+ self.assertEqual(
+ validate_factory_machine(bad_on),
+ ["transitions[0] on must be one of ['settled'], got 'manual'"],
+ )
+
+ def test_join_transitions_from_a_list(self) -> None:
+ # A ``from`` LIST is a join transition: it fires once every source
+ # state settled (the compiled dag fan-in shape).
+ ok = {
+ "states": [
+ state("a", entry=True),
+ state("b", entry=True),
+ state("d"),
+ ],
+ "transitions": [{"from": ["a", "b"], "to": "d"}],
+ }
+ self.assertEqual(validate_factory_machine(ok), [])
+
+ unknown_source = {
+ "states": [state("a", entry=True), state("d")],
+ "transitions": [{"from": ["a", "ghost"], "to": "d"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(unknown_source),
+ ["transitions[0] references unknown from-state 'ghost'"],
+ )
+ repeated_source = {
+ "states": [state("a", entry=True), state("d")],
+ "transitions": [{"from": ["a", "a"], "to": "d"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(repeated_source),
+ ["transitions[0] from must not repeat a state"],
+ )
+ empty_source = {
+ "states": [state("a", entry=True), state("d")],
+ "transitions": [{"from": [], "to": "d"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(empty_source),
+ ["transitions[0] from must name at least one state"],
+ )
+ non_string_entry = {
+ "states": [state("a", entry=True), state("d")],
+ "transitions": [{"from": ["a", 5], "to": "d"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(non_string_entry),
+ ["transitions[0] from entries must be non-empty state id strings"],
+ )
+ # A guard needs exactly one from-state's latest settle output.
+ guard_on_join = {
+ "states": [
+ state("a", entry=True),
+ state("b", entry=True),
+ state("d"),
+ ],
+ "transitions": [
+ {"from": ["a", "b"], "to": "d", "when": {"output": "o", "op": "exists"}},
+ ],
+ }
+ self.assertEqual(
+ validate_factory_machine(guard_on_join),
+ [
+ "transitions[0] with multiple from-states cannot carry a when guard; "
+ "use single-state transitions for guards"
+ ],
+ )
+ resident_source = {
+ "states": [
+ state("a", entry=True),
+ {"id": "watcher", "subagent": "w", "lifecycle": "resident"},
+ state("d"),
+ ],
+ "transitions": [{"from": ["a", "watcher"], "to": "d"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(resident_source),
+ ["transitions[0] cannot leave resident state 'watcher'"],
+ )
+ # Regression (bot review): UNHASHABLE malformed entries (a dict, a
+ # list) used to raise a raw TypeError from the set() dedupe before
+ # the type check; validation must report an error instead.
+ for bad_from in ([{}], [[1]], ["a", {}]):
+ malformed = {
+ "states": [state("a", entry=True), state("d")],
+ "transitions": [{"from": bad_from, "to": "d"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(malformed),
+ ["transitions[0] from entries must be non-empty state id strings"],
+ )
+ self.assertEqual(
+ validate_factory_spec(
+ {
+ "states": [state("a", entry=True), state("d")],
+ "transitions": [{"from": bad_from, "to": "d"}],
+ }
+ ),
+ ["transitions[0] from entries must be non-empty state id strings"],
+ )
+
+ def test_self_loop_is_legal_re_entry(self) -> None:
+ machine = {
+ "states": [state("a", entry=True, max_entries=5, outputs=[{"name": "o", "type": "json"}])],
+ "transitions": [{"from": "a", "to": "a"}],
+ }
+ self.assertEqual(validate_factory_machine(machine), [])
+
+ def test_cyclic_machine_validates(self) -> None:
+ machine = {
+ "states": [
+ state("seed", entry=True, outputs=[{"name": "o", "type": "text"}]),
+ state("b"),
+ state("c"),
+ ],
+ "transitions": [
+ {"from": "seed", "to": "b"},
+ {"from": "b", "to": "c"},
+ {"from": "c", "to": "b"},
+ ],
+ }
+ self.assertEqual(validate_factory_machine(machine), [])
+ self.assertEqual(validate_factory_spec(machine), [])
+
+ def test_guard_rules(self) -> None:
+ 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}],
+ }
+
+ unknown_output = machine_with({"output": "missing", "op": "exists"})
+ self.assertEqual(
+ validate_factory_machine(unknown_output),
+ ["transitions[0] when.output 'missing' is not a declared output of state 'a'"],
+ )
+ empty_output = machine_with({"output": "", "op": "exists"})
+ self.assertEqual(
+ validate_factory_machine(empty_output),
+ ["transitions[0] when requires a non-empty output"],
+ )
+ not_object = machine_with("nope")
+ self.assertEqual(validate_factory_machine(not_object), ["transitions[0] when must be an object"])
+ path_on_text = {
+ "states": [
+ state("a", entry=True, outputs=[{"name": "note", "type": "text"}]),
+ state("b"),
+ ],
+ "transitions": [{"from": "a", "to": "b", "when": {"output": "note", "path": "x", "op": "eq", "value": 1}}],
+ }
+ self.assertEqual(
+ validate_factory_machine(path_on_text),
+ ["transitions[0] when.path requires a json output, got text output 'note'"],
+ )
+ bad_op = machine_with({"output": "verdict", "op": "matches", "value": 1})
+ self.assertEqual(
+ validate_factory_machine(bad_op),
+ ["transitions[0] when.op must be one of ['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'exists', 'contains'], got 'matches'"],
+ )
+ for op in ("gt", "gte", "lt", "lte"):
+ non_numeric = machine_with({"output": "verdict", "op": op, "value": "1"})
+ self.assertEqual(
+ validate_factory_machine(non_numeric),
+ [f"transitions[0] when.op {op!r} requires a numeric value"],
+ op,
+ )
+ contains_needs_list = machine_with({"output": "verdict", "op": "contains", "value": "x"})
+ self.assertEqual(
+ validate_factory_machine(contains_needs_list),
+ ["transitions[0] when.op 'contains' requires a non-empty list value"],
+ )
+ # Review finding: an empty list is not a legal contains needle.
+ contains_empty_list = machine_with({"output": "verdict", "op": "contains", "value": []})
+ self.assertEqual(
+ validate_factory_machine(contains_empty_list),
+ ["transitions[0] when.op 'contains' requires a non-empty list value"],
+ )
+ eq_rejects_list = machine_with({"output": "verdict", "op": "eq", "value": [1]})
+ self.assertEqual(
+ validate_factory_machine(eq_rejects_list),
+ ["transitions[0] when.op 'eq' requires a scalar value"],
+ )
+ ne_rejects_list = machine_with({"output": "verdict", "op": "ne", "value": [1]})
+ self.assertEqual(
+ validate_factory_machine(ne_rejects_list),
+ ["transitions[0] when.op 'ne' requires a scalar value"],
+ )
+ empty_path = machine_with({"output": "verdict", "path": "", "op": "exists"})
+ self.assertEqual(
+ validate_factory_machine(empty_path),
+ ["transitions[0] when.path must be a non-empty dotted path"],
+ )
+ # Valid guard shapes across every op.
+ for when in (
+ {"output": "verdict", "path": "approved", "op": "eq", "value": False},
+ {"output": "verdict", "path": "approved", "op": "ne", "value": True},
+ {"output": "verdict", "path": "score", "op": "gt", "value": 1.5},
+ {"output": "verdict", "path": "score", "op": "gte", "value": 2},
+ {"output": "verdict", "path": "score", "op": "lt", "value": 0},
+ {"output": "verdict", "path": "score", "op": "lte", "value": -3},
+ {"output": "verdict", "path": "findings", "op": "exists"},
+ {"output": "verdict", "path": "tags", "op": "contains", "value": ["a", "b"]},
+ {"output": "verdict", "op": "exists"},
+ ):
+ self.assertEqual(validate_factory_machine(machine_with(when)), [], repr(when))
+
+ def test_collects_multiple_errors(self) -> None:
+ machine = {
+ "run": {"max_parallel": 99, "failure_policy": "nope"},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "w", "retries": 99},
+ {"id": "b", "subagent": "w", "max_entries": 0},
+ ],
+ "transitions": [{"from": "a", "to": "ghost"}],
+ }
+ self.assertEqual(
+ validate_factory_machine(machine),
+ [
+ "run failure_policy must be one of ['fail_fast', 'continue', 'escalate'], got 'nope'",
+ "run max_parallel must be an integer between 1 and 64",
+ "state a retries must be an integer between 0 and 10",
+ "state b max_entries must be an integer >= 1",
+ "transitions[0] references unknown to-state 'ghost'",
+ ],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Dag compilation: the dag sugar compiles to machine form
+# ---------------------------------------------------------------------------
+
+
+class CompileFactoryDagTest(unittest.TestCase):
+ def test_chain_compiles(self) -> None:
+ dag = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", depends_on=["a"]),
+ node("c", depends_on=["b"]),
+ ]
+ }
+ machine, errors = compile_factory_dag(dag)
+ self.assertEqual(errors, [])
+ self.assertEqual(
+ machine,
+ {
+ "states": [
+ {"id": "a", "entry": True, "max_entries": 1, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "entry": False, "max_entries": 1, "subagent": "worker"},
+ {"id": "c", "entry": False, "max_entries": 1, "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "a", "to": "b"},
+ {"from": "b", "to": "c"},
+ ],
+ },
+ )
+ self.assertEqual(validate_factory_machine(machine), [])
+
+ def test_diamond_compiles_the_fan_in_to_one_join_transition(self) -> None:
+ # Review finding: a fan-in node's full effective dependency set
+ # compiles to ONE join transition that waits for every predecessor.
+ # Per-edge transitions would let d start after only b (or c) settled
+ # and then block the other transition at max_entries, so d could run
+ # with a missing input.
+ dag = {
+ "run": {"failure_policy": "continue", "max_parallel": 3, "budget_ms": 5000},
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", depends_on=["a"], outputs=[{"name": "o", "type": "text"}]),
+ node("c", depends_on=["a"], outputs=[{"name": "o", "type": "text"}]),
+ node(
+ "d",
+ depends_on=["b", "c"],
+ inputs=[{"name": "left", "type": "text", "from": "b.o"}, {"name": "right", "type": "text", "from": "c.o"}],
+ budget_ms=4000,
+ ),
+ ],
+ }
+ machine, errors = compile_factory_dag(dag)
+ self.assertEqual(errors, [])
+ self.assertEqual(
+ machine,
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 3, "budget_ms": 5000},
+ "states": [
+ {"id": "a", "entry": True, "max_entries": 1, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "entry": False, "max_entries": 1, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "c", "entry": False, "max_entries": 1, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {
+ "id": "d",
+ "entry": False,
+ "max_entries": 1,
+ "subagent": "worker",
+ "budget_ms": 4000,
+ "inputs": [
+ {"name": "left", "type": "text", "from": "b.o"},
+ {"name": "right", "type": "text", "from": "c.o"},
+ ],
+ },
+ ],
+ "transitions": [
+ {"from": "a", "to": "b"},
+ {"from": "a", "to": "c"},
+ {"from": ["b", "c"], "to": "d"},
+ ],
+ },
+ )
+ self.assertEqual(validate_factory_machine(machine), [])
+
+ def test_wide_fan_in_stays_one_join_per_target(self) -> None:
+ # 300 predecessors, data edges plus depends_on: the target's compiled
+ # machine carries exactly ONE join transition listing them all.
+ sources = [node(f"s{i}", outputs=[{"name": "o", "type": "text"}]) for i in range(300)]
+ target = node(
+ "t",
+ depends_on=[f"s{i}" for i in range(0, 300, 2)],
+ inputs=[{"name": f"i{i}", "type": "text", "from": f"s{i}.o"} for i in range(1, 300, 2)],
+ )
+ machine, errors = compile_factory_dag({"nodes": [*sources, target]})
+ self.assertEqual(errors, [])
+ self.assertEqual(len(machine["transitions"]), 1)
+ join = machine["transitions"][0]
+ self.assertEqual(join["to"], "t")
+ self.assertEqual(set(join["from"]), {f"s{i}" for i in range(300)})
+ self.assertEqual(validate_factory_machine(machine), [])
+
+ def test_control_only_dependency_waits_too(self) -> None:
+ # The join carries depends_on-only edges as well: a node with a
+ # control-only parent must still wait for that parent's settle.
+ dag = {
+ "nodes": [
+ node("b", outputs=[{"name": "o", "type": "text"}]),
+ node("c"),
+ node("d", depends_on=["b", "c"], inputs=[{"name": "l", "type": "text", "from": "b.o"}]),
+ ]
+ }
+ machine, errors = compile_factory_dag(dag)
+ self.assertEqual(errors, [])
+ # c contributes no data (d reads nothing from it), so the join waits
+ # for it as a pure control-only parent.
+ self.assertEqual(machine["transitions"], [{"from": ["b", "c"], "to": "d"}])
+
+ def test_data_edge_alone_creates_a_transition(self) -> None:
+ dag = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", inputs=[{"name": "i", "type": "text", "from": "a.o"}]),
+ ]
+ }
+ machine, errors = compile_factory_dag(dag)
+ self.assertEqual(errors, [])
+ self.assertEqual(machine["states"][1]["entry"], False)
+ self.assertEqual(machine["transitions"], [{"from": "a", "to": "b"}])
+
+ def test_depends_on_and_input_edge_dedupe_into_one_transition(self) -> None:
+ dag = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", depends_on=["a", "a"], inputs=[{"name": "i", "type": "text", "from": "a.o"}]),
+ ]
+ }
+ machine, errors = compile_factory_dag(dag)
+ self.assertEqual(errors, [])
+ self.assertEqual(machine["transitions"], [{"from": "a", "to": "b"}])
+
+ def test_explicit_empty_depends_on_still_enters(self) -> None:
+ dag = {"nodes": [node("a", depends_on=[])]}
+ machine, errors = compile_factory_dag(dag)
+ self.assertEqual(errors, [])
+ self.assertEqual(machine["states"][0]["entry"], True)
+ self.assertEqual(machine["transitions"], [])
+
+ def test_invalid_dag_returns_errors_without_a_machine(self) -> None:
+ for bad, expected in (
+ ("nope", "factory dag must be a JSON object"),
+ ({"nodes": "nope"}, "factory dag requires a nodes list"),
+ ({"nodes": []}, "factory dag must declare between 1 and 1024 nodes, got 0"),
+ ({"nodes": [node("a", depends_on=["ghost"])]}, "node a depends on unknown node 'ghost'"),
+ ):
+ machine, errors = compile_factory_dag(bad)
+ self.assertIsNone(machine, repr(bad))
+ self.assertEqual(len(errors), 1, repr(bad))
+ self.assertIn(expected, errors[0])
+
+ def test_compiled_dag_and_handwritten_machine_canonicalize_identically(self) -> None:
+ dag = {
+ "run": {"failure_policy": "continue", "max_parallel": 2},
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", depends_on=["a"], budget_ms=1000),
+ ],
+ }
+ machine = {
+ "run": {"failure_policy": "continue", "max_parallel": 2},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "subagent": "worker", "max_entries": 1, "budget_ms": 1000},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ self.assertEqual(canonicalize_factory_spec(dag), canonicalize_factory_spec(machine))
+
+ # The join form compiles identically too.
+ diamond_dag = {
+ "nodes": [
+ node("a", outputs=[{"name": "o", "type": "text"}]),
+ node("b", depends_on=["a"]),
+ node("c", depends_on=["a"]),
+ node("d", depends_on=["b", "c"]),
+ ]
+ }
+ diamond_machine = {
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "subagent": "worker", "max_entries": 1},
+ {"id": "c", "subagent": "worker", "max_entries": 1},
+ {"id": "d", "subagent": "worker", "max_entries": 1},
+ ],
+ "transitions": [
+ {"from": "a", "to": "b"},
+ {"from": "a", "to": "c"},
+ {"from": ["b", "c"], "to": "d"},
+ ],
+ }
+ self.assertEqual(canonicalize_factory_spec(diamond_dag), canonicalize_factory_spec(diamond_machine))
+
+
+class ValidateFactorySpecFormTest(unittest.TestCase):
+ """The unified entry point detects the form first."""
+
+ def test_both_forms_are_rejected_together(self) -> None:
+ both = {"nodes": [node("a")], "states": [state("a", entry=True)]}
+ self.assertEqual(validate_factory_spec(both), ["pass either dag or machine form, not both"])
+ with self.assertRaisesRegex(ValueError, "not both"):
+ canonicalize_factory_spec(both)
+
+ def test_machine_wins_when_states_or_transitions_present(self) -> None:
+ transitions_only = {"transitions": [{"from": "a", "to": "b"}]}
+ self.assertEqual(
+ validate_factory_spec(transitions_only),
+ ["factory machine requires a states list"],
+ )
+
+ def test_dag_wording_without_machine_keys(self) -> None:
+ self.assertEqual(
+ validate_factory_spec({"nodes": "nope"}),
+ ["factory dag requires a nodes list"],
+ )
+
+ def test_validation_reports_errors_and_never_raises(self) -> None:
+ # The write-time dry run touches arbitrary caller JSON: malformed
+ # shapes (unhashable entries, wrong types everywhere) must surface
+ # as error lists, never as raw exceptions (regression: the join
+ # set() dedupe used to raise TypeError on unhashable from entries).
+ hostile = [
+ "str",
+ 12,
+ None,
+ {"nodes": "nope"},
+ {"nodes": [None, 5, "str"]},
+ {"nodes": [{"id": {}, "subagent": "w"}]},
+ {"nodes": [{"id": ["x"], "subagent": "w"}]},
+ {"nodes": [{"id": "a", "subagent": {"prompt": 1}}]},
+ {"nodes": [{"id": "a", "subagent": "w", "depends_on": "a"}]},
+ {"nodes": [{"id": "a", "subagent": "w", "depends_on": [{}]}]},
+ {"nodes": [{"id": "a", "subagent": "w", "inputs": "nope"}]},
+ {"nodes": [{"id": "a", "subagent": "w", "inputs": [{"from": 5}]}]},
+ {"nodes": [{"id": "a", "subagent": "w", "outputs": [{"name": {}, "type": "text"}]}]},
+ {"nodes": [{"id": "a", "subagent": "w", "foreach": {"over": 5, "max": "x"}}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w"}], "transitions": [{"from": {}, "to": "a"}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w"}], "transitions": [{"from": [{}], "to": "a"}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w"}], "transitions": [{"from": ["a", {}], "to": "a"}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w"}], "transitions": [{"from": ["a"], "to": {}}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w"}], "transitions": [{"from": "a", "to": "a", "when": {"op": "eq", "value": [1]}}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w", "max_entries": {}}]},
+ {"states": [{"id": "a", "entry": True, "subagent": "w"}], "transitions": {"from": "a"}},
+ {"nodes": [{"id": "a", "subagent": "w"}], "states": [{"id": "b", "entry": True, "subagent": "w"}]},
+ ]
+ for index, spec in enumerate(hostile):
+ result = validate_factory_spec(spec)
+ self.assertIsInstance(result, list, f"spec #{index}")
+ self.assertTrue(all(isinstance(error, str) and error for error in result), f"spec #{index}")
+ self.assertTrue(result, f"hostile spec #{index} must report errors")
+
+
+ def test_non_object_specs_reject_with_dag_wording(self) -> None:
+ for bad in (None, [], "nodes", 42):
+ self.assertEqual(validate_factory_spec(bad), ["factory dag must be a JSON object"], repr(bad))
+
+
+class TopologicalOrderTest(unittest.TestCase):
+ def test_happy_path_respects_effective_dependencies(self) -> None:
+ nodes = [
+ node("z", inputs=[{"name": "i", "type": "text", "from": "m.o"}]),
+ node("a"),
+ node("m", outputs=[{"name": "o", "type": "text"}], depends_on=["a"]),
+ ]
+ self.assertEqual(topological_order(nodes), ["a", "m", "z"])
+
+ def test_chain(self) -> None:
+ nodes = [
+ node("c", depends_on=["b"]),
+ node("b", depends_on=["a"]),
+ node("a"),
+ ]
+ self.assertEqual(topological_order(nodes), ["a", "b", "c"])
+
+ def test_cycle_raises(self) -> None:
+ nodes = [node("a", depends_on=["b"]), node("b", depends_on=["a"])]
+ with self.assertRaises(ValueError) as ctx:
+ topological_order(nodes)
+ self.assertIn("contains a cycle", str(ctx.exception))
+
+ self_cycle = [node("a", depends_on=["a"])]
+ with self.assertRaises(ValueError) as ctx:
+ topological_order(self_cycle)
+ self.assertIn("contains a cycle", str(ctx.exception))
+
+ def test_missing_dependency_raises(self) -> None:
+ with self.assertRaises(ValueError) as ctx:
+ topological_order([node("a", depends_on=["ghost"])])
+ self.assertIn("depends on unknown node 'ghost'", str(ctx.exception))
+
+ def test_duplicate_id_raises(self) -> None:
+ with self.assertRaises(ValueError) as ctx:
+ topological_order([node("a"), node("a")])
+ self.assertIn("duplicate node id 'a'", str(ctx.exception))
+
+ def test_malformed_nodes_raise(self) -> None:
+ with self.assertRaises(ValueError):
+ topological_order(["not an object"]) # type: ignore[list-item]
+ with self.assertRaises(ValueError):
+ topological_order([{"subagent": "w"}])
+ with self.assertRaises(ValueError):
+ topological_order([node("a", depends_on="b")]) # type: ignore[arg-type]
+ with self.assertRaises(ValueError):
+ topological_order([node("a", inputs="b")]) # type: ignore[arg-type]
+ with self.assertRaises(ValueError):
+ topological_order([node("a", inputs=["not an object"])]) # type: ignore[list-item]
+ with self.assertRaises(ValueError):
+ topological_order([node("a", inputs=[{"name": "i", "type": "text", "from": "nodot"}])])
+
+ def test_stable_order_uses_input_position(self) -> None:
+ nodes = [node("b"), node("c"), node("a"), node("d")]
+ self.assertEqual(topological_order(nodes), ["b", "c", "a", "d"])
+
+
+class NonQuadraticValidationTest(unittest.TestCase):
+ """Review finding: write-time validation must stay linear in the port
+ count. A rebuild-and-count duplicate check is quadratic, so a state with
+ tens of thousands of ports would block the write."""
+
+ def test_many_outputs_validate_in_linear_time(self) -> None:
+ outputs = [{"name": f"o{i}", "type": "text"} for i in range(8000)]
+ outputs.append({"name": "o1", "type": "json"}) # a duplicate at the end
+ dag = {"nodes": [node("a", outputs=outputs)]}
+ started = time.monotonic()
+ errors = validate_factory_spec(dag)
+ elapsed = time.monotonic() - started
+ self.assertEqual(errors, ["node a declares duplicate output name 'o1'"])
+ self.assertLess(elapsed, 2.0)
+
+ def test_many_inputs_from_one_source_validate_in_linear_time(self) -> None:
+ source = node("src", outputs=[{"name": f"o{i}", "type": "text"} for i in range(3000)])
+ inputs = [{"name": f"i{i}", "type": "text", "from": f"src.o{i}"} for i in range(3000)]
+ inputs.append({"name": "i1", "type": "text", "from": "src.o1"}) # duplicate input name
+ dag = {"nodes": [source, node("dst", inputs=inputs)]}
+ started = time.monotonic()
+ errors = validate_factory_spec(dag)
+ elapsed = time.monotonic() - started
+ self.assertEqual(errors, ["node dst declares duplicate input name 'i1'"])
+ self.assertLess(elapsed, 2.0)
+
+ def test_many_duplicate_outputs_report_once(self) -> None:
+ # The duplicate report is deduplicated too: every repeat of one
+ # name produces exactly one error sentence.
+ outputs = [{"name": "dup", "type": "text"} for _ in range(500)]
+ dag = {"nodes": [node("a", outputs=outputs)]}
+ self.assertEqual(validate_factory_spec(dag), ["node a declares duplicate output name 'dup'"])
+
+
+class ChildNameTest(unittest.TestCase):
+ def test_short_state_ids_keep_their_slug(self) -> None:
+ name = _child_name("0123456789abcdef", "collect", 0, 1)
+ self.assertEqual(name, "sw-collect-012345-i0")
+ self.assertLessEqual(len(name), 64)
+
+ def test_long_state_ids_disambiguate_with_a_digest(self) -> None:
+ # Review finding: truncating the state id to 20 characters made two
+ # states sharing a prefix collide on the supervisor's unique
+ # sibling-name requirement; the token now carries a digest of the
+ # full id.
+ one = _child_name("0123456789abcdef", "collect-findings-pass-one", 0, 1)
+ two = _child_name("0123456789abcdef", "collect-findings-pass-two", 0, 1)
+ self.assertNotEqual(one, two)
+ self.assertLessEqual(len(one), 64)
+ self.assertLessEqual(len(two), 64)
+ # The instance index and the attempt disambiguate re-spawns.
+ self.assertNotEqual(_child_name("r", "collect", 0, 1), _child_name("r", "collect", 1, 1))
+ self.assertTrue(_child_name("r", "collect", 0, 2).endswith("-a2"))
+
+
+class SpawnLabelTest(unittest.TestCase):
+ """The configured inline subagent name labels spawned children.
+
+ The first instance of a state spawns with the configured name verbatim
+ (the label agents message the child by); later instances and retries
+ keep the generated label's -i<n>/-a<n> suffixes, because one state's
+ settled children stay registered for the run's life and the supervisor
+ rejects duplicate sibling names. (Macroscope review finding: the name
+ was dropped, so every child got the generated label.)
+ """
+
+ def test_configured_name_labels_the_first_instance_verbatim(self) -> None:
+ self.assertEqual(_spawn_label("reviewer", "0123456789abcdef", "reviewing", 0, 1), "reviewer")
+
+ def test_configured_name_keeps_the_generated_suffixes_when_disambiguating(self) -> None:
+ self.assertEqual(_spawn_label("reviewer", "r", "reviewing", 1, 1), "reviewer-i1")
+ self.assertEqual(_spawn_label("reviewer", "r", "reviewing", 0, 2), "reviewer-a2")
+ self.assertEqual(_spawn_label("reviewer", "r", "reviewing", 2, 3), "reviewer-i2-a3")
+ self.assertNotEqual(
+ _spawn_label("reviewer", "r", "reviewing", 0, 1), _spawn_label("reviewer", "r", "reviewing", 1, 1)
+ )
+
+ def test_absent_configured_name_falls_back_to_the_generated_label(self) -> None:
+ self.assertEqual(
+ _spawn_label(None, "0123456789abcdef", "collect", 0, 1),
+ _child_name("0123456789abcdef", "collect", 0, 1),
+ )
+
+ def test_suffixed_labels_stay_within_the_host_cap(self) -> None:
+ # A configured name at the 64-character cap still fits its first
+ # instance; a suffixed admission that would pass the cap shrinks
+ # its base with a digest of the full name, like the generated
+ # labels do (Macroscope and Cursor review findings: the overflow
+ # would fail every later spawn admission).
+ long_name = "x" * SUBAGENT_NAME_MAX_LENGTH
+ self.assertEqual(_spawn_label(long_name, "r", "a", 0, 1), long_name)
+ second = _spawn_label(long_name, "r", "a", 1, 1)
+ self.assertLessEqual(len(second), SUBAGENT_NAME_MAX_LENGTH)
+ self.assertTrue(second.endswith("-i1"))
+ self.assertIn(hashlib.sha256(long_name.encode("utf-8")).hexdigest()[:16], second)
+ # Truncation alone could collide (two long names sharing the
+ # prefix): the digest keeps them distinct.
+ sharing_prefix = "x" * (SUBAGENT_NAME_MAX_LENGTH - 1) + "y"
+ other = _spawn_label(sharing_prefix, "r", "a", 1, 1)
+ self.assertNotEqual(second, other)
+ self.assertLessEqual(len(other), SUBAGENT_NAME_MAX_LENGTH)
+ # Retry suffixes and both suffixes together fit as well.
+ for instance_index, attempt in ((0, 2), (9, 12), (1000000, 99)):
+ self.assertLessEqual(
+ len(_spawn_label(long_name, "r", "a", instance_index, attempt)),
+ SUBAGENT_NAME_MAX_LENGTH,
+ (instance_index, attempt),
+ )
+
+
+class FactoryHelpTest(unittest.TestCase):
+ """rlm.factory.help(): the embedded authoring reference (PR #3199).
+
+ The full agent-facing reference — authoring rules, guards/joins/cycles,
+ foreach, budgets, stall detectors, and the API with worked examples —
+ is a module-level constant in rlm/factory.py; ``help()`` returns it
+ with no filesystem resolution, so packaged kernels (where the repo
+ layout is not adjacent) see the same guide.
+ """
+
+ def test_factory_help_returns_the_full_reference(self) -> None:
+ doc = rlm_module.rlm.factory.help()
+ self.assertIsInstance(doc, str)
+ # help() returns the embedded constant, never a filesystem read.
+ self.assertEqual(doc, factory_module.FACTORY_HELP)
+
+ # The shipped section structure: store, author, dag sugar, run, safety.
+ for heading in (
+ "# Factory",
+ "## Store the spec",
+ "## Authoring reference",
+ "## Dag form",
+ "## Run and steer",
+ "## Safety",
+ ):
+ self.assertIn(heading, doc)
+
+ # Prose sections wrap at ~76 columns; flatten before matching phrases.
+ flat = " ".join(doc.split())
+ # The opt-in contract in the opening: disabled by default, the
+ # /factory on|off|status pointer, the exact refusal, and help()
+ # readable while disabled.
+ self.assertIn("The factory is opt-in: it ships disabled", flat)
+ self.assertIn("`/factory on` (`/factory off` disables it again, `/factory status` reports it;", flat)
+ self.assertIn("the persisted setting is `factory.enabled` in the agent dir's settings.json", flat)
+ self.assertIn("every `rlm.factory` call except `help()`", flat)
+ self.assertIn("every factory harness write (`create_factory` and updates of factory entries)", flat)
+ self.assertIn(factory_module.FACTORY_DISABLED_MESSAGE, flat)
+ self.assertIn("`help()` answers while disabled", flat)
+ # Guards: the op set evaluated over the from-state's latest settle.
+ self.assertIn("`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `exists`, `contains`", flat)
+ self.assertIn("over the from-state's latest settle", flat)
+ # foreach: one child per item of the named json input, clamped at max.
+ self.assertIn('**foreach**: `{"over": "<input>", "max": 1..256}`', flat)
+ self.assertIn("expands one entry into one child per item of the named `json` input", flat)
+ # max_parallel is the run's global budget, not a per-node limit.
+ self.assertIn(
+ "`run.max_parallel` (1..64, default 8) is the run's global budget of "
+ "simultaneously running instances",
+ flat,
+ )
+ self.assertIn("not a per-node limit", flat)
+ # Stall detectors: dead configurations fail loudly, never wedge.
+ self.assertIn("Dead configurations fail loudly, never wedge", flat)
+ self.assertIn("nothing in flight and nothing pending", flat)
+ # The stop/resume contract.
+ self.assertIn("`stop(run_id)` cancels every running child of the run (idempotent)", flat)
+ self.assertIn("`resume(run_id)` continues a paused run and raises on a non-paused one", flat)
+
+ # The run/status snippet, as the agent types it.
+ self.assertIn('result = await rlm.factory.run("pr-manager")', doc)
+ self.assertIn('status = await rlm.factory.status(result["run_id"])', doc)
+
+ # The worked examples bound their emitted payloads — captured answers
+ # are capped previews (~160-200 chars), so an unbounded json payload
+ # would truncate at the cap and fail to bind.
+ self.assertIn('findings": ["at most three one-line findings"]', doc)
+ self.assertIn("capped at the eight most relevant", doc)
+ self.assertIn("an unbounded payload truncates at the cap and fails to bind", flat)
+
+ # The configured inline subagent name contract.
+ self.assertIn("The optional `name` labels the spawned children", flat)
+ self.assertIn("the first instance is named exactly `name`", flat)
+ self.assertIn("unique across the machine's states", flat)
+ self.assertIn("a name another state's name can suffix onto, `foo` vs `foo-i1`, is rejected at write time", flat)
+
+ def test_help_advertises_only_calls_the_namespace_has(self) -> None:
+ # The guide and the namespace MUST agree exactly: every dotted
+ # `rlm.factory.<call>(...)` example the guide teaches must exist as
+ # an attribute on the namespace, or an agent following the returned
+ # reference hits an AttributeError (Macroscope review finding: the
+ # guide advertised watch()/graph() that the namespace did not carry;
+ # they arrive with the stacked live-view PR).
+ doc = rlm_module.rlm.factory.help()
+ flat = " ".join(doc.split())
+ advertised = sorted(set(re.findall(r"rlm\.factory\.(\w+)\(", doc)))
+ namespace = rlm_module.rlm.factory
+ 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"):
+ self.assertIn(name, advertised)
+ for name in ("run", "status", "stop", "resume", "help"):
+ 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)
+
+
+# ---------------------------------------------------------------------------
+# The opt-in settings seam: `factory.enabled` in the agent-dir settings file
+# ---------------------------------------------------------------------------
+
+
+class FactorySettingReadTest(unittest.TestCase):
+ """The settings seam behind the opt-in gate.
+
+ The gate resolves the agent dir the way the rest of the runtime does and
+ reads the same nested-camelCase settings document the daemon and TUI
+ settings surface write. The read is lenient like the Rust loader
+ (wrong-typed values read as unset) and fail-closed (a missing or corrupt
+ document leaves the factory disabled, never a crash).
+ """
+
+ def setUp(self) -> None:
+ temp = TemporaryDirectory()
+ self.addCleanup(temp.cleanup)
+ self.settings_path = Path(temp.name) / "settings.json"
+ previous = os.environ.get("PRIME_AGENT_CODING_AGENT_DIR")
+ os.environ["PRIME_AGENT_CODING_AGENT_DIR"] = str(Path(temp.name))
+
+ def restore() -> None:
+ if previous is None:
+ os.environ.pop("PRIME_AGENT_CODING_AGENT_DIR", None)
+ else:
+ os.environ["PRIME_AGENT_CODING_AGENT_DIR"] = previous
+
+ self.addCleanup(restore)
+
+ def write_settings(self, document: Any) -> None:
+ self.settings_path.write_text(json.dumps(document), encoding="utf-8")
+
+ def test_round_trips_the_real_settings_document_shape(self) -> None:
+ # A settings file as the daemon writes it: flat camelCase keys and
+ # nested feature objects (agentTraces/telemetry/terminal); the
+ # factory key is shaped exactly like the other feature toggles.
+ # /factory on writes enabled true over the same document...
+ document = {
+ "defaultProvider": "prime-inference",
+ "defaultModel": "internal/glm-5.3-fast",
+ "rlmMaxDepth": 2,
+ "theme": "dark",
+ "agentTraces": {"enabled": False},
+ "telemetry": {"enabled": None, "noticeShown": True},
+ "terminal": {"showImages": True},
+ "factory": {"enabled": True},
+ }
+ self.write_settings(document)
+ self.assertTrue(factory_module.factory_enabled())
+ # ...and /factory off writes enabled false, leaving the rest intact.
+ document["factory"] = {"enabled": False}
+ self.write_settings(document)
+ self.assertFalse(factory_module.factory_enabled())
+
+ def test_missing_or_wrong_typed_settings_read_as_disabled(self) -> None:
+ # No settings file at all: the shipped default is off.
+ self.assertFalse(factory_module.factory_enabled())
+ # A settings document without the factory key is the same default.
+ self.write_settings({})
+ self.assertFalse(factory_module.factory_enabled())
+ # Wrong-typed values read as unset, like the lenient Rust loader.
+ for document in (
+ {"factory": None},
+ {"factory": "enabled"},
+ {"factory": {"enabled": None}},
+ {"factory": {"enabled": "true"}},
+ {"factory": {"enabled": 1}},
+ ):
+ self.write_settings(document)
+ self.assertFalse(factory_module.factory_enabled(), str(document))
+ # An enabled object with unknown sibling keys still reads enabled.
+ self.write_settings({"factory": {"enabled": True, "extra": "ignored"}})
+ self.assertTrue(factory_module.factory_enabled())
+ # A corrupt document fails closed: a clean refusal, never a crash.
+ self.settings_path.write_text("{ not json", encoding="utf-8")
+ self.assertFalse(factory_module.factory_enabled())
+
+
+# ---------------------------------------------------------------------------
+# Executor test infrastructure
+# ---------------------------------------------------------------------------
+
+
+def async_test(coroutine):
+ """Run one async test method on a fresh event loop."""
+
+ def wrapper(self):
+ return asyncio.run(coroutine(self))
+
+ wrapper.__name__ = coroutine.__name__
+ return wrapper
+
+
+async def yield_loop_turn() -> None:
+ """Yield one event-loop turn: cooperative, with no wall-clock wait."""
+ resumed = asyncio.Event()
+ asyncio.get_running_loop().call_soon(resumed.set)
+ await resumed.wait()
+
+
+class FakeClock:
+ """Injectable monotonic clock with optional per-collect advancement."""
+
+ def __init__(self, start: float = 1000.0, advance_per_collect: float = 0.0) -> None:
+ self.now = start
+ self.advance_per_collect = advance_per_collect
+
+ def __call__(self) -> float:
+ return self.now
+
+ def advance(self, seconds: float) -> None:
+ self.now += seconds
+
+
+class ClockSleep:
+ """Injectable sleep that records delays and advances the fake clock.
+
+ Real sleep passes wall-clock time, so a recorded backoff slice also moves
+ the injected clock: a control loop waiting out a backoff deadline makes
+ progress without a real wait.
+ """
+
+ def __init__(self, clock: FakeClock) -> None:
+ self.clock = clock
+ self.sleeps: list[float] = []
+
+ async def __call__(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.clock.advance(seconds)
+
+
+class GatedSleep:
+ """Injectable sleep that suspends every call until released."""
+
+ def __init__(self) -> None:
+ self.sleeps: list[float] = []
+ self.entered = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def __call__(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.entered.set()
+ await self.release.wait()
+
+
+def _node_of_name(name: str) -> str:
+ """The factory node a spawn name belongs to.
+
+ Generated labels are "sw-<node id>-<run>-..."; a state with a
+ configured inline subagent name spawns children named by it verbatim,
+ so such a name keys the node by the whole string.
+ """
+ parts = name.split("-")
+ return parts[1] if parts[0] == "sw" and len(parts) > 2 else name
+
+
+class FakeHost:
+ """Deterministic async host_request fake that routes by request type.
+
+ Child names carry the node id as their second dash-separated part (or
+ are a state's configured inline subagent name verbatim), so node ids
+ in these tests never contain "-". Collect outcomes are
+ scripted per child id first (``child_outcomes``), then per node id
+ (``outcomes``); a "running" outcome never settles. ``rate_limit_first``
+ / ``rate_limit_forever`` make spawn admissions for a node fail with a
+ 429-style RuntimeError. ``gate("rlm.collect"|"rlm.delete_subagent"|"rlm.run"|"factory.progress", n)``
+ suspends the n-th call of that type on an asyncio.Event so tests can
+ reproduce races between the control loop and stop()/resume().
+ ``advance_per_run`` advances the injected clock on every admission (a
+ slow spawn), and ``advance_per_collect`` on every collect poll.
+ """
+
+ def __init__(self, clock: FakeClock | None = None) -> None:
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+ self.notices: list[dict[str, Any]] = []
+ self.children: dict[str, dict[str, Any]] = {}
+ self.counter = 0
+ self.collects = 0
+ self.clock = clock
+ self.advance_per_run: float = 0.0
+ self.outcomes: dict[str, dict[str, Any]] = {}
+ self.child_outcomes: dict[str, dict[str, Any]] = {}
+ self.rate_limit_first: dict[str, int] = {}
+ self.rate_limit_forever: set[str] = set()
+ self.gates: dict[tuple[str, int], asyncio.Event] = {}
+ self.gate_entries: dict[tuple[str, int], asyncio.Event] = {}
+ self._call_indices: dict[str, int] = {}
+
+ def gate(self, request_type: str, call_number: int) -> asyncio.Event:
+ """Suspend the call_number-th call of that type on a returned event."""
+ event = asyncio.Event()
+ self.gates[(request_type, call_number)] = event
+ self.gate_entries[(request_type, call_number)] = asyncio.Event()
+ return event
+
+ def gate_entered(self, request_type: str, call_number: int) -> asyncio.Event:
+ return self.gate_entries[(request_type, call_number)]
+
+ def calls_of(self, request_type: str) -> list[dict[str, Any]]:
+ return [payload for kind, payload in self.calls if kind == request_type]
+
+ def spawn_calls(self, node_id: str) -> list[dict[str, Any]]:
+ return [p for p in self.calls_of("rlm.run") if _node_of_name(p["kwargs"]["name"]) == node_id]
+
+ def deleted_targets(self) -> list[str]:
+ return [p["target"] for p in self.calls_of("rlm.delete_subagent")]
+
+ def notice_kinds(self) -> list[str]:
+ return [notice["kind"] for notice in self.notices]
+
+ @staticmethod
+ def _entry(
+ *,
+ child_id: str,
+ name: str,
+ status: str,
+ settled: bool,
+ answer: str | None = None,
+ error: str | None = None,
+ ) -> dict[str, Any]:
+ entry: dict[str, Any] = {
+ "rlm_child_id": child_id,
+ "session_name": name,
+ "session_dir": f"/tmp/{child_id}",
+ "status": status,
+ "settled": settled,
+ "tool_use_count": 1,
+ "duration_ms": 5,
+ }
+ if answer is not None:
+ entry["answer_preview"] = answer
+ if error is not None:
+ entry["error"] = error
+ return entry
+
+ async def __call__(self, request_type: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
+ payload = payload or {}
+ gate = None
+ if request_type in ("rlm.collect", "rlm.delete_subagent", "rlm.run", "factory.progress"):
+ index = self._call_indices.get(request_type, 0) + 1
+ self._call_indices[request_type] = index
+ gate = self.gates.pop((request_type, index), None)
+ if gate is not None:
+ entry_event = self.gate_entries.pop((request_type, index), None)
+ if entry_event is not None:
+ entry_event.set()
+ if gate is not None:
+ await gate.wait()
+ if request_type == "rlm.run":
+ # Count this node's prior admission calls before recording the
+ # current one, so rate_limit_first<n> fails exactly the first n.
+ name = payload["kwargs"]["name"]
+ node_id = _node_of_name(name)
+ attempted = len(
+ [
+ p
+ for kind, p in self.calls
+ if kind == "rlm.run" and _node_of_name(p["kwargs"]["name"]) == node_id
+ ]
+ )
+ self.calls.append((request_type, payload))
+ if self.clock is not None:
+ self.clock.advance(self.advance_per_run)
+ limit = self.rate_limit_first.get(node_id, 0) + (999 if node_id in self.rate_limit_forever else 0)
+ if attempted < limit:
+ raise RuntimeError("429 rate limit exceeded")
+ self.counter += 1
+ child_id = f"child-{self.counter}"
+ self.children[child_id] = {"name": name, "node": node_id}
+ return {
+ "rlm_child_id": child_id,
+ "name": name,
+ "session_dir": f"/tmp/{child_id}",
+ "model": "fake-model",
+ }
+ self.calls.append((request_type, payload))
+ if request_type == "rlm.collect":
+ self.collects += 1
+ if self.clock is not None:
+ self.clock.advance(self.clock.advance_per_collect)
+ results = []
+ for target in payload["targets"]:
+ child = self.children.get(target)
+ if child is None:
+ continue # deleted children vanish from collect results
+ outcome = (
+ self.child_outcomes.get(target)
+ or self.outcomes.get(child["node"])
+ or {"status": "done", "answer": f"answer-{child['node']}"}
+ )
+ if outcome["status"] == "running":
+ results.append(
+ self._entry(child_id=target, name=child["name"], status="running", settled=False)
+ )
+ continue
+ results.append(
+ self._entry(
+ child_id=target,
+ name=child["name"],
+ status=outcome["status"],
+ settled=True,
+ answer=outcome.get("answer"),
+ error=outcome.get("error"),
+ )
+ )
+ return {"results": results}
+ if request_type == "rlm.delete_subagent":
+ target = payload["target"]
+ child = self.children.pop(target, None)
+ return {
+ "subagent": {
+ "rlm_child_id": target,
+ "session_name": child["name"] if child else "unknown",
+ "session_dir": f"/tmp/{target}",
+ "status": "running",
+ },
+ "outcome": "deleted",
+ }
+ if request_type == "factory.progress":
+ self.notices.append(payload)
+ return {}
+ raise AssertionError(f"unexpected host request type {request_type!r}")
+
+
+class DeleteFailsHost(FakeHost):
+ """FakeHost whose rlm.delete_subagent always raises."""
+
+ async def __call__(self, request_type: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
+ if request_type == "rlm.delete_subagent":
+ self.calls.append((request_type, payload or {}))
+ raise RuntimeError("delete_subagent: child already gone")
+ return await super().__call__(request_type, payload)
+
+
+class DeadNoticeHost(FakeHost):
+ """FakeHost whose factory.progress bridge is dead (every call raises)."""
+
+ async def __call__(self, request_type: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
+ if request_type == "factory.progress":
+ self.calls.append((request_type, payload or {}))
+ raise RuntimeError("bridge dead")
+ return await super().__call__(request_type, payload)
+
+
+# ---------------------------------------------------------------------------
+# Executor tests
+# ---------------------------------------------------------------------------
+
+
+class _ExecutorTestCase(unittest.TestCase):
+ """The scripted in-memory kernel every executor test runs against.
+
+ A temp-dir harness with a real subagent entry, an injected clock and
+ sleeps, a ``FakeHost`` behind the ``host_request`` patch seam, and the
+ per-test default executor. The factory opt-in gate reads the
+ ``factory.enabled`` setting from the agent dir's settings file, so the
+ agent dir points at a temp dir whose settings file the tests write in
+ the real document shape the daemon writes (``{"factory": {"enabled":
+ true}}``); every executor test then runs through the live gate with the
+ setting on, and the opt-in gate tests flip the file per case.
+ """
+
+ def setUp(self) -> None:
+ temp = TemporaryDirectory()
+ self.addCleanup(temp.cleanup)
+ self.harness = HarnessState(Path(temp.name) / "harness_state.json")
+ self.harness.create_subagent("Worker", "Do the work carefully.", id="worker")
+ self.clock = FakeClock()
+ self.host = FakeHost(clock=self.clock)
+ self.sleeps = ClockSleep(self.clock)
+ self.executor = FactoryExecutor(now=self.clock, sleep=self.sleeps, harness=self.harness)
+ previous_executor = factory_module._DEFAULT_EXECUTOR
+ factory_module._DEFAULT_EXECUTOR = self.executor
+ self.addCleanup(lambda: setattr(factory_module, "_DEFAULT_EXECUTOR", previous_executor))
+ # The fake is an async callable: patch it in directly (AsyncMock does
+ # not await async side effects), which preserves the patch seam.
+ patcher = patch.object(rlm_module, "host_request", self.host)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ agent_temp = TemporaryDirectory()
+ self.addCleanup(agent_temp.cleanup)
+ self.settings_path = Path(agent_temp.name) / "settings.json"
+ self.write_settings({"factory": {"enabled": True}})
+ self._isolate_agent_dir(agent_temp.name)
+
+ def write_settings(self, document: Any) -> None:
+ """Write the agent-dir settings document (the real file shape)."""
+ self.settings_path.write_text(json.dumps(document), encoding="utf-8")
+
+ def _isolate_agent_dir(self, agent_dir: str) -> None:
+ previous = os.environ.get("PRIME_AGENT_CODING_AGENT_DIR")
+ os.environ["PRIME_AGENT_CODING_AGENT_DIR"] = agent_dir
+
+ def restore() -> None:
+ if previous is None:
+ os.environ.pop("PRIME_AGENT_CODING_AGENT_DIR", None)
+ else:
+ os.environ["PRIME_AGENT_CODING_AGENT_DIR"] = previous
+
+ self.addCleanup(restore)
+
+ def disable_factory(self) -> None:
+ """Flip the settings file to the disabled default."""
+ self.write_settings({"factory": {"enabled": False}})
+
+ # -- helpers shared with the opt-in gate tests ----------------------------
+
+ def store_factory(self, dag: dict[str, Any], spec_id: str = "sw") -> None:
+ self.harness.create_factory("Factory", "Factory content", id=spec_id, dag=dag)
+
+ def store_machine(self, machine: dict[str, Any], spec_id: str = "sw") -> None:
+ self.harness.create_factory("Factory", "Factory content", id=spec_id, machine=machine)
+
+ def node(self, node_id: str, **overrides: Any) -> dict[str, Any]:
+ base: dict[str, Any] = {"id": node_id, "subagent": "worker"}
+ base.update(overrides)
+ return base
+
+ async def start(self, spec_id: str = "sw") -> dict[str, Any]:
+ return await rlm_module.rlm.factory.run(spec_id)
+
+
+class FactoryOptInGateTest(_ExecutorTestCase):
+ """The opt-in gate: `factory.enabled` (default off) closes the namespace.
+
+ The factory ships disabled; the user turns it on with /factory on (the
+ persisted `factory.enabled` setting in the agent dir's settings.json).
+ While it is off, every rlm.factory call except help() and every factory
+ harness write refuses with ONE exact message, and nothing starts or
+ persists behind the refusal.
+ """
+
+ # -- namespace gate --------------------------------------------------------
+
+ @async_test
+ async def test_run_proceeds_when_the_enabled_setting_is_written(self) -> None:
+ self.store_factory({"nodes": [self.node("a")]}, spec_id="sw")
+ result = await self.start()
+ self.assertIn("run_id", result)
+ self.assertEqual(result["started"], ["a"])
+ self.assertTrue(self.host.calls)
+
+ @async_test
+ async def test_empty_settings_refuse_run_with_the_exact_message(self) -> None:
+ self.store_factory({"nodes": [self.node("a")]}, spec_id="sw")
+ # An empty settings document: the factory key absent reads as the
+ # disabled default, and the refusal precedes any spec resolution.
+ self.write_settings({})
+ with self.assertRaises(ValueError) as raised:
+ await self.start()
+ self.assertEqual(str(raised.exception), "the factory is disabled; run /factory on to enable it")
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ self.assertEqual(self.host.calls, [])
+ # No settings file at all is the same disabled default.
+ self.settings_path.unlink()
+ with self.assertRaises(ValueError) as raised:
+ await self.start()
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ self.assertEqual(self.host.calls, [])
+
+ @async_test
+ async def test_status_stop_and_resume_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.status(run_id),
+ rlm_module.rlm.factory.stop(run_id),
+ rlm_module.rlm.factory.resume(run_id),
+ ):
+ with self.assertRaises(ValueError) as raised:
+ await call
+ 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()
+ self.assertEqual(doc, factory_module.FACTORY_HELP)
+ self.assertIn("The factory is opt-in", doc)
+
+ # -- harness write gate ----------------------------------------------------
+
+ def test_create_factory_refuses_while_disabled(self) -> None:
+ self.disable_factory()
+ with self.assertRaises(ValueError) as raised:
+ self.harness.create_factory("Factory", "Never stores.", id="sw", dag={"nodes": [self.node("a")]})
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ self.assertEqual(self.harness.list("factory"), [])
+ # The refusal precedes spec validation: an invalid spec never gets
+ # the spec error while the factory is off, only the one message.
+ with self.assertRaises(ValueError) as raised:
+ self.harness.create_factory("Broken", "Never stores.", id="bad", dag={"nodes": []})
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ self.assertEqual(self.harness.list("factory"), [])
+ # The generic create path refuses identically.
+ with self.assertRaises(ValueError) as raised:
+ self.harness.create(
+ "factory",
+ "Generic",
+ "content",
+ id="generic",
+ arguments={"dag": {"nodes": [self.node("a")]}},
+ )
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ self.assertEqual(self.harness.list("factory"), [])
+
+ def test_factory_entry_updates_refuse_while_disabled(self) -> None:
+ self.store_factory({"nodes": [self.node("a")]}, spec_id="sw")
+ self.disable_factory()
+ with self.assertRaises(ValueError) as raised:
+ self.harness.update_factory("sw", "Factory", "content updated")
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ with self.assertRaises(ValueError) as raised:
+ self.harness.update("factory", "sw", "Factory", "content updated")
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ with self.assertRaises(ValueError) as raised:
+ self.harness.upsert(
+ "factory",
+ "Factory",
+ "content",
+ id="upserted",
+ arguments={"dag": {"nodes": [self.node("a")]}},
+ )
+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)
+ # The stored entry is untouched behind the refusals.
+ self.assertEqual(self.harness.get("factory", "sw").content, "Factory content")
+ self.assertEqual(self.harness.list("factory"), [self.harness.get("factory", "sw")])
+
+ def test_delete_stays_available_while_disabled(self) -> None:
+ # Deleting is cleanup, not authoring or execution: the gate list is
+ # run/status/stop/resume (and the later graph/watch) plus creates and
+ # updates, so an operator can still clear stale entries while off.
+ self.store_factory({"nodes": [self.node("a")]}, spec_id="sw")
+ self.disable_factory()
+ self.assertTrue(self.harness.delete_factory("sw"))
+ self.assertIsNone(self.harness.get("factory", "sw"))
+
+
+class FactoryExecutorTest(_ExecutorTestCase):
+
+ # -- helpers -------------------------------------------------------------
+
+ def corrupt_stored_spec(self, spec_id: str, spec: Any, *, key: str = "dag") -> None:
+ """Bypass write-time validation the way a hand-edited or foreign
+ store would: mutate the stored entry's spec in memory."""
+ entry = self.harness.get("factory", spec_id)
+ entry.arguments = {key: spec}
+
+ def state_report(self, status: dict[str, Any], state_id: str) -> dict[str, Any]:
+ return next(entry for entry in status["nodes"] if entry["id"] == state_id)
+
+ def events_of(self, status: dict[str, Any], kind: str) -> list[dict[str, Any]]:
+ return [event for event in status["events"] if event["kind"] == kind]
+
+ def all_events_of(self, run_result: dict[str, Any], kind: str) -> list[dict[str, Any]]:
+ run = self.executor._runs[run_result["run_id"]]
+ return [event for event in run.events if event["kind"] == kind]
+
+ async def settle(self, run_result: dict[str, Any], *, max_polls: int = 50_000) -> dict[str, Any]:
+ """Yield to the control loop until the run leaves the running state."""
+ 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")
+
+ async def wait_until(self, predicate, *, max_polls: int = 50_000) -> None:
+ for _ in range(max_polls):
+ if predicate():
+ return
+ await yield_loop_turn()
+ self.fail("condition never became true")
+
+ def node_status(self, status: dict[str, Any], node_id: str) -> dict[str, Any]:
+ return next(entry for entry in status["nodes"] if entry["id"] == node_id)
+
+ # -- dry run ---------------------------------------------------------------
+
+ @async_test
+ async def test_run_rejects_invalid_dag_and_starts_nothing(self) -> None:
+ # Write-time validation blocks create_factory, so corrupt the stored
+ # spec in memory (a hand-edited or foreign store) to prove run()
+ # re-validates on its own and starts nothing on any failure.
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]}, spec_id="empty")
+ self.corrupt_stored_spec("empty", {"nodes": []})
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]}, spec_id="cyclic")
+ self.corrupt_stored_spec(
+ "cyclic",
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker", "depends_on": ["b"]},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ]
+ },
+ )
+ for spec_id in ("empty", "cyclic"):
+ with self.assertRaisesRegex(ValueError, "factory"):
+ await self.start(spec_id)
+ self.assertEqual(self.host.calls, [])
+
+ @async_test
+ async def test_run_lists_all_missing_subagent_references(self) -> None:
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "ghost-a"},
+ {"id": "b", "subagent": "ghost-b"},
+ ],
+ }
+ )
+ with self.assertRaises(ValueError) as ctx:
+ await self.start()
+ self.assertIn("ghost-a", str(ctx.exception))
+ self.assertIn("ghost-b", str(ctx.exception))
+ self.assertEqual(self.host.calls, [])
+
+ @async_test
+ async def test_run_rejects_unknown_spec(self) -> None:
+ with self.assertRaisesRegex(ValueError, "unknown factory spec"):
+ await self.start("missing-spec")
+
+ @async_test
+ async def test_resolves_subagent_by_id_and_title_with_model_settings(self) -> None:
+ self.harness.create_subagent(
+ "The Worker",
+ "Template by title.",
+ id="worker-md",
+ metadata={"model": "pi/test-model", "thinking": "low"},
+ )
+ self.store_factory(
+ {
+ "run": {"max_parallel": 2},
+ "nodes": [
+ {"id": "x", "subagent": "The Worker"},
+ {"id": "y", "subagent": "worker-md"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ for node_id in ("x", "y"):
+ spawn = self.host.spawn_calls(node_id)
+ self.assertEqual(len(spawn), 1, node_id)
+ self.assertEqual(spawn[0]["prompt"], "Template by title.")
+ self.assertEqual(spawn[0]["kwargs"]["model"], "pi/test-model")
+ self.assertEqual(spawn[0]["kwargs"]["thinking"], "low")
+
+ @async_test
+ async def test_inline_subagent_name_labels_the_spawned_child(self) -> None:
+ # Macroscope review finding: the inline subagent name was dropped by
+ # _resolve_subagents, so the child spawned with the generated label
+ # instead of the configured name agents message the child by. The
+ # name rides through run creation to the spawn call, and the spawned
+ # event's ledger entry carries the same label.
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": {"prompt": "Do the review.", "name": "reviewer"}},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(
+ [p["kwargs"]["name"] for p in self.host.calls_of("rlm.run")],
+ ["reviewer"],
+ )
+ self.assertEqual(
+ [event["name"] for event in self.all_events_of(result, "spawned")],
+ ["reviewer"],
+ )
+
+ @async_test
+ async def test_inline_subagent_name_disambiguates_reentry_and_foreach(self) -> None:
+ # One state's settled children stay registered for the run's life,
+ # and the supervisor rejects duplicate sibling names, so re-entry
+ # (max_entries > 1) and foreach fan-out keep the configured prefix
+ # with the same -i<n> suffix the generated labels use.
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {
+ "id": "loop",
+ "entry": True,
+ "subagent": {"prompt": "Work.", "name": "worker"},
+ "max_entries": 2,
+ },
+ ],
+ "transitions": [{"from": "loop", "to": "loop"}],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(
+ [p["kwargs"]["name"] for p in self.host.calls_of("rlm.run")],
+ ["worker", "worker-i1"],
+ )
+
+ self.host.outcomes["src"] = {
+ "status": "done",
+ "answer": 'Here.\n```json\n{"items": ["one", "two"]}\n```',
+ }
+ self.host.calls.clear()
+ self.host.children.clear()
+ self.host.counter = 0
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 8},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": {"prompt": "Expand item {items}.", "name": "expander"},
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 4},
+ },
+ ],
+ },
+ spec_id="fan",
+ )
+ result = await self.start("fan")
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ # The first foreach instance keeps the configured name; the second
+ # disambiguates with the instance suffix.
+ self.assertEqual(
+ [
+ p["kwargs"]["name"]
+ for p in self.host.calls_of("rlm.run")
+ if p["kwargs"]["name"].startswith("expander")
+ ],
+ ["expander", "expander-i1"],
+ )
+
+ @async_test
+ async def test_run_starts_ready_nodes_and_reports_counts(self) -> None:
+ self.store_factory(
+ {
+ "run": {"max_parallel": 2},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ {"id": "c", "subagent": "worker", "depends_on": ["b"]},
+ {"id": "d", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ self.assertIn("run_id", result)
+ self.assertEqual(result["spec_id"], "sw")
+ self.assertEqual(result["nodes"], 4)
+ self.assertEqual(result["max_parallel"], 2)
+ self.assertEqual(result["started"], ["a", "d"])
+ self.assertEqual(result["pending"], ["b", "c"])
+ self.assertEqual(len(self.host.calls_of("rlm.run")), 2)
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertTrue(all(entry["status"] == "done" for entry in status["nodes"]))
+ self.assertEqual(self.host.notice_kinds(), ["finished"])
+ self.assertEqual(status["usage"]["spawns"], 4)
+ self.assertEqual(status["usage"]["settled"], 4)
+
+ # -- propagation and binding ------------------------------------------------
+
+ @async_test
+ async def test_propagation_binds_answer_into_prompt(self) -> None:
+ self.host.outcomes["a"] = {"status": "done", "answer": "ANSWER-A"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "outputs": [{"name": "out", "type": "text"}]},
+ {
+ "id": "b",
+ "subagent": {"prompt": "Summarize: {draft}"},
+ "depends_on": ["a"],
+ "inputs": [{"name": "draft", "type": "text", "from": "a.out"}],
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["a"])
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ prompts = [call["prompt"] for call in self.host.spawn_calls("b")]
+ self.assertEqual(prompts, ["Summarize: ANSWER-A"])
+ self.assertEqual(self.node_status(status, "b")["answer_preview"], "answer-b")
+
+ @async_test
+ async def test_json_input_prefers_fenced_block(self) -> None:
+ self.host.outcomes["a"] = {
+ "status": "done",
+ "answer": 'Verdict text.\n```json\n{"result": {"x": 1}}\n```',
+ }
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "outputs": [{"name": "result", "type": "json"}]},
+ {
+ "id": "b",
+ "subagent": {"prompt": "Process {data}."},
+ "depends_on": ["a"],
+ "inputs": [{"name": "data", "type": "json", "from": "a.result"}],
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ prompts = [call["prompt"] for call in self.host.spawn_calls("b")]
+ self.assertEqual(prompts, ['Process {"x": 1}.'])
+
+ @async_test
+ async def test_json_input_falls_back_to_whole_text(self) -> None:
+ self.host.outcomes["a"] = {"status": "done", "answer": '{"result": 7}'}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "outputs": [{"name": "result", "type": "json"}]},
+ {
+ "id": "b",
+ "subagent": {"prompt": "Process {data}."},
+ "depends_on": ["a"],
+ "inputs": [{"name": "data", "type": "json", "from": "a.result"}],
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual([call["prompt"] for call in self.host.spawn_calls("b")], ["Process 7."])
+
+ @async_test
+ async def test_bad_json_input_fails_node_without_spawning(self) -> None:
+ self.host.outcomes["a"] = {"status": "done", "answer": "not json at all"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "outputs": [{"name": "result", "type": "json"}]},
+ {
+ "id": "b",
+ "subagent": {"prompt": "Process {data}."},
+ "depends_on": ["a"],
+ "inputs": [{"name": "data", "type": "json", "from": "a.result"}],
+ },
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ # b failed at binding (continue policy): never spawned, marked error;
+ # c still ran and finished, so the run completes but reports failed.
+ self.assertEqual(self.host.spawn_calls("b"), [])
+ b = self.node_status(status, "b")
+ self.assertEqual(b["status"], "error")
+ self.assertIn("no JSON object containing output", b["error"])
+ self.assertEqual(self.node_status(status, "c")["status"], "done")
+ self.assertEqual(status["state"], "failed")
+
+ @async_test
+ async def test_unplaced_inputs_are_appended(self) -> None:
+ self.host.outcomes["a"] = {"status": "done", "answer": "ANSWER-A"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "outputs": [{"name": "out", "type": "text"}]},
+ {
+ "id": "b",
+ "subagent": {"prompt": "No placeholders here."},
+ "depends_on": ["a"],
+ "inputs": [{"name": "draft", "type": "text", "from": "a.out"}],
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(
+ [call["prompt"] for call in self.host.spawn_calls("b")],
+ ["No placeholders here.\n\n## Inputs\n- draft: ANSWER-A\n"],
+ )
+
+ @async_test
+ async def test_two_parent_fan_in_binds_both_answers(self) -> None:
+ # Both parents settle in one collect batch; the join must fire ONCE
+ # (not once per source settle) and bind both captured answers into a
+ # single prompt.
+ self.host.outcomes["a"] = {"status": "done", "answer": "ANSWER-A"}
+ self.host.outcomes["b"] = {"status": "done", "answer": "ANSWER-B"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "outputs": [{"name": "out", "type": "text"}]},
+ {"id": "b", "subagent": "worker", "outputs": [{"name": "out", "type": "text"}]},
+ {
+ "id": "c",
+ "subagent": {"prompt": "Combine {left} and {right}."},
+ "depends_on": ["a", "b"],
+ "inputs": [
+ {"name": "left", "type": "text", "from": "a.out"},
+ {"name": "right", "type": "text", "from": "b.out"},
+ ],
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["a", "b"])
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(
+ [call["prompt"] for call in self.host.spawn_calls("c")],
+ ["Combine ANSWER-A and ANSWER-B."],
+ )
+ # the join fired exactly once: one entry, one spawn, nothing blocked
+ self.assertEqual(self.state_report(status, "c")["entries_used"], 1)
+ self.assertEqual(len(self.host.spawn_calls("c")), 1)
+ self.assertEqual(self.all_events_of(result, "transition_blocked"), [])
+
+ @async_test
+ async def test_fan_in_waits_for_every_parent_across_batches(self) -> None:
+ # Review finding (fan-in compiled as independent transitions): a
+ # control-only parent must hold the fan-in node back too. b settles
+ # first; d must not enter (nor spawn) until c settles, and it must
+ # never run with a missing input.
+ self.host.child_outcomes["child-1"] = {"status": "done", "answer": "go"}
+ self.host.child_outcomes["child-2"] = {"status": "done", "answer": "ANSWER-B"}
+ self.host.child_outcomes["child-3"] = {"status": "running"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {
+ "id": "b",
+ "subagent": "worker",
+ "depends_on": ["a"],
+ "outputs": [{"name": "out", "type": "text"}],
+ },
+ {"id": "c", "subagent": "worker", "depends_on": ["a"]},
+ {
+ "id": "d",
+ "subagent": {"prompt": "Combine {left}."},
+ "depends_on": ["b", "c"],
+ "inputs": [{"name": "left", "type": "text", "from": "b.out"}],
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ run = self.executor._runs[result["run_id"]]
+ # b settled, c still running: d must never be entered or spawned.
+ await self.wait_until(
+ lambda: any(entry.is_settle for entry in run.states["b"].entries)
+ and len(self.host.calls_of("rlm.collect")) >= 2
+ )
+ self.assertEqual(self.host.spawn_calls("d"), [])
+ self.assertEqual(
+ [e for e in self.all_events_of(result, "state_entry") if e.get("node") == "d"], []
+ )
+ # c settles now; only then may d run.
+ self.host.child_outcomes["child-3"] = {"status": "done", "answer": "ANSWER-C"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(
+ [call["prompt"] for call in self.host.spawn_calls("d")],
+ ["Combine ANSWER-B."],
+ )
+ self.assertEqual(self.all_events_of(result, "transition_blocked"), [])
+ self.assertEqual(self.state_report(status, "d")["entries_used"], 1)
+
+ @async_test
+ async def test_answer_capture_cap_slices_previews(self) -> None:
+ long_answer = "x" * 300
+ self.host.outcomes["a"] = {"status": "done", "answer": long_answer}
+ self.store_factory(
+ {
+ "nodes": [{"id": "a", "subagent": "worker"}],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ captured = self.node_status(status, "a")["answer_preview"]
+ self.assertEqual(len(captured), ANSWER_CAPTURE_CAP)
+ self.assertEqual(captured, long_answer[:ANSWER_CAPTURE_CAP])
+
+
+ # -- foreach ----------------------------------------------------------------
+
+ def store_fan_factory(self, *, policy: str) -> None:
+ self.host.outcomes["src"] = {"status": "done", "answer": '{"items": ["a", "b", "c", "d", "e"]}'}
+ self.store_factory(
+ {
+ "run": {"failure_policy": policy, "max_parallel": 8},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": "worker",
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 5},
+ },
+ ],
+ }
+ )
+
+ @async_test
+ async def test_foreach_expands_clamped_instances(self) -> None:
+ self.host.outcomes["src"] = {
+ "status": "done",
+ "answer": 'Here.\n```json\n{"items": [1, 2, 3, 4, 5]}\n```',
+ }
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 8},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": {"prompt": "Expand item {items}."},
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 3},
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ fan = self.node_status(status, "fan")
+ self.assertEqual(fan["status"], "done")
+ # 5 items clamped to foreach.max 3; all instances settle -> node done.
+ self.assertEqual(len(fan["instances"]), 3)
+ self.assertEqual(
+ sorted(call["prompt"] for call in self.host.spawn_calls("fan")),
+ ["Expand item 1.", "Expand item 2.", "Expand item 3."],
+ )
+
+ @async_test
+ async def test_foreach_zero_items_marks_node_done(self) -> None:
+ self.host.outcomes["src"] = {"status": "done", "answer": '{"items": []}'}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": "worker",
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 4},
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.node_status(status, "fan")["status"], "done")
+ self.assertEqual(self.host.spawn_calls("fan"), [])
+
+ @async_test
+ async def test_foreach_mixed_instances_escalate_pauses(self) -> None:
+ self.store_fan_factory(policy="escalate")
+ result = await self.start()
+ # src is child-1; the five fan instances are child-2..child-6.
+ # Instances 0-1 fail permanently; 2-4 succeed in the same collect
+ # batch. The node must reach error and the policy must apply even
+ # though the failures did not settle last.
+ self.host.child_outcomes["child-2"] = {"status": "error", "error": "boom-1"}
+ self.host.child_outcomes["child-3"] = {"status": "error", "error": "boom-2"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "paused")
+ self.assertEqual(self.host.notice_kinds(), ["paused"])
+ fan = self.node_status(status, "fan")
+ self.assertEqual(fan["status"], "error")
+ self.assertEqual([i["status"] for i in fan["instances"]], ["error", "error", "done", "done", "done"])
+
+ @async_test
+ async def test_foreach_mixed_instances_fail_fast_cancels_siblings(self) -> None:
+ self.store_fan_factory(policy="fail_fast")
+ result = await self.start()
+ # instance 0 (child-2) fails first while its siblings are still in
+ # flight: fail_fast must cancel those siblings now, not after they
+ # settle.
+ self.host.child_outcomes["child-2"] = {"status": "error", "error": "boom"}
+ for child_id in ("child-3", "child-4", "child-5", "child-6"):
+ self.host.child_outcomes[child_id] = {"status": "running"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ self.assertEqual(self.host.notice_kinds(), ["failed"])
+ fan = self.node_status(status, "fan")
+ self.assertEqual(fan["status"], "error")
+ self.assertEqual(
+ [i["status"] for i in fan["instances"]],
+ ["error", "cancelled", "cancelled", "cancelled", "cancelled"],
+ )
+ self.assertEqual(len(self.host.deleted_targets()), 4)
+
+ @async_test
+ async def test_foreach_mixed_instances_continue_finishes_with_node_error(self) -> None:
+ self.store_fan_factory(policy="continue")
+ result = await self.start()
+ self.host.child_outcomes["child-2"] = {"status": "error", "error": "boom-1"}
+ self.host.child_outcomes["child-3"] = {"status": "error", "error": "boom-2"}
+ status = await self.settle(result)
+ # the node fails on the first permanent instance failure, the rest
+ # still settle, and the run finishes with the node error recorded
+ self.assertEqual(status["state"], "failed")
+ self.assertEqual(self.host.notice_kinds(), ["failed"])
+ fan = self.node_status(status, "fan")
+ self.assertEqual(fan["status"], "error")
+ self.assertEqual([i["status"] for i in fan["instances"]], ["error", "error", "done", "done", "done"])
+ self.assertEqual(self.host.deleted_targets(), [])
+
+ @async_test
+ async def test_foreach_failure_never_admits_queued_siblings_and_waits_for_running_ones(self) -> None:
+ # Review findings (two): (1) a terminal entry's queued instances are
+ # never admitted (_next_pending_instance serves running entries
+ # only), and (2) quiescence counts the INSTANCE layer, so a failed
+ # foreach entry's still-running siblings are collected before the
+ # run ends -- finalizing earlier would orphan them under the
+ # supervisor with no collector.
+ self.host.outcomes["src"] = {"status": "done", "answer": '{"items": ["a", "b", "c", "d", "e"]}'}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 2},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": "worker",
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 5},
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ run = self.executor._runs[result["run_id"]]
+ # src is child-1; max_parallel 2 admits fan instances child-2 and
+ # child-3 first (child-2 fails permanently, child-3 stays running),
+ # leaving three instances queued behind the cap.
+ self.host.child_outcomes["child-2"] = {"status": "error", "error": "boom"}
+ self.host.child_outcomes["child-3"] = {"status": "running"}
+ await self.wait_until(
+ lambda: any(entry.status == "error" for entry in run.states["fan"].entries)
+ )
+ # The entry is terminal error with a running sibling: the run is NOT
+ # complete yet, and nothing new may be admitted.
+ self.assertEqual(run.state, "running")
+ self.assertEqual(len(self.host.spawn_calls("fan")), 2)
+ # The running sibling settles now; the run ends only after applying
+ # its result, and the queued instances were cancelled, never run.
+ self.host.child_outcomes["child-3"] = {"status": "done", "answer": "ok"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ fan = self.node_status(status, "fan")
+ self.assertEqual(fan["status"], "error")
+ self.assertEqual(
+ [i["status"] for i in fan["instances"]],
+ ["error", "done", "cancelled", "cancelled", "cancelled"],
+ )
+ self.assertEqual(len(self.host.spawn_calls("fan")), 2)
+ self.assertEqual(self.host.deleted_targets(), [])
+ # the never-admitted siblings carry their own cancelled ledger events
+ cancelled = [e for e in self.all_events_of(result, "cancelled") if e.get("node") == "fan"]
+ self.assertEqual(len(cancelled), 3)
+ self.assertTrue(all(e.get("detail") == "entry failed before admission" for e in cancelled))
+
+ @async_test
+ async def test_foreach_sibling_failure_after_terminal_entry_settles_without_retry(self) -> None:
+ # Review finding (Cursor Bugbot): a foreach sibling failing with
+ # retries left AFTER its entry is already terminal was reset to
+ # pending -- _next_pending_instance serves running entries only, so
+ # the instance was never re-admitted, while _run_complete and the
+ # stall detector both counted it as in-flight: the control loop
+ # never finished the run. A terminal entry cannot re-admit a
+ # retry, so the sibling settles error instead.
+ self.host.outcomes["src"] = {"status": "done", "answer": '{"items": ["a", "b"]}'}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 8},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": "worker",
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 2},
+ "retries": 1,
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ run = self.executor._runs[result["run_id"]]
+ # src is child-1; fan instances are child-2 (i0) and child-3 (i1).
+ # i0 fails (attempt 1 <= retries 1 -> retry), is re-admitted as
+ # child-4, and fails again (attempt 2 > retries 1 -> the entry is
+ # terminal error while i1 is still running).
+ self.host.child_outcomes["child-2"] = {"status": "error", "error": "boom-1"}
+ self.host.child_outcomes["child-4"] = {"status": "error", "error": "boom-2"}
+ self.host.child_outcomes["child-3"] = {"status": "running"}
+ await self.wait_until(
+ lambda: any(entry.status == "error" for entry in run.states["fan"].entries)
+ )
+ self.assertEqual(len(self.host.spawn_calls("fan")), 3)
+ # i1 fails now with retries remaining, but the entry is terminal:
+ # no retry is queued, the run finishes instead of hanging.
+ self.host.child_outcomes["child-3"] = {"status": "error", "error": "boom-3"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ fan = self.node_status(status, "fan")
+ self.assertEqual(fan["status"], "error")
+ self.assertEqual([i["status"] for i in fan["instances"]], ["error", "error"])
+ self.assertEqual([i["attempt"] for i in fan["instances"]], [2, 1])
+ # only i0's failure was ever retried; i1 settled without a re-spawn
+ self.assertEqual(len(self.host.spawn_calls("fan")), 3)
+ retries = [e for e in self.all_events_of(result, "retry") if e.get("node") == "fan"]
+ self.assertEqual([e["instance"] for e in retries], [0])
+
+ # -- failure policies ---------------------------------------------------------
+
+ @async_test
+ async def test_fail_fast_cancels_running_children(self) -> None:
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.host.outcomes["b"] = {"status": "running"}
+ self.host.outcomes["c"] = {"status": "running"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 8},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "failure_policy": "fail_fast"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ self.assertEqual(self.node_status(status, "a")["status"], "error")
+ self.assertEqual(self.node_status(status, "b")["status"], "cancelled")
+ self.assertEqual(self.node_status(status, "c")["status"], "cancelled")
+ # delete_subagent cascaded to both running children
+ self.assertEqual(len(self.host.deleted_targets()), 2)
+ self.assertEqual(self.host.notice_kinds(), ["failed"])
+
+ @async_test
+ async def test_continue_policy_finishes_remaining_nodes(self) -> None:
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ # a failed; b (depends_on a, no data edge) still ran and finished; c ran.
+ self.assertEqual(self.node_status(status, "a")["status"], "error")
+ self.assertEqual(self.node_status(status, "b")["status"], "done")
+ self.assertEqual(self.node_status(status, "c")["status"], "done")
+ self.assertEqual(self.host.deleted_targets(), [])
+ self.assertEqual(status["state"], "failed")
+ self.assertEqual(self.host.notice_kinds(), ["failed"])
+
+ @async_test
+ async def test_escalate_pauses_notifies_and_resume_continues(self) -> None:
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ self.assertEqual(self.node_status(paused, "a")["status"], "error")
+ self.assertEqual(self.node_status(paused, "b")["status"], "pending")
+ self.assertEqual(self.host.spawn_calls("b"), [])
+ self.assertIn("paused", self.host.notice_kinds())
+ # resume() restarts the run: b is ready (a is terminal) and finishes.
+ resumed = await rlm_module.rlm.factory.resume(result["run_id"])
+ self.assertEqual(resumed["state"], "running")
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "failed") # a errored, b done
+ self.assertEqual(self.node_status(final, "b")["status"], "done")
+ self.assertEqual(self.host.notice_kinds(), ["paused", "failed"])
+ # a second resume on the finished run must refuse
+ with self.assertRaisesRegex(ValueError, "not paused"):
+ await rlm_module.rlm.factory.resume(result["run_id"])
+
+ @async_test
+ async def test_resume_defers_rate_limited_admissions(self) -> None:
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.host.rate_limit_first["b"] = 2
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ sleep_mark = len(self.sleeps.sleeps)
+ resumed = await rlm_module.rlm.factory.resume(result["run_id"])
+ # resume() must not sleep in the calling turn: the rate-limited
+ # admission defers to the control loop's backoff, exactly like run()
+ self.assertEqual(resumed["started"], [])
+ self.assertEqual(self.sleeps.sleeps[sleep_mark:], [])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "failed") # a errored, b done
+ self.assertEqual(self.node_status(final, "b")["status"], "done")
+ # b needed 3 admissions total: one deferred at resume, then one
+ # rate-limited retry inside the loop's backoff, then the success.
+ self.assertEqual(len(self.host.spawn_calls("b")), 3)
+ self.assertEqual(self.sleeps.sleeps[sleep_mark:], [1.0])
+
+ @async_test
+ async def test_repeated_pause_records_every_milestone_in_the_ledger(self) -> None:
+ # A run that pauses, resumes, and pauses again must record the second
+ # pause in the ledger even though the parent notice fires once per
+ # kind: status() is the only reader of the repeat.
+ self.host.outcomes["a"] = {"status": "error", "error": "a boom"}
+ self.host.outcomes["b"] = {"status": "error", "error": "b boom"}
+ self.store_machine(
+ {
+ "run": {"failure_policy": "escalate"},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ )
+ result = await self.start()
+ first = await self.settle(result)
+ self.assertEqual(first["state"], "paused")
+ self.assertEqual(len(self.events_of(first, "milestone")), 1) # one pause so far
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ second = await self.settle(result)
+ self.assertEqual(second["state"], "paused")
+ self.assertEqual(self.executor._runs[result["run_id"]].pause_reason, "b boom")
+ # the second pause is in the ledger with its own event, notice-free
+ milestones = [event for event in second["events"] if event["kind"] == "milestone"]
+ self.assertEqual([event["milestone"] for event in milestones], ["paused", "paused"])
+ self.assertIn("a boom", milestones[0]["detail"])
+ self.assertIn("b boom", milestones[1]["detail"])
+ self.assertEqual(self.host.notice_kinds(), ["paused"]) # one notice per kind
+ # the announced pause keeps "shown"; the repeat (no second notice)
+ # was only ever read through status(), so it reads "delivered"
+ self.assertEqual(milestones[0]["stage"], "shown")
+ self.assertEqual(milestones[1]["stage"], "delivered")
+
+ # -- retries --------------------------------------------------------------------
+
+ @async_test
+ async def test_retries_respawn_until_attempts_exhausted(self) -> None:
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [{"id": "a", "subagent": "worker", "retries": 2}],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ # retries=2 -> 3 admissions total, then the policy applies
+ self.assertEqual(len(self.host.spawn_calls("a")), 3)
+ self.assertEqual(self.node_status(status, "a")["attempts"], 3)
+ self.assertEqual(self.node_status(status, "a")["status"], "error")
+ self.assertEqual(status["state"], "failed")
+
+ # -- budgets ----------------------------------------------------------------------
+
+ @async_test
+ async def test_node_budget_marks_attempt_failed(self) -> None:
+ # The fake clock advances 2s per collect, so the node's 1000ms budget
+ # (admission to settlement) is exceeded when the child settles.
+ self.clock.advance_per_collect = 2.0
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker", "budget_ms": 1000},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ a = self.node_status(status, "a")
+ self.assertEqual(a["status"], "error")
+ self.assertIn("budget", a["error"])
+ # budget failures do not retry: exactly one admission for a
+ self.assertEqual(len(self.host.spawn_calls("a")), 1)
+ # b (depends_on a, no data edge) still ran and finished
+ self.assertEqual(self.node_status(status, "b")["status"], "done")
+ self.assertEqual(status["state"], "failed")
+
+ @async_test
+ async def test_run_budget_pauses_and_notifies_then_resume_completes(self) -> None:
+ self.clock.advance_per_collect = 2.0
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "budget_ms": 1500},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ self.assertIn("budget_exceeded", self.host.notice_kinds())
+ self.assertEqual(self.host.spawn_calls("b"), [])
+ # the pause reports the overshoot accounting: elapsed time past the
+ # budget, and that only new spawns stop.
+ milestone = next(
+ event for event in self.events_of(paused, "milestone") if event["milestone"] == "budget_exceeded"
+ )
+ self.assertIn("no new spawns", milestone["detail"])
+ self.assertIn("2000ms", milestone["detail"])
+ self.assertEqual(self.executor._runs[result["run_id"]].pause_reason, "run budget exceeded")
+ # resume continues despite the spent budget (reported once per run)
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(self.node_status(final, "b")["status"], "done")
+ self.assertEqual(self.host.notice_kinds(), ["budget_exceeded", "finished"])
+
+ @async_test
+ async def test_admission_phase_stops_at_the_run_budget_boundary(self) -> None:
+ # Review finding: the run budget must be enforced before EACH
+ # admission, including run()'s own admission phase -- a slow spawn
+ # must not fill max_parallel with instances launched after the
+ # budget expired.
+ self.host.advance_per_run = 2.0 # every admission costs two seconds
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "budget_ms": 3000, "max_parallel": 8},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ # Admissions at t=1000 and t=1002 pass the budget check; the third
+ # would launch at t=1004 (4000ms elapsed > 3000ms budget), so the
+ # run pauses BEFORE admitting it.
+ self.assertEqual(result["started"], ["a", "b"])
+ self.assertEqual(len(self.host.calls_of("rlm.run")), 2)
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "paused")
+ self.assertIn("budget_exceeded", self.host.notice_kinds())
+ # c was prepared but never admitted: its entry reports running, its
+ # instance is still pending, and no spawn call was made for it.
+ c_report = self.node_status(status, "c")
+ self.assertEqual(c_report["status"], "running")
+ self.assertEqual(c_report["instances"][0]["status"], "pending")
+ self.assertEqual(self.host.spawn_calls("c"), [])
+ # resume is the explicit operator decision: c runs, no second pause
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(self.node_status(final, "c")["status"], "done")
+ self.assertEqual(self.host.notice_kinds(), ["budget_exceeded", "finished"])
+
+ @async_test
+ async def test_run_max_children_pauses_at_admission_then_resume_completes(self) -> None:
+ # Macroscope finding: foreach.max bounds per-entry expansion,
+ # max_transitions bounds transitions, and max_parallel bounds
+ # concurrency — nothing bounded TOTAL admissions over the run's
+ # life. run.max_children is that budget: enforced before each
+ # admission (run()'s own phase included), pause once at the
+ # boundary, resume continues past it (explicit operator decision).
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_children": 2},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ # run()'s admission phase admits a and b; c's spawn is refused.
+ self.assertEqual(result["started"], ["a", "b"])
+ self.assertEqual(len(self.host.calls_of("rlm.run")), 2)
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "paused")
+ # its OWN milestone kind, distinct from the run-budget pause
+ self.assertIn("max_children_exceeded", self.host.notice_kinds())
+ self.assertNotIn("budget_exceeded", self.host.notice_kinds())
+ milestone = next(
+ event for event in self.events_of(status, "milestone") if event["milestone"] == "max_children_exceeded"
+ )
+ self.assertIn("run max_children 2 exceeded after 2 children", milestone["detail"])
+ self.assertIn("no new spawns", milestone["detail"])
+ self.assertIn("resume with await rlm.factory.resume", milestone["detail"])
+ self.assertEqual(self.executor._runs[result["run_id"]].pause_reason, "max_children exceeded")
+ self.assertEqual(status["usage"]["spawns"], 2)
+ self.assertEqual(status["usage"]["max_children"], 2)
+ # c was prepared but never admitted: entry running, instance pending.
+ c_report = self.node_status(status, "c")
+ self.assertEqual(c_report["status"], "running")
+ self.assertEqual(c_report["instances"][0]["status"], "pending")
+ self.assertEqual(self.host.spawn_calls("c"), [])
+ # resume is the explicit operator decision: c runs, no second pause
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(self.node_status(final, "c")["status"], "done")
+ self.assertEqual(final["usage"]["spawns"], 3)
+ self.assertEqual(self.host.notice_kinds(), ["max_children_exceeded", "finished"])
+
+ @async_test
+ async def test_foreach_children_count_against_the_run_max_children_budget(self) -> None:
+ # The finding's scenario, pinned: nothing bounded the total
+ # children of repeated foreach expansion (10,000 transitions x
+ # foreach.max 256 = 2.56M admissions with no run budget). foreach
+ # expansions count against run.max_children: the run pauses
+ # mid-expansion with the exact error, and resume finishes the
+ # expansion exactly once past it.
+ self.host.outcomes["src"] = {
+ "status": "done",
+ "answer": '```json\n{"items": ["w", "x", "y", "z"]}\n```',
+ }
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue", "max_children": 2, "max_parallel": 8},
+ "nodes": [
+ {"id": "src", "subagent": "worker", "outputs": [{"name": "items", "type": "json"}]},
+ {
+ "id": "fan",
+ "subagent": {"prompt": "Expand item {items}."},
+ "depends_on": ["src"],
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "foreach": {"over": "items", "max": 256},
+ },
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ # src plus fan instance 0 hit the budget; the remaining fan
+ # instances wait: the executor refuses their spawns, it never
+ # wedges and never spends them.
+ self.assertEqual(paused["state"], "paused")
+ self.assertIn("max_children_exceeded", self.host.notice_kinds())
+ self.assertEqual(self.executor._runs[result["run_id"]].pause_reason, "max_children exceeded")
+ self.assertEqual(paused["usage"]["spawns"], 2)
+ fan = self.node_status(paused, "fan")
+ self.assertEqual(len(fan["instances"]), 4)
+ self.assertEqual([instance["status"] for instance in fan["instances"]], ["running", "pending", "pending", "pending"])
+ self.assertEqual(len(self.host.spawn_calls("fan")), 1)
+ # resume finishes the expansion: all four fan children run, no
+ # second child-budget pause fires.
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(self.node_status(final, "fan")["status"], "done")
+ self.assertEqual(final["usage"]["spawns"], 5)
+ self.assertEqual(
+ sorted(call["prompt"] for call in self.host.spawn_calls("fan")),
+ ["Expand item w.", "Expand item x.", "Expand item y.", "Expand item z."],
+ )
+ self.assertEqual(self.host.notice_kinds(), ["max_children_exceeded", "finished"])
+
+
+ # -- stop and rate limits -------------------------------------------------------------
+
+ @async_test
+ async def test_stop_cancels_children_and_pending_nodes(self) -> None:
+ self.host.outcomes["a"] = {"status": "running"}
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["a"])
+ await self.wait_until(lambda: self.host.collects >= 1)
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["run_id"], result["run_id"])
+ self.assertEqual(stopped["state"], "stopped")
+ self.assertEqual(stopped["cancelled"], ["a", "b"])
+ self.assertEqual(self.host.deleted_targets(), ["child-1"])
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "stopped")
+ self.assertEqual(self.node_status(status, "a")["status"], "cancelled")
+ self.assertEqual(self.node_status(status, "b")["status"], "cancelled")
+ # repeated stop is idempotent: same result, no duplicate ledger event
+ again = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(again, {"run_id": result["run_id"], "state": "stopped", "cancelled": []})
+ run_stopped_events = [e for e in self.executor._runs[result["run_id"]].events if e["kind"] == "run_stopped"]
+ self.assertEqual(len(run_stopped_events), 1)
+
+ @async_test
+ async def test_concurrent_stop_runs_one_cancellation_pass(self) -> None:
+ # Review finding: two concurrent stop() calls would both pass a bare
+ # "stopped" check, issue duplicate delete_subagent requests, and
+ # record a second run_stopped event. The transitional "stopping"
+ # state is guarded too.
+ self.host.outcomes["a"] = {"status": "running"}
+ self.host.outcomes["b"] = {"status": "running"}
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ await self.wait_until(lambda: self.host.collects >= 1)
+ delete_gate = self.host.gate("rlm.delete_subagent", 1)
+ stop_one = asyncio.ensure_future(rlm_module.rlm.factory.stop(result["run_id"]))
+ await self.wait_until(lambda: self.executor._runs[result["run_id"]].state == "stopping")
+ # stop #2 lands while stop #1 is suspended mid-cancellation: it must
+ # early-return without starting a second pass.
+ stop_two = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stop_two, {"run_id": result["run_id"], "state": "stopping", "cancelled": []})
+ delete_gate.set()
+ stopped = await stop_one
+ self.assertEqual(stopped["state"], "stopped")
+ self.assertEqual(sorted(stopped["cancelled"]), ["a", "b"])
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "stopped")
+ # one cancellation pass: each child deleted exactly once, one event
+ self.assertEqual(sorted(self.host.deleted_targets()), ["child-1", "child-2"])
+ self.assertEqual(len(self.host.deleted_targets()), 2)
+ run_stopped_events = [e for e in self.executor._runs[result["run_id"]].events if e["kind"] == "run_stopped"]
+ self.assertEqual(len(run_stopped_events), 1)
+
+ @async_test
+ async def test_stop_window_admits_no_new_spawns_and_never_finalizes(self) -> None:
+ # max_parallel 2 with three ready nodes: c waits for a slot. The
+ # loop's first collect and stop()'s first delete are gated so the
+ # stop window opens mid-collect with free-able slots and a ready
+ # pending node: the loop must neither admit c nor finalize the run.
+ self.store_factory(
+ {
+ "run": {"max_parallel": 2},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ collect_gate = self.host.gate("rlm.collect", 1)
+ delete_gate = self.host.gate("rlm.delete_subagent", 1)
+ result = await self.start()
+ self.assertEqual(result["started"], ["a", "b"]) # c waits for a slot
+ run = self.executor._runs[result["run_id"]]
+ await yield_loop_turn() # the loop reaches collect#1 and suspends
+ stop_task = asyncio.ensure_future(rlm_module.rlm.factory.stop(result["run_id"]))
+ for _ in range(1000):
+ if run.state == "stopping":
+ break
+ await yield_loop_turn()
+ self.assertEqual(run.state, "stopping")
+ # release the collect: the loop settles a and b inside the stop window
+ collect_gate.set()
+ await run.task # the loop must exit on "stopping" without admitting c
+ delete_gate.set()
+ stopped = await stop_task
+ self.assertEqual(stopped["state"], "stopped")
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "stopped")
+ # never finalized: no finished notice, and c was never admitted
+ self.assertEqual(self.host.notice_kinds(), [])
+ self.assertEqual(len(self.host.calls_of("rlm.run")), 2)
+
+ @async_test
+ async def test_stop_during_in_flight_admission_deletes_the_child(self) -> None:
+ # run() admission is deferred by a 429, the control loop retries, and
+ # stop() lands while that retry is still in flight: the child the
+ # suspended spawn returns must be deleted and never registered running.
+ self.host.rate_limit_first["a"] = 1
+ spawn_gate = self.host.gate("rlm.run", 2)
+ gate_entered = self.host.gate_entered("rlm.run", 2)
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]})
+ result = await self.start()
+ self.assertEqual(result["started"], [])
+ await gate_entered.wait() # the loop is suspended mid-spawn
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["a"])
+ spawn_gate.set() # the admission returns a child into a stopped run
+ run = self.executor._runs[result["run_id"]]
+ await run.task
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ instance = self.node_status(status, "a")["instances"][0]
+ self.assertEqual(status["state"], "stopped")
+ self.assertEqual(instance["status"], "cancelled")
+ self.assertEqual(instance["child"], "child-1")
+ self.assertEqual(self.host.deleted_targets(), ["child-1"]) # retracted
+ self.assertEqual(status["usage"]["spawns"], 0) # never registered
+ self.assertEqual(len(self.host.spawn_calls("a")), 2) # no re-admission
+ # the retraction is recorded after run_stopped: a cancelled ledger
+ # entry for the retracted child, and no spawned event after it.
+ kinds = [event["kind"] for event in status["events"]]
+ self.assertEqual(kinds[kinds.index("run_stopped"):], ["run_stopped", "cancelled"])
+
+ @async_test
+ async def test_stop_during_admission_backoff_cancels_the_instance(self) -> None:
+ # stop() lands while the loop waits out a rate-limit backoff
+ # deadline: waking must not retry the spawn; the instance is
+ # cancelled instead.
+ self.sleeps = GatedSleep()
+ self.executor = FactoryExecutor(now=self.clock, sleep=self.sleeps, harness=self.harness)
+ factory_module._DEFAULT_EXECUTOR = self.executor
+ self.host.rate_limit_first["a"] = 2
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]})
+ result = await self.start()
+ self.assertEqual(result["started"], [])
+ await self.sleeps.entered.wait() # the loop waits out the backoff slice
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["a"])
+ self.sleeps.release.set() # the backoff wakes into a stopped run
+ run = self.executor._runs[result["run_id"]]
+ await run.task
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "stopped")
+ self.assertEqual(self.node_status(status, "a")["instances"][0]["status"], "cancelled")
+ # the retry never happened: two admissions, both before the stop
+ self.assertEqual(len(self.host.spawn_calls("a")), 2)
+ self.assertEqual(self.host.deleted_targets(), []) # no child existed
+ self.assertEqual(status["usage"]["spawns"], 0)
+
+ @async_test
+ async def test_stop_cancels_an_in_flight_earlier_entry_of_a_reentered_state(self) -> None:
+ # x re-enters (max_entries 2): entry 1 settles while entry 0 is still
+ # running, so the state's latest entry reads done. stop() must still
+ # report and cancel the in-flight entry 0, not read the state as done.
+ self.host.child_outcomes["child-3"] = {"status": "running"}
+ self.host.child_outcomes["child-4"] = {"status": "done", "answer": "x-two"}
+ self.store_machine(
+ {
+ "run": {"max_parallel": 4},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker"},
+ {"id": "b", "entry": True, "subagent": "worker"},
+ {"id": "x", "subagent": "worker", "max_entries": 2},
+ ],
+ "transitions": [{"from": "a", "to": "x"}, {"from": "b", "to": "x"}],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["a", "b"])
+ run = self.executor._runs[result["run_id"]]
+ # entry 1 settles while entry 0's child stays running forever
+ await self.wait_until(lambda: any(entry.status == "done" for entry in run.states["x"].entries))
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["x"]) # not []: entry 0 is in flight
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "stopped")
+ node = self.node_status(status, "x")
+ self.assertEqual([(e["index"], e["status"]) for e in node["entries"]], [(0, "cancelled"), (1, "done")])
+ self.assertEqual([(i["index"], i["status"]) for i in node["instances"]], [(0, "cancelled"), (1, "done")])
+ self.assertEqual(self.host.deleted_targets(), ["child-3"])
+
+ @async_test
+ async def test_concurrent_stop_during_fail_fast_deletes_each_child_once(self) -> None:
+ # Regression (bot review): fail_fast's cancellation cascade runs while
+ # the run is still "running", so a concurrent stop() started its own
+ # pass mid-cascade and issued a duplicate delete_subagent for a child
+ # the first pass already owned. The pass CLAIMS each instance before
+ # its await, so every child is deleted exactly once.
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ delete_gate = self.host.gate("rlm.delete_subagent", 1)
+ delete_entered = self.host.gate_entered("rlm.delete_subagent", 1)
+ self.store_factory(
+ {
+ "run": {"failure_policy": "fail_fast"},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ # a settles error -> fail_fast cancels b; the first delete is gated.
+ await delete_entered.wait()
+ # stop() lands while the run is still "running" (fail_fast sets
+ # "failed" only after its cascade): its pass must skip b (claimed)
+ # and cancel c itself.
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["state"], "stopped")
+ delete_gate.set()
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "stopped")
+ # The gated delete resumes after the stop pass: the fail_fast
+ # cascade finishes inside the control-loop task, so the task-done
+ # barrier waits for BOTH deletions deterministically (an assert on
+ # the delete list alone could race the released call).
+ run = self.executor._runs[result["run_id"]]
+ await self.wait_until(lambda: run.task.done())
+ # every child deleted exactly once, in one pass each
+ self.assertEqual(sorted(self.host.deleted_targets()), ["child-2", "child-3"])
+ self.assertEqual(
+ len([event for event in self.all_events_of(result, "cancel_failed")]), 0
+ )
+
+ @async_test
+ async def test_failed_delete_records_cancel_failed_and_cancelled(self) -> None:
+ # A delete that raises still releases the executor's slot, so the
+ # ledger records the failure AND the cancellation (the eval replay
+ # checker keys off cancelled events) while the instance reads
+ # cancelled in the stopped run.
+ failing = DeleteFailsHost(clock=self.clock)
+ patcher = patch.object(rlm_module, "host_request", failing)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ failing.outcomes["a"] = {"status": "running"}
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]})
+ result = await self.start()
+ await self.wait_until(lambda: failing.collects >= 1)
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["a"])
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ self.assertEqual(status["state"], "stopped")
+ instance = self.node_status(status, "a")["instances"][0]
+ self.assertEqual(instance["status"], "cancelled")
+ kinds = [(event["kind"], event.get("detail")) for event in status["events"]]
+ self.assertIn(("cancel_failed", None), kinds)
+ self.assertIn(("cancelled", "slot released despite the failed delete"), kinds)
+ # the failure is recorded before the cancellation it explains
+ self.assertLess(kinds.index(("cancel_failed", None)), kinds.index(("cancelled", "slot released despite the failed delete")))
+
+ @async_test
+ async def test_rate_limit_at_admission_defers_to_backoff(self) -> None:
+ # First two admissions for a fail with a 429: one at run() admission
+ # (deferred, no sleep in the calling turn), one inside the loop
+ # (records the backoff deadline), then the loop waits out the
+ # deadline in bounded slices and the retry succeeds.
+ self.host.rate_limit_first["a"] = 2
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]})
+ result = await self.start()
+ self.assertEqual(result["started"], [])
+ # run() itself never slept: the deferral is nonblocking.
+ self.assertEqual(self.sleeps.sleeps, [])
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ # three host admissions in total: one deferred at run(), then one
+ # rate-limited retry inside the loop's backoff, then success
+ self.assertEqual(len(self.host.spawn_calls("a")), 3)
+ self.assertEqual(self.node_status(status, "a")["attempts"], 3)
+ self.assertEqual(self.sleeps.sleeps, [1.0])
+
+ @async_test
+ async def test_rate_limit_backoff_exhaustion_fails_node(self) -> None:
+ self.host.rate_limit_forever.add("b")
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ # BACKOFF_MAX_ATTEMPTS consecutive rate-limited admissions fail the
+ # node through its failure_policy.
+ self.assertEqual(BACKOFF_MAX_ATTEMPTS, 5)
+ self.assertEqual(len(self.host.spawn_calls("b")), 5)
+ b = self.node_status(status, "b")
+ self.assertEqual(b["status"], "error")
+ self.assertIn("spawn admission failed", b["error"])
+ self.assertEqual(status["state"], "failed")
+ # The backoff waits out its deadlines in bounded slices (each capped
+ # at the collect poll timeout), never one blocking sleep per delay:
+ # the sole control lane stays free for collection while admission
+ # backs off.
+ self.assertTrue(self.sleeps.sleeps)
+ self.assertTrue(all(delay <= POLL_TIMEOUT_MS / 1000 for delay in self.sleeps.sleeps))
+ self.assertEqual(sum(self.sleeps.sleeps), 1.0 + 2.0 + 4.0 + 8.0) # 1,2,4,8s delays
+ # (Children keep being collected during a backoff when some are
+ # running -- test_backoff_keeps_collecting_running_children proves
+ # that property; here b backs off with nothing in flight.)
+
+ @async_test
+ async def test_backoff_keeps_collecting_running_children(self) -> None:
+ # Review finding: a blocking backoff (one long sleep per retry)
+ # starves collection for the whole delay, so a sibling that
+ # completes during the backoff is observed late and can be
+ # misclassified against its own budget. The loop must keep polling
+ # children while admission waits out its deadline.
+ self.host.outcomes["a"] = {"status": "running"}
+ self.host.rate_limit_first["b"] = 3
+ self.store_factory(
+ {
+ "run": {"failure_policy": "continue"},
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ ],
+ }
+ )
+ result = await self.start()
+ run = self.executor._runs[result["run_id"]]
+ self.assertEqual(result["started"], ["a"]) # b deferred at admission
+ # b's loop retry records the first backoff deadline.
+ await self.wait_until(lambda: any(e["kind"] == "spawn_backoff" for e in run.events))
+ collects_at_backoff = self.host.collects
+ # a completes while b is still backed off (its 1s+2s+4s delays are
+ # waited out in slices, with collects between them).
+ self.host.outcomes["a"] = {"status": "done", "answer": "late-but-collected"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.node_status(status, "a")["status"], "done")
+ self.assertEqual(self.node_status(status, "b")["status"], "done")
+ # a settled during the backoff window: collects continued past the
+ # deadline the loop was waiting out.
+ self.assertGreater(self.host.collects, collects_at_backoff)
+ settled = [e for e in self.all_events_of(result, "settled") if e.get("node") == "a" and e.get("status") == "done"]
+ self.assertEqual(len(settled), 1)
+
+ # -- scale -----------------------------------------------------------------------------
+
+ @async_test
+ async def test_scale_chain_100_completes(self) -> None:
+ nodes = [{"id": "n0", "subagent": {"prompt": "step"}}]
+ for index in range(1, 100):
+ nodes.append({"id": f"n{index}", "subagent": {"prompt": "step"}, "depends_on": [f"n{index - 1}"]})
+ self.store_factory({"run": {"max_parallel": 8}, "nodes": nodes})
+ started = time.monotonic()
+ result = await self.start()
+ status = await self.settle(result)
+ elapsed = time.monotonic() - started
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(len(status["nodes"]), 100)
+ self.assertTrue(all(entry["status"] == "done" for entry in status["nodes"]))
+ self.assertLess(elapsed, 10.0)
+
+ @async_test
+ async def test_scale_fan_1000_completes(self) -> None:
+ nodes = [{"id": "n0", "subagent": {"prompt": "step"}}]
+ for index in range(1, 1000):
+ nodes.append({"id": f"n{index}", "subagent": {"prompt": "step"}, "depends_on": ["n0"]})
+ self.store_factory({"run": {"max_parallel": 64}, "nodes": nodes})
+ started = time.monotonic()
+ result = await self.start()
+ status = await self.settle(result)
+ elapsed = time.monotonic() - started
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(len(status["nodes"]), 1000)
+ self.assertTrue(all(entry["status"] == "done" for entry in status["nodes"]))
+ self.assertLess(elapsed, 10.0)
+
+ # -- status, ledger, notices ----------------------------------------------------------
+
+ @async_test
+ async def test_status_marks_events_delivered_and_unknown_run_raises(self) -> None:
+ self.store_factory({"nodes": [{"id": "a", "subagent": "worker"}]})
+ result = await self.start()
+ run = self.executor._runs[result["run_id"]]
+ await self.wait_until(lambda: run.state != "running")
+ # Before any status() read: answers are arrived, the milestone is shown.
+ stages = {event["kind"]: event["stage"] for event in run.events}
+ self.assertEqual(stages["answer_captured"], "arrived")
+ self.assertEqual(stages["milestone"], "shown")
+ status = await rlm_module.rlm.factory.status(result["run_id"])
+ # Reading the ledger marks the unseen events delivered; the milestone
+ # keeps "shown" because its notice already reached the parent, so the
+ # stage taxonomy stays observable through status().
+ after = {event["kind"]: event["stage"] for event in run.events}
+ self.assertEqual(after["milestone"], "shown")
+ self.assertEqual(after["answer_captured"], "delivered")
+ self.assertEqual(status["events"][-1]["stage"], "shown") # the milestone
+ # EVENT_WINDOW: a state-machine run's ledger grows fast (the
+ # pr-manager happy path is ~43 events before any retry).
+ self.assertEqual(EVENT_WINDOW, 200)
+ self.assertLessEqual(len(status["events"]), EVENT_WINDOW)
+ # exactly one notice for the one milestone
+ self.assertEqual(self.host.notice_kinds(), ["finished"])
+ for call in ("status", "stop", "resume"):
+ with self.assertRaisesRegex(ValueError, "unknown factory run"):
+ await getattr(rlm_module.rlm.factory, call)("no-such-run")
+
+ @async_test
+ async def test_milestone_notices_carry_validated_payloads(self) -> None:
+ # The TS-era host handler validated the payload; the kernel-side
+ # contract it validated is pinned here: run-level milestones send
+ # {run_id, kind, detail} (no node), node-level ones add "node", and
+ # every notice goes through one "factory.progress" host request.
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ resume = await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "failed")
+ kinds = self.host.notice_kinds()
+ self.assertEqual(kinds, ["paused", "failed"])
+ paused_notice, failed_notice = self.host.notices
+ self.assertEqual(paused_notice["kind"], "paused")
+ self.assertEqual(paused_notice["run_id"], result["run_id"])
+ self.assertIn("state a failed", paused_notice["detail"])
+ self.assertIn("resume", paused_notice["detail"])
+ self.assertEqual(paused_notice.get("node"), "a") # node-level milestone
+ self.assertEqual(failed_notice["kind"], "failed")
+ self.assertEqual(failed_notice["run_id"], result["run_id"])
+ self.assertIsNone(failed_notice.get("node")) # run-level milestone
+ self.assertEqual(set(paused_notice.keys()), {"run_id", "kind", "detail", "node"})
+ self.assertEqual(set(failed_notice.keys()), {"run_id", "kind", "detail"})
+ # one host request per notice, typed factory.progress
+ self.assertEqual(len(self.host.calls_of("factory.progress")), 2)
+
+ @async_test
+ async def test_dead_bridge_keeps_the_milestone_in_the_ledger(self) -> None:
+ # A dead bridge cannot be told: the milestone stays in the ledger
+ # (stage "recorded") and status() still surfaces it to the parent.
+ failing = DeadNoticeHost(clock=self.clock)
+ patcher = patch.object(rlm_module, "host_request", failing)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ failing.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ run = self.executor._runs[result["run_id"]]
+ # a fails: escalate pauses the run while the bridge is dead, so the
+ # milestone lands in the ledger without ever being shown.
+ await self.wait_until(lambda: run.state == "paused")
+ await self.wait_until(lambda: any(event["kind"] == "milestone" for event in run.events))
+ raw = [event for event in run.events if event["kind"] == "milestone"]
+ self.assertEqual(len(raw), 1)
+ self.assertEqual(raw[0]["stage"], "recorded") # never shown: bridge dead
+ self.assertIn("state a failed", raw[0]["detail"])
+ # status() still surfaces the milestone to the parent: the read marks
+ # the unread ("recorded") event delivered, like any other ledger read.
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ milestones = [event for event in paused["events"] if event["kind"] == "milestone"]
+ self.assertEqual(len(milestones), 1)
+ self.assertEqual(milestones[0]["milestone"], "paused")
+ self.assertEqual(milestones[0]["stage"], "delivered") # read via status()
+ self.assertIn("state a failed", milestones[0]["detail"])
+ # the run is not wedged: resume still works end to end.
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "failed")
+ self.assertEqual(self.node_status(final, "b")["status"], "done")
+
+
+ # -- machine form: transitions, guards, re-entry, residents ---------------------
+
+ @async_test
+ async def test_machine_three_round_review_loop(self) -> None:
+ # review verdict approved=false twice, then true: the guarded switch
+ # alternates reviewing/fixing until approved, then quiesces as done.
+ self.host.child_outcomes["child-1"] = {"status": "done", "answer": "DRAFT-1"}
+ self.host.child_outcomes["child-2"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": false, "findings": ["AUDIT-A1"]}}\n```',
+ }
+ self.host.child_outcomes["child-3"] = {"status": "done", "answer": "fixed round 1"}
+ self.host.child_outcomes["child-4"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": false, "findings": ["AUDIT-B1"]}}\n```',
+ }
+ self.host.child_outcomes["child-5"] = {"status": "done", "answer": "fixed round 2"}
+ self.host.child_outcomes["child-6"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": true, "findings": []}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {
+ "id": "draft",
+ "entry": True,
+ "subagent": "worker",
+ "outputs": [{"name": "draft", "type": "text"}],
+ },
+ {
+ "id": "reviewing",
+ "subagent": "worker",
+ "inputs": [{"name": "draft", "type": "text", "from": "draft.draft"}],
+ "outputs": [{"name": "verdict", "type": "json"}],
+ "max_entries": 4,
+ },
+ {"id": "fixing", "subagent": "worker", "max_entries": 3},
+ ],
+ "transitions": [
+ {"from": "draft", "to": "reviewing"},
+ {
+ "from": "reviewing",
+ "to": "fixing",
+ "when": {"output": "verdict", "path": "approved", "op": "eq", "value": False},
+ },
+ {"from": "fixing", "to": "reviewing"},
+ ],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["draft"])
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ reviewing = self.state_report(status, "reviewing")
+ fixing = self.state_report(status, "fixing")
+ self.assertEqual(reviewing["status"], "done")
+ self.assertEqual(reviewing["entries_used"], 3)
+ self.assertEqual(len(reviewing["entries"]), 3)
+ self.assertEqual(len(reviewing["instances"]), 3)
+ self.assertEqual(fixing["status"], "done")
+ self.assertEqual(fixing["entries_used"], 2)
+ self.assertEqual(len(self.host.spawn_calls("reviewing")), 3)
+ self.assertEqual(len(self.host.spawn_calls("fixing")), 2)
+ self.assertEqual(status["usage"]["transitions_fired"], 5)
+ # the final approved verdict never fires the guarded transition
+ fired = self.all_events_of(result, "transition_fired")
+ self.assertEqual(len(fired), 5)
+ self.assertEqual(self.all_events_of(result, "transition_blocked"), [])
+
+ @async_test
+ async def test_machine_guard_switch_fires_only_the_matching_branch(self) -> None:
+ self.host.outcomes["pick"] = {
+ "status": "done",
+ "answer": '```json\n{"pick": {"choice": "left"}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {
+ "id": "pick",
+ "entry": True,
+ "subagent": "worker",
+ "outputs": [{"name": "pick", "type": "json"}],
+ },
+ {"id": "left", "subagent": "worker"},
+ {"id": "right", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "pick", "to": "left", "when": {"output": "pick", "path": "choice", "op": "eq", "value": "left"}},
+ {"from": "pick", "to": "right", "when": {"output": "pick", "path": "choice", "op": "eq", "value": "right"}},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ left = self.state_report(status, "left")
+ right = self.state_report(status, "right")
+ self.assertEqual(left["status"], "done")
+ self.assertEqual(left["entries_used"], 1)
+ # the exclusive guard never entered "right": quiescence ignores it
+ self.assertEqual(right["entries_used"], 0)
+ self.assertEqual(right["status"], "pending")
+ self.assertEqual(self.host.spawn_calls("right"), [])
+ self.assertEqual(status["usage"]["transitions_fired"], 1)
+
+ @async_test
+ async def test_machine_fan_out_from_one_settle_fires_all(self) -> None:
+ self.host.outcomes["fan"] = {"status": "done", "answer": "go"}
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {"id": "fan", "entry": True, "subagent": "worker", "outputs": [{"name": "go", "type": "text"}]},
+ {"id": "left", "subagent": "worker"},
+ {"id": "right", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "fan", "to": "left"},
+ {"from": "fan", "to": "right"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.state_report(status, "left")["status"], "done")
+ self.assertEqual(self.state_report(status, "right")["status"], "done")
+ self.assertEqual(status["usage"]["transitions_fired"], 2)
+ fired = self.all_events_of(result, "transition_fired")
+ self.assertEqual([event["to"] for event in fired], ["left", "right"])
+
+ @async_test
+ async def test_machine_max_entries_blocked_transition_quiesces_done(self) -> None:
+ self.store_machine(
+ {
+ "states": [
+ {"id": "once", "entry": True, "subagent": "worker", "max_entries": 1},
+ {"id": "sink", "subagent": "worker", "max_entries": 1},
+ ],
+ "transitions": [
+ {"from": "once", "to": "sink"},
+ {"from": "once", "to": "sink"},
+ {"from": "once", "to": "once"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ # once settles once: sink is entered (one fire), the duplicate edge and
+ # the self-loop are blocked by max_entries, and the run quiesces done.
+ self.assertEqual(status["state"], "done")
+ once = self.state_report(status, "once")
+ self.assertEqual(once["entries_used"], 1)
+ self.assertEqual(once["max_entries"], 1)
+ sink = self.state_report(status, "sink")
+ self.assertEqual(sink["entries_used"], 1)
+ self.assertEqual(status["usage"]["transitions_fired"], 1)
+ blocked = self.all_events_of(result, "transition_blocked")
+ self.assertEqual(len(blocked), 2)
+ self.assertTrue(all(event["to"] in ("once", "sink") for event in blocked))
+
+ @async_test
+ async def test_machine_self_loop_reenters_until_guard_fails(self) -> None:
+ self.host.child_outcomes["child-1"] = {
+ "status": "done",
+ "answer": '```json\n{"count": {"value": 1}}\n```',
+ }
+ self.host.child_outcomes["child-2"] = {
+ "status": "done",
+ "answer": '```json\n{"count": {"value": 2}}\n```',
+ }
+ self.host.child_outcomes["child-3"] = {
+ "status": "done",
+ "answer": '```json\n{"count": {"value": 3}}\n```',
+ }
+ self.store_machine(
+ {
+ "states": [
+ {
+ "id": "tick",
+ "entry": True,
+ "subagent": "worker",
+ "max_entries": 4,
+ "outputs": [{"name": "count", "type": "json"}],
+ }
+ ],
+ "transitions": [
+ {"from": "tick", "to": "tick", "when": {"output": "count", "path": "value", "op": "lt", "value": 3}},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ tick = self.state_report(status, "tick")
+ self.assertEqual(tick["entries_used"], 3)
+ self.assertEqual(len(self.host.spawn_calls("tick")), 3)
+ self.assertEqual(status["usage"]["transitions_fired"], 2)
+
+ @async_test
+ async def test_machine_max_transitions_pauses_once_then_resumes(self) -> None:
+ self.store_machine(
+ {
+ "run": {"max_transitions": 1, "failure_policy": "continue"},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "a", "to": "b"},
+ {"from": "b", "to": "c"},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ # a->b fired (cap 1); b's settle pauses the run before b->c
+ self.assertEqual(paused["state"], "paused")
+ # the max_transitions pause uses its OWN milestone kind, distinct from
+ # the run-budget pause's budget_exceeded (no kind collision)
+ self.assertIn("max_transitions_exceeded", self.host.notice_kinds())
+ self.assertNotIn("budget_exceeded", self.host.notice_kinds())
+ self.assertEqual(paused["usage"]["transitions_fired"], 1)
+ self.assertEqual(self.state_report(paused, "b")["status"], "done")
+ self.assertEqual(self.state_report(paused, "c")["entries_used"], 0)
+ resumed = await rlm_module.rlm.factory.resume(result["run_id"])
+ self.assertEqual(resumed["state"], "running")
+ final = await self.settle(result)
+ # resume is the explicit operator override: the remaining transition fires
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(final["usage"]["transitions_fired"], 2)
+ self.assertEqual(self.state_report(final, "c")["status"], "done")
+
+ @async_test
+ async def test_machine_max_transitions_pause_mid_settle_does_not_refire_on_resume(self) -> None:
+ # Regression (review finding): cap=1 with a fan-out settle
+ # [a->b, a->c]. The pause lands AFTER a->b fired; resume must
+ # continue with a->c only — a->b must never fire twice.
+ self.store_machine(
+ {
+ "run": {"max_transitions": 1, "failure_policy": "continue"},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker"},
+ {"id": "b", "subagent": "worker"},
+ {"id": "c", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "a", "to": "b"},
+ {"from": "a", "to": "c"},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ self.assertIn("max_transitions_exceeded", self.host.notice_kinds())
+ # a->b fired before the pause; a->c is the paused transition
+ self.assertEqual(self.state_report(paused, "b")["entries_used"], 1)
+ self.assertEqual(self.state_report(paused, "c")["entries_used"], 0)
+ self.assertEqual(paused["usage"]["transitions_fired"], 1)
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ # exactly one entry of each target: the pre-pause fire is not repeated
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(self.state_report(final, "b")["entries_used"], 1)
+ self.assertEqual(self.state_report(final, "c")["entries_used"], 1)
+ self.assertEqual(len(self.host.spawn_calls("b")), 1)
+ self.assertEqual(final["usage"]["transitions_fired"], 2)
+
+ @async_test
+ async def test_machine_join_paused_at_max_transitions_fires_after_resume(self) -> None:
+ # Regression (bot review): a join transition that reaches the
+ # max_transitions boundary was marked fired BEFORE the pause, so
+ # the resume skipped it forever and the join target never entered.
+ # The provisional mark must be cleared when the settle is re-queued.
+ self.store_machine(
+ {
+ "run": {"max_transitions": 1, "failure_policy": "continue"},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker"},
+ {"id": "b", "entry": True, "subagent": "worker"},
+ {"id": "c", "subagent": "worker", "max_entries": 2},
+ ],
+ "transitions": [
+ {"from": "a", "to": "c"},
+ {"from": ["a", "b"], "to": "c"},
+ ],
+ }
+ )
+ result = await self.start()
+ paused = await self.settle(result)
+ self.assertEqual(paused["state"], "paused")
+ self.assertIn("max_transitions_exceeded", self.host.notice_kinds())
+ # a->c fired before the pause; the join is the paused transition
+ self.assertEqual(self.state_report(paused, "c")["entries_used"], 1)
+ self.assertEqual(paused["usage"]["transitions_fired"], 1)
+ await rlm_module.rlm.factory.resume(result["run_id"])
+ final = await self.settle(result)
+ # the join fired after the resume: c has TWO entries, never one
+ self.assertEqual(final["state"], "done")
+ self.assertEqual(self.state_report(final, "c")["entries_used"], 2)
+ joins = [e for e in self.all_events_of(result, "transition_fired") if e.get("from") == ["a", "b"]]
+ self.assertEqual(len(joins), 1)
+ self.assertEqual(len(self.host.spawn_calls("c")), 2)
+ self.assertEqual(final["usage"]["transitions_fired"], 2)
+
+ @async_test
+ async def test_machine_guards_compare_json_strictly(self) -> None:
+ # eq: a bool never equals a number (true != 1) and a number never
+ # equals a string; numbers compare numerically (1 == 1.0).
+ self.host.outcomes["pick"] = {
+ "status": "done",
+ "answer": '```json\n{"pick": {"approved": true}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {"id": "pick", "entry": True, "subagent": "worker", "outputs": [{"name": "pick", "type": "json"}]},
+ {"id": "boolish", "subagent": "worker"},
+ {"id": "numish", "subagent": "worker"},
+ {"id": "strish", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "pick", "to": "boolish", "when": {"output": "pick", "path": "approved", "op": "eq", "value": True}},
+ {"from": "pick", "to": "numish", "when": {"output": "pick", "path": "approved", "op": "eq", "value": 1}},
+ {"from": "pick", "to": "strish", "when": {"output": "pick", "path": "approved", "op": "eq", "value": "true"}},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.state_report(status, "boolish")["status"], "done")
+ self.assertEqual(self.state_report(status, "numish")["entries_used"], 0)
+ self.assertEqual(self.state_report(status, "strish")["entries_used"], 0)
+
+ self.host.outcomes["num"] = {
+ "status": "done",
+ "answer": '```json\n{"num": {"value": 1.0}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {"id": "num", "entry": True, "subagent": "worker", "outputs": [{"name": "num", "type": "json"}]},
+ {"id": "floats", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "num", "to": "floats", "when": {"output": "num", "path": "value", "op": "eq", "value": 1}},
+ ],
+ },
+ spec_id="numeric",
+ )
+ result = await self.start("numeric")
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.state_report(status, "floats")["status"], "done")
+
+ # ne is the strict complement: true != 1 fires.
+ self.host.outcomes["flag"] = {
+ "status": "done",
+ "answer": '```json\n{"flag": {"on": true}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {"id": "flag", "entry": True, "subagent": "worker", "outputs": [{"name": "flag", "type": "json"}]},
+ {"id": "notone", "subagent": "worker"},
+ ],
+ "transitions": [
+ {"from": "flag", "to": "notone", "when": {"output": "flag", "path": "on", "op": "ne", "value": 1}},
+ ],
+ },
+ spec_id="necheck",
+ )
+ result = await self.start("necheck")
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.state_report(status, "notone")["status"], "done")
+
+ def test_json_output_binds_from_the_fence_that_carries_the_port(self) -> None:
+ # several fences: the port rides whichever block carries it, so a
+ # verdict fence followed by a summary fence still binds the port
+ two_fences = '```json\n{"o": 1}\n```\n\n```json\n{"summary": "s"}\n```'
+ self.assertEqual(_parse_json_output(two_fences, "o"), (1, None))
+ self.assertEqual(_parse_json_output(two_fences, "summary"), ("s", None))
+ # a port in several fences binds from the trailing block
+ both = '```json\n{"o": "first"}\n```\n\n```json\n{"o": "last"}\n```'
+ self.assertEqual(_parse_json_output(both, "o"), ("last", None))
+ # no fence carries the port: fall back to the whole answer, then fail
+ self.assertEqual(_parse_json_output('{"o": 2}', "o"), (2, None))
+ value, error = _parse_json_output(two_fences, "missing")
+ self.assertIsNone(value)
+ self.assertIn("no JSON object containing output 'missing'", error)
+
+ def test_guard_primitives_json_strict_and_defensive(self) -> None:
+ outputs = {"verdict": {"approved": True, "count": 1.0, "tags": ["a"]}}
+ when = lambda **kw: {"output": "verdict", **kw} # noqa: E731
+ # bool vs number never equal, either way
+ self.assertFalse(_guard_passes(when(path="approved", op="eq", value=1), outputs))
+ self.assertFalse(_guard_passes(when(path="approved", op="eq", value=0), outputs))
+ self.assertTrue(_guard_passes(when(path="approved", op="ne", value=1), outputs))
+ # numbers compare numerically
+ self.assertTrue(_guard_passes(when(path="count", op="eq", value=1), outputs))
+ self.assertTrue(_guard_passes(when(path="count", op="lte", value=1.5), outputs))
+ # contains works on lists; an empty needle is defensively False
+ self.assertTrue(_guard_passes(when(path="tags", op="contains", value=["a"]), outputs))
+ self.assertFalse(_guard_passes(when(path="tags", op="contains", value=[]), outputs))
+ # a missing port fails every op except exists (explicitly false)
+ self.assertFalse(_guard_passes(when(path="gone", op="ne", value=1), outputs))
+ self.assertFalse(_guard_passes(when(path="gone", op="exists"), outputs))
+ self.assertTrue(_guard_passes(when(path="approved", op="exists"), outputs))
+ # large JSON integers compare exactly: no lossy float conversion
+ # (9007199254740993 and 9007199254740992 are distinct under eq/ne)
+ big = {"verdict": {"n": 9007199254740993}}
+ self.assertTrue(_guard_passes(when(path="n", op="eq", value=9007199254740993), big))
+ self.assertFalse(_guard_passes(when(path="n", op="eq", value=9007199254740992), big))
+ self.assertTrue(_guard_passes(when(path="n", op="ne", value=9007199254740992), big))
+ # numeric cross-type equality stays exact too
+ self.assertTrue(_guard_passes(when(path="count", op="eq", value=1.0), outputs))
+
+ @async_test
+ async def test_machine_stall_fails_with_the_pending_entry_reason(self) -> None:
+ # An entry whose input source is never entered cannot bind: the loop
+ # must end the run failed naming the stuck state, not hang or misreport.
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {"id": "a", "entry": True, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "subagent": "worker", "inputs": [{"name": "i", "type": "text", "from": "c.o"}]},
+ {"id": "c", "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ b = self.state_report(status, "b")
+ self.assertEqual(b["status"], "pending")
+ stall_events = self.events_of(status, "executor_error")
+ self.assertEqual(len(stall_events), 1)
+ self.assertIn("pending entry of state 'b'", stall_events[0]["error"])
+ self.assertIn("never settled", stall_events[0]["error"])
+ self.assertIn("failed", self.host.notice_kinds())
+
+ @async_test
+ async def test_machine_optional_input_binds_null_then_the_real_settle(self) -> None:
+ # The closed review/fix loop shape: reviewing's fix-report input is
+ # optional, so its first entry binds the null sentinel before the
+ # fixer ever runs; the re-entry re-binds the real fix report.
+ self.host.child_outcomes["child-1"] = {"status": "done", "answer": "GO"}
+ self.host.child_outcomes["child-2"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": false, "findings": ["AUDIT-A1"]}}\n```',
+ }
+ self.host.child_outcomes["child-3"] = {
+ "status": "done",
+ "answer": '```json\n{"fix": {"fixed": ["AUDIT-A1"]}}\n```',
+ }
+ self.host.child_outcomes["child-4"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": true, "findings": []}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker", "outputs": [{"name": "go", "type": "text"}]},
+ {
+ "id": "rev",
+ "subagent": "worker",
+ "inputs": [
+ {"name": "go", "type": "text", "from": "seed.go"},
+ {"name": "fix", "type": "json", "from": "fixer.fix", "optional": True},
+ ],
+ "outputs": [{"name": "verdict", "type": "json"}],
+ "max_entries": 4,
+ },
+ {
+ "id": "fixer",
+ "subagent": "worker",
+ "inputs": [{"name": "verdict", "type": "json", "from": "rev.verdict"}],
+ "outputs": [{"name": "fix", "type": "json"}],
+ "max_entries": 2,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "rev"},
+ {"from": "rev", "to": "fixer", "when": {"output": "verdict", "path": "approved", "op": "eq", "value": False}},
+ {"from": "fixer", "to": "rev"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ rev_prompts = [call["prompt"] for call in self.host.spawn_calls("rev")]
+ self.assertEqual(len(rev_prompts), 2)
+ # round 1: the fixer never settled, so the optional input bound null
+ self.assertIn("null", rev_prompts[0])
+ self.assertNotIn("AUDIT-A1", rev_prompts[0])
+ # round 2: the re-entry re-bound the fixer's captured fix report
+ self.assertIn("AUDIT-A1", rev_prompts[1])
+ rev = self.state_report(status, "rev")
+ self.assertEqual(rev["entries_used"], 2)
+ self.assertEqual(self.state_report(status, "fixer")["entries_used"], 1)
+ self.assertEqual(status["usage"]["transitions_fired"], 3)
+
+ @async_test
+ async def test_machine_optional_foreach_over_expands_empty_then_the_real_settle(self) -> None:
+ # Review finding (PR #3199): marking the foreach.over input
+ # optional used to hit "foreach entry did not resolve its over
+ # input" -- a hard failure where the required form only waits. The
+ # optional over input now expands to zero items when its source
+ # never settled (the same done-with-no-instances path as a settled
+ # empty list), and the re-entry binds the real list.
+ self.host.outcomes["src"] = {
+ "status": "done",
+ "answer": '```json\n{"items": ["a", "b", "c"]}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker"},
+ {
+ "id": "fan",
+ "subagent": {"prompt": "Process item {items}."},
+ "inputs": [{"name": "items", "type": "json", "from": "src.items", "optional": True}],
+ "foreach": {"over": "items", "max": 4},
+ "max_entries": 2,
+ },
+ {
+ "id": "src",
+ "subagent": "worker",
+ "outputs": [{"name": "items", "type": "json"}],
+ "max_entries": 1,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "fan"},
+ {"from": "fan", "to": "src"},
+ {"from": "src", "to": "fan"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ # round 1: src never settled, so the optional over input expanded to
+ # zero items -- the entry settled done with NO spawn and NO error.
+ fan = self.state_report(status, "fan")
+ self.assertEqual(fan["entries_used"], 2)
+ self.assertEqual([entry["status"] for entry in fan["entries"]], ["done", "done"])
+ self.assertEqual(self.all_events_of(result, "node_error"), [])
+ self.assertEqual(
+ [
+ e["detail"]
+ for e in self.all_events_of(result, "node_ready")
+ if e.get("node") == "fan" and e.get("entry") == 0
+ ],
+ ["foreach expanded to zero items; nothing to run"],
+ )
+ # round 2: the re-entry bound the real list and ran one instance
+ # per item (the fan->src transition after it is blocked by
+ # src's max_entries).
+ self.assertEqual(
+ [call["prompt"] for call in self.host.spawn_calls("fan")],
+ ["Process item a.", "Process item b.", "Process item c."],
+ )
+ self.assertEqual(self.state_report(status, "src")["entries_used"], 1)
+ self.assertEqual(status["usage"]["transitions_fired"], 3)
+
+ @async_test
+ async def test_machine_optional_input_over_an_errored_source_binds_the_null_sentinel(self) -> None:
+ # Review finding (PR #3199): an optional input bound the null
+ # sentinel only while its source had NO settle. Once the source
+ # settled with an error, _prepare_entry still failed the dependent
+ # entry ("... unavailable (latest settle status 'error')"), so one
+ # failed fixer iteration killed the review/fix loop that the
+ # optional input exists to enable. An errored settle is not a
+ # value: the optional input binds the sentinel exactly like the
+ # never-settled case and the dependent re-enters.
+ self.host.child_outcomes["child-1"] = {"status": "done", "answer": "GO"}
+ self.host.child_outcomes["child-2"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": false, "findings": ["AUDIT-A1"]}}\n```',
+ }
+ self.host.child_outcomes["child-3"] = {"status": "error", "error": "fixer exploded"}
+ self.host.child_outcomes["child-4"] = {
+ "status": "done",
+ "answer": '```json\n{"verdict": {"approved": true, "findings": []}}\n```',
+ }
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker", "outputs": [{"name": "go", "type": "text"}]},
+ {
+ "id": "rev",
+ "subagent": "worker",
+ "inputs": [
+ {"name": "go", "type": "text", "from": "seed.go"},
+ {"name": "fix", "type": "json", "from": "fixer.fix", "optional": True},
+ ],
+ "outputs": [{"name": "verdict", "type": "json"}],
+ "max_entries": 4,
+ },
+ {
+ "id": "fixer",
+ "subagent": "worker",
+ "inputs": [{"name": "verdict", "type": "json", "from": "rev.verdict"}],
+ "outputs": [{"name": "fix", "type": "json"}],
+ "max_entries": 2,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "rev"},
+ {"from": "rev", "to": "fixer", "when": {"output": "verdict", "path": "approved", "op": "eq", "value": False}},
+ {"from": "fixer", "to": "rev"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ # The fixer failed, so the continue-policy run still reports
+ # failed -- but the reviewer RE-ENTERED and completed instead of
+ # dying at input binding over the errored source.
+ self.assertEqual(status["state"], "failed")
+ rev = self.state_report(status, "rev")
+ self.assertEqual(rev["entries_used"], 2)
+ self.assertEqual([entry["status"] for entry in rev["entries"]], ["done", "done"])
+ self.assertNotIn("error", rev)
+ fixer = self.state_report(status, "fixer")
+ self.assertEqual(fixer["entries_used"], 1)
+ self.assertEqual(fixer["error"], "fixer exploded")
+ # Round 1 bound the sentinel (the fixer had not settled); round 2
+ # bound the sentinel AGAIN over the errored settle.
+ rev_prompts = [call["prompt"] for call in self.host.spawn_calls("rev")]
+ self.assertEqual(len(rev_prompts), 2)
+ self.assertIn("- fix: null", rev_prompts[0])
+ self.assertIn("- fix: null", rev_prompts[1])
+ self.assertEqual(len(self.host.spawn_calls("fixer")), 1)
+
+ @async_test
+ async def test_machine_optional_foreach_over_an_errored_source_expands_empty(self) -> None:
+ # The errored-settle sentinel carries to the optional foreach.over
+ # input: an errored source expands to zero items, the same
+ # done-with-no-instances path as the never-settled optional over --
+ # the entry proceeds instead of failing at binding.
+ self.host.outcomes["src"] = {"status": "error", "error": "src exploded"}
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker"},
+ {
+ "id": "fan",
+ "subagent": {"prompt": "Process item {items}."},
+ "inputs": [{"name": "items", "type": "json", "from": "src.items", "optional": True}],
+ "foreach": {"over": "items", "max": 4},
+ "max_entries": 2,
+ },
+ {
+ "id": "src",
+ "subagent": "worker",
+ "outputs": [{"name": "items", "type": "json"}],
+ "max_entries": 1,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "fan"},
+ {"from": "fan", "to": "src"},
+ {"from": "src", "to": "fan"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ # Round 1: src never settled -> empty expansion. Round 2: src
+ # settled with an ERROR -> empty expansion again, never a spawn
+ # and never a binding failure on the fan entries.
+ fan = self.state_report(status, "fan")
+ self.assertEqual(fan["entries_used"], 2)
+ self.assertEqual([entry["status"] for entry in fan["entries"]], ["done", "done"])
+ self.assertNotIn("error", fan)
+ self.assertEqual(self.host.spawn_calls("fan"), [])
+ self.assertEqual(
+ [e for e in self.all_events_of(result, "node_error") if e.get("node") == "fan"],
+ [],
+ )
+ self.assertEqual(
+ [e["detail"] for e in self.all_events_of(result, "node_ready") if e.get("node") == "fan"],
+ ["foreach expanded to zero items; nothing to run"] * 2,
+ )
+
+ @async_test
+ async def test_machine_required_input_over_an_errored_source_fails_the_dependent_entry(self) -> None:
+ # The boundary the authoring reference pins: "their required input
+ # over the failed source then fails the dependent entry". Only the
+ # optional form binds the sentinel; a required input over an
+ # errored source is a hard binding failure (binding failures never
+ # retry), so the dependent fails without ever spawning.
+ self.host.outcomes["src"] = {"status": "error", "error": "src exploded"}
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker"},
+ {
+ "id": "src",
+ "subagent": "worker",
+ "outputs": [{"name": "items", "type": "json"}],
+ "max_entries": 1,
+ },
+ {
+ "id": "dep",
+ "subagent": "worker",
+ "inputs": [{"name": "items", "type": "json", "from": "src.items"}],
+ "max_entries": 1,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "src"},
+ {"from": "src", "to": "dep"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ dep = self.state_report(status, "dep")
+ self.assertEqual(dep["entries_used"], 1)
+ self.assertEqual([entry["status"] for entry in dep["entries"]], ["error"])
+ self.assertIn(
+ "input 'items' from state 'src' is unavailable (latest settle status 'error')",
+ dep["entries"][0]["error"],
+ )
+ self.assertEqual(self.host.spawn_calls("dep"), [])
+
+ @async_test
+ async def test_machine_optional_input_over_a_settled_source_with_no_captured_value_binds_the_null_sentinel(self) -> None:
+ # Review finding (PR #3199), second no-value condition: the source
+ # settled done but captured no value for the declared port (an
+ # empty answer). The optional dependent proceeds on the null
+ # sentinel; only the required dependent over the same valueless
+ # settle fails its entry.
+ self.host.outcomes["src"] = {"status": "done", "answer": ""}
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker"},
+ {
+ "id": "src",
+ "subagent": "worker",
+ "outputs": [{"name": "go", "type": "text"}],
+ "max_entries": 1,
+ },
+ {
+ "id": "opt",
+ "subagent": {"prompt": "Proceed."},
+ "inputs": [{"name": "go", "type": "text", "from": "src.go", "optional": True}],
+ "max_entries": 1,
+ },
+ {
+ "id": "req",
+ "subagent": {"prompt": "Proceed."},
+ "inputs": [{"name": "go", "type": "text", "from": "src.go"}],
+ "max_entries": 1,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "src"},
+ {"from": "src", "to": "opt"},
+ {"from": "src", "to": "req"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ opt = self.state_report(status, "opt")
+ self.assertEqual(opt["entries_used"], 1)
+ self.assertEqual([entry["status"] for entry in opt["entries"]], ["done"])
+ self.assertIn("- go: None", self.host.spawn_calls("opt")[0]["prompt"])
+ req = self.state_report(status, "req")
+ self.assertEqual(req["entries_used"], 1)
+ self.assertEqual([entry["status"] for entry in req["entries"]], ["error"])
+ self.assertIn(
+ "input 'go' from state 'src' has no captured output 'go'",
+ req["entries"][0]["error"],
+ )
+ self.assertEqual(self.host.spawn_calls("req"), [])
+
+ @async_test
+ async def test_machine_optional_input_over_a_failed_json_capture_binds_the_null_sentinel(self) -> None:
+ # Review finding (PR #3199), third no-value condition: the source
+ # settled done, declared a json port, but its answer never parsed
+ # for that port (a JSON capture failure recorded on the settle).
+ # The optional dependent proceeds on the null sentinel; only the
+ # required dependent over the same failed capture fails its entry.
+ self.host.outcomes["src"] = {"status": "done", "answer": "no json here"}
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue", "max_parallel": 4},
+ "states": [
+ {"id": "seed", "entry": True, "subagent": "worker"},
+ {
+ "id": "src",
+ "subagent": "worker",
+ "outputs": [{"name": "data", "type": "json"}],
+ "max_entries": 1,
+ },
+ {
+ "id": "opt",
+ "subagent": {"prompt": "Proceed."},
+ "inputs": [{"name": "data", "type": "json", "from": "src.data", "optional": True}],
+ "max_entries": 1,
+ },
+ {
+ "id": "req",
+ "subagent": {"prompt": "Proceed."},
+ "inputs": [{"name": "data", "type": "json", "from": "src.data"}],
+ "max_entries": 1,
+ },
+ ],
+ "transitions": [
+ {"from": "seed", "to": "src"},
+ {"from": "src", "to": "opt"},
+ {"from": "src", "to": "req"},
+ ],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "failed")
+ opt = self.state_report(status, "opt")
+ self.assertEqual(opt["entries_used"], 1)
+ self.assertEqual([entry["status"] for entry in opt["entries"]], ["done"])
+ self.assertIn("- data: null", self.host.spawn_calls("opt")[0]["prompt"])
+ req = self.state_report(status, "req")
+ self.assertEqual(req["entries_used"], 1)
+ self.assertEqual([entry["status"] for entry in req["entries"]], ["error"])
+ self.assertIn(
+ "input 'data': no JSON object containing output 'data' in the upstream answer",
+ req["entries"][0]["error"],
+ )
+ self.assertEqual(self.host.spawn_calls("req"), [])
+
+ @async_test
+ async def test_resident_node_spawns_stays_alive_and_stops(self) -> None:
+ self.host.outcomes["watcher"] = {"status": "running"}
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "t", "subagent": "worker"},
+ {"id": "watcher", "subagent": "worker", "lifecycle": "resident"},
+ ],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["t", "watcher"])
+ status = await self.settle(result)
+ # The task node settled; the run reports done while the resident stays
+ # alive under the supervisor (V1 wake source: its own prompt/tooling).
+ self.assertEqual(status["state"], "done")
+ self.assertEqual(self.node_status(status, "t")["status"], "done")
+ resident = self.node_status(status, "watcher")
+ self.assertEqual(resident["status"], "running")
+ self.assertEqual(resident["lifecycle"], "resident")
+ self.assertIn("finished", self.host.notice_kinds())
+ # stop() tears the resident child down.
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["watcher"])
+ self.assertEqual(self.host.deleted_targets(), ["child-2"])
+ self.assertEqual((await rlm_module.rlm.factory.status(result["run_id"]))["state"], "stopped")
+
+ @async_test
+ async def test_resident_queued_instance_is_admitted_before_completion(self) -> None:
+ # Review finding: _run_complete reported quiescence while a resident
+ # running entry still had a PENDING instance (queued behind
+ # max_parallel), so the run finalized and the resident child was
+ # never admitted. A resident entry's pending instances block
+ # completion; its admitted running instances never do.
+ self.host.outcomes["go"] = {"status": "running"}
+ # A resident child never settles: it stays alive under the parent
+ # session until stop() tears it down.
+ self.host.outcomes["watcher"] = {"status": "running"}
+ self.store_machine(
+ {
+ "run": {"max_parallel": 1},
+ "states": [
+ {"id": "go", "entry": True, "subagent": "worker"},
+ {"id": "watcher", "entry": True, "subagent": "worker", "lifecycle": "resident"},
+ ],
+ "transitions": [],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["go"]) # the resident queues behind the cap
+ run = self.executor._runs[result["run_id"]]
+ await self.wait_until(lambda: self.host.collects >= 2)
+ watcher = run.states["watcher"]
+ self.assertEqual(watcher.entries[-1].status, "running")
+ self.assertEqual(watcher.entries[-1].instances[-1].status, "pending")
+ # The task settles; the resident instance must be admitted next, and
+ # only then may the run report completion.
+ self.host.outcomes["go"] = {"status": "done", "answer": "go-done"}
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ resident = self.node_status(status, "watcher")
+ self.assertEqual(resident["status"], "running") # admitted, still alive
+ self.assertEqual(status["usage"]["spawns"], 2)
+ self.assertEqual(len(self.host.spawn_calls("watcher")), 1)
+ self.assertIn("finished", self.host.notice_kinds())
+ # the resident child is torn down by stop()
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["watcher"])
+ self.assertEqual(self.host.deleted_targets(), ["child-2"])
+
+ @async_test
+ async def test_resident_saturated_cap_fails_the_run_instead_of_wedging(self) -> None:
+ # Cursor review finding (PR #3199): with every max_parallel slot held
+ # by resident instances, queued work can never be admitted -- a
+ # resident never settles, so no slot ever frees, _run_complete stays
+ # false, and the residents keep children in flight so the no-in-flight
+ # stall detector never fires. The loop would poll forever; it now
+ # fails the run with a deterministic executor error instead.
+ self.host.outcomes["r1"] = {"status": "running"} # residents never settle
+ self.host.outcomes["r2"] = {"status": "running"}
+ self.store_machine(
+ {
+ "run": {"max_parallel": 1},
+ "states": [
+ {"id": "r1", "entry": True, "subagent": "worker", "lifecycle": "resident"},
+ {"id": "r2", "entry": True, "subagent": "worker", "lifecycle": "resident"},
+ ],
+ "transitions": [],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["r1"]) # the second resident queues behind the cap
+ status = await self.settle(result) # never leaves "running" without the fix
+ self.assertEqual(status["state"], "failed")
+ errors = self.events_of(status, "executor_error")
+ self.assertEqual(len(errors), 1)
+ self.assertEqual(
+ errors[0]["error"],
+ "control loop stalled: resident instances hold every max_parallel 1 slot; "
+ "queued instances can never be admitted",
+ )
+ self.assertIn("failed", self.host.notice_kinds())
+ # The queued resident was never admitted; stop() still cancels its
+ # queued entry and tears the admitted child down.
+ self.assertEqual(self.host.spawn_calls("r2"), [])
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["r1", "r2"])
+ self.assertEqual(self.host.deleted_targets(), ["child-1"])
+
+ @async_test
+ async def test_resident_in_flight_stall_fails_the_run_instead_of_wedging(self) -> None:
+ # Bugbot review finding (PR #3199): the dead-end stall check only ran
+ # with NOTHING in flight, but an admitted resident never settles, so a
+ # pending entry waiting on an input source that never settled kept the
+ # loop polling collect forever (in_flight true, _run_complete false,
+ # _resident_cap_starved false: it sees queued instances, not
+ # unprepared entries). Residents can never unblock a pending entry
+ # (no outputs, no outgoing transitions), so the stall detection must
+ # fire with only resident instances in flight too.
+ self.host.outcomes["watcher"] = {"status": "running"} # residents never settle
+ self.store_machine(
+ {
+ "run": {"failure_policy": "continue"},
+ "states": [
+ {"id": "watcher", "entry": True, "subagent": "worker", "lifecycle": "resident"},
+ {"id": "a", "entry": True, "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "subagent": "worker", "inputs": [{"name": "i", "type": "text", "from": "c.o"}]},
+ {"id": "c", "subagent": "worker", "outputs": [{"name": "o", "type": "text"}]},
+ ],
+ "transitions": [{"from": "a", "to": "b"}],
+ }
+ )
+ result = await self.start()
+ self.assertEqual(result["started"], ["watcher", "a"])
+ status = await self.settle(result) # never leaves "running" without the fix
+ self.assertEqual(status["state"], "failed")
+ self.assertEqual(self.state_report(status, "b")["status"], "pending")
+ stall_events = self.events_of(status, "executor_error")
+ self.assertEqual(len(stall_events), 1)
+ self.assertIn("pending entry of state 'b'", stall_events[0]["error"])
+ self.assertIn("never settled", stall_events[0]["error"])
+ self.assertIn("failed", self.host.notice_kinds())
+ # stop() still tears the resident child down and cancels the stuck
+ # entries; the never-entered source state c reads cancelled too.
+ stopped = await rlm_module.rlm.factory.stop(result["run_id"])
+ self.assertEqual(stopped["cancelled"], ["watcher", "b", "c"])
+ self.assertEqual(self.host.deleted_targets(), ["child-1"])
+
+ @async_test
+ async def test_resume_bumps_the_loop_generation_no_double_admission(self) -> None:
+ # Review finding (resume race): the pause-path control loop can still
+ # be winding down (an in-flight milestone await) when resume() lands.
+ # resume() bumps the loop generation FIRST, so the old loop exits at
+ # its next check instead of continuing as a SECOND concurrent loop.
+ # The admission below is gated mid-spawn so a stale loop that wrongly
+ # continued would re-admit the SAME pending instance (a duplicate
+ # child) while the new loop's admission is still in flight.
+ self.host.outcomes["a"] = {"status": "error", "error": "boom"}
+ self.host.rate_limit_first["b"] = 1 # resume()'s admission defers once
+ progress_gate = self.host.gate("factory.progress", 1)
+ progress_entered = self.host.gate_entered("factory.progress", 1)
+ # rlm.run call #1 is a's admission at run(); #2 is b's first admission
+ # at resume() (rate limited, deferred nonblockingly); the gate holds
+ # call #3 -- the NEW loop's retry admission -- mid-spawn.
+ spawn_gate = self.host.gate("rlm.run", 3)
+ self.store_factory(
+ {
+ "nodes": [
+ {"id": "a", "subagent": "worker"},
+ {"id": "b", "subagent": "worker", "depends_on": ["a"]},
+ ],
+ }
+ )
+ result = await self.start()
+ # a fails: escalate pauses, and the pause-path loop suspends inside
+ # the gated milestone host request (still winding down).
+ await progress_entered.wait()
+ run = self.executor._runs[result["run_id"]]
+ self.assertEqual(run.state, "paused")
+ old_task = run.task
+ self.assertIsNotNone(old_task)
+ self.assertFalse(old_task.done())
+ # resume() bumps the generation, fires a->b, defers b's first
+ # admission (rate limited, nonblocking), and starts the new loop.
+ resumed = await rlm_module.rlm.factory.resume(result["run_id"])
+ self.assertEqual(resumed["state"], "running")
+ self.assertEqual(resumed["started"], [])
+ self.assertIsNot(run.task, old_task)
+ # Releasing the milestone lets the old loop continue: with the
+ # generation bump it must exit without admitting anything (the new
+ # loop owns b, suspended mid-admission at the spawn gate).
+ progress_gate.set()
+ await old_task
+ self.assertTrue(old_task.done())
+ spawn_gate.set()
+ final = await self.settle(result)
+ self.assertEqual(final["state"], "failed")
+ self.assertEqual(self.node_status(final, "b")["status"], "done")
+ # b has exactly two admissions: the deferred one at resume() and
+ # the new loop's successful retry. A stale second loop would admit
+ # it once more while the gated spawn was in flight.
+ self.assertEqual(len(self.host.spawn_calls("b")), 2)
+ self.assertEqual(self.all_events_of(result, "executor_error"), [])
+ self.assertEqual(
+ len([e for e in self.all_events_of(result, "state_entry") if e.get("node") == "b"]), 1
+ )
+
+ @async_test
+ async def test_long_state_ids_spawn_distinct_sibling_names(self) -> None:
+ # Review finding: truncating the state id to 20 characters made two
+ # states sharing a prefix produce the same sibling name, and the
+ # second admission failed the supervisor's unique-name requirement.
+ # The digest token keeps every admission name unique.
+ self.store_machine(
+ {
+ "run": {"max_parallel": 8},
+ "states": [
+ {"id": "collect-findings-pass-one", "entry": True, "subagent": "worker"},
+ {"id": "collect-findings-pass-two", "entry": True, "subagent": "worker"},
+ ],
+ "transitions": [],
+ }
+ )
+ result = await self.start()
+ status = await self.settle(result)
+ self.assertEqual(status["state"], "done")
+ names = [call["kwargs"]["name"] for call in self.host.calls_of("rlm.run")]
+ self.assertEqual(len(names), 2)
+ self.assertNotEqual(names[0], names[1])
+ self.assertTrue(all(name.startswith("sw-collect-findings-") for name in names))
+ self.assertTrue(all(len(name) <= 64 for name in names))
+ # both states ran to completion: neither admission failed
+ self.assertEqual(self.node_status(status, "collect-findings-pass-one")["status"], "done")
+ self.assertEqual(self.node_status(status, "collect-findings-pass-two")["status"], "done")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/prime-agent-runtime/test/test_harness.py b/prime-agent-runtime/test/test_harness.py
index 1b2ed97693..40b05a9e84 100644
--- a/prime-agent-runtime/test/test_harness.py
+++ b/prime-agent-runtime/test/test_harness.py
@@ -12,6 +12,36 @@ from rlm import harness as package_harness
from rlm import rlm as callable_rlm
from rlm.harness import HarnessState, get_harness_state
+# The agent-dir override setUpModule installs: an isolated dir whose
+# settings.json carries the factory opt-in setting.
+_factory_gate_dir: tempfile.TemporaryDirectory | None = None
+_previous_agent_dir: str | None = None
+
+
+def setUpModule() -> None:
+ # The factory opt-in gate refuses every factory write while the
+ # `factory.enabled` setting is off (the default); the harness CRUD tests
+ # exercise the write paths with the setting on, written in the real
+ # settings.json shape the daemon writes. The gate's own refusal pins
+ # live in test_factory.py.
+ global _factory_gate_dir, _previous_agent_dir
+ _factory_gate_dir = tempfile.TemporaryDirectory(prefix="harness_test_agent_dir_")
+ settings = Path(_factory_gate_dir.name) / "settings.json"
+ settings.write_text('{"factory": {"enabled": true}}', encoding="utf-8")
+ _previous_agent_dir = os.environ.get("PRIME_AGENT_CODING_AGENT_DIR")
+ os.environ["PRIME_AGENT_CODING_AGENT_DIR"] = _factory_gate_dir.name
+
+
+def tearDownModule() -> None:
+ global _factory_gate_dir
+ if _previous_agent_dir is None:
+ os.environ.pop("PRIME_AGENT_CODING_AGENT_DIR", None)
+ else:
+ os.environ["PRIME_AGENT_CODING_AGENT_DIR"] = _previous_agent_dir
+ if _factory_gate_dir is not None:
+ _factory_gate_dir.cleanup()
+ _factory_gate_dir = None
+
PYTHON_REFERENCE = {
"type": "python",
"import": "agent_skills.example",
@@ -19,6 +49,23 @@ PYTHON_REFERENCE = {
"call_pattern": "await run(...)",
}
+FACTORY_DAG = {
+ "run": {"failure_policy": "continue", "max_parallel": 2},
+ "nodes": [
+ {
+ "id": "collect",
+ "subagent": "researcher",
+ "outputs": [{"name": "findings", "type": "text"}],
+ },
+ {
+ "id": "review",
+ "subagent": {"prompt": "Review the findings."},
+ "depends_on": ["collect"],
+ "inputs": [{"name": "draft", "type": "text", "from": "collect.findings"}],
+ },
+ ],
+}
+
class HarnessStateTest(unittest.TestCase):
def test_crud_for_all_entry_kinds(self) -> None:
@@ -56,6 +103,14 @@ class HarnessStateTest(unittest.TestCase):
path="subagent/path",
metadata={"kind": "subagent"},
),
+ "factory": state.create_factory(
+ "Factory",
+ "Factory content",
+ id="factory_entry",
+ path="factory/path",
+ dag=FACTORY_DAG,
+ metadata={"kind": "factory"},
+ ),
}
for kind, entry in created.items():
@@ -73,8 +128,9 @@ class HarnessStateTest(unittest.TestCase):
arguments={"target": {"type": "string", "required": True}, "mode": {"type": "string"}},
)
state.update_subagent("subagent_entry", "Subagent", "Subagent content updated")
+ state.update_factory("factory_entry", "Factory", "Factory content updated", dag=FACTORY_DAG)
- for kind in ("prompt", "memory", "skill", "subagent"):
+ for kind in ("prompt", "memory", "skill", "subagent", "factory"):
entry_id = f"{kind}_entry"
self.assertEqual(state.get(kind, entry_id).version, 2)
self.assertIn("updated", state.get(kind, entry_id).content)
@@ -114,14 +170,28 @@ class HarnessStateTest(unittest.TestCase):
outcome="next validation passed",
)
+ factory = state.create_factory(
+ "PR review sweep",
+ "Sweep review across changed files.",
+ id="pr_sweep",
+ dag=FACTORY_DAG,
+ )
+
reloaded = HarnessState(state.file_path)
self.assertEqual(reloaded.get("memory", memory.id).content, memory.content)
self.assertEqual(reloaded.get("skill", skill.id).version, 1)
self.assertEqual(reloaded.get("skill", skill.id).arguments["failure_log"]["type"], "string")
self.assertEqual(reloaded.get("subagent", subagent.id).metadata["max_turns"], 3)
+ self.assertEqual(reloaded.get("factory", factory.id).arguments["dag"], FACTORY_DAG)
self.assertEqual(reloaded.refinements[0].id, event.id)
self.assertIn("Prefer focused patches", reloaded.overview())
+ self.assertIn("factory", reloaded.overview())
+ self.assertIn("await rlm.factory.run", reloaded.overview())
+ self.assertIn("await rlm.factory.status(run_id)", reloaded.overview())
+ self.assertIn("await rlm.factory.stop(run_id)", reloaded.overview())
+ self.assertIn("await rlm.factory.resume(run_id)", reloaded.overview())
+ self.assertIn("create_factory/update_factory/delete_factory", reloaded.overview())
self.assertIn(
"Call contract: installed Python skills use await <skill_import>(...)",
reloaded.overview(),
@@ -134,6 +204,228 @@ class HarnessStateTest(unittest.TestCase):
self.assertIn("receiver_role='child'", overview)
self.assertIn("refinements: 1", reloaded.overview())
+ def test_create_factory_with_invalid_dag_raises_and_does_not_store(self) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+
+ invalid_dags = [
+ None,
+ "not a dag",
+ {"nodes": []},
+ {"nodes": [{"id": "a", "subagent": "w"}, {"id": "a", "subagent": "w"}]},
+ {"nodes": [{"id": "a", "subagent": "w", "depends_on": ["a"]}]},
+ {
+ "nodes": [
+ {"id": "a", "subagent": "w", "outputs": [{"name": "o", "type": "text"}]},
+ {"id": "b", "subagent": "w", "inputs": [{"name": "i", "type": "json", "from": "a.o"}]},
+ ]
+ },
+ ]
+ for index, dag in enumerate(invalid_dags):
+ with self.assertRaises(ValueError, msg=f"dag #{index}") as ctx:
+ state.create_factory("Broken sweep", "Should never store.", id=f"broken_{index}", dag=dag)
+ self.assertTrue(str(ctx.exception).strip())
+
+ self.assertEqual(state.list("factory"), [])
+ for index in range(len(invalid_dags)):
+ self.assertIsNone(state.get("factory", f"broken_{index}"))
+
+ # An invalid dag leaves nothing on disk either.
+ reloaded = HarnessState(state.file_path)
+ self.assertEqual(reloaded.list("factory"), [])
+
+ def test_create_factory_with_valid_dag_stores_arguments_dag(self) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+
+ entry = state.create_factory(
+ "PR review sweep",
+ "Sweep review across changed files.",
+ id="pr_sweep",
+ path="review",
+ dag=FACTORY_DAG,
+ metadata={"owner": "kernel"},
+ )
+
+ self.assertEqual(entry.kind, "factory")
+ self.assertEqual(entry.arguments["dag"], FACTORY_DAG)
+ self.assertEqual(state.get("factory", "pr_sweep").arguments["dag"], FACTORY_DAG)
+ self.assertIn(entry, state.list("factory"))
+
+ reloaded = HarnessState(state.file_path)
+ self.assertEqual(reloaded.get("factory", "pr_sweep").arguments["dag"], FACTORY_DAG)
+
+ def test_create_factory_with_machine_stores_arguments_machine(self) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+ machine = {
+ "states": [
+ {"id": "collect", "entry": True, "subagent": "researcher", "outputs": [{"name": "findings", "type": "text"}]},
+ {
+ "id": "fix",
+ "subagent": {"prompt": "Fix the findings."},
+ "max_entries": 3,
+ "inputs": [{"name": "draft", "type": "text", "from": "collect.findings"}],
+ },
+ ],
+ "transitions": [
+ {"from": "collect", "to": "fix", "when": {"output": "findings", "op": "exists"}},
+ ],
+ }
+
+ entry = state.create_factory("Loop", "Fix-and-review loop.", id="loop", machine=machine)
+
+ self.assertEqual(entry.arguments, {"machine": machine})
+ self.assertEqual(state.get("factory", "loop").arguments["machine"], machine)
+
+ # An invalid machine is rejected exactly like an invalid dag.
+ with self.assertRaises(ValueError):
+ state.create_factory("Broken", "Never stores.", id="broken", machine={"states": [{}]})
+ self.assertIsNone(state.get("factory", "broken"))
+
+ # Supplying both forms at once is a usage error, not a validation one.
+ with self.assertRaisesRegex(ValueError, "not both"):
+ state.create_factory("Both", "Never stores.", id="both", dag=FACTORY_DAG, machine=machine)
+ self.assertIsNone(state.get("factory", "both"))
+
+ def test_update_factory_with_machine_replaces_the_spec(self) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+ state.create_factory("PR review sweep", "Sweep.", id="pr_sweep", dag=FACTORY_DAG)
+
+ machine = {"states": [{"id": "solo", "entry": True, "subagent": "worker"}], "transitions": []}
+ updated = state.update_factory("pr_sweep", "PR review sweep", "Sweep v2.", machine=machine)
+ self.assertEqual(updated.version, 2)
+ self.assertEqual(state.get("factory", "pr_sweep").arguments, {"machine": machine})
+
+ # Omitting both forms still preserves the stored spec.
+ state.update_factory("pr_sweep", "PR review sweep", "Sweep v3.")
+ self.assertEqual(state.get("factory", "pr_sweep").arguments, {"machine": machine})
+
+ with self.assertRaises(ValueError):
+ state.update_factory("pr_sweep", "PR review sweep", "Bad machine.", machine={"states": "nope"})
+ self.assertEqual(state.get("factory", "pr_sweep").content, "Sweep v3.")
+
+ def test_update_factory_without_dag_preserves_stored_dag(self) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+ entry = state.create_factory("PR review sweep", "Sweep review.", id="pr_sweep", dag=FACTORY_DAG)
+ stored_at_create = dict(entry.arguments["dag"])
+
+ updated = state.update_factory("pr_sweep", "PR review sweep", "Sweep review across PRs.")
+
+ self.assertEqual(updated.version, 2)
+ self.assertEqual(state.get("factory", "pr_sweep").arguments["dag"], FACTORY_DAG)
+
+ replacement = {
+ "nodes": [
+ {"id": "solo", "subagent": "worker", "outputs": [{"name": "report", "type": "text"}]}
+ ]
+ }
+ state.update_factory("pr_sweep", "PR review sweep", "Sweep review across PRs.", dag=replacement)
+ self.assertEqual(state.get("factory", "pr_sweep").arguments["dag"], replacement)
+
+ with self.assertRaises(ValueError):
+ state.update_factory("pr_sweep", "PR review sweep", "Bad dag.", dag={"nodes": []})
+ self.assertEqual(state.get("factory", "pr_sweep").arguments["dag"], replacement)
+ # The pre-update snapshot was taken before any replacement landed.
+ self.assertEqual(stored_at_create, FACTORY_DAG)
+
+ def test_delete_factory_removes_the_entry(self) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+ state.create_factory("PR review sweep", "Sweep review.", id="pr_sweep", dag=FACTORY_DAG)
+
+ self.assertTrue(state.delete_factory("pr_sweep"))
+ self.assertIsNone(state.get("factory", "pr_sweep"))
+ self.assertFalse(state.delete_factory("pr_sweep"))
+
+ def test_generic_create_and_update_validate_factory_arguments(self) -> None:
+ # The shared write path must enforce the write-time dry run for every
+ # factory writer, not only create_factory: a generic create/update (a
+ # refinement edit) carrying an invalid spec must raise and never
+ # persist an unusable factory entry.
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+
+ with self.assertRaisesRegex(ValueError, "rejected"):
+ state.create("factory", "Broken", "content", id="broken", arguments={"dag": {"nodes": []}})
+ self.assertEqual(state.list("factory"), [])
+
+ # Neither form at all is rejected with the structural wording.
+ with self.assertRaisesRegex(ValueError, "require a dag or machine object in arguments"):
+ state.create("factory", "Empty", "content", id="empty", arguments={})
+ self.assertEqual(state.list("factory"), [])
+
+ # Both forms at once is rejected with the usage wording.
+ with self.assertRaisesRegex(ValueError, "not both"):
+ state.create(
+ "factory",
+ "Both",
+ "content",
+ id="both",
+ arguments={"dag": FACTORY_DAG, "machine": {"states": [{"id": "s", "entry": True, "subagent": "w"}]}},
+ )
+ self.assertEqual(state.list("factory"), [])
+
+ # A valid spec stores through the generic path, and a generic
+ # update that writes arguments validates the replacement.
+ state.create("factory", "Sweep", "content", id="sweep", arguments={"dag": FACTORY_DAG})
+ with self.assertRaisesRegex(ValueError, "rejected"):
+ state.update("factory", "sweep", "Sweep", "content", arguments={"dag": {"nodes": []}})
+ self.assertEqual(state.get("factory", "sweep").arguments["dag"], FACTORY_DAG)
+
+ # An update that omits arguments preserves the stored spec.
+ state.update("factory", "sweep", "Sweep", "content updated")
+ self.assertEqual(state.get("factory", "sweep").arguments["dag"], FACTORY_DAG)
+
+ # An invalid spec leaves nothing on disk either.
+ reloaded = HarnessState(state.file_path)
+ self.assertEqual(len(reloaded.list("factory")), 1)
+ self.assertIsNone(reloaded.get("factory", "broken"))
+
+ def test_generic_create_factory_without_arguments_is_rejected(self) -> None:
+ # Regression (bot review): a generic create with NO arguments stored
+ # an unusable factory (no dag, no machine) that run() later rejects;
+ # a NEW factory requires its spec (updates may omit it and preserve).
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+
+ with self.assertRaisesRegex(ValueError, "require a dag or machine object in arguments"):
+ state.create("factory", "No spec", "content", id="no_spec")
+ self.assertEqual(state.list("factory"), [])
+ self.assertIsNone(state.get("factory", "no_spec"))
+ reloaded = HarnessState(state.file_path)
+ self.assertEqual(reloaded.list("factory"), [])
+
+ def test_create_factory_deep_copies_the_caller_spec(self) -> None:
+ # Regression (bot review): storing the caller-owned spec by reference
+ # let a later mutation change the live entry without validation (and
+ # an update that omits both forms would then preserve the mutated,
+ # unvalidated spec).
+ with tempfile.TemporaryDirectory() as temp_dir:
+ state = HarnessState(Path(temp_dir) / "harness_state.json")
+ dag = {"nodes": [{"id": "collect", "subagent": "worker"}]}
+ state.create_factory("Sweep", "Sweep review.", id="sweep", dag=dag)
+
+ dag["nodes"] = [] # corrupt the caller-owned dict after creation
+ self.assertEqual(
+ state.get("factory", "sweep").arguments["dag"],
+ {"nodes": [{"id": "collect", "subagent": "worker"}]},
+ )
+ # An update that omits both forms preserves the VALID stored spec,
+ # not the corrupted caller dict.
+ state.update_factory("sweep", "Sweep", "Sweep review across PRs.")
+ self.assertEqual(
+ state.get("factory", "sweep").arguments["dag"],
+ {"nodes": [{"id": "collect", "subagent": "worker"}]},
+ )
+ reloaded = HarnessState(state.file_path)
+ self.assertEqual(
+ reloaded.get("factory", "sweep").arguments["dag"],
+ {"nodes": [{"id": "collect", "subagent": "worker"}]},
+ )
+
def test_save_failure_preserves_previous_state_on_disk(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
state = HarnessState(Path(temp_dir) / "harness_state.json")