A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat/machine library (#3285)
Seth Kartene78f11f5409f
diff --git a/.changes/feat-machine-library.md b/.changes/feat-machine-library.mdnew file mode 100644index 0000000000..8e5db780c0--- /dev/null+++ b/.changes/feat-machine-library.md@@ -0,0 +1,2 @@+- New `prime-agent factory list | import | export` commands manage the machine library of shareable `MACHINE.md` factory templates; the bundled seeds (`builder`, `pr-manager`, `review-sweep`) ship inside the runtime so every install sees them, personal machines live under the agent dir, and an invalid machine never persists.+- `await rlm.factory.run('<name>')` runs a library machine directly without creating a harness entry; a machine that exists but is broken names its exact errors, and an existing export target is refused instead of silently overwritten.diff --git a/crates/pa-cli/src/command_registry.rs b/crates/pa-cli/src/command_registry.rsindex c097c2472e..6772753696 100644--- a/crates/pa-cli/src/command_registry.rs+++ b/crates/pa-cli/src/command_registry.rs@@ -242,6 +242,51 @@ pub const COMMAND_SPECS: &[CommandSpec] = &["Export a saved session to HTML",),CommandSpec::new(&["config"], "config", "Configure package resources"),+ CommandSpec::new(+ &["factory"],+ "factory <list|import|export>",+ "Share and run factory machines from the machine library",+ )+ .description(+ "Machines are MACHINE.md templates (frontmatter plus a fenced machine-spec block) \+resolved from the bundled library shipped inside the runtime, then from the personal \+library under the agent dir. Run one with `await rlm.factory.run(\"<name>\")` from a session.",+ ),+ CommandSpec::new(+ &["factory", "list"],+ "factory list [--json]",+ "List the machine library",+ )+ .description(+ "Lists the bundled machines and the personal machines with their descriptions; \+files that fail the parser skip with a warning.",+ )+ .options(&["--json Print JSON"]),+ CommandSpec::new(+ &["factory", "import"],+ "factory import <path> [--json]",+ "Validate and import a MACHINE.md into the personal library",+ )+ .description(+ "The machine's spec passes the kernel's write-time validator; an invalid spec \+never persists and the exact errors print verbatim.",+ )+ .options(&["--json Print JSON"]),+ CommandSpec::new(+ &["factory", "export"],+ "factory export <name> --out <path> [--json]",+ "Export a machine to a MACHINE.md file",+ )+ .description(+ "Resolves the library machine named <name> (bundled first, then the personal \+library) and copies its MACHINE.md to the output path; an existing target is \+refused, never overwritten.",+ )+ .options(&[+ "--out <path> Destination MACHINE.md path",+ "--json Print JSON",+ ])+ .examples(&["factory export review-sweep --out shared-review-sweep.MACHINE.md"]),CommandSpec::new(&["prompt"],"prompt [--model <selector>] [--cwd <dir>] [--json]",diff --git a/crates/pa-cli/src/factory_command.rs b/crates/pa-cli/src/factory_command.rsnew file mode 100644index 0000000000..be48cb9bc2--- /dev/null+++ b/crates/pa-cli/src/factory_command.rs@@ -0,0 +1,533 @@+//! `prime-agent factory`: the machine library commands.+//!+//! Every subcommand — list included — is one `rlm.factory.cli_dispatch`+//! payload through the kernel Python. The kernel owns the whole library+//! contract: the bundled seeds ship as wheel package data inside the+//! runtime, the personal library lives under the agent dir, the strict+//! MACHINE.md parser gates what lists, and the write-time validator gates+//! what persists (an invalid spec never persists; the exact error+//! sentences reach this command's output verbatim). The CLI never+//! re-implements resolution or parsing, so the two sides cannot drift.++use std::io::Write as _;+use std::path::PathBuf;+use std::process::{Command, Stdio};++use serde_json::{json, Value};++/// One machine as the kernel lists it (`cli_dispatch`'s `list` op).+#[derive(Debug, Clone, PartialEq, serde::Deserialize)]+struct MachineListing {+ name: String,+ description: String,+ #[serde(default)]+ version: String,+ #[serde(default)]+ author: String,+ /// The library level: `repo` (the bundled library) or `user`.+ source: String,+ path: String,+}++/// The thin runner executed by the kernel Python: one JSON payload in on+/// stdin, one JSON result out on stdout (`rlm.factory.cli_dispatch`).+const CLI_DISPATCH_RUNNER: &str = concat!(+ "import json, sys\n",+ "from rlm.factory import cli_dispatch\n",+ "payload = json.loads(sys.stdin.read() or \"{}\")\n",+ "print(json.dumps(cli_dispatch(payload)))\n",+);++/// The parsed `prime-agent factory` invocation.+#[derive(Debug, PartialEq, Eq)]+enum FactoryCommand {+ List {+ json: bool,+ },+ Import {+ path: String,+ json: bool,+ },+ Export {+ name: String,+ out: String,+ json: bool,+ },+}++/// Parse the subcommand and its flags; `Err` carries a usage hint.+fn parse_factory_command(args: &[String]) -> Result<FactoryCommand, String> {+ let children: Vec<&str> = crate::command_registry::get_child_command_specs(&["factory"])+ .into_iter()+ .map(|spec| spec.path[spec.path.len() - 1])+ .collect();+ let Some(subcommand) = args.first() else {+ return Err(String::new());+ };+ if !children.contains(&subcommand.as_str()) {+ let suggestion = crate::command_registry::find_command_suggestion(subcommand, &children);+ return Err(format!(+ "Unknown factory command: {subcommand}{}",+ suggestion.map_or_else(String::new, |s| format!(" (did you mean \"{s}\"?)"))+ ));+ }+ let mut json = false;+ let mut operands: Vec<String> = Vec::new();+ let mut out: Option<String> = None;+ let mut rest = args[1..].iter();+ while let Some(arg) = rest.next() {+ match arg.as_str() {+ "--json" => json = true,+ "--out" => {+ let Some(value) = rest.next() else {+ return Err("--out requires a file path".to_string());+ };+ out = Some(value.clone());+ }+ other if other.starts_with('-') => {+ return Err(format!("unknown option {other:?}"));+ }+ other => operands.push(other.to_string()),+ }+ }+ match subcommand.as_str() {+ "list" => {+ if !operands.is_empty() {+ return Err("Usage: prime-agent factory list [--json]".to_string());+ }+ Ok(FactoryCommand::List { json })+ }+ "import" => {+ if operands.len() != 1 {+ return Err("Usage: prime-agent factory import <path> [--json]".to_string());+ }+ Ok(FactoryCommand::Import {+ path: operands.remove(0),+ json,+ })+ }+ "export" => {+ if operands.len() != 1 {+ return Err(+ "Usage: prime-agent factory export <name> --out <path> [--json]".to_string(),+ );+ }+ let Some(out) = out else {+ return Err(+ "Usage: prime-agent factory export <name> --out <path> [--json]".to_string(),+ );+ };+ Ok(FactoryCommand::Export {+ name: operands.remove(0),+ out,+ json,+ })+ }+ _ => Err(String::new()),+ }+}++/// Run the `factory` command; returns the process exit code.+pub fn run_factory_command(args: &[String]) -> i32 {+ let command = match parse_factory_command(args) {+ Ok(command) => command,+ Err(empty_hint) if empty_hint.is_empty() => {+ eprintln!("Missing factory command.");+ eprintln!("Run \"prime-agent help factory\" for usage.");+ return 1;+ }+ Err(error) => {+ eprintln!("Error: {error}");+ eprintln!("Run `prime-agent help factory` for usage.");+ return 1;+ }+ };+ match command {+ FactoryCommand::List { json } => run_list(json),+ FactoryCommand::Import { path, json } => run_import(&path, json),+ FactoryCommand::Export { name, out, json } => run_export(&name, &out, json),+ }+}++/// The `list` payload: the op alone — the kernel resolves every library+/// directory itself.+fn list_payload() -> Value {+ json!({"op": "list"})+}++/// The `import` payload: the machine file the user pointed at.+fn import_payload(path: &std::path::Path) -> Value {+ json!({+ "op": "import",+ "path": path.display().to_string(),+ })+}++/// The `export` payload: the name and the out target the user chose.+fn export_payload(name: &str, out: &std::path::Path) -> Value {+ json!({+ "op": "export",+ "name": name,+ "out": out.display().to_string(),+ })+}++/// `factory list`: library contents with descriptions.+fn run_list(json: bool) -> i32 {+ let payload = list_payload();+ match resolve_kernel_python().and_then(|python| dispatch_via_kernel(&python, &payload)) {+ Ok(result) => render_list(&result, json),+ Err(error) => {+ eprintln!("Error: {error}");+ 1+ }+ }+}++/// Render one `list` dispatch result: errors verbatim, warnings as+/// warnings, machines as rows (or the whole payload for `--json`).+fn render_list(result: &Value, json: bool) -> i32 {+ if let Some(code) = print_dispatch_errors(result) {+ return code;+ }+ if json {+ println!(+ "{}",+ serde_json::to_string_pretty(result).unwrap_or_default()+ );+ return 0;+ }+ let machines: Vec<MachineListing> = result+ .get("machines")+ .cloned()+ .map(|value| serde_json::from_value(value).unwrap_or_default())+ .unwrap_or_default();+ for warning in result+ .get("warnings")+ .and_then(Value::as_array)+ .map(|warnings| {+ warnings+ .iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ })+ .unwrap_or_default()+ {+ eprintln!("Warning: {warning}");+ }+ if machines.is_empty() {+ println!("No machines in the library.");+ return 0;+ }+ let name_width = machines+ .iter()+ .map(|machine| machine.name.chars().count())+ .max()+ .unwrap_or(0);+ for machine in &machines {+ println!("{}", listing_row(machine, name_width));+ }+ 0+}++fn pad_end(text: &str, width: usize) -> String {+ let length = text.chars().count();+ if length >= width {+ return text.to_string();+ }+ let mut padded = String::from(text);+ padded.extend(std::iter::repeat_n(' ', width - length));+ padded+}++/// Format one listing row (exposed for the unit tests).+#[must_use]+fn listing_row(machine: &MachineListing, name_width: usize) -> String {+ format!(+ "{} {} {}",+ pad_end(&machine.name, name_width),+ machine.source.as_str(),+ machine.description+ )+}++/// Resolve the kernel Python (bootstrapping the venv on first use), the+/// same interpreter the factory gate lives in.+fn resolve_kernel_python() -> Result<PathBuf, String> {+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .map_err(|error| format!("failed to start the CLI runtime: {error}"))?;+ runtime+ .block_on(pa_core::kernel::ensure_kernel_python(+ pa_core::kernel::EnsureKernelPythonOptions::default(),+ ))+ .map_err(|error| format!("kernel python unavailable: {error:#}"))+}++/// Drive one `rlm.factory.cli_dispatch` payload through the kernel Python.+fn dispatch_via_kernel(python: &std::path::Path, payload: &Value) -> Result<Value, String> {+ let mut child = Command::new(python);+ child+ .args(["-c", CLI_DISPATCH_RUNNER])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ // Hidden window on Windows, matching the kernel probes.+ pa_core::platform::process::set_no_window(&mut child);+ let mut child = child+ .spawn()+ .map_err(|error| format!("failed to run the kernel python: {error}"))?;+ {+ let stdin = child.stdin.as_mut().expect("stdin was piped on this child");+ stdin+ .write_all(payload.to_string().as_bytes())+ .map_err(|error| format!("failed to send the payload: {error}"))?;+ }+ let output = child+ .wait_with_output()+ .map_err(|error| format!("failed to wait for the kernel python: {error}"))?;+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ let tail: Vec<&str> = stderr.lines().rev().take(3).collect::<Vec<_>>();+ let mut lines = tail;+ lines.reverse();+ return Err(format!(+ "the kernel python failed (exit {}): {}",+ output.status,+ lines.join(" | ")+ ));+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ serde_json::from_str(stdout.trim_end_matches(['\n', '\r']))+ .map_err(|error| format!("unreadable kernel result: {error}"))+}++/// `factory import <path>`: validate through the kernel gate and persist.+fn run_import(path: &str, json: bool) -> i32 {+ let source = crate::config::expand_tilde_path(path);+ if !source.is_file() {+ eprintln!("Error: machine file not found: {}", source.display());+ return 1;+ }+ let payload = import_payload(&source);+ match resolve_kernel_python().and_then(|python| dispatch_via_kernel(&python, &payload)) {+ Ok(result) => print_dispatch_result(&result, json, "imported"),+ Err(error) => {+ eprintln!("Error: {error}");+ 1+ }+ }+}++/// `factory export <name> --out <path>`: serialize a machine to MACHINE.md.+fn run_export(name: &str, out: &str, json: bool) -> i32 {+ let payload = export_payload(name, &crate::config::expand_tilde_path(out));+ match resolve_kernel_python().and_then(|python| dispatch_via_kernel(&python, &payload)) {+ Ok(result) => print_dispatch_result(&result, json, "exported"),+ Err(error) => {+ eprintln!("Error: {error}");+ 1+ }+ }+}++/// The failed dispatch's error sentences (the validator's exact text,+/// unwrapped from the JSON envelope — printing the `Value` would show the+/// JSON quoting around every sentence).+fn dispatch_error_sentences(result: &Value) -> Vec<&str> {+ result+ .get("errors")+ .and_then(Value::as_array)+ .map(|errors| errors.iter().filter_map(Value::as_str).collect())+ .unwrap_or_default()+}++/// Print a failed dispatch's errors verbatim (the validator's exact+/// sentences); `Some(exit code)` when the result is not an ok-payload.+fn print_dispatch_errors(result: &Value) -> Option<i32> {+ if result.get("ok").and_then(Value::as_bool).unwrap_or(false) {+ return None;+ }+ for error in dispatch_error_sentences(result) {+ eprintln!("Error: {error}");+ }+ Some(1)+}++/// Print one dispatch result: errors verbatim (the validator's exact+/// sentences), or the ok-payload as text or JSON. `verb` is the done-word+/// of the subcommand that ran ("imported" or "exported").+fn print_dispatch_result(result: &Value, json: bool, verb: &str) -> i32 {+ if let Some(code) = print_dispatch_errors(result) {+ return code;+ }+ if json {+ println!(+ "{}",+ serde_json::to_string_pretty(result).unwrap_or_default()+ );+ return 0;+ }+ let name = result+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let path = result+ .get("path")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let source = result.get("source").and_then(Value::as_str);+ if verb == "exported" {+ match source {+ Some(source) => println!("Exported {name} to {path} (from {source})."),+ None => println!("Exported {name} to {path}."),+ }+ } else {+ println!("Imported {name} into {path}.");+ }+ 0+}++#[cfg(test)]+mod tests {+ use super::*;++ fn arg(words: &[&str]) -> Vec<String> {+ words.iter().map(ToString::to_string).collect()+ }++ #[test]+ fn parses_the_three_subcommands() {+ assert_eq!(+ parse_factory_command(&arg(&["list"])),+ Ok(FactoryCommand::List { json: false })+ );+ assert_eq!(+ parse_factory_command(&arg(&["list", "--json"])),+ Ok(FactoryCommand::List { json: true })+ );+ assert_eq!(+ parse_factory_command(&arg(&["import", "/tmp/m.MACHINE.md"])),+ Ok(FactoryCommand::Import {+ path: "/tmp/m.MACHINE.md".to_string(),+ json: false+ })+ );+ assert_eq!(+ parse_factory_command(&arg(&[+ "export",+ "sweep",+ "--out",+ "/tmp/s.MACHINE.md",+ "--json"+ ])),+ Ok(FactoryCommand::Export {+ name: "sweep".to_string(),+ out: "/tmp/s.MACHINE.md".to_string(),+ json: true+ })+ );+ }++ #[test]+ fn rejects_missing_and_unknown_subcommands() {+ assert_eq!(parse_factory_command(&arg(&[])), Err(String::new()));+ let unknown = parse_factory_command(&arg(&["run"]));+ assert!(unknown.is_err());+ assert!(unknown+ .unwrap_err()+ .contains("Unknown factory command: run"));+ let missing_out = parse_factory_command(&arg(&["export", "sweep"]));+ assert!(missing_out.is_err());+ assert!(missing_out+ .unwrap_err()+ .starts_with("Usage: prime-agent factory export"));+ let dangling_out = parse_factory_command(&arg(&["export", "sweep", "--out"]));+ assert!(dangling_out.is_err());+ assert!(dangling_out+ .unwrap_err()+ .starts_with("--out requires a file path"));+ let extra = parse_factory_command(&arg(&["list", "extra"]));+ assert!(extra.is_err());+ }++ #[test]+ fn dispatch_results_print_errors_verbatim() {+ let failure: Value = serde_json::from_str(+ r#"{"ok": false, "errors": ["run max_parallel must be an integer between 1 and 64"]}"#,+ )+ .expect("fixture");+ // Errors go to stderr inside print_dispatch_result; the exit code is the pin.+ assert_eq!(print_dispatch_result(&failure, false, "imported"), 1);+ assert_eq!(render_list(&failure, false), 1);+ // The sentence prints verbatim: unwrapped from the JSON envelope,+ // never with JSON quoting.+ assert_eq!(+ dispatch_error_sentences(&failure),+ ["run max_parallel must be an integer between 1 and 64"]+ );+ }++ #[test]+ fn dispatch_runner_contract_is_the_json_facade() {+ assert!(CLI_DISPATCH_RUNNER.contains("from rlm.factory import cli_dispatch"));+ assert!(CLI_DISPATCH_RUNNER.contains("print(json.dumps(cli_dispatch(payload)))"));+ }++ #[test]+ fn payloads_carry_only_what_the_user_typed() {+ // The kernel resolves every library directory itself, so the+ // payloads carry no directory fields to drift out of sync.+ assert_eq!(list_payload(), serde_json::json!({"op": "list"}));+ assert_eq!(+ import_payload(std::path::Path::new("/tmp/m.MACHINE.md")),+ serde_json::json!({"op": "import", "path": "/tmp/m.MACHINE.md"})+ );+ assert_eq!(+ export_payload("sweep", std::path::Path::new("/tmp/s.MACHINE.md")),+ serde_json::json!({+ "op": "export",+ "name": "sweep",+ "out": "/tmp/s.MACHINE.md",+ })+ );+ }++ #[test]+ fn listing_row_renders_name_source_description() {+ let listing = MachineListing {+ name: "sweep".to_string(),+ description: "A machine that sweeps.".to_string(),+ version: "1".to_string(),+ author: "Tester".to_string(),+ source: "repo".to_string(),+ path: "/machines/sweep/MACHINE.md".to_string(),+ };+ assert_eq!(+ listing_row(&listing, 5),+ "sweep repo A machine that sweeps."+ );+ }++ #[test]+ fn render_list_parses_the_kernel_listing() {+ let result: Value = serde_json::from_str(+ r#"{"ok": true, "machines": [+ {"name": "review-sweep", "description": "Sweep a branch.", "version": "1", "author": "Prime Agent", "source": "repo", "path": "/rlm/machines/review-sweep/MACHINE.md"},+ {"name": "mine", "description": "Personal.", "version": "", "author": "", "source": "user", "path": "/agent/machines/mine/MACHINE.md"}+ ], "warnings": []}"#,+ )+ .expect("fixture");+ // The rows print to stdout; the exit code pins the ok-path.+ assert_eq!(render_list(&result, false), 0);+ assert_eq!(render_list(&result, true), 0);+ }++ #[test]+ fn render_list_exits_cleanly_with_no_machines() {+ let result: Value = serde_json::from_str(r#"{"ok": true, "machines": [], "warnings": []}"#)+ .expect("fixture");+ assert_eq!(render_list(&result, false), 0);+ }+}diff --git a/crates/pa-cli/src/lib.rs b/crates/pa-cli/src/lib.rsindex c79aaf37e3..97d882753c 100644--- a/crates/pa-cli/src/lib.rs+++ b/crates/pa-cli/src/lib.rs@@ -37,6 +37,7 @@ pub(crate) mod daemon_command;pub(crate) mod daemon_discovery;pub(crate) mod daemon_mode;pub(crate) mod daemon_session_list;+pub(crate) mod factory_command;pub(crate) mod file_processor;pub(crate) mod global_flags;pub(crate) mod headless_autonomous;diff --git a/crates/pa-cli/src/public_command.rs b/crates/pa-cli/src/public_command.rsindex 6c6f31ef21..98f60de310 100644--- a/crates/pa-cli/src/public_command.rs+++ b/crates/pa-cli/src/public_command.rs@@ -180,6 +180,7 @@ pub fn handle_public_command(args: &[String]) -> PublicCommandResult {"model" => rewrite_nested_command("model", "list", "--list-models", &rest),"session" => rewrite_nested_command("session", "export", "--export", &rest),"prompt" => handled_with_exit(crate::prompt_command::run_prompt_command(&rest)),+ "factory" => handled_with_exit(crate::factory_command::run_factory_command(&rest)),"config" => {if !rest.is_empty() {return fail(format!("Usage: {APP_NAME} config"), None);diff --git a/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs b/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rsindex f8e8006b90..000f70c314 100644--- a/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs+++ b/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs@@ -49,10 +49,12 @@ pub(super) fn resolve_runtime_source_dir() -> Option<PathBuf> {.find(|candidate| candidate.join("pyproject.toml").exists())}-/// Content identity of the runtime: a hash of every `rlm/*.py` file plus-/// `pyproject.toml`, so any runtime change invalidates an existing venv.-/// Falls back to the bare package name when the runtime resolves to a-/// registry install (no local source).+/// Content identity of the runtime: a hash of every `rlm/*.py` file, the+/// packaged machine library under `src/rlm/machines` (wheel package data:+/// machine changes are runtime changes), and `pyproject.toml`, so any+/// runtime change invalidates an existing venv. Falls back to the bare+/// package name when the runtime resolves to a registry install (no local+/// source).////// # Panics///@@ -75,6 +77,7 @@ fn hash_runtime_source(source_dir: &Path) -> anyhow::Result<String> {let rlm_dir = source_dir.join("src").join("rlm");let mut files = vec![source_dir.join("pyproject.toml")];collect_python_files(&rlm_dir, &mut files)?;+ collect_package_data_files(&rlm_dir.join("machines"), &mut files)?;files.sort();let mut hasher = sha2::Sha256::new();for file in &files {@@ -99,3 +102,73 @@ pub(super) fn collect_python_files(dir: &Path, files: &mut Vec<PathBuf>) -> anyh}Ok(())}++/// Collect every file under the packaged machine library (`src/rlm/machines`,+/// any extension: the wheel ships the MACHINE.md files as package data), so+/// machine changes invalidate an existing venv exactly like a `.py` change.+fn collect_package_data_files(dir: &Path, files: &mut Vec<PathBuf>) -> anyhow::Result<()> {+ if !dir.is_dir() {+ return Ok(()); // a runtime payload without a machine library is legal+ }+ for entry in std::fs::read_dir(dir)? {+ let entry = entry?;+ let path = entry.path();+ if path.is_dir() {+ collect_package_data_files(&path, files)?;+ } else {+ files.push(path);+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn runtime_fixture(temp: &std::path::Path, machine_body: &str) -> anyhow::Result<()> {+ let rlm = temp.join("src").join("rlm");+ std::fs::create_dir_all(&rlm)?;+ std::fs::write(+ rlm.join("factory.py"),+ "X = 1+",+ )?;+ let machines = rlm.join("machines").join("review-sweep");+ std::fs::create_dir_all(&machines)?;+ std::fs::write(machines.join("MACHINE.md"), machine_body)?;+ std::fs::write(+ temp.join("pyproject.toml"),+ "[project]+",+ )?;+ Ok(())+ }++ #[test]+ fn machine_library_changes_invalidate_the_runtime_identity() -> anyhow::Result<()> {+ let temp = tempfile::tempdir()?;+ runtime_fixture(+ temp.path(),+ "---+name: review-sweep+",+ )?;+ let before = hash_runtime_source(temp.path())?;+ runtime_fixture(+ temp.path(),+ "---+name: review-sweep+version: 2+",+ )?;+ let after = hash_runtime_source(temp.path())?;+ assert_ne!(before, after, "a machine file change is a runtime change");++ // A runtime without the machine library still hashes cleanly.+ std::fs::remove_dir_all(temp.path().join("src").join("rlm").join("machines"))?;+ let bare = hash_runtime_source(temp.path())?;+ assert_ne!(bare, after);+ Ok(())+ }+}diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 0836e9513c..05fd634014 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -538,14 +538,23 @@ class _RLMFactoryNamespace:memory only; children stay supervisor-owned. Every call is async, soalways await it: ``await rlm.factory.run('<id>')``.+ When no stored entry carries the id, ``run`` falls back to the machine+ library: the bundled seeds ship inside the runtime (the personal+ library lives under the agent dir), and the template runs directly+ without creating a harness entry:+ ``await rlm.factory.run('review-sweep')``.+ ``prime-agent factory list | import | export`` manages the library (a+ broken machine names its exact errors; a missing one lists what the+ library has).+The factory is opt-in: while the ``factory.enabled`` setting is off (thedefault; the user turns it on with ``/factory on``), every call aboverefuses with one clean message and only ``help()`` answers, so theguide 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()``.+ (states, ports, guards, joins, foreach, budgets, the machine library,+ and the API with worked examples): ``rlm.factory.help()``."""async def run(self, spec_id: str, *, name: str | None = None) -> dict[str, Any]:diff --git a/prime-agent-runtime/src/rlm/factory.py b/prime-agent-runtime/src/rlm/factory.pyindex 2bfc2e86ee..e49bcb6d81 100644--- a/prime-agent-runtime/src/rlm/factory.py+++ b/prime-agent-runtime/src/rlm/factory.py@@ -44,9 +44,11 @@ import copyimport hashlibimport heapqimport json+import osimport reimport timefrom dataclasses import dataclass, field+from pathlib import Pathfrom typing import Any, Callablefrom uuid import uuid4@@ -898,16 +900,30 @@ __all__ = ["FACTORY_HELP","FactoryExecutor","FactoryRun",+ "MachineFile",+ "MachineResolutionError","canonicalize_factory_spec",+ "cli_dispatch","compile_factory_dag","default_factory_executor",+ "export_factory_spec",+ "export_library_machine",+ "export_machine","factory_enabled",+ "import_machine",+ "list_machines",+ "machine_library_dirs",+ "parse_machine_file",+ "render_machine_file",+ "repo_machines_dir","require_factory_enabled",+ "resolve_machine","resume_factory","run_factory","status_factory","stop_factory","topological_order",+ "user_machines_dir","validate_factory_machine","validate_factory_spec",]@@ -1263,6 +1279,10 @@ class FactoryRun:run_id: strspec_id: strname: str | None+ # The canonicalized machine this run executes: a stored entry's spec or a+ # library machine's template, kept so export_machine can serialize the+ # exact machine a run is running (byte-pretty, stable formatting).+ machine: "dict[str, Any]" = field(default_factory=dict)state: str = "running" # running | stopping | paused | done | failed | stoppedstarted_at: float = 0.0max_parallel: int = RUN_MAX_PARALLEL_DEFAULT@@ -1369,6 +1389,40 @@ class FactoryExecutor:if reference_errors:raise ValueError("; ".join(reference_errors))run = self._create_run(entry.id, canonical, resolved, name=name)+ return await self._launch_run(run)++ async def run_machine(+ self, machine: MachineFile, *, machine_path: Path | None = None, name: str | None = None+ ) -> dict[str, Any]:+ """Validate a library machine and start a run of it.++ Harness entries remain runtime instances; machines in the library+ are templates, so a library run never creates one. The machine's+ spec goes through the same validation and canonicalization as a+ stored entry's (``canonicalize_factory_spec``), the run records the+ machine's name as its spec id, and the result reports the machine+ fields so a caller can trace the run back to the library file.+ """+ canonical = canonicalize_factory_spec(machine.spec)+ harness = self._resolve_harness()+ resolved, reference_errors = self._resolve_subagents(harness, canonical)+ if reference_errors:+ raise ValueError("; ".join(reference_errors))+ run = self._create_run(machine.name, canonical, resolved, name=name)+ result = await self._launch_run(run)+ result["machine"] = machine.name+ if machine_path is not None:+ result["machine_path"] = str(machine_path)+ return result++ async def _launch_run(self, run: FactoryRun) -> dict[str, Any]:+ """Register a run, enter its entry states, and start the control loop.++ Shared by ``run`` (stored entries) and ``run_machine`` (library+ machines): both validate first, so this never sees an invalid+ spec. Nonblocking: admission enters every entry state up to+ ``max_parallel`` and returns; a background task continues the run.+ """self._runs[run.run_id] = runself._event(run, "run_started", detail=f"{len(run.states)} states, max_parallel {run.max_parallel}"@@ -1386,8 +1440,8 @@ class FactoryExecutor:self._start_loop(run)return {"run_id": run.run_id,- "spec_id": entry.id,- "name": name,+ "spec_id": run.spec_id,+ "name": run.name,"nodes": len(run.states),"max_parallel": run.max_parallel,"started": started,@@ -1593,6 +1647,7 @@ class FactoryExecutor:run_id=uuid4().hex,spec_id=spec_id,name=name,+ machine=canonical,started_at=self._now_fn(),max_parallel=run_spec["max_parallel"],max_transitions=run_spec["max_transitions"],@@ -2773,9 +2828,43 @@ def default_factory_executor() -> FactoryExecutor: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."""+ """Validate a factory spec and start a nonblocking run of it.++ The argument names a stored factory entry (a runtime instance) first;+ when no entry carries that id, it resolves a machine from the library+ (repo directory first, user second) and runs the template directly:+ ``await rlm.factory.run("review-sweep")`` starts the library machine+ without creating a harness entry. Harness entries remain runtime+ instances; machines are templates.+ """require_factory_enabled()- return await default_factory_executor().run(spec_id, name=name)+ executor = default_factory_executor()+ harness = executor._resolve_harness()+ if harness.get("factory", spec_id) is None:+ try:+ machine, path = resolve_machine(spec_id)+ except MachineResolutionError as error:+ if error.broken:+ raise ValueError(+ f"the library machine {spec_id!r} exists but is broken ({error})"+ ) from None+ raise ValueError(+ f"unknown factory spec {spec_id!r}: no stored factory entry and "+ f"no library machine with that name ({error})"+ ) from None+ except ValueError as error:+ # An id that is not a legal machine name (spaces, capitals) can+ # never resolve from the library either; the unknown-spec frame+ # must not lose the lookup to the name-rule sentence. Only the+ # name-rule error can arrive here: every library-file failure+ # (unreadable, non-UTF-8, unparseable, spec-invalid) is a+ # MachineResolutionError in the first except arm.+ raise ValueError(+ f"unknown factory spec {spec_id!r}: no stored factory entry, and "+ f"the id is not a valid machine name either ({error})"+ ) from None+ return await executor.run_machine(machine, machine_path=path, name=name)+ return await executor.run(spec_id, name=name)async def status_factory(run_id: str) -> dict[str, Any]:@@ -2796,6 +2885,794 @@ async def resume_factory(run_id: str) -> dict[str, Any]:return await default_factory_executor().resume(run_id)+# ---------------------------------------------------------------------------+# Machine library: MACHINE.md files (import, export, share).+#+# A MACHINE.md is the shareable unit of the machine library, mirroring the+# SKILL.md/skills conventions: YAML frontmatter (name, description, version,+# author) followed by one fenced ``machine-spec`` block whose payload is a+# JSON factory spec in the exact schema ``validate_factory_spec`` accepts+# (machine form, or dag sugar that compiles to one) -- no new spec parser.+# The library resolves from two levels, repo first, user second:+#+# - repo: the bundled machines shipped INSIDE the runtime package+# (``src/rlm/machines/<name>/MACHINE.md``, wheel package data, so every+# installed kernel sees the same seeds a checkout does);+# ``PRIME_AGENT_MACHINES_DIR`` redirects the level at a team directory.+# - user: ``<agent dir>/machines/<name>/MACHINE.md`` (personal machines).+#+# ``import_machine`` is the library's gate: it parses the file, passes the+# spec through the SAME write-time validator as every factory write (an+# invalid spec never persists, with exact user-correctable errors), then+# writes the file verbatim into the user library so its documentation+# travels with the spec. ``export_machine`` serializes a library machine, a+# stored factory entry's spec, or a run's canonical machine back to+# MACHINE.md (byte-pretty, stable formatting for diffs). Harness entries+# remain runtime instances; machines in the library are templates, so+# ``run_factory`` falls back to the library when its argument names no+# stored entry: ``await rlm.factory.run("review-sweep")``.+# ---------------------------------------------------------------------------++MACHINE_FILE_NAME = "MACHINE.md"+MACHINE_SPEC_FENCE = "machine-spec"+MACHINES_DIR_NAME = "machines"+MACHINE_NAME_MAX_LENGTH = 64+MACHINE_DESCRIPTION_MAX_LENGTH = 1024+MACHINE_FRONTMATTER_FIELDS: tuple[str, ...] = ("name", "description", "version", "author")++_MACHINE_NAME_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]*")+_PLAIN_FRONTMATTER_VALUE = re.compile(r"[A-Za-z0-9][A-Za-z0-9 ._/@+~-]*")+++def machine_name_errors(name: Any) -> list[str]:+ """Name rules mirrored from the skill library (validate_name)."""+ if not isinstance(name, str) or not name:+ return ["machine name must be a non-empty string"]+ errors: list[str] = []+ if len(name) > MACHINE_NAME_MAX_LENGTH:+ errors.append(f"machine name exceeds {MACHINE_NAME_MAX_LENGTH} characters ({len(name)})")+ if _MACHINE_NAME_PATTERN.fullmatch(name) is None:+ errors.append(+ "machine name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)"+ )+ if name.endswith("-"):+ errors.append("machine name must not end with a hyphen")+ return errors+++def machine_description_errors(description: Any) -> list[str]:+ """Description rules mirrored from the skill library (validate_description).++ One rule is the library's own: the description is one listing row, so+ embedded line breaks are a format error.+ """+ if not isinstance(description, str) or not description.strip():+ return ["frontmatter description is required"]+ if len(description) > MACHINE_DESCRIPTION_MAX_LENGTH:+ return [+ "frontmatter description exceeds "+ f"{MACHINE_DESCRIPTION_MAX_LENGTH} characters ({len(description)})"+ ]+ if "\n" in description or "\r" in description:+ return ["frontmatter description must be a single line"]+ return []+++def _unquote_frontmatter_value(raw: str, field: str) -> "tuple[str | None, str | None]":+ """Unquote one frontmatter value: plain, single-quoted, or double-quoted.++ Plain values must stay YAML-safe (no colon anywhere), so a rendered+ value always parses back identically.+ """+ value = raw.strip()+ if len(value) >= 2 and value[0] == '"' and value[-1] == '"':+ try:+ unquoted = json.loads(value)+ except ValueError as error:+ return None, f"frontmatter {field} has an invalid double-quoted value ({error})"+ if not isinstance(unquoted, str):+ return None, f"frontmatter {field} must be a string scalar"+ return unquoted, None+ if len(value) >= 2 and value[0] == "'" and value[-1] == "'":+ return value[1:-1].replace("''", "'"), None+ if ":" in value:+ return (+ None,+ f"frontmatter {field} is not a plain scalar (quote the value to include ':' characters)",+ )+ return value, None+++def _parse_machine_frontmatter(+ text: str, *, source: str+) -> "tuple[dict[str, str] | None, str, list[str]]":+ """Parse the strict frontmatter subset MACHINE.md allows.++ The subset is deliberately narrower than full YAML: one ``key: value``+ line per field, the four machine fields only, quoted values for+ anything that is not a plain scalar. The error sentences are the+ import gate's user-correctable surface. Returns+ ``(fields, body, [])`` on success or ``(None, "", errors)``.+ """+ normalized = text.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n")+ lines = normalized.split("\n")+ if not lines or lines[0].rstrip() != "---":+ return None, "", [f"{source}: MACHINE.md must start with a `---` frontmatter block"]+ fields: dict[str, str] = {}+ errors: list[str] = []+ close_index: int | None = None+ for index in range(1, len(lines)):+ line = lines[index].rstrip()+ if line == "---":+ close_index = index+ break+ if not line.strip():+ errors.append(f"{source}: frontmatter line {index + 1} is empty (one `key: value` line per field)")+ continue+ key, separator, raw_value = line.partition(":")+ if not separator:+ errors.append(f"{source}: frontmatter line {index + 1} must be `key: value`")+ continue+ key = key.strip()+ if key not in MACHINE_FRONTMATTER_FIELDS:+ errors.append(+ f"{source}: unknown frontmatter key {key!r} "+ f"(allowed: {', '.join(MACHINE_FRONTMATTER_FIELDS)})"+ )+ continue+ if key in fields:+ errors.append(f"{source}: frontmatter field {key!r} is declared more than once")+ continue+ if not raw_value.strip():+ errors.append(f"{source}: frontmatter field {key!r} requires a value")+ continue+ unquoted, error = _unquote_frontmatter_value(raw_value, key)+ if error is not None:+ errors.append(f"{source}: {error}")+ continue+ assert unquoted is not None+ fields[key] = unquoted+ if close_index is None:+ return None, "", [f"{source}: frontmatter is not closed (end it with a `---` line)"]+ body = "\n".join(lines[close_index + 1 :])+ if errors:+ return None, "", errors+ return fields, body, []+++def _extract_machine_spec_blocks(body: str, *, source: str) -> "tuple[str | None, list[str]]":+ """Return the single fenced ``machine-spec`` payload from the body.++ Other fenced blocks (prose examples, JSON listings) are skipped as+ opaque units: their content never participates in the fence scan.+ """+ lines = body.split("\n")+ contents: list[str] = []+ index = 0+ while index < len(lines):+ line = lines[index].rstrip()+ if not line.lstrip().startswith("```"):+ index += 1+ continue+ open_index = index+ info = line.strip()[3:].strip()+ index += 1+ content_lines: list[str] = []+ closed = False+ while index < len(lines):+ fence_line = lines[index].rstrip()+ if fence_line == "```":+ closed = True+ index += 1+ break+ content_lines.append(lines[index])+ index += 1+ if info != MACHINE_SPEC_FENCE:+ if not closed:+ return None, [f"{source}: the ```{info} fence opened at line {open_index + 1} is never closed"]+ continue+ if not closed:+ return None, [f"{source}: the ```{MACHINE_SPEC_FENCE} fence is never closed"]+ contents.append("\n".join(content_lines))+ if not contents:+ return None, [+ f"{source}: MACHINE.md requires exactly one fenced ```{MACHINE_SPEC_FENCE} block; found none"+ ]+ if len(contents) > 1:+ return None, [+ f"{source}: MACHINE.md requires exactly one fenced ```{MACHINE_SPEC_FENCE} block; "+ f"found {len(contents)}"+ ]+ return contents[0], []+++@dataclass(frozen=True)+class MachineFile:+ """A parsed MACHINE.md: strict frontmatter plus the machine-spec payload."""++ name: str+ description: str+ version: str+ author: str+ spec: "dict[str, Any]"+++def parse_machine_file(text: str, *, source: str = "machine file") -> "tuple[MachineFile | None, list[str]]":+ """Parse one MACHINE.md. Returns ``(machine, [])`` or ``(None, errors)``.++ This owns the FILE format only (frontmatter, fence, JSON payload); the+ spec stays in the existing validated schema, and the import and run+ gates pass it through ``validate_factory_spec`` separately.+ """+ fields, body, errors = _parse_machine_frontmatter(text, source=source)+ if fields is None:+ return None, errors+ payload, errors = _extract_machine_spec_blocks(body, source=source)+ if errors:+ return None, errors+ assert payload is not None+ try:+ spec = json.loads(payload)+ except ValueError as error:+ return None, [+ f"{source}: the ```{MACHINE_SPEC_FENCE} block must contain a JSON object ({error})"+ ]+ if not isinstance(spec, dict):+ return None, [+ f"{source}: the ```{MACHINE_SPEC_FENCE} block must contain a JSON object, "+ f"got a {type(spec).__name__}"+ ]+ name = fields.get("name", "")+ errors = machine_name_errors(name)+ errors.extend(machine_description_errors(fields.get("description")))+ if errors:+ return None, errors+ return (+ MachineFile(+ name=name,+ description=fields["description"],+ version=fields.get("version", ""),+ author=fields.get("author", ""),+ spec=spec,+ ),+ [],+ )+++def _render_frontmatter_value(value: str) -> str:+ """Render one frontmatter value: plain when YAML-safe, else double-quoted."""+ if _PLAIN_FRONTMATTER_VALUE.fullmatch(value) is not None:+ return value+ return json.dumps(value, ensure_ascii=False)+++def _machine_contract_lines(spec: "dict[str, Any]") -> list[str]:+ """Deterministic contract prose generated from the spec (both forms)."""+ lines: list[str] = []+ run = spec.get("run")+ if isinstance(run, dict):+ parts = [+ f"failure_policy={run.get('failure_policy')}",+ f"max_parallel={run.get('max_parallel')}",+ ]+ if "budget_ms" in run:+ parts.append(f"budget_ms={run['budget_ms']}")+ if "max_transitions" in run:+ parts.append(f"max_transitions={run['max_transitions']}")+ lines.append("Run: " + ", ".join(parts))+ states = spec.get("states") if isinstance(spec.get("states"), list) else spec.get("nodes")+ if not isinstance(states, list):+ return lines+ lines.append("")+ lines.append("States:")+ for state in states:+ if not isinstance(state, dict):+ continue+ flags = []+ if state.get("entry"):+ flags.append("entry")+ for key in ("lifecycle", "max_entries", "retries", "failure_policy", "budget_ms"):+ if key in state:+ flags.append(f"{key}={state[key]}")+ label = f"- {state.get('id')}"+ if flags:+ label += f" ({', '.join(flags)})"+ lines.append(label)+ subagent = state.get("subagent")+ if isinstance(subagent, dict):+ settings = subagent.get("name") or subagent.get("prompt", "")[:60]+ lines.append(f" subagent: inline ({settings})")+ elif isinstance(subagent, str):+ lines.append(f" subagent: {subagent}")+ for inp in state.get("inputs") or []:+ if isinstance(inp, dict):+ optional = " [optional]" if inp.get("optional") else ""+ lines.append(+ f" input: {inp.get('name')} ({inp.get('type')}) <- {inp.get('from')}{optional}"+ )+ for out in state.get("outputs") or []:+ if isinstance(out, dict):+ lines.append(f" output: {out.get('name')} ({out.get('type')})")+ foreach = state.get("foreach")+ if isinstance(foreach, dict):+ lines.append(f" foreach: over {foreach.get('over')}, max {foreach.get('max')}")+ transitions = spec.get("transitions")+ if isinstance(transitions, list):+ lines.append("")+ lines.append("Transitions:")+ for transition in transitions:+ if not isinstance(transition, dict):+ continue+ raw_from = transition.get("from")+ if isinstance(raw_from, list):+ source_text = "[" + ", ".join(str(item) for item in raw_from) + "]"+ else:+ source_text = str(raw_from)+ guard = transition.get("when")+ guard_text = ""+ if isinstance(guard, dict):+ port = guard.get("output")+ path = guard.get("path")+ target = f"{port}.{path}" if path else str(port)+ guard_text = f" when {target} {guard.get('op')} {json.dumps(guard.get('value'))}"+ lines.append(f"- {source_text} -> {transition.get('to')}{guard_text}")+ return lines+++def render_machine_file(machine: MachineFile) -> str:+ """Render a MachineFile back to canonical MACHINE.md text.++ Byte-stable: the same machine always renders to the same bytes (stable+ formatting for diffs), and ``parse_machine_file`` of the output+ recovers the same machine.+ """+ frontmatter = [+ "---",+ f"name: {_render_frontmatter_value(machine.name)}",+ f"description: {_render_frontmatter_value(machine.description)}",+ f"version: {_render_frontmatter_value(machine.version)}",+ f"author: {_render_frontmatter_value(machine.author)}",+ "---",+ ]+ sections = [+ "\n".join(frontmatter),+ "",+ f"# {machine.name}",+ "",+ "## Machine contract",+ "",+ ]+ sections.extend(_machine_contract_lines(machine.spec))+ sections.append("")+ sections.append(f"```{MACHINE_SPEC_FENCE}")+ sections.append(json.dumps(machine.spec, indent=2, ensure_ascii=False))+ sections.append("```")+ return "\n".join(sections) + "\n"+++def _machine_env_dir(name: str) -> str | None:+ # Set-but-empty env values behave as unset (mirrors harness._env_dir).+ value = (os.environ.get(name) or "").strip()+ return value or None+++def repo_machines_dir() -> Path:+ """The bundled machine library shipped inside the runtime package.++ An explicit ``PRIME_AGENT_MACHINES_DIR`` wins (a team can point the+ shared level at their own directory); otherwise the library resolves+ relative to this module — ``src/rlm/machines`` in a checkout, exactly+ the wheel-package data a kernel venv installs into+ ``site-packages/rlm/machines`` — so an installed kernel sees the same+ seeds a checkout does, with no source-tree walk-up that could pick up+ a stray directory above an installed venv.+ """+ override = _machine_env_dir("PRIME_AGENT_MACHINES_DIR")+ if override:+ return Path(override).expanduser().resolve()+ return Path(__file__).resolve().parent / MACHINES_DIR_NAME+++def user_machines_dir() -> Path:+ """The personal machines directory (``<agent dir>/machines``)."""+ raw = (+ _machine_env_dir("PRIME_AGENT_CODING_AGENT_DIR")+ or _machine_env_dir("PI_CODING_AGENT_DIR")+ or str(Path.home() / ".prime" / "agent")+ )+ return Path(raw).expanduser().resolve() / MACHINES_DIR_NAME+++def machine_library_dirs(+ *, repo_dir: "str | Path | None" = None, user_dir: "str | Path | None" = None+) -> "list[tuple[str, Path]]":+ """Library levels in resolution order: repo first, user second.++ Both levels always exist (the repo level is the packaged library;+ the user level is the personal directory under the agent dir); a+ missing directory is simply empty, so listing and resolving skip it.+ """+ repo = Path(repo_dir).expanduser() if repo_dir is not None else repo_machines_dir()+ user = Path(user_dir).expanduser() if user_dir is not None else user_machines_dir()+ return [("repo", repo), ("user", user)]+++def _read_library_machine(path: Path) -> "tuple[MachineFile | None, str]":+ """One library file's validity verdict, shared by scan and resolve.++ The four gates both surfaces apply — read, decode, the file format's+ strict parser, the write-time spec validator — in one helper, so+ `factory list` and `resolve_machine` can never disagree: a file+ invalid here is never listed as usable and never claims its name at+ resolve time. Returns ``(machine, "")`` when the file parses and+ validates, ``(None, "<path>: <exact errors>")`` when it fails to read,+ decode, or parse, and ``(machine, "<path>: <exact spec errors>")``+ when it parses but its spec fails the validator (the machine rides+ along so resolve can tell which name the file carries).+ """+ try:+ text = path.read_text(encoding="utf-8")+ except OSError as error:+ return None, f"{path}: unreadable ({error})"+ except UnicodeDecodeError as error:+ return None, f"{path}: not valid UTF-8 ({error})"+ machine, errors = parse_machine_file(text, source=str(path))+ if machine is None or errors:+ return None, f"{path}: {'; '.join(errors)}"+ spec_errors = validate_factory_spec(machine.spec)+ if spec_errors:+ return machine, f"{path}: {'; '.join(spec_errors)}"+ return machine, ""+++def _scan_machine_library(+ *, repo_dir: "str | Path | None" = None, user_dir: "str | Path | None" = None+) -> "tuple[list[dict[str, Any]], list[str]]":+ """One pass over both levels: the listed machines and broken-file+ warnings (``<path>: <errors>``).++ The shared scan behind ``list_machines`` and the CLI's ``factory list``:+ both levels resolve identically, repo wins on name conflicts, and the+ gates are ``_read_library_machine`` — the same verdict+ ``resolve_machine`` applies, so a machine the listing shows always+ parses and validates for resolve/run/import, while the files it skips+ surface as warnings here and never claim their name on the resolve+ surface either (their exact errors surface there only when no valid+ machine carries the name).+ """+ machines: dict[str, dict[str, Any]] = {}+ warnings: list[str] = []+ for source, directory in machine_library_dirs(repo_dir=repo_dir, user_dir=user_dir):+ if not directory.is_dir():+ continue+ for path in sorted(directory.glob(f"*/{MACHINE_FILE_NAME}")):+ machine, error = _read_library_machine(path)+ if error:+ warnings.append(error)+ continue+ if machine.name in machines:+ continue # repo first: the earlier level keeps the name+ machines[machine.name] = {+ "name": machine.name,+ "description": machine.description,+ "version": machine.version,+ "author": machine.author,+ "source": source,+ "path": str(path),+ }+ return [machines[name] for name in sorted(machines)], warnings+++def list_machines(+ *, repo_dir: "str | Path | None" = None, user_dir: "str | Path | None" = None+) -> "list[dict[str, Any]]":+ """Library contents with descriptions, resolution-deduped (repo wins).++ Broken files are skipped silently here (the agent-facing list);+ ``cli_dispatch``'s ``list`` op surfaces them as warnings so the CLI's+ ``factory list`` can say why a machine does not show.+ """+ return _scan_machine_library(repo_dir=repo_dir, user_dir=user_dir)[0]+++class MachineResolutionError(ValueError):+ """One library lookup failure, with its kind.++ ``broken`` distinguishes the two outcomes a caller must not blur: the+ name's only carriers are machine files that failed to parse or+ validate (the first file's errors say why) versus no machine carrying+ the name at all.+ """++ def __init__(self, message: str, *, broken: bool) -> None:+ super().__init__(message)+ self.broken = broken+++def resolve_machine(+ name: str,+ *,+ repo_dir: "str | Path | None" = None,+ user_dir: "str | Path | None" = None,+) -> "tuple[MachineFile, Path]":+ """Resolve one machine by name: repo directory first, user second.++ The fast path reads ``<dir>/<name>/MACHINE.md`` directly, but only+ serves what passes ``_read_library_machine`` — the SAME validity+ verdict the listing scan applies — and only when its DECLARED name+ matches: a directory named ``x`` holding ``name: y`` is not the+ machine ``x`` (the declared name is the machine's name); such a file+ resolves only through the scan below, under its declared name like it+ does in the skill library. A file that fails to read, decode, or+ parse, or carries a spec the write-time validator rejects, never+ claims its name on either surface: resolution falls through to the+ next level exactly like the listing does, so `factory list`,+ ``rlm.factory.run``, and export can never disagree about a name. A+ name whose only carriers are invalid files raises+ ``MachineResolutionError`` with ``broken=True`` and the first file's+ exact errors (in repo-to-user order) — broken, never missing; a name+ no machine carries raises it with ``broken=False``.+ """+ errors = machine_name_errors(name)+ if errors:+ raise ValueError("; ".join(errors))+ broken: str | None = None+ for _source, directory in machine_library_dirs(repo_dir=repo_dir, user_dir=user_dir):+ path = directory / str(name) / MACHINE_FILE_NAME+ if not path.is_file():+ continue+ machine, file_error = _read_library_machine(path)+ if file_error:+ # The same verdict the listing scan applied: an invalid file+ # does not claim the name, so the next level gets its chance.+ # Keep the broken frame only for a file that carries the name+ # — one that fails outright (machine is None) or declares+ # this name — because a file declaring another name never+ # carried this one.+ if broken is None and (machine is None or machine.name == name):+ broken = file_error+ continue+ if machine.name == name:+ return machine, path+ listed = list_machines(repo_dir=repo_dir, user_dir=user_dir)+ for entry in listed:+ if entry["name"] == name:+ machine, parse_errors = parse_machine_file(+ Path(entry["path"]).read_text(encoding="utf-8"), source=entry["path"]+ )+ if machine is None or parse_errors:+ raise MachineResolutionError("; ".join(parse_errors), broken=True)+ return machine, Path(entry["path"])+ if broken is not None:+ raise MachineResolutionError(broken, broken=True)+ listing = ", ".join(entry["name"] for entry in listed)+ raise MachineResolutionError(+ f"unknown machine {name!r}: no MACHINE.md for it in the machine library (machines: {listing or 'none'})",+ broken=False,+ )+++def import_machine(path: "str | Path", *, target_dir: "str | Path | None" = None) -> "dict[str, Any]":+ """The library gate: parse a MACHINE.md, validate its spec, persist it.++ The spec goes through the SAME write-time validator as every factory+ write (``validate_factory_spec``): an invalid spec never persists, and+ the ``ValueError`` carries every error sentence, so the surface stays+ user-correctable. Valid files persist byte-for-byte (their own prose,+ formatting, and line endings travel with the machine) into the user+ library.+ """+ source_path = Path(path).expanduser()+ if not source_path.is_file():+ raise ValueError(f"machine file not found: {source_path}")+ raw = source_path.read_bytes()+ text = raw.decode("utf-8")+ machine, errors = parse_machine_file(text, source=str(source_path))+ if machine is None or errors:+ raise ValueError("; ".join(errors))+ spec_errors = validate_factory_spec(machine.spec)+ if spec_errors:+ raise ValueError("; ".join(spec_errors))+ destination_root = Path(target_dir).expanduser() if target_dir is not None else user_machines_dir()+ destination = destination_root / machine.name / MACHINE_FILE_NAME+ destination.parent.mkdir(parents=True, exist_ok=True)+ created = not destination.exists()+ destination.write_bytes(raw)+ return {"name": machine.name, "path": str(destination), "created": created}+++def _single_line(text: Any) -> str:+ """Collapse free prose onto one line (whitespace runs become spaces).++ A stored entry's ``content`` is free prose while a machine description+ must be a single line, so exports collapse rather than refuse.+ """+ if not isinstance(text, str):+ return ""+ return " ".join(text.split())+++def _write_export_target(destination: Path, text: str, *, overwrite: bool) -> None:+ """Write an export target, never silently clobbering one.++ The no-overwrite path creates the file exclusively (``open(..., "x"``):+ the existence check and the creation are one atomic step, so a file+ created concurrently after a plain ``exists()`` check cannot slip past+ the refusal, and a symlink planted at the target refuses instead of+ being followed); ``overwrite=True`` is the explicit opt-in that+ replaces whatever is there.+ """+ if overwrite:+ destination.write_text(text, encoding="utf-8")+ return+ try:+ with open(destination, "x", encoding="utf-8") as handle:+ handle.write(text)+ except FileExistsError:+ raise ValueError(+ f"export path {destination} already exists (pass overwrite=True to replace it)"+ ) from None+++def export_factory_spec(+ spec: Any,+ out_path: "str | Path",+ *,+ name: str,+ description: str,+ version: str = "1",+ author: str = "",+ overwrite: bool = False,+) -> "dict[str, Any]":+ """Serialize any spec (stored entry or run machine) to MACHINE.md.++ Byte-pretty and stable: the same spec always renders to the same bytes.+ The spec passes through the write-time validator first, so an exported+ file always re-imports. The out target is never overwritten silently: an+ existing file refuses unless ``overwrite=True`` says otherwise.+ """+ errors = validate_factory_spec(spec)+ errors.extend(machine_name_errors(name))+ errors.extend(machine_description_errors(description))+ if errors:+ raise ValueError("; ".join(errors))+ machine = MachineFile(+ name=name,+ description=description,+ version=version,+ author=author,+ spec=copy.deepcopy(spec),+ )+ destination = Path(out_path).expanduser()+ if destination.is_dir():+ raise ValueError(f"export path {destination} is a directory (pass a file path)")+ destination.parent.mkdir(parents=True, exist_ok=True)+ _write_export_target(destination, render_machine_file(machine), overwrite=overwrite)+ return {"name": name, "path": str(destination), "source": "spec"}+++def export_library_machine(+ name: str,+ out_path: "str | Path",+ *,+ repo_dir: "str | Path | None" = None,+ user_dir: "str | Path | None" = None,+ overwrite: bool = False,+) -> "dict[str, Any]":+ """Export one library machine to MACHINE.md at ``out_path``.++ Resolution is the library contract only (repo directory first, user+ second); the file copies verbatim so the shared documentation travels+ with the spec. The out target is never overwritten silently: an+ existing file refuses unless ``overwrite=True`` says otherwise. The+ CLI dispatches here because a fresh CLI process has no session state+ (stored entries and live runs) to resolve from.+ """+ machine, path = resolve_machine(name, repo_dir=repo_dir, user_dir=user_dir)+ destination = Path(out_path).expanduser()+ if destination.is_dir():+ raise ValueError(f"export path {destination} is a directory (pass a file path)")+ destination.parent.mkdir(parents=True, exist_ok=True)+ _write_export_target(+ destination, path.read_text(encoding="utf-8"), overwrite=overwrite+ )+ return {"name": machine.name, "path": str(destination), "source": "library"}+++def export_machine(+ target: str,+ out_path: "str | Path",+ *,+ repo_dir: "str | Path | None" = None,+ user_dir: "str | Path | None" = None,+ overwrite: bool = False,+) -> "dict[str, Any]":+ """Export one machine to MACHINE.md at ``out_path``.++ Resolution mirrors ``run_factory``: a stored factory entry first, a+ live run's canonical machine second, then the library machine (repo+ directory first, user second). Library machines copy their file+ verbatim so the shared documentation travels with the spec; entry and+ run specs render byte-pretty.+ """+ executor = default_factory_executor()+ harness = executor._resolve_harness()+ entry = harness.get("factory", target)+ if entry is not None:+ arguments = entry.arguments if isinstance(entry.arguments, dict) else {}+ spec = arguments.get("machine")+ if spec is None:+ spec = arguments.get("dag")+ if spec is None:+ raise ValueError(f"factory entry {target!r} carries no machine or dag spec")+ errors = machine_name_errors(target)+ if errors:+ raise ValueError(+ "; ".join(errors + [f"the stored entry id {target!r} cannot become a machine name"])+ )+ description = _single_line(entry.content) or _single_line(entry.title)+ return export_factory_spec(+ spec, out_path, name=target, description=description, overwrite=overwrite+ )+ run = executor._runs.get(target)+ if run is not None and run.machine:+ errors = machine_name_errors(run.spec_id)+ if errors:+ raise ValueError(+ "; ".join(errors + [f"the run's spec id {run.spec_id!r} cannot become a machine name"])+ )+ description = _single_line(run.name) or f"factory run {run.run_id}"+ return export_factory_spec(+ run.machine, out_path, name=run.spec_id, description=description, overwrite=overwrite+ )+ return export_library_machine(+ target, out_path, repo_dir=repo_dir, user_dir=user_dir, overwrite=overwrite+ )+++def cli_dispatch(payload: Any) -> "dict[str, Any]":+ """JSON facade for the ``prime-agent factory`` subcommands.++ The CLI resolves the kernel Python, feeds one JSON payload on stdin,+ and reads one JSON result from stdout: ``{"ok": true, ...}`` or+ ``{"ok": false, "errors": [...]}``. Every error surfaces as data, so+ the exact validator sentences reach the command's output verbatim.+ The payload carries only what the user typed (an op, a path, a name,+ an out target); this process resolves every library directory itself,+ so the kernel is the single resolution contract for list, import, and+ export alike — a fresh CLI process has no session state (stored+ entries, live runs), so export resolves the library only.+ """+ if not isinstance(payload, dict):+ return {"ok": False, "errors": ["factory cli payload must be a JSON object"]}+ op = payload.get("op")+ if op == "list":+ machines, warnings = _scan_machine_library()+ return {"ok": True, "machines": machines, "warnings": warnings}+ if op == "import":+ if not isinstance(payload.get("path"), str) or not payload["path"]:+ return {"ok": False, "errors": ["factory import requires a `path` string"]}+ try:+ result = import_machine(payload["path"])+ except (ValueError, OSError) as error:+ return {"ok": False, "errors": [str(error)]}+ return {"ok": True, **result}+ if op == "export":+ if not isinstance(payload.get("name"), str) or not payload["name"]:+ return {"ok": False, "errors": ["factory export requires a `name` string"]}+ if not isinstance(payload.get("out"), str) or not payload["out"]:+ return {"ok": False, "errors": ["factory export requires an `out` string"]}+ try:+ result = export_library_machine(payload["name"], payload["out"])+ except (ValueError, OSError) as error:+ return {"ok": False, "errors": [str(error)]}+ return {"ok": True, **result}+ return {+ "ok": False,+ "errors": [f"unknown factory cli op {op!r} (expected 'list', 'import' or 'export')"],+ }++FACTORY_HELP: str = r"""# FactoryThe factory runs state-machine workflows of spawned child agents. A stored@@ -3079,12 +3956,22 @@ detail, and the event ledger until then.## 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 machine library: machines are `MACHINE.md` files (frontmatter plus+ one fenced `machine-spec` block), one directory per machine, resolved+ from two levels — the bundled seeds shipped inside the runtime (visible+ in every install; `PRIME_AGENT_MACHINES_DIR` redirects the level at a+ team directory) first, the personal `machines/` library under the agent+ dir second; the earlier level wins on name conflicts. `prime-agent+ factory list | import | export` manages them: list shows only what+ parses and validates (broken files print as warnings), import runs the same+ write-time validation as a stored spec so an invalid machine never+ persists, and export copies a library machine verbatim to a fresh path+ (an existing target is refused, never overwritten). `rlm.factory.run('<name>')`+ runs a library machine directly without creating a harness entry; a+ machine that exists but is broken names its errors+ instead of pretending the name is unknown. The bundled 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 orclick) opens one live diagram per run, newest run first. `j`/`k` move theselection, `s` stops the selected run, `r` resumes it, `m` copies it as@@ -3108,4 +3995,4 @@ detail, and the event ledger until then.retire them. Prefer `rlm.factory.stop(run_id)` over deleting a factorychild by hand — the executor claims and cancels children itself, and ahand 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/machines/builder/MACHINE.md b/prime-agent-runtime/src/rlm/machines/builder/MACHINE.mdnew file mode 100644index 0000000000..adc33d9bf1--- /dev/null+++ b/prime-agent-runtime/src/rlm/machines/builder/MACHINE.md@@ -0,0 +1,100 @@+---+name: builder+description: Build a documented status report from parallel section writers and merge their drafts.+version: 1+author: Prime Agent+---++# builder++## What this machine does++Builds a documented status report from parallel section writers. One source+child inspects the working tree and produces a short outline, one writer+child drafts a section per outline line (up to eight in parallel), and a+collector child assembles the sections into a single markdown report.++This is the fan-in example: `collect` waits on the joined `sections` text+port until every writer settles, then merges them. No guards, no loops -+the simplest multi-child shape the factory runs.++## How to run it++ result = await rlm.factory.run("builder")++Then watch progress with `await rlm.factory.status(result["run_id"])`. The+collector's `merged` text is the latest settle answer of the `collect`+state.++```machine-spec+{+ "run": {+ "budget_ms": 900000,+ "failure_policy": "escalate",+ "max_parallel": 8+ },+ "nodes": [+ {+ "id": "scope",+ "subagent": {+ "prompt": "Inspect the current working tree and produce a status outline. Count the changed files with `git status --porcelain`, the failing checks by reading the latest CI artifacts if present, and open questions worth flagging. Return a fenced json block of the form {\\\"outline\\\": [\\\"one short line about scope\\\", ...]} with at most five lines. Output only the json block.",+ "name": "builder-scope"+ },+ "outputs": [+ {+ "name": "outline",+ "type": "json"+ }+ ],+ "budget_ms": 240000+ },+ {+ "id": "notes",+ "subagent": {+ "prompt": "Draft one section of a status report for the current working tree using the outline below. Reply with the section text only: one short paragraph, no heading, no closing remarks.\\n\\n{outline}",+ "name": "builder-notes"+ },+ "inputs": [+ {+ "name": "outline",+ "type": "json",+ "from": "scope.outline"+ }+ ],+ "outputs": [+ {+ "name": "section",+ "type": "text"+ }+ ],+ "foreach": {+ "over": "outline",+ "max": 8+ },+ "budget_ms": 240000+ },+ {+ "id": "collect",+ "subagent": {+ "prompt": "You are given the joined section drafts below. Assemble them into one markdown report: add a `## Status` heading, keep each section as its own paragraph in the given order, and append a `## Follow-ups` list with the open questions. Reply with the final markdown only.",+ "name": "build-collector"+ },+ "inputs": [+ {+ "name": "sections",+ "type": "text",+ "from": "notes.section"+ }+ ],+ "outputs": [+ {+ "name": "merged",+ "type": "text"+ }+ ],+ "budget_ms": 240000+ }+ ]+}+```+diff --git a/prime-agent-runtime/src/rlm/machines/pr-manager/MACHINE.md b/prime-agent-runtime/src/rlm/machines/pr-manager/MACHINE.mdnew file mode 100644index 0000000000..25f9e672b6--- /dev/null+++ b/prime-agent-runtime/src/rlm/machines/pr-manager/MACHINE.md@@ -0,0 +1,155 @@+---+name: pr-manager+description: Drive a pull request through review and fix cycles, then keep a resident watcher on it.+version: 1+author: Prime Agent+---++# pr-manager++## What this machine does++Drives a pull request through review and fix cycles. One entry child+resolves the pull request URL, a reviewer child judges the diff, and a+fixer child addresses the findings; the guarded loop alternates until the+verdict approves or the bounded re-entries run out, then a resident+watcher stays available for follow-ups.++This is the machine-form example: guarded transitions select the next+state (`approved` true or false), `max_entries` bounds each loop state,+the fixer's `fix_report` is an optional input on the reviewer's next+re-entry (it binds only after the fixer settled at least once), and+`monitoring` uses the `resident` lifecycle so its instance stays alive+after approval instead of ending the run.++## How to run it++ result = await rlm.factory.run("pr-manager")++Then watch progress with `await rlm.factory.status(result["run_id"])`.+The alternation count is bounded by `max_transitions` and by each loop+state's `max_entries`; the run pauses (escalates) instead of spinning.++```machine-spec+{+ "run": {+ "budget_ms": 1800000,+ "failure_policy": "escalate",+ "max_parallel": 8,+ "max_transitions": 24+ },+ "states": [+ {+ "id": "entry",+ "entry": true,+ "subagent": {+ "prompt": "Identify the pull request under review for the current branch. Run `gh pr view --json url,title` for the current branch and return a fenced json block of the form {\\\"pr_url\\\": \\\"https://github.com/owner/repo/pull/N\\\"}. Output only the json block.",+ "name": "pr-entry"+ },+ "outputs": [+ {+ "name": "pr_url",+ "type": "json"+ }+ ],+ "budget_ms": 240000+ },+ {+ "id": "reviewing",+ "subagent": {+ "prompt": "Review the pull request at {pr_url} for merge-blocking defects. Fetch the diff with `gh pr diff` and judge correctness, regressions, and test gaps. When a fix report is bound below, verify the described fixes landed instead. Return a fenced json block of the form {\\\"verdict\\\": {\\\"approved\\\": <true|false>, \\\"findings\\\": [\\\"one sentence per finding\\\"]}}. Output only the json block.",+ "name": "pr-reviewing"+ },+ "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,+ "budget_ms": 240000+ },+ {+ "id": "fixing",+ "subagent": {+ "prompt": "Address the review findings in the verdict below. Make the smallest targeted fixes in the working tree, run the relevant tests, and reply with 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}",+ "name": "pr-fixing"+ },+ "inputs": [+ {+ "name": "verdict",+ "type": "json",+ "from": "reviewing.verdict"+ }+ ],+ "outputs": [+ {+ "name": "fix_report",+ "type": "json"+ }+ ],+ "max_entries": 3,+ "budget_ms": 480000+ },+ {+ "id": "monitoring",+ "subagent": {+ "prompt": "Stay resident as the pull-request watcher for {pr_url}: inspect the checks with `gh pr checks` once, report their state in one line, and remain available for follow-up questions about the pull request.",+ "name": "pr-monitoring"+ },+ "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"+ }+ ]+}+```+diff --git a/prime-agent-runtime/src/rlm/machines/review-sweep/MACHINE.md b/prime-agent-runtime/src/rlm/machines/review-sweep/MACHINE.mdnew file mode 100644index 0000000000..21b1a93e7c--- /dev/null+++ b/prime-agent-runtime/src/rlm/machines/review-sweep/MACHINE.md@@ -0,0 +1,110 @@+---+name: review-sweep+description: Sweep the changed files of a branch for review findings and merge them into one issue list.+version: 1+author: Prime Agent+---++# review-sweep++## What this machine does++Sweeps the current branch for review findings. One source child lists the+changed files, a reviewer child reviews each file in parallel (up to eight+at a time), and one aggregator child merges the per-file verdicts into a+single issue list.++The review state is a `foreach`: the `files` input (a JSON list) expands to+one reviewer instance per changed file (the `foreach.max` cap of 256 only+bounds pathological diffs; `run.max_parallel: 8` is what bounds how many+reviewers run at once), and every reviewer's one-line verdict joins into+the `found` text port the aggregator reads.++## How to run it++Store a copy of this machine as a runtime instance and run it, or run the+template directly from the library:++ result = await rlm.factory.run("review-sweep")++Then watch progress with `await rlm.factory.status(result["run_id"])`. The+run finishes at quiescence; the aggregator's `issues` JSON is the latest+settle answer of the `report` state.++```machine-spec+{+ "run": {+ "budget_ms": 900000,+ "failure_policy": "escalate",+ "max_parallel": 8+ },+ "nodes": [+ {+ "id": "files",+ "subagent": {+ "prompt": "List every file the current branch changes relative to the base branch. Run `git merge-base HEAD origin/main` first; when it resolves, list the changed files with `git diff --name-only <merge-base>`; when it does not, fall back to `git diff --name-only HEAD~1`. Return a fenced json block of the form {\\\"files\\\": [\\\"path/to/file\\\", ...]} with one entry per changed file. Output only the json block.",+ "name": "files-source"+ },+ "outputs": [+ {+ "name": "files",+ "type": "json"+ }+ ],+ "budget_ms": 240000+ },+ {+ "id": "review",+ "subagent": {+ "prompt": "Review the changed file {files} for merge-blocking defects: correctness bugs, regressions, unhandled error paths, and missing tests. Read the file in the working tree and judge the change itself. Reply with one short line: `<path>: <the most serious problem, or 'clean'>`.",+ "name": "file-reviewer"+ },+ "inputs": [+ {+ "name": "files",+ "type": "json",+ "from": "files.files"+ }+ ],+ "outputs": [+ {+ "name": "found",+ "type": "text"+ }+ ],+ "foreach": {+ "over": "files",+ "max": 256+ },+ "budget_ms": 240000+ },+ {+ "id": "report",+ "subagent": {+ "prompt": "You are given the list of changed files and one review line per file below. Merge them into a fenced json block of the form {\\\"issues\\\": [{\\\"file\\\": \\\"path\\\", \\\"finding\\\": \\\"...\"}]} that lists every file whose review line is not clean, and add a `clean` count. Output only the json block.",+ "name": "review-aggregator"+ },+ "inputs": [+ {+ "name": "file_list",+ "type": "json",+ "from": "files.files"+ },+ {+ "name": "found",+ "type": "text",+ "from": "review.found"+ }+ ],+ "outputs": [+ {+ "name": "issues",+ "type": "json"+ }+ ],+ "budget_ms": 240000+ }+ ]+}+```+diff --git a/prime-agent-runtime/test/test_factory.py b/prime-agent-runtime/test/test_factory.pyindex deb45b3a0e..2ad221ec1f 100644--- a/prime-agent-runtime/test/test_factory.py+++ b/prime-agent-runtime/test/test_factory.py@@ -50,6 +50,8 @@ import hashlibimport jsonimport osimport re+import shutil+import subprocessimport timeimport unittestfrom pathlib import Path@@ -63,16 +65,34 @@ from rlm.factory import (ANSWER_CAPTURE_CAP,BACKOFF_MAX_ATTEMPTS,EVENT_WINDOW,+ MACHINE_FILE_NAME,+ MACHINE_SPEC_FENCE,POLL_TIMEOUT_MS,SUBAGENT_NAME_MAX_LENGTH,FactoryExecutor,+ MachineFile,+ MachineResolutionError,_child_name,_guard_passes,_parse_json_output,+ _scan_machine_library,_spawn_label,canonicalize_factory_spec,+ cli_dispatch,compile_factory_dag,+ export_factory_spec,+ export_library_machine,+ export_machine,+ import_machine,+ list_machines,+ machine_description_errors,+ machine_name_errors,+ parse_machine_file,+ render_machine_file,+ repo_machines_dir,+ resolve_machine,topological_order,+ user_machines_dir,validate_factory_machine,validate_factory_spec,)@@ -2288,6 +2308,39 @@ class FactoryHelpTest(unittest.TestCase):self.assertIn("capped at the eight most relevant", doc)self.assertIn("an unbounded payload truncates at the cap and fails to bind", flat)+ # The Discovery section ships the machine library as present (this+ # branch merges it): the bundled location, the seed names, the CLI+ # surface, and the run-from-library fallback — every phrase+ # fact-checked against the machine-library code (parse/import+ # gate/run fallback).+ self.assertIn(+ "The machine library: machines are `MACHINE.md` files (frontmatter plus "+ "one fenced `machine-spec` block), one directory per machine, resolved "+ "from two levels — the bundled seeds shipped inside the runtime "+ "(visible in every install; `PRIME_AGENT_MACHINES_DIR` redirects the "+ "level at a team directory) first, the personal `machines/` library "+ "under the agent dir second",+ flat,+ )+ self.assertIn(+ "`prime-agent factory list | import | export` manages them: list shows "+ "only what parses and validates (broken files print as warnings), "+ "import runs the same write-time validation as a stored spec so an "+ "invalid machine never persists, and export copies a library machine "+ "verbatim to a fresh path (an existing target is refused, never "+ "overwritten)",+ flat,+ )+ self.assertIn(+ "`rlm.factory.run('<name>')` runs a library machine directly without "+ "creating a harness entry; a machine that exists but is broken names "+ "its errors instead of pretending the name is unknown",+ flat,+ )+ self.assertIn(+ "The bundled seeds are `builder`, `pr-manager`, and `review-sweep`", 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)@@ -5528,3 +5581,1521 @@ class FactoryExecutorTest(_ExecutorTestCase):if __name__ == "__main__":unittest.main()+++# ---------------------------------------------------------------------------+# Machine library: MACHINE.md parse, render, gate, resolution, run.+#+# New-feature coverage (the machine library): the file format round-trips+# (export -> import -> identical validated spec), the import gate refuses+# invalid specs with the write-time validator's exact errors and never+# persists, library resolution is repo-first/user-second, and+# rlm.factory.run falls back to the library for machine names.+# ---------------------------------------------------------------------------+++def machine_file_text(+ *,+ name: str = "sweep",+ description: str = "A machine that sweeps.",+ version: str = "1",+ author: str = "Tester",+ spec_json: str | None = None,+ frontmatter: str | None = None,+ body: str | None = None,+) -> str:+ """Build MACHINE.md text; ``frontmatter``/``body`` override the defaults."""+ if frontmatter is None:+ frontmatter = (+ "---\n"+ f"name: {name}\n"+ f"description: {description}\n"+ f"version: {version}\n"+ f"author: {author}\n"+ "---"+ )+ if body is None:+ spec_json = spec_json or json.dumps({"run": {"failure_policy": "continue"}, "states": [+ {"id": "a", "entry": True, "subagent": {"prompt": "Do the work."}}+ ]})+ body = f"# {name}\n\n```machine-spec\n{spec_json}\n```"+ return f"{frontmatter}\n\n{body}"+++class MachineFileParseTest(unittest.TestCase):+ """The strict MACHINE.md format: frontmatter + one machine-spec fence."""++ def parse(self, text: str) -> "tuple[MachineFile | None, list[str]]":+ return parse_machine_file(text, source="test-MACHINE.md")++ def test_parses_frontmatter_and_spec(self) -> None:+ machine, errors = self.parse(machine_file_text())+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.name, "sweep")+ self.assertEqual(machine.description, "A machine that sweeps.")+ self.assertEqual(machine.version, "1")+ self.assertEqual(machine.author, "Tester")+ self.assertEqual(machine.spec["states"][0]["id"], "a")++ def test_parses_quoted_frontmatter_values(self) -> None:+ text = machine_file_text(+ frontmatter=(+ "---\n"+ 'name: "sweep"\n'+ "description: 'It: reviews things.'\n"+ "version: 1\n"+ "author: Prime Agent\n"+ "---"+ )+ )+ machine, errors = self.parse(text)+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.name, "sweep")+ self.assertEqual(machine.description, "It: reviews things.")++ def test_missing_frontmatter_is_an_exact_error(self) -> None:+ machine, errors = self.parse("# just prose\n\n```machine-spec\n{}\n```")+ self.assertIsNone(machine)+ self.assertEqual(+ errors, ["test-MACHINE.md: MACHINE.md must start with a `---` frontmatter block"]+ )++ def test_unclosed_frontmatter_is_an_exact_error(self) -> None:+ machine, errors = self.parse("---\nname: sweep\nno close")+ self.assertIsNone(machine)+ self.assertEqual(+ errors, ["test-MACHINE.md: frontmatter is not closed (end it with a `---` line)"]+ )++ def test_unknown_and_duplicate_frontmatter_keys_are_exact_errors(self) -> None:+ machine, errors = self.parse(+ machine_file_text(frontmatter="---\nname: sweep\ndescription: A machine.\n---", body="x")+ )+ # Missing the spec fence is reported too, but the frontmatter still parsed:+ self.assertIsNone(machine)+ machine2, errors2 = self.parse(+ machine_file_text(frontmatter="---\nname: sweep\nname: again\ndescription: A machine.\n---")+ )+ self.assertIsNone(machine2)+ self.assertTrue(any("declared more than once" in error for error in errors2), errors2)+ machine3, errors3 = self.parse(+ machine_file_text(frontmatter="---\nname: sweep\ndescription: A machine.\nlicense: MIT\n---")+ )+ self.assertIsNone(machine3)+ self.assertTrue(any("unknown frontmatter key 'license'" in error for error in errors3), errors3)++ def test_missing_name_and_description_are_exact_errors(self) -> None:+ machine, errors = self.parse(+ machine_file_text(frontmatter="---\nversion: 1\nauthor: Tester\n---")+ )+ self.assertIsNone(machine)+ self.assertTrue(any("machine name must be a non-empty string" in error for error in errors), errors)+ self.assertTrue(any("frontmatter description is required" in error for error in errors), errors)++ def test_multiline_descriptions_are_rejected(self) -> None:+ # The description is one listing row by contract, so a quoted+ # frontmatter value that decodes an embedded line break is a format+ # error with its own sentence — not a machine whose listing renders+ # across several terminal lines.+ for description in ('"A machine that\\nsweeps."', '"A machine that\\rsweeps."'):+ machine, errors = self.parse(machine_file_text(frontmatter=(+ "---\nname: sweep\n"+ f"description: {description}\n"+ "version: 1\nauthor: Tester\n---"+ )))+ self.assertIsNone(machine, description)+ self.assertEqual(+ errors, ["frontmatter description must be a single line"]+ )+ self.assertEqual(+ machine_description_errors("One line, as the format requires."), []+ )++ def test_name_rules_mirror_the_skill_library(self) -> None:+ for bad in ("Sweep", "sweep x", "-sweep", "sweep-", "a" * 65):+ machine, errors = self.parse(machine_file_text(name=bad))+ self.assertIsNone(machine, bad)+ self.assertTrue(errors, bad)+ self.assertEqual(machine_name_errors("sweep-2"), [])+ self.assertEqual(machine_name_errors(""), ["machine name must be a non-empty string"])+ self.assertEqual(machine_name_errors(7), ["machine name must be a non-empty string"])+ self.assertIn("must not end with a hyphen", machine_name_errors("sweep-")[0])++ def test_plain_value_with_colon_demands_quotes(self) -> None:+ machine, errors = self.parse(+ machine_file_text(+ frontmatter="---\nname: sweep\ndescription: Reviews: everything\n---",+ body="# sweep\n\n```machine-spec\n{\"run\": {}}\n```",+ )+ )+ self.assertIsNone(machine)+ self.assertTrue(any("quote the value" in error for error in errors), errors)++ def test_no_fence_is_an_exact_error(self) -> None:+ machine, errors = self.parse(machine_file_text(body="# sweep\n\nNo spec here."))+ self.assertIsNone(machine)+ self.assertEqual(+ errors,+ ["test-MACHINE.md: MACHINE.md requires exactly one fenced ```machine-spec block; found none"],+ )++ def test_multiple_fences_are_an_exact_error(self) -> None:+ spec_json = '{"run": {"failure_policy": "continue"}, "states": [{"id": "a", "entry": true, "subagent": {"prompt": "P."}}]}'+ text = machine_file_text(body=f"# sweep\n\n```machine-spec\n{spec_json}\n```\n\n```machine-spec\n{spec_json}\n```")+ machine, errors = self.parse(text)+ self.assertIsNone(machine)+ self.assertEqual(+ errors,+ ["test-MACHINE.md: MACHINE.md requires exactly one fenced ```machine-spec block; found 2"],+ )++ def test_unterminated_fence_is_an_exact_error(self) -> None:+ text = machine_file_text(body="# sweep\n\n```machine-spec\n{\"run\": {}}")+ machine, errors = self.parse(text)+ self.assertIsNone(machine)+ self.assertEqual(errors, ["test-MACHINE.md: the ```machine-spec fence is never closed"])++ def test_fence_payload_must_be_a_json_object(self) -> None:+ machine, errors = self.parse(machine_file_text(body="# sweep\n\n```machine-spec\n[1, 2]\n```"))+ self.assertIsNone(machine)+ self.assertIn(+ "must contain a JSON object, got a list", errors[0]+ )+ machine2, errors2 = self.parse(machine_file_text(body="# sweep\n\n```machine-spec\nnot json\n```"))+ self.assertIsNone(machine2)+ self.assertTrue(errors2[0].startswith("test-MACHINE.md: the ```machine-spec block must contain a JSON object"), errors2)++ def test_other_fenced_blocks_do_not_confuse_the_scan(self) -> None:+ spec_json = '{"run": {"failure_policy": "continue"}, "states": [{"id": "a", "entry": true, "subagent": {"prompt": "P."}}]}'+ text = machine_file_text(+ body=(+ "# sweep\n\n"+ "Example prose with a json block:\n\n"+ "```json\n{\"not\": \"a machine\"}\n```\n\n"+ "```text\nplain text\n```\n\n"+ f"```machine-spec\n{spec_json}\n```"+ )+ )+ machine, errors = self.parse(text)+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.spec["run"]["failure_policy"], "continue")++ def test_crlf_and_bom_are_normalized(self) -> None:+ text = machine_file_text().replace("\n", "\r\n")+ machine, errors = self.parse("\ufeff" + text)+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.name, "sweep")+++class MachineFileRenderTest(unittest.TestCase):+ """render_machine_file is byte-stable and parse-identical."""++ def render(self, spec: dict[str, Any]) -> str:+ machine = MachineFile(+ name="sweep",+ description="A machine that sweeps.",+ version="1",+ author="Tester",+ spec=spec,+ )+ return render_machine_file(machine)++ def test_render_is_byte_stable_and_round_trips(self) -> None:+ text = self.render(valid_machine())+ self.assertEqual(text, self.render(valid_machine()))+ machine, errors = parse_machine_file(text, source="rendered")+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.name, "sweep")+ self.assertEqual(machine.description, "A machine that sweeps.")+ self.assertEqual(machine.version, "1")+ self.assertEqual(machine.author, "Tester")+ self.assertEqual(machine.spec, valid_machine())++ def test_render_quotes_non_plain_values(self) -> None:+ machine = MachineFile(+ name="sweep",+ description="Reviews: everything, carefully.",+ version="1",+ author="Tester",+ spec={"states": [{"id": "a", "entry": True, "subagent": {"prompt": "P."}}]},+ )+ text = render_machine_file(machine)+ self.assertIn('description: "Reviews: everything, carefully."', text)+ reparsed, errors = parse_machine_file(text, source="rendered")+ self.assertEqual(errors, [])+ assert reparsed is not None+ self.assertEqual(reparsed.description, "Reviews: everything, carefully.")++ def test_render_generates_contract_prose_from_both_forms(self) -> None:+ machine_text = self.render(valid_machine())+ self.assertIn("Run: failure_policy=continue, max_parallel=4", machine_text)+ self.assertIn("States:", machine_text)+ self.assertIn("- collect (entry)", machine_text)+ self.assertIn(" input: draft (text) <- collect.findings", machine_text)+ self.assertIn("Transitions:", machine_text)+ self.assertIn("- reviewing -> fixing when verdict.approved eq false", machine_text)+ dag_text = self.render(valid_dag())+ self.assertIn("- fan-out", dag_text)+ self.assertIn(" input: items (text) <- collect.findings", dag_text)+ self.assertIn("```machine-spec", machine_text)++ def test_render_pretty_json_is_two_space_indented(self) -> None:+ text = self.render({"run": {"failure_policy": "continue"}, "states": [+ {"id": "a", "entry": True, "subagent": {"prompt": "P."}}+ ]})+ fence = text.split("```machine-spec\n", 1)[1].rsplit("```", 1)[0]+ self.assertIn('\n "run": {\n "failure_policy": "continue"\n },', fence)+++class MachineFileRoundTripTest(unittest.TestCase):+ """export -> import -> identical validated spec (the format round-trip)."""++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ root = Path(temp.name).resolve()+ self.library = root / "machines"+ self.out_dir = root / "out"++ def test_exported_file_imports_to_the_identical_spec(self) -> None:+ spec = valid_dag()+ out = self.out_dir / "shared.MACHINE.md"+ export_factory_spec(spec, out, name="sweep", description="A machine that sweeps.")+ imported = import_machine(out, target_dir=self.library)+ self.assertEqual(imported["name"], "sweep")+ self.assertTrue(imported["created"])+ stored, errors = parse_machine_file(+ (self.library / "sweep" / "MACHINE.md").read_text(encoding="utf-8"), source="stored"+ )+ self.assertEqual(errors, [])+ assert stored is not None+ self.assertEqual(validate_factory_spec(stored.spec), [])+ self.assertEqual(+ canonicalize_factory_spec(stored.spec), canonicalize_factory_spec(spec)+ )++ def test_library_export_import_export_is_byte_identical(self) -> None:+ spec = valid_machine()+ first = self.out_dir / "first.MACHINE.md"+ export_factory_spec(spec, first, name="sweep", description="A machine that sweeps.")+ import_machine(first, target_dir=self.library)+ # Export the imported library machine (verbatim copy) and re-import: bytes never move.+ second = self.out_dir / "second.MACHINE.md"+ export_machine("sweep", second, repo_dir=None, user_dir=self.library)+ self.assertEqual(first.read_text(encoding="utf-8"), second.read_text(encoding="utf-8"))+ imported = import_machine(second, target_dir=self.library)+ self.assertFalse(imported["created"])+++class ImportGateTest(unittest.TestCase):+ """The import gate: invalid specs never persist, with exact errors."""++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ self.library = Path(temp.name) / "machines"+ self.sources = Path(temp.name) / "sources"++ def write_source(self, text: str) -> Path:+ self.sources.mkdir(parents=True, exist_ok=True)+ path = self.sources / "machine.MACHINE.md"+ path.write_text(text, encoding="utf-8")+ return path++ def test_import_persists_valid_files_verbatim(self) -> None:+ text = machine_file_text(+ description="A machine that sweeps.",+ spec_json=json.dumps(valid_dag()),+ )+ path = self.write_source(text)+ result = import_machine(path, target_dir=self.library)+ self.assertEqual(result["name"], "sweep")+ stored = self.library / "sweep" / "MACHINE.md"+ self.assertTrue(stored.is_file())+ self.assertEqual(stored.read_text(encoding="utf-8"), text)++ def test_import_preserves_crlf_and_cr_files_byte_for_byte(self) -> None:+ # The import persists the SUPPLIED file: a valid CRLF or CR machine+ # keeps its exact bytes (a read_text/write_text round trip would+ # silently rewrite every line ending), and the stored copy still+ # parses.+ text = machine_file_text(spec_json=json.dumps(valid_dag()))+ self.sources.mkdir(parents=True, exist_ok=True)+ for line_ending in ("\r\n", "\r"):+ source = self.sources / f"{len(line_ending)}-byte-newline.MACHINE.md"+ source.write_bytes(text.replace("\n", line_ending).encode("utf-8"))+ result = import_machine(source, target_dir=self.library)+ stored = Path(result["path"])+ self.assertEqual(stored.read_bytes(), source.read_bytes())+ stored_machine, errors = parse_machine_file(+ stored.read_text(encoding="utf-8"), source=str(stored)+ )+ self.assertEqual(errors, [])+ assert stored_machine is not None+ self.assertEqual(stored_machine.name, "sweep")++ def test_import_rejects_invalid_spec_with_exact_errors_and_persists_nothing(self) -> None:+ invalid_spec = {+ "run": {"max_parallel": None},+ "states": [{"id": "a", "entry": True, "subagent": {"prompt": "P."}}],+ }+ path = self.write_source(machine_file_text(spec_json=json.dumps(invalid_spec)))+ with self.assertRaises(ValueError) as ctx:+ import_machine(path, target_dir=self.library)+ self.assertIn(+ "run max_parallel must be an integer between 1 and 64", str(ctx.exception)+ )+ self.assertFalse(self.library.exists())++ def test_import_rejects_both_forms_and_guaranteed_dead_specs(self) -> None:+ both_forms = {+ "nodes": [{"id": "a", "subagent": {"prompt": "P."}}],+ "states": [{"id": "s", "subagent": {"prompt": "P."}}],+ }+ path = self.write_source(machine_file_text(spec_json=json.dumps(both_forms)))+ with self.assertRaises(ValueError) as ctx:+ import_machine(path, target_dir=self.library)+ self.assertIn("pass either dag or machine form, not both", str(ctx.exception))+ dead = {"states": [+ {"id": "start", "entry": True, "subagent": {"prompt": "P."}},+ {+ "id": "loop",+ "subagent": {"prompt": "P."},+ "inputs": [{"name": "v", "type": "text", "from": "loop.v"}],+ "outputs": [{"name": "v", "type": "text"}],+ },+ ]}+ path = self.write_source(machine_file_text(spec_json=json.dumps(dead)))+ with self.assertRaises(ValueError) as ctx:+ import_machine(path, target_dir=self.library)+ self.assertIn("cannot require itself", str(ctx.exception))+ self.assertFalse(self.library.exists())++ def test_import_rejects_malformed_files_with_format_errors(self) -> None:+ path = self.write_source("# no frontmatter here")+ with self.assertRaises(ValueError) as ctx:+ import_machine(path, target_dir=self.library)+ self.assertIn("must start with a `---` frontmatter block", str(ctx.exception))+ self.assertFalse(self.library.exists())++ def test_import_rejects_multiline_descriptions_and_persists_nothing(self) -> None:+ # A quoted description decoding an embedded newline renders the+ # machine across several listing rows: the import gate refuses it+ # with the format's own sentence, exactly like any other parse+ # failure.+ path = self.write_source(machine_file_text(frontmatter=(+ "---\nname: multiline\n"+ 'description: "A machine that\\nsweeps the branch."\n'+ "version: 1\nauthor: Tester\n---"+ )))+ with self.assertRaises(ValueError) as ctx:+ import_machine(path, target_dir=self.library)+ self.assertIn("frontmatter description must be a single line", str(ctx.exception))+ self.assertFalse(self.library.exists())++ def test_import_rejects_missing_files_and_overwrites_renamed(self) -> None:+ with self.assertRaises(ValueError) as ctx:+ import_machine(self.sources / "nope.MACHINE.md", target_dir=self.library)+ self.assertIn("machine file not found", str(ctx.exception))+ text = machine_file_text()+ first = self.write_source(text)+ import_machine(first, target_dir=self.library)+ result = import_machine(first, target_dir=self.library)+ self.assertFalse(result["created"])++ def test_import_gate_is_the_write_time_validator(self) -> None:+ # The exact sentences import_machine raises are the write-time+ # validator's: bypassing the gate must fail the reject test above.+ invalid_spec = {"states": [{"id": "a", "entry": True, "subagent": 5}]}+ path = self.write_source(machine_file_text(spec_json=json.dumps(invalid_spec)))+ with self.assertRaises(ValueError) as ctx:+ import_machine(path, target_dir=self.library)+ self.assertIn(+ "state a requires a subagent", str(ctx.exception)+ )+ self.assertFalse(self.library.exists())+++class MachineLibraryResolutionTest(unittest.TestCase):+ """Repo directory first, user directory second."""++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ root = Path(temp.name).resolve()+ self.repo = root / "repo-machines"+ self.user = root / "user-machines"++ def store(self, root: Path, name: str, description: str, spec: dict[str, Any] | None = None) -> Path:+ directory = root / name+ directory.mkdir(parents=True, exist_ok=True)+ spec = spec if spec is not None else {"states": [+ {"id": "a", "entry": True, "subagent": {"prompt": "P."}}+ ]}+ text = machine_file_text(name=name, description=description, spec_json=json.dumps(spec))+ path = directory / "MACHINE.md"+ path.write_text(text, encoding="utf-8")+ return path++ def test_repo_dir_wins_over_user_dir(self) -> None:+ repo_path = self.store(self.repo, "sweep", "The repo machine.")+ user_path = self.store(self.user, "sweep", "The user machine.")+ machine, path = resolve_machine("sweep", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, repo_path)+ self.assertEqual(machine.description, "The repo machine.")++ def test_frontmatter_name_wins_over_the_directory_name(self) -> None:+ # Mirrors the skill library: the declared name is the machine's+ # name even when its directory is named differently.+ directory = self.user / "renamed-dir"+ directory.mkdir(parents=True)+ (directory / "MACHINE.md").write_text(+ machine_file_text(name="sweep", description="The renamed machine."),+ encoding="utf-8",+ )+ machine, path = resolve_machine("sweep", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, directory / "MACHINE.md")+ self.assertEqual(machine.description, "The renamed machine.")+ listed = list_machines(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["sweep"])++ def test_the_declared_name_wins_over_the_directory_name(self) -> None:+ # The fast path reads <dir>/<name>/MACHINE.md but only returns it+ # when its DECLARED name matches: a directory named `misdir`+ # holding `name: actual` is not the machine `misdir` — it resolves+ # as `actual` (and a repo machine declared `sweep` is never+ # shadowed by a `sweep/` directory that declares another name).+ directory = self.user / "misdir"+ directory.mkdir(parents=True)+ (directory / "MACHINE.md").write_text(+ machine_file_text(name="actual", description="Declared, not directory-named."),+ encoding="utf-8",+ )+ machine, path = resolve_machine("actual", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, directory / "MACHINE.md")+ with self.assertRaises(ValueError) as raised:+ resolve_machine("misdir", repo_dir=self.repo, user_dir=self.user)+ self.assertIn("unknown machine 'misdir'", str(raised.exception))++ def test_a_directory_named_machine_shadowing_is_refused(self) -> None:+ # repo/sweep/ declares `other`: asking for `sweep` must not return+ # that file, and a user machine legitimately named `sweep` wins.+ misnamed = self.repo / "sweep"+ misnamed.mkdir(parents=True)+ (misnamed / "MACHINE.md").write_text(+ machine_file_text(name="other", description="Not sweep."),+ encoding="utf-8",+ )+ self.store(self.user, "sweep", "The real sweep.")+ machine, path = resolve_machine("sweep", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, self.user / "sweep" / "MACHINE.md")+ self.assertEqual(machine.description, "The real sweep.")++ def test_user_dir_serves_names_the_repo_does_not_have(self) -> None:+ self.store(self.repo, "repo-only", "The repo machine.")+ user_path = self.store(self.user, "mine", "The user machine.")+ machine, path = resolve_machine("mine", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, user_path)+ self.assertEqual(machine.description, "The user machine.")++ def test_unknown_name_lists_available_machines(self) -> None:+ self.store(self.repo, "builder", "Builds.")+ self.store(self.user, "sweep", "Sweeps.")+ with self.assertRaises(ValueError) as ctx:+ resolve_machine("missing", repo_dir=self.repo, user_dir=self.user)+ self.assertIn("unknown machine 'missing'", str(ctx.exception))+ self.assertIn("builder", str(ctx.exception))+ self.assertIn("sweep", str(ctx.exception))++ def test_invalid_machine_name_is_rejected_before_scanning(self) -> None:+ with self.assertRaises(ValueError) as ctx:+ resolve_machine("Not A Name", repo_dir=self.repo, user_dir=self.user)+ self.assertIn("invalid characters", str(ctx.exception))++ def test_list_machines_dedupes_repo_first_and_sorts_by_name(self) -> None:+ self.store(self.repo, "sweep", "The repo machine.")+ self.store(self.user, "sweep", "The user machine.")+ self.store(self.user, "alpha", "An early machine.")+ listed = list_machines(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["alpha", "sweep"])+ sweep = next(entry for entry in listed if entry["name"] == "sweep")+ self.assertEqual(sweep["source"], "repo")+ self.assertEqual(sweep["description"], "The repo machine.")+ self.assertEqual(listed[0]["source"], "user")++ def test_list_machines_skips_broken_files(self) -> None:+ good = self.store(self.user, "good", "Good machine.")+ broken = self.user / "broken" / "MACHINE.md"+ broken.parent.mkdir(parents=True, exist_ok=True)+ broken.write_text("no frontmatter", encoding="utf-8")+ listed = list_machines(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["good"])++ def test_list_machines_excludes_spec_invalid_files_with_their_errors(self) -> None:+ # The listing reports only machines resolve/run can use: a repo+ # file whose spec fails the write-time validator never wins the+ # name, a valid user machine shows instead, and the exact+ # validator sentences ride the scan warnings (the CLI list+ # surface) naming the broken file.+ invalid = self.store(self.repo, "sweep", "The broken repo machine.", spec={"states": []})+ self.store(self.user, "sweep", "The user machine.")+ listed, warnings = _scan_machine_library(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["sweep"])+ self.assertEqual(listed[0]["source"], "user")+ self.assertEqual(listed[0]["description"], "The user machine.")+ self.assertEqual(+ warnings,+ [f"{invalid}: factory machine must declare between 1 and 1024 states, got 0"],+ )+ self.assertEqual(list_machines(repo_dir=self.repo, user_dir=self.user)[0]["source"], "user")++ def test_resolve_machine_raises_exact_parse_errors_for_broken_files(self) -> None:+ broken = self.user / "broken" / "MACHINE.md"+ broken.parent.mkdir(parents=True, exist_ok=True)+ broken.write_text("---\nname: broken\n---\n\n```machine-spec\n{}\n```\n", encoding="utf-8")+ with self.assertRaises(ValueError) as ctx:+ resolve_machine("broken", repo_dir=self.repo, user_dir=self.user)+ self.assertIn("frontmatter description is required", str(ctx.exception))++ def test_resolve_machine_reports_non_utf8_files_as_broken(self) -> None:+ # A machine file that exists but does not decode is a broken library+ # file, exactly like one that fails to parse: the decode error rides+ # the broken frame with the SAME sentence the listing scan warns+ # with (the shared verdict's wording, path-prefixed).+ # (UnicodeDecodeError is a ValueError, so an unguarded read would+ # instead surface through run_factory's name-rule arm as an+ # invalid id.)+ corrupt = self.user / "broken" / "MACHINE.md"+ corrupt.parent.mkdir(parents=True, exist_ok=True)+ corrupt.write_bytes(b"\xff\xfe\xff not utf-8")+ with self.assertRaises(MachineResolutionError) as ctx:+ resolve_machine("broken", repo_dir=self.repo, user_dir=self.user)+ self.assertTrue(ctx.exception.broken)+ self.assertIn("not valid UTF-8", str(ctx.exception))+ self.assertIn(str(corrupt), str(ctx.exception))++ def test_resolve_machine_reports_spec_invalid_files_as_broken(self) -> None:+ # A file that parses but carries a spec the write-time validator+ # rejects is the exists-but-broken case at resolve time when it is+ # the name's only carrier — the exact broken frame naming the file,+ # never a usable machine the run rejects late, and never a missing+ # frame. The scan path below skips one in a differently-named+ # directory, so an unknown name keeps the missing frame instead of+ # resolving a spec-invalid file, and a file at the name's directory+ # that DECLARES another name never carried the requested one: the+ # invalid file claims no name on either surface.+ invalid = self.store(self.repo, "sweep", "The broken repo machine.", spec={"states": []})+ with self.assertRaises(MachineResolutionError) as ctx:+ resolve_machine("sweep", repo_dir=self.repo, user_dir=self.user)+ self.assertTrue(ctx.exception.broken)+ message = str(ctx.exception)+ self.assertIn(str(invalid), message)+ self.assertIn("factory machine must declare between 1 and 1024 states, got 0", message)+ renamed = self.repo / "renamed-dir"+ renamed.mkdir(parents=True)+ (renamed / "MACHINE.md").write_text(+ machine_file_text(+ name="ghost", description="Ghost.", spec_json=json.dumps({"states": []})+ ),+ encoding="utf-8",+ )+ with self.assertRaises(MachineResolutionError) as scan_ctx:+ resolve_machine("ghost", repo_dir=self.repo, user_dir=self.user)+ self.assertFalse(scan_ctx.exception.broken)+ self.assertIn("unknown machine 'ghost'", str(scan_ctx.exception))+ misnamed = self.repo / "warp"+ misnamed.mkdir(parents=True)+ (misnamed / "MACHINE.md").write_text(+ machine_file_text(+ name="other", description="Not warp.", spec_json=json.dumps({"states": []})+ ),+ encoding="utf-8",+ )+ with self.assertRaises(MachineResolutionError) as misnamed_ctx:+ resolve_machine("warp", repo_dir=self.repo, user_dir=self.user)+ self.assertFalse(misnamed_ctx.exception.broken)+ self.assertIn("unknown machine 'warp'", str(misnamed_ctx.exception))++ def test_list_and_resolve_agree_on_spec_invalid_files(self) -> None:+ # Cursor's finding: the scan skips a spec-invalid repo machine so+ # the listing surfaces a valid user machine of the same name, but+ # resolve still raised broken on the repo file — `factory list`+ # advertised a machine that run and export refused. Both surfaces+ # now share _read_library_machine's verdict: an invalid file never+ # claims its name, so the valid user machine serves exactly where+ # the listing shows it, and export copies it verbatim.+ self.store(self.repo, "sweep", "The broken repo machine.", spec={"states": []})+ user_path = self.store(self.user, "sweep", "The user machine.")+ listed = list_machines(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["sweep"])+ self.assertEqual(listed[0]["source"], "user")+ machine, path = resolve_machine("sweep", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, user_path)+ self.assertEqual(machine.description, "The user machine.")+ self.assertEqual(validate_factory_spec(machine.spec), [])+ out = self.user.parent / "exported.MACHINE.md"+ result = export_library_machine("sweep", out, repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(result["source"], "library")+ self.assertEqual(out.read_text(encoding="utf-8"), user_path.read_text(encoding="utf-8"))++ def test_resolve_falls_through_parse_broken_files_to_valid_user_machines(self) -> None:+ # The shared verdict covers every invalidity class: a repo file+ # that fails to parse claims its name no more than a spec-invalid+ # one, so the valid user machine serves on both surfaces (the+ # listing always skipped it) instead of resolve raising broken on+ # the repo file.+ broken = self.repo / "sweep" / "MACHINE.md"+ broken.parent.mkdir(parents=True)+ broken.write_text("no frontmatter", encoding="utf-8")+ user_path = self.store(self.user, "sweep", "The user machine.")+ listed = list_machines(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["sweep"])+ machine, path = resolve_machine("sweep", repo_dir=self.repo, user_dir=self.user)+ self.assertEqual(path, user_path)+ self.assertEqual(machine.description, "The user machine.")++ def test_one_non_utf8_file_never_poisons_the_listing_scan(self) -> None:+ # The shared scan skips a non-decodable file like any other broken+ # one (its warning rides the CLI list surface), so it can neither+ # break the listing nor reframe an unrelated unknown name.+ self.store(self.repo, "builder", "Builds.")+ corrupt = self.user / "zz-corrupt" / "MACHINE.md"+ corrupt.parent.mkdir(parents=True, exist_ok=True)+ corrupt.write_bytes(b"\xff\xfe")+ listed, warnings = _scan_machine_library(repo_dir=self.repo, user_dir=self.user)+ self.assertEqual([entry["name"] for entry in listed], ["builder"])+ self.assertTrue(any("not valid UTF-8" in warning for warning in warnings), warnings)+ with self.assertRaises(MachineResolutionError) as ctx:+ resolve_machine("missing", repo_dir=self.repo, user_dir=self.user)+ self.assertFalse(ctx.exception.broken)+ self.assertIn("unknown machine 'missing'", str(ctx.exception))+ self.assertIn("builder", str(ctx.exception))++ def test_env_overrides_drive_the_production_dirs(self) -> None:+ env = patch.dict(os.environ, {+ "PRIME_AGENT_MACHINES_DIR": str(self.repo),+ "PRIME_AGENT_CODING_AGENT_DIR": str(Path(self.repo).parent / "agent-home"),+ })+ env.start()+ self.addCleanup(env.stop)+ self.store(self.repo, "sweep", "The repo machine.")+ self.assertEqual(repo_machines_dir(), self.repo)+ self.assertEqual(user_machines_dir(), Path(self.repo).parent / "agent-home" / "machines")+ machine, path = resolve_machine("sweep")+ self.assertEqual(path, self.repo / "sweep" / "MACHINE.md")++ def test_the_bundled_library_ships_inside_the_runtime_package(self) -> None:+ # The repo level is the packaged library: the machines directory+ # beside this module (site-packages/rlm/machines in an installed+ # kernel, src/rlm/machines in a checkout), so an installed kernel+ # resolves the seeds a checkout does. The env override still wins.+ packaged = Path(factory_module.__file__).resolve().parent / "machines"+ repo_dir = repo_machines_dir()+ self.assertEqual(repo_dir, packaged)+ self.assertTrue(packaged.is_dir())+ with patch.dict(os.environ, {"PRIME_AGENT_MACHINES_DIR": str(self.repo)}):+ self.assertEqual(repo_machines_dir(), self.repo)++ def test_the_shipped_seed_machines_validate_clean(self) -> None:+ # The repo-level library resolves as the packaged directory and the+ # shipped examples parse, validate, and canonicalize: a broken seed+ # fails here before it can ship.+ repo_dir = repo_machines_dir()+ names = {entry["name"] for entry in list_machines(repo_dir=repo_dir, user_dir=Path("/nonexistent-user-machines"))}+ self.assertIn("review-sweep", names)+ self.assertIn("builder", names)+ self.assertIn("pr-manager", names)+ for name in ("review-sweep", "builder", "pr-manager"):+ machine, path = resolve_machine(name, repo_dir=repo_dir, user_dir=Path("/nonexistent-user-machines"))+ self.assertEqual(machine.name, name)+ self.assertEqual(validate_factory_spec(machine.spec), [], name)+ self.assertEqual(validate_factory_spec(canonicalize_factory_spec(machine.spec)), [], name)+ machine_two = parse_machine_file(path.read_text(encoding="utf-8"), source=str(path))[0]+ assert machine_two is not None+ self.assertEqual(machine_two.spec, machine.spec, name)+++class MachineCliDispatchTest(unittest.TestCase):+ """The JSON facade the CLI's factory subcommands drive.++ The payload carries only what the user typed (an op, a path, a name, an+ out target); the dispatch process resolves every library directory+ itself through the production env seams (`PRIME_AGENT_MACHINES_DIR`,+ `PRIME_AGENT_CODING_AGENT_DIR`), so these tests exercise the same+ resolution a real CLI invocation runs.+ """++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ root = Path(temp.name).resolve()+ self.repo = root / "repo-machines"+ self.agent_home = root / "agent-home"+ self.sources = root / "sources"+ self.out_dir = root / "out"+ self.source_text = machine_file_text(+ description="A machine that sweeps.", spec_json=json.dumps(valid_dag())+ )+ self.sources.mkdir(parents=True, exist_ok=True)+ self.source_path = self.sources / "machine.MACHINE.md"+ self.source_path.write_text(self.source_text, encoding="utf-8")+ env = patch.dict(os.environ, {+ "PRIME_AGENT_MACHINES_DIR": str(self.repo),+ "PRIME_AGENT_CODING_AGENT_DIR": str(self.agent_home),+ })+ env.start()+ self.addCleanup(env.stop)++ def test_import_dispatch_persists_into_the_user_library(self) -> None:+ result = cli_dispatch({"op": "import", "path": str(self.source_path)})+ self.assertTrue(result["ok"], result)+ self.assertEqual(result["name"], "sweep")+ destination = self.agent_home / "machines" / "sweep" / "MACHINE.md"+ self.assertEqual(Path(result["path"]), destination)+ self.assertEqual(destination.read_text(encoding="utf-8"), self.source_text)++ def test_import_dispatch_surfaces_gate_errors_as_data(self) -> None:+ bad = self.sources / "bad.MACHINE.md"+ bad.write_text(+ machine_file_text(spec_json=json.dumps({"run": {"max_parallel": None}, "states": [+ {"id": "a", "entry": True, "subagent": {"prompt": "P."}}+ ]})),+ encoding="utf-8",+ )+ result = cli_dispatch({"op": "import", "path": str(bad)})+ self.assertFalse(result["ok"])+ self.assertFalse((self.agent_home / "machines").exists())+ self.assertTrue(any("max_parallel must be an integer between 1 and 64" in e for e in result["errors"]), result)++ def test_export_dispatch_resolves_library_machines(self) -> None:+ import_machine(self.source_path, target_dir=self.repo)+ result = cli_dispatch({+ "op": "export",+ "name": "sweep",+ "out": str(self.out_dir / "shared.MACHINE.md"),+ })+ self.assertTrue(result["ok"], result)+ self.assertEqual(result["source"], "library")+ self.assertEqual(+ Path(result["path"]).read_text(encoding="utf-8"), self.source_text+ )++ def test_export_dispatch_refuses_to_overwrite_the_target(self) -> None:+ import_machine(self.source_path, target_dir=self.repo)+ target = self.out_dir / "shared.MACHINE.md"+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text("keep me", encoding="utf-8")+ result = cli_dispatch({+ "op": "export",+ "name": "sweep",+ "out": str(target),+ })+ self.assertFalse(result["ok"])+ self.assertTrue(any("already exists" in e for e in result["errors"]), result)+ self.assertEqual(target.read_text(encoding="utf-8"), "keep me")++ def test_export_dispatch_resolves_the_library_only(self) -> None:+ # A fresh CLI process has no session state, so the dispatch resolves+ # library machines only: a stored factory entry never intercepts+ # the CLI's export, even when one exists.+ self.agent_home.mkdir(parents=True, exist_ok=True)+ (self.agent_home / "settings.json").write_text(+ json.dumps({"factory": {"enabled": True}}), encoding="utf-8"+ )+ harness = HarnessState(Path(self.agent_home) / "harness_state.json")+ previous_executor = factory_module._DEFAULT_EXECUTOR+ factory_module._DEFAULT_EXECUTOR = FactoryExecutor(harness=harness)+ self.addCleanup(lambda: setattr(factory_module, "_DEFAULT_EXECUTOR", previous_executor))+ harness.create_factory(+ "sweep", "Stored.",+ machine={"states": [{"id": "a", "entry": True, "subagent": {"prompt": "P."}}]},+ )+ result = cli_dispatch({"op": "export", "name": "sweep", "out": str(self.out_dir / "s.MACHINE.md")})+ self.assertFalse(result["ok"])+ self.assertTrue(any("unknown machine 'sweep'" in e for e in result["errors"]), result)++ def test_export_dispatch_reports_unknown_machines(self) -> None:+ result = cli_dispatch({+ "op": "export",+ "name": "ghost",+ "out": str(self.out_dir / "ghost.MACHINE.md"),+ })+ self.assertFalse(result["ok"])+ self.assertTrue(any("unknown machine 'ghost'" in e for e in result["errors"]), result)++ def test_list_dispatch_lists_the_library_with_warnings(self) -> None:+ (self.repo / "sweep").mkdir(parents=True)+ (self.repo / "sweep" / "MACHINE.md").write_text(self.source_text, encoding="utf-8")+ broken = self.agent_home / "machines" / "broken"+ broken.mkdir(parents=True)+ (broken / "MACHINE.md").write_text("no frontmatter", encoding="utf-8")+ result = cli_dispatch({"op": "list"})+ self.assertTrue(result["ok"], result)+ self.assertEqual([m["name"] for m in result["machines"]], ["sweep"])+ self.assertEqual(result["machines"][0]["source"], "repo")+ self.assertTrue(any("broken" in warning for warning in result["warnings"]), result)++ def test_dispatch_rejects_bad_payloads(self) -> None:+ self.assertEqual(cli_dispatch("nope")["ok"], False)+ missing = cli_dispatch({"op": "import"})+ self.assertFalse(missing["ok"])+ self.assertIn("requires a `path` string", missing["errors"][0])+ unknown_op = cli_dispatch({"op": "wat"})+ self.assertFalse(unknown_op["ok"])+ self.assertIn("unknown factory cli op", unknown_op["errors"][0])+ self.assertIn("'list'", unknown_op["errors"][0])+++class ExportMachineTest(unittest.TestCase):+ """export_machine serializes library machines, entries, and runs."""++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ root = Path(temp.name).resolve()+ self.library = root / "machines"+ self.out_dir = root / "out"+ self.out_dir.mkdir(parents=True)+ self.harness = HarnessState(root / "harness_state.json")+ self.previous_executor = factory_module._DEFAULT_EXECUTOR+ self.executor = FactoryExecutor(harness=self.harness)+ factory_module._DEFAULT_EXECUTOR = self.executor+ self.addCleanup(lambda: setattr(factory_module, "_DEFAULT_EXECUTOR", self.previous_executor))+ # The opt-in gate: create_factory (below) refuses while the+ # `factory.enabled` setting is off, so the agent dir points at an+ # isolated temp dir whose settings file writes the real document+ # shape the daemon writes -- the core's enabled-fixture pattern.+ agent_temp = TemporaryDirectory()+ self.addCleanup(agent_temp.cleanup)+ self._isolate_agent_dir(agent_temp.name)+ self.write_settings({"factory": {"enabled": True}})++ def write_settings(self, document: Any) -> None:+ """Write the agent-dir settings document (the real file shape)."""+ settings_path = Path(os.environ["PRIME_AGENT_CODING_AGENT_DIR"]) / "settings.json"+ 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 test_exports_a_library_machine_verbatim(self) -> None:+ text = machine_file_text(description="A machine that sweeps.", spec_json=json.dumps(valid_dag()))+ directory = self.library / "sweep"+ directory.mkdir(parents=True)+ (directory / "MACHINE.md").write_text(text, encoding="utf-8")+ out = self.out_dir / "shared.MACHINE.md"+ result = export_machine("sweep", out, repo_dir=None, user_dir=self.library)+ self.assertEqual(result["source"], "library")+ self.assertEqual(out.read_text(encoding="utf-8"), text)++ def test_export_refuses_to_silently_overwrite_the_target(self) -> None:+ # A fresh target only: an existing file refuses (overwrite=True is+ # the explicit opt-in), so an export never clobbers a user file.+ text = machine_file_text(description="A machine that sweeps.", spec_json=json.dumps(valid_dag()))+ directory = self.library / "sweep"+ directory.mkdir(parents=True)+ (directory / "MACHINE.md").write_text(text, encoding="utf-8")+ out = self.out_dir / "shared.MACHINE.md"+ out.write_text("keep me", encoding="utf-8")+ with self.assertRaises(ValueError) as raised:+ export_machine("sweep", out, repo_dir=None, user_dir=self.library)+ self.assertIn("already exists", str(raised.exception))+ self.assertEqual(out.read_text(encoding="utf-8"), "keep me")+ result = export_machine("sweep", out, repo_dir=None, user_dir=self.library, overwrite=True)+ self.assertEqual(result["source"], "library")+ self.assertEqual(out.read_text(encoding="utf-8"), text)++ def test_export_refuses_a_symlinked_target_without_following_it(self) -> None:+ # The no-overwrite path creates the file exclusively, so a symlink+ # planted at the target refuses instead of being followed and its+ # victim keeps its bytes.+ text = machine_file_text(description="A machine that sweeps.", spec_json=json.dumps(valid_dag()))+ directory = self.library / "sweep"+ directory.mkdir(parents=True)+ (directory / "MACHINE.md").write_text(text, encoding="utf-8")+ victim = self.out_dir / "victim.txt"+ victim.write_text("keep me", encoding="utf-8")+ link = self.out_dir / "link.MACHINE.md"+ link.symlink_to(victim)+ with self.assertRaises(ValueError) as raised:+ export_machine("sweep", link, repo_dir=None, user_dir=self.library)+ self.assertIn("already exists", str(raised.exception))+ self.assertEqual(victim.read_text(encoding="utf-8"), "keep me")+ self.assertTrue(link.is_symlink())++ def test_multiline_entry_content_exports_as_one_line(self) -> None:+ # A stored entry's content is free prose; a machine description+ # must be a single line, so the export collapses it instead of+ # refusing a perfectly ordinary entry.+ self.harness.create_factory(+ "multiline", "First line of prose.\nSecond line of prose.\n\nThird paragraph.",+ machine={"states": [{"id": "a", "entry": True, "subagent": {"prompt": "P."}}]},+ )+ out = self.out_dir / "multiline.MACHINE.md"+ result = export_machine("multiline", out)+ self.assertEqual(result["source"], "spec")+ rendered = out.read_text(encoding="utf-8")+ self.assertIn(+ "description: First line of prose. Second line of prose. Third paragraph.",+ rendered,+ )++ def test_spec_export_refuses_to_silently_overwrite_the_target(self) -> None:+ out = self.out_dir / "spec.MACHINE.md"+ export_factory_spec(valid_machine(), out, name="sweep", description="A machine that sweeps.")+ out.write_text("keep me", encoding="utf-8")+ with self.assertRaises(ValueError) as raised:+ export_factory_spec(valid_machine(), out, name="sweep", description="Overwrite.")+ self.assertIn("already exists", str(raised.exception))+ self.assertEqual(out.read_text(encoding="utf-8"), "keep me")+ export_factory_spec(valid_machine(), out, name="sweep", description="Overwrite.", overwrite=True)+ self.assertIn("Overwrite.", out.read_text(encoding="utf-8"))++ def test_spec_export_multiline_description_is_one_sentence(self) -> None:+ # The single-line rule lives in machine_description_errors alone:+ # one defect, one sentence, whether the description arrives as a+ # parsed frontmatter value or an export argument.+ with self.assertRaises(ValueError) as raised:+ export_factory_spec(+ valid_machine(),+ self.out_dir / "x.MACHINE.md",+ name="sweep",+ description="A machine that\nsweeps.",+ )+ self.assertEqual(+ str(raised.exception), "frontmatter description must be a single line"+ )++ def test_exports_a_stored_entry_spec_byte_pretty(self) -> None:+ self.harness.create_factory("Sweep", "A machine that sweeps.", id="sweep", dag=valid_dag())+ out = self.out_dir / "sweep.MACHINE.md"+ result = export_machine("sweep", out, repo_dir=None, user_dir=self.library)+ self.assertEqual(result["source"], "spec")+ machine, errors = parse_machine_file(out.read_text(encoding="utf-8"), source=str(out))+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.name, "sweep")+ self.assertEqual(validate_factory_spec(machine.spec), [])+ self.assertEqual(canonicalize_factory_spec(machine.spec), canonicalize_factory_spec(valid_dag()))++ def test_entry_ids_that_are_not_machine_names_are_rejected(self) -> None:+ self.harness.create_factory("Sweep", "A machine that sweeps.", id="Sweep Entry", dag=valid_dag())+ with self.assertRaises(ValueError) as ctx:+ export_machine("Sweep Entry", self.out_dir / "x.MACHINE.md", repo_dir=None, user_dir=self.library)+ self.assertIn("invalid characters", str(ctx.exception))++ def test_exports_a_runs_canonical_machine(self) -> None:+ self.harness.create_factory("Sweep", "A machine that sweeps.", id="sweep", machine=valid_machine())+ run = self.executor._create_run(+ "sweep", canonicalize_factory_spec(valid_machine()), {}, name="the run"+ )+ self.executor._runs[run.run_id] = run+ self.assertEqual(run.machine, canonicalize_factory_spec(valid_machine()))+ out = self.out_dir / "run-machine.MACHINE.md"+ result = export_machine(run.run_id, out, repo_dir=None, user_dir=self.library)+ self.assertEqual(result["source"], "spec")+ machine, errors = parse_machine_file(out.read_text(encoding="utf-8"), source=str(out))+ self.assertEqual(errors, [])+ assert machine is not None+ self.assertEqual(machine.spec, canonicalize_factory_spec(valid_machine()))++ def test_unknown_targets_list_every_source(self) -> None:+ with self.assertRaises(ValueError) as ctx:+ export_machine("ghost", self.out_dir / "ghost.MACHINE.md", repo_dir=None, user_dir=self.library)+ self.assertIn("unknown machine 'ghost'", str(ctx.exception))++ def test_out_path_must_not_be_a_directory(self) -> None:+ directory = self.library / "sweep"+ directory.mkdir(parents=True)+ (directory / "MACHINE.md").write_text(+ machine_file_text(description="A machine that sweeps."), encoding="utf-8"+ )+ with self.assertRaises(ValueError) as ctx:+ export_machine("sweep", self.out_dir, repo_dir=None, user_dir=self.library)+ self.assertIn("is a directory", str(ctx.exception))++ def test_export_rejects_invalid_specs(self) -> None:+ with self.assertRaises(ValueError) as ctx:+ export_factory_spec(+ {"run": {"max_parallel": None}, "states": [{"id": "a", "entry": True, "subagent": {"prompt": "P."}}]},+ self.out_dir / "bad.MACHINE.md",+ name="sweep",+ description="A machine that sweeps.",+ )+ self.assertIn("max_parallel must be an integer between 1 and 64", str(ctx.exception))+ self.assertFalse((self.out_dir / "bad.MACHINE.md").exists())+++class FactoryRunFromLibraryTest(unittest.TestCase):+ """rlm.factory.run falls back to the machine library for machine names."""++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ root = Path(temp.name).resolve()+ self.library = root / "machines"+ self.harness = HarnessState(root / "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))+ patcher = patch.object(rlm_module, "host_request", self.host)+ patcher.start()+ self.addCleanup(patcher.stop)+ # Isolate the library resolution from this machine's real home dir.+ agent_home = root / "agent-home"+ # The library run routes through rlm.factory.run, so it inherits the+ # opt-in gate: the isolated agent dir carries the same enabled+ # settings document the core's executor tests write (the real file+ # shape the daemon writes), or the disabled default refuses the run.+ agent_home.mkdir(parents=True, exist_ok=True)+ (agent_home / "settings.json").write_text(+ json.dumps({"factory": {"enabled": True}}), encoding="utf-8"+ )+ env = patch.dict(os.environ, {+ "PRIME_AGENT_MACHINES_DIR": str(self.library),+ "PRIME_AGENT_CODING_AGENT_DIR": str(agent_home),+ })+ env.start()+ self.addCleanup(env.stop)++ def store_machine_file(self, name: str, spec: dict[str, Any]) -> Path:+ directory = self.library / name+ directory.mkdir(parents=True, exist_ok=True)+ path = directory / "MACHINE.md"+ path.write_text(+ machine_file_text(name=name, description="A machine that sweeps.", spec_json=json.dumps(spec)),+ encoding="utf-8",+ )+ return path++ @async_test+ async def test_run_resolves_machine_names_from_the_library(self) -> None:+ path = self.store_machine_file(+ "sweep",+ {+ "run": {"failure_policy": "continue", "max_parallel": 2},+ "nodes": [+ {"id": "a", "subagent": "worker", "outputs": [{"name": "out", "type": "text"}]},+ {+ "id": "b",+ "subagent": {"prompt": "Use {draft}"},+ "depends_on": ["a"],+ "inputs": [{"name": "draft", "type": "text", "from": "a.out"}],+ },+ ],+ },+ )+ result = await rlm_module.rlm.factory.run("sweep")+ self.assertEqual(result["spec_id"], "sweep")+ self.assertEqual(result["machine"], "sweep")+ self.assertEqual(result["machine_path"], str(path))+ self.assertEqual(result["started"], ["a"])+ status = await self.settle(result)+ self.assertEqual(status["state"], "done")+ self.assertEqual(status["spec_id"], "sweep")+ self.assertEqual(len(self.host.calls_of("rlm.run")), 2)++ @async_test+ async def test_stored_entries_win_over_library_machines(self) -> None:+ self.store_machine_file(+ "sweep",+ {"nodes": [{"id": "only-a", "subagent": "worker"}]},+ )+ self.harness.create_factory(+ "Sweep", "A stored instance.", id="sweep", dag={"nodes": [+ {"id": "entry-a", "subagent": "worker"},+ {"id": "entry-b", "subagent": "worker"},+ ]}+ )+ result = await rlm_module.rlm.factory.run("sweep")+ self.assertNotIn("machine", result)+ self.assertEqual(result["nodes"], 2)+ self.assertEqual(sorted(result["started"]), ["entry-a", "entry-b"])++ @async_test+ async def test_unknown_names_report_the_library(self) -> None:+ with self.assertRaisesRegex(ValueError, "unknown factory spec 'missing-spec'"):+ await rlm_module.rlm.factory.run("missing-spec")+ try:+ await rlm_module.rlm.factory.run("missing-spec")+ except ValueError as error:+ self.assertIn("no stored factory entry", str(error))+ self.assertIn("no library machine with that name", str(error))++ @async_test+ async def test_an_invalid_name_still_reports_the_unknown_spec_frame(self) -> None:+ # A stored-entry id that is not a legal machine name (spaces,+ # capitals) can never resolve from the library: the lookup must+ # not surface the bare name-rule sentence, losing the unknown-spec+ # frame.+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("My Spec")+ message = str(raised.exception)+ self.assertIn("unknown factory spec 'My Spec'", message)+ self.assertIn("not a valid machine name", message)+ self.assertIn("lowercase a-z, 0-9, hyphens", message)+ self.assertEqual(self.host.calls, [])++ @async_test+ async def test_a_broken_library_file_names_its_errors_not_a_missing_name(self) -> None:+ # A file that exists but fails to parse reports the exact parse+ # errors; it never pretends the name is unknown.+ directory = self.library / "broken"+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "MACHINE.md").write_text(+ "---\nname: broken\n---\n\n```machine-spec\n{}\n```\n", encoding="utf-8"+ )+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("broken")+ self.assertIn("exists but is broken", str(raised.exception))+ self.assertIn("frontmatter description is required", str(raised.exception))+ self.assertNotIn("no library machine with that name", str(raised.exception))+ self.assertEqual(self.host.calls, [])++ @async_test+ async def test_a_spec_invalid_library_file_is_broken_not_a_late_rejection(self) -> None:+ # A file that parses but carries a spec the write-time validator+ # rejects is the exists-but-broken case at resolve time: the run+ # refuses with the exact validator sentences naming the file,+ # never a late canonicalize error after resolution, and nothing+ # spawns.+ path = self.store_machine_file("sweep", {"states": []})+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("sweep")+ message = str(raised.exception)+ self.assertIn("exists but is broken", message)+ self.assertIn("factory machine must declare between 1 and 1024 states, got 0", message)+ self.assertIn(str(path), message)+ self.assertNotIn("no library machine with that name", message)+ self.assertEqual(self.host.calls, [])++ @async_test+ async def test_an_invalid_repo_machine_never_shadows_a_valid_user_machine(self) -> None:+ # Cursor's follow-up finding: the listing scan skips a spec-invalid+ # repo machine so a valid user machine of the same name surfaces,+ # but the run still raised exists-but-broken on the repo file —+ # `factory list` advertised a machine the run refused. Run, resolve,+ # and export share the listing's verdict, so the run serves the+ # user machine the listing advertises; the invalid repo file never+ # shadows it and never masquerades as usable.+ self.store_machine_file("sweep", {"states": []})+ agent_home = Path(os.environ["PRIME_AGENT_CODING_AGENT_DIR"])+ user_file = agent_home / "machines" / "sweep" / "MACHINE.md"+ user_file.parent.mkdir(parents=True)+ user_file.write_text(+ machine_file_text(+ name="sweep",+ description="The user machine.",+ spec_json=json.dumps({"nodes": [{"id": "a", "subagent": "worker"}]}),+ ),+ encoding="utf-8",+ )+ listed = list_machines()+ self.assertEqual([entry["name"] for entry in listed], ["sweep"])+ self.assertEqual(listed[0]["source"], "user")+ result = await rlm_module.rlm.factory.run("sweep")+ self.assertEqual(result["spec_id"], "sweep")+ self.assertEqual(result["machine"], "sweep")+ self.assertEqual(result["machine_path"], str(user_file))+ self.assertEqual(result["started"], ["a"])+ status = await self.settle(result)+ self.assertEqual(status["state"], "done")+ self.assertEqual(status["spec_id"], "sweep")++ @async_test+ async def test_a_non_utf8_library_file_is_broken_not_an_invalid_name(self) -> None:+ # A machine file that exists but does not decode is a broken library+ # file: the run reports it in the exists-but-broken frame, never as+ # an invalid machine name (the name-rule arm must not swallow the+ # decode error).+ directory = self.library / "sweep"+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "MACHINE.md").write_bytes(b"\xff\xfe\xff not utf-8")+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("sweep")+ message = str(raised.exception)+ self.assertIn("exists but is broken", message)+ self.assertIn("not valid UTF-8", message)+ self.assertNotIn("not a valid machine name", message)+ self.assertEqual(self.host.calls, [])++ @async_test+ async def test_one_corrupt_library_file_never_reframes_unknown_names(self) -> None:+ # One non-decodable file skips in the listing scan like any broken+ # file: an unrelated unknown name keeps the unknown-spec frame, never+ # the name-rule arm the decode error would otherwise reach.+ corrupt = self.library / "zz-corrupt"+ corrupt.mkdir(parents=True, exist_ok=True)+ (corrupt / "MACHINE.md").write_bytes(b"\xff\xfe")+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("missing-spec")+ message = str(raised.exception)+ self.assertIn("unknown factory spec 'missing-spec'", message)+ self.assertIn("no library machine with that name", message)+ self.assertNotIn("not a valid machine name", message)+ self.assertEqual(self.host.calls, [])++ @async_test+ async def test_the_opt_in_gate_refuses_library_runs_while_disabled(self) -> None:+ # The library run routes through rlm.factory.run, so it inherits the+ # opt-in gate and the refusal precedes library resolution: while the+ # setting is off, a stored library machine name is refused with the+ # one disabled message -- never an unknown-spec error, never a run+ # -- and nothing spawns.+ self.store_machine_file("sweep", {"nodes": [{"id": "a", "subagent": "worker"}]})+ agent_home = Path(os.environ["PRIME_AGENT_CODING_AGENT_DIR"])+ (agent_home / "settings.json").write_text(+ json.dumps({"factory": {"enabled": False}}), encoding="utf-8"+ )+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("sweep")+ 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.+ (agent_home / "settings.json").unlink()+ with self.assertRaises(ValueError) as raised:+ await rlm_module.rlm.factory.run("sweep")+ self.assertEqual(str(raised.exception), factory_module.FACTORY_DISABLED_MESSAGE)+ self.assertEqual(self.host.calls, [])++ @async_test+ async def test_run_from_library_compiles_dag_sugar(self) -> None:+ self.store_machine_file(+ "pipeline",+ {+ "nodes": [+ {"id": "src", "subagent": "worker", "outputs": [{"name": "v", "type": "text"}]},+ {+ "id": "fan-in",+ "subagent": {"prompt": "Merge {v}."},+ "depends_on": ["src"],+ "inputs": [{"name": "v", "type": "text", "from": "src.v"}],+ },+ ],+ },+ )+ result = await rlm_module.rlm.factory.run("pipeline")+ self.assertEqual(result["machine"], "pipeline")+ run = self.executor._runs[result["run_id"]]+ # The run executes the compiled machine, and the run's stashed+ # machine is exactly the canonicalized template.+ self.assertIn("states", run.machine)+ self.assertNotIn("nodes", run.machine)+ self.assertEqual(validate_factory_spec(run.machine), [])+ self.assertEqual(run.machine, canonicalize_factory_spec(run.machine))++ # helpers ------------------------------------------------------------------++ async def settle(self, run_result: dict[str, Any], *, max_polls: int = 50_000) -> dict[str, Any]:+ run_id = run_result["run_id"]+ for _ in range(max_polls):+ run = self.executor._runs[run_id]+ if run.state != "running":+ return await rlm_module.rlm.factory.status(run_id)+ await yield_loop_turn()+ self.fail(f"run {run_id} never left the running state")+++# ---------------------------------------------------------------------------+# The installed-runtime library: the wheel a kernel venv actually installs.+# ---------------------------------------------------------------------------++_INSTALLED_LIBRARY_RUNNER = r"""+import asyncio+import json+++class ScriptedHost:+ # Deterministic fake for the rlm host bridge: spawn registers a child,+ # collect settles it with the review-sweep node's scripted answer.+ def __init__(self):+ self.children = {}+ self.counter = 0++ @staticmethod+ def answer_for(name):+ if name.startswith("files-source"):+ return "```json\n{\"files\": [\"sample.ts\"]}\n```"+ if name.startswith("file-reviewer"):+ return "sample.ts: clean"+ if name.startswith("review-aggregator"):+ return "```json\n{\"issues\": [], \"clean\": 1}\n```"+ return "done"++ async def __call__(self, request_type, payload=None):+ payload = payload or {}+ if request_type == "rlm.run":+ self.counter += 1+ child_id = f"child-{self.counter}"+ name = payload["kwargs"]["name"]+ self.children[child_id] = name+ return {+ "rlm_child_id": child_id,+ "name": name,+ "session_dir": f"/tmp/{child_id}",+ "model": "test/worker",+ }+ if request_type == "rlm.collect":+ results = []+ for target in payload["targets"]:+ name = self.children.get(target)+ if name is None:+ continue+ results.append({+ "rlm_child_id": target,+ "session_name": name,+ "session_dir": f"/tmp/{target}",+ "status": "done",+ "settled": True,+ "answer_preview": self.answer_for(name),+ "tool_use_count": 1,+ "duration_ms": 5,+ })+ return {"results": results}+ if request_type == "rlm.delete_subagent":+ self.children.pop(payload["target"], None)+ return {"outcome": "deleted"}+ return {}+++async def main():+ import rlm as rlm_module+ import rlm.factory as factory_module+ from rlm.factory import FactoryExecutor++ rlm_module.host_request = ScriptedHost()++ async def instant_sleep(_seconds):+ await asyncio.sleep(0)++ factory_module._DEFAULT_EXECUTOR = FactoryExecutor(sleep=instant_sleep)+ factory = rlm_module.rlm.factory+ result = await factory.run("review-sweep")+ status = None+ for _ in range(500):+ status = await factory.status(result["run_id"])+ if status["state"] != "running":+ break+ await asyncio.sleep(0.02)+ print(json.dumps({+ "state": status["state"],+ "spec_id": result["spec_id"],+ "machine": result["machine"],+ "machine_path": result["machine_path"],+ "nodes": sorted(node["id"] for node in status["nodes"]),+ "events": status["events"][-8:],+ }))+++asyncio.run(main())+"""+++class InstalledRuntimeLibraryTest(unittest.TestCase):+ """A kernel venv built from a staged runtime runs the bundled machines.++ The kernel installs prime-agent-runtime non-editably into its venv (the+ bootstrap's ``uv pip install <staged runtime>`` builds the hatchling+ wheel, whose target package is ``src/rlm``), so the machine library+ must resolve from the installed package — ``site-packages/rlm/+ machines`` — not from any source-checkout path. This stages the+ runtime the way the release does, installs it into a fresh venv, and+ runs ``rlm.factory.run("review-sweep")`` end-to-end in that interpreter+ against a scripted host, asserting the machine came from the installed+ wheel.+ """++ # Names the release staging drops from the runtime tree (the assemble+ # script's RUNTIME_EXCLUDED_NAMES): the venv bootstrap installs the+ # staged layout, so the test stages the same way.+ STAGING_EXCLUDED = frozenset({"test", "uv.lock", ".venv", "__pycache__", ".pytest_cache"})++ def setUp(self) -> None:+ temp = TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ self.root = Path(temp.name).resolve()++ def stage_runtime(self) -> Path:+ """Copy the runtime tree the release-staging way, minus its excludes."""+ runtime_dir = Path(__file__).resolve().parents[1]+ staged = self.root / "payload" / "prime-agent-runtime"+ for source in runtime_dir.rglob("*"):+ relative = source.relative_to(runtime_dir)+ if any(part in self.STAGING_EXCLUDED for part in relative.parts):+ continue+ target = staged / relative+ if source.is_dir():+ target.mkdir(parents=True, exist_ok=True)+ else:+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(source.read_bytes())+ return staged++ def test_kernel_venv_runs_review_sweep_from_the_installed_wheel(self) -> None:+ if os.name != "posix":+ self.skipTest("the staged kernel-venv path is POSIX-shaped")+ uv = shutil.which("uv")+ if uv is None:+ self.skipTest("uv is not available to build the kernel venv")+ staged = self.stage_runtime()+ venv = self.root / "kernel-venv"+ agent_home = self.root / "agent-home"+ agent_home.mkdir(parents=True)+ (agent_home / "settings.json").write_text(+ json.dumps({"factory": {"enabled": True}}), encoding="utf-8"+ )+ for args in (+ [uv, "venv", str(venv)],+ [uv, "pip", "install", "--python", str(venv / "bin" / "python"), "--no-deps", str(staged)],+ ):+ install = subprocess.run(+ args, capture_output=True, text=True, timeout=240, check=False+ )+ self.assertEqual(+ install.returncode, 0,+ f"{' '.join(args)} failed:\n{install.stdout}\n{install.stderr}",+ )+ run_result = subprocess.run(+ [+ str(venv / "bin" / "python"), "-I", "-c", _INSTALLED_LIBRARY_RUNNER,+ ],+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ env={**os.environ, "PRIME_AGENT_CODING_AGENT_DIR": str(agent_home)},+ )+ self.assertEqual(+ run_result.returncode, 0,+ f"the installed-runtime run failed:\n{run_result.stdout}\n{run_result.stderr}",+ )+ payload = json.loads(run_result.stdout)+ self.assertEqual(payload["state"], "done", payload)+ self.assertEqual(payload["spec_id"], "review-sweep")+ self.assertEqual(payload["machine"], "review-sweep")+ machine_path = Path(payload["machine_path"])+ self.assertTrue(machine_path.is_file(), machine_path)+ self.assertIn("site-packages", str(machine_path), machine_path)+ self.assertIn(os.path.join("rlm", "machines"), str(machine_path), machine_path)+ # The installed package is the wheel copy, not this checkout's source.+ self.assertNotIn("prime-agent-runtime", str(machine_path), machine_path)+ self.assertEqual(payload["nodes"], ["files", "report", "review"])diff --git a/scripts/release/assemble_artifacts.py b/scripts/release/assemble_artifacts.pyindex 58e91a6d4a..f9f1bd112c 100755--- a/scripts/release/assemble_artifacts.py+++ b/scripts/release/assemble_artifacts.py@@ -95,8 +95,9 @@ def binary_name_for_target(target: str) -> str:# The runtime sidecar ships only what the kernel consumes. The venv# bootstrap installs it with `uv pip install <payload>/prime-agent-runtime`# (uv's pip interface builds the hatchling wheel, whose target packages-# only `src/rlm`), and the venv cache identity hashes `src/rlm/*.py` +-# `pyproject.toml` — so the pytest suite (`test/`) and the development+# only `src/rlm`), and the venv cache identity hashes `src/rlm/*.py` + the+# packaged machine library under `src/rlm/machines` + `pyproject.toml` — so+# the pytest suite (`test/`) and the development# `uv.lock` (the pip interface never reads the project lockfile) are dead# weight in every installed tree, and dropping them changes neither the# built wheel nor the bootstrap-version identity. The cache names and