From 4a2bc052d66a66f425f7001cb9bbcaba77be2bba Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:50:07 +0000 Subject: [PATCH 1/5] crates: install per-project worker packages with nix A project lists nixpkgs packages on a Worker packages card. When the list is non-empty, every agent and checks run of that project starts its command inside `nix shell nixpkgs# nixpkgs#`, so a stdio MCP server finds what it needs on PATH. The scheduler reads the list on every run. A fixed bash wrapper builds the packages first and exits with code 86 when that fails. An agent run then fails with a reason that names the worker packages, and a checks run is a checks error, not a checks failure. The design doc gains a Worker packages row and the playwright-mcp recipe. --- crates/factory-runner/src/checks.rs | 41 ++++++++--- crates/factory-runner/src/lib.rs | 1 + crates/factory-runner/src/packages.rs | 40 +++++++++++ crates/factory-runner/src/worker.rs | 14 +++- crates/factory-runner/tests/codex.rs | 2 + crates/factory-runner/tests/copilot.rs | 1 + crates/factory-runner/tests/github.rs | 61 ++++++++++++++++ crates/factory-runner/tests/runner.rs | 49 +++++++++++++ crates/factory-server/src/lib.rs | 1 + crates/factory-server/src/packages.rs | 88 ++++++++++++++++++++++++ crates/factory-server/src/pages.rs | 30 +++++++- crates/factory-server/src/podman.rs | 10 ++- crates/factory-server/src/scheduler.rs | 10 ++- crates/factory-server/src/store.rs | 47 ++++++++++++- crates/factory-server/src/web.rs | 34 +++++++++ crates/factory-server/tests/dashboard.rs | 69 ++++++++++++++++++- crates/factory-server/tests/podman.rs | 1 + crates/factory-server/tests/scheduler.rs | 79 +++++++++++++++++++++ docs/design.md | 16 ++++- e2e/tests/project-settings.spec.ts | 26 +++++++ 20 files changed, 603 insertions(+), 17 deletions(-) create mode 100644 crates/factory-runner/src/packages.rs create mode 100644 crates/factory-server/src/packages.rs diff --git a/crates/factory-runner/src/checks.rs b/crates/factory-runner/src/checks.rs index b7e06cdb..5c24ceae 100644 --- a/crates/factory-runner/src/checks.rs +++ b/crates/factory-runner/src/checks.rs @@ -5,20 +5,26 @@ use std::process::Stdio; use factory_core::Event; use tokio::process::Command; +use crate::packages; use crate::worker::{WORK_DIR, WorkerConfig}; const MAX_REPORT: usize = 30_000; +const MAX_PACKAGE_ERROR: usize = 4_000; /// Exit codes podman uses for its own errors, as opposed to the command's. const PODMAN_ERRORS: [i32; 3] = [125, 126, 127]; /// The arguments after `podman` to run `command` with bash in the job's /// checkout. The container gets no Claude token and no GitHub credentials. +/// With `packages`, the command runs in a `nix shell` with them on `PATH`, and +/// bash is not a login shell, because the image's `/etc/profile` resets `PATH` +/// and would drop them. #[must_use] pub fn checks_args( config: &WorkerConfig, name: &str, workspace: &Path, command: &str, + packages: &[String], ) -> Vec { let mut volume = OsString::from(workspace.as_os_str()); volume.push(format!(":{WORK_DIR}")); @@ -45,9 +51,15 @@ pub fn checks_args( args.push("--volume".into()); args.push(volume.into()); } - for arg in [config.image.as_str(), "bash", "-lc", command] { - args.push(arg.into()); - } + args.push(config.image.as_str().into()); + let flag = if packages.is_empty() { "-lc" } else { "-c" }; + args.extend(packages::wrap( + packages, + ["bash", flag, command] + .into_iter() + .map(OsString::from) + .collect(), + )); args } @@ -63,9 +75,10 @@ pub async fn run_checks( name: &str, workspace: &Path, command: &str, + packages: &[String], ) -> Result { let output = Command::new(&config.podman) - .args(checks_args(config, name, workspace, command)) + .args(checks_args(config, name, workspace, command, packages)) .stdin(Stdio::null()) .kill_on_drop(true) .output() @@ -76,6 +89,12 @@ pub async fn run_checks( } let mut text = String::from_utf8_lossy(&output.stdout).into_owned(); text.push_str(&String::from_utf8_lossy(&output.stderr)); + if !packages.is_empty() && output.status.code() == Some(packages::FAILED_CODE) { + return Err(packages::failure( + packages, + &format!(": {}", tail(text.trim(), MAX_PACKAGE_ERROR)), + )); + } if output .status .code() @@ -87,15 +106,19 @@ pub async fn run_checks( text.trim() )); } - let mut start = text.len().saturating_sub(MAX_REPORT); - while !text.is_char_boundary(start) { - start += 1; - } Ok(Event::ChecksFailed { report: format!( "`{command}` failed ({}):\n\n{}", output.status, - &text[start..] + tail(&text, MAX_REPORT) ), }) } + +fn tail(text: &str, max: usize) -> &str { + let mut start = text.len().saturating_sub(max); + while !text.is_char_boundary(start) { + start += 1; + } + &text[start..] +} diff --git a/crates/factory-runner/src/lib.rs b/crates/factory-runner/src/lib.rs index c29ebb74..05d1944d 100644 --- a/crates/factory-runner/src/lib.rs +++ b/crates/factory-runner/src/lib.rs @@ -17,6 +17,7 @@ mod github; mod gitlab; mod images; mod outcome; +mod packages; mod prompt; mod stream; mod worker; diff --git a/crates/factory-runner/src/packages.rs b/crates/factory-runner/src/packages.rs new file mode 100644 index 00000000..7b11ad64 --- /dev/null +++ b/crates/factory-runner/src/packages.rs @@ -0,0 +1,40 @@ +use std::ffi::OsString; + +/// The exit code the wrapper uses when the packages cannot be built, so the +/// factory tells that apart from the wrapped command's own failure. +pub const FAILED_CODE: i32 = 86; + +/// Collects the package names before `--`, builds them so a failure is +/// reported before the command starts, then runs the command in a nix shell. +/// The package names arrive as arguments, never inside this text. +const SCRIPT: &str = r#"pkgs=() +while [ "$1" != -- ]; do pkgs+=("nixpkgs#$1"); shift; done +shift +nix build --no-link "${pkgs[@]}" >&2 || exit 86 +exec nix shell "${pkgs[@]}" --command "$@""#; + +/// The container command that runs `command` with `packages` on `PATH`, +/// which is `command` itself when the list is empty. +#[must_use] +pub fn wrap(packages: &[String], command: Vec) -> Vec { + if packages.is_empty() { + return command; + } + let mut args: Vec = ["bash", "-c", SCRIPT, "factory-worker-packages"] + .into_iter() + .map(OsString::from) + .collect(); + args.extend(packages.iter().map(OsString::from)); + args.push("--".into()); + args.extend(command); + args +} + +/// Why a run failed when its packages could not be installed. +#[must_use] +pub fn failure(packages: &[String], detail: &str) -> String { + format!( + "the worker packages ({}) could not be installed{detail}", + packages.join(", ") + ) +} diff --git a/crates/factory-runner/src/worker.rs b/crates/factory-runner/src/worker.rs index 8f4afbc7..b674d093 100644 --- a/crates/factory-runner/src/worker.rs +++ b/crates/factory-runner/src/worker.rs @@ -9,6 +9,7 @@ use tokio::process::Command; use crate::agent::{AgentItem, Credential, RunResult, TokenUsage, backend}; use crate::outcome::{Expect, failed_event}; +use crate::packages; use crate::stream::LogLine; /// Where the job's checkout appears inside the worker. @@ -192,6 +193,9 @@ pub struct WorkerRun { /// The MCP servers active for this run, or `None` when none is. `None` /// passes no MCP config, so the arguments are unchanged. pub mcp: Option, + /// The project's nixpkgs packages. A non-empty list runs the agent inside + /// `nix shell` with them on `PATH`; an empty one changes nothing. + pub packages: Vec, } #[derive(Debug, Clone, PartialEq)] @@ -298,7 +302,7 @@ pub fn podman_args(config: &WorkerConfig, run: &WorkerRun) -> Vec { } args.push(config.image.clone().into()); - args.extend(backend.command(config, run)); + args.extend(packages::wrap(&run.packages, backend.command(config, run))); args } @@ -399,6 +403,14 @@ pub async fn run( Credential::File(name) => fs::read_to_string(run.config_dir.join(name)).ok(), Credential::Env(_) => None, }; + if !run.packages.is_empty() + && collected.result.is_none() + && status + .as_ref() + .is_ok_and(|status| status.code() == Some(packages::FAILED_CODE)) + { + return failed(packages::failure(&run.packages, &tail(&stderr))); + } collected.into_report(run.expect, credential, status, &stderr) } diff --git a/crates/factory-runner/tests/codex.rs b/crates/factory-runner/tests/codex.rs index d5218b9e..6036534f 100644 --- a/crates/factory-runner/tests/codex.rs +++ b/crates/factory-runner/tests/codex.rs @@ -33,6 +33,7 @@ fn codex_run(dir: &Path, session: SessionRun) -> WorkerRun { model: None, effort: None, mcp: None, + packages: Vec::new(), } } @@ -343,6 +344,7 @@ fn a_claude_run_is_unchanged_by_the_codex_backend() { name: "context7".into(), }], }), + packages: Vec::new(), }; let args = strings(&factory_runner::podman_args(&WorkerConfig::default(), &run)); diff --git a/crates/factory-runner/tests/copilot.rs b/crates/factory-runner/tests/copilot.rs index 933e4b59..e578ef8a 100644 --- a/crates/factory-runner/tests/copilot.rs +++ b/crates/factory-runner/tests/copilot.rs @@ -35,6 +35,7 @@ fn copilot_run(dir: &Path, session: SessionRun) -> WorkerRun { model: None, effort: None, mcp: None, + packages: Vec::new(), } } diff --git a/crates/factory-runner/tests/github.rs b/crates/factory-runner/tests/github.rs index 098ad6d4..e7e2481c 100644 --- a/crates/factory-runner/tests/github.rs +++ b/crates/factory-runner/tests/github.rs @@ -246,6 +246,7 @@ fn checks_run_with_bash_in_the_checkout_without_tokens() { "factory-job-7", Path::new("/jobs/7/work"), "just lint", + &[], ) .iter() .map(|arg| arg.to_string_lossy().into_owned()) @@ -256,6 +257,65 @@ fn checks_run_with_bash_in_the_checkout_without_tokens() { assert!(!args.iter().any(|arg| arg.contains("secret"))); } +#[test] +fn checks_with_packages_run_the_command_inside_nix_shell() { + let config = WorkerConfig::default(); + let packages = ["a".to_owned(), "b".to_owned()]; + let args: Vec = checks_args( + &config, + "factory-job-7", + Path::new("/jobs/7/work"), + "just lint; echo $HOME", + &packages, + ) + .iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + let image = args.iter().position(|arg| *arg == config.image).unwrap(); + assert_eq!(args[image + 1], "bash"); + assert_eq!(args[image + 2], "-c"); + assert!(args[image + 3].contains("nix shell")); + assert!(!args[image + 3].contains("just lint")); + assert_eq!( + args[image + 4..], + [ + "factory-worker-packages", + "a", + "b", + "--", + "bash", + "-c", + "just lint; echo $HOME" + ] + ); +} + +#[tokio::test] +async fn packages_that_cannot_be_installed_are_a_checks_error() { + let dir = tempfile::tempdir().unwrap(); + let podman = script( + dir.path(), + "podman", + "echo 'error: attribute nope missing' >&2\nexit 86", + ); + let config = WorkerConfig { + podman, + ..WorkerConfig::default() + }; + let packages = ["nope".to_owned()]; + let err = run_checks( + &config, + "factory-job-7", + Path::new("/jobs/7/work"), + "just lint", + &packages, + ) + .await + .unwrap_err(); + assert!(err.contains("worker packages (nope)"), "{err}"); + assert!(err.contains("attribute nope missing"), "{err}"); +} + #[tokio::test] async fn check_results_become_events_and_podman_errors_are_retried() { let dir = tempfile::tempdir().unwrap(); @@ -275,6 +335,7 @@ async fn check_results_become_events_and_podman_errors_are_retried() { "factory-job-7", Path::new("/jobs/7/work"), "just lint", + &[], ) .await } diff --git a/crates/factory-runner/tests/runner.rs b/crates/factory-runner/tests/runner.rs index a9bfb0ca..ee7b7d85 100644 --- a/crates/factory-runner/tests/runner.rs +++ b/crates/factory-runner/tests/runner.rs @@ -56,6 +56,7 @@ fn worker_run(dir: &Path, session: SessionRun) -> WorkerRun { model: None, effort: None, mcp: None, + packages: Vec::new(), } } @@ -485,6 +486,54 @@ fn podman_args_give_the_worker_its_token_limits_and_mounts() { ); } +#[test] +fn packages_wrap_the_agent_command_in_nix_shell_and_no_packages_change_nothing() { + let config = WorkerConfig::default(); + let plain = strings(&podman_args( + &config, + &worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())), + )); + let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())); + run.packages = vec!["a".into(), "b".into()]; + let wrapped = strings(&podman_args(&config, &run)); + + let image = plain.iter().position(|arg| *arg == config.image).unwrap(); + assert_eq!(plain[..=image], wrapped[..=image]); + assert_eq!(wrapped[image + 1..image + 3], ["bash", "-c"]); + assert!(wrapped[image + 3].contains("nix shell")); + assert_eq!( + wrapped[image + 4..image + 8], + ["factory-worker-packages", "a", "b", "--"] + ); + assert_eq!(wrapped[image + 8..], plain[image + 1..]); +} + +#[tokio::test] +async fn a_package_failure_fails_the_run_with_the_packages_named() { + let dir = tempfile::tempdir().unwrap(); + let empty = dir.path().join("empty"); + fs::write(&empty, "").unwrap(); + let config = WorkerConfig { + podman: fake_podman(dir.path(), &empty, "error: attribute nope missing", 86), + ..WorkerConfig::default() + }; + let mut worker = worker_run(dir.path(), SessionRun::Start(SESSION.into())); + worker.packages = vec!["nope".into(), "also".into()]; + + let report = run(&config, &worker, |_| {}, |_| {}, |_| {}).await; + let reason = failure_reason(report.event); + assert!( + reason.contains("worker packages (nope, also) could not be installed"), + "{reason}" + ); + assert!(reason.contains("attribute nope missing"), "{reason}"); + + // Without packages the same exit code is an ordinary failed run. + worker.packages = Vec::new(); + let report = run(&config, &worker, |_| {}, |_| {}, |_| {}).await; + assert!(!failure_reason(report.event).contains("worker packages")); +} + #[test] fn a_later_run_resumes_the_session() { let args = strings(&podman_args( diff --git a/crates/factory-server/src/lib.rs b/crates/factory-server/src/lib.rs index 1a9ee346..23d43477 100644 --- a/crates/factory-server/src/lib.rs +++ b/crates/factory-server/src/lib.rs @@ -13,6 +13,7 @@ mod github; mod gitlab; mod localtime; mod mcp; +mod packages; mod pages; mod podman; mod projects; diff --git a/crates/factory-server/src/packages.rs b/crates/factory-server/src/packages.rs new file mode 100644 index 00000000..7b9314ce --- /dev/null +++ b/crates/factory-server/src/packages.rs @@ -0,0 +1,88 @@ +//! The validation of a project's worker packages: the nixpkgs attribute paths +//! the factory puts on `PATH` in each of the project's workers. + +const MAX_PACKAGES: usize = 32; +const MAX_LEN: usize = 128; + +/// Checks the packages posted for a project. Entries are trimmed, a blank one +/// is dropped and a duplicate collapses into its first place. Returns the +/// list to save, or the problem, which names the entry. +/// +/// # Errors +/// +/// Fails when an entry is not a dotted nixpkgs attribute path of letters, +/// digits, `_`, `+` and `-`, is longer than 128 bytes, or there are more than +/// 32 entries. +pub fn validate<'a>(entries: impl IntoIterator) -> Result, String> { + let mut packages: Vec = Vec::new(); + for entry in entries { + let entry = entry.trim(); + if entry.is_empty() { + continue; + } + if entry.len() > MAX_LEN { + return Err(format!( + "the package {:?} is longer than {MAX_LEN} bytes", + &entry[..entry.floor_char_boundary(40)] + )); + } + if !is_attribute_path(entry) { + return Err(format!( + "{entry:?} is not a nixpkgs package name; use an attribute path such as playwright-mcp or python3Packages.requests" + )); + } + if !packages.iter().any(|seen| seen == entry) { + packages.push(entry.to_owned()); + } + } + if packages.len() > MAX_PACKAGES { + return Err(format!( + "a project can list at most {MAX_PACKAGES} packages" + )); + } + Ok(packages) +} + +fn is_attribute_path(entry: &str) -> bool { + entry.split('.').all(|part| { + !part.is_empty() + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-')) + }) +} + +#[cfg(test)] +mod tests { + use super::validate; + + #[test] + fn keeps_order_trims_and_collapses_duplicates() { + let packages = validate([ + " playwright-mcp ", + "", + "python3Packages.requests", + "playwright-mcp", + ]); + assert_eq!( + packages.unwrap(), + ["playwright-mcp", "python3Packages.requests"] + ); + } + + #[test] + fn rejects_shell_text_flake_references_and_bad_dots() { + for bad in ["foo;rm -rf /", "nixpkgs#foo", "a..b", ".a", "a.", "a b"] { + let err = validate([bad]).unwrap_err(); + assert!(err.contains(bad), "{err}"); + } + } + + #[test] + fn limits_count_and_length() { + let many: Vec = (0..33).map(|n| format!("p{n}")).collect(); + assert!(validate(many.iter().map(String::as_str)).is_err()); + assert!(validate(["a".repeat(129).as_str()]).is_err()); + assert!(validate(["a".repeat(128).as_str()]).is_ok()); + } +} diff --git a/crates/factory-server/src/pages.rs b/crates/factory-server/src/pages.rs index a2845b4f..6e09f307 100644 --- a/crates/factory-server/src/pages.rs +++ b/crates/factory-server/src/pages.rs @@ -784,7 +784,9 @@ pub struct ProjectSettings { pub upstream: UpstreamCard, /// The project's local checks command, or `None` when it has none. pub checks: Option, - /// The form token the Local checks card posts. + /// The project's worker packages. + pub packages: Vec, + /// The form token the Local checks and Worker packages cards post. pub checks_csrf: String, } @@ -1918,6 +1920,7 @@ pub fn settings_project( (project_forge_account_card(&project.name, card)) } (project_checks_card(project)) + (project_packages_card(project)) (project_maintenance_card(project)) (project_servers_card(project, nav.admin)) @if let Some(problem) = problem { @@ -1985,6 +1988,31 @@ fn project_checks_card(project: &ProjectSettings) -> Markup { } } +fn project_packages_card(project: &ProjectSettings) -> Markup { + html! { + form.card.settings-form method="post" + action={ "/settings/projects/" (crate::web::query_escape(&project.name)) "/packages" } { + h2 { "Worker packages" } + div.field { + label for="packages" { "nixpkgs packages" } + textarea #packages.wide name="packages" rows="4" + autocapitalize="none" spellcheck="false" placeholder="playwright-mcp" { + (project.packages.join("\n")) + } + p.hint { + "One nixpkgs package per line, such as playwright-mcp or python3Packages.requests. " + "The factory puts them on PATH in every agent and checks run of this project, " + "which is how a stdio MCP server gets the tools it needs. The first run with a new " + "package takes longer while nix downloads it." + } + p.hint { "A change applies at the next run. A run already in the worker keeps the packages it started with." } + } + input type="hidden" name="csrf" value=(project.checks_csrf); + (save_bar("Save packages")) + } + } +} + fn project_maintenance_card(project: &ProjectSettings) -> Markup { let maintenance = &project.maintenance; let packaging = maintenance.packaging.as_ref(); diff --git a/crates/factory-server/src/podman.rs b/crates/factory-server/src/podman.rs index b766f07c..589d960d 100644 --- a/crates/factory-server/src/podman.rs +++ b/crates/factory-server/src/podman.rs @@ -322,6 +322,7 @@ impl Executor for PodmanExecutor { model: request.model, effort: request.effort, mcp: request.mcp, + packages: request.packages, }; let report = run( &config, @@ -368,7 +369,14 @@ impl Executor for PodmanExecutor { ), }); } - run_checks(&config, &name, &workspace, &request.command).await + run_checks( + &config, + &name, + &workspace, + &request.command, + &request.packages, + ) + .await } async fn summarize(&self, request: SummaryRequest) -> Result { diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index fce6fea5..e7c3e0ca 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -124,6 +124,8 @@ pub struct AgentRequest { /// proxy token, or `None` when none is active. The runner passes it to /// `claude --mcp-config`. pub mcp: Option, + /// The project's worker packages, read on every run. + pub packages: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -133,6 +135,8 @@ pub struct ChecksRequest { pub base: String, /// The project's `checks` command. pub command: String, + /// The project's worker packages, read on every run. + pub packages: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -798,7 +802,7 @@ impl Scheduler { }); } Command::RunChecks { .. } => { - self.checks(row.id, &project, &settings, workers_free)?; + self.checks(row.id, &row.project, &project, &settings, workers_free)?; } Command::Summarize { .. } if self.due(row.id) => { self.summarize(row.id, &project, &settings); @@ -1366,6 +1370,7 @@ impl Scheduler { model, effort: Some(effort), mcp: selection.config, + packages: self.store.project_packages(&row.project)?, }; Ok((request, selection.skipped)) } @@ -1492,6 +1497,7 @@ impl Scheduler { fn checks( self: &Arc, job_id: i64, + project_name: &str, project: &Project, settings: &Settings, workers_free: bool, @@ -1511,6 +1517,7 @@ impl Scheduler { let scheduler = Arc::clone(self); let settings = settings.clone(); let base = project.base.clone(); + let packages = self.store.project_packages(project_name)?; self.spawn(job_id, Kind::Worker, async move { scheduler.note(job_id, &format!("Running the checks: {command}")); let result = scheduler @@ -1521,6 +1528,7 @@ impl Scheduler { job_id, base, command, + packages, }, ) .await; diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index bf04819f..3b159544 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -214,6 +214,10 @@ CREATE TABLE IF NOT EXISTS project_mcp_args ( args TEXT NOT NULL, PRIMARY KEY (project, server) ); +CREATE TABLE IF NOT EXISTS project_packages ( + project TEXT PRIMARY KEY, + packages TEXT NOT NULL +); CREATE TABLE IF NOT EXISTS cost_closed_jobs ( job_id INTEGER PRIMARY KEY REFERENCES jobs (id) ); @@ -3219,7 +3223,7 @@ impl Store { /// The deleted configuration is the project's rows in `projects`, /// `project_models`, `project_settings`, `project_gates`, `project_efforts`, /// `project_agents`, `project_mcp`, `project_mcp_tools`, - /// `project_mcp_tool_refreshes`, `project_mcp_args`, `project_totals` and + /// `project_mcp_tool_refreshes`, `project_mcp_args`, `project_packages`, `project_totals` and /// `project_collaborators`, `project_maintenance`, `renovate_prs`, its MCP header values in `secrets`, its /// `job_costs` rows, and the `cost` rows in `job_events` for its jobs. With /// no collaborator rows left, the project and its surviving jobs are visible @@ -3267,6 +3271,7 @@ impl Store { "project_mcp_tools", "project_mcp_tool_refreshes", "project_mcp_args", + "project_packages", "project_totals", "project_collaborators", "project_maintenance", @@ -3756,6 +3761,46 @@ impl Store { Ok(()) } + /// The nixpkgs packages `project` puts on `PATH` in its workers, in the + /// order saved. Empty when none is saved. + /// + /// # Errors + /// + /// Fails on a database error or when the stored list is not valid JSON. + pub fn project_packages(&self, project: &str) -> Result, StoreError> { + let stored: Option = self + .conn() + .query_row( + "SELECT packages FROM project_packages WHERE project = ?1", + [project], + |row| row.get(0), + ) + .optional()?; + match stored { + Some(json) => Ok(serde_json::from_str(&json)?), + None => Ok(Vec::new()), + } + } + + /// Saves `project`'s worker packages, writing only this row. The caller has + /// validated them with [`crate::packages::validate`]. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn save_project_packages( + &self, + project: &str, + packages: &[String], + ) -> Result<(), StoreError> { + self.conn().execute( + "INSERT INTO project_packages (project, packages) VALUES (?1, ?2) + ON CONFLICT (project) DO UPDATE SET packages = excluded.packages", + params![project, serde_json::to_string(packages)?], + )?; + Ok(()) + } + /// Saves a project's auto-merge and LLM-review flags together, so the one /// settings form writes the whole row. A saved row replaces the project /// file defaults as a whole. diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index d9a62181..da5a158d 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -289,6 +289,10 @@ fn project_card_routes() -> Router { "/settings/projects/{project}/checks", post(save_project_checks), ) + .route( + "/settings/projects/{project}/packages", + post(save_project_packages), + ) .route("/settings/projects/{project}/name", post(save_project_name)) .route( "/settings/projects/{project}/maintenance/check", @@ -2099,6 +2103,7 @@ fn project_settings( check: None, }, checks: project.checks.clone(), + packages: state.store.project_packages(name)?, checks_csrf: state.csrf.issue(login), }) } @@ -3194,6 +3199,35 @@ async fn save_project_checks( ) } +#[derive(Deserialize)] +struct PackagesForm { + #[serde(default)] + packages: String, + #[serde(default)] + csrf: String, +} + +async fn save_project_packages( + State(state): State, + headers: HeaderMap, + Path(project): Path, + Form(form): Form, +) -> Result { + visible_project(&state, &headers, &project)?; + require_csrf(&state, &user(&headers), &form.csrf)?; + let packages = + crate::packages::validate(form.packages.lines()).map_err(AppError::BadRequest)?; + state.store.save_project_packages(&project, &packages)?; + project_page( + &state, + &headers, + &project, + pages::PipelinePart::parse(None), + Some("Saved."), + None, + ) +} + #[derive(Deserialize)] struct NameForm { #[serde(default)] diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index ec2fc9de..3c8cc561 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -11740,7 +11740,7 @@ async fn each_settings_form_ends_in_a_save_bar_and_the_page_tracks_changes() { ] { let body = dashboard.get(uri).await.body; let bars = if uri == "/settings/projects/maestro" { - 6 + 7 } else { 1 }; @@ -14969,6 +14969,73 @@ async fn a_non_collaborator_cannot_save_the_checks_command() { ); } +async fn packages_post(dashboard: &Dashboard, login: &str, packages: &str) -> Reply { + let page = dashboard.get_as(login, PROJECT_PAGE).await; + let doc = scraper::Html::parse_document(&page.body); + let csrf = doc + .select(&scraper::Selector::parse("form[action$='/packages'] input[name=csrf]").unwrap()) + .next() + .and_then(|input| input.value().attr("value")) + .expect("the Worker packages card carries a csrf token") + .to_owned(); + dashboard + .post_as( + login, + &format!("{PROJECT_PAGE}/packages"), + &format!("packages={packages}&csrf={csrf}"), + ) + .await +} + +#[tokio::test] +async fn the_worker_packages_card_saves_validates_and_shows_the_list() { + let dashboard = dashboard(); + let page = dashboard.get(PROJECT_PAGE).await.body; + assert!(page.contains("

Worker packages

")); + + let reply = packages_post( + &dashboard, + USER, + "playwright-mcp%0D%0Apython3Packages.requests%0A", + ) + .await; + assert_eq!(reply.status, StatusCode::OK); + let stored = vec![ + "playwright-mcp".to_owned(), + "python3Packages.requests".to_owned(), + ]; + assert_eq!(dashboard.store.project_packages("maestro").unwrap(), stored); + let page = dashboard.get(PROJECT_PAGE).await.body; + assert!(page.contains("playwright-mcp\npython3Packages.requests")); + + for bad in ["foo%3Brm+-rf+%2F", "nixpkgs%23foo"] { + let reply = packages_post(&dashboard, USER, bad).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST, "{bad}"); + assert_eq!(dashboard.store.project_packages("maestro").unwrap(), stored); + } +} + +#[tokio::test] +async fn a_collaborator_of_another_project_cannot_save_worker_packages() { + let dashboard = two_projects(); + dashboard + .store + .add_collaborator("tool", DAVE, "test") + .unwrap(); + let reply = dashboard + .post_as( + DAVE, + "/settings/projects/maestro/packages", + "packages=evil&csrf=x", + ) + .await; + assert_eq!(reply.status, StatusCode::NOT_FOUND); + assert_eq!( + dashboard.store.project_packages("maestro").unwrap(), + Vec::::new() + ); +} + #[tokio::test] async fn checks_requests_without_a_valid_form_token_change_nothing() { let dashboard = dashboard(); diff --git a/crates/factory-server/tests/podman.rs b/crates/factory-server/tests/podman.rs index f6bea5f6..6577a4e6 100644 --- a/crates/factory-server/tests/podman.rs +++ b/crates/factory-server/tests/podman.rs @@ -82,6 +82,7 @@ fn request() -> AgentRequest { model: None, effort: None, mcp: None, + packages: Vec::new(), } } diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index 32d8924b..9c23947f 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -7302,3 +7302,82 @@ fn the_upstream_credential_is_the_upstream_token_then_the_project_token_then_non } ); } + +fn to_verifying(store: &Store, project: &str, text: &str) -> i64 { + let id = store.create(project, "alice", text).unwrap(); + for event in [ + Event::Start, + Event::Agent(AgentResult::Clarified), + Event::Agent(AgentResult::Spec("s".into())), + Event::Approve, + Event::Agent(AgentResult::Plan(vec![factory_core::PlannedPr { + title: "t".into(), + summary: "s".into(), + number: None, + description: None, + notes: None, + }])), + Event::Approve, + Event::Agent(AgentResult::CommitsReady(ready())), + ] { + store.apply(id, event).unwrap(); + } + id +} + +#[tokio::test] +async fn worker_packages_reach_only_their_projects_agent_and_checks_runs() { + let (store, executor, scheduler) = setup_two_projects(|_| questions()); + store + .save_project_packages("maestro", &strings(&["playwright-mcp", "jq"])) + .unwrap(); + store.create("maestro", "alice", "one").unwrap(); + store.create("factory", "alice", "two").unwrap(); + + scheduler.tick().await.unwrap(); + executor.release(2); + wait_idle(&scheduler).await; + let requests = executor.requests(); + let packages_of = |repo: &str| { + requests + .iter() + .find(|r| r.repo.ends_with(repo)) + .unwrap() + .packages + .clone() + }; + assert_eq!(packages_of("maestro"), strings(&["playwright-mcp", "jq"])); + assert_eq!(packages_of("factory"), Vec::::new()); + + to_verifying(&store, "maestro", "three"); + to_verifying(&store, "factory", "four"); + step(&scheduler).await; + let checks = executor.checks_run.lock().unwrap().clone(); + assert_eq!(checks.len(), 2); + let with_packages: Vec<_> = checks.iter().filter(|c| !c.packages.is_empty()).collect(); + assert_eq!(with_packages.len(), 1); + assert_eq!( + with_packages[0].packages, + strings(&["playwright-mcp", "jq"]) + ); +} + +#[tokio::test] +async fn a_change_to_the_worker_packages_reaches_the_next_run() { + let (store, executor, scheduler) = setup_two_projects(|_| questions()); + store.create("maestro", "alice", "one").unwrap(); + scheduler.tick().await.unwrap(); + executor.release(1); + wait_idle(&scheduler).await; + assert_eq!(executor.requests()[0].packages, Vec::::new()); + + store + .save_project_packages("maestro", &strings(&["jq"])) + .unwrap(); + to_verifying(&store, "maestro", "two"); + step(&scheduler).await; + assert_eq!( + executor.checks_run.lock().unwrap()[0].packages, + strings(&["jq"]) + ); +} diff --git a/docs/design.md b/docs/design.md index f5275f40..290ed2a9 100644 --- a/docs/design.md +++ b/docs/design.md @@ -41,7 +41,7 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | MCP tool toggles | A project can turn off single tools of an MCP server it uses. Every tool is on by default, so the factory stores the tools that are off, and a project with none off behaves as before. The setting is per project and server and applies to all five stages, without a per-stage grid. A tool a server adds later starts on. The settings page marks it "new" so an operator sees it. The `project_mcp_tools` table holds the last tool list per project and server, keyed by project, server and tool name, with the tool's description, an `offered` flag, a `disabled` flag and the number of the refresh that first saw it. `project_mcp_tool_refreshes` counts each project and server's refreshes, so a tool is "new" when the latest refresh first saw it and is not the first one. The list is per project because a server may offer different tools for different credentials. "Refresh connection" fills the table, see MCP connection check: after a successful `initialize` it sends `notifications/initialized` and pages through `tools/list` by its cursor with the negotiated `MCP-Protocol-Version` and the `Mcp-Session-Id`. The same 15-second total timeout covers the whole exchange, and each reply is read up to 1 MiB. Only a complete list replaces the stored one. A tool missing from it keeps its row with `offered` cleared, so a turned-off tool stays off if the server offers it again, and the page lists it as "no longer offered". A failed list keeps the old rows and the result says the tools could not be listed. The refresh route returns the page's refresh area, the button, the result and the tool list, and htmx replaces that area, found from the button with `closest .mcp-refresh`. The swap drops unsaved changes to that list's checkboxes, and the hint says so. The list sits on the project's page for the server as one checkbox per stored tool, checked when on, with its description. Each shown tool posts a hidden `mcp..shown.` field and, when checked, `mcp..tool.`. A server name has no `.`, so the handler splits the tool name off after the prefix. The save handler turns off the shown tools left unchecked and turns on the checked ones. It leaves a tool the form did not show as it is, so a refresh between render and save turns nothing off by accident. The proxy enforces the setting, because a worker with `bypassPermissions` and a run token could call a tool with `curl` that a Claude Code flag only hid from the model. `StoreUpstreams` returns the server's turned-off tool names with its headers, read on each request, so a change reaches a run in flight at its next request. For a POST, the proxy parses the body it already buffers as JSON-RPC, rejecting duplicate keys so it and the server cannot read two different tool names. A `tools/call` whose `params.name` is off gets a JSON-RPC error that names the tool as turned off for the project, with the request's `id`, and the proxy forwards nothing. A batch array holding such a call gets a 403 and nothing is forwarded. When the server has a tool turned off, a POST body that does not parse gets a 400 rather than being forwarded. A `tools/list` reply is buffered up to 4 MiB and the turned-off tools are removed from `result.tools`, in a JSON body or in the SSE event carrying the response, with other SSE events passed through as they are. A reply over the cap or one that does not parse is relayed unchanged, and the call block still applies. A stream resumed by `Last-Event-ID` may replay an unfiltered list, and the call block applies there too. Every other request and response streams as before. Each blocked call goes through `McpWarnings`, deduped per run, server and tool, and `Store` writes a factory line to the job log and an `mcp-tool-blocked` row in `job_events` with `: ` in its `detail`, which the job page timeline shows as a note under the step. Deleting a server deletes its tool rows with its `project_mcp` rows. A rename loses them like the stored values. An edit that changes the URL's origin clears `offered` on every row and keeps each `disabled` flag until the next refresh. A stdio server has no tool toggles. The proxy is what enforces them, a stdio server bypasses it, and listing its tools needs the same throwaway container as the connection check. A toggle could then only hide a tool from the model, not block it. Both are a follow-up. | | Job MCP tool calls | The proxy records every call a job makes to a remote server, and the scheduler records every call to a stdio server from the agent's output. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. A call to a stdio server never reaches the proxy, so the scheduler records it from the agent's output. The scheduler's log sink sees each `LogLine::Tool` the parsers emit. When its name is `mcp____` and `` is a stdio server of that run, the sink calls `McpWarnings::record_tool_called`, which writes the same `mcp-tool-call` row under the run's job. The name splits at the first `__` after the prefix, because a server name holds no underscore. A tool name that belongs to a remote server is skipped, so no call is counted twice. All three parsers already emit that name: Claude from `tool_use`, Codex from `mcp_tool_call` and Copilot from the `mcpServerName` and `mcpToolName` of `tool.execution_start`. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. | | Approval gates | Spec, plan and publish. Each project has its own gates, in a `project_gates` table in SQLite with one row per project and a column per gate. The factory-wide gates in the stored settings are the defaults: onboarding a project copies them into its row, and a later change to a default leaves existing projects alone. Spec and plan are on in the code default, publish is off. The settings page edits the defaults on the Default gates page and a project's gates on its pipeline, see Settings layout. A job copies its project's gates when it is created, so a later settings change does not touch existing jobs. Everything after the last gate runs without stopping, apart from questions the agent asks. The state machine stops at a gate only when the job has it. A job with the publish gate stops before the first push of each planned pull request and waits for approval. Later pushes to the same pull request, such as fixes for CI or review comments, are not gated. Gates were one global setting before. A one-time migration at startup gives every project with no `project_gates` row the current global gates, the way `Store::migrate_global_auto_merge` moved auto-merge, so each project keeps its earlier behaviour. You merge on GitHub, unless the project's auto-merge setting is on: then the factory squash-merges a pull request once every check passed and no review comment waits for the agent. Auto-merge is per project, see Project settings. A pull request with no checks reported yet is not merged, so a push is never merged before GitHub starts its CI. | -| Settings layout | The settings pages share a sidebar with six groups. You has Notifications, the per-user page at `/settings/notifications`, see User settings. Forges has one entry per forge kind, GitHub at `/settings/forges/github`, each a page for the login's own token on that forge, see "Forge tokens". `/settings/forges/` is a 404. A login that is not a factory admin sees only the You, Forges and Projects groups, since the Factory, Agents and Integrations pages answer it with 403, see Factory admins. Factory has Workers, Default gates, Pull request polling and Renovate. `/settings/github` redirects to `/settings/polling`, because the interval applies to every forge. Agents has one entry per registered agent, from the registry, each linking to its page: Claude's is `/settings/agents/claude` and Codex's is `/settings/agents/codex` and Copilot's is `/settings/agents/copilot`. Integrations has MCP servers. Projects has one entry per project the login collaborates on and a link to onboarding. Each entry is its own page with its own URL: `/settings/workers`, `/settings/gates`, `/settings/polling`, `/settings/forges/`, `/settings/renovate`, `/settings/agents/claude`, `/settings/agents/codex`, `/settings/agents/copilot`, `/settings/mcp`, `/settings/mcp/`, `/settings/projects/` and `/settings/projects//mcp/`. `/settings` redirects to the first project the login collaborates on, or to `/settings/notifications` when it collaborates on none. The Projects group lists only the login's own projects, from `Store::project_labels_for`, by shown name, see Dashboard access and Project display name. `/settings` redirects to the first project of that list. The project page has a Project name card above the forge account and Local checks cards, which saves the display name. The Codex page shows whether a login is stored and when Codex last refreshed it, never the file or a token. "Sign in with ChatGPT" starts a `codex login --device-auth` container from the worker image, and a fragment polls `/settings/agents/codex/login/fragment` every five seconds for the verification URL and one-time code, then for "Signed in" or a failure reason with the scrubbed output below it, under the headings described in "Copilot auth"; Cancel removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only textarea posts a pasted `auth.json` to `/settings/agents/codex/auth` as the fallback, and Clear removes the stored login. The Copilot page shows whether a token is stored, never the token, in an input value or in the page source. "Sign in with GitHub" posts to `/settings/agents/copilot/login` and starts a `copilot login --device-code` container from the worker image. A fragment at `/settings/agents/copilot/login/fragment` polls every five seconds for the URL and code with the ANSI color stripped, then for "Signed in" or a failure reason with the scrubbed output below it, under one of the two headings in "Copilot auth". The fragment that reports "Signed in" carries an `HX-Refresh` header, so the page reloads and its stored-token status updates. Cancel posts to `/settings/agents/copilot/login/cancel` and removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only token field posts to `/settings/agents/copilot/token` as the fallback, and Clear posts to `/settings/agents/copilot/token/clear`. An empty save keeps the stored token. With no master key the field and the sign-in button are disabled and Clear still works. A note says the GitHub account needs a Copilot plan, that it should not be moonthebot unless that is intended, and that the token goes to Copilot workers. The page has no price table. The Codex page also holds the Codex price table, one row per model with its input, cached input and output prices per million tokens, with a form to add or edit a model at `/settings/agents/codex/prices` and a Delete button that posts to `/settings/agents/codex/prices/delete`, see Job cost. Each page has one form, and its Save button sits in a bar that stays at the bottom of the window. The Save button comes before a Delete or Clear button in the form, so Enter in a field saves. Once an input of the form changes, the bar reads "Unsaved changes." and leaving the page asks first. `static/settings-form.js` does both, and without it the forms save the same way. A save redraws the same page with a notice. Adding a server opens its page, and deleting one opens the MCP servers page. A project's page also has a Forge account card, `#forge-account`, see "Project collaborators". A project's page has a Local checks card above the Maintenance card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/checks`, see Project registry. A project's page ends its pipeline form with a Maintenance card, a form of its own with its own save bar, see Project maintenance settings. A project's page draws its settings as the path a job takes: clarify, spec, plan, implement, review and merge, with the spec, plan and publish gates between them. Each stage shows its model, its effort and the MCP servers on in it. The agent is set in the panel, not shown on the node. Selecting a stage, a gate or merge opens its panel under the pipeline. The selection is a `?stage=` query parameter, `clarify` to `review`, `gate-spec`, `gate-plan`, `gate-publish` or `merge`, and an unknown value opens clarify. It works without JavaScript, a link opens the same panel, and a save comes back to it. Every panel sits in the one form and only the selected one shows, so a save posts every field and a hidden panel's values are kept. `static/settings-pipeline.js` switches panels without a reload, keeps the address and the form's action on the open panel, and updates the nodes as the fields change. A stage panel sets the stage's agent, its model, its effort and a switch per MCP server for that stage. The agent control lists every registered agent above the model as a selectable radio. It preselects the stage's effective agent, Claude when the project saved none. The model suggestions and the effort radios come from the selected agent: for Claude the aliases fable, opus, sonnet and haiku and the levels low, medium, high, xhigh and max, for Codex the `gpt-6` family aliases and the levels minimal, low, medium, high and xhigh, and for Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash` and the levels low, medium, high, xhigh and max. The model is typed or picked from the aliases, and the effort is five radio buttons. A server's switch is on when the server runs in that stage. Saving with a switch on turns the server on in exactly the stages switched on. Saving with every switch off stops a running server and keeps its stages for the server's own page, and leaves a stopped server as it is. The review stage reads Off and is drawn dashed while LLM review is off, and its panel holds the LLM review switch. A gate panel shows the factory default, marks a gate that differs from it on the panel and with a dot on its diamond, and offers "Use the default". The merge panel holds auto-merge. A card under the pipeline sums up each MCP server for the project and links to its page. A project's panels and MCP page link to the server registry (`/settings/mcp`) only for a factory admin. Collaborators still turn servers on and off and enter header values. A project's MCP page holds the project's header values, the connection check, the five stage switches and the tool list with a filter, a count of the tools on, and buttons to turn every shown tool on or off. `static/mcp-tools.js` runs those controls, and without it they stay hidden. A server's page holds its URL and header names and lists the projects that use it. A save that renames or removes a header, or changes the URL's origin, and so deletes stored values, is held back: `Store::mcp_edit_deletes` lists the values it would delete without writing, and the page shows the posted URL and names with each project and header it deletes and a button that saves anyway. An edit that deletes nothing saves at once. Deleting a server is a form of its own, below the edit form, and needs the server's name typed into it. Any other name deletes nothing and redraws the page with the problem. The model chips, the datalist and the hint follow the selected agent. The page draws the saved agent's set on load, so it is right without JavaScript. When the user switches a stage's agent, `settings-pipeline.js` redraws them for the new agent, as it does the effort radios. A model field that holds one of the previous agent's suggestions is cleared to "CLI default", because the new agent would refuse it. A typed id that is not one of those suggestions stays. The "CLI default" chip stays for every agent. Each stage panel has its own chips and datalist, so a switch on one stage leaves the hidden panels alone. Job 47 is the reason: the panel offered Claude's aliases for a Copilot stage. A project's page for a stdio server, `/settings/projects//mcp/`, shows the enabled switch, the stages, the command and base arguments, the project's extra arguments and the command line a run starts. The project's pipeline panels list a stdio server with a switch per stage like a remote one, and the project's MCP servers card marks it "stdio". | +| Settings layout | The settings pages share a sidebar with six groups. You has Notifications, the per-user page at `/settings/notifications`, see User settings. Forges has one entry per forge kind, GitHub at `/settings/forges/github`, each a page for the login's own token on that forge, see "Forge tokens". `/settings/forges/` is a 404. A login that is not a factory admin sees only the You, Forges and Projects groups, since the Factory, Agents and Integrations pages answer it with 403, see Factory admins. Factory has Workers, Default gates, Pull request polling and Renovate. `/settings/github` redirects to `/settings/polling`, because the interval applies to every forge. Agents has one entry per registered agent, from the registry, each linking to its page: Claude's is `/settings/agents/claude` and Codex's is `/settings/agents/codex` and Copilot's is `/settings/agents/copilot`. Integrations has MCP servers. Projects has one entry per project the login collaborates on and a link to onboarding. Each entry is its own page with its own URL: `/settings/workers`, `/settings/gates`, `/settings/polling`, `/settings/forges/`, `/settings/renovate`, `/settings/agents/claude`, `/settings/agents/codex`, `/settings/agents/copilot`, `/settings/mcp`, `/settings/mcp/`, `/settings/projects/` and `/settings/projects//mcp/`. `/settings` redirects to the first project the login collaborates on, or to `/settings/notifications` when it collaborates on none. The Projects group lists only the login's own projects, from `Store::project_labels_for`, by shown name, see Dashboard access and Project display name. `/settings` redirects to the first project of that list. The project page has a Project name card above the forge account and Local checks cards, which saves the display name. The Codex page shows whether a login is stored and when Codex last refreshed it, never the file or a token. "Sign in with ChatGPT" starts a `codex login --device-auth` container from the worker image, and a fragment polls `/settings/agents/codex/login/fragment` every five seconds for the verification URL and one-time code, then for "Signed in" or a failure reason with the scrubbed output below it, under the headings described in "Copilot auth"; Cancel removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only textarea posts a pasted `auth.json` to `/settings/agents/codex/auth` as the fallback, and Clear removes the stored login. The Copilot page shows whether a token is stored, never the token, in an input value or in the page source. "Sign in with GitHub" posts to `/settings/agents/copilot/login` and starts a `copilot login --device-code` container from the worker image. A fragment at `/settings/agents/copilot/login/fragment` polls every five seconds for the URL and code with the ANSI color stripped, then for "Signed in" or a failure reason with the scrubbed output below it, under one of the two headings in "Copilot auth". The fragment that reports "Signed in" carries an `HX-Refresh` header, so the page reloads and its stored-token status updates. Cancel posts to `/settings/agents/copilot/login/cancel` and removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only token field posts to `/settings/agents/copilot/token` as the fallback, and Clear posts to `/settings/agents/copilot/token/clear`. An empty save keeps the stored token. With no master key the field and the sign-in button are disabled and Clear still works. A note says the GitHub account needs a Copilot plan, that it should not be moonthebot unless that is intended, and that the token goes to Copilot workers. The page has no price table. The Codex page also holds the Codex price table, one row per model with its input, cached input and output prices per million tokens, with a form to add or edit a model at `/settings/agents/codex/prices` and a Delete button that posts to `/settings/agents/codex/prices/delete`, see Job cost. Each page has one form, and its Save button sits in a bar that stays at the bottom of the window. The Save button comes before a Delete or Clear button in the form, so Enter in a field saves. Once an input of the form changes, the bar reads "Unsaved changes." and leaving the page asks first. `static/settings-form.js` does both, and without it the forms save the same way. A save redraws the same page with a notice. Adding a server opens its page, and deleting one opens the MCP servers page. A project's page also has a Forge account card, `#forge-account`, see "Project collaborators". A project's page has a Local checks card above the Maintenance card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/checks`, see Project registry. A project's page ends its pipeline form with a Maintenance card, a form of its own with its own save bar, see Project maintenance settings. A project's page draws its settings as the path a job takes: clarify, spec, plan, implement, review and merge, with the spec, plan and publish gates between them. Each stage shows its model, its effort and the MCP servers on in it. The agent is set in the panel, not shown on the node. Selecting a stage, a gate or merge opens its panel under the pipeline. The selection is a `?stage=` query parameter, `clarify` to `review`, `gate-spec`, `gate-plan`, `gate-publish` or `merge`, and an unknown value opens clarify. It works without JavaScript, a link opens the same panel, and a save comes back to it. Every panel sits in the one form and only the selected one shows, so a save posts every field and a hidden panel's values are kept. `static/settings-pipeline.js` switches panels without a reload, keeps the address and the form's action on the open panel, and updates the nodes as the fields change. A stage panel sets the stage's agent, its model, its effort and a switch per MCP server for that stage. The agent control lists every registered agent above the model as a selectable radio. It preselects the stage's effective agent, Claude when the project saved none. The model suggestions and the effort radios come from the selected agent: for Claude the aliases fable, opus, sonnet and haiku and the levels low, medium, high, xhigh and max, for Codex the `gpt-6` family aliases and the levels minimal, low, medium, high and xhigh, and for Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash` and the levels low, medium, high, xhigh and max. The model is typed or picked from the aliases, and the effort is five radio buttons. A server's switch is on when the server runs in that stage. Saving with a switch on turns the server on in exactly the stages switched on. Saving with every switch off stops a running server and keeps its stages for the server's own page, and leaves a stopped server as it is. The review stage reads Off and is drawn dashed while LLM review is off, and its panel holds the LLM review switch. A gate panel shows the factory default, marks a gate that differs from it on the panel and with a dot on its diamond, and offers "Use the default". The merge panel holds auto-merge. A card under the pipeline sums up each MCP server for the project and links to its page. A project's panels and MCP page link to the server registry (`/settings/mcp`) only for a factory admin. Collaborators still turn servers on and off and enter header values. A project's MCP page holds the project's header values, the connection check, the five stage switches and the tool list with a filter, a count of the tools on, and buttons to turn every shown tool on or off. `static/mcp-tools.js` runs those controls, and without it they stay hidden. A server's page holds its URL and header names and lists the projects that use it. A save that renames or removes a header, or changes the URL's origin, and so deletes stored values, is held back: `Store::mcp_edit_deletes` lists the values it would delete without writing, and the page shows the posted URL and names with each project and header it deletes and a button that saves anyway. An edit that deletes nothing saves at once. Deleting a server is a form of its own, below the edit form, and needs the server's name typed into it. Any other name deletes nothing and redraws the page with the problem. The model chips, the datalist and the hint follow the selected agent. The page draws the saved agent's set on load, so it is right without JavaScript. When the user switches a stage's agent, `settings-pipeline.js` redraws them for the new agent, as it does the effort radios. A model field that holds one of the previous agent's suggestions is cleared to "CLI default", because the new agent would refuse it. A typed id that is not one of those suggestions stays. The "CLI default" chip stays for every agent. Each stage panel has its own chips and datalist, so a switch on one stage leaves the hidden panels alone. Job 47 is the reason: the panel offered Claude's aliases for a Copilot stage. A project's page for a stdio server, `/settings/projects//mcp/`, shows the enabled switch, the stages, the command and base arguments, the project's extra arguments and the command line a run starts. The project's pipeline panels list a stdio server with a switch per stage like a remote one, and the project's MCP servers card marks it "stdio". A project's page has a Worker packages card below the Local checks card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/packages`, see Worker packages. | | Renovate retry limits | Two factory-wide limits govern the reruns of failed CI on a Renovate pull request. Automatic reruns is how many times the factory reruns failed CI on one head commit before it asks an agent, default 3. Total reruns is how many reruns one head commit gets before the factory comments and stops triage, default 7. They live in the settings JSON row as `renovate_auto_reruns` and `renovate_total_reruns`, so a factory that never saved them reads 3 and 7. They are factory-wide because the factory has one CI flakiness profile for its Renovate pull requests, and a per-project value would only add a field to forget. The page is `/settings/renovate`, in the Factory group and admin-only like the other Factory pages. A save is refused with a message and nothing stored when a value is not a whole number, when total is less than 1, or when automatic is greater than total. Automatic 0 is valid and sends the first failure to the agent. The Renovate triage reads them on every watch, so a change will apply to jobs already in flight and need no restart. | | Renovate pull request jobs | A Renovate job is a `Job` with `kind` `Renovate(RenovatePr)`, at its own `Stage::Renovate` with the request text set to the pull request title. A job stored before `kind` existed loads as `Request`. It skips clarify, spec, plan, implement and publish. The factory watches the pull request, and the core decides everything from what each watch reports. `Event::RenovateObserved` carries the head commit, the CI state (`NoChecks`, `Pending`, `Failed` with the log, or `Passed` with the diff and description when the job has no verdict for that head), the retry limits, the project's auto-merge flag and the project account's access (`RenovateAccess`: whether it may rerun CI, whether it may merge, and its login; a job stored before this loads with full access). The factory holds the limits and passes them in on every observation, so a saved limit reaches a job in flight with no restart and the job stores only its counts. A different head resets the reruns, the automatic reruns, the stop and the verdict. A failed observation checks the total first: at or above the total the job queues the stopped comment, which names the rerun count, and stops. Below it, the job reruns with no agent until the automatic reruns are used up, then runs `Task::AnalyzeFailure`. A transient verdict reruns and counts toward the total only. With Read access the factory makes no rerun call: a failed head goes straight to `Task::AnalyzeFailure` and a transient verdict queues a `TransientNoWrite` comment, which says the failure looks transient and that the project account needs Write to rerun CI, and stops until a new head or Retry. The executor reads the account's access with `Forge::access` and `Forge::may_merge` on every watch, so granting Write takes effect on the next head with no restart, and a failed read fails the watch so the scheduler retries. A caused-by-update verdict queues a comment with the reason and stops. A passed observation with no verdict for the head runs `Task::CheckDiff`. With a safe verdict, auto-merge on queues `Command::MergeRenovate`, which approves and merges only that head, unless the account may not merge (Read access, or a forge that refuses it), when the job waits as ready to merge and the job page names the account and the access it needs, and auto-merge off waits as ready to merge and merges on a later watch once the switch is on. An unsafe verdict queues a comment and waits. `NoChecks` and `Pending` change nothing, so a pull request with no checks never merges. A comment is a factory turn with `Command::PostComment`, answered by `Event::Commented`, and a `(head, kind)` pair is recorded so each kind posts once per head. A stopped or unsafe job waits at `Ask::Renovate` and keeps a watch-only command, so it still sees a merge, a close or a new head. A ready job keeps the full watch. Limits and the auto-merge switch arrive on every watch and core applies them. `Store::apply_in` writes no `job_events` row and does not rewrite the job for an `Event::RenovateObserved` that leaves the job equal, because every look would otherwise change the job's notification key. A change those settings cause, such as a merge or a stop, is recorded. `Event::Retry` on a stopped job resets both counts. When the stored access may rerun CI it reruns without counting that rerun. When it may not (Read), Retry returns the job to the factory turn, so a fresh watch reads the current head, CI and access and decides again. The executor checks the access of the credential it resolves before each Renovate rerun, approval and merge (an agent-requested rerun in a request job is not checked), because a collaborator may replace the token after the watch. A denied rerun returns `Event::RerunDenied`, which returns the job to the factory turn for a fresh watch, so Retry on a Read account goes to the failure analysis and not to a rerun. A denied approval or merge returns the job to watching and the executor makes no write call. The denial error starts with `NOT_PERMITTED`, and the scheduler treats it as a denial and not a retryable failure. `Event::Merged` ends in `merged` and `Event::ClosedUnmerged` in `cancelled`, which is Done and sends no notification. The comment bodies are plain text from the project account. A Renovate job has the requester `factory`, so every operation of it, and the discovery that creates it, runs as the project token. A project with Renovate on and no project token is skipped by discovery with a logged warning. The diff verdict records `from` and `to`, the upstream refs the bump moves between when the diff shows them, because the packaging analysis fetches the upstream build config changes between them. Each of the two runs starts a fresh session under `Session::Renovate` and uses the review stage's agent, model, effort and MCP servers. The worker gets the log or the diff in its prompt and no GitHub token. Discovery: on each pass the scheduler lists, for each project with "Renovate pull requests" on, the open pull requests against the project's base branch that `renovate[bot]` or `renovate` opened, at most once per 5 minutes per project, which keeps it under the spec's 10 minutes. The last listing time per project lives in memory, so a restart lists again at once. A project with the switch off gets no listing call. `create_renovate_job` inserts the job and a `renovate_prs (project, number, job_id)` row in one transaction and does nothing when the pair exists, so a pull request gets one job across restarts, even after the job finishes and expires. Job expiry leaves the table alone and `remove_project` deletes its rows. The job's requester is `factory`, because the factory made it, see Job board. The scheduler reads the retry limits from `Settings` and the project's auto-merge flag on every watch and passes them to the executor, which builds `RenovateObserved`. The executor reads the pull request status with the project token, fetches the failure log only for a failed head and the diff only for a passed head with no verdict, and reports a merge or close at once. A watch-only look reports nothing while the head is the one the job already has. A merge approves the checked head with a plain review text and then squash-merges only that head, so a commit pushed after the watch is never approved. GitHub may still accept a review of an older commit that stays in the pull request, and the merge, guarded by the head SHA, is what refuses a moved head. A refused approval or merge returns the job to watching, so the next look sees the current head or a merge or close by a person. A rerun that finds no failed Actions run changes no count and stops triage with a comment, because a rerun that never happened must not use up the limit. A rerun of a Renovate job logs "Rerunning CI" and not that the agent asked. Discovery passes the stored Renovate account to `Forge::renovate_prs` for a Salsa project and `None` for GitHub. With `None` the forge keeps `renovate[bot]` and `renovate`. With a name the GitLab forge lists open merge requests with `author_username` and `target_branch` set to the base. | | Fix job for a stopped Renovate job | A stopped Renovate job can hand its stop to a fix job, a normal job built by `Job::fix` with `JobKind::Fix { source_job, source_pr }` and a request text from `RenovatePr::fix_request`. `RenovatePr::fix` holds a `FixLink` with the fix job's id, the reason the job showed when the fix started, and a `FixState`, `Running` or `Merged` with the head at the merge and a `RebaseState` of `Pending`, `Requested` or `Failed`. A job stored without `fix` loads with none. `Event::FixStarted` applies only at the stopped wait and only when no fix runs, so a double submit creates one fix job. The job then waits as `RenovateWait::Fixing`, which keeps the watch-only command and offers no Retry, and a new head keeps a running fix. The scheduler reads a running fix job on every watch of the Renovate job, before the executor watch, because a watch-only look at the same head returns nothing. It reports `Event::FixEnded` with `Merged` for a merged stage with a numbered pull request, `Closed` for a merged stage with none and for a non-retryable failure whose reason is that the pull request closed without merging, `Cancelled` for a cancelled stage, `Dismissed` for a dismissed failure, and `Deleted` for a missing job or one whose `fix_source` is not this job and pull request, since ids may be reused. A merge carries the head the pull request had at the merge, not the last polled head. The scheduler asks the forge when the fix pull requests merged (`mergedAt`) and weighs the evidence about the current head in order: the time GitHub recorded the force push that set it decides; a commit made after the merge became the head after it; and a head the factory saw before the merge (`renovate_heads` keeps when it first saw each head) was the head by then. A head that became the head after the merge is a new head, so the empty head asks for no rebase and the factory records `RebaseSkipped`. A plain push has no date on GitHub and a commit date only bounds it from below, so a head with none of that evidence is unknown, not dated by its commit: the scheduler reports `FixOutcome::MergedUnordered` with the real head, and the job goes to Needs you with the hand-rebase message and keeps that head as its watch baseline, so watching the same head again changes nothing and only a later head restarts triage. A timeline that lacks the head's commit node still counts: the commit date is optional and the force-push event or the first-seen evidence decides. The factory's own record of the merge is not used, because it lags the real merge. A failed fix job that is not dismissed reports nothing, so the Renovate job keeps waiting while the fix job is retried from its own page. The core ignores it unless the id matches a running fix, and the store writes no `job_events` row when it leaves the job equal, so a repeated report adds none. `Store::start_fix` creates the fix job with the clicking login as requester and applies `FixStarted` in one transaction, so core's rejection of a second start rolls the new job back. A merged fix carries `head` in `FixOutcome::Merged`, the Renovate head when the fix merged, because the last head the job observed may be older or newer. After the rebase result, that head is the baseline for the next observation. The core queues one `Command::RequestRebase` for that head. `Executor::request_rebase` runs in the server process with the account that resolves for the Renovate job, like `merge_renovate`, so the worker gets no token. It reads the pull request and returns `Rebase::HeadMoved` when the head differs, and otherwise ticks the checkbox and returns `Requested` or `NoCheckbox`. The scheduler maps those to `RebaseRequested`, `RebaseSkipped` and `RebaseFailed`, and a failed write becomes `RebaseFailed` with gh's message, with no retry. The forge call takes the expected head and compares it with the head in the same read as the description, and `Store::claim_rebase` records the request in `rebase_claims` before the write, and the store grants the claim only while the job still owes a pending rebase for that fix and head, in the same transaction that inserts it, and only while the job's own `next_command()` is still that `RequestRebase`, so neither a stale command nor a cancelled job claims. A stored result or a new fix retires the claims of the Renovate job, so an old claim never blocks a later fix that reuses the id. A restart that finds the claim without a result writes nothing and reports `RebaseFailed`, since the write may have happened, so the request happens at most once per fix job. `Event::RebaseRequested` goes back to `Fixing`, `Event::RebaseSkipped` clears the fix, and `Event::RebaseFailed` waits as `RenovateWait::RebaseFailed` with the hand-rebase message. Any other ending returns the job to `Stopped`, with the newest stop reason or else the reason saved on the link, plus a line that names the fix job. It does so from the `Fixing` wait and from a factory turn on a new head. A new head after a merged fix clears the fix and starts triage from zero. The fix events store as `fix-started`, `fix-ended`, `rebase-requested`, `rebase-skipped` and `rebase-failed`. The Triage stopped card of a Renovate job shows an instructions textarea and a "Fix in a separate pull request" button next to Retry, and no other wait shows them. The form posts to `POST /jobs/{id}/fix` behind the same project collaborator check as Retry and a CSRF check with `require_csrf`, because the post creates a job. The form carries a token bound to the login, on the full page and on the polled fragment, and a missing or invalid token answers 403 and creates nothing. The page links to the fix job and back only after it checks that the stored job is still in the same project and still has the matching `fix_source` or pull request number, as it does for gap jobs, since SQLite reuses ids, and it shows plain text otherwise. The stopped reason and the line that names the fix job render on separate lines, and an empty instruction counts as none. A rejected second start answers 409. The `Fixing` wait renders "Waiting for fix job #N" with `#N` as a same-tab link and no buttons. It sits in the Factory lane, so the job is in Running and `GET /notifications` lists nothing for it, while `RebaseFailed` stays in Needs you. The Renovate job page lists its fix job, and the fix job page links back to the Renovate job. The timeline has no step for the `renovate` stage, so the fix and rebase events show as a list under the steps. `fix-started` stores the fix job's id, `fix-ended` the id and how it ended, and `rebase-failed` the reason. | @@ -54,7 +54,8 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | Remembered project | The board at `/` opens on the project last selected in this browser, so a trip to Settings and back through the factory logo does not reset the picker. A full `GET /` that carries a visible `?project=` sets the cookie `factory_project` with `Path=/`, `SameSite=Lax`, `HttpOnly` and `Max-Age=31536000`. The value is percent-encoded with `query_escape`, so any project name round-trips. There is no `Secure` attribute, because the dashboard is also reached over plain HTTP on localhost and the value is not a secret. A `GET /` with no `project` reads the cookie and uses it only when the name is in the login's `projects_for` list. Otherwise it falls back to the first project, so a cookie naming a removed project, a project the login no longer sees, or garbage gives no 404 and does not reveal whether the project exists. An explicit `?project=` always beats the cookie, and an unknown or hidden name still returns the 404 and sets no cookie. Only `index` sets the cookie. `/fragments/*`, `POST /jobs`, job pages and settings pages do not. The selection is a cookie and not a `user_settings` column, see User settings, because the requester chose browser-side storage, it needs no schema change, and each browser keeps its own choice. A new browser starts on the first project. The cookie and `?project=` hold the identifier, not the display name. The picker's row link carries the identifier in `/?project=` and shows the shown name, see Project display name and Project picker. | | Project picker | The board's top bar picks the project with a `
`, not a native `