From 9794241091226e992d848e260063e14a69646463 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 03:20:38 +0900 Subject: [PATCH 01/72] Fix the Software Factory interfaces in a new hide-factory crate The crate's public values (Factory, Task, card, states, questions, discoveries, config with the D-30 defaults), the SQLite store schema, the dependency graph helpers, the worker/operator role table, the judgment feature ids with their inputs, prompts and schemas, the hide factory command and answer contract, the adapter traits the engine is generic over, and FactorySummary, the value stage 2 draws. --- Cargo.lock | 11 + Cargo.toml | 4 + hide-factory/Cargo.toml | 17 + hide-factory/src/adapters.rs | 337 ++++++++++++++ hide-factory/src/command.rs | 537 ++++++++++++++++++++++ hide-factory/src/dag.rs | 228 ++++++++++ hide-factory/src/judgment.rs | 516 +++++++++++++++++++++ hide-factory/src/lib.rs | 24 + hide-factory/src/model.rs | 854 +++++++++++++++++++++++++++++++++++ hide-factory/src/role.rs | 116 +++++ hide-factory/src/store.rs | 466 +++++++++++++++++++ hide-factory/src/summary.rs | 370 +++++++++++++++ 12 files changed, 3480 insertions(+) create mode 100644 hide-factory/Cargo.toml create mode 100644 hide-factory/src/adapters.rs create mode 100644 hide-factory/src/command.rs create mode 100644 hide-factory/src/dag.rs create mode 100644 hide-factory/src/judgment.rs create mode 100644 hide-factory/src/lib.rs create mode 100644 hide-factory/src/model.rs create mode 100644 hide-factory/src/role.rs create mode 100644 hide-factory/src/store.rs create mode 100644 hide-factory/src/summary.rs diff --git a/Cargo.lock b/Cargo.lock index 4a4dfe36ec..0522672578 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1225,6 +1225,17 @@ dependencies = [ "tempfile", ] +[[package]] +name = "hide-factory" +version = "0.1.0" +dependencies = [ + "rusqlite", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", +] + [[package]] name = "hide-herdr-client" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index aa5bfd9bc1..70bba475d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "hide-kit", "hide-agent-hooks", "hide-ai", + "hide-factory", "hide-memory", "hide-platform", "hide-project", @@ -39,6 +40,9 @@ debug = "line-tables-only" [profile.dev.package.hide-ai] debug = "line-tables-only" +[profile.dev.package.hide-factory] +debug = "line-tables-only" + [profile.dev.package.hide-herdr-client] debug = "line-tables-only" diff --git a/hide-factory/Cargo.toml b/hide-factory/Cargo.toml new file mode 100644 index 0000000000..f40430c669 --- /dev/null +++ b/hide-factory/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "hide-factory" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +rusqlite = { version = "=0.32.1", features = ["bundled"] } +serde = { version = "=1.0.229", features = ["derive"] } +serde_json = "=1.0.151" +sha2 = "=0.10.9" + +[dev-dependencies] +tempfile = "=3.27.0" + +[lints.rust] +unsafe_op_in_unsafe_fn = "deny" diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs new file mode 100644 index 0000000000..59047317e7 --- /dev/null +++ b/hide-factory/src/adapters.rs @@ -0,0 +1,337 @@ +//! What the engine asks of the world. The engine knows these traits only; +//! the daemon supplies the real ones (local git, `gh`, Herdr workers, the +//! judgment provider) and the tests supply recording fakes. +//! +//! Every call runs on the engine's own thread, never under the core's +//! runtime lock. A call that can take minutes (a verify command, a judgment) +//! is started and polled instead of waited for. + +use serde::{Deserialize, Serialize}; + +use crate::judgment::{Judgment, JudgmentAnswer}; +use crate::model::{Factory, IssueRef, MergeMethod, PullRequest, Runtime, Task, UnixMs}; + +pub trait Clock { + fn now(&self) -> UnixMs; +} + +/// A structured failure an adapter reports. `signal` is set only for the +/// structured environment signals of D-31 (ENOSPC, exit 137, GitHub +/// 401/403/429/5xx, network, Herdr socket, usage limit); everything else is +/// the Task's (B58). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Failure { + pub stage: String, + pub signal: Option, + /// A diagnostic detail for the log; never a token or card text. + pub detail: String, + /// GitHub scope missing for a 403 (B59). + pub missing_scope: Option, + /// Usage limit reset time (B58). + pub reset_at: Option, +} + +impl Failure { + pub fn task(stage: &str, detail: impl Into) -> Self { + Self { + stage: stage.to_owned(), + signal: None, + detail: detail.into(), + missing_scope: None, + reset_at: None, + } + } + + pub fn environment(stage: &str, signal: EnvSignal, detail: impl Into) -> Self { + Self { + stage: stage.to_owned(), + signal: Some(signal), + detail: detail.into(), + missing_scope: None, + reset_at: None, + } + } +} + +/// The structured environment signals (D-31 rule 2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvSignal { + DiskFull, + OutOfMemory, + GithubAuth, + GithubForbidden, + GithubRateLimit, + GithubServer, + Network, + HerdrSocket, + UsageLimit, +} + +impl EnvSignal { + pub fn as_str(self) -> &'static str { + match self { + Self::DiskFull => "disk_full", + Self::OutOfMemory => "out_of_memory", + Self::GithubAuth => "github_auth", + Self::GithubForbidden => "github_forbidden", + Self::GithubRateLimit => "github_rate_limit", + Self::GithubServer => "github_server", + Self::Network => "network", + Self::HerdrSocket => "herdr_socket", + Self::UsageLimit => "usage_limit", + } + } +} + +/// What `init` detected for a project (B1). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProjectProbe { + pub github: bool, + pub repo: Option, + /// Required checks of the default branch's protection. + pub required_checks: Vec, + /// Verify command candidates read from repository files. + pub verify_candidates: Vec, + pub merge_methods: Vec, + pub default_branch: String, +} + +/// What changed outside the Factory since the last read (D-27). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum OutsideEvent { + /// An open pull request not made by the Factory closes a Task's issue. + ClosingPr { + issue: IssueRef, + pr: u64, + url: String, + merged: bool, + }, + /// The issue was closed with no pull request. + IssueClosed { + issue: IssueRef, + }, + IssueReopened { + issue: IssueRef, + }, + LabelRemoved { + issue: IssueRef, + }, + /// A person put the `factory` label on an issue the Factory does not + /// hold yet (B15). + Labeled { + issue: IssueRef, + title: String, + body: String, + }, + BodyEdited { + issue: IssueRef, + body_hash: String, + }, + /// A push to main the Factory did not make (B47). + OutsidePush { + sha: String, + }, +} + +/// Issues, labels and outside work (GitHub or local). +pub trait TaskSource { + fn probe(&mut self, project: &str) -> Result; + /// Writes needed when the Factory is created (the `factory` label). + fn planned_writes(&self, probe: &ProjectProbe) -> Vec; + fn prepare(&mut self, factory: &Factory) -> Result<(), Failure>; + /// Creates the Task's issue with the card summary and the label; converges + /// on an existing issue carrying the same Task marker (B73). + fn create_issue( + &mut self, + factory: &Factory, + task: &Task, + body: &str, + ) -> Result; + fn label_issue(&mut self, factory: &Factory, issue: &IssueRef) -> Result<(), Failure>; + fn read_issue(&mut self, factory: &Factory, issue: &IssueRef) -> Result; + fn observe(&mut self, factory: &Factory, tasks: &[&Task]) + -> Result, Failure>; +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct IssueText { + pub title: String, + pub body: String, + pub open: bool, +} + +/// A verification run the engine polls. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct VerifyRun { + pub id: String, + pub log: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum VerifyPoll { + Pending, + Passed, + Failed { check: String, link: String }, + Environment { signal: EnvSignal, check: String }, +} + +/// CI required checks or the verify bundle (D-53). +pub trait Verifier { + /// Starts the Task-stage verification (after done). + fn start(&mut self, factory: &Factory, task: &Task) -> Result; + /// Starts the bundle on the latest main merged into the Task (B38). + fn start_premerge(&mut self, factory: &Factory, task: &Task) -> Result; + fn poll(&mut self, factory: &Factory, run: &VerifyRun) -> VerifyPoll; + fn cancel(&mut self, run: &VerifyRun); +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum PreMerge { + Clean, + Conflict { + files: Vec, + }, + QuickCheckFailed { + check: String, + }, + /// The Task touches a configured risk path (B41). + RiskPath { + paths: Vec, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum MainCheck { + Pending, + Green, + Red { + link: String, + }, + /// No main verification configured. + None, +} + +/// Branches, pull requests, merges and reverts. +pub trait MergeTarget { + fn main_head(&mut self, factory: &Factory) -> Result; + /// Pushes the branch and opens the pull request, or finds the one a + /// harness opened (B36). + fn open_pr( + &mut self, + factory: &Factory, + task: &Task, + body: &str, + ) -> Result, Failure>; + fn close_pr(&mut self, factory: &Factory, pr: &PullRequest) -> Result<(), Failure>; + fn reopen_pr(&mut self, factory: &Factory, pr: &PullRequest) -> Result<(), Failure>; + fn diff_lines(&mut self, factory: &Factory, task: &Task) -> Result; + fn changed_paths(&mut self, factory: &Factory, task: &Task) -> Result, Failure>; + /// merge-tree against the current main and the quick check (B38). + fn premerge(&mut self, factory: &Factory, task: &Task) -> Result; + /// Whether the local main checkout has uncommitted changes (B42). + fn main_dirty(&mut self, factory: &Factory) -> Result; + /// Merges with the head SHA pinned; converges on an already-merged PR. + fn merge( + &mut self, + factory: &Factory, + task: &Task, + method: MergeMethod, + ) -> Result; + /// Main verification of a commit (B43, B44). + fn main_check(&mut self, factory: &Factory, sha: &str) -> Result; + /// Re-runs a skipped or cancelled main run (B45). + fn rerun_main(&mut self, factory: &Factory, sha: &str) -> Result<(), Failure>; + /// Reverts a merge (revert PR on GitHub, revert commit locally). + fn revert(&mut self, factory: &Factory, task: &Task, sha: &str) -> Result; + fn revert_check(&mut self, factory: &Factory, revert: &RevertRef) + -> Result; + fn merge_revert(&mut self, factory: &Factory, revert: &RevertRef) -> Result; +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RevertRef { + pub task: String, + pub sha: String, + pub pr: Option, + pub commit: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkerSpawn { + pub factory: String, + pub task: String, + pub name: String, + pub runtime: Runtime, + pub project: String, + pub branch: String, + pub prompt: String, + /// Reuse the worktree and session (retry, wake, relanding). + pub resume: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkerStatus { + Working, + /// At rest (idle or done) since the given time. + Resting { + since: UnixMs, + }, + Blocked, + Gone, +} + +/// Starts, messages, sleeps and wakes workers (D-14). +pub trait WorkerRuntime { + fn spawn(&mut self, request: &WorkerSpawn) -> Result; + /// Sends a reply or wake message through the mailbox. + fn message( + &mut self, + worker: &crate::model::WorkerRef, + intent: &str, + reply_to: Option<&str>, + body: &str, + ) -> Result<(), Failure>; + fn sleep(&mut self, worker: &crate::model::WorkerRef) -> Result<(), Failure>; + fn wake(&mut self, worker: &crate::model::WorkerRef, body: &str) -> Result<(), Failure>; + fn status(&mut self, worker: &crate::model::WorkerRef) -> WorkerStatus; + fn stop(&mut self, worker: &crate::model::WorkerRef) -> Result<(), Failure>; + /// Removes the Task's worktree and local branch (B43, B62, B71). + fn remove_worktree(&mut self, worker: &crate::model::WorkerRef) -> Result<(), Failure>; + fn usage_limited(&mut self, runtime: Runtime) -> Option; +} + +/// Submits judgments and hands back finished answers (D-13, D-44). +pub trait Judge { + /// Queues a judgment; refused when the Factory's queue is full. + fn submit(&mut self, judgment: Judgment) -> Result<(), Failure>; + /// Answers finished since the last call. + fn finished(&mut self) -> Vec; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MemoryPressure { + Normal, + Warn, + Critical, +} + +pub trait Environment { + fn disk_free(&mut self, project: &str) -> Option; + fn memory_pressure(&mut self) -> MemoryPressure; +} + +/// Where a person is told (D-30): an inbox item exists in the store; this +/// only reaches the optional macOS notification and a producer pane. +pub trait Notifier { + fn macos(&mut self, title: &str, body: &str); + /// Sends a pending review's result to the producer pane; false when the + /// pane is gone (B11). + fn producer(&mut self, pane: &str, body: &str) -> bool; +} diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs new file mode 100644 index 0000000000..ecb1d22bd9 --- /dev/null +++ b/hide-factory/src/command.rs @@ -0,0 +1,537 @@ +//! The `hide factory` command contract: what each command carries over the +//! pane-capability socket, which permission it needs, and how its answer is +//! printed for a person (`--json` prints the answer as it is). + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::model::{CheckPoint, DiscoveryClass, MergeMode, Runtime}; +use crate::role::Permission; + +/// A new or updated card as `hide factory add` sends it. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CardInput { + pub title: Option, + pub goal: Option, + pub criteria: Vec, + pub out_of_scope: Vec, + pub open_decisions: Vec, + pub depends_on: Vec, + pub external: Vec, + pub review_directly: bool, + pub priority: Option, + pub merge_mode: Option, + pub runtime: Option, + /// A PRD the daemon copies into the Factory's private folder (D-10). + pub prd: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "verb", rename_all = "snake_case", deny_unknown_fields)] +pub enum Command { + /// Without `confirm`, shows what would be created and writes nothing (B1). + Init { + project: String, + verification: Option, + merge_mode: Option, + confirm: bool, + }, + /// New Task, or the same Task again by `task` or `issue` (B9, B14). + Add { + project: Option, + task: Option, + issue: Option, + card: CardInput, + /// The adding pane, where a pending review's result goes (B11). + producer_pane: Option, + }, + Status { + project: Option, + }, + Show { + task: String, + }, + Inbox, + Answer { + task: String, + question: Option, + /// `suggestion`, `default`, a listed choice, or free text. + choice: Option, + text: Option, + }, + Ask { + text: String, + suggestion: String, + default_action: String, + deadline_hours: Option, + letter: Option, + }, + Block { + text: String, + suggestion: String, + deadline_hours: Option, + letter: Option, + }, + Propose { + class: DiscoveryClass, + text: String, + /// A prerequisite or unrelated Task's card. + card: Option, + letter: Option, + }, + Done { + summary: Option, + breaking: bool, + letter: Option, + }, + Decide { + text: String, + }, + Config { + project: Option, + set: Vec<(String, String)>, + }, + Priority { + task: String, + priority: i32, + }, + Dep { + task: String, + on: String, + remove: bool, + }, + Pause { + task: String, + }, + Resume { + task: String, + }, + Retry { + task: String, + }, + Merge { + task: String, + }, + RequestChanges { + task: String, + comment: String, + }, + Cancel { + task: String, + }, + Revive { + task: String, + }, + Close { + project: Option, + }, + /// A natural-language check (B67). + Check { + project: Option, + at: CheckPoint, + instruction: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum VerificationChoice { + Ci { checks: Vec }, + Commands { commands: Vec }, + None, +} + +impl Command { + pub fn permission(&self) -> Permission { + match self { + Self::Status { .. } | Self::Show { .. } | Self::Inbox => Permission::Read, + Self::Ask { .. } + | Self::Block { .. } + | Self::Propose { .. } + | Self::Done { .. } + | Self::Decide { .. } => Permission::Report, + Self::Dep { remove: false, .. } => Permission::AddDependency, + Self::Dep { remove: true, .. } | Self::Priority { .. } => Permission::Loosen, + Self::Init { .. } | Self::Add { .. } | Self::Check { .. } => Permission::Intake, + Self::Answer { .. } => Permission::Answer, + Self::Merge { .. } | Self::RequestChanges { .. } => Permission::Merge, + Self::Pause { .. } + | Self::Resume { .. } + | Self::Retry { .. } + | Self::Cancel { .. } + | Self::Revive { .. } + | Self::Close { .. } => Permission::Control, + Self::Config { set, .. } if set.is_empty() => Permission::Read, + Self::Config { .. } => Permission::Configure, + } + } + + pub fn verb(&self) -> &'static str { + match self { + Self::Init { .. } => "init", + Self::Add { .. } => "add", + Self::Status { .. } => "status", + Self::Show { .. } => "show", + Self::Inbox => "inbox", + Self::Answer { .. } => "answer", + Self::Ask { .. } => "ask", + Self::Block { .. } => "block", + Self::Propose { .. } => "propose", + Self::Done { .. } => "done", + Self::Decide { .. } => "decide", + Self::Config { .. } => "config", + Self::Priority { .. } => "priority", + Self::Dep { .. } => "dep", + Self::Pause { .. } => "pause", + Self::Resume { .. } => "resume", + Self::Retry { .. } => "retry", + Self::Merge { .. } => "merge", + Self::RequestChanges { .. } => "request-changes", + Self::Cancel { .. } => "cancel", + Self::Revive { .. } => "revive", + Self::Close { .. } => "close", + Self::Check { .. } => "check", + } + } +} + +/// A refusal: a stable code, the facts the caller needs, and the next step. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Refusal { + pub reason: String, + pub next_action: String, + #[serde(default, skip_serializing_if = "Value::is_null")] + pub detail: Value, +} + +impl Refusal { + pub fn new(reason: &str, next_action: impl Into) -> Self { + Self { + reason: reason.to_owned(), + next_action: next_action.into(), + detail: Value::Null, + } + } + + pub fn with(mut self, detail: Value) -> Self { + self.detail = detail; + self + } + + pub fn to_json(&self) -> Value { + let mut value = serde_json::json!({ + "ok": false, + "reason": self.reason, + "next_action": self.next_action, + }); + if !self.detail.is_null() { + value["detail"] = self.detail.clone(); + } + value + } +} + +pub const USAGE: &str = "hide factory init [--ci [...]] [--verify ]... [--no-verification] [--merge auto|manual] [--confirm] +hide factory add [--task |] --title --goal --criterion ... [--out-of-scope ]... [--open ]... [--after ]... [--external ]... [--prd ] [--review-directly] [--priority ] [--merge auto|manual] [--runtime claude|codex] [--project ] +hide factory status [--project ] +hide factory show +hide factory inbox +hide factory answer [--question ] [--choose suggestion|default|] [--text ] +hide factory ask --question --suggestion --default [--deadline-hours ] +hide factory block --question --suggestion [--deadline-hours ] +hide factory propose --class in-scope|decision|scope-change|prerequisite|unrelated --text [--title --goal --criterion ...] +hide factory done [--summary ] [--breaking] +hide factory config [--project ] [--set =]... +hide factory priority +hide factory dep add|remove --on +hide factory pause|resume|retry|merge|cancel|revive +hide factory request-changes --comment +hide factory check --at intake|after-done|periodic --instruction [--project ] +hide factory close [--project ] +Add --json to print the answer as JSON."; + +/// Prints an answer for a person. Every answer carries `ok`; a refusal +/// prints its reason and next step. +pub fn render_human(verb: &str, answer: &Value) -> String { + if answer["ok"] != true { + let mut text = format!( + "refused: {}", + answer["reason"].as_str().unwrap_or("unavailable") + ); + if let Some(detail) = answer.get("detail") { + if let Some(state) = detail["state"].as_str() { + text.push_str(&format!("\ncurrent state: {state}")); + } + if let Some(actions) = detail["allowed"].as_array() { + let names: Vec<_> = actions.iter().filter_map(Value::as_str).collect(); + text.push_str(&format!("\nallowed: {}", names.join(", "))); + } + if let Some(fields) = detail["fields"].as_array() { + for field in fields { + text.push_str(&format!( + "\n- {}: {}", + field["field"].as_str().unwrap_or("?"), + field["problem"].as_str().unwrap_or("?") + )); + } + } + } + if let Some(next) = answer["next_action"].as_str() { + text.push_str(&format!("\nnext: {next}")); + } + return text; + } + match verb { + "status" => render_status(answer), + "show" => render_show(&answer["task"]), + "inbox" => render_inbox(answer), + "init" => render_init(answer), + "add" => { + let mut text = format!( + "{} {}: {}", + answer["task"]["display_id"].as_str().unwrap_or("?"), + answer["result"].as_str().unwrap_or("?"), + answer["task"]["title"].as_str().unwrap_or("") + ); + if let Some(questions) = answer["questions"].as_array() { + for question in questions { + text.push_str(&format!( + "\n? {} (suggestion: {})", + question["text"].as_str().unwrap_or(""), + question["suggestion"].as_str().unwrap_or("") + )); + } + } + text + } + "config" => serde_json::to_string_pretty(&answer["config"]).unwrap_or_default(), + _ => { + let mut text = answer["message"].as_str().unwrap_or("ok").to_owned(); + if let Some(task) = answer.get("task") + && let (Some(id), Some(state)) = + (task["display_id"].as_str(), task["state"].as_str()) + { + text.push_str(&format!("\n{id}: {state}")); + } + text + } + } +} + +fn render_init(answer: &Value) -> String { + let mut text = String::new(); + if answer["created"] == true { + text.push_str(&format!( + "Factory {} created for {}\n", + answer["factory"]["id"].as_str().unwrap_or("?"), + answer["factory"]["project"].as_str().unwrap_or("?") + )); + text.push_str("Add a Task: hide factory add --title --goal --criterion "); + return text; + } + if answer["existing"] == true { + return format!( + "This project already has Factory {}", + answer["factory"]["id"].as_str().unwrap_or("?") + ); + } + text.push_str(&format!( + "project: {}\nsource: {}\n", + answer["project"].as_str().unwrap_or("?"), + answer["source"].as_str().unwrap_or("?") + )); + text.push_str("verification candidates:\n"); + for candidate in answer["candidates"].as_array().into_iter().flatten() { + text.push_str(&format!( + " - {} {}\n", + candidate["kind"].as_str().unwrap_or("?"), + candidate["value"].as_str().unwrap_or("") + )); + } + text.push_str(&format!( + "merge mode: {}\n", + answer["merge_mode"].as_str().unwrap_or("?") + )); + if let Some(note) = answer["auto_unavailable"].as_str() { + text.push_str(&format!("auto: unavailable ({note})\n")); + } + for write in answer["writes"].as_array().into_iter().flatten() { + text.push_str(&format!("will write: {}\n", write.as_str().unwrap_or(""))); + } + text.push_str("Nothing was written. Choose a verification and add --confirm."); + text +} + +fn render_status(answer: &Value) -> String { + let mut text = String::new(); + for factory in answer["factories"].as_array().into_iter().flatten() { + let flow = &factory["flow"]; + text.push_str(&format!( + "{} {} 정리 중 {} · 대기 {} · 실행 중 {} · 완료 오늘 {} 내 차례 {}\n", + factory["id"].as_str().unwrap_or("?"), + factory["project_name"].as_str().unwrap_or("?"), + flow["drafting"], + flow["waiting"], + flow["running"], + flow["done_today"], + factory["my_turn"], + )); + if let Some(read) = factory["outside_read_at"].as_u64() { + text.push_str(&format!(" outside read at {read}")); + if factory["stale"] == true { + text.push_str(" (stale)"); + } + text.push('\n'); + } + if factory["main_broken"] == true { + text.push_str(" main broken: auto merge stopped\n"); + } + for column in factory["columns"].as_array().into_iter().flatten() { + text.push_str(&format!( + " [{}]\n", + column["label"].as_str().unwrap_or("?") + )); + for card in column["cards"].as_array().into_iter().flatten() { + let mark = if card["needs_person"] == true { + "!" + } else { + " " + }; + text.push_str(&format!( + " {mark} {:<8} {:<10} {}{}\n", + card["display_id"].as_str().unwrap_or("?"), + card["state_label"].as_str().unwrap_or("?"), + card["title"].as_str().unwrap_or(""), + card["waiting_for"] + .as_str() + .map(|wait| format!(" (waits: {wait})")) + .unwrap_or_default() + )); + } + } + } + if text.is_empty() { + text.push_str("No Factory. Create one: hide factory init "); + } + text +} + +fn render_show(task: &Value) -> String { + let mut text = format!( + "{} {} [{}]\n", + task["display_id"].as_str().unwrap_or("?"), + task["title"].as_str().unwrap_or(""), + task["state_label"].as_str().unwrap_or("?") + ); + text.push_str(&format!("goal: {}\n", task["goal"].as_str().unwrap_or(""))); + for criterion in task["criteria"].as_array().into_iter().flatten() { + text.push_str(&format!(" ✓ {}\n", criterion.as_str().unwrap_or(""))); + } + for item in task["out_of_scope"].as_array().into_iter().flatten() { + text.push_str(&format!( + " out of scope: {}\n", + item.as_str().unwrap_or("") + )); + } + let chain = |key: &str| { + task[key] + .as_array() + .map(|items| { + items + .iter() + .filter_map(Value::as_str) + .collect::>() + .join(", ") + }) + .unwrap_or_default() + }; + text.push_str(&format!( + "chain: [{}] -> {} -> [{}]\n", + chain("before"), + task["display_id"].as_str().unwrap_or("?"), + chain("after") + )); + if let Some(external) = task["external"] + .as_array() + .filter(|items| !items.is_empty()) + { + let names: Vec<_> = external.iter().filter_map(Value::as_str).collect(); + text.push_str(&format!("외부 대기: {}\n", names.join(", "))); + } + text.push_str(&format!( + "verification {}/{}", + task["failures"], task["failure_limit"] + )); + if let Some(pr) = task["pr"]["url"].as_str() { + text.push_str(&format!(" PR {pr}")); + } + if let Some(pane) = task["worker"]["pane"].as_str() { + text.push_str(&format!(" worker {pane}")); + } + text.push('\n'); + for attachment in task["attachments"].as_array().into_iter().flatten() { + text.push_str(&format!( + "attachment v{} {} sha256:{}\n", + attachment["version"], + attachment["path"].as_str().unwrap_or(""), + attachment["sha256"].as_str().unwrap_or("") + )); + } + for decision in task["decisions"].as_array().into_iter().flatten() { + text.push_str(&format!( + "decision ({}): {}\n", + decision["by"].as_str().unwrap_or("?"), + decision["text"].as_str().unwrap_or("") + )); + } + for question in task["questions"].as_array().into_iter().flatten() { + let state = if question["answer"].is_null() { + "open".to_owned() + } else { + format!( + "answered by {}", + question["answer"]["relayed_by"].as_str().unwrap_or("?") + ) + }; + text.push_str(&format!( + "question {} [{state}]: {}\n", + question["id"].as_str().unwrap_or("?"), + question["text"].as_str().unwrap_or("") + )); + } + text +} + +fn render_inbox(answer: &Value) -> String { + let mut text = format!("내 차례 {}\n", answer["count"]); + for item in answer["items"].as_array().into_iter().flatten() { + text.push_str(&format!( + "- [{}] {} {} ({}) {}\n", + item["group"].as_str().unwrap_or("?"), + item["display_id"].as_str().unwrap_or("?"), + item["title"].as_str().unwrap_or(""), + item["project"].as_str().unwrap_or(""), + item["text"].as_str().unwrap_or("") + )); + if let Some(suggestion) = item["suggestion"] + .as_str() + .filter(|value| !value.is_empty()) + { + text.push_str(&format!(" suggestion: {suggestion}\n")); + } + if let Some(default) = item["default_action"].as_str() { + text.push_str(&format!(" default: {default}\n")); + } + if let Some(remaining) = item["remaining"].as_str() { + text.push_str(&format!(" {remaining}\n")); + } + if let Some(question) = item["question"].as_str() { + text.push_str(&format!( + " answer: hide factory answer {} --question {question} --choose suggestion\n", + item["display_id"].as_str().unwrap_or("?") + )); + } + } + text +} diff --git a/hide-factory/src/dag.rs b/hide-factory/src/dag.rs new file mode 100644 index 0000000000..83d57dd3f7 --- /dev/null +++ b/hide-factory/src/dag.rs @@ -0,0 +1,228 @@ +//! The dependency graph (D-29): cycles, start eligibility, slot order and the +//! reduced edges the graph view draws (D-36). + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::model::{Task, TaskState}; + +/// Edges as `task -> predecessors` within one Factory. +pub type Edges = BTreeMap>; + +pub fn edges<'a>(tasks: impl Iterator) -> Edges { + let mut edges = Edges::new(); + for task in tasks { + edges + .entry(task.id.clone()) + .or_default() + .extend(task.card.depends_on.iter().cloned()); + } + edges +} + +/// A cycle the edge `from -> on` would close, as the path from `on` back to +/// `from`, or `None`. +pub fn cycle_with(edges: &Edges, from: &str, on: &str) -> Option> { + if from == on { + return Some(vec![from.to_owned()]); + } + // Is `from` reachable from `on` following predecessor edges? + let mut stack = vec![(on.to_owned(), vec![on.to_owned()])]; + let mut seen = BTreeSet::new(); + while let Some((node, path)) = stack.pop() { + if node == from { + return Some(path); + } + if !seen.insert(node.clone()) { + continue; + } + for next in edges.get(&node).into_iter().flatten() { + let mut path = path.clone(); + path.push(next.clone()); + stack.push((next.clone(), path)); + } + } + None +} + +/// Whether the whole graph is acyclic; returns one cycle when not. +pub fn find_cycle(edges: &Edges) -> Option> { + for (task, predecessors) in edges { + for predecessor in predecessors { + let mut without = edges.clone(); + without + .get_mut(task) + .map(|set| set.remove(predecessor)) + .unwrap_or(false); + if let Some(path) = cycle_with(&without, task, predecessor) { + return Some(path); + } + } + } + None +} + +/// The predecessors a Task still waits for: those not merged yet (B20). +/// Predecessors outside the Factory are handled before this (missing ids are +/// refused at intake); external waits never count (B64). +pub fn waiting_for(task: &Task, tasks: &BTreeMap) -> Vec { + task.card + .depends_on + .iter() + .filter(|id| { + tasks + .get(*id) + .is_none_or(|predecessor| !predecessor.state.merged()) + }) + .cloned() + .collect() +} + +/// Waiting Tasks that may start now, in slot order: priority high first, +/// then oldest first (D-29, B21). +pub fn startable(tasks: &BTreeMap) -> Vec<&Task> { + let mut ready: Vec<&Task> = tasks + .values() + .filter(|task| task.state == TaskState::Waiting && waiting_for(task, tasks).is_empty()) + .collect(); + ready.sort_by(|a, b| slot_order(a, b)); + ready +} + +pub fn slot_order(a: &Task, b: &Task) -> std::cmp::Ordering { + b.human + .priority + .cmp(&a.human.priority) + .then(a.created_at.cmp(&b.created_at)) + .then(a.seq.cmp(&b.seq)) +} + +/// Edges with every edge implied by a longer path removed; the data keeps +/// all of them (D-36). +pub fn transitive_reduction(edges: &Edges) -> Vec<(String, String)> { + let mut reduced = Vec::new(); + for (task, predecessors) in edges { + for predecessor in predecessors { + let implied = predecessors + .iter() + .any(|other| other != predecessor && reaches(edges, other, predecessor)); + if !implied { + reduced.push((predecessor.clone(), task.clone())); + } + } + } + reduced +} + +fn reaches(edges: &Edges, from: &str, to: &str) -> bool { + let mut stack = vec![from.to_owned()]; + let mut seen = BTreeSet::new(); + while let Some(node) = stack.pop() { + if node == to { + return true; + } + if !seen.insert(node.clone()) { + continue; + } + stack.extend(edges.get(&node).into_iter().flatten().cloned()); + } + false +} + +/// Tasks downstream of `task` (those that wait on it, directly or not). +pub fn dependents(edges: &Edges, task: &str) -> BTreeSet { + let mut found = BTreeSet::new(); + let mut frontier = vec![task.to_owned()]; + while let Some(node) = frontier.pop() { + for (candidate, predecessors) in edges { + if predecessors.contains(&node) && found.insert(candidate.clone()) { + frontier.push(candidate.clone()); + } + } + } + found +} + +/// A topological order of the given Tasks, predecessors first; `None` when +/// the graph has a cycle. +pub fn topological(edges: &Edges) -> Option> { + let mut order = Vec::new(); + let mut placed = BTreeSet::new(); + let nodes: BTreeSet = edges + .keys() + .cloned() + .chain(edges.values().flatten().cloned()) + .collect(); + while placed.len() < nodes.len() { + let next = nodes.iter().find(|node| { + !placed.contains(*node) + && edges + .get(*node) + .into_iter() + .flatten() + .all(|predecessor| placed.contains(predecessor)) + })?; + placed.insert(next.clone()); + order.push(next.clone()); + } + Some(order) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn graph(pairs: &[(&str, &str)]) -> Edges { + let mut edges = Edges::new(); + for (task, on) in pairs { + edges + .entry((*task).to_owned()) + .or_default() + .insert((*on).to_owned()); + edges.entry((*on).to_owned()).or_default(); + } + edges + } + + #[test] + fn an_edge_that_closes_a_loop_is_found_with_its_path() { + let edges = graph(&[("b", "a"), ("c", "b")]); + assert_eq!( + cycle_with(&edges, "a", "c"), + Some(vec!["c".into(), "b".into(), "a".into()]) + ); + assert_eq!(cycle_with(&edges, "c", "a"), None); + assert_eq!(cycle_with(&edges, "a", "a"), Some(vec!["a".into()])); + assert!(find_cycle(&edges).is_none()); + let looped = graph(&[("b", "a"), ("a", "b")]); + assert!(find_cycle(&looped).is_some()); + } + + #[test] + fn the_reduction_drops_only_edges_a_longer_path_implies() { + // a -> b -> c and a -> c: the direct a -> c is implied. + let edges = graph(&[("b", "a"), ("c", "b"), ("c", "a"), ("d", "a")]); + let mut reduced = transitive_reduction(&edges); + reduced.sort(); + assert_eq!( + reduced, + vec![ + ("a".to_owned(), "b".to_owned()), + ("a".to_owned(), "d".to_owned()), + ("b".to_owned(), "c".to_owned()) + ] + ); + } + + #[test] + fn dependents_and_order_follow_the_chain_only() { + let edges = graph(&[("b", "a"), ("c", "b"), ("e", "d")]); + assert_eq!( + dependents(&edges, "a"), + ["b", "c"].into_iter().map(str::to_owned).collect() + ); + let order = topological(&edges).unwrap(); + let position = |id: &str| order.iter().position(|node| node == id).unwrap(); + assert!(position("a") < position("b") && position("b") < position("c")); + assert!(position("d") < position("e")); + } +} diff --git a/hide-factory/src/judgment.rs b/hide-factory/src/judgment.rs new file mode 100644 index 0000000000..545e094528 --- /dev/null +++ b/hide-factory/src/judgment.rs @@ -0,0 +1,516 @@ +//! The Factory's judgments (D-13): one tool-less call each, whose input the +//! code bundles and whose answer can only pass, add questions and flags, or +//! choose from a closed list. The provider work belongs to hide-ai; the +//! feature ids, prompts, schemas and parsing belong here. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::model::{Card, RecoveryAction, SplitPiece}; + +pub const INTAKE_REVIEW: &str = "factory_intake_review"; +pub const DRIFT: &str = "factory_drift"; +pub const WATCH: &str = "factory_watch"; +pub const ENV_DIAGNOSIS: &str = "factory_env_diagnosis"; +pub const CHECK: &str = "factory_check"; + +pub const SCHEMA_VERSION: &str = "factory.v1"; + +/// Size caps of a bundled input; a larger part is cut with a marker. +pub const INPUT_LIMIT: usize = 48 * 1024; +pub const ATTACHMENT_LIMIT: usize = 24 * 1024; +pub const DIFF_LIMIT: usize = 24 * 1024; +/// Pending judgments per Factory (D-44). +pub const QUEUE_LIMIT: usize = 16; + +/// Order the queue serves: intake review first (D-44). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Priority { + Intake = 0, + Factory = 1, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "feature", rename_all = "snake_case")] +pub enum JudgmentInput { + IntakeReview { + card: Card, + attachment: Option, + other_tasks: Vec, + repo_files: Vec, + guide: Option, + }, + Drift { + card: Card, + diff: String, + decisions: Vec, + }, + Watch { + board: Value, + }, + EnvDiagnosis { + facts: Value, + actions: Vec, + }, + Check { + instruction: String, + card: Card, + diff: Option, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OtherTask { + pub id: String, + pub title: String, + pub goal: String, + pub state: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Judgment { + /// Stable per subject and input; resubmitting the same is a duplicate. + pub id: String, + pub factory: String, + pub task: Option, + pub priority: Priority, + pub input: JudgmentInput, +} + +impl Judgment { + pub fn feature_id(&self) -> &'static str { + match self.input { + JudgmentInput::IntakeReview { .. } => INTAKE_REVIEW, + JudgmentInput::Drift { .. } => DRIFT, + JudgmentInput::Watch { .. } => WATCH, + JudgmentInput::EnvDiagnosis { .. } => ENV_DIAGNOSIS, + JudgmentInput::Check { .. } => CHECK, + } + } + + pub fn system(&self) -> &'static str { + match self.input { + JudgmentInput::IntakeReview { .. } => INTAKE_SYSTEM, + JudgmentInput::Drift { .. } => DRIFT_SYSTEM, + JudgmentInput::Watch { .. } => WATCH_SYSTEM, + JudgmentInput::EnvDiagnosis { .. } => ENV_SYSTEM, + JudgmentInput::Check { .. } => CHECK_SYSTEM, + } + } + + pub fn schema(&self) -> Value { + match self.input { + JudgmentInput::IntakeReview { .. } => intake_schema(), + JudgmentInput::Drift { .. } | JudgmentInput::Check { .. } => finding_schema(), + JudgmentInput::Watch { .. } => watch_schema(), + JudgmentInput::EnvDiagnosis { .. } => env_schema(), + } + } + + /// The bundled input as the provider reads it, within [`INPUT_LIMIT`]. + pub fn render_input(&self) -> String { + let value = match &self.input { + JudgmentInput::IntakeReview { + card, + attachment, + other_tasks, + repo_files, + guide, + } => json!({ + "card": card, + "attachment": attachment.as_deref().map(|text| cut(text, ATTACHMENT_LIMIT)), + "other_tasks": other_tasks, + "repo_files": repo_files.iter().take(400).collect::>(), + "guide": guide.as_deref().map(|text| cut(text, 8 * 1024)), + }), + JudgmentInput::Drift { + card, + diff, + decisions, + } => json!({"card": card, "diff": cut(diff, DIFF_LIMIT), "decisions": decisions}), + JudgmentInput::Watch { board } => json!({"board": board}), + JudgmentInput::EnvDiagnosis { facts, actions } => json!({ + "facts": facts, + "actions": actions.iter().map(|action| action.as_str()).collect::>(), + }), + JudgmentInput::Check { + instruction, + card, + diff, + } => json!({ + "instruction": instruction, + "card": card, + "diff": diff.as_deref().map(|text| cut(text, DIFF_LIMIT)), + }), + }; + cut(&value.to_string(), INPUT_LIMIT) + } +} + +/// Cuts at a UTF-8 boundary and marks the cut. +pub fn cut(text: &str, limit: usize) -> String { + if text.len() <= limit { + return text.to_owned(); + } + let mut end = limit; + while !text.is_char_boundary(end) { + end -= 1; + } + format!("{}\n[cut {} bytes]", &text[..end], text.len() - end) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct JudgmentAnswer { + pub id: String, + pub factory: String, + pub task: Option, + pub outcome: JudgmentOutcome, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum JudgmentOutcome { + Answered { + value: Value, + }, + /// No provider, a provider failure, or a full queue (B19, B68): the + /// judgment is never skipped; the engine escalates. + Failed { + reason: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProposedQuestion { + pub text: String, + pub suggestion: String, + #[serde(default)] + pub default_action: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IntakeVerdict { + pub questions: Vec, + pub dependencies: Vec, + pub split: Vec, + pub flags: Vec, +} + +impl IntakeVerdict { + pub fn result(&self) -> crate::model::ReviewResult { + if !self.split.is_empty() { + crate::model::ReviewResult::Split + } else if !self.questions.is_empty() { + crate::model::ReviewResult::NeedsAnswers + } else { + crate::model::ReviewResult::Ready + } + } +} + +pub fn parse_intake(value: &Value) -> Result { + let questions = parse_questions(&value["questions"])?; + let dependencies = string_list(&value["dependencies"])?; + let flags = string_list(&value["flags"])?; + let mut split = Vec::new(); + for piece in value["split"].as_array().into_iter().flatten() { + let title = text_field(piece, "title")?; + let goal = text_field(piece, "goal")?; + let criteria = string_list(&piece["criteria"])?; + if criteria.is_empty() { + return Err("split_piece_without_criteria".into()); + } + let after = piece["after"] + .as_array() + .map(|items| { + items + .iter() + .filter_map(Value::as_u64) + .map(|n| n as usize) + .collect() + }) + .unwrap_or_default(); + split.push(SplitPiece { + title, + goal, + criteria, + after, + }); + } + if split.len() == 1 { + return Err("split_needs_two_pieces".into()); + } + Ok(IntakeVerdict { + questions, + dependencies, + split, + flags, + }) +} + +/// Drift and user checks: pass, or add questions and flags (D-44). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Finding { + pub pass: bool, + pub questions: Vec, + pub flags: Vec, +} + +pub fn parse_finding(value: &Value) -> Result { + let pass = value["pass"].as_bool().ok_or("pass_missing")?; + let mut questions = parse_questions(&value["questions"])?; + for question in &mut questions { + if question.default_action.is_none() { + // A check may only make work slower: every question it adds + // carries a default so the worker keeps going (D-44). + question.default_action = Some(question.suggestion.clone()); + } + } + let flags = string_list(&value["flags"])?; + Ok(Finding { + pass: pass && questions.is_empty() && flags.is_empty(), + questions, + flags, + }) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Warning { + pub text: String, + /// A warning without a proposed action goes to the log only (B69). + pub action: Option, + pub task: Option, +} + +pub fn parse_watch(value: &Value) -> Result, String> { + let mut warnings = Vec::new(); + for item in value["warnings"].as_array().into_iter().flatten() { + warnings.push(Warning { + text: text_field(item, "text")?, + action: item["action"] + .as_str() + .map(str::trim) + .filter(|action| !action.is_empty()) + .map(str::to_owned), + task: item["task"].as_str().map(str::to_owned), + }); + } + Ok(warnings) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnosis { + pub cause: String, + /// Only an action from the closed list (D-54); anything else is a + /// proposal for a person. + pub action: Option, + pub proposal: Option<(String, String)>, +} + +pub fn parse_env(value: &Value) -> Result { + let cause = text_field(value, "cause")?; + let action = match value["action"].as_str() { + None | Some("") | Some("none") => None, + Some(name) => Some( + RecoveryAction::ALL + .into_iter() + .find(|action| action.as_str() == name) + .ok_or("action_not_in_list")?, + ), + }; + let proposal = match (value["command"].as_str(), value["impact"].as_str()) { + (Some(command), Some(impact)) if !command.trim().is_empty() => { + Some((command.to_owned(), impact.to_owned())) + } + _ => None, + }; + Ok(Diagnosis { + cause, + action, + proposal, + }) +} + +fn parse_questions(value: &Value) -> Result, String> { + let mut questions = Vec::new(); + for item in value.as_array().into_iter().flatten() { + let text = text_field(item, "text")?; + let suggestion = text_field(item, "suggestion")?; + let default_action = item["default_action"] + .as_str() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_owned); + questions.push(ProposedQuestion { + text, + suggestion, + default_action, + }); + } + Ok(questions) +} + +fn text_field(value: &Value, key: &str) -> Result { + value[key] + .as_str() + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(str::to_owned) + .ok_or_else(|| format!("{key}_missing")) +} + +fn string_list(value: &Value) -> Result, String> { + match value { + Value::Null => Ok(Vec::new()), + Value::Array(items) => Ok(items + .iter() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(str::to_owned) + .collect()), + _ => Err("list_expected".into()), + } +} + +const QUESTION_ITEM: &str = r#"{"type":"object","additionalProperties":false,"required":["text","suggestion","default_action"],"properties":{"text":{"type":"string"},"suggestion":{"type":"string"},"default_action":{"type":"string"}}}"#; + +fn question_item() -> Value { + serde_json::from_str(QUESTION_ITEM).unwrap_or(Value::Null) +} + +fn intake_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["questions", "dependencies", "split", "flags"], + "properties": { + "questions": {"type": "array", "items": question_item()}, + "dependencies": {"type": "array", "items": {"type": "string"}}, + "split": {"type": "array", "items": { + "type": "object", + "additionalProperties": false, + "required": ["title", "goal", "criteria", "after"], + "properties": { + "title": {"type": "string"}, + "goal": {"type": "string"}, + "criteria": {"type": "array", "items": {"type": "string"}}, + "after": {"type": "array", "items": {"type": "integer"}} + } + }}, + "flags": {"type": "array", "items": {"type": "string"}} + } + }) +} + +fn finding_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["pass", "questions", "flags"], + "properties": { + "pass": {"type": "boolean"}, + "questions": {"type": "array", "items": question_item()}, + "flags": {"type": "array", "items": {"type": "string"}} + } + }) +} + +fn watch_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["warnings"], + "properties": {"warnings": {"type": "array", "items": { + "type": "object", + "additionalProperties": false, + "required": ["text", "action", "task"], + "properties": { + "text": {"type": "string"}, + "action": {"type": "string"}, + "task": {"type": "string"} + } + }}} + }) +} + +fn env_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["cause", "action", "command", "impact"], + "properties": { + "cause": {"type": "string"}, + "action": {"type": "string"}, + "command": {"type": "string"}, + "impact": {"type": "string"} + } + }) +} + +const INTAKE_SYSTEM: &str = "You review a software Task card before it runs, with no knowledge of the conversation that wrote it. You see only the card, its attached PRD, the repository's file list and guide, and the other Tasks of the same Factory. Return JSON only. You may only add: questions a person must answer before the Task can run safely (each with a concrete suggestion and a default action), dependencies on other listed Tasks by id when this Task cannot start until that one is merged, a split when the Task is clearly too large for one pull request (two or more pieces, each with a goal and checkable criteria, `after` naming earlier pieces), and short flags. Ask about untestable completion criteria, hidden decisions, and mismatch between the card and the PRD. Never rewrite the card. Do not add a dependency only because two Tasks touch the same file. Return empty arrays when the card is ready."; + +const DRIFT_SYSTEM: &str = "You compare a finished change with the Task card it claims to complete: its goal, completion criteria and out-of-scope list, and the decisions the worker recorded. Return JSON only. pass is true when the diff does what the card asks and nothing it rules out. When it drifts, add questions for a person, each with a suggestion and a default action that keeps the change as narrow as the card; add flags for a reported breaking change or a public contract change. You cannot send work back and you cannot approve anything wider than the card."; + +const WATCH_SYSTEM: &str = "You read a Factory board summary: recent events, Task states, waits and decision records. Return JSON only: warnings a person should act on, each naming the Task id it is about when there is one and an action the person can take. A warning with no action is still allowed but goes to a log. Never propose merging, removing dependencies or widening scope on your own."; + +const ENV_SYSTEM: &str = "You diagnose an environment problem from facts the code collected (disk usage by owner, failure signals, which stage failed, how many Tasks). Return JSON only: a one-line cause, and either one action from the given list (or \"none\"), or an exact shell command with its impact for a person to approve. Never choose an action that is not in the list; login, deletion outside the Factory and installing tools are always a proposal."; + +const CHECK_SYSTEM: &str = "You run one natural-language check a person configured on a Factory Task. Return JSON only. pass is true when the instruction is satisfied by the card and change you see. Otherwise add questions (with a suggestion and a default action) or flags. You cannot change the card or the change."; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_check_question_without_a_default_takes_its_suggestion() { + let finding = parse_finding(&json!({ + "pass": true, + "questions": [{"text": "Docs updated?", "suggestion": "Leave docs", "default_action": ""}], + "flags": [] + })) + .unwrap(); + assert!(!finding.pass, "a question turns a pass into a finding"); + assert_eq!( + finding.questions[0].default_action.as_deref(), + Some("Leave docs") + ); + } + + #[test] + fn a_diagnosis_cannot_pick_an_action_outside_the_closed_list() { + assert!( + parse_env(&json!({"cause":"disk","action":"rm_rf_home","command":"","impact":""})) + .is_err() + ); + let diagnosis = parse_env( + &json!({"cause":"disk","action":"remove_finished_worktrees","command":"","impact":""}), + ) + .unwrap(); + assert_eq!( + diagnosis.action, + Some(RecoveryAction::RemoveFinishedWorktrees) + ); + } + + #[test] + fn a_split_needs_at_least_two_pieces_with_criteria() { + let one = json!({"questions":[],"dependencies":[],"flags":[],"split":[{"title":"a","goal":"g","criteria":["c"],"after":[]}]}); + assert!(parse_intake(&one).is_err()); + let two = json!({"questions":[],"dependencies":[],"flags":[],"split":[ + {"title":"a","goal":"g","criteria":["c"],"after":[]}, + {"title":"b","goal":"g","criteria":["c"],"after":[0]}]}); + let verdict = parse_intake(&two).unwrap(); + assert_eq!(verdict.result(), crate::model::ReviewResult::Split); + assert_eq!(verdict.split[1].after, vec![0]); + } + + #[test] + fn inputs_are_cut_at_a_character_boundary() { + let text = "가".repeat(10); + let cut_text = cut(&text, 7); + assert!(cut_text.starts_with("가가")); + assert!(cut_text.contains("[cut")); + } +} diff --git a/hide-factory/src/lib.rs b/hide-factory/src/lib.rs new file mode 100644 index 0000000000..803725e622 --- /dev/null +++ b/hide-factory/src/lib.rs @@ -0,0 +1,24 @@ +//! Software Factory: the engine that takes Tasks with clear requirements, +//! runs them through workers in dependency order, verifies and merges them, +//! and hands a person only what they must act on (PRD software-factory). +//! +//! This crate knows nothing of Hide's runtime or Herdr. It owns the values +//! ([`model`]), the store ([`store`]), the dependency graph ([`dag`]), the +//! roles ([`role`]), the judgment features ([`judgment`]), the command +//! contract ([`command`]), the stage 2 summary ([`summary`]) and the adapter +//! traits the engine is generic over ([`adapters`]). `docs/factory.md` is the +//! owning guide. + +pub mod adapters; +pub mod command; +pub mod dag; +pub mod judgment; +pub mod model; +pub mod role; +pub mod store; +pub mod summary; + +pub use command::{Command, Refusal}; +pub use model::{Factory, Task, TaskState}; +pub use role::Role; +pub use summary::FactorySummary; diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs new file mode 100644 index 0000000000..c491773604 --- /dev/null +++ b/hide-factory/src/model.rs @@ -0,0 +1,854 @@ +//! The Factory's values: what a Factory, a Task, its card and its records are. +//! +//! Nothing here performs I/O. The engine changes these values, the store +//! saves them, and the CLI and the stage 2 screens read them. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +/// Minutes and hours as the engine counts them: milliseconds since the epoch. +pub type UnixMs = u64; + +pub const MINUTE_MS: u64 = 60_000; +pub const HOUR_MS: u64 = 60 * MINUTE_MS; +pub const DAY_MS: u64 = 24 * HOUR_MS; + +/// One Factory per project. Its id is stable for the project's path, so a +/// closed Factory created again for the same project returns with its records +/// (B74). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Factory { + pub id: String, + /// Canonical path of the project's primary checkout. + pub project: String, + /// A short name the inbox shows next to each item. + pub project_name: String, + pub source: SourceKind, + pub config: Config, + pub closed: bool, + pub created_at: UnixMs, + /// Next `T-` number. Never lowered. + pub next_task: u32, + /// Next `L-` number for a local project without its own local issue + /// store. Never lowered. + pub next_local_issue: u32, + /// Auto merge stopped because main verification failed (B44, B47, B48). + pub main: MainHealth, + /// When outside work was last read, and how many reads failed in a row + /// (B65 stale mark after three). + pub outside_read_at: Option, + pub outside_read_failures: u32, + /// Watch judgments sent today and the day they count for (B69). + pub watch_day: u64, + pub watch_sent_today: u32, + pub watch_last_at: Option, +} + +/// Where Tasks come from and where they merge (D-04, B3). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SourceKind { + /// A project with a GitHub remote: issues, labels, pull requests. + Github, + /// A project without one: local issues `L-` and a local merge to main. + Local, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MainHealth { + pub broken: bool, + /// The last main commit whose verification passed. + pub last_green: Option, + /// Why auto merge stays stopped; empty when it runs. + pub reason: Option, + /// A recovery that could not decide or failed waits for a person (B48). + pub needs_person: bool, + /// Merges Factory made since the last green, oldest first. + pub merges_since_green: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LandedMerge { + pub task: String, + pub sha: String, + pub at: UnixMs, +} + +/// The one verification a Factory chose (D-53). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Verification { + /// Required checks of the pull request (GitHub only). Empty `checks` + /// means the branch protection's required checks. + Ci { checks: Vec }, + /// Commands run in the Task worktree; every one must exit 0. + Commands { commands: Vec }, + /// No verification: auto merge is not available (B2). + None, +} + +impl Verification { + pub fn exists(&self) -> bool { + !matches!(self, Self::None) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MergeMode { + Auto, + Manual, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MergeMethod { + Merge, + Squash, + Rebase, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Runtime { + Claude, + Codex, +} + +impl Runtime { + pub fn as_str(self) -> &'static str { + match self { + Self::Claude => "claude", + Self::Codex => "codex", + } + } + + pub fn parse(value: &str) -> Option { + match value { + "claude" => Some(Self::Claude), + "codex" => Some(Self::Codex), + _ => None, + } + } +} + +/// When a natural-language check runs (D-15). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckPoint { + Intake, + AfterDone, + Periodic, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserCheck { + pub at: CheckPoint, + pub instruction: String, +} + +/// The typed recovery actions (D-54). Nothing outside this list runs without +/// a person's approval. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RecoveryAction { + RemoveFinishedWorktrees, + RestartWorker, + SleepWakeWorker, + SwitchRuntime, + RetryReadsAndReconnect, +} + +impl RecoveryAction { + pub const ALL: [Self; 5] = [ + Self::RemoveFinishedWorktrees, + Self::RestartWorker, + Self::SleepWakeWorker, + Self::SwitchRuntime, + Self::RetryReadsAndReconnect, + ]; + + pub fn as_str(self) -> &'static str { + match self { + Self::RemoveFinishedWorktrees => "remove_finished_worktrees", + Self::RestartWorker => "restart_worker", + Self::SleepWakeWorker => "sleep_wake_worker", + Self::SwitchRuntime => "switch_runtime", + Self::RetryReadsAndReconnect => "retry_reads_and_reconnect", + } + } +} + +/// Every setting a Factory has, with the D-30 defaults (B66). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + pub verification: Verification, + pub merge_mode: MergeMode, + pub merge_method: MergeMethod, + /// Optional quick check before a merge (D-46), run on the merged tree. + pub quick_check: Option, + /// Concurrent workers on this machine across every Factory (D-30, D-45). + pub max_workers: u32, + pub question_deadline_ms: u64, + pub stall_ms: u64, + pub no_report_ms: u64, + pub watch_interval_ms: u64, + pub watch_daily_limit: u32, + pub outside_read_ms: u64, + pub cancel_keep_ms: u64, + pub done_fold_ms: u64, + pub archive_fold_ms: u64, + pub new_task_limit: u32, + pub verify_failure_limit: u32, + pub verify_timeout_ms: u64, + pub disk_floor_bytes: u64, + pub default_runtime: Runtime, + pub harness: Option, + pub autonomy: Vec, + pub autonomy_diff_limit: u32, + pub recovery: Vec, + pub risk_paths: Vec, + pub checks: Vec, + pub prd_in_issue: bool, + pub macos_notifications: bool, +} + +impl Default for Config { + fn default() -> Self { + Self { + verification: Verification::None, + merge_mode: MergeMode::Manual, + merge_method: MergeMethod::Merge, + quick_check: None, + max_workers: 5, + question_deadline_ms: 24 * HOUR_MS, + stall_ms: 30 * MINUTE_MS, + no_report_ms: 2 * MINUTE_MS, + watch_interval_ms: 30 * MINUTE_MS, + watch_daily_limit: 5, + outside_read_ms: 2 * MINUTE_MS, + cancel_keep_ms: 7 * DAY_MS, + done_fold_ms: 3 * DAY_MS, + archive_fold_ms: 90 * DAY_MS, + new_task_limit: 3, + verify_failure_limit: 3, + verify_timeout_ms: 60 * MINUTE_MS, + disk_floor_bytes: 20 * 1024 * 1024 * 1024, + default_runtime: Runtime::Claude, + harness: None, + autonomy: AutonomyScope::presets(), + autonomy_diff_limit: 200, + recovery: Vec::new(), + risk_paths: Vec::new(), + checks: Vec::new(), + prd_in_issue: false, + macos_notifications: false, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Harness { + pub name: String, + /// The natural-language "how to work" preset placed in the worker prompt. + pub instructions: String, +} + +/// A kind of Task a worker may create and start without a person (D-18). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AutonomyScope { + pub id: String, + pub description: String, + pub enabled: bool, +} + +impl AutonomyScope { + /// The presets hide offers; every one starts off (D-18, B32). + pub fn presets() -> Vec { + [ + ("flaky_test", "Fix a flaky test"), + ("dependency_patch", "Update a dependency by a patch version"), + ("lint_format", "Lint and format fixes"), + ("docs_links", "Fix documentation links and typos"), + ] + .into_iter() + .map(|(id, description)| Self { + id: id.to_owned(), + description: description.to_owned(), + enabled: false, + }) + .collect() + } +} + +/// The Task lifecycle (D-28, Q29) plus the two places the PRD names outside +/// the main line: paused (B54) and merged-awaiting-main (B43). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TaskState { + /// 정리 중: the card has open questions or waits for its review. + Drafting, + /// 대기: Ready; waits for its predecessors, a slot or the environment. + Waiting, + /// 실행 중: a worker holds a slot. + Running, + /// 일시정지: a person paused it; slot released, worker asleep. + Paused, + /// 막힘: waits for an answer or a predecessor; slot released. + Blocked, + /// 검증 중: the worker reported done; Factory verifies. + Verifying, + /// 머지 대기: a person merges, requests changes or cancels. + MergeWaiting, + /// 머지됨: merged; main verification has not passed yet. + Landed, + /// 완료. + Done, + /// 멈춤: stopped without report, stalled, or verification failed three times. + Stopped, + /// 다시 올리기: reverted from main; runs again on the latest main. + Relanding, + /// 밖에서 진행 중: an outside pull request closes this Task's issue. + Outside, + /// 취소: kept seven days for revival. + Cancelled, +} + +impl TaskState { + pub const ALL: [Self; 13] = [ + Self::Drafting, + Self::Waiting, + Self::Running, + Self::Paused, + Self::Blocked, + Self::Verifying, + Self::MergeWaiting, + Self::Landed, + Self::Done, + Self::Stopped, + Self::Relanding, + Self::Outside, + Self::Cancelled, + ]; + + pub fn as_str(self) -> &'static str { + match self { + Self::Drafting => "drafting", + Self::Waiting => "waiting", + Self::Running => "running", + Self::Paused => "paused", + Self::Blocked => "blocked", + Self::Verifying => "verifying", + Self::MergeWaiting => "merge_waiting", + Self::Landed => "landed", + Self::Done => "done", + Self::Stopped => "stopped", + Self::Relanding => "relanding", + Self::Outside => "outside", + Self::Cancelled => "cancelled", + } + } + + /// Korean label the operator reads. + pub fn label(self) -> &'static str { + match self { + Self::Drafting => "정리 중", + Self::Waiting => "대기", + Self::Running => "실행 중", + Self::Paused => "일시정지", + Self::Blocked => "막힘", + Self::Verifying => "검증 중", + Self::MergeWaiting => "머지 대기", + Self::Landed => "머지됨", + Self::Done => "완료", + Self::Stopped => "멈춤", + Self::Relanding => "다시 올리기", + Self::Outside => "밖에서 진행 중", + Self::Cancelled => "취소", + } + } + + /// The board column (D-47). Cancelled sits outside the board. + pub fn column(self) -> Option { + match self { + Self::Drafting => Some(Column::Drafting), + Self::Waiting => Some(Column::Waiting), + Self::Done => Some(Column::Done), + Self::Cancelled => None, + _ => Some(Column::Running), + } + } + + /// Whether the Task holds one of the machine's worker slots. + pub fn holds_slot(self) -> bool { + matches!(self, Self::Running | Self::Relanding) + } + + /// A predecessor in this state lets its dependents start (D-29: merged). + pub fn merged(self) -> bool { + matches!(self, Self::Landed | Self::Done) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Column { + Drafting, + Waiting, + Running, + Done, +} + +impl Column { + pub const ALL: [Self; 4] = [Self::Drafting, Self::Waiting, Self::Running, Self::Done]; + + pub fn as_str(self) -> &'static str { + match self { + Self::Drafting => "drafting", + Self::Waiting => "waiting", + Self::Running => "running", + Self::Done => "done", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::Drafting => "정리 중", + Self::Waiting => "대기", + Self::Running => "실행 중", + Self::Done => "완료", + } + } +} + +/// The card's fields (D-06). Goal, criteria, out-of-scope, open decisions and +/// dependencies come from the producer; the review only adds. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Card { + pub title: String, + pub goal: String, + pub criteria: Vec, + pub out_of_scope: Vec, + pub open_decisions: Vec, + /// Task ids or issue references this Task waits on. + pub depends_on: Vec, + /// Waits on a Task of another repository: shown only (B64). + pub external: Vec, +} + +/// What a person sets on a card (D-06); empty means the Factory default. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct HumanFields { + pub review_directly: bool, + pub priority: i32, + pub merge_mode: Option, + pub runtime: Option, +} + +/// The record a Task is shown by: its issue once Ready, else its Task id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum IssueRef { + Github { number: u64 }, + Local { number: u32 }, +} + +impl IssueRef { + pub fn display(&self) -> String { + match self { + Self::Github { number } => format!("#{number}"), + Self::Local { number } => format!("L-{number}"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attachment { + /// Absolute path of the private copy the worker reads. + pub path: String, + pub sha256: String, + pub version: u32, + pub original: String, +} + +/// Where a question came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum QuestionOrigin { + Review, + Worker, + Check, + Engine, +} + +/// What answering a question does once chosen. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum QuestionKind { + /// An open decision while drafting (no deadline progress, D-09). + Intake, + /// The review proposed a split (D-55). + Split { pieces: Vec }, + /// A worker question with a default action (B26). + Default, + /// A worker question that cannot proceed without an answer (B27). + Blocking, + /// A scope change: a person approves a wider scope (B29 ③). + ScopeChange, + /// The new-task cap was reached (B31). + NewTaskCap, + /// A worker proposed a new Task outside autonomy (B30). + ProposedTask { draft: Box }, + /// A stop, a main break or a recovery that needs a person; the choices + /// are the actions. + Action, + /// A label-path card needs a person's confirmation (D-48, B15). + ConfirmCard, + /// A recovery proposal with the exact command and impact (B61). + Proposal { command: String, impact: String }, + /// Notification only (unrelated discovery, outside change, watch). + Notice, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SplitPiece { + pub title: String, + pub goal: String, + pub criteria: Vec, + /// Indexes of earlier pieces this piece waits on. + pub after: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Question { + pub id: String, + pub origin: QuestionOrigin, + pub kind: QuestionKind, + pub text: String, + pub suggestion: String, + pub default_action: Option, + pub deadline: Option, + pub asked_at: UnixMs, + pub choices: Vec, + pub answer: Option, + /// The letter a worker asked through, answered by reply. + pub letter: Option, +} + +impl Question { + pub fn open(&self) -> bool { + self.answer.is_none() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Answer { + pub text: String, + /// The suggestion or default chosen, when one was. + pub chose: Option, + /// Who relayed it: a pane id for an operator pane, or `deadline`. + pub relayed_by: String, + pub at: UnixMs, +} + +/// The five discovery classes (D-16, B29). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DiscoveryClass { + InScope = 1, + Decision = 2, + ScopeChange = 3, + Prerequisite = 4, + Unrelated = 5, +} + +impl DiscoveryClass { + pub fn parse(value: &str) -> Option { + match value { + "in-scope" | "in_scope" => Some(Self::InScope), + "decision" => Some(Self::Decision), + "scope-change" | "scope_change" => Some(Self::ScopeChange), + "prerequisite" => Some(Self::Prerequisite), + "unrelated" => Some(Self::Unrelated), + _ => None, + } + } + + /// How far the class is from a person: a reclassification may only move + /// toward a person (B30). ① and ② are the agent's, ③ and ⑤ go to a + /// person, ④ creates work a person approves. + pub fn toward_person(self) -> u8 { + match self { + Self::InScope => 0, + Self::Decision => 1, + Self::Prerequisite => 2, + Self::ScopeChange => 3, + Self::Unrelated => 3, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Discovery { + pub id: String, + pub class: DiscoveryClass, + pub text: String, + pub at: UnixMs, + /// The Task a prerequisite proposal created, once it exists. + pub task: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DecisionRecord { + pub text: String, + pub by: String, + pub at: UnixMs, +} + +/// A person gate that sends an auto Task to merge waiting (D-25, B39, B41). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Gate { + ReviewDirectly, + ApprovedScopeChange, + BreakingChange, + NoVerification, + RiskPath, + ManualMode, + OpenQuestion, + CheckFailed, + AutonomyDiff, + DirtyMain, +} + +impl Gate { + pub fn reason(self) -> &'static str { + match self { + Self::ReviewDirectly => "직접 확인 표시", + Self::ApprovedScopeChange => "승인된 범위 변경", + Self::BreakingChange => "보고된 breaking change 또는 공개 계약 변경", + Self::NoVerification => "검증 없음", + Self::RiskPath => "위험 경로 변경", + Self::ManualMode => "manual 머지", + Self::OpenQuestion => "열린 질문", + Self::CheckFailed => "점검을 하지 못함", + Self::AutonomyDiff => "자율 처리 diff 상한 초과", + Self::DirtyMain => "main checkout에 커밋 안 된 변경", + } + } +} + +/// Why a Task stopped (D-28, B24, B37, B31). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StopReason { + NoReport, + Stalled, + VerifyFailed, + NewTaskCap, + EnvironmentRepeated, +} + +impl StopReason { + pub fn label(self) -> &'static str { + match self { + Self::NoReport => "보고 없이 멈춤", + Self::Stalled => "정체", + Self::VerifyFailed => "검증 3회 실패", + Self::NewTaskCap => "새 Task 상한", + Self::EnvironmentRepeated => "같은 환경 실패 반복", + } + } +} + +/// The worker a Task runs, as the runtime adapter reported it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkerRef { + pub name: String, + pub pane: Option, + pub runtime: Runtime, + pub worktree: String, + pub branch: String, + pub started_at: UnixMs, + pub asleep: bool, +} + +/// A verification attempt in progress or finished. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attempt { + /// n of the n/3 count: fixes the worker submitted (D-53). + pub number: u32, + pub commit: Option, + pub started_at: UnixMs, + pub stage: AttemptStage, + pub outcome: Option, + pub log: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AttemptStage { + /// After done, in the Task worktree or the pull request's checks. + Task, + /// Before merge, on the latest main merged in (verify factories, B38). + PreMerge, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "result", rename_all = "snake_case")] +pub enum AttemptOutcome { + Passed, + Failed { check: String, link: String }, + Environment { signal: String, check: String }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PullRequest { + pub number: u64, + pub url: String, + pub head: String, + /// The Factory opened it (B36); otherwise a harness or an outside PR did. + pub by_factory: bool, + pub open: bool, +} + +/// A Task: the Factory's unit of execution (D-05). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Task { + pub factory: String, + /// `T-`. + pub id: String, + pub seq: u32, + pub issue: Option, + pub card: Card, + pub human: HumanFields, + pub state: TaskState, + pub state_since: UnixMs, + pub created_at: UnixMs, + pub updated_at: UnixMs, + /// The Task that proposed this one; its worker may not propose (depth 1). + pub proposed_by: Option, + /// Autonomy scope id when started without a person (B32). + pub autonomy: Option, + pub attachments: Vec, + pub questions: Vec, + pub discoveries: Vec, + pub decisions: Vec, + pub flags: Vec, + pub review: ReviewState, + pub producer_pane: Option, + pub worker: Option, + pub attempts: Vec, + /// n of n/3: verification failures counted against the Task (D-53). + pub failures: u32, + /// Environment failures in a row, for the reclassification rule (B60). + pub environment_failures: u32, + pub pr: Option, + pub merge_sha: Option, + pub gates: Vec, + pub stop: Option, + pub breaking: bool, + pub scope_approved: bool, + pub new_tasks: u32, + pub new_task_cap_extended: bool, + pub cancelled_at: Option, + /// State the Task was cancelled from, for revival (B55). + pub cancelled_from: Option, + pub purged: bool, + pub done_at: Option, + /// A person has seen the completion (the done column's unread dot). + pub seen: bool, + /// Worker reported done and then went quiet; tracked for B24. + pub last_report_at: Option, + pub idle_since: Option, + /// Intent keys of external writes already made (B73). + pub writes: BTreeSet, + /// Environment hold: a start was refused by the pre-start check (B57). + pub held: Option, + pub label_path: bool, + pub source_body_hash: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReviewState { + /// Not reviewed yet. + #[default] + Pending, + /// The judgment is queued or running. + Requested { at: UnixMs }, + /// The review answered. + Done { result: ReviewResult }, + /// The review could not run (B19); a person is asked to fix the provider. + Failed { reason: String }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReviewResult { + Ready, + NeedsAnswers, + Split, +} + +impl Task { + pub fn display_id(&self) -> String { + self.issue + .as_ref() + .map(IssueRef::display) + .unwrap_or_else(|| self.id.clone()) + } + + pub fn open_questions(&self) -> impl Iterator { + self.questions.iter().filter(|question| question.open()) + } + + pub fn merge_mode(&self, factory: &Factory) -> MergeMode { + if !factory.config.verification.exists() { + return MergeMode::Manual; + } + self.human.merge_mode.unwrap_or(factory.config.merge_mode) + } + + pub fn runtime(&self, factory: &Factory) -> Runtime { + self.human.runtime.unwrap_or(factory.config.default_runtime) + } + + /// The card a person must look at: blocked, stopped, merge waiting, or + /// an open question (D-28, D-47). + pub fn needs_person(&self) -> bool { + matches!( + self.state, + TaskState::Blocked | TaskState::Stopped | TaskState::MergeWaiting + ) || self + .open_questions() + .any(|question| !matches!(question.kind, QuestionKind::Notice)) + } + + pub fn branch_slug(&self) -> String { + let mut slug = String::new(); + for character in self.card.title.chars() { + if character.is_ascii_alphanumeric() { + slug.push(character.to_ascii_lowercase()); + } else if !slug.ends_with('-') && !slug.is_empty() { + slug.push('-'); + } + if slug.len() >= 32 { + break; + } + } + let slug = slug.trim_matches('-').to_owned(); + let number = match &self.issue { + Some(IssueRef::Github { number }) => number.to_string(), + Some(IssueRef::Local { number }) => format!("l{number}"), + None => self.id.to_ascii_lowercase(), + }; + if slug.is_empty() { + format!("factory/{number}") + } else { + format!("factory/{number}-{slug}") + } + } +} diff --git a/hide-factory/src/role.rs b/hide-factory/src/role.rs new file mode 100644 index 0000000000..449605872c --- /dev/null +++ b/hide-factory/src/role.rs @@ -0,0 +1,116 @@ +//! Who may run which Factory command (D-33, B56). +//! +//! The daemon decides the caller's role from its capability registry before +//! a command reaches the engine; a capability file holds only a token, so +//! editing it cannot change a role. + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "role", rename_all = "snake_case")] +pub enum Role { + /// A pane the Factory spawned, or a caller bound by cwd to a Factory + /// worktree. It reports on its own Task only. + Worker { factory: String, task: String }, + /// Any other pane or checkout caller; relays a person's words. + Operator { pane: String }, + /// The engine itself (timers, deadline defaults). Never a CLI caller. + Engine, +} + +impl Role { + pub fn name(&self) -> &'static str { + match self { + Self::Worker { .. } => "worker", + Self::Operator { .. } => "operator", + Self::Engine => "engine", + } + } + + /// What is recorded as having relayed a person's words. + pub fn relayed_by(&self) -> String { + match self { + Self::Worker { task, .. } => format!("worker:{task}"), + Self::Operator { pane } => pane.clone(), + Self::Engine => "engine".to_owned(), + } + } +} + +/// Every command a caller may send, named by what it does to the Factory. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Permission { + /// Read status, show, inbox. + Read, + /// Report on one's own Task: ask, block, propose, done, decisions. + Report, + /// Add a dependency (safer and slower). + AddDependency, + /// Create a Factory, add or edit a Task. + Intake, + /// Answer, approve scope, relay a person's words. + Answer, + /// Remove a dependency, change priority (faster, looser). + Loosen, + /// Merge, request changes (release a gate). + Merge, + /// Pause, resume, retry, cancel, revive, close. + Control, + /// Change settings. + Configure, +} + +impl Permission { + pub fn allowed(self, role: &Role) -> bool { + match role { + Role::Engine => true, + Role::Operator { .. } => !matches!(self, Self::Report), + Role::Worker { .. } => { + matches!(self, Self::Read | Self::Report | Self::AddDependency) + } + } + } +} + +/// The refusal a disallowed command gets, with the role it was refused for. +pub const ROLE_NOT_ALLOWED: &str = "role_not_allowed"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_worker_may_only_report_read_and_add_dependencies() { + let worker = Role::Worker { + factory: "f".into(), + task: "T-1".into(), + }; + for permission in [ + Permission::Read, + Permission::Report, + Permission::AddDependency, + ] { + assert!(permission.allowed(&worker), "{permission:?}"); + } + for permission in [ + Permission::Intake, + Permission::Answer, + Permission::Loosen, + Permission::Merge, + Permission::Control, + Permission::Configure, + ] { + assert!(!permission.allowed(&worker), "{permission:?}"); + } + } + + #[test] + fn an_operator_relays_a_person_but_does_not_report_as_a_worker() { + let operator = Role::Operator { pane: "p1".into() }; + assert!(Permission::Answer.allowed(&operator)); + assert!(Permission::Merge.allowed(&operator)); + assert!(!Permission::Report.allowed(&operator)); + assert_eq!(operator.relayed_by(), "p1"); + } +} diff --git a/hide-factory/src/store.rs b/hide-factory/src/store.rs new file mode 100644 index 0000000000..09115f2700 --- /dev/null +++ b/hide-factory/src/store.rs @@ -0,0 +1,466 @@ +//! The Factory store: one SQLite file (`factory.sqlite3`, WAL) in the state +//! folder, the source of truth for every Factory on this machine (D-03), and +//! a private folder beside it for PRD copies and verify logs. +//! +//! The schema is versioned with `PRAGMA user_version`; a newer file than this +//! build knows is refused rather than read. + +use std::fs; +use std::io::Write as _; +use std::path::{Path, PathBuf}; + +use rusqlite::{Connection, OptionalExtension, params}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::model::{Attachment, Factory, Task, UnixMs}; + +pub const SCHEMA_VERSION: i64 = 1; +pub const STORE_FILE: &str = "factory.sqlite3"; +pub const FILES_DIR: &str = "factory-files"; +/// A verify or CI log copy keeps at most its last 1 MiB per attempt (D-58). +pub const LOG_TAIL_LIMIT: usize = 1024 * 1024; +/// A PRD attachment larger than this is refused. +pub const ATTACHMENT_LIMIT: u64 = 4 * 1024 * 1024; +/// Events kept per Factory; the oldest are dropped past it. +pub const EVENT_LIMIT: i64 = 20_000; + +const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS factories ( + id TEXT PRIMARY KEY, + project TEXT NOT NULL UNIQUE, + data TEXT NOT NULL, + closed INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS tasks ( + factory TEXT NOT NULL REFERENCES factories(id), + id TEXT NOT NULL, + seq INTEGER NOT NULL, + issue TEXT, + state TEXT NOT NULL, + priority INTEGER NOT NULL DEFAULT 0, + data TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (factory, id) +); +CREATE INDEX IF NOT EXISTS tasks_issue ON tasks(factory, issue); +CREATE TABLE IF NOT EXISTS dependencies ( + factory TEXT NOT NULL, + task TEXT NOT NULL, + on_task TEXT NOT NULL, + PRIMARY KEY (factory, task, on_task) +); +CREATE TABLE IF NOT EXISTS events ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + factory TEXT NOT NULL, + task TEXT, + at INTEGER NOT NULL, + kind TEXT NOT NULL, + detail TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS events_factory ON events(factory, seq); +CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); +"; + +#[derive(Debug)] +pub struct StoreError(pub String); + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for StoreError { + fn from(error: rusqlite::Error) -> Self { + Self(format!("sqlite: {error}")) + } +} + +impl From for StoreError { + fn from(error: serde_json::Error) -> Self { + Self(format!("encoding: {error}")) + } +} + +impl From for StoreError { + fn from(error: std::io::Error) -> Self { + Self(format!("io: {error}")) + } +} + +/// One recorded transition, failure or external call (B77): ids and stage +/// only, never card text or secrets. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Event { + pub factory: String, + pub task: Option, + pub at: UnixMs, + pub kind: String, + pub detail: serde_json::Value, +} + +pub struct Store { + connection: Connection, + files: PathBuf, +} + +/// Everything the engine loads at start (B72). +#[derive(Default)] +pub struct Loaded { + pub factories: Vec, + pub tasks: Vec, + pub meta: Vec<(String, String)>, +} + +impl Store { + /// Opens or creates the store in `state_dir`; the files folder is made + /// private (0700) on Unix. + pub fn open(state_dir: &Path) -> Result { + fs::create_dir_all(state_dir)?; + let files = state_dir.join(FILES_DIR); + fs::create_dir_all(&files)?; + private_dir(&files)?; + let path = state_dir.join(STORE_FILE); + let connection = Connection::open(&path)?; + private_file(&path)?; + connection.pragma_update(None, "journal_mode", "WAL")?; + connection.pragma_update(None, "synchronous", "NORMAL")?; + connection.pragma_update(None, "foreign_keys", "ON")?; + connection.busy_timeout(std::time::Duration::from_secs(2))?; + let version: i64 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?; + if version > SCHEMA_VERSION { + return Err(StoreError(format!( + "store schema {version} is newer than this build ({SCHEMA_VERSION})" + ))); + } + connection.execute_batch(SCHEMA)?; + connection.pragma_update(None, "user_version", SCHEMA_VERSION)?; + Ok(Self { connection, files }) + } + + pub fn files_dir(&self) -> &Path { + &self.files + } + + pub fn load(&self) -> Result { + let mut loaded = Loaded::default(); + let mut statement = self + .connection + .prepare("SELECT data FROM factories ORDER BY created_at, id")?; + for row in statement.query_map([], |row| row.get::<_, String>(0))? { + loaded.factories.push(serde_json::from_str(&row?)?); + } + let mut statement = self + .connection + .prepare("SELECT data FROM tasks ORDER BY factory, seq")?; + for row in statement.query_map([], |row| row.get::<_, String>(0))? { + loaded.tasks.push(serde_json::from_str(&row?)?); + } + let mut statement = self.connection.prepare("SELECT key, value FROM meta")?; + for row in statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))? { + loaded.meta.push(row?); + } + Ok(loaded) + } + + pub fn put_factory(&self, factory: &Factory) -> Result<(), StoreError> { + self.connection.execute( + "INSERT INTO factories (id, project, data, closed, created_at) VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(id) DO UPDATE SET project = excluded.project, data = excluded.data, closed = excluded.closed", + params![ + factory.id, + factory.project, + serde_json::to_string(factory)?, + factory.closed, + factory.created_at as i64 + ], + )?; + Ok(()) + } + + /// Saves a Task and its dependency rows in one transaction. + pub fn put_task(&mut self, task: &Task) -> Result<(), StoreError> { + let transaction = self.connection.transaction()?; + transaction.execute( + "INSERT INTO tasks (factory, id, seq, issue, state, priority, data, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) + ON CONFLICT(factory, id) DO UPDATE SET issue = excluded.issue, state = excluded.state, + priority = excluded.priority, data = excluded.data, updated_at = excluded.updated_at", + params![ + task.factory, + task.id, + task.seq, + task.issue.as_ref().map(|issue| issue.display()), + task.state.as_str(), + task.human.priority, + serde_json::to_string(task)?, + task.created_at as i64, + task.updated_at as i64 + ], + )?; + transaction.execute( + "DELETE FROM dependencies WHERE factory = ?1 AND task = ?2", + params![task.factory, task.id], + )?; + for on in &task.card.depends_on { + transaction.execute( + "INSERT OR IGNORE INTO dependencies (factory, task, on_task) VALUES (?1, ?2, ?3)", + params![task.factory, task.id, on], + )?; + } + transaction.commit()?; + Ok(()) + } + + pub fn set_meta(&self, key: &str, value: &str) -> Result<(), StoreError> { + self.connection.execute( + "INSERT INTO meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + params![key, value], + )?; + Ok(()) + } + + pub fn append_event(&self, event: &Event) -> Result<(), StoreError> { + self.connection.execute( + "INSERT INTO events (factory, task, at, kind, detail) VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + event.factory, + event.task, + event.at as i64, + event.kind, + event.detail.to_string() + ], + )?; + let count: i64 = self.connection.query_row( + "SELECT COUNT(*) FROM events WHERE factory = ?1", + params![event.factory], + |row| row.get(0), + )?; + if count > EVENT_LIMIT { + self.connection.execute( + "DELETE FROM events WHERE seq IN (SELECT seq FROM events WHERE factory = ?1 ORDER BY seq LIMIT ?2)", + params![event.factory, count - EVENT_LIMIT], + )?; + } + Ok(()) + } + + pub fn events( + &self, + factory: &str, + task: Option<&str>, + limit: usize, + ) -> Result, StoreError> { + let mut statement = self.connection.prepare( + "SELECT factory, task, at, kind, detail FROM events + WHERE factory = ?1 AND (?2 IS NULL OR task = ?2) ORDER BY seq DESC LIMIT ?3", + )?; + let rows = statement.query_map(params![factory, task, limit as i64], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, String>(3)?, + row.get::<_, String>(4)?, + )) + })?; + let mut events = Vec::new(); + for row in rows { + let (factory, task, at, kind, detail) = row?; + events.push(Event { + factory, + task, + at: at as u64, + kind, + detail: serde_json::from_str(&detail)?, + }); + } + events.reverse(); + Ok(events) + } + + pub fn factory_for_project(&self, project: &str) -> Result, StoreError> { + Ok(self + .connection + .query_row( + "SELECT id FROM factories WHERE project = ?1", + params![project], + |row| row.get(0), + ) + .optional()?) + } + + /// Copies a PRD into the private folder under its hash (D-10, B16). + pub fn attach( + &self, + factory: &str, + task: &str, + source: &Path, + version: u32, + ) -> Result { + let metadata = fs::metadata(source)?; + if !metadata.is_file() { + return Err(StoreError("attachment_not_a_file".into())); + } + if metadata.len() > ATTACHMENT_LIMIT { + return Err(StoreError("attachment_too_large".into())); + } + let bytes = fs::read(source)?; + let digest = hex(&Sha256::digest(&bytes)); + let folder = self.files.join(factory).join(task); + fs::create_dir_all(&folder)?; + private_dir(&folder)?; + let extension = source + .extension() + .and_then(|value| value.to_str()) + .filter(|value| value.len() <= 8 && value.chars().all(|c| c.is_ascii_alphanumeric())) + .unwrap_or("md"); + let path = folder.join(format!("{digest}.{extension}")); + if !path.exists() { + write_private(&path, &bytes)?; + read_only(&path)?; + } + Ok(Attachment { + path: path.to_string_lossy().into_owned(), + sha256: digest, + version, + original: source.to_string_lossy().into_owned(), + }) + } + + /// Keeps the last [`LOG_TAIL_LIMIT`] bytes of a log for one attempt. + pub fn keep_log( + &self, + factory: &str, + task: &str, + attempt: u32, + stage: &str, + bytes: &[u8], + ) -> Result { + let folder = self.files.join(factory).join(task).join("logs"); + fs::create_dir_all(&folder)?; + private_dir(&folder)?; + let tail = &bytes[bytes.len().saturating_sub(LOG_TAIL_LIMIT)..]; + let path = folder.join(format!("attempt-{attempt}-{stage}.log")); + write_private(&path, tail)?; + Ok(path) + } +} + +pub fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + hex(&Sha256::digest(bytes)) +} + +fn write_private(path: &Path, bytes: &[u8]) -> Result<(), StoreError> { + let temporary = path.with_extension("partial"); + { + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + } + fs::rename(&temporary, path)?; + Ok(()) +} + +fn private_dir(path: &Path) -> Result<(), StoreError> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + } + let _ = path; + Ok(()) +} + +fn private_file(path: &Path) -> Result<(), StoreError> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + } + let _ = path; + Ok(()) +} + +fn read_only(path: &Path) -> Result<(), StoreError> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o400))?; + } + #[cfg(not(unix))] + { + let mut permissions = fs::metadata(path)?.permissions(); + permissions.set_readonly(true); + fs::set_permissions(path, permissions)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_newer_schema_is_refused_rather_than_read() { + let folder = tempfile::tempdir().unwrap(); + drop(Store::open(folder.path()).unwrap()); + let connection = Connection::open(folder.path().join(STORE_FILE)).unwrap(); + connection + .pragma_update(None, "user_version", SCHEMA_VERSION + 1) + .unwrap(); + drop(connection); + let error = Store::open(folder.path()).err().unwrap(); + assert!(error.0.contains("newer"), "{error}"); + } + + #[test] + fn a_log_copy_keeps_only_its_last_mebibyte() { + let folder = tempfile::tempdir().unwrap(); + let store = Store::open(folder.path()).unwrap(); + let mut bytes = vec![b'a'; LOG_TAIL_LIMIT]; + bytes.extend_from_slice(b"tail"); + let path = store.keep_log("f", "T-1", 1, "task", &bytes).unwrap(); + let kept = fs::read(path).unwrap(); + assert_eq!(kept.len(), LOG_TAIL_LIMIT); + assert!(kept.ends_with(b"tail")); + } + + #[test] + fn an_attachment_is_a_private_read_only_copy_named_by_its_hash() { + let folder = tempfile::tempdir().unwrap(); + let store = Store::open(&folder.path().join("state")).unwrap(); + let source = folder.path().join("prd.md"); + fs::write(&source, "# PRD\n").unwrap(); + let attachment = store.attach("f", "T-1", &source, 1).unwrap(); + assert_eq!(attachment.sha256, sha256_hex(b"# PRD\n")); + assert!( + attachment + .path + .ends_with(&format!("{}.md", attachment.sha256)) + ); + let copy = Path::new(&attachment.path); + assert!(fs::metadata(copy).unwrap().permissions().readonly()); + fs::write(&source, "# PRD v2\n").unwrap(); + let second = store.attach("f", "T-1", &source, 2).unwrap(); + assert_ne!(second.path, attachment.path); + assert_eq!(fs::read_to_string(copy).unwrap(), "# PRD\n"); + } +} diff --git a/hide-factory/src/summary.rs b/hide-factory/src/summary.rs new file mode 100644 index 0000000000..d1723a3d56 --- /dev/null +++ b/hide-factory/src/summary.rs @@ -0,0 +1,370 @@ +//! `FactorySummary`: the one value the CLI's `status` and `inbox` print and +//! the stage 2 screens draw (D-50). Every number in it is derived here from +//! the store's Tasks (design #4, #10); the shell computes nothing. +//! +//! This type is a contract with stage 2: add fields, never rename or remove. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::dag; +use crate::model::{Column, DAY_MS, Factory, QuestionKind, Task, TaskState, UnixMs}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct FactorySummary { + /// The one person-facing number: open inbox items across Factories (D-37). + pub my_turn: u32, + pub factories: Vec, + pub inbox: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FactoryView { + pub id: String, + pub project: String, + pub project_name: String, + pub source: String, + pub closed: bool, + pub flow: Flow, + pub my_turn: u32, + pub columns: Vec, + /// Off the board, revivable for the keep period (D-47). + pub cancelled: Vec, + pub graph: Graph, + pub outside_read_at: Option, + /// Three outside reads failed in a row (B65). + pub stale: bool, + pub main_broken: bool, + pub auto_merge_available: bool, + pub merge_mode: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Flow { + pub drafting: u32, + pub waiting: u32, + pub running: u32, + pub done_today: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ColumnView { + pub column: String, + pub label: String, + pub cards: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CardView { + pub task: String, + pub display_id: String, + pub title: String, + pub state: String, + pub state_label: String, + pub needs_person: bool, + /// What a waiting Task waits for, in words (D-36). + pub waiting_for: Option, + pub priority: i32, + pub since: UnixMs, + /// A completion the person has not looked at (D-30). + pub unread: bool, + /// Old completions fold (3 days) and old records fold (90 days). + pub folded: bool, + pub failures: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Graph { + pub nodes: Vec, + /// Reduced edges `(predecessor, task)` (D-36); the data keeps all. + pub edges: Vec<(String, String)>, + /// Tasks with no relation, drawn below. + pub unrelated: Vec, +} + +/// One person-facing item (D-19, D-49 order). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct InboxItem { + pub group: String, + pub rank: u8, + pub factory: String, + pub task: String, + pub display_id: String, + pub title: String, + pub project: String, + pub question: Option, + pub text: String, + pub suggestion: String, + pub default_action: Option, + pub choices: Vec, + pub deadline: Option, + pub remaining: Option, + pub waiting_since: UnixMs, +} + +pub fn build(factories: &[&Factory], tasks: &[&Task], now: UnixMs) -> FactorySummary { + let mut summary = FactorySummary::default(); + for factory in factories { + let mine: BTreeMap = tasks + .iter() + .filter(|task| task.factory == factory.id) + .map(|task| (task.id.clone(), (*task).clone())) + .collect(); + let items = inbox_items(factory, &mine, now); + let view = factory_view(factory, &mine, items.len() as u32, now); + summary.my_turn += view.my_turn; + summary.inbox.extend(items); + summary.factories.push(view); + } + summary.inbox.sort_by(|a, b| { + a.rank + .cmp(&b.rank) + .then(a.waiting_since.cmp(&b.waiting_since)) + }); + summary +} + +fn factory_view( + factory: &Factory, + tasks: &BTreeMap, + my_turn: u32, + now: UnixMs, +) -> FactoryView { + let today = now / DAY_MS; + let mut flow = Flow::default(); + let mut columns: BTreeMap> = BTreeMap::new(); + let mut cancelled = Vec::new(); + for task in tasks.values() { + let card = card_view(factory, task, tasks, now); + match task.state.column() { + Some(Column::Drafting) => flow.drafting += 1, + Some(Column::Waiting) => flow.waiting += 1, + Some(Column::Running) => flow.running += 1, + Some(Column::Done) if task.done_at.is_some_and(|at| at / DAY_MS == today) => { + flow.done_today += 1; + } + Some(Column::Done) => {} + None => {} + } + match task.state.column() { + Some(column) => columns.entry(column).or_default().push((task, card)), + None => cancelled.push(card), + } + } + let columns = Column::ALL + .into_iter() + .map(|column| { + let mut cards = columns.remove(&column).unwrap_or_default(); + // Person cards first, longest waiting first; then priority, then age (D-47). + cards.sort_by(|(a, a_view), (b, b_view)| { + b_view.needs_person.cmp(&a_view.needs_person).then_with(|| { + if a_view.needs_person { + a.state_since.cmp(&b.state_since) + } else { + dag::slot_order(a, b) + } + }) + }); + ColumnView { + column: column.as_str().to_owned(), + label: column.label().to_owned(), + cards: cards.into_iter().map(|(_, view)| view).collect(), + } + }) + .collect(); + let edges = dag::edges(tasks.values()); + let reduced = dag::transitive_reduction(&edges); + let related: std::collections::BTreeSet<&String> = + reduced.iter().flat_map(|(a, b)| [a, b]).collect(); + let graph = Graph { + nodes: tasks + .values() + .filter(|task| task.state != TaskState::Cancelled) + .map(|task| task.id.clone()) + .collect(), + unrelated: tasks + .values() + .filter(|task| task.state != TaskState::Cancelled && !related.contains(&task.id)) + .map(|task| task.id.clone()) + .collect(), + edges: reduced, + }; + FactoryView { + id: factory.id.clone(), + project: factory.project.clone(), + project_name: factory.project_name.clone(), + source: match factory.source { + crate::model::SourceKind::Github => "github".into(), + crate::model::SourceKind::Local => "local".into(), + }, + closed: factory.closed, + flow, + my_turn, + columns, + cancelled, + graph, + outside_read_at: factory.outside_read_at, + stale: factory.outside_read_failures >= 3, + main_broken: factory.main.broken, + auto_merge_available: factory.config.verification.exists(), + merge_mode: match factory.config.merge_mode { + crate::model::MergeMode::Auto if factory.config.verification.exists() => "auto".into(), + _ => "manual".into(), + }, + } +} + +pub fn card_view( + factory: &Factory, + task: &Task, + tasks: &BTreeMap, + now: UnixMs, +) -> CardView { + let waiting = dag::waiting_for(task, tasks); + let waiting_for = match task.state { + TaskState::Waiting if !waiting.is_empty() => Some( + waiting + .iter() + .map(|id| { + tasks + .get(id) + .map(Task::display_id) + .unwrap_or_else(|| id.clone()) + }) + .collect::>() + .join(", "), + ), + TaskState::Waiting => task.held.clone().or_else(|| Some("slot".into())), + TaskState::Blocked => Some( + task.open_questions() + .find(|question| matches!(question.kind, QuestionKind::Blocking)) + .map(|_| "answer".to_owned()) + .unwrap_or_else(|| "predecessor".to_owned()), + ), + _ => None, + }; + let folded = match task.state { + TaskState::Done => task + .done_at + .is_some_and(|at| now.saturating_sub(at) > factory.config.done_fold_ms), + TaskState::Cancelled => task.purged, + _ => false, + }; + CardView { + task: task.id.clone(), + display_id: task.display_id(), + title: task.card.title.clone(), + state: task.state.as_str().to_owned(), + state_label: task + .stop + .filter(|_| task.state == TaskState::Stopped) + .map(|reason| format!("{} ({})", task.state.label(), reason.label())) + .unwrap_or_else(|| task.state.label().to_owned()), + needs_person: task.needs_person(), + waiting_for, + priority: task.human.priority, + since: task.state_since, + unread: task.state == TaskState::Done && !task.seen, + folded, + failures: task.failures, + } +} + +/// Inbox order (D-49): blocking questions longest waiting first, then other +/// answers, then merge waiting, then stopped, then notices. +pub fn inbox_items( + factory: &Factory, + tasks: &BTreeMap, + now: UnixMs, +) -> Vec { + let mut items = Vec::new(); + for task in tasks.values() { + if matches!(task.state, TaskState::Cancelled) && task.purged { + continue; + } + let base = |group: &str, rank: u8, text: String, since: UnixMs| InboxItem { + group: group.to_owned(), + rank, + factory: factory.id.clone(), + task: task.id.clone(), + display_id: task.display_id(), + title: task.card.title.clone(), + project: factory.project_name.clone(), + question: None, + text, + suggestion: String::new(), + default_action: None, + choices: Vec::new(), + deadline: None, + remaining: None, + waiting_since: since, + }; + for question in task.open_questions() { + let (group, rank) = match question.kind { + QuestionKind::Blocking => ("answer", 0), + QuestionKind::Notice => ("notice", 4), + QuestionKind::Action | QuestionKind::Proposal { .. } => ("stopped", 3), + _ => ("answer", 1), + }; + let mut item = base(group, rank, question.text.clone(), question.asked_at); + item.question = Some(question.id.clone()); + item.suggestion = question.suggestion.clone(); + item.default_action = question.default_action.clone(); + item.choices = question.choices.clone(); + item.deadline = question.deadline; + item.remaining = match (&question.kind, question.deadline) { + (QuestionKind::Blocking, _) => { + let days = now.saturating_sub(question.asked_at) / DAY_MS; + (days >= 1).then(|| format!("{days}일째 기다림")) + } + (_, Some(deadline)) if deadline > now => { + let hours = (deadline - now).div_ceil(crate::model::HOUR_MS); + Some(format!("{hours}시간 남음")) + } + (_, Some(_)) => Some("기한 지남".into()), + _ => None, + }; + items.push(item); + } + match task.state { + TaskState::MergeWaiting => { + let reasons: Vec<_> = task.gates.iter().map(|gate| gate.reason()).collect(); + let mut item = base( + "merge", + 2, + if reasons.is_empty() { + "머지 대기".to_owned() + } else { + format!("머지 대기: {}", reasons.join(", ")) + }, + task.state_since, + ); + item.choices = vec!["merge".into(), "request-changes".into(), "cancel".into()]; + items.push(item); + } + TaskState::Stopped + if !task.open_questions().any(|question| { + matches!( + question.kind, + QuestionKind::Action | QuestionKind::NewTaskCap + ) + }) => + { + let mut item = base( + "stopped", + 3, + format!( + "멈춤: {}", + task.stop.map(|reason| reason.label()).unwrap_or("?") + ), + task.state_since, + ); + item.choices = vec!["retry".into(), "cancel".into()]; + items.push(item); + } + _ => {} + } + } + items +} From b41b9030f67b395042176f4c8e3e8cad2b4c877a Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 03:39:17 +0900 Subject: [PATCH 02/72] Run Factory Tasks through the engine: state machine, DAG scheduling, verification, merge and revert The engine owns every Factory on the machine and moves Tasks on commands, letters and ticks: intake review, issue creation, slot scheduling by priority then age across Factories, worker questions and discoveries, verification with the failure limit, pre-merge checks, human gates, auto and manual merge, main-break revert of the first failing merge, outside work, environment holds and cascades, watch warnings and retention. Recording fakes and an injected clock drive 40 engine tests. --- hide-factory/src/adapters.rs | 2 + hide-factory/src/command.rs | 4 + hide-factory/src/engine.rs | 5241 +++++++++++++++++++++++++++++ hide-factory/src/lib.rs | 2 + hide-factory/tests/engine.rs | 1506 +++++++++ hide-factory/tests/support/mod.rs | 597 ++++ 6 files changed, 7352 insertions(+) create mode 100644 hide-factory/src/engine.rs create mode 100644 hide-factory/tests/engine.rs create mode 100644 hide-factory/tests/support/mod.rs diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index 59047317e7..ed1df74cf4 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -231,6 +231,8 @@ pub trait MergeTarget { fn reopen_pr(&mut self, factory: &Factory, pr: &PullRequest) -> Result<(), Failure>; fn diff_lines(&mut self, factory: &Factory, task: &Task) -> Result; fn changed_paths(&mut self, factory: &Factory, task: &Task) -> Result, Failure>; + /// The Task's diff against main, for the drift and user checks (D-44). + fn diff_text(&mut self, factory: &Factory, task: &Task) -> Result; /// merge-tree against the current main and the quick check (B38). fn premerge(&mut self, factory: &Factory, task: &Task) -> Result; /// Whether the local main checkout has uncommitted changes (B42). diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs index ecb1d22bd9..7eb1d64c18 100644 --- a/hide-factory/src/command.rs +++ b/hide-factory/src/command.rs @@ -78,6 +78,10 @@ pub enum Command { text: String, /// A prerequisite or unrelated Task's card. card: Option, + /// An enabled autonomy scope the new Task claims (B32). + autonomy: Option, + /// Moves an earlier discovery to `class`; only toward a person (B30). + reclassify: Option, letter: Option, }, Done { diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs new file mode 100644 index 0000000000..67c3ff6da1 --- /dev/null +++ b/hide-factory/src/engine.rs @@ -0,0 +1,5241 @@ +//! The engine: every Factory on this machine, their Tasks and the rules that +//! move them (D-01, D-28, D-29). It is one value driven from one thread: +//! `command` for a caller, `letter` for mail addressed to a Factory, and +//! `tick` for time and the outside world. Each change is saved before the +//! answer leaves (B72). + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use serde_json::{Value, json}; + +use crate::adapters::{ + Clock, EnvSignal, Environment, Failure, Judge, MainCheck, MemoryPressure, MergeTarget, + Notifier, OutsideEvent, PreMerge, RevertRef, TaskSource, Verifier, VerifyPoll, VerifyRun, + WorkerRuntime, WorkerSpawn, WorkerStatus, +}; +use crate::command::{CardInput, Command, Refusal, VerificationChoice}; +use crate::dag; +use crate::judgment::{self, Judgment, JudgmentInput, JudgmentOutcome, OtherTask, Priority}; +use crate::model::*; +use crate::role::{ROLE_NOT_ALLOWED, Role}; +use crate::store::{Event, Store, StoreError, sha256_hex}; +use crate::summary::{self, FactorySummary}; + +/// The world the engine acts on. +pub struct Ports { + pub clock: Box, + pub source: Box, + pub verifier: Box, + pub merge: Box, + pub workers: Box, + pub judge: Box, + pub environment: Box, + pub notifier: Box, +} + +/// Mail addressed to a Factory's code-owned recipient (D-14). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Inbound { + pub id: String, + pub factory: String, + pub sender_pane: String, + /// `request`, `block`, `report` or `watch`. + pub kind: String, + pub body: String, +} + +pub const TITLE_LIMIT: usize = 200; +pub const TEXT_LIMIT: usize = 4_000; +pub const LIST_LIMIT: usize = 30; +pub const TASK_LIMIT: usize = 5_000; +/// Wait between retries of a rate-limited or failing GitHub read (B58). +const BACKOFF_MS: [u64; 5] = [ + MINUTE_MS, + 2 * MINUTE_MS, + 5 * MINUTE_MS, + 15 * MINUTE_MS, + 30 * MINUTE_MS, +]; +const PROCESSED_LETTERS: usize = 4_096; +const CASCADE_WINDOW_MS: u64 = 30 * MINUTE_MS; +const ENV_RECHECK_MS: u64 = MINUTE_MS; + +struct VerifyState { + run: VerifyRun, + stage: AttemptStage, +} + +#[derive(Clone)] +enum RevertPhase { + /// A skipped or cancelled run was asked again; waits for its result. + Bisecting { + index: usize, + }, + Reverting { + revert: RevertRef, + task: String, + }, +} + +pub struct Engine { + store: Store, + ports: Ports, + factories: BTreeMap, + tasks: BTreeMap>, + verifying: BTreeMap<(String, String), VerifyState>, + /// Judgments waiting: id -> (factory, task, purpose). + judgments: BTreeMap, Purpose)>, + /// Drift and user checks still running per Task. + checks_running: BTreeMap<(String, String), u32>, + reverts: BTreeMap, + /// Main heads already checked per Factory. + main_seen: BTreeMap, + processed: BTreeSet, + processed_order: Vec, + /// Recent environment-class failures: (at, factory, task, stage). + env_failures: Vec<(UnixMs, String, String, String)>, + /// New starts halted by a cascade until this time (B60). + halt_until: Option, + env_problem_since: Option, + env_diagnosed: bool, + hold_checked_at: Option, + hold_reason: Option, + /// A runtime unavailable until its usage resets (B58). + runtime_blocked: BTreeMap, + github_backoff: BTreeMap, + machine_max_workers: u32, + question_seq: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Purpose { + Intake, + Drift, + Check, + Watch, + Env, +} + +type Reply = Result; + +fn refuse(reason: &str, next: &str) -> Refusal { + Refusal::new(reason, next) +} + +impl Engine { + pub fn open(state_dir: &Path, ports: Ports) -> Result { + let store = Store::open(state_dir)?; + let loaded = store.load()?; + let mut engine = Self { + store, + ports, + factories: BTreeMap::new(), + tasks: BTreeMap::new(), + verifying: BTreeMap::new(), + judgments: BTreeMap::new(), + checks_running: BTreeMap::new(), + reverts: BTreeMap::new(), + main_seen: BTreeMap::new(), + processed: BTreeSet::new(), + processed_order: Vec::new(), + env_failures: Vec::new(), + halt_until: None, + env_problem_since: None, + env_diagnosed: false, + hold_checked_at: None, + hold_reason: None, + runtime_blocked: BTreeMap::new(), + github_backoff: BTreeMap::new(), + machine_max_workers: 5, + question_seq: 0, + }; + for factory in loaded.factories { + engine.tasks.entry(factory.id.clone()).or_default(); + engine.factories.insert(factory.id.clone(), factory); + } + for task in loaded.tasks { + for question in &task.questions { + if let Some(number) = question + .id + .strip_prefix('Q') + .and_then(|n| n.parse::().ok()) + { + engine.question_seq = engine.question_seq.max(number); + } + } + engine + .tasks + .entry(task.factory.clone()) + .or_default() + .insert(task.id.clone(), task); + } + for (key, value) in loaded.meta { + match key.as_str() { + "machine.max_workers" => { + engine.machine_max_workers = value.parse().unwrap_or(5); + } + "processed_letters" => { + let ids: Vec = serde_json::from_str(&value).unwrap_or_default(); + engine.processed_order = ids.clone(); + engine.processed = ids.into_iter().collect(); + } + _ => {} + } + } + // A restart resumes what was in flight (B72): verifications start + // again from their recorded attempt, since a child of the old + // process is gone; reviews still pending are asked again. + let now = engine.now(); + let pending: Vec<(String, String, TaskState, ReviewState)> = engine + .all_tasks() + .map(|task| { + ( + task.factory.clone(), + task.id.clone(), + task.state, + task.review.clone(), + ) + }) + .collect(); + for (factory, id, state, review) in pending { + if state == TaskState::Verifying { + engine.restart_verification(&factory, &id); + } + if state == TaskState::Drafting && matches!(review, ReviewState::Requested { .. }) { + engine.request_review(&factory, &id, now); + } + } + Ok(engine) + } + + fn now(&self) -> UnixMs { + self.ports.clock.now() + } + + fn all_tasks(&self) -> impl Iterator { + self.tasks.values().flat_map(BTreeMap::values) + } + + pub fn factories(&self) -> impl Iterator { + self.factories.values() + } + + pub fn task(&self, factory: &str, id: &str) -> Option<&Task> { + self.tasks.get(factory)?.get(id) + } + + pub fn tasks_of(&self, factory: &str) -> impl Iterator { + self.tasks + .get(factory) + .into_iter() + .flat_map(BTreeMap::values) + } + + pub fn summary(&self) -> FactorySummary { + let factories: Vec<&Factory> = self.factories.values().collect(); + let tasks: Vec<&Task> = self.all_tasks().collect(); + summary::build(&factories, &tasks, self.now()) + } + + pub fn events(&self, factory: &str, task: Option<&str>, limit: usize) -> Vec { + self.store.events(factory, task, limit).unwrap_or_default() + } + + /// The role of a caller (D-33): a pane the Factory spawned, or a cwd + /// inside a Factory worktree, is a worker of that Task. + pub fn role_for(&self, pane: Option<&str>, cwd: Option<&str>) -> Option<(String, String)> { + for task in self.all_tasks() { + let Some(worker) = &task.worker else { continue }; + if matches!(task.state, TaskState::Cancelled | TaskState::Done) { + continue; + } + if pane.is_some() && worker.pane.as_deref() == pane { + return Some((task.factory.clone(), task.id.clone())); + } + if let Some(cwd) = cwd { + let root = Path::new(&worker.worktree); + if Path::new(cwd).starts_with(root) { + return Some((task.factory.clone(), task.id.clone())); + } + } + } + None + } + + /// Worker panes and worktrees, for the daemon's role registry. + pub fn worker_bindings(&self) -> Vec<(String, String, Option, String)> { + self.all_tasks() + .filter(|task| !matches!(task.state, TaskState::Cancelled | TaskState::Done)) + .filter_map(|task| { + task.worker.as_ref().map(|worker| { + ( + task.factory.clone(), + task.id.clone(), + worker.pane.clone(), + worker.worktree.clone(), + ) + }) + }) + .collect() + } + + pub fn factory_for_project(&self, project: &str) -> Option<&Factory> { + let path = Path::new(project); + self.factories + .values() + .filter(|factory| path.starts_with(&factory.project)) + .max_by_key(|factory| factory.project.len()) + } + + fn record(&self, factory: &str, task: Option<&str>, kind: &str, detail: Value) { + let event = Event { + factory: factory.to_owned(), + task: task.map(str::to_owned), + at: self.now(), + kind: kind.to_owned(), + detail, + }; + // A failed diagnostic write never changes a decision. + let _ = self.store.append_event(&event); + } + + fn save_factory(&mut self, id: &str) { + if let Some(factory) = self.factories.get(id) + && let Err(error) = self.store.put_factory(factory) + { + self.record( + id, + None, + "store.failed", + json!({"stage": "factory", "error": error.0}), + ); + } + } + + fn save(&mut self, factory: &str, id: &str) { + let Some(task) = self + .tasks + .get(factory) + .and_then(|tasks| tasks.get(id)) + .cloned() + else { + return; + }; + if let Err(error) = self.store.put_task(&task) { + self.record( + factory, + Some(id), + "store.failed", + json!({"stage": "task", "error": error.0}), + ); + } + } + + fn with_task( + &mut self, + factory: &str, + id: &str, + change: impl FnOnce(&mut Task) -> R, + ) -> Option { + let now = self.now(); + let task = self.tasks.get_mut(factory)?.get_mut(id)?; + let result = change(task); + task.updated_at = now; + self.save(factory, id); + Some(result) + } + + fn set_state(&mut self, factory: &str, id: &str, state: TaskState) { + let now = self.now(); + let mut from = None; + self.with_task(factory, id, |task| { + if task.state != state { + from = Some(task.state); + task.state = state; + task.state_since = now; + if state == TaskState::Done { + task.done_at = Some(now); + task.seen = false; + } + if state != TaskState::Stopped { + task.stop = None; + } + } + }); + if let Some(from) = from { + self.record( + factory, + Some(id), + "task.state", + json!({"from": from.as_str(), "to": state.as_str()}), + ); + } + } + + fn next_question_id(&mut self) -> String { + self.question_seq += 1; + format!("Q{}", self.question_seq) + } + + #[allow(clippy::too_many_arguments)] + fn add_question( + &mut self, + factory: &str, + id: &str, + origin: QuestionOrigin, + kind: QuestionKind, + text: &str, + suggestion: &str, + default_action: Option, + deadline: Option, + choices: Vec, + letter: Option, + ) -> String { + let question_id = self.next_question_id(); + let now = self.now(); + let notify = matches!(kind, QuestionKind::Blocking); + let question = Question { + id: question_id.clone(), + origin, + kind, + text: judgment::cut(text, TEXT_LIMIT), + suggestion: judgment::cut(suggestion, TEXT_LIMIT), + default_action, + deadline, + asked_at: now, + choices, + answer: None, + letter, + }; + self.with_task(factory, id, |task| task.questions.push(question)); + self.record( + factory, + Some(id), + "question.added", + json!({"question": question_id}), + ); + if notify + && self + .factories + .get(factory) + .is_some_and(|f| f.config.macos_notifications) + { + let title = self + .task(factory, id) + .map(|task| format!("Factory: {} needs an answer", task.display_id())) + .unwrap_or_default(); + self.ports.notifier.macos(&title, "Open hide factory inbox"); + } + question_id + } + + fn notice(&mut self, factory: &str, id: &str, text: &str) { + self.add_question( + factory, + id, + QuestionOrigin::Engine, + QuestionKind::Notice, + text, + "", + None, + None, + vec!["ok".into()], + None, + ); + } + + fn running_count(&self) -> u32 { + self.all_tasks() + .filter(|task| task.state.holds_slot()) + .count() as u32 + } + + // ----------------------------------------------------------------- commands + + pub fn command(&mut self, role: &Role, command: Command) -> Value { + if !command.permission().allowed(role) { + return Refusal::new( + ROLE_NOT_ALLOWED, + "This command needs a person; ask in an operator pane", + ) + .with(json!({"role": role.name(), "verb": command.verb()})) + .to_json(); + } + let verb = command.verb(); + let answer = self.run_command(role, command); + match answer { + Ok(mut value) => { + if value.get("ok").is_none() { + value["ok"] = json!(true); + } + value + } + Err(refusal) => { + self.record( + "-", + None, + "command.refused", + json!({"verb": verb, "reason": refusal.reason}), + ); + refusal.to_json() + } + } + } + + fn run_command(&mut self, role: &Role, command: Command) -> Reply { + match command { + Command::Init { + project, + verification, + merge_mode, + confirm, + } => self.init(&project, verification, merge_mode, confirm), + Command::Add { + project, + task, + issue, + card, + producer_pane, + } => self.add( + role, + project.as_deref(), + task.as_deref(), + issue.as_deref(), + card, + producer_pane, + ), + Command::Status { project } => self.status(project.as_deref()), + Command::Show { task } => { + let (factory, id) = self.resolve(role, &task)?; + Ok(json!({"task": self.show(&factory, &id)})) + } + Command::Inbox => { + let summary = self.summary(); + Ok(json!({"count": summary.my_turn, "items": summary.inbox})) + } + Command::Answer { + task, + question, + choice, + text, + } => { + let (factory, id) = self.resolve(role, &task)?; + self.answer(role, &factory, &id, question.as_deref(), choice, text) + } + Command::Ask { + text, + suggestion, + default_action, + deadline_hours, + letter, + } => { + let (factory, id) = self.own_task(role)?; + self.ask( + &factory, + &id, + &text, + &suggestion, + Some(default_action), + deadline_hours, + letter, + ) + } + Command::Block { + text, + suggestion, + deadline_hours, + letter, + } => { + let (factory, id) = self.own_task(role)?; + self.ask( + &factory, + &id, + &text, + &suggestion, + None, + deadline_hours, + letter, + ) + } + Command::Propose { + class, + text, + card, + autonomy, + reclassify, + letter, + } => { + let (factory, id) = self.own_task(role)?; + self.propose( + &factory, &id, class, &text, card, autonomy, reclassify, letter, + ) + } + Command::Done { + summary, + breaking, + letter, + } => { + let (factory, id) = self.own_task(role)?; + self.done(&factory, &id, summary, breaking, letter) + } + Command::Decide { text } => { + let (factory, id) = self.own_task(role)?; + let by = role.relayed_by(); + let now = self.now(); + self.with_task(&factory, &id, |task| { + task.decisions.push(DecisionRecord { + text: judgment::cut(&text, TEXT_LIMIT), + by, + at: now, + }) + }); + Ok(json!({"message": "decision recorded"})) + } + Command::Config { project, set } => self.config(role, project.as_deref(), set), + Command::Priority { task, priority } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "priority")?; + self.with_task(&factory, &id, |task| task.human.priority = priority); + Ok(self.task_answer(&factory, &id, "priority set")) + } + Command::Dep { task, on, remove } => self.dep(role, &task, &on, remove), + Command::Pause { task } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "pause")?; + self.put_to_sleep(&factory, &id); + self.set_state(&factory, &id, TaskState::Paused); + Ok(self.task_answer(&factory, &id, "paused; slot released")) + } + Command::Resume { task } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "resume")?; + self.set_state(&factory, &id, TaskState::Waiting); + Ok(self.task_answer(&factory, &id, "resumes when a slot is free")) + } + Command::Retry { task } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "retry")?; + self.with_task(&factory, &id, |task| { + task.failures = 0; + task.environment_failures = 0; + for question in task.questions.iter_mut().filter(|q| q.open()) { + if matches!(question.kind, QuestionKind::Action) { + question.answer = Some(Answer { + text: "retry".into(), + chose: Some("retry".into()), + relayed_by: role.relayed_by(), + at: 0, + }); + } + } + }); + self.set_state(&factory, &id, TaskState::Waiting); + Ok(self.task_answer( + &factory, + &id, + "restarts in the same worktree when a slot is free", + )) + } + Command::Merge { task } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "merge")?; + self.manual_merge(role, &factory, &id) + } + Command::RequestChanges { task, comment } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "request-changes")?; + if comment.trim().is_empty() { + return Err(refuse( + "comment_required", + "Add --comment with what to change", + )); + } + let by = role.relayed_by(); + let now = self.now(); + self.with_task(&factory, &id, |task| { + task.decisions.push(DecisionRecord { + text: format!("수정 요청: {}", judgment::cut(&comment, TEXT_LIMIT)), + by, + at: now, + }); + task.gates.clear(); + }); + self.set_state(&factory, &id, TaskState::Running); + self.wake(&factory, &id, &format!( + "Factory: 사람이 수정을 요청했습니다.\n{comment}\n고친 뒤 다시 hide factory done 하세요." + )); + Ok(self.task_answer(&factory, &id, "sent back to the worker")) + } + Command::Cancel { task } => { + let (factory, id) = self.resolve(role, &task)?; + self.allowed(&factory, &id, "cancel")?; + self.cancel(&factory, &id); + Ok(self.task_answer(&factory, &id, "cancelled; revivable for 7 days")) + } + Command::Revive { task } => { + let (factory, id) = self.resolve(role, &task)?; + // A cancelled Task past its keep period says so (B71). + if self + .task(&factory, &id) + .is_none_or(|t| t.state != TaskState::Cancelled) + { + self.allowed(&factory, &id, "revive")?; + } + self.revive(&factory, &id) + } + Command::Close { project } => self.close(role, project.as_deref()), + Command::Check { + project, + at, + instruction, + } => { + let factory = self.factory_id(project.as_deref())?; + if instruction.trim().is_empty() { + return Err(refuse("instruction_required", "Give --instruction")); + } + if let Some(f) = self.factories.get_mut(&factory) { + f.config.checks.push(UserCheck { + at, + instruction: judgment::cut(&instruction, TEXT_LIMIT), + }); + } + self.save_factory(&factory); + Ok(json!({"message": "check added"})) + } + } + } + + fn factory_id(&self, project: Option<&str>) -> Result { + match project { + Some(project) => self + .factory_for_project(project) + .map(|factory| factory.id.clone()) + .ok_or_else(|| { + refuse( + "factory_not_found", + "Create one with hide factory init ", + ) + }), + None => { + let open: Vec<_> = self.factories.values().filter(|f| !f.closed).collect(); + match open.as_slice() { + [only] => Ok(only.id.clone()), + [] => Err(refuse( + "factory_not_found", + "Create one with hide factory init ", + )), + _ => Err(refuse("factory_ambiguous", "Pass --project ")), + } + } + } + } + + /// A Task by its id (`T-3`), issue (`#412`, `L-12`) or `factory/T-3`. + fn resolve(&self, role: &Role, reference: &str) -> Result<(String, String), Refusal> { + let reference = reference.trim(); + let mut found = Vec::new(); + for task in self.all_tasks() { + if task.id == reference + || task + .issue + .as_ref() + .is_some_and(|issue| issue.display() == reference) + || format!("{}/{}", task.factory, task.id) == reference + { + found.push((task.factory.clone(), task.id.clone())); + } + } + if let Role::Worker { factory, .. } = role { + found.retain(|(f, _)| f == factory); + } + match found.as_slice() { + [one] => Ok(one.clone()), + [] => Err(refuse( + "task_not_found", + "Check the Task id or issue number with hide factory status", + )), + _ => Err(refuse("task_ambiguous", "Use /")), + } + } + + fn own_task(&self, role: &Role) -> Result<(String, String), Refusal> { + match role { + Role::Worker { factory, task } => Ok((factory.clone(), task.clone())), + _ => Err(refuse( + ROLE_NOT_ALLOWED, + "Only a Factory worker reports on its Task", + )), + } + } + + /// Actions a person may take in each state (Q29, B53). + pub fn allowed_actions(task: &Task) -> Vec<&'static str> { + let mut actions: Vec<&'static str> = match task.state { + TaskState::Drafting => vec!["edit", "cancel"], + TaskState::Waiting => vec!["priority", "dep-remove", "cancel"], + TaskState::Running => vec!["pause", "cancel"], + TaskState::Paused => vec!["resume", "cancel"], + // Q29: a blocked Task takes only an answer. + TaskState::Blocked => vec![], + TaskState::Verifying => vec!["cancel"], + TaskState::MergeWaiting => vec!["merge", "request-changes", "cancel"], + TaskState::Stopped => vec!["retry", "cancel"], + TaskState::Landed | TaskState::Done | TaskState::Relanding => vec![], + TaskState::Outside => vec!["revive"], + TaskState::Cancelled if !task.purged => vec!["revive"], + TaskState::Cancelled => vec![], + }; + if task.open_questions().next().is_some() { + actions.insert(0, "answer"); + } + actions + } + + fn allowed(&self, factory: &str, id: &str, action: &str) -> Result<(), Refusal> { + let task = self + .task(factory, id) + .ok_or_else(|| refuse("task_not_found", "Check hide factory status"))?; + let allowed = Self::allowed_actions(task); + if allowed.contains(&action) { + return Ok(()); + } + Err(refuse( + "action_not_allowed_in_state", + "Choose one of the allowed actions", + ) + .with(json!({"state": task.state.label(), "allowed": allowed}))) + } + + fn task_answer(&self, factory: &str, id: &str, message: &str) -> Value { + let task = self.task(factory, id); + json!({ + "message": message, + "task": task.map(|task| json!({ + "id": task.id, + "display_id": task.display_id(), + "state": task.state.label(), + "state_id": task.state.as_str(), + })), + }) + } + + // --------------------------------------------------------------------- init + + fn init( + &mut self, + project: &str, + verification: Option, + merge_mode: Option, + confirm: bool, + ) -> Reply { + let project = project.trim_end_matches('/').to_owned(); + if project.is_empty() || !Path::new(&project).is_absolute() { + return Err(refuse( + "project_required", + "Give the project's absolute path", + )); + } + if let Some(existing) = self.factories.values().find(|f| f.project == project) { + if !existing.closed { + return Ok( + json!({"existing": true, "factory": {"id": existing.id, "project": existing.project}}), + ); + } + if confirm { + let id = existing.id.clone(); + if let Some(factory) = self.factories.get_mut(&id) { + factory.closed = false; + } + self.save_factory(&id); + self.record(&id, None, "factory.reopened", json!({})); + return Ok( + json!({"created": true, "reopened": true, "factory": {"id": id, "project": project}}), + ); + } + } + let probe = match self.ports.source.probe(&project) { + Ok(probe) => probe, + Err(failure) => { + let next = match failure.signal { + Some(EnvSignal::GithubAuth) => "Run gh auth login, then retry".to_owned(), + _ => "Check the project path and retry".to_owned(), + }; + return Err(refuse("init_failed", &next).with(json!({"stage": failure.stage}))); + } + }; + let source = if probe.github { + SourceKind::Github + } else { + SourceKind::Local + }; + let mut candidates = Vec::new(); + if probe.github { + candidates.push( + json!({"kind": "ci", "value": if probe.required_checks.is_empty() { + "(no required checks on the default branch)".to_owned() + } else { + probe.required_checks.join(", ") + }}), + ); + } + for command in &probe.verify_candidates { + candidates.push(json!({"kind": "verify", "value": command})); + } + let writes = self.ports.source.planned_writes(&probe); + let verification = match verification { + Some(VerificationChoice::Ci { checks }) => { + if !probe.github { + return Err(refuse( + "ci_unavailable", + "A project without GitHub verifies with --verify ", + )); + } + Verification::Ci { checks } + } + Some(VerificationChoice::Commands { commands }) => { + let commands: Vec = commands + .into_iter() + .filter(|c| !c.trim().is_empty()) + .collect(); + if commands.is_empty() { + return Err(refuse( + "verify_command_required", + "Give at least one --verify ", + )); + } + Verification::Commands { commands } + } + Some(VerificationChoice::None) => Verification::None, + None => Verification::None, + }; + let auto_unavailable = + (!verification.exists()).then_some("검증이 없으면 auto를 쓸 수 없습니다"); + let requested_mode = merge_mode.unwrap_or(if verification.exists() { + MergeMode::Auto + } else { + MergeMode::Manual + }); + if requested_mode == MergeMode::Auto && !verification.exists() { + return Err(refuse( + "auto_needs_verification", + "Choose --ci or --verify, or use --merge manual", + ) + .with(json!({"candidates": candidates}))); + } + if !confirm { + return Ok(json!({ + "preview": true, + "project": project, + "source": if probe.github { "github" } else { "local" }, + "candidates": candidates, + "merge_mode": "auto", + "auto_unavailable": auto_unavailable, + "writes": writes, + })); + } + if !matches!( + verification, + Verification::Ci { .. } | Verification::Commands { .. } | Verification::None + ) { + unreachable!(); + } + let id = format!("f-{}", &sha256_hex(project.as_bytes())[..10]); + let now = self.now(); + let mut config = Config { + verification, + merge_mode: requested_mode, + ..Config::default() + }; + if let Some(method) = probe.merge_methods.first() { + config.merge_method = *method; + } + let factory = Factory { + id: id.clone(), + project: project.clone(), + project_name: Path::new(&project) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| project.clone()), + source, + config, + closed: false, + created_at: now, + next_task: 1, + next_local_issue: 1, + main: MainHealth::default(), + outside_read_at: None, + outside_read_failures: 0, + watch_day: 0, + watch_sent_today: 0, + watch_last_at: None, + }; + if let Err(failure) = self.ports.source.prepare(&factory) { + return Err(self.github_refusal(&failure, "init")); + } + self.factories.insert(id.clone(), factory); + self.tasks.entry(id.clone()).or_default(); + self.save_factory(&id); + self.record( + &id, + None, + "factory.created", + json!({"source": source_name(source)}), + ); + Ok(json!({"created": true, "factory": {"id": id, "project": project}})) + } + + fn github_refusal(&mut self, failure: &Failure, stage: &str) -> Refusal { + match failure.signal { + Some(EnvSignal::GithubAuth) => { + refuse("github_login_required", "Run gh auth login, then retry") + .with(json!({"stage": stage})) + } + Some(EnvSignal::GithubForbidden) => { + let scope = failure + .missing_scope + .clone() + .unwrap_or_else(|| "repo".into()); + refuse( + "github_permission_missing", + &format!("Run gh auth refresh -s {scope}, then retry"), + ) + .with(json!({"stage": stage, "scope": scope})) + } + _ => refuse("github_unavailable", "Retry later").with(json!({"stage": stage})), + } + } + + // ---------------------------------------------------------------------- add + + fn validate_card( + &self, + factory: &str, + own: Option<&str>, + card: &CardInput, + existing: Option<&Card>, + ) -> Result { + let mut problems = Vec::new(); + let mut field = |name: &str, problem: &str| { + problems.push(json!({"field": name, "problem": problem})); + }; + let title = card + .title + .clone() + .or_else(|| existing.map(|c| c.title.clone())) + .unwrap_or_default(); + let goal = card + .goal + .clone() + .or_else(|| existing.map(|c| c.goal.clone())) + .unwrap_or_default(); + if title.trim().is_empty() { + field("title", "missing"); + } else if title.chars().count() > TITLE_LIMIT || title.contains('\n') { + field("title", "one line of at most 200 characters"); + } + if goal.trim().is_empty() { + field("goal", "missing"); + } else if goal.len() > TEXT_LIMIT { + field("goal", "too long"); + } + let criteria = if card.criteria.is_empty() { + existing.map(|c| c.criteria.clone()).unwrap_or_default() + } else { + card.criteria.clone() + }; + if criteria.iter().all(|c| c.trim().is_empty()) { + field("criteria", "at least one completion criterion"); + } + for (name, list) in [ + ("criteria", &criteria), + ("out_of_scope", &card.out_of_scope), + ("open_decisions", &card.open_decisions), + ("depends_on", &card.depends_on), + ("external", &card.external), + ] { + if list.len() > LIST_LIMIT { + field(name, "too many items"); + } + if list.iter().any(|item| item.len() > TEXT_LIMIT) { + field(name, "an item is too long"); + } + } + if let Some(priority) = card.priority + && !(-100..=100).contains(&priority) + { + field("priority", "between -100 and 100"); + } + let tasks = self.tasks.get(factory); + let mut depends = Vec::new(); + for reference in &card.depends_on { + let found = tasks.and_then(|tasks| { + tasks.values().find(|task| { + task.id == *reference + || task + .issue + .as_ref() + .is_some_and(|issue| issue.display() == *reference) + }) + }); + match found { + Some(task) if task.state == TaskState::Cancelled => { + field("depends_on", "a cancelled Task") + } + Some(task) => depends.push(task.id.clone()), + None => field( + "depends_on", + &format!("{reference} does not exist in this Factory"), + ), + } + } + if let Some(own) = own { + let mut edges = dag::edges(tasks.into_iter().flat_map(|t| t.values())); + edges.insert(own.to_owned(), BTreeSet::new()); + for on in &depends { + if let Some(path) = dag::cycle_with(&edges, own, on) { + field("depends_on", &format!("cycle: {}", path.join(" -> "))); + } + edges.entry(own.to_owned()).or_default().insert(on.clone()); + } + } else { + let mut seen = BTreeSet::new(); + for on in &depends { + if !seen.insert(on) { + field("depends_on", "listed twice"); + } + } + } + if !problems.is_empty() { + return Err( + refuse("card_invalid", "Fix the listed fields and add again") + .with(json!({"fields": problems})), + ); + } + Ok(Card { + title: title.trim().to_owned(), + goal: goal.trim().to_owned(), + criteria: criteria + .into_iter() + .filter(|c| !c.trim().is_empty()) + .collect(), + out_of_scope: if card.out_of_scope.is_empty() { + existing.map(|c| c.out_of_scope.clone()).unwrap_or_default() + } else { + card.out_of_scope.clone() + }, + open_decisions: card.open_decisions.clone(), + depends_on: depends, + external: card.external.clone(), + }) + } + + fn add( + &mut self, + role: &Role, + project: Option<&str>, + task_ref: Option<&str>, + issue: Option<&str>, + input: CardInput, + producer_pane: Option, + ) -> Reply { + // The Task named, or the one bound to the issue (B9, B14). + let existing = match (task_ref, issue) { + (Some(reference), _) => Some(self.resolve(role, reference)?), + (None, Some(issue)) => self + .all_tasks() + .find(|task| task.issue.as_ref().is_some_and(|i| i.display() == issue)) + .map(|task| (task.factory.clone(), task.id.clone())), + _ => None, + }; + let factory_id = match &existing { + Some((factory, _)) => factory.clone(), + None => self.factory_id(project)?, + }; + let factory = self.factories.get(&factory_id).cloned().ok_or_else(|| { + refuse( + "factory_not_found", + "Create one with hide factory init ", + ) + })?; + if factory.closed { + return Err(refuse( + "factory_closed", + "Reopen it with hide factory init --confirm", + )); + } + let now = self.now(); + if let Some((factory_id, id)) = existing { + return self.readd(&factory, &factory_id, &id, input, producer_pane, now); + } + // A new Task, possibly bound to an existing issue. + let issue_ref = match issue { + Some(text) => Some(parse_issue(text, factory.source).ok_or_else(|| { + refuse("issue_invalid", "Give an issue as # or L-") + })?), + None => None, + }; + let mut input = input; + if let Some(issue) = &issue_ref + && (input.title.is_none() || input.goal.is_none()) + { + match self.ports.source.read_issue(&factory, issue) { + Ok(text) => { + input.title.get_or_insert(text.title); + if input.goal.is_none() && !text.body.trim().is_empty() { + input.goal = Some(judgment::cut(&text.body, TEXT_LIMIT)); + } + } + Err(failure) => return Err(self.github_refusal(&failure, "read_issue")), + } + } + if self.tasks.get(&factory_id).map_or(0, BTreeMap::len) >= TASK_LIMIT { + return Err(refuse("capacity", "Cancel or finish Tasks first")); + } + let seq = factory.next_task; + let id = format!("T-{seq}"); + let card = self.validate_card(&factory_id, Some(&id), &input, None)?; + let mut task = Task { + factory: factory_id.clone(), + id: id.clone(), + seq, + issue: issue_ref, + card, + human: HumanFields { + review_directly: input.review_directly, + priority: input.priority.unwrap_or(0), + merge_mode: input.merge_mode, + runtime: input.runtime, + }, + state: TaskState::Drafting, + state_since: now, + created_at: now, + updated_at: now, + proposed_by: None, + autonomy: None, + attachments: Vec::new(), + questions: Vec::new(), + discoveries: Vec::new(), + decisions: Vec::new(), + flags: Vec::new(), + review: ReviewState::Pending, + producer_pane, + worker: None, + attempts: Vec::new(), + failures: 0, + environment_failures: 0, + pr: None, + merge_sha: None, + gates: Vec::new(), + stop: None, + breaking: false, + scope_approved: false, + new_tasks: 0, + new_task_cap_extended: false, + cancelled_at: None, + cancelled_from: None, + purged: false, + done_at: None, + seen: true, + last_report_at: None, + idle_since: None, + writes: BTreeSet::new(), + held: None, + label_path: false, + source_body_hash: None, + }; + if let Some(prd) = &input.prd { + let attachment = self + .store + .attach(&factory_id, &id, Path::new(prd), 1) + .map_err(|error| { + refuse("attachment_failed", "Check the PRD path") + .with(json!({"error": error.0})) + })?; + task.attachments.push(attachment); + } + if let Some(factory) = self.factories.get_mut(&factory_id) { + factory.next_task += 1; + } + self.save_factory(&factory_id); + self.tasks + .entry(factory_id.clone()) + .or_default() + .insert(id.clone(), task); + self.save(&factory_id, &id); + self.record(&factory_id, Some(&id), "task.added", json!({"via": "add"})); + for decision in input.open_decisions.iter().filter(|d| !d.trim().is_empty()) { + self.add_question( + &factory_id, + &id, + QuestionOrigin::Engine, + QuestionKind::Intake, + &format!("열린 결정: {decision}"), + "결정을 적어 주세요", + None, + None, + Vec::new(), + None, + ); + } + self.request_review(&factory_id, &id, now); + Ok(self.add_answer(&factory_id, &id)) + } + + fn readd( + &mut self, + factory: &Factory, + factory_id: &str, + id: &str, + input: CardInput, + producer_pane: Option, + now: UnixMs, + ) -> Reply { + let task = self + .task(factory_id, id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "Check hide factory status"))?; + if task.state == TaskState::Cancelled { + return Err(refuse( + "task_cancelled", + "Revive it first with hide factory revive", + )); + } + let card = self.validate_card(factory_id, Some(id), &input, Some(&task.card))?; + let attachment = match &input.prd { + Some(prd) => { + let version = task.attachments.last().map_or(1, |a| a.version + 1); + let attachment = self + .store + .attach(factory_id, id, Path::new(prd), version) + .map_err(|error| { + refuse("attachment_failed", "Check the PRD path") + .with(json!({"error": error.0})) + })?; + (task.attachments.last().map(|a| &a.sha256) != Some(&attachment.sha256)) + .then_some(attachment) + } + None => None, + }; + let unchanged = card == task.card && attachment.is_none(); + if task.state != TaskState::Drafting { + // Running work: a changed card or PRD is a scope change a person + // approves (B16); the same content changes nothing. + if unchanged { + return Ok(self.add_answer(factory_id, id)); + } + if let Some(attachment) = attachment { + self.with_task(factory_id, id, |task| { + task.flags.push(format!( + "pending PRD v{} {}", + attachment.version, attachment.sha256 + )); + }); + self.record( + factory_id, + Some(id), + "attachment.pending", + json!({"version": attachment.version}), + ); + } + self.add_question( + factory_id, + id, + QuestionOrigin::Engine, + QuestionKind::ScopeChange, + "실행 중에 카드나 PRD가 바뀌었습니다. 새 범위를 승인할까요?", + "approve", + Some("지금 범위로 진행".into()), + Some(now + factory.config.question_deadline_ms), + vec!["approve".into(), "reject".into()], + None, + ); + return Ok(self.add_answer(factory_id, id)); + } + if unchanged && matches!(task.review, ReviewState::Done { .. }) { + return Ok(self.add_answer(factory_id, id)); + } + self.with_task(factory_id, id, |task| { + task.card = card; + if let Some(attachment) = attachment { + task.attachments.push(attachment); + } + if let Some(priority) = input.priority { + task.human.priority = priority; + } + task.human.review_directly |= input.review_directly; + if input.merge_mode.is_some() { + task.human.merge_mode = input.merge_mode; + } + if input.runtime.is_some() { + task.human.runtime = input.runtime; + } + if producer_pane.is_some() { + task.producer_pane = producer_pane; + } + // The producer handled the review's questions in its + // conversation; the new card is reviewed again (B9). + for question in task.questions.iter_mut().filter(|q| q.open()) { + if matches!(question.origin, QuestionOrigin::Review) + || matches!( + question.kind, + QuestionKind::Intake | QuestionKind::Split { .. } + ) + { + question.answer = Some(Answer { + text: "card updated".into(), + chose: None, + relayed_by: "re-add".into(), + at: now, + }); + } + } + task.review = ReviewState::Pending; + }); + for decision in input.open_decisions.iter().filter(|d| !d.trim().is_empty()) { + self.add_question( + factory_id, + id, + QuestionOrigin::Engine, + QuestionKind::Intake, + &format!("열린 결정: {decision}"), + "결정을 적어 주세요", + None, + None, + Vec::new(), + None, + ); + } + self.record(factory_id, Some(id), "task.updated", json!({"via": "add"})); + self.request_review(factory_id, id, now); + Ok(self.add_answer(factory_id, id)) + } + + /// What `add` answers now: ready, needs_answers, split, or pending while + /// the review runs (the daemon waits up to 90 s for a final answer). + pub fn add_answer(&self, factory: &str, id: &str) -> Value { + let Some(task) = self.task(factory, id) else { + return Refusal::new("task_not_found", "Check hide factory status").to_json(); + }; + let result = match (&task.review, task.state) { + (_, state) if state != TaskState::Drafting => "ready", + ( + ReviewState::Done { + result: ReviewResult::Split, + }, + _, + ) => "split", + (ReviewState::Done { .. }, _) + if task + .open_questions() + .any(|q| !matches!(q.kind, QuestionKind::Notice)) => + { + "needs_answers" + } + (ReviewState::Done { .. }, _) => "ready", + _ => "pending", + }; + let questions: Vec = task + .open_questions() + .filter(|q| !matches!(q.kind, QuestionKind::Notice)) + .map( + |q| json!({"id": q.id, "text": q.text, "suggestion": q.suggestion, "kind": q.kind}), + ) + .collect(); + json!({ + "ok": true, + "result": result, + "task": {"id": task.id, "display_id": task.display_id(), "title": task.card.title, "state": task.state.as_str()}, + "questions": questions, + }) + } + + pub fn review_settled(&self, factory: &str, id: &str) -> bool { + self.task(factory, id).is_none_or(|task| { + !matches!( + task.review, + ReviewState::Pending | ReviewState::Requested { .. } + ) + }) + } + + fn request_review(&mut self, factory: &str, id: &str, now: UnixMs) { + let Some(task) = self.task(factory, id).cloned() else { + return; + }; + let attachment = task + .attachments + .last() + .and_then(|a| std::fs::read_to_string(&a.path).ok()); + let other_tasks = self + .tasks_of(factory) + .filter(|other| other.id != id && other.state != TaskState::Cancelled) + .take(100) + .map(|other| OtherTask { + id: other.id.clone(), + title: other.card.title.clone(), + goal: judgment::cut(&other.card.goal, 400), + state: other.state.as_str().to_owned(), + }) + .collect(); + let project = self + .factories + .get(factory) + .map(|f| f.project.clone()) + .unwrap_or_default(); + let (repo_files, guide) = repo_context(&project); + let judgment_id = format!( + "{factory}:{id}:intake:{}", + sha256_hex( + serde_json::to_string(&task.card) + .unwrap_or_default() + .as_bytes() + ) + .get(..12) + .unwrap_or("") + ); + let mut checks = Vec::new(); + if let Some(f) = self.factories.get(factory) { + for check in f + .config + .checks + .iter() + .filter(|c| c.at == CheckPoint::Intake) + { + checks.push(check.instruction.clone()); + } + } + let judgment = Judgment { + id: judgment_id.clone(), + factory: factory.to_owned(), + task: Some(id.to_owned()), + priority: Priority::Intake, + input: JudgmentInput::IntakeReview { + card: task.card.clone(), + attachment, + other_tasks, + repo_files, + guide, + }, + }; + self.with_task(factory, id, |task| { + task.review = ReviewState::Requested { at: now } + }); + match self.ports.judge.submit(judgment) { + Ok(()) => { + self.judgments.insert( + judgment_id, + (factory.to_owned(), Some(id.to_owned()), Purpose::Intake), + ); + } + Err(failure) => self.review_failed(factory, id, &failure.detail), + } + for (index, instruction) in checks.into_iter().enumerate() { + let check_id = format!("{factory}:{id}:intake-check:{index}:{now}"); + let judgment = Judgment { + id: check_id.clone(), + factory: factory.to_owned(), + task: Some(id.to_owned()), + priority: Priority::Factory, + input: JudgmentInput::Check { + instruction, + card: task.card.clone(), + diff: None, + }, + }; + if self.ports.judge.submit(judgment).is_ok() { + self.judgments.insert( + check_id, + (factory.to_owned(), Some(id.to_owned()), Purpose::Check), + ); + } + } + } + + /// The review could not run: never skipped and never ready (B19). + fn review_failed(&mut self, factory: &str, id: &str, reason: &str) { + self.with_task(factory, id, |task| { + task.review = ReviewState::Failed { + reason: reason.to_owned(), + } + }); + self.record( + factory, + Some(id), + "review.failed", + json!({"reason": reason}), + ); + let already = self.task(factory, id).is_some_and(|task| { + task.open_questions() + .any(|q| q.text.starts_with("검토를 하지 못했습니다")) + }); + if !already { + self.add_question( + factory, + id, + QuestionOrigin::Engine, + QuestionKind::Action, + "검토를 하지 못했습니다. Settings › Background AI에서 provider를 고친 뒤 다시 검토하세요.", + "retry-review", + None, + None, + vec!["retry-review".into(), "cancel".into()], + None, + ); + } + self.pending_to_producer(factory, id); + } + + fn pending_to_producer(&mut self, factory: &str, id: &str) { + let Some(task) = self.task(factory, id) else { + return; + }; + let Some(pane) = task.producer_pane.clone() else { + return; + }; + let answer = self.add_answer(factory, id); + let body = format!( + "Factory review of {}: {}", + answer["task"]["display_id"].as_str().unwrap_or(id), + answer["result"].as_str().unwrap_or("pending") + ); + if !self.ports.notifier.producer(&pane, &body) { + self.with_task(factory, id, |task| task.producer_pane = None); + } + } + + fn apply_intake(&mut self, factory: &str, id: &str, value: &Value) { + let verdict = match judgment::parse_intake(value) { + Ok(verdict) => verdict, + Err(reason) => return self.review_failed(factory, id, &reason), + }; + let result = verdict.result(); + let now = self.now(); + // The review only adds (D-02, B8): questions, dependencies, flags. + for question in &verdict.questions { + self.add_question( + factory, + id, + QuestionOrigin::Review, + QuestionKind::Intake, + &question.text, + &question.suggestion, + question.default_action.clone(), + None, + Vec::new(), + None, + ); + } + let candidates: Vec = verdict + .dependencies + .iter() + .filter_map(|reference| { + self.tasks_of(factory) + .find(|task| { + task.id == *reference + || task + .issue + .as_ref() + .is_some_and(|i| i.display() == *reference) + }) + .filter(|task| task.id != id && task.state != TaskState::Cancelled) + .map(|task| task.id.clone()) + }) + .collect(); + for on in candidates { + let edges = dag::edges(self.tasks_of(factory)); + if dag::cycle_with(&edges, id, &on).is_some() { + self.record( + factory, + Some(id), + "review.dependency_refused", + json!({"on": on, "reason": "cycle"}), + ); + continue; + } + self.with_task(factory, id, |task| { + if !task.card.depends_on.contains(&on) { + task.card.depends_on.push(on.clone()); + } + }); + } + if !verdict.split.is_empty() { + self.add_question( + factory, + id, + QuestionOrigin::Review, + QuestionKind::Split { + pieces: verdict.split.clone(), + }, + &format!("이 Task를 {}개로 쪼갤까요?", verdict.split.len()), + "split", + None, + None, + vec!["split".into(), "proceed".into()], + None, + ); + } + self.with_task(factory, id, |task| { + task.flags.extend(verdict.flags.iter().cloned()); + task.review = ReviewState::Done { result }; + }); + self.record( + factory, + Some(id), + "review.done", + json!({"result": format!("{result:?}"), "at": now}), + ); + self.maybe_ready(factory, id); + self.pending_to_producer(factory, id); + } + + /// Drafting -> Waiting when the review is done and nothing is open (B12). + fn maybe_ready(&mut self, factory_id: &str, id: &str) { + let Some(task) = self.task(factory_id, id).cloned() else { + return; + }; + if task.state != TaskState::Drafting + || !matches!(task.review, ReviewState::Done { .. }) + || task + .open_questions() + .any(|q| !matches!(q.kind, QuestionKind::Notice)) + { + return; + } + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + // Ready creates the issue (B13); a Task added from an issue gets the label. + let key = "issue"; + if task.issue.is_none() { + if !task.writes.contains(key) { + self.with_task(factory_id, id, |task| { + task.writes.insert(key.to_owned()); + }); + } + let body = issue_body(&task, &factory); + match self.ports.source.create_issue(&factory, &task, &body) { + Ok(issue) => { + self.record( + factory_id, + Some(id), + "github.issue_created", + json!({"issue": issue.display()}), + ); + if let IssueRef::Local { number } = issue + && let Some(f) = self.factories.get_mut(factory_id) + { + f.next_local_issue = f.next_local_issue.max(number + 1); + } + self.save_factory(factory_id); + self.with_task(factory_id, id, |task| task.issue = Some(issue)); + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + return; + } + } + } else if factory.source == SourceKind::Github && !task.writes.contains("label") { + let issue = task.issue.clone().unwrap_or(IssueRef::Github { number: 0 }); + match self.ports.source.label_issue(&factory, &issue) { + Ok(()) => { + self.with_task(factory_id, id, |task| { + task.writes.insert("label".into()); + }); + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + return; + } + } + } + self.set_state(factory_id, id, TaskState::Waiting); + } + + // ------------------------------------------------------------------- answer + + fn answer( + &mut self, + role: &Role, + factory: &str, + id: &str, + question: Option<&str>, + choice: Option, + text: Option, + ) -> Reply { + let task = self + .task(factory, id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "Check hide factory status"))?; + let open: Vec<&Question> = task.open_questions().collect(); + let target = match question { + Some(qid) => open.iter().find(|q| q.id == qid).copied(), + None => open.first().copied(), + }; + let Some(target) = target.cloned() else { + return Err(refuse( + "no_open_question", + "This Task has no open question with that id", + ) + .with(json!({"state": task.state.label(), "allowed": Self::allowed_actions(&task)}))); + }; + let chosen = match choice.as_deref() { + Some("suggestion") => Some(target.suggestion.clone()), + Some("default") => target.default_action.clone(), + Some(other) => Some(other.to_owned()), + None => None, + }; + let text = text.or_else(|| chosen.clone()).unwrap_or_default(); + if text.trim().is_empty() { + return Err(refuse( + "answer_required", + "Pass --choose suggestion|default| or --text", + )); + } + if !target.choices.is_empty() + && let Some(choice) = &chosen + && !target.choices.contains(choice) + && choice != &target.suggestion + && Some(choice) != target.default_action.as_ref() + { + return Err(refuse("choice_invalid", "Choose one of the listed choices") + .with(json!({"allowed": target.choices}))); + } + let now = self.now(); + let relayed_by = role.relayed_by(); + let answer = Answer { + text: judgment::cut(&text, TEXT_LIMIT), + chose: chosen.clone(), + relayed_by: relayed_by.clone(), + at: now, + }; + self.with_task(factory, id, |task| { + if let Some(question) = task.questions.iter_mut().find(|q| q.id == target.id) { + question.answer = Some(answer.clone()); + } + task.decisions.push(DecisionRecord { + text: format!("{} -> {}", judgment::cut(&target.text, 200), answer.text), + by: relayed_by.clone(), + at: now, + }); + }); + self.record( + factory, + Some(id), + "question.answered", + json!({"question": target.id, "by": relayed_by}), + ); + let decision = chosen.as_deref().unwrap_or(text.as_str()).to_owned(); + match &target.kind { + QuestionKind::ConfirmCard if decision == "cancel" => self.cancel(factory, id), + QuestionKind::Intake | QuestionKind::ConfirmCard => self.maybe_ready(factory, id), + QuestionKind::Split { pieces } => { + if decision == "split" || decision == target.suggestion { + self.split(factory, id, pieces.clone()); + } else { + self.with_task(factory, id, |task| { + task.flags.retain(|flag| flag != "split") + }); + self.maybe_ready(factory, id); + } + } + QuestionKind::Default => { + if Some(&decision) != target.default_action.as_ref() { + let body = format!( + "Factory: 사람이 기본 행동과 다르게 답했습니다: {text}\n이 답을 반영한 뒤 다시 hide factory done 하세요." + ); + let finished = self.task(factory, id).is_some_and(|t| { + matches!(t.state, TaskState::Verifying | TaskState::MergeWaiting) + }); + if finished { + // The worker reported done; the answer sends it back. + self.cancel_verification(factory, id); + self.set_state(factory, id, TaskState::Running); + self.wake(factory, id, &body); + } else { + self.reply(factory, id, target.letter.as_deref(), &body); + } + } + self.advance_merge(factory, id); + } + QuestionKind::ScopeChange => { + let approved = decision == "approve"; + self.with_task(factory, id, |task| { + if approved { + task.scope_approved = true; + if let Some(flag) = + task.flags.iter().position(|f| f.starts_with("pending PRD")) + { + task.flags.remove(flag); + } + } + }); + self.reply(factory, id, target.letter.as_deref(), &if approved { + format!("Factory: 범위 변경이 승인되었습니다. {text}") + } else { + format!("Factory: 범위 변경은 승인되지 않았습니다. 지금 범위 안에서 진행하세요. {text}") + }); + self.advance_merge(factory, id); + } + QuestionKind::Blocking => { + self.reply( + factory, + id, + target.letter.as_deref(), + &format!("Factory: 답이 왔습니다: {text}\n이어서 진행하세요."), + ); + if task.state == TaskState::Blocked + && task + .open_questions() + .filter(|q| matches!(q.kind, QuestionKind::Blocking)) + .count() + <= 1 + { + // Waits for a slot like any start, then wakes the same session (B27). + self.set_state(factory, id, TaskState::Waiting); + } + } + QuestionKind::NewTaskCap => { + match decision.as_str() { + "continue" => { + self.with_task(factory, id, |task| task.new_task_cap_extended = true); + self.set_state(factory, id, TaskState::Waiting); + } + _ => { + self.notice(factory, id, "새 Task를 더 만들지 않고 멈춘 상태로 둡니다. 다시 시도하거나 취소하세요."); + } + } + } + QuestionKind::ProposedTask { draft } => { + if decision == "approve" { + let new_id = self.create_child(factory, id, (**draft).clone(), None); + self.record( + factory, + Some(id), + "proposal.approved", + json!({"task": new_id}), + ); + } + } + QuestionKind::Action => match decision.as_str() { + "retry-review" => { + self.with_task(factory, id, |task| task.review = ReviewState::Pending); + self.request_review(factory, id, now); + } + "retry" if task.state == TaskState::Stopped => { + self.set_state(factory, id, TaskState::Waiting); + } + "cancel" => self.cancel(factory, id), + "resume-auto" => { + if let Some(f) = self.factories.get_mut(factory) { + f.main.broken = false; + f.main.needs_person = false; + f.main.reason = None; + } + self.save_factory(factory); + } + "retry-revert" => { + if let Some(f) = self.factories.get_mut(factory) { + f.main.needs_person = false; + } + self.reverts.remove(factory); + self.save_factory(factory); + } + other if other.starts_with("revert ") => { + let target_task = other.trim_start_matches("revert ").to_owned(); + if let Some(f) = self.factories.get_mut(factory) { + f.main.needs_person = false; + } + self.save_factory(factory); + self.start_revert(factory, &target_task); + } + _ => {} + }, + QuestionKind::Proposal { .. } => { + // A person runs a proposed command themselves; the Factory + // runs only its typed recovery actions (D-54). + self.record( + factory, + Some(id), + "proposal.answered", + json!({"decision": decision}), + ); + } + QuestionKind::Notice => { + if task.state == TaskState::Done { + self.with_task(factory, id, |task| task.seen = true); + } + } + } + Ok(self.task_answer(factory, id, "answered")) + } + + fn split(&mut self, factory: &str, id: &str, pieces: Vec) { + let Some(first) = pieces.first().cloned() else { + return; + }; + // The original becomes the first piece and keeps its issue (D-55). + self.with_task(factory, id, |task| { + task.card.title = first.title.clone(); + task.card.goal = first.goal.clone(); + task.card.criteria = first.criteria.clone(); + task.review = ReviewState::Pending; + }); + let mut ids = vec![id.to_owned()]; + for piece in pieces.iter().skip(1) { + let mut depends: Vec = piece + .after + .iter() + .filter_map(|index| ids.get(*index).cloned()) + .collect(); + if depends.is_empty() { + depends.push(id.to_owned()); + } + let card = Card { + title: piece.title.clone(), + goal: piece.goal.clone(), + criteria: piece.criteria.clone(), + out_of_scope: Vec::new(), + open_decisions: Vec::new(), + depends_on: depends, + external: Vec::new(), + }; + let new_id = self.new_task(factory, card, None, None); + ids.push(new_id.clone()); + let now = self.now(); + self.request_review(factory, &new_id, now); + } + let now = self.now(); + self.request_review(factory, id, now); + } + + fn new_task( + &mut self, + factory: &str, + card: Card, + proposed_by: Option, + autonomy: Option, + ) -> String { + let now = self.now(); + let seq = self.factories.get(factory).map_or(1, |f| f.next_task); + let id = format!("T-{seq}"); + if let Some(f) = self.factories.get_mut(factory) { + f.next_task += 1; + } + self.save_factory(factory); + let task = Task { + factory: factory.to_owned(), + id: id.clone(), + seq, + issue: None, + card, + human: HumanFields::default(), + state: TaskState::Drafting, + state_since: now, + created_at: now, + updated_at: now, + proposed_by, + autonomy, + attachments: Vec::new(), + questions: Vec::new(), + discoveries: Vec::new(), + decisions: Vec::new(), + flags: Vec::new(), + review: ReviewState::Pending, + producer_pane: None, + worker: None, + attempts: Vec::new(), + failures: 0, + environment_failures: 0, + pr: None, + merge_sha: None, + gates: Vec::new(), + stop: None, + breaking: false, + scope_approved: false, + new_tasks: 0, + new_task_cap_extended: false, + cancelled_at: None, + cancelled_from: None, + purged: false, + done_at: None, + seen: true, + last_report_at: None, + idle_since: None, + writes: BTreeSet::new(), + held: None, + label_path: false, + source_body_hash: None, + }; + self.tasks + .entry(factory.to_owned()) + .or_default() + .insert(id.clone(), task); + self.save(factory, &id); + self.record(factory, Some(&id), "task.added", json!({"via": "engine"})); + id + } + + fn create_child( + &mut self, + factory: &str, + parent: &str, + card: Card, + autonomy: Option, + ) -> String { + let id = self.new_task(factory, card, Some(parent.to_owned()), autonomy); + let now = self.now(); + self.request_review(factory, &id, now); + id + } + + // ---------------------------------------------------------- worker reports + + #[allow(clippy::too_many_arguments)] + fn ask( + &mut self, + factory: &str, + id: &str, + text: &str, + suggestion: &str, + default_action: Option, + deadline_hours: Option, + letter: Option, + ) -> Reply { + let task = self + .task(factory, id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "Check hide factory status"))?; + if text.trim().is_empty() { + return Err(refuse("question_required", "Give --question")); + } + // A question must carry a suggestion and a deadline (B28). + if suggestion.trim().is_empty() { + return Err(refuse( + "suggestion_required", + "Give --suggestion with what you propose", + )); + } + let Some(hours) = deadline_hours.filter(|h| *h > 0 && *h <= 24 * 30) else { + return Err(refuse( + "deadline_required", + "Give --deadline-hours (the Factory default is 24)", + )); + }; + if default_action.as_ref().is_some_and(|d| d.trim().is_empty()) { + return Err(refuse( + "default_required", + "Give --default with the action you take meanwhile", + )); + } + if !matches!(task.state, TaskState::Running | TaskState::Relanding) { + return Err(refuse( + "action_not_allowed_in_state", + "A worker asks while its Task runs", + ) + .with(json!({"state": task.state.label()}))); + } + let now = self.now(); + let deadline = now + hours * HOUR_MS; + let blocking = default_action.is_none(); + let question = self.add_question( + factory, + id, + QuestionOrigin::Worker, + if blocking { + QuestionKind::Blocking + } else { + QuestionKind::Default + }, + text, + suggestion, + default_action.clone(), + Some(deadline), + Vec::new(), + letter, + ); + self.with_task(factory, id, |task| task.last_report_at = Some(now)); + if blocking { + // A question it cannot work past releases the slot and sleeps (B27). + self.put_to_sleep(factory, id); + self.set_state(factory, id, TaskState::Blocked); + return Ok( + json!({"message": "blocked: the Task waits for the answer; your session is woken with it", "question": question}), + ); + } + Ok(json!({ + "message": format!("continue with the default action: {}", default_action.unwrap_or_default()), + "question": question, + })) + } + + #[allow(clippy::too_many_arguments)] + fn propose( + &mut self, + factory: &str, + id: &str, + class: DiscoveryClass, + text: &str, + card: Option, + autonomy: Option, + reclassify: Option, + letter: Option, + ) -> Reply { + let task = self + .task(factory, id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "Check hide factory status"))?; + if text.trim().is_empty() { + return Err(refuse("text_required", "Give --text")); + } + let now = self.now(); + if let Some(previous) = reclassify { + let Some(discovery) = task.discoveries.iter().find(|d| d.id == previous) else { + return Err(refuse( + "discovery_not_found", + "Name a discovery of this Task", + )); + }; + // Only toward a person (B30). + if class.toward_person() < discovery.class.toward_person() { + return Err(refuse( + "reclassify_away_from_person", + "A discovery may only move toward a person", + ) + .with( + json!({"from": format!("{:?}", discovery.class), "to": format!("{class:?}")}), + )); + } + } + let discovery_id = format!("D{}", task.discoveries.len() + 1); + self.with_task(factory, id, |task| { + task.discoveries.push(Discovery { + id: discovery_id.clone(), + class, + text: judgment::cut(text, TEXT_LIMIT), + at: now, + task: None, + }); + task.last_report_at = Some(now); + }); + let deadline = self + .factories + .get(factory) + .map_or(24 * HOUR_MS, |f| f.config.question_deadline_ms); + match class { + DiscoveryClass::InScope => { + Ok(json!({"message": "recorded", "discovery": discovery_id})) + } + DiscoveryClass::Decision => { + self.with_task(factory, id, |task| { + task.decisions.push(DecisionRecord { + text: judgment::cut(text, TEXT_LIMIT), + by: format!("worker:{id}"), + at: now, + }) + }); + Ok(json!({"message": "decision recorded", "discovery": discovery_id})) + } + DiscoveryClass::ScopeChange => { + let question = self.add_question( + factory, + id, + QuestionOrigin::Worker, + QuestionKind::ScopeChange, + &format!("범위 변경: {text}"), + "approve", + Some("범위를 넓히지 않고 진행".into()), + Some(now + deadline), + vec!["approve".into(), "reject".into()], + letter, + ); + Ok( + json!({"message": "continue within the current scope; a person decides the wider scope", "question": question}), + ) + } + DiscoveryClass::Unrelated => { + self.notice(factory, id, &format!("무관한 발견: {text}")); + Ok(json!({"message": "sent to the person's inbox", "discovery": discovery_id})) + } + DiscoveryClass::Prerequisite => { + // Depth 1: a Task a worker proposed cannot propose (B30). + if task.proposed_by.is_some() || task.autonomy.is_some() { + return Err(refuse( + "proposal_depth_exceeded", + "Report it as a scope change or an unrelated finding instead", + )); + } + let input = card.unwrap_or_default(); + let draft = self.validate_card(factory, None, &input, None)?; + let limit = self + .factories + .get(factory) + .map_or(3, |f| f.config.new_task_limit); + if task.new_tasks >= limit && !task.new_task_cap_extended { + return Err(refuse( + "new_task_limit", + "A person decides whether this Task may create more", + )); + } + let enabled = autonomy.as_ref().and_then(|scope| { + self.factories.get(factory).and_then(|f| { + f.config + .autonomy + .iter() + .find(|s| s.id == *scope && s.enabled) + .map(|s| s.id.clone()) + }) + }); + let (created, message) = match enabled { + Some(scope) => { + let new_id = self.create_child(factory, id, draft, Some(scope)); + ( + Some(new_id), + "a new Task starts on its own within the enabled autonomy scope", + ) + } + None => { + self.add_question( + factory, + id, + QuestionOrigin::Worker, + QuestionKind::ProposedTask { + draft: Box::new(draft.clone()), + }, + &format!("새 Task 제안: {}", draft.title), + "approve", + None, + None, + vec!["approve".into(), "reject".into()], + letter, + ); + (None, "proposed; a person approves before it is drafted") + } + }; + self.with_task(factory, id, |task| { + task.new_tasks += 1; + if let Some(new_id) = &created { + if let Some(discovery) = + task.discoveries.iter_mut().find(|d| d.id == discovery_id) + { + discovery.task = Some(new_id.clone()); + } + // The current Task waits on the prerequisite (D-16 ④). + task.card.depends_on.push(new_id.clone()); + } + }); + if created.is_some() { + self.put_to_sleep(factory, id); + self.set_state(factory, id, TaskState::Blocked); + } + let reached = self + .task(factory, id) + .is_some_and(|t| t.new_tasks >= limit && !t.new_task_cap_extended); + if reached { + self.put_to_sleep(factory, id); + self.with_task(factory, id, |task| task.stop = Some(StopReason::NewTaskCap)); + self.set_state(factory, id, TaskState::Stopped); + self.with_task(factory, id, |task| task.stop = Some(StopReason::NewTaskCap)); + self.add_question( + factory, + id, + QuestionOrigin::Engine, + QuestionKind::NewTaskCap, + &format!( + "새 Task가 {limit}개 생겼습니다. 쪼갤까요 / 계속할까요 / 멈출까요" + ), + "split", + None, + None, + vec!["split".into(), "continue".into(), "stop".into()], + None, + ); + } + Ok(json!({"message": message, "task": created, "discovery": discovery_id})) + } + } + } + + fn done( + &mut self, + factory_id: &str, + id: &str, + summary_text: Option, + breaking: bool, + letter: Option, + ) -> Reply { + let task = self + .task(factory_id, id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "Check hide factory status"))?; + if !matches!(task.state, TaskState::Running | TaskState::Relanding) { + return Err(refuse( + "action_not_allowed_in_state", + "done is reported while the Task runs", + ) + .with(json!({"state": task.state.label()}))); + } + let now = self.now(); + let factory = self + .factories + .get(factory_id) + .cloned() + .ok_or_else(|| refuse("factory_not_found", "?"))?; + self.with_task(factory_id, id, |task| { + task.last_report_at = Some(now); + task.breaking |= breaking; + if let Some(text) = &summary_text { + task.decisions.push(DecisionRecord { + text: format!("done: {}", judgment::cut(text, TEXT_LIMIT)), + by: format!("worker:{id}"), + at: now, + }); + } + task.gates.clear(); + }); + let _ = letter; + self.put_to_sleep(factory_id, id); + // B36: a pull request for a GitHub Factory before CI is read. + if factory.source == SourceKind::Github && task.pr.is_none() { + let body = pr_body(&task, &factory); + match self.ports.merge.open_pr(&factory, &task, &body) { + Ok(pr) => { + self.with_task(factory_id, id, |task| { + task.pr = pr; + task.writes.insert("pr".into()); + }); + self.record(factory_id, Some(id), "github.pr_opened", json!({})); + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + } + } + } + self.set_state(factory_id, id, TaskState::Verifying); + self.start_checks(factory_id, id); + if !factory.config.verification.exists() { + // No verification: straight to merge waiting (B2, B35). + self.advance_merge(factory_id, id); + return Ok( + json!({"message": "검증 없음: 머지 대기로 갑니다", "state": "merge_waiting"}), + ); + } + self.start_verification(factory_id, id, AttemptStage::Task); + Ok( + json!({"message": "검증 중: 결과는 편지로 갑니다. 지금은 차례를 끝내세요.", "state": "verifying"}), + ) + } + + fn start_checks(&mut self, factory: &str, id: &str) { + let Some(task) = self.task(factory, id).cloned() else { + return; + }; + let Some(f) = self.factories.get(factory).cloned() else { + return; + }; + let diff = self.ports.merge.diff_text(&f, &task).unwrap_or_default(); + let mut count = 0; + let decisions = task.decisions.iter().map(|d| d.text.clone()).collect(); + let attempt = task.attempts.len(); + let drift = Judgment { + id: format!("{factory}:{id}:drift:{attempt}"), + factory: factory.to_owned(), + task: Some(id.to_owned()), + priority: Priority::Factory, + input: JudgmentInput::Drift { + card: task.card.clone(), + diff: diff.clone(), + decisions, + }, + }; + match self.ports.judge.submit(drift.clone()) { + Ok(()) => { + self.judgments.insert( + drift.id, + (factory.to_owned(), Some(id.to_owned()), Purpose::Drift), + ); + count += 1; + } + Err(_) => self.check_failed(factory, id), + } + for (index, check) in f + .config + .checks + .iter() + .filter(|c| c.at == CheckPoint::AfterDone) + .enumerate() + { + let judgment = Judgment { + id: format!("{factory}:{id}:check:{index}:{attempt}"), + factory: factory.to_owned(), + task: Some(id.to_owned()), + priority: Priority::Factory, + input: JudgmentInput::Check { + instruction: check.instruction.clone(), + card: task.card.clone(), + diff: Some(diff.clone()), + }, + }; + match self.ports.judge.submit(judgment.clone()) { + Ok(()) => { + self.judgments.insert( + judgment.id, + (factory.to_owned(), Some(id.to_owned()), Purpose::Check), + ); + count += 1; + } + Err(_) => self.check_failed(factory, id), + } + } + self.checks_running + .insert((factory.to_owned(), id.to_owned()), count); + } + + /// A check that could not run is never skipped: merge waits for a person (B68). + fn check_failed(&mut self, factory: &str, id: &str) { + self.with_task(factory, id, |task| { + if !task.gates.contains(&Gate::CheckFailed) { + task.gates.push(Gate::CheckFailed); + } + }); + self.record(factory, Some(id), "check.failed", json!({})); + } + + fn apply_finding(&mut self, factory: &str, id: &str, value: &Value) { + let finding = match judgment::parse_finding(value) { + Ok(finding) => finding, + Err(_) => return self.check_failed(factory, id), + }; + let now = self.now(); + let deadline = self + .factories + .get(factory) + .map_or(24 * HOUR_MS, |f| f.config.question_deadline_ms); + for question in &finding.questions { + // The Task stays verifying; the worker is not woken (D-44). + self.add_question( + factory, + id, + QuestionOrigin::Check, + QuestionKind::Default, + &question.text, + &question.suggestion, + question.default_action.clone(), + Some(now + deadline), + Vec::new(), + None, + ); + } + self.with_task(factory, id, |task| { + for flag in &finding.flags { + if flag.to_lowercase().contains("breaking") || flag.contains("contract") { + task.breaking = true; + } + task.flags.push(flag.clone()); + } + }); + } + + // ------------------------------------------------------------ verification + + fn start_verification(&mut self, factory_id: &str, id: &str, stage: AttemptStage) { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + let Some(task) = self.task(factory_id, id).cloned() else { + return; + }; + let started = match stage { + AttemptStage::Task => self.ports.verifier.start(&factory, &task), + AttemptStage::PreMerge => self.ports.verifier.start_premerge(&factory, &task), + }; + let now = self.now(); + let number = task.failures + 1; + match started { + Ok(run) => { + self.with_task(factory_id, id, |task| { + task.attempts.push(Attempt { + number, + commit: None, + started_at: now, + stage, + outcome: None, + log: run.log.clone(), + }); + }); + self.record( + factory_id, + Some(id), + "verify.started", + json!({"stage": format!("{stage:?}"), "attempt": number}), + ); + self.verifying.insert( + (factory_id.to_owned(), id.to_owned()), + VerifyState { run, stage }, + ); + } + Err(failure) => self.verification_environment(factory_id, id, &failure, "start"), + } + } + + fn restart_verification(&mut self, factory: &str, id: &str) { + let stage = self + .task(factory, id) + .and_then(|task| task.attempts.last()) + .filter(|attempt| attempt.outcome.is_none()) + .map(|attempt| attempt.stage); + if let Some(stage) = stage { + self.with_task(factory, id, |task| { + task.attempts.pop(); + }); + self.start_verification(factory, id, stage); + } + self.start_checks(factory, id); + } + + fn cancel_verification(&mut self, factory: &str, id: &str) { + if let Some(state) = self.verifying.remove(&(factory.to_owned(), id.to_owned())) { + self.ports.verifier.cancel(&state.run); + } + } + + fn poll_verifications(&mut self) { + let keys: Vec<(String, String)> = self.verifying.keys().cloned().collect(); + for (factory_id, id) in keys { + let Some(factory) = self.factories.get(&factory_id).cloned() else { + continue; + }; + let Some(state) = self.verifying.get(&(factory_id.clone(), id.clone())) else { + continue; + }; + let stage = state.stage; + let poll = self.ports.verifier.poll(&factory, &state.run); + let outcome = match poll { + VerifyPoll::Pending => continue, + VerifyPoll::Passed => AttemptOutcome::Passed, + VerifyPoll::Failed { check, link } => AttemptOutcome::Failed { check, link }, + VerifyPoll::Environment { signal, check } => AttemptOutcome::Environment { + signal: signal.as_str().into(), + check, + }, + }; + self.verifying.remove(&(factory_id.clone(), id.clone())); + self.with_task(&factory_id, &id, |task| { + if let Some(attempt) = task.attempts.last_mut() { + attempt.outcome = Some(outcome.clone()); + } + }); + self.record( + &factory_id, + Some(&id), + "verify.finished", + json!({"stage": format!("{stage:?}"), "outcome": outcome}), + ); + match outcome { + AttemptOutcome::Passed => { + self.with_task(&factory_id, &id, |task| task.environment_failures = 0); + if stage == AttemptStage::PreMerge { + self.with_task(&factory_id, &id, |task| { + task.writes.insert("premerge_passed".into()); + }); + } + self.advance_merge(&factory_id, &id); + } + AttemptOutcome::Failed { check, link } => { + self.verification_failed(&factory_id, &id, &check, &link) + } + AttemptOutcome::Environment { signal, check } => { + let signal = parse_signal(&signal).unwrap_or(EnvSignal::Network); + let failure = Failure::environment(&check, signal, "verification"); + self.verification_environment(&factory_id, &id, &failure, &check); + } + } + } + } + + /// One failure is a failure; nothing runs again (D-23, B37). + fn verification_failed(&mut self, factory: &str, id: &str, check: &str, link: &str) { + let limit = self + .factories + .get(factory) + .map_or(3, |f| f.config.verify_failure_limit); + let now = self.now(); + self.with_task(factory, id, |task| { + task.failures += 1; + task.environment_failures = 0; + task.writes.remove("premerge_passed"); + }); + let failures = self.task(factory, id).map_or(0, |t| t.failures); + self.cascade_note(factory, id, check, now); + if self.reclassified_by_cascade(factory, id) { + return; + } + if failures >= limit { + let last = self + .task(factory, id) + .and_then(|t| { + t.decisions + .iter() + .rev() + .find(|d| d.text.starts_with("done:")) + .map(|d| d.text.clone()) + }) + .unwrap_or_default(); + self.with_task(factory, id, |task| { + task.stop = Some(StopReason::VerifyFailed) + }); + self.set_state(factory, id, TaskState::Stopped); + self.with_task(factory, id, |task| { + task.stop = Some(StopReason::VerifyFailed) + }); + self.add_question(factory, id, QuestionOrigin::Engine, QuestionKind::Action, + &format!("검증이 {failures}번 실패했습니다: {check} ({link}). worker의 마지막 설명: {last}"), + "retry", None, None, vec!["retry".into(), "cancel".into()], None); + return; + } + self.set_state(factory, id, TaskState::Running); + self.wake(factory, id, &format!( + "Factory: 검증 실패 ({failures}/{limit}): {check}\n로그: {link}\n범위 안에서 고쳐서 다시 hide factory done 하세요. 범위 밖이 필요하면 hide factory propose 또는 ask 로 보고하세요." + )); + } + + // ------------------------------------------------------------------- merge + + /// Moves a verified Task toward merge: pre-merge checks, gates, then an + /// auto merge or merge waiting (B38, B39, B40, B41, B42). + fn advance_merge(&mut self, factory_id: &str, id: &str) { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + let Some(task) = self.task(factory_id, id).cloned() else { + return; + }; + if task.state != TaskState::Verifying { + return; + } + let key = (factory_id.to_owned(), id.to_owned()); + if self.verifying.contains_key(&key) { + return; + } + if self.checks_running.get(&key).is_some_and(|n| *n > 0) { + return; + } + let verified = match &factory.config.verification { + Verification::None => true, + _ => task + .attempts + .iter() + .rev() + .find(|a| a.stage == AttemptStage::Task) + .is_some_and(|a| a.outcome == Some(AttemptOutcome::Passed)), + }; + if !verified { + return; + } + let now = self.now(); + // Questions with a default wait only here, until answer or deadline (B26). + let waiting_question = task.open_questions().any(|q| { + matches!(q.kind, QuestionKind::Default | QuestionKind::ScopeChange) + && q.deadline.is_none_or(|d| d > now) + }); + if waiting_question { + return; + } + let mode = task.merge_mode(&factory); + // Merge-tree and the quick check, in seconds (B38). + if factory.config.verification.exists() || factory.source == SourceKind::Local { + match self.ports.merge.premerge(&factory, &task) { + Ok(PreMerge::Clean) => {} + Ok(PreMerge::Conflict { files }) => { + // A rebase is not a verification failure. + self.record( + factory_id, + Some(id), + "merge.conflict", + json!({"files": files.len()}), + ); + self.set_state(factory_id, id, TaskState::Running); + self.wake(factory_id, id, &format!( + "Factory: 최신 main과 충돌합니다 ({}). main 위로 rebase한 뒤 다시 hide factory done 하세요. 이 일은 검증 실패로 세지 않습니다.", + files.join(", ") + )); + return; + } + Ok(PreMerge::QuickCheckFailed { check }) => { + self.verification_failed(factory_id, id, &check, "quick check"); + return; + } + Ok(PreMerge::RiskPath { paths }) => { + self.with_task(factory_id, id, |task| { + if !task.gates.contains(&Gate::RiskPath) { + task.gates.push(Gate::RiskPath); + } + }); + self.record( + factory_id, + Some(id), + "merge.risk_path", + json!({"paths": paths.len()}), + ); + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + return; + } + } + } + // Verify factories run the bundle once on the latest main merged in. + if matches!(factory.config.verification, Verification::Commands { .. }) + && !task.writes.contains("premerge_passed") + { + self.start_verification(factory_id, id, AttemptStage::PreMerge); + return; + } + let task = self.task(factory_id, id).cloned().unwrap_or(task); + let mut gates: Vec = task + .gates + .iter() + .copied() + .filter(|g| matches!(g, Gate::RiskPath | Gate::CheckFailed)) + .collect(); + if task.human.review_directly { + gates.push(Gate::ReviewDirectly); + } + if task.scope_approved { + gates.push(Gate::ApprovedScopeChange); + } + if task.breaking { + gates.push(Gate::BreakingChange); + } + if !factory.config.verification.exists() { + gates.push(Gate::NoVerification); + } + if mode == MergeMode::Manual { + gates.push(Gate::ManualMode); + } + if task.autonomy.is_some() { + let lines = self + .ports + .merge + .diff_lines(&factory, &task) + .unwrap_or(u32::MAX); + if lines > factory.config.autonomy_diff_limit { + gates.push(Gate::AutonomyDiff); + } + } + if task.open_questions().any(|q| { + !matches!( + q.kind, + QuestionKind::Notice | QuestionKind::Default | QuestionKind::ScopeChange + ) + }) { + gates.push(Gate::OpenQuestion); + } + gates.dedup(); + if !gates.is_empty() { + self.with_task(factory_id, id, |task| task.gates = gates.clone()); + self.set_state(factory_id, id, TaskState::MergeWaiting); + return; + } + if factory.main.broken { + // Auto merge is stopped until main is green again (B44, D-47). + return; + } + self.merge_now(factory_id, id); + } + + fn merge_now(&mut self, factory_id: &str, id: &str) -> Option { + let factory = self.factories.get(factory_id).cloned()?; + let task = self.task(factory_id, id).cloned()?; + if factory.source == SourceKind::Local { + match self.ports.merge.main_dirty(&factory) { + Ok(true) => { + self.with_task(factory_id, id, |task| { + if !task.gates.contains(&Gate::DirtyMain) { + task.gates.push(Gate::DirtyMain); + } + }); + self.set_state(factory_id, id, TaskState::MergeWaiting); + return None; + } + Ok(false) => {} + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + return None; + } + } + } + match self + .ports + .merge + .merge(&factory, &task, factory.config.merge_method) + { + Ok(sha) => { + let now = self.now(); + self.with_task(factory_id, id, |task| { + task.merge_sha = Some(sha.clone()); + task.writes.insert("merge".into()); + task.gates.clear(); + }); + if let Some(f) = self.factories.get_mut(factory_id) { + f.main.merges_since_green.push(LandedMerge { + task: id.to_owned(), + sha: sha.clone(), + at: now, + }); + } + self.save_factory(factory_id); + self.main_seen.insert(factory_id.to_owned(), sha.clone()); + self.record(factory_id, Some(id), "merge.done", json!({"sha": sha})); + self.set_state(factory_id, id, TaskState::Landed); + self.check_landed(factory_id, id); + Some(sha) + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + None + } + } + } + + fn manual_merge(&mut self, _role: &Role, factory_id: &str, id: &str) -> Reply { + let factory = self + .factories + .get(factory_id) + .cloned() + .ok_or_else(|| refuse("factory_not_found", "?"))?; + if factory.source == SourceKind::Local + && matches!(self.ports.merge.main_dirty(&factory), Ok(true)) + { + return Err(refuse( + "main_dirty", + "Commit or stash the changes in the main checkout, then merge", + )); + } + match self.merge_now(factory_id, id) { + Some(sha) => Ok( + json!({"message": "merged", "sha": sha, "task": self.task_answer(factory_id, id, "")["task"]}), + ), + None => Err(refuse( + "merge_failed", + "See hide factory show for the reason", + )), + } + } + + fn check_landed(&mut self, factory_id: &str, id: &str) { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + let Some(task) = self.task(factory_id, id).cloned() else { + return; + }; + let Some(sha) = task.merge_sha.clone() else { + return; + }; + match self.ports.merge.main_check(&factory, &sha) { + Ok(MainCheck::Green) | Ok(MainCheck::None) => self.finish(factory_id, id, &sha), + Ok(MainCheck::Pending) => {} + Ok(MainCheck::Red { link }) => self.main_broken(factory_id, &sha, &link), + Err(failure) => self.external_failure(factory_id, Some(id), &failure), + } + } + + fn finish(&mut self, factory_id: &str, id: &str, sha: &str) { + self.set_state(factory_id, id, TaskState::Done); + if let Some(f) = self.factories.get_mut(factory_id) { + f.main.last_green = Some(sha.to_owned()); + if let Some(position) = f.main.merges_since_green.iter().position(|m| m.sha == sha) { + f.main.merges_since_green.drain(..=position); + } + } + self.save_factory(factory_id); + // Worker tab and worktree go once main is green (B43). + if let Some(worker) = self.task(factory_id, id).and_then(|t| t.worker.clone()) { + let _ = self.ports.workers.stop(&worker); + if let Err(failure) = self.ports.workers.remove_worktree(&worker) { + self.record( + factory_id, + Some(id), + "cleanup.failed", + json!({"stage": failure.stage}), + ); + } + } + // A finished Task is a watch event (D-32). + self.watch_due(factory_id, true); + } + + // ------------------------------------------------------------- main break + + fn main_broken(&mut self, factory_id: &str, sha: &str, link: &str) { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + if factory.main.broken && factory.main.reason.as_deref() == Some(sha) { + return; + } + let by_factory = factory.main.merges_since_green.iter().any(|m| m.sha == sha); + if let Some(f) = self.factories.get_mut(factory_id) { + f.main.broken = true; + f.main.reason = Some(sha.to_owned()); + } + self.save_factory(factory_id); + self.record( + factory_id, + None, + "main.broken", + json!({"sha": sha, "by_factory": by_factory}), + ); + if factory.config.macos_notifications { + self.ports.notifier.macos( + "Factory: main is broken", + "Auto merge stopped. Open hide factory inbox", + ); + } + // The notice rides on the last merged Task, or the draft fix Task. + if !by_factory { + // Outside push: no revert; a fix Task draft and a notice (B47). + let card = Card { + title: format!("main 고치기 ({})", &sha[..sha.len().min(8)]), + goal: format!("Factory 밖 push 뒤 main 검증이 실패했습니다: {link}"), + criteria: vec!["main 검증이 다시 통과한다".into()], + ..Card::default() + }; + // The draft waits for a person's confirmation like a labelled + // issue's card (D-48). + let fix = self.new_task(factory_id, card, None, None); + self.add_question( + factory_id, + &fix, + QuestionOrigin::Engine, + QuestionKind::ConfirmCard, + &format!("main 깨짐: Factory 밖 push({sha})로 검증이 실패해 자동 머지를 멈췄습니다. 수정 Task 초안을 확인해 주세요. {link}"), + "confirm", + None, + None, + vec!["confirm".into(), "cancel".into()], + None, + ); + let now = self.now(); + self.request_review(factory_id, &fix, now); + self.watch_due(factory_id, true); + return; + } + let anchor = factory + .main + .merges_since_green + .last() + .map(|m| m.task.clone()) + .unwrap_or_default(); + if !anchor.is_empty() { + self.notice(factory_id, &anchor, &format!("main 깨짐: Factory 머지 뒤 main 검증이 실패했습니다. 자동 머지를 멈추고 원인 머지를 찾습니다. {link}")); + } + self.reverts + .insert(factory_id.to_owned(), RevertPhase::Bisecting { index: 0 }); + self.watch_due(factory_id, true); + self.drive_revert(factory_id); + } + + /// Finds the first failing merge since the last green and reverts it + /// alone (D-26, B45); a stage that cannot decide stops for a person (B48). + fn drive_revert(&mut self, factory_id: &str) { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + if factory.main.needs_person { + return; + } + let Some(phase) = self.reverts.get(factory_id).cloned() else { + return; + }; + match phase { + RevertPhase::Bisecting { index } => { + let merges = factory.main.merges_since_green.clone(); + if merges.len() == 1 { + let task = merges[0].task.clone(); + return self.start_revert(factory_id, &task); + } + let mut index = index; + while index < merges.len() { + let merge = &merges[index]; + match self.ports.merge.main_check(&factory, &merge.sha) { + Ok(MainCheck::Green) => index += 1, + Ok(MainCheck::Red { .. }) => { + let task = merge.task.clone(); + return self.start_revert(factory_id, &task); + } + Ok(MainCheck::Pending) => { + // A skipped or cancelled run is asked again once. + let key = format!("rerun:{}", merge.sha); + let asked = self + .task(factory_id, &merge.task) + .is_some_and(|t| t.writes.contains(&key)); + if !asked { + if let Err(failure) = + self.ports.merge.rerun_main(&factory, &merge.sha) + { + self.external_failure( + factory_id, + Some(&merge.task.clone()), + &failure, + ); + } + let task = merge.task.clone(); + self.with_task(factory_id, &task, |t| { + t.writes.insert(key); + }); + } + self.reverts + .insert(factory_id.to_owned(), RevertPhase::Bisecting { index }); + return; + } + Ok(MainCheck::None) | Err(_) => break, + } + } + self.revert_needs_person( + factory_id, + "원인 머지를 하나로 정하지 못했습니다", + &merges, + ); + } + RevertPhase::Reverting { revert, task } => { + match self.ports.merge.revert_check(&factory, &revert) { + Ok(MainCheck::Pending) => {} + Ok(MainCheck::Green) | Ok(MainCheck::None) => { + match self.ports.merge.merge_revert(&factory, &revert) { + Ok(sha) => { + self.reverts.remove(factory_id); + self.record( + factory_id, + Some(&task), + "main.reverted", + json!({"sha": sha}), + ); + if let Some(f) = self.factories.get_mut(factory_id) { + f.main.merges_since_green.retain(|m| m.task != task); + } + self.save_factory(factory_id); + self.main_seen.remove(factory_id); + // The original Task lands again on the latest main (B46). + self.with_task(factory_id, &task, |t| { + t.merge_sha = None; + t.writes.remove("merge"); + t.writes.remove("premerge_passed"); + t.writes.insert(format!("reverted:{}", revert.sha)); + // A new pull request carries it again. + t.pr = None; + }); + self.set_state(factory_id, &task, TaskState::Relanding); + } + Err(failure) => { + self.external_failure(factory_id, Some(&task), &failure); + let merges = factory.main.merges_since_green.clone(); + self.revert_needs_person( + factory_id, + "revert를 머지하지 못했습니다", + &merges, + ); + } + } + } + Ok(MainCheck::Red { .. }) | Err(_) => { + let merges = factory.main.merges_since_green.clone(); + self.revert_needs_person( + factory_id, + "revert의 검증이 실패했습니다", + &merges, + ); + } + } + } + } + } + + fn start_revert(&mut self, factory_id: &str, task: &str) { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + let Some(sha) = self + .task(factory_id, task) + .and_then(|t| t.merge_sha.clone()) + else { + let merges = factory.main.merges_since_green.clone(); + return self.revert_needs_person(factory_id, "되돌릴 머지를 찾지 못했습니다", &merges); + }; + let Some(target) = self.task(factory_id, task).cloned() else { + return; + }; + match self.ports.merge.revert(&factory, &target, &sha) { + Ok(revert) => { + self.record( + factory_id, + Some(task), + "main.revert_opened", + json!({"sha": sha}), + ); + self.with_task(factory_id, task, |t| { + t.writes.insert(format!("revert:{sha}")); + }); + self.reverts.insert( + factory_id.to_owned(), + RevertPhase::Reverting { + revert, + task: task.to_owned(), + }, + ); + self.drive_revert(factory_id); + } + Err(failure) => { + self.external_failure(factory_id, Some(task), &failure); + let merges = factory.main.merges_since_green.clone(); + self.revert_needs_person(factory_id, "revert를 만들지 못했습니다", &merges); + } + } + } + + fn revert_needs_person(&mut self, factory_id: &str, why: &str, merges: &[LandedMerge]) { + if let Some(f) = self.factories.get_mut(factory_id) { + f.main.needs_person = true; + } + self.save_factory(factory_id); + self.reverts.remove(factory_id); + let anchor = merges.last().map(|m| m.task.clone()); + let Some(anchor) = anchor else { return }; + let mut choices = vec!["retry-revert".to_owned()]; + choices.extend(merges.iter().map(|m| format!("revert {}", m.task))); + choices.push("resume-auto".into()); + let list: Vec = merges + .iter() + .map(|m| format!("{} {}", m.task, &m.sha[..m.sha.len().min(8)])) + .collect(); + self.add_question( + factory_id, + &anchor, + QuestionOrigin::Engine, + QuestionKind::Action, + &format!( + "main 깨짐 복구를 멈췄습니다: {why}. 후보 머지: {}", + list.join(", ") + ), + "retry-revert", + None, + None, + choices, + None, + ); + } + + // ----------------------------------------------------------------- control + + fn put_to_sleep(&mut self, factory: &str, id: &str) { + if let Some(worker) = self.task(factory, id).and_then(|t| t.worker.clone()) { + match self.ports.workers.sleep(&worker) { + Ok(()) => { + self.with_task(factory, id, |task| { + if let Some(worker) = &mut task.worker { + worker.asleep = true; + } + }); + } + Err(failure) => self.record( + factory, + Some(id), + "worker.sleep_failed", + json!({"stage": failure.stage}), + ), + } + } + } + + fn wake(&mut self, factory: &str, id: &str, body: &str) { + let Some(worker) = self.task(factory, id).and_then(|t| t.worker.clone()) else { + return; + }; + let result = if worker.asleep { + self.ports.workers.wake(&worker, body) + } else { + self.ports + .workers + .message(&worker, &format!("factory-{id}-{}", self.now()), None, body) + }; + match result { + Ok(()) => { + self.with_task(factory, id, |task| { + if let Some(worker) = &mut task.worker { + worker.asleep = false; + } + task.idle_since = None; + }); + } + Err(failure) => self.external_failure(factory, Some(id), &failure), + } + } + + fn reply(&mut self, factory: &str, id: &str, letter: Option<&str>, body: &str) { + let Some(worker) = self.task(factory, id).and_then(|t| t.worker.clone()) else { + return; + }; + let state = self.task(factory, id).map(|t| t.state); + if worker.asleep || state == Some(TaskState::Blocked) { + // A blocked Task wakes when it gets a slot again. + self.with_task(factory, id, |task| { + task.flags + .push(format!("pending reply: {}", judgment::cut(body, 2000))) + }); + return; + } + let intent = format!("factory-{id}-reply-{}", self.now()); + if let Err(failure) = self.ports.workers.message(&worker, &intent, letter, body) { + self.external_failure(factory, Some(id), &failure); + } + } + + fn cancel(&mut self, factory_id: &str, id: &str) { + let Some(task) = self.task(factory_id, id).cloned() else { + return; + }; + let now = self.now(); + self.cancel_verification(factory_id, id); + if let Some(worker) = &task.worker { + let _ = self.ports.workers.stop(worker); + } + if let (Some(factory), Some(pr)) = (self.factories.get(factory_id).cloned(), &task.pr) + && pr.by_factory + && pr.open + { + match self.ports.merge.close_pr(&factory, pr) { + Ok(()) => { + self.with_task(factory_id, id, |task| { + if let Some(pr) = &mut task.pr { + pr.open = false; + } + }); + } + Err(failure) => self.external_failure(factory_id, Some(id), &failure), + } + } + self.with_task(factory_id, id, |task| { + task.cancelled_at = Some(now); + task.cancelled_from = Some(task.state); + if let Some(worker) = &mut task.worker { + worker.asleep = true; + } + }); + self.set_state(factory_id, id, TaskState::Cancelled); + } + + fn revive(&mut self, factory_id: &str, id: &str) -> Reply { + let task = self + .task(factory_id, id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "?"))?; + let keep = self + .factories + .get(factory_id) + .map_or(7 * DAY_MS, |f| f.config.cancel_keep_ms); + if task.purged + || task + .cancelled_at + .is_some_and(|at| self.now().saturating_sub(at) > keep) + { + return Err(refuse("revive_expired", "Add the Task again")); + } + if let (Some(factory), Some(pr)) = (self.factories.get(factory_id).cloned(), &task.pr) + && pr.by_factory + && !pr.open + { + match self.ports.merge.reopen_pr(&factory, pr) { + Ok(()) => { + self.with_task(factory_id, id, |task| { + if let Some(pr) = &mut task.pr { + pr.open = true; + } + }); + } + Err(failure) => self.external_failure(factory_id, Some(id), &failure), + } + } + let target = match task.cancelled_from { + Some(TaskState::Drafting) => TaskState::Drafting, + _ if task.issue.is_none() => TaskState::Drafting, + _ => TaskState::Waiting, + }; + self.with_task(factory_id, id, |task| { + task.cancelled_at = None; + task.cancelled_from = None; + }); + self.set_state(factory_id, id, target); + if target == TaskState::Drafting { + self.maybe_ready(factory_id, id); + } + Ok(self.task_answer(factory_id, id, "revived with the same branch and worktree")) + } + + fn dep(&mut self, role: &Role, task: &str, on: &str, remove: bool) -> Reply { + let (factory, id) = self.resolve(role, task)?; + if let Role::Worker { task: own, .. } = role + && *own != id + { + return Err(refuse( + ROLE_NOT_ALLOWED, + "A worker changes only its own Task", + )); + } + let (_, on_id) = self.resolve(role, on)?; + let current = self + .task(&factory, &id) + .cloned() + .ok_or_else(|| refuse("task_not_found", "?"))?; + if remove { + self.allowed(&factory, &id, "dep-remove")?; + self.with_task(&factory, &id, |task| { + task.card.depends_on.retain(|d| *d != on_id) + }); + self.record( + &factory, + Some(&id), + "dependency.removed", + json!({"on": on_id, "by": role.relayed_by()}), + ); + return Ok(self.task_answer(&factory, &id, "dependency removed")); + } + if matches!( + current.state, + TaskState::Done | TaskState::Landed | TaskState::Cancelled + ) { + return Err(refuse("action_not_allowed_in_state", "The Task is finished") + .with(json!({"state": current.state.label(), "allowed": Self::allowed_actions(¤t)}))); + } + let edges = dag::edges(self.tasks_of(&factory)); + if let Some(path) = dag::cycle_with(&edges, &id, &on_id) { + return Err( + refuse("dependency_cycle", "That dependency would close a loop") + .with(json!({"cycle": path})), + ); + } + self.with_task(&factory, &id, |task| { + if !task.card.depends_on.contains(&on_id) { + task.card.depends_on.push(on_id.clone()); + } + }); + self.record( + &factory, + Some(&id), + "dependency.added", + json!({"on": on_id, "by": role.relayed_by()}), + ); + let unmerged = self + .task(&factory, &on_id) + .is_some_and(|t| !t.state.merged()); + if unmerged && matches!(current.state, TaskState::Running) { + self.put_to_sleep(&factory, &id); + self.set_state(&factory, &id, TaskState::Blocked); + } + Ok(self.task_answer(&factory, &id, "dependency added")) + } + + fn close(&mut self, role: &Role, project: Option<&str>) -> Reply { + let _ = role; + let factory = self.factory_id(project)?; + let running: Vec = self + .tasks_of(&factory) + .filter(|t| t.state.column() == Some(Column::Running)) + .map(Task::display_id) + .collect(); + if !running.is_empty() { + return Err(refuse( + "factory_has_running_tasks", + "Finish, pause or cancel them first", + ) + .with(json!({"tasks": running}))); + } + if let Some(f) = self.factories.get_mut(&factory) { + f.closed = true; + } + self.save_factory(&factory); + self.record(&factory, None, "factory.closed", json!({})); + Ok( + json!({"message": "closed; hide factory init --confirm brings it back with its records"}), + ) + } + + fn config(&mut self, role: &Role, project: Option<&str>, set: Vec<(String, String)>) -> Reply { + let factory_id = self.factory_id(project)?; + let mut config = self + .factories + .get(&factory_id) + .map(|f| f.config.clone()) + .unwrap_or_default(); + let mut machine_workers = None; + for (key, value) in &set { + let bad = || { + refuse( + "config_invalid", + "Check hide factory config for the keys and values", + ) + .with(json!({"key": key})) + }; + let number = || value.parse::().map_err(|_| bad()); + match key.as_str() { + "merge_mode" => { + config.merge_mode = match value.as_str() { + "auto" => MergeMode::Auto, + "manual" => MergeMode::Manual, + _ => return Err(bad()), + } + } + "merge_method" => { + config.merge_method = match value.as_str() { + "merge" => MergeMethod::Merge, + "squash" => MergeMethod::Squash, + "rebase" => MergeMethod::Rebase, + _ => return Err(bad()), + } + } + "verify" => { + let commands: Vec = value + .split("&&&") + .map(str::trim) + .filter(|c| !c.is_empty()) + .map(str::to_owned) + .collect(); + config.verification = if commands.is_empty() { + Verification::None + } else { + Verification::Commands { commands } + }; + } + "ci" => { + config.verification = Verification::Ci { + checks: value + .split(',') + .map(str::trim) + .filter(|c| !c.is_empty()) + .map(str::to_owned) + .collect(), + }; + } + "no_verification" => config.verification = Verification::None, + "quick_check" => { + config.quick_check = Some(value.clone()).filter(|v| !v.trim().is_empty()) + } + "max_workers" => machine_workers = Some(number()?.clamp(1, 64) as u32), + "question_deadline_hours" => config.question_deadline_ms = number()? * HOUR_MS, + "stall_minutes" => config.stall_ms = number()? * MINUTE_MS, + "watch_interval_minutes" => config.watch_interval_ms = number()?.max(5) * MINUTE_MS, + "watch_daily_limit" => config.watch_daily_limit = number()? as u32, + "outside_read_minutes" => config.outside_read_ms = number()?.max(1) * MINUTE_MS, + "cancel_keep_days" => config.cancel_keep_ms = number()? * DAY_MS, + "done_fold_days" => config.done_fold_ms = number()? * DAY_MS, + "new_task_limit" => config.new_task_limit = number()? as u32, + "verify_timeout_minutes" => config.verify_timeout_ms = number()?.max(1) * MINUTE_MS, + "disk_floor_gb" => config.disk_floor_bytes = number()? * 1024 * 1024 * 1024, + "default_runtime" => { + config.default_runtime = Runtime::parse(value).ok_or_else(bad)? + } + "harness" => { + config.harness = match value.split_once(':') { + Some((name, instructions)) => Some(Harness { + name: name.trim().into(), + instructions: instructions.trim().into(), + }), + None if value.trim().is_empty() => None, + None => return Err(bad()), + } + } + "autonomy" => { + let (scope, enabled) = value.split_once('=').ok_or_else(bad)?; + let enabled = enabled == "on"; + match config.autonomy.iter_mut().find(|s| s.id == scope) { + Some(existing) => existing.enabled = enabled, + None => config.autonomy.push(AutonomyScope { + id: scope.into(), + description: scope.into(), + enabled, + }), + } + } + "recovery" => { + let (action, enabled) = value.split_once('=').ok_or_else(bad)?; + let action = RecoveryAction::ALL + .into_iter() + .find(|a| a.as_str() == action) + .ok_or_else(bad)?; + config.recovery.retain(|a| *a != action); + if enabled == "on" { + config.recovery.push(action); + } + } + "risk_paths" => { + config.risk_paths = value + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_owned) + .collect() + } + "prd_in_issue" => config.prd_in_issue = value == "on", + "macos_notifications" => config.macos_notifications = value == "on", + _ => return Err(bad()), + } + } + if !set.is_empty() { + if config.merge_mode == MergeMode::Auto && !config.verification.exists() { + return Err(refuse( + "auto_needs_verification", + "Set a verification before auto merge", + )); + } + if let Some(f) = self.factories.get_mut(&factory_id) { + f.config = config.clone(); + } + if let Some(workers) = machine_workers { + self.machine_max_workers = workers; + let _ = self + .store + .set_meta("machine.max_workers", &workers.to_string()); + } + self.save_factory(&factory_id); + self.record(&factory_id, None, "config.changed", json!({"keys": set.iter().map(|(k, _)| k).collect::>(), "by": role.relayed_by()})); + } + Ok(json!({"config": config, "machine": {"max_workers": self.machine_max_workers}})) + } + + fn status(&self, project: Option<&str>) -> Reply { + let mut summary = self.summary(); + if let Some(project) = project { + let id = self.factory_id(Some(project))?; + summary.factories.retain(|f| f.id == id); + } + Ok(serde_json::to_value(&summary).unwrap_or_default()) + } + + fn show(&self, factory: &str, id: &str) -> Value { + let Some(task) = self.task(factory, id) else { + return Value::Null; + }; + let config = self + .factories + .get(factory) + .map(|f| f.config.clone()) + .unwrap_or_default(); + let edges = dag::edges(self.tasks_of(factory)); + let name = |tid: &String| { + self.task(factory, tid) + .map(Task::display_id) + .unwrap_or_else(|| tid.clone()) + }; + let after: Vec = edges + .iter() + .filter(|(_, preds)| preds.contains(id)) + .map(|(tid, _)| name(tid)) + .collect(); + json!({ + "id": task.id, + "factory": task.factory, + "display_id": task.display_id(), + "title": task.card.title, + "state": task.state.as_str(), + "state_label": task.state.label(), + "stop": task.stop.map(|s| s.label()), + "goal": task.card.goal, + "criteria": task.card.criteria, + "out_of_scope": task.card.out_of_scope, + "before": task.card.depends_on.iter().map(name).collect::>(), + "after": after, + "external": task.card.external, + "failures": task.failures, + "failure_limit": config.verify_failure_limit, + "pr": task.pr, + "worker": task.worker, + "attachments": task.attachments, + "decisions": task.decisions, + "questions": task.questions, + "discoveries": task.discoveries, + "gates": task.gates.iter().map(|g| g.reason()).collect::>(), + "allowed": Self::allowed_actions(task), + "priority": task.human.priority, + "merge_sha": task.merge_sha, + "attempts": task.attempts, + }) + } + + // ------------------------------------------------------------------ letters + + /// Mail to a Factory (D-14): the CLI's own reports carry a typed body; a + /// harness that only speaks the letter protocol is read as a question or + /// a report (B25). Each letter is applied once. + pub fn letter(&mut self, letter: Inbound) -> Value { + if self.processed.contains(&letter.id) { + return json!({"ok": true, "message": "already applied", "duplicate": true}); + } + let Some((factory, task)) = self.role_for(Some(&letter.sender_pane), None) else { + self.remember_letter(&letter.id); + self.record( + &letter.factory, + None, + "letter.unbound", + json!({"letter": letter.id, "kind": letter.kind}), + ); + return Refusal::new( + "sender_not_a_worker", + "Only a Factory worker reports to a Factory", + ) + .to_json(); + }; + if factory != letter.factory { + self.remember_letter(&letter.id); + return Refusal::new( + "sender_not_a_worker", + "This worker belongs to another Factory", + ) + .to_json(); + } + let role = Role::Worker { + factory: factory.clone(), + task: task.clone(), + }; + let command = match serde_json::from_str::(&letter.body) + .ok() + .and_then(|v| v.get("factory").cloned()) + { + Some(value) => match serde_json::from_value::(value) { + Ok(command) => with_letter(command, &letter.id), + Err(_) => { + self.remember_letter(&letter.id); + return Refusal::new( + "letter_invalid", + "Use hide factory ask|block|propose|done", + ) + .to_json(); + } + }, + None => plain_letter(&letter), + }; + let answer = match command { + Some(command) => self.command(&role, command), + None if letter.kind == "watch" => { + // The watch's inactivity warning about a worker: stalled (B24). + self.stall(&factory, &task); + json!({"ok": true, "message": "stalled"}) + } + None => { + Refusal::new("letter_invalid", "Use hide factory ask|block|propose|done").to_json() + } + }; + self.remember_letter(&letter.id); + answer + } + + fn remember_letter(&mut self, id: &str) { + if self.processed.insert(id.to_owned()) { + self.processed_order.push(id.to_owned()); + while self.processed_order.len() > PROCESSED_LETTERS { + let old = self.processed_order.remove(0); + self.processed.remove(&old); + } + let _ = self.store.set_meta( + "processed_letters", + &serde_json::to_string(&self.processed_order).unwrap_or_default(), + ); + } + } + + pub fn letter_seen(&self, id: &str) -> bool { + self.processed.contains(id) + } + + fn stall(&mut self, factory: &str, id: &str) { + if self + .task(factory, id) + .is_some_and(|t| t.state == TaskState::Running) + { + self.put_to_sleep(factory, id); + self.with_task(factory, id, |task| task.stop = Some(StopReason::Stalled)); + self.set_state(factory, id, TaskState::Stopped); + self.with_task(factory, id, |task| task.stop = Some(StopReason::Stalled)); + } + } + + // --------------------------------------------------------------------- tick + + /// Advances everything time or the outside world moves. Each step is + /// bounded and makes at most one external call per Task. + pub fn tick(&mut self) { + self.apply_judgments(); + self.poll_verifications(); + self.expire_questions(); + self.check_workers(); + self.read_outside(); + self.check_main(); + let factories: Vec = self.factories.keys().cloned().collect(); + for factory in &factories { + self.drive_revert(factory); + self.unblock(factory); + let verifying: Vec = self + .tasks_of(factory) + .filter(|t| t.state == TaskState::Verifying) + .map(|t| t.id.clone()) + .collect(); + for id in verifying { + self.advance_merge(factory, &id); + } + let landed: Vec = self + .tasks_of(factory) + .filter(|t| t.state == TaskState::Landed) + .map(|t| t.id.clone()) + .collect(); + for id in landed { + self.check_landed(factory, &id); + } + let drafting: Vec = self + .tasks_of(factory) + .filter(|t| t.state == TaskState::Drafting) + .map(|t| t.id.clone()) + .collect(); + for id in drafting { + self.maybe_ready(factory, &id); + } + self.watch_due(factory, false); + } + self.start_tasks(); + self.environment_recovery(); + self.retention(); + } + + /// A Task blocked only on a predecessor (a prerequisite it proposed, a + /// dependency added while it ran) waits for a slot again once every + /// predecessor merged and no blocking question is open (B27, D-16). + fn unblock(&mut self, factory: &str) { + let Some(tasks) = self.tasks.get(factory) else { + return; + }; + let ready: Vec = tasks + .values() + .filter(|t| t.state == TaskState::Blocked) + .filter(|t| { + !t.open_questions() + .any(|q| matches!(q.kind, QuestionKind::Blocking)) + }) + .filter(|t| dag::waiting_for(t, tasks).is_empty()) + .map(|t| t.id.clone()) + .collect(); + for id in ready { + self.set_state(factory, &id, TaskState::Waiting); + } + } + + fn apply_judgments(&mut self) { + for answer in self.ports.judge.finished() { + let Some((factory, task, purpose)) = self.judgments.remove(&answer.id) else { + continue; + }; + match (&answer.outcome, purpose, task) { + (JudgmentOutcome::Answered { value }, Purpose::Intake, Some(task)) => { + self.apply_intake(&factory, &task, value) + } + (JudgmentOutcome::Failed { reason }, Purpose::Intake, Some(task)) => { + self.review_failed(&factory, &task, reason) + } + (outcome, Purpose::Drift | Purpose::Check, Some(task)) => { + let key = (factory.clone(), task.clone()); + if let Some(count) = self.checks_running.get_mut(&key) { + *count = count.saturating_sub(1); + } + let drafting = self + .task(&factory, &task) + .is_some_and(|t| t.state == TaskState::Drafting); + match outcome { + JudgmentOutcome::Answered { value } if drafting => { + // An intake check only adds questions to the draft. + if let Ok(finding) = judgment::parse_finding(value) { + for question in finding.questions { + self.add_question( + &factory, + &task, + QuestionOrigin::Check, + QuestionKind::Intake, + &question.text, + &question.suggestion, + question.default_action, + None, + Vec::new(), + None, + ); + } + } + } + JudgmentOutcome::Answered { value } => { + self.apply_finding(&factory, &task, value) + } + JudgmentOutcome::Failed { .. } if drafting => {} + JudgmentOutcome::Failed { .. } => self.check_failed(&factory, &task), + } + self.advance_merge(&factory, &task); + } + (JudgmentOutcome::Answered { value }, Purpose::Watch, _) => { + self.apply_watch(&factory, value) + } + (JudgmentOutcome::Answered { value }, Purpose::Env, _) => { + self.apply_diagnosis(&factory, value) + } + (JudgmentOutcome::Failed { reason }, purpose, task) => { + // A watch or diagnosis that fails changes no Task (B69). + self.record( + &factory, + task.as_deref(), + "judgment.failed", + json!({"purpose": format!("{purpose:?}"), "reason": reason}), + ); + } + _ => {} + } + } + } + + fn expire_questions(&mut self) { + let now = self.now(); + let mut expired = Vec::new(); + for task in self.all_tasks() { + for question in task.open_questions() { + if matches!( + question.kind, + QuestionKind::Default | QuestionKind::ScopeChange + ) && question.deadline.is_some_and(|d| d <= now) + { + expired.push(( + task.factory.clone(), + task.id.clone(), + question.id.clone(), + question.default_action.clone(), + )); + } + } + } + for (factory, id, question, default) in expired { + let text = default.unwrap_or_default(); + self.with_task(&factory, &id, |task| { + if let Some(q) = task.questions.iter_mut().find(|q| q.id == question) { + q.answer = Some(Answer { + text: text.clone(), + chose: Some(text.clone()), + relayed_by: "deadline".into(), + at: now, + }); + } + }); + self.record( + &factory, + Some(&id), + "question.deadline", + json!({"question": question}), + ); + self.advance_merge(&factory, &id); + } + } + + fn check_workers(&mut self) { + let now = self.now(); + let running: Vec<(String, String, WorkerRef, Option, UnixMs)> = self + .all_tasks() + .filter(|t| t.state == TaskState::Running) + .filter_map(|t| { + t.worker.clone().map(|w| { + ( + t.factory.clone(), + t.id.clone(), + w, + t.last_report_at, + t.state_since, + ) + }) + }) + .collect(); + for (factory, id, worker, last_report, since) in running { + let no_report = self + .factories + .get(&factory) + .map_or(2 * MINUTE_MS, |f| f.config.no_report_ms); + match self.ports.workers.status(&worker) { + WorkerStatus::Resting { since: rest } => { + // A turn that ended with no Factory report since it began (B24). + let reported = last_report.is_some_and(|at| at >= rest.min(since).max(since)); + if !reported && now.saturating_sub(rest) >= no_report && rest >= since { + self.with_task(&factory, &id, |task| { + task.stop = Some(StopReason::NoReport) + }); + self.set_state(&factory, &id, TaskState::Stopped); + self.with_task(&factory, &id, |task| { + task.stop = Some(StopReason::NoReport) + }); + self.record(&factory, Some(&id), "worker.no_report", json!({})); + } + } + WorkerStatus::Gone => { + self.with_task(&factory, &id, |task| task.stop = Some(StopReason::NoReport)); + self.set_state(&factory, &id, TaskState::Stopped); + self.with_task(&factory, &id, |task| task.stop = Some(StopReason::NoReport)); + self.record(&factory, Some(&id), "worker.gone", json!({})); + } + WorkerStatus::Working | WorkerStatus::Blocked => {} + } + } + } + + fn start_tasks(&mut self) { + let now = self.now(); + if self.halt_until.is_some_and(|until| until > now) { + return; + } + // Rule 1: hold starts below the disk floor or at critical memory + // pressure; re-checked when a worker ends or a minute passes (B57). + let due = self + .hold_checked_at + .is_none_or(|at| now.saturating_sub(at) >= ENV_RECHECK_MS) + || self.hold_reason.is_none(); + let mut candidates: Vec = self + .all_tasks() + .filter(|t| self.factories.get(&t.factory).is_some_and(|f| !f.closed)) + .filter(|t| matches!(t.state, TaskState::Waiting | TaskState::Relanding)) + .filter(|t| { + let tasks = &self.tasks[&t.factory]; + dag::waiting_for(t, tasks).is_empty() + }) + .cloned() + .collect(); + if candidates.is_empty() { + return; + } + // Relanding goes first; then priority, then age (D-29). + candidates.sort_by(|a, b| { + (b.state == TaskState::Relanding) + .cmp(&(a.state == TaskState::Relanding)) + .then_with(|| dag::slot_order(a, b)) + }); + if due { + self.hold_checked_at = Some(now); + self.hold_reason = None; + let project = self + .factories + .get(&candidates[0].factory) + .map(|f| f.project.clone()) + .unwrap_or_default(); + let floor = self + .factories + .get(&candidates[0].factory) + .map_or(20 << 30, |f| f.config.disk_floor_bytes); + if self + .ports + .environment + .disk_free(&project) + .is_some_and(|free| free < floor) + { + self.hold_reason = Some("디스크 여유가 기준보다 작음".into()); + } else if self.ports.environment.memory_pressure() == MemoryPressure::Critical { + self.hold_reason = Some("메모리 압박 critical".into()); + } + } + if let Some(reason) = self.hold_reason.clone() { + self.env_problem_since.get_or_insert(now); + for task in &candidates { + if task.held.as_deref() != Some(reason.as_str()) { + let held = reason.clone(); + self.with_task(&task.factory, &task.id, |t| t.held = Some(held)); + } + } + return; + } + for task in &candidates { + if task.held.is_some() { + self.with_task(&task.factory, &task.id, |t| t.held = None); + } + } + let mut free = self + .machine_max_workers + .saturating_sub(self.running_count()); + for task in candidates { + // A relanding Task already holds its slot. + let relanding = task.state == TaskState::Relanding; + if free == 0 && !relanding { + continue; + } + if self.start(&task.factory, &task.id) && !relanding { + free -= 1; + } + } + } + + fn start(&mut self, factory_id: &str, id: &str) -> bool { + let Some(factory) = self.factories.get(factory_id).cloned() else { + return false; + }; + let Some(task) = self.task(factory_id, id).cloned() else { + return false; + }; + let now = self.now(); + let mut runtime = task.runtime(&factory); + if let Some(until) = self.runtime_blocked.get(&runtime).copied() { + if until > now { + let other = match runtime { + Runtime::Claude => Runtime::Codex, + Runtime::Codex => Runtime::Claude, + }; + if task.human.runtime.is_none() + && self.runtime_blocked.get(&other).is_none_or(|u| *u <= now) + { + runtime = other; + } else { + return false; + } + } else { + self.runtime_blocked.remove(&runtime); + } + } + let relanding = task.state == TaskState::Relanding; + // A Task with a worker resumes it (wake after answer, pause, retry, + // relanding); otherwise a new worker starts (B22, B54). + if let Some(worker) = task.worker.clone() { + let pending: Vec = task + .flags + .iter() + .filter_map(|f| f.strip_prefix("pending reply: ").map(str::to_owned)) + .collect(); + let gone = matches!(self.ports.workers.status(&worker), WorkerStatus::Gone); + let body = if relanding { + "Factory: 이 Task의 머지가 main 검증 실패로 revert되었습니다. 최신 main 위로 다시 올리고 다시 hide factory done 하세요.".to_owned() + } else if gone { + String::new() + } else if pending.is_empty() { + "Factory: 이어서 진행하세요.".to_owned() + } else { + pending.join("\n") + }; + let restarted = if gone { + // Retry: the same worktree and session, a fresh process (B54). + let request = WorkerSpawn { + factory: factory_id.to_owned(), + task: id.to_owned(), + name: worker.name.clone(), + runtime, + project: factory.project.clone(), + branch: worker.branch.clone(), + prompt: worker_prompt(&task, &factory, true), + resume: Some(worker.clone()), + }; + self.ports.workers.spawn(&request).map(Some) + } else { + self.ports.workers.wake(&worker, &body).map(|()| None) + }; + match restarted { + Ok(new_worker) => { + self.with_task(factory_id, id, |t| { + if let Some(w) = new_worker { + t.worker = Some(w); + } + if let Some(w) = &mut t.worker { + w.asleep = false; + } + t.flags.retain(|f| !f.starts_with("pending reply: ")); + t.last_report_at = None; + }); + self.set_state(factory_id, id, TaskState::Running); + true + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + false + } + } + } else { + let request = WorkerSpawn { + factory: factory_id.to_owned(), + task: id.to_owned(), + name: worker_name(&factory, &task), + runtime, + project: factory.project.clone(), + branch: task.branch_slug(), + prompt: worker_prompt(&task, &factory, false), + resume: None, + }; + match self.ports.workers.spawn(&request) { + Ok(worker) => { + self.with_task(factory_id, id, |t| { + t.worker = Some(worker); + t.last_report_at = None; + }); + self.record( + factory_id, + Some(id), + "worker.started", + json!({"runtime": runtime.as_str()}), + ); + self.set_state(factory_id, id, TaskState::Running); + true + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + false + } + } + } + } + + // ------------------------------------------------------------ outside work + + fn read_outside(&mut self) { + let now = self.now(); + let due: Vec = self + .factories + .values() + .filter(|f| !f.closed) + .filter(|f| { + f.outside_read_at + .is_none_or(|at| now.saturating_sub(at) >= f.config.outside_read_ms) + }) + .filter(|f| { + self.github_backoff + .get(&f.id) + .is_none_or(|(_, until)| *until <= now) + }) + .map(|f| f.id.clone()) + .collect(); + for factory_id in due { + let Some(factory) = self.factories.get(&factory_id).cloned() else { + continue; + }; + let tasks: Vec = self.tasks_of(&factory_id).cloned().collect(); + let refs: Vec<&Task> = tasks.iter().collect(); + match self.ports.source.observe(&factory, &refs) { + Ok(events) => { + self.github_backoff.remove(&factory_id); + if let Some(f) = self.factories.get_mut(&factory_id) { + f.outside_read_at = Some(now); + f.outside_read_failures = 0; + } + self.save_factory(&factory_id); + for event in events { + self.apply_outside(&factory_id, event); + } + } + Err(failure) => { + if let Some(f) = self.factories.get_mut(&factory_id) { + f.outside_read_failures += 1; + f.outside_read_at = Some(now); + } + self.save_factory(&factory_id); + self.external_failure(&factory_id, None, &failure); + } + } + } + } + + fn task_for_issue(&self, factory: &str, issue: &IssueRef) -> Option { + self.tasks_of(factory) + .find(|t| t.issue.as_ref() == Some(issue)) + .cloned() + } + + /// The person wins outside; the Factory follows (D-27, B49-B52, B15). + fn apply_outside(&mut self, factory_id: &str, event: OutsideEvent) { + let factory = self.factories.get(factory_id).cloned(); + match event { + OutsideEvent::ClosingPr { + issue, + pr, + url, + merged, + } => { + let Some(task) = self.task_for_issue(factory_id, &issue) else { + return; + }; + if task.pr.as_ref().is_some_and(|p| p.number == pr) { + return; + } + match task.state { + TaskState::Done | TaskState::Landed | TaskState::Cancelled => {} + _ if merged => { + self.record( + factory_id, + Some(&task.id), + "outside.merged", + json!({"pr": pr}), + ); + if let Some(worker) = &task.worker { + let _ = self.ports.workers.stop(worker); + } + self.set_state(factory_id, &task.id, TaskState::Done); + } + TaskState::Outside => {} + TaskState::Running + | TaskState::Verifying + | TaskState::Blocked + | TaskState::Paused + | TaskState::MergeWaiting + | TaskState::Stopped => { + // Stop the worker; the worktree stays 7 days (B50). + self.cancel_verification(factory_id, &task.id); + if let Some(worker) = &task.worker { + let _ = self.ports.workers.stop(worker); + } + self.with_task(factory_id, &task.id, |t| { + t.cancelled_at = Some(t.updated_at); + t.cancelled_from = Some(t.state); + if let Some(w) = &mut t.worker { + w.asleep = true; + } + }); + self.set_state(factory_id, &task.id, TaskState::Outside); + self.notice(factory_id, &task.id, &format!("밖의 PR이 이 Task의 issue를 닫습니다: {url}. worker를 멈췄고 worktree는 7일 남습니다. 되살리려면 hide factory revive {}", task.display_id())); + } + _ => { + self.set_state(factory_id, &task.id, TaskState::Outside); + self.record(factory_id, Some(&task.id), "outside.pr", json!({"pr": pr})); + } + } + } + OutsideEvent::IssueClosed { issue } | OutsideEvent::LabelRemoved { issue } => { + let Some(task) = self.task_for_issue(factory_id, &issue) else { + return; + }; + if matches!( + task.state, + TaskState::Done | TaskState::Landed | TaskState::Cancelled + ) { + return; + } + if task.state == TaskState::Outside { + // Its outside PR closed the issue: follow it to done. + self.set_state(factory_id, &task.id, TaskState::Done); + return; + } + self.cancel(factory_id, &task.id); + self.notice(factory_id, &task.id, "issue가 PR 없이 닫혔거나 factory 라벨이 빠져 Task를 취소했습니다. 7일 동안 되살릴 수 있습니다."); + } + OutsideEvent::IssueReopened { issue } => { + if let Some(task) = self.task_for_issue(factory_id, &issue) + && task.state == TaskState::Done + { + self.notice( + factory_id, + &task.id, + "완료한 Task의 issue가 다시 열렸습니다. 자동으로 다시 넣지 않았습니다.", + ); + } + } + OutsideEvent::BodyEdited { issue, body_hash } => { + let Some(task) = self.task_for_issue(factory_id, &issue) else { + return; + }; + if task.source_body_hash.as_deref() == Some(body_hash.as_str()) { + return; + } + let first = task.source_body_hash.is_none(); + self.with_task(factory_id, &task.id, |t| { + t.source_body_hash = Some(body_hash.clone()) + }); + if first { + return; + } + match task.state { + TaskState::Drafting | TaskState::Waiting => { + // Before start: back to drafting and reviewed again (B52). + self.set_state(factory_id, &task.id, TaskState::Drafting); + let now = self.now(); + self.request_review(factory_id, &task.id, now); + } + TaskState::Running + | TaskState::Blocked + | TaskState::Paused + | TaskState::Verifying => { + let deadline = factory + .as_ref() + .map_or(24 * HOUR_MS, |f| f.config.question_deadline_ms); + let now = self.now(); + self.add_question( + factory_id, + &task.id, + QuestionOrigin::Engine, + QuestionKind::ScopeChange, + "사람이 issue 본문을 고쳤습니다. 새 범위를 승인할까요?", + "approve", + Some("지금 범위로 진행".into()), + Some(now + deadline), + vec!["approve".into(), "reject".into()], + None, + ); + } + _ => {} + } + } + OutsideEvent::Labeled { issue, title, body } => { + if self.task_for_issue(factory_id, &issue).is_some() + || factory.as_ref().is_some_and(|f| f.closed) + { + return; + } + // The label path: the review drafts the card from the body and + // a person confirms it (B15, D-48); the body is not touched. + let card = Card { + title: judgment::cut(&title, TITLE_LIMIT), + goal: judgment::cut(&body, TEXT_LIMIT), + criteria: extract_criteria(&body), + ..Card::default() + }; + let id = self.new_task(factory_id, card, None, None); + self.with_task(factory_id, &id, |t| { + t.issue = Some(issue.clone()); + t.label_path = true; + t.writes.insert("label".into()); + t.source_body_hash = Some(sha256_hex(body.as_bytes())); + }); + self.add_question( + factory_id, + &id, + QuestionOrigin::Engine, + QuestionKind::ConfirmCard, + "라벨로 들어온 Task입니다. 카드 초안을 확인해 주세요.", + "confirm", + None, + None, + vec!["confirm".into(), "cancel".into()], + None, + ); + let now = self.now(); + self.request_review(factory_id, &id, now); + } + OutsideEvent::OutsidePush { sha } => { + self.record(factory_id, None, "outside.push", json!({"sha": sha})); + } + } + } + + /// Reads main's head and its verification for pushes the Factory did not + /// make (B47) and recovery back to green (D-47). + fn check_main(&mut self) { + let factories: Vec = self + .factories + .values() + .filter(|f| !f.closed) + .cloned() + .collect(); + for factory in factories { + let due = factory.main.broken + || factory + .outside_read_at + .is_some_and(|at| self.now().saturating_sub(at) < 1000) + || !self.main_seen.contains_key(&factory.id); + if !due { + continue; + } + let Ok(head) = self.ports.merge.main_head(&factory) else { + continue; + }; + let known = factory + .main + .merges_since_green + .iter() + .any(|m| m.sha == head); + if self.main_seen.get(&factory.id) == Some(&head) && !factory.main.broken { + continue; + } + match self.ports.merge.main_check(&factory, &head) { + Ok(MainCheck::Green) => { + self.main_seen.insert(factory.id.clone(), head.clone()); + if factory.main.broken && !self.reverts.contains_key(&factory.id) { + // Green again: auto merge resumes (D-47). + if let Some(f) = self.factories.get_mut(&factory.id) { + f.main.broken = false; + f.main.needs_person = false; + f.main.reason = None; + f.main.last_green = Some(head.clone()); + } + self.save_factory(&factory.id); + self.record(&factory.id, None, "main.green", json!({"sha": head})); + } + } + Ok(MainCheck::Red { link }) if !known && !factory.main.broken => { + self.main_seen.insert(factory.id.clone(), head.clone()); + self.main_broken(&factory.id, &head, &link); + } + Ok(_) => { + if !factory.main.broken { + self.main_seen.insert(factory.id.clone(), head); + } + } + Err(failure) => self.external_failure(&factory.id, None, &failure), + } + } + } + + // ------------------------------------------------------------- environment + + /// A failure the Task did not cause is not counted (D-31 rule 2, B58). + fn verification_environment( + &mut self, + factory: &str, + id: &str, + failure: &Failure, + stage: &str, + ) { + let now = self.now(); + self.with_task(factory, id, |task| task.environment_failures += 1); + self.env_failures + .push((now, factory.to_owned(), id.to_owned(), stage.to_owned())); + let repeated = self.task(factory, id).map_or(0, |t| t.environment_failures); + let others_fine = !self.env_failures.iter().any(|(at, f, t, _)| { + now.saturating_sub(*at) <= CASCADE_WINDOW_MS && f == factory && t != id + }); + if repeated >= 3 && others_fine { + // Only this Task keeps failing this way: the Task's (B60). + self.with_task(factory, id, |task| { + task.stop = Some(StopReason::EnvironmentRepeated) + }); + self.set_state(factory, id, TaskState::Stopped); + self.with_task(factory, id, |task| { + task.stop = Some(StopReason::EnvironmentRepeated) + }); + self.add_question( + factory, + id, + QuestionOrigin::Engine, + QuestionKind::Action, + &format!("같은 환경 실패가 이 Task에서만 3번 반복되었습니다 ({stage})."), + "retry", + None, + None, + vec!["retry".into(), "cancel".into()], + None, + ); + return; + } + self.external_failure(factory, Some(id), failure); + if self + .task(factory, id) + .is_some_and(|t| t.state == TaskState::Verifying) + { + // Back to waiting; the worker sleeps until the environment clears. + self.set_state(factory, id, TaskState::Waiting); + } + } + + fn cascade_note(&mut self, factory: &str, id: &str, stage: &str, now: UnixMs) { + self.env_failures + .retain(|(at, ..)| now.saturating_sub(*at) <= CASCADE_WINDOW_MS); + self.env_failures.push(( + now, + factory.to_owned(), + format!("task:{id}"), + stage.to_owned(), + )); + } + + /// Three different Tasks failing the same stage within 30 minutes is the + /// environment: their counts go back and new starts halt (B60). + fn reclassified_by_cascade(&mut self, factory: &str, id: &str) -> bool { + let now = self.now(); + let stage = self + .env_failures + .iter() + .rev() + .find(|(_, f, t, _)| f == factory && *t == format!("task:{id}")) + .map(|(_, _, _, s)| s.clone()); + let Some(stage) = stage else { return false }; + let tasks: BTreeSet = self + .env_failures + .iter() + .filter(|(at, f, t, s)| { + now.saturating_sub(*at) <= CASCADE_WINDOW_MS + && f == factory + && *s == stage + && t.starts_with("task:") + }) + .map(|(_, _, t, _)| t.trim_start_matches("task:").to_owned()) + .collect(); + if tasks.len() < 3 { + return false; + } + for task in &tasks { + self.with_task(factory, task, |t| { + t.failures = t.failures.saturating_sub(1); + }); + if self.task(factory, task).is_some_and(|t| { + matches!( + t.state, + TaskState::Running | TaskState::Verifying | TaskState::Stopped + ) + }) { + self.put_to_sleep(factory, task); + self.set_state(factory, task, TaskState::Waiting); + } + } + self.env_failures + .retain(|(_, f, t, s)| !(f == factory && *s == stage && t.starts_with("task:"))); + self.halt_until = Some(now + CASCADE_WINDOW_MS); + self.env_problem_since.get_or_insert(now); + self.record( + factory, + None, + "environment.cascade", + json!({"stage": stage, "tasks": tasks.len()}), + ); + true + } + + /// Code handles each structured signal first (D-31, Q40, B58, B59). + fn external_failure(&mut self, factory: &str, task: Option<&str>, failure: &Failure) { + self.record( + factory, + task, + "external.failed", + json!({"stage": failure.stage, "signal": failure.signal.map(EnvSignal::as_str)}), + ); + let now = self.now(); + let Some(signal) = failure.signal else { return }; + self.env_problem_since.get_or_insert(now); + let anchor = task + .map(str::to_owned) + .or_else(|| self.tasks_of(factory).last().map(|t| t.id.clone())); + match signal { + EnvSignal::GithubRateLimit | EnvSignal::GithubServer | EnvSignal::Network => { + let (attempts, _) = self.github_backoff.get(factory).copied().unwrap_or((0, 0)); + let wait = BACKOFF_MS[(attempts as usize).min(BACKOFF_MS.len() - 1)]; + self.github_backoff + .insert(factory.to_owned(), (attempts + 1, now + wait)); + } + EnvSignal::GithubAuth => { + if let Some(anchor) = anchor { + self.once_notice( + factory, + &anchor, + "GitHub 로그인이 풀렸습니다. gh auth login 으로 다시 로그인하세요.", + ); + } + } + EnvSignal::GithubForbidden => { + if let Some(anchor) = anchor { + let scope = failure + .missing_scope + .clone() + .unwrap_or_else(|| "repo".into()); + self.once_notice( + factory, + &anchor, + &format!( + "GitHub 권한이 모자라 {}을 하지 않았습니다. gh auth refresh -s {scope}", + failure.stage + ), + ); + } + } + EnvSignal::DiskFull => { + self.hold_reason = Some("디스크 부족".into()); + self.hold_checked_at = Some(now); + self.remove_finished_worktrees(); + } + EnvSignal::OutOfMemory => { + if let Some(task) = task + && self.task(factory, task).is_some_and(|t| { + matches!(t.state, TaskState::Running | TaskState::Verifying) + }) + { + self.set_state(factory, task, TaskState::Waiting); + } + } + EnvSignal::HerdrSocket => { + // Reconnect is the adapter's; the worker restarts in the same + // worktree and session at its next start. + if let Some(task) = task + && self + .task(factory, task) + .is_some_and(|t| t.state == TaskState::Running) + { + self.set_state(factory, task, TaskState::Waiting); + } + } + EnvSignal::UsageLimit => { + let runtime = task + .and_then(|t| self.task(factory, t)) + .and_then(|t| t.worker.as_ref().map(|w| w.runtime)); + if let Some(runtime) = runtime { + self.runtime_blocked + .insert(runtime, failure.reset_at.unwrap_or(now + HOUR_MS)); + } + if let Some(task) = task + && self + .task(factory, task) + .is_some_and(|t| t.state == TaskState::Running) + { + self.set_state(factory, task, TaskState::Waiting); + } + } + } + } + + fn once_notice(&mut self, factory: &str, id: &str, text: &str) { + let exists = self + .task(factory, id) + .is_some_and(|t| t.open_questions().any(|q| q.text == text)); + if !exists { + self.notice(factory, id, text); + } + } + + /// D-54 ①: only worktrees of finished Tasks and of cancelled Tasks past + /// their keep period (B62). + fn remove_finished_worktrees(&mut self) { + let now = self.now(); + let targets: Vec<(String, String, WorkerRef)> = self + .all_tasks() + .filter(|t| !t.purged) + .filter(|t| { + let keep = self + .factories + .get(&t.factory) + .map_or(7 * DAY_MS, |f| f.config.cancel_keep_ms); + t.state == TaskState::Done + || (t.state == TaskState::Cancelled + && t.cancelled_at + .is_some_and(|at| now.saturating_sub(at) > keep)) + }) + .filter_map(|t| { + t.worker + .clone() + .map(|w| (t.factory.clone(), t.id.clone(), w)) + }) + .collect(); + for (factory, id, worker) in targets { + match self.ports.workers.remove_worktree(&worker) { + Ok(()) => { + self.with_task(&factory, &id, |t| t.purged = true); + self.record(&factory, Some(&id), "cleanup.worktree", json!({})); + } + Err(failure) => self.record( + &factory, + Some(&id), + "cleanup.failed", + json!({"stage": failure.stage}), + ), + } + } + } + + fn environment_recovery(&mut self) { + let now = self.now(); + let Some(since) = self.env_problem_since else { + return; + }; + let still = self.hold_reason.is_some() || self.halt_until.is_some_and(|u| u > now); + if !still { + self.env_problem_since = None; + self.env_diagnosed = false; + return; + } + if self.env_diagnosed || now.saturating_sub(since) < CASCADE_WINDOW_MS { + return; + } + // Not cleared in 30 minutes: a judgment diagnoses (B61). + let Some(factory) = self.factories.values().find(|f| !f.closed).cloned() else { + return; + }; + self.env_diagnosed = true; + let facts = json!({ + "hold": self.hold_reason, + "halted": self.halt_until.is_some_and(|u| u > now), + "recent_failures": self.env_failures.iter().map(|(_, _, t, s)| json!({"task": t, "stage": s})).collect::>(), + "disk_free": self.ports.environment.disk_free(&factory.project), + }); + let judgment = Judgment { + id: format!("{}:env:{now}", factory.id), + factory: factory.id.clone(), + task: None, + priority: Priority::Factory, + input: JudgmentInput::EnvDiagnosis { + facts, + actions: RecoveryAction::ALL.to_vec(), + }, + }; + if self.ports.judge.submit(judgment.clone()).is_ok() { + self.judgments + .insert(judgment.id, (factory.id.clone(), None, Purpose::Env)); + } + } + + fn apply_diagnosis(&mut self, factory: &str, value: &Value) { + let Ok(diagnosis) = judgment::parse_env(value) else { + return; + }; + let enabled = self + .factories + .get(factory) + .map(|f| f.config.recovery.clone()) + .unwrap_or_default(); + let anchor = self.tasks_of(factory).last().map(|t| t.id.clone()); + match diagnosis.action { + Some(action) if enabled.contains(&action) => { + self.record( + factory, + None, + "recovery.run", + json!({"action": action.as_str()}), + ); + match action { + RecoveryAction::RemoveFinishedWorktrees => self.remove_finished_worktrees(), + RecoveryAction::RetryReadsAndReconnect => { + self.github_backoff.clear(); + self.hold_reason = None; + } + RecoveryAction::RestartWorker + | RecoveryAction::SleepWakeWorker + | RecoveryAction::SwitchRuntime => { + self.runtime_blocked.clear(); + } + } + } + Some(action) => { + if let Some(anchor) = anchor { + self.add_question( + factory, + &anchor, + QuestionOrigin::Engine, + QuestionKind::Proposal { + command: action.as_str().into(), + impact: diagnosis.cause.clone(), + }, + &format!( + "환경 문제: {}. 복구 동작 {}을 실행할까요?", + diagnosis.cause, + action.as_str() + ), + "approve", + None, + None, + vec!["approve".into(), "dismiss".into()], + None, + ); + } + } + None => { + if let (Some(anchor), Some((command, impact))) = (anchor, diagnosis.proposal) { + self.add_question( + factory, + &anchor, + QuestionOrigin::Engine, + QuestionKind::Proposal { + command: command.clone(), + impact: impact.clone(), + }, + &format!( + "환경 문제: {}. 사람이 실행할 명령: {command} (영향: {impact})", + diagnosis.cause + ), + "run it yourself", + None, + None, + vec!["done".into(), "dismiss".into()], + None, + ); + } + } + } + } + + // -------------------------------------------------------------------- watch + + fn watch_due(&mut self, factory_id: &str, event: bool) { + let now = self.now(); + let Some(factory) = self.factories.get(factory_id).cloned() else { + return; + }; + if factory.closed || self.tasks_of(factory_id).next().is_none() { + return; + } + let interval_due = factory + .watch_last_at + .is_none_or(|at| now.saturating_sub(at) >= factory.config.watch_interval_ms); + if !event && !interval_due { + return; + } + let board = serde_json::to_value(summary::build( + &[&factory], + &self.tasks_of(factory_id).collect::>(), + now, + )) + .unwrap_or_default(); + let judgment = Judgment { + id: format!("{factory_id}:watch:{now}"), + factory: factory_id.to_owned(), + task: None, + priority: Priority::Factory, + input: JudgmentInput::Watch { board }, + }; + if let Some(f) = self.factories.get_mut(factory_id) { + f.watch_last_at = Some(now); + } + self.save_factory(factory_id); + if self.ports.judge.submit(judgment.clone()).is_ok() { + self.judgments + .insert(judgment.id, (factory_id.to_owned(), None, Purpose::Watch)); + } + } + + fn apply_watch(&mut self, factory_id: &str, value: &Value) { + let Ok(warnings) = judgment::parse_watch(value) else { + return; + }; + let now = self.now(); + let today = now / DAY_MS; + for warning in warnings { + let Some(action) = warning.action.clone() else { + // No action to take: the log only (B69). + self.record( + factory_id, + warning.task.as_deref(), + "watch.logged", + json!({}), + ); + continue; + }; + let (limit, sent) = { + let Some(f) = self.factories.get_mut(factory_id) else { + return; + }; + if f.watch_day != today { + f.watch_day = today; + f.watch_sent_today = 0; + } + (f.config.watch_daily_limit, f.watch_sent_today) + }; + if sent >= limit { + self.record(factory_id, None, "watch.capped", json!({})); + continue; + } + let anchor = warning + .task + .clone() + .and_then(|t| self.resolve(&Role::Engine, &t).ok().map(|(_, id)| id)) + .or_else(|| self.tasks_of(factory_id).last().map(|t| t.id.clone())); + let Some(anchor) = anchor else { continue }; + self.add_question( + factory_id, + &anchor, + QuestionOrigin::Engine, + QuestionKind::Notice, + &format!("감시: {} (할 일: {action})", warning.text), + &action, + None, + None, + vec!["ok".into()], + None, + ); + if let Some(f) = self.factories.get_mut(factory_id) { + f.watch_sent_today += 1; + } + self.save_factory(factory_id); + } + } + + // --------------------------------------------------------------- retention + + fn retention(&mut self) { + let now = self.now(); + let expired: Vec<(String, String)> = self + .all_tasks() + .filter(|t| t.state == TaskState::Cancelled && !t.purged) + .filter(|t| { + let keep = self + .factories + .get(&t.factory) + .map_or(7 * DAY_MS, |f| f.config.cancel_keep_ms); + t.cancelled_at + .is_some_and(|at| now.saturating_sub(at) > keep) + }) + .map(|t| (t.factory.clone(), t.id.clone())) + .collect(); + for (factory, id) in expired { + if let Some(worker) = self.task(&factory, &id).and_then(|t| t.worker.clone()) + && let Err(failure) = self.ports.workers.remove_worktree(&worker) + { + self.record( + &factory, + Some(&id), + "cleanup.failed", + json!({"stage": failure.stage}), + ); + continue; + } + self.with_task(&factory, &id, |t| t.purged = true); + self.record(&factory, Some(&id), "cleanup.cancelled", json!({})); + } + } +} + +fn with_letter(command: Command, letter: &str) -> Option { + let letter = Some(letter.to_owned()); + Some(match command { + Command::Ask { + text, + suggestion, + default_action, + deadline_hours, + .. + } => Command::Ask { + text, + suggestion, + default_action, + deadline_hours, + letter, + }, + Command::Block { + text, + suggestion, + deadline_hours, + .. + } => Command::Block { + text, + suggestion, + deadline_hours, + letter, + }, + Command::Propose { + class, + text, + card, + autonomy, + reclassify, + .. + } => Command::Propose { + class, + text, + card, + autonomy, + reclassify, + letter, + }, + Command::Done { + summary, breaking, .. + } => Command::Done { + summary, + breaking, + letter, + }, + Command::Decide { text } => Command::Decide { text }, + Command::Dep { + task, + on, + remove: false, + } => Command::Dep { + task, + on, + remove: false, + }, + _ => return None, + }) +} + +/// A letter from a harness that follows the Observer protocol only (B25). +fn plain_letter(letter: &Inbound) -> Option { + let body = letter.body.trim(); + let suggestion = body + .lines() + .find_map(|line| { + let lower = line.to_lowercase(); + ["recommendation:", "suggestion:", "추천:", "제안:"] + .iter() + .find(|prefix| lower.trim_start().starts_with(*prefix)) + .map(|prefix| line.trim_start()[prefix.len()..].trim().to_owned()) + }) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "(질문 본문을 보세요)".to_owned()); + match letter.kind.as_str() { + "block" | "request" => Some(Command::Block { + text: judgment::cut(body, TEXT_LIMIT), + suggestion, + deadline_hours: Some(24), + letter: Some(letter.id.clone()), + }), + "report" => Some(Command::Done { + summary: Some(judgment::cut(body, TEXT_LIMIT)), + breaking: false, + letter: Some(letter.id.clone()), + }), + _ => None, + } +} + +fn parse_signal(value: &str) -> Option { + [ + EnvSignal::DiskFull, + EnvSignal::OutOfMemory, + EnvSignal::GithubAuth, + EnvSignal::GithubForbidden, + EnvSignal::GithubRateLimit, + EnvSignal::GithubServer, + EnvSignal::Network, + EnvSignal::HerdrSocket, + EnvSignal::UsageLimit, + ] + .into_iter() + .find(|signal| signal.as_str() == value) +} + +pub fn parse_issue(text: &str, source: SourceKind) -> Option { + let text = text.trim(); + if let Some(number) = text.strip_prefix("L-").and_then(|n| n.parse().ok()) { + return Some(IssueRef::Local { number }); + } + let number: u64 = text.trim_start_matches('#').parse().ok()?; + match source { + SourceKind::Github => Some(IssueRef::Github { number }), + SourceKind::Local => u32::try_from(number) + .ok() + .map(|number| IssueRef::Local { number }), + } +} + +fn source_name(source: SourceKind) -> &'static str { + match source { + SourceKind::Github => "github", + SourceKind::Local => "local", + } +} + +fn extract_criteria(body: &str) -> Vec { + body.lines() + .map(str::trim) + .filter_map(|line| { + line.strip_prefix("- [ ]") + .or_else(|| line.strip_prefix("- [x]")) + }) + .map(|line| line.trim().to_owned()) + .filter(|line| !line.is_empty()) + .take(LIST_LIMIT) + .collect() +} + +fn repo_context(project: &str) -> (Vec, Option) { + let mut files = Vec::new(); + if let Ok(entries) = std::fs::read_dir(project) { + for entry in entries.flatten().take(200) { + let name = entry.file_name().to_string_lossy().into_owned(); + if name.starts_with('.') && name != ".github" { + continue; + } + files.push(name); + } + } + files.sort(); + let guide = ["AGENTS.md", "CLAUDE.md", "README.md"] + .iter() + .find_map(|name| std::fs::read_to_string(Path::new(project).join(name)).ok()) + .map(|text| judgment::cut(&text, 8 * 1024)); + (files, guide) +} + +/// The marker that lets an issue write converge on retry (B73). +pub fn task_marker(factory: &Factory, task: &Task) -> String { + format!("", factory.id, task.id) +} + +pub fn issue_body(task: &Task, factory: &Factory) -> String { + let mut body = format!( + "{}\n\n## 목표\n{}\n\n## 완료 조건\n", + task_marker(factory, task), + task.card.goal + ); + for criterion in &task.card.criteria { + body.push_str(&format!("- [ ] {criterion}\n")); + } + if !task.card.out_of_scope.is_empty() { + body.push_str("\n## 범위 밖\n"); + for item in &task.card.out_of_scope { + body.push_str(&format!("- {item}\n")); + } + } + if factory.config.prd_in_issue + && let Some(text) = task + .attachments + .last() + .and_then(|a| std::fs::read_to_string(&a.path).ok()) + { + body.push_str("\n## PRD\n"); + body.push_str(&judgment::cut(&text, 48 * 1024)); + } + body +} + +pub fn pr_body(task: &Task, factory: &Factory) -> String { + let mut body = issue_body(task, factory); + if !task.decisions.is_empty() { + body.push_str("\n## 결정 기록\n"); + for decision in &task.decisions { + body.push_str(&format!("- {}\n", decision.text)); + } + } + match &task.issue { + Some(IssueRef::Github { number }) => body.push_str(&format!("\nCloses #{number}\n")), + Some(IssueRef::Local { number }) => body.push_str(&format!("\nCloses L-{number}\n")), + None => {} + } + body +} + +fn worker_name(factory: &Factory, task: &Task) -> String { + let name: String = factory + .project_name + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-') + .take(16) + .collect(); + format!( + "factory-{}-{}", + if name.is_empty() { "p" } else { &name }, + task.id.to_ascii_lowercase() + ) +} + +/// The worker's first prompt (B22): the card, the attachments, the harness +/// preset and the Factory's reporting rules. +pub fn worker_prompt(task: &Task, factory: &Factory, resumed: bool) -> String { + let mut prompt = String::new(); + if resumed { + prompt.push_str("Factory: 같은 worktree에서 이 Task를 이어서 맡습니다. 지금까지 한 일을 확인하고 이어가세요.\n\n"); + } + prompt.push_str(&format!( + "당신은 Software Factory의 worker입니다. Task {}: {}\n\n", + task.display_id(), + task.card.title + )); + prompt.push_str(&format!("목표:\n{}\n\n완료 조건:\n", task.card.goal)); + for criterion in &task.card.criteria { + prompt.push_str(&format!("- {criterion}\n")); + } + if !task.card.out_of_scope.is_empty() { + prompt.push_str("\n범위 밖 (하지 마세요):\n"); + for item in &task.card.out_of_scope { + prompt.push_str(&format!("- {item}\n")); + } + } + for attachment in &task.attachments { + prompt.push_str(&format!("\n첨부 (읽기 전용): {}\n", attachment.path)); + } + if let Some(harness) = &factory.config.harness { + prompt.push_str(&format!( + "\n일하는 방식 ({}):\n{}\n", + harness.name, harness.instructions + )); + } + prompt.push_str(REPORTING_RULES); + prompt +} + +pub const REPORTING_RULES: &str = " +Factory 보고 규약 (반드시 지키세요): +- 이 worktree의 branch에 커밋하세요. main에 직접 push하거나 머지하지 마세요. 검증과 머지는 Factory가 합니다. +- 끝나면: hide factory done --summary '<무엇을 했는지>' [--breaking] (바로 '검증 중'이 오면 차례를 끝내세요. 결과는 편지로 옵니다) +- 기본 행동으로 계속할 수 있는 질문: hide factory ask --question '<질문>' --suggestion '<제안>' --default '<그동안 할 행동>' --deadline-hours 24 +- 답 없이는 진행할 수 없는 질문: hide factory block --question '<질문>' --suggestion '<제안>' --deadline-hours 24 (차례를 끝내세요) +- 작업 중 발견: hide factory propose --class in-scope|decision|scope-change|prerequisite|unrelated --text '<내용>' + 범위를 스스로 넓히지 마세요. 선행 작업은 prerequisite로 제안하고(--title --goal --criterion), 무관한 발견은 unrelated로 남기세요. +- 보고 없이 차례를 끝내면 Task가 멈춥니다. +"; diff --git a/hide-factory/src/lib.rs b/hide-factory/src/lib.rs index 803725e622..a992f19405 100644 --- a/hide-factory/src/lib.rs +++ b/hide-factory/src/lib.rs @@ -12,6 +12,7 @@ pub mod adapters; pub mod command; pub mod dag; +pub mod engine; pub mod judgment; pub mod model; pub mod role; @@ -19,6 +20,7 @@ pub mod store; pub mod summary; pub use command::{Command, Refusal}; +pub use engine::{Engine, Inbound, Ports}; pub use model::{Factory, Task, TaskState}; pub use role::Role; pub use summary::FactorySummary; diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs new file mode 100644 index 0000000000..853d0afdb2 --- /dev/null +++ b/hide-factory/tests/engine.rs @@ -0,0 +1,1506 @@ +//! The engine's rules, driven through its command, letter and tick entry +//! points over a recording fake world and an injected clock. + +mod support; + +use std::collections::BTreeMap; + +use hide_factory::Inbound; +use hide_factory::adapters::{ + EnvSignal, Failure, MainCheck, MemoryPressure, OutsideEvent, VerifyPoll, WorkerStatus, +}; +use hide_factory::command::{CardInput, Command, VerificationChoice}; +use hide_factory::model::*; +use serde_json::json; +use support::*; + +fn set_workers(h: &mut Bench, factory: &str, n: u32) { + let answer = h.op(Command::Config { + project: Some(PROJECT.into()), + set: vec![("max_workers".into(), n.to_string())], + }); + assert_eq!(answer["ok"], true, "{answer}"); + let _ = factory; +} + +/// Ticks until the Task reaches `state`, failing with its last state. +fn tick_until(h: &mut Bench, factory: &str, id: &str, state: TaskState) { + for _ in 0..20 { + if h.state(factory, id) == state { + return; + } + h.engine.tick(); + } + panic!( + "{id} never reached {state:?}; it is {:?}", + h.state(factory, id) + ); +} + +fn open_question(h: &Bench, factory: &str, id: &str) -> Question { + h.task(factory, id) + .open_questions() + .next() + .cloned() + .expect("an open question") +} + +// ------------------------------------------------------------------- init + +#[test] +fn init_previews_without_writing_and_creates_once_confirmed() { + let mut h = Bench::new(true); + let preview = h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: None, + confirm: false, + }); + assert_eq!(preview["preview"], true, "{preview}"); + assert!(h.world().writes.is_empty(), "a preview writes nothing"); + assert!(h.engine.factories().next().is_none()); + assert_eq!(preview["writes"], json!(["label factory"])); + + // Auto merge needs a verification (B2). + let refused = h.op(Command::Init { + project: PROJECT.into(), + verification: Some(VerificationChoice::None), + merge_mode: Some(MergeMode::Auto), + confirm: true, + }); + assert_eq!(refused["reason"], "auto_needs_verification", "{refused}"); + + let created = h.op(Command::Init { + project: PROJECT.into(), + verification: Some(VerificationChoice::Ci { + checks: vec!["test".into()], + }), + merge_mode: Some(MergeMode::Auto), + confirm: true, + }); + assert_eq!(created["created"], true, "{created}"); + assert_eq!(h.writes("label.create"), vec!["label.create factory"]); + + // The same project again shows the existing Factory (B5). + let again = h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: None, + confirm: true, + }); + assert_eq!(again["existing"], true, "{again}"); + assert_eq!(h.writes("label.create").len(), 1); +} + +#[test] +fn a_closed_factory_refuses_tasks_and_comes_back_with_its_records() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Keep me", &[]); + // Not while a Task runs (B74). + assert_eq!(h.state(&f, &t), TaskState::Running); + let refused = h.op(Command::Close { project: None }); + assert_eq!(refused["reason"], "factory_has_running_tasks", "{refused}"); + h.op(Command::Cancel { task: t.clone() }); + let closed = h.op(Command::Close { project: None }); + assert_eq!(closed["ok"], true, "{closed}"); + let refused = h.add("New", &[]); + assert_eq!(refused["reason"], "factory_closed", "{refused}"); + + let reopened = h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: None, + confirm: true, + }); + assert_eq!(reopened["reopened"], true, "{reopened}"); + assert_eq!(h.task(&f, &t).card.title, "Keep me"); +} + +// -------------------------------------------------------------------- add + +#[test] +fn a_card_missing_its_shape_is_refused_with_each_field() { + let mut h = Bench::new(false); + let f = h.factory(true); + let answer = h.add_card(CardInput { + title: Some("only a title".into()), + ..CardInput::default() + }); + assert_eq!(answer["reason"], "card_invalid", "{answer}"); + let fields: Vec<&str> = answer["detail"]["fields"] + .as_array() + .unwrap() + .iter() + .map(|field| field["field"].as_str().unwrap()) + .collect(); + assert_eq!(fields, vec!["goal", "criteria"]); + + let answer = h.add("Depends on nothing real", &["T-9"]); + assert_eq!(answer["reason"], "card_invalid", "{answer}"); + assert!( + h.engine.tasks_of(&f).next().is_none(), + "a refused card creates no Task" + ); +} + +#[test] +fn a_dependency_that_closes_a_loop_is_refused_with_its_path() { + let mut h = Bench::new(false); + let f = h.factory(true); + set_workers(&mut h, &f, 1); + h.world().hold_judgments = true; + let a = h.add("A", &[])["task"]["id"].as_str().unwrap().to_owned(); + let b = h.add("B", &[&a])["task"]["id"].as_str().unwrap().to_owned(); + let c = h.add("C", &[&b])["task"]["id"].as_str().unwrap().to_owned(); + let refused = h.op(Command::Dep { + task: a.clone(), + on: c.clone(), + remove: false, + }); + assert_eq!(refused["reason"], "dependency_cycle", "{refused}"); + assert_eq!(refused["detail"]["cycle"], json!([c, b, a])); +} + +#[test] +fn a_review_that_cannot_run_keeps_the_task_drafting_and_asks_for_the_provider() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().judge_down = true; + let answer = h.add("Needs review", &[]); + let id = answer["task"]["id"].as_str().unwrap().to_owned(); + assert_eq!(answer["result"], "pending", "{answer}"); + h.engine.tick(); + assert_eq!(h.state(&f, &id), TaskState::Drafting, "never skipped (B19)"); + let inbox = h.op(Command::Inbox); + assert!( + inbox["items"][0]["text"] + .as_str() + .unwrap() + .contains("Background AI"), + "{inbox}" + ); + + h.world().judge_down = false; + let question = open_question(&h, &f, &id); + h.op(Command::Answer { + task: id.clone(), + question: Some(question.id), + choice: Some("retry-review".into()), + text: None, + }); + h.engine.tick(); + assert_ne!(h.state(&f, &id), TaskState::Drafting); +} + +#[test] +fn review_questions_hold_the_task_until_answered_and_re_adding_is_idempotent() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().intake.insert( + "Vague".into(), + json!({"questions": [{"text": "Which API?", "suggestion": "REST"}], "dependencies": [], "flags": [], "split": []}), + ); + let id = h.add("Vague", &[])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + h.engine.tick(); + assert_eq!(h.engine.add_answer(&f, &id)["result"], "needs_answers"); + assert_eq!(h.state(&f, &id), TaskState::Drafting); + + // The same card again: still one Task (B9, B73). + let again = h.op(Command::Add { + project: None, + task: Some(id.clone()), + issue: None, + card: card("Vague", &[]), + producer_pane: None, + }); + assert_eq!(again["task"]["id"], id.as_str()); + assert_eq!(h.engine.tasks_of(&f).count(), 1); + + let question = open_question(&h, &f, &id); + h.op(Command::Answer { + task: id.clone(), + question: Some(question.id), + choice: Some("suggestion".into()), + text: None, + }); + assert_eq!(h.task(&f, &id).issue, Some(IssueRef::Local { number: 1 })); + assert_ne!(h.state(&f, &id), TaskState::Drafting); + assert_eq!(h.writes("issue.create").len(), 1); +} + +// --------------------------------------------------------------------- DAG + +/// Six Tasks with a fork and a join run in topological order with at most +/// two workers, and each starts only after its predecessors merged (B20, B21). +#[test] +fn a_six_task_graph_runs_in_dependency_order_within_the_slot_cap() { + let mut h = Bench::new(false); + let f = h.factory(true); + set_workers(&mut h, &f, 2); + h.world().hold_judgments = true; + let t1 = h.add("Root", &[])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let t2 = h.add("Left", &[&t1])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let t3 = h.add("Right", &[&t1])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let t4 = h.add("Join", &[&t2, &t3])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let t5 = h.add("Alone", &[])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let t6 = h.add("Last", &[&t4])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + h.world().hold_judgments = false; + + let mut starts: Vec = Vec::new(); + let mut max_running = 0; + let mut concurrent = false; + for _ in 0..60 { + h.engine.tick(); + let running: Vec = h + .engine + .tasks_of(&f) + .filter(|task| task.state == TaskState::Running) + .map(|task| task.id.clone()) + .collect(); + max_running = max_running.max(running.len()); + concurrent |= running.len() == 2; + for id in &running { + if !starts.contains(id) { + starts.push(id.clone()); + } + h.done(&f, id); + } + if h.engine + .tasks_of(&f) + .all(|task| task.state == TaskState::Done) + { + break; + } + } + assert!( + h.engine + .tasks_of(&f) + .all(|task| task.state == TaskState::Done), + "every Task finished" + ); + assert_eq!(max_running, 2, "never more than the slot cap"); + assert!(concurrent, "independent Tasks ran together"); + let merges: Vec = h + .writes("merge ") + .iter() + .map(|w| w.trim_start_matches("merge ").to_owned()) + .collect(); + assert_eq!(merges.len(), 6, "each Task merged exactly once: {merges:?}"); + let merged_at = |id: &str| merges.iter().position(|m| m == id).unwrap(); + let started_at = |id: &str| h.world().spawned.iter().position(|s| s.task == id).unwrap(); + for (task, predecessors) in [ + (&t2, vec![&t1]), + (&t3, vec![&t1]), + (&t4, vec![&t2, &t3]), + (&t6, vec![&t4]), + ] { + for predecessor in predecessors { + assert!( + merged_at(predecessor) < merged_at(task), + "{predecessor} merges before {task}" + ); + assert!(started_at(predecessor) < started_at(task)); + } + } + // Priority equal: oldest first; the root and the lone Task go first. + assert_eq!(&starts[..2], &[t1.clone(), t5.clone()]); + assert_eq!(h.world().spawned.len(), 6, "one worker per Task"); +} + +#[test] +fn a_dependent_starts_only_after_its_predecessor_merged_not_when_it_is_verifying() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("A", &[]); + let b = h.ready("B", &[&a]); + assert_eq!(h.state(&f, &b), TaskState::Waiting); + h.world() + .verify + .insert(a.clone(), [VerifyPoll::Pending, VerifyPoll::Pending].into()); + h.done(&f, &a); + h.engine.tick(); + assert_eq!(h.state(&f, &a), TaskState::Verifying); + assert_eq!( + h.state(&f, &b), + TaskState::Waiting, + "verifying is not merged" + ); + let card = h.engine.summary().factories[0].columns[1].cards.clone(); + assert_eq!(card[0].waiting_for.as_deref(), Some("L-1")); + tick_until(&mut h, &f, &a, TaskState::Done); + tick_until(&mut h, &f, &b, TaskState::Running); +} + +#[test] +fn slots_go_by_priority_then_age_across_factories() { + let mut h = Bench::new(false); + let f1 = h.factory(true); + let f2 = h.factory_at("/work/other", true); + set_workers(&mut h, &f1, 1); + h.world().hold_judgments = true; + let old = h.add("Old", &[])["task"]["id"].as_str().unwrap().to_owned(); + h.advance(MINUTE_MS); + let answer = h.op(Command::Add { + project: Some("/work/other".into()), + task: None, + issue: None, + card: CardInput { + priority: Some(5), + ..card("Urgent elsewhere", &[]) + }, + producer_pane: None, + }); + let urgent = answer["task"]["id"].as_str().unwrap().to_owned(); + h.world().hold_judgments = false; + h.engine.tick(); + assert_eq!(h.state(&f2, &urgent), TaskState::Running); + assert_eq!(h.state(&f1, &old), TaskState::Waiting); + h.done(&f2, &urgent); + tick_until(&mut h, &f1, &old, TaskState::Running); +} + +// ------------------------------------------------------------- worker reports + +#[test] +fn a_question_with_a_default_waits_only_before_merge_and_the_deadline_applies_it() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Asks", &[]); + let answer = h.as_worker( + &f, + &t, + Command::Ask { + text: "Name the flag?".into(), + suggestion: "--fast".into(), + default_action: "use --fast".into(), + deadline_hours: Some(24), + letter: None, + }, + ); + assert_eq!(answer["ok"], true, "{answer}"); + assert_eq!( + h.state(&f, &t), + TaskState::Running, + "the worker keeps going (B26)" + ); + h.done(&f, &t); + for _ in 0..5 { + h.engine.tick(); + } + assert_eq!( + h.state(&f, &t), + TaskState::Verifying, + "merge waits for the answer or the deadline" + ); + assert!(h.writes("merge").is_empty()); + h.advance(24 * HOUR_MS); + tick_until(&mut h, &f, &t, TaskState::Done); + let question = &h.task(&f, &t).questions[0]; + assert_eq!(question.answer.as_ref().unwrap().relayed_by, "deadline"); +} + +#[test] +fn a_different_answer_before_the_deadline_sends_the_worker_back() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Asks", &[]); + h.as_worker( + &f, + &t, + Command::Ask { + text: "Name the flag?".into(), + suggestion: "--fast".into(), + default_action: "use --fast".into(), + deadline_hours: Some(24), + letter: None, + }, + ); + h.done(&f, &t); + h.engine.tick(); + let question = open_question(&h, &f, &t); + h.op(Command::Answer { + task: t.clone(), + question: Some(question.id), + choice: None, + text: Some("use --quick".into()), + }); + assert_eq!(h.state(&f, &t), TaskState::Running); + assert!( + h.world() + .wakes + .iter() + .any(|(task, body)| *task == t && body.contains("--quick")) + ); +} + +#[test] +fn a_question_needs_a_suggestion_and_a_deadline() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Asks", &[]); + let refused = h.as_worker( + &f, + &t, + Command::Block { + text: "Which?".into(), + suggestion: " ".into(), + deadline_hours: Some(24), + letter: None, + }, + ); + assert_eq!(refused["reason"], "suggestion_required", "{refused}"); + let refused = h.as_worker( + &f, + &t, + Command::Block { + text: "Which?".into(), + suggestion: "this one".into(), + deadline_hours: None, + letter: None, + }, + ); + assert_eq!(refused["reason"], "deadline_required", "{refused}"); + assert!(h.task(&f, &t).questions.is_empty()); +} + +#[test] +fn a_blocking_question_releases_the_slot_and_the_answer_wakes_the_same_session() { + let mut h = Bench::new(false); + let f = h.factory(true); + set_workers(&mut h, &f, 1); + let blocked = h.ready("Blocks", &[]); + let other = h.ready("Other", &[]); + assert_eq!(h.state(&f, &other), TaskState::Waiting); + h.as_worker( + &f, + &blocked, + Command::Block { + text: "Which database?".into(), + suggestion: "sqlite".into(), + deadline_hours: Some(24), + letter: Some("letter-7".into()), + }, + ); + assert_eq!(h.state(&f, &blocked), TaskState::Blocked); + assert!(h.world().sleeps.contains(&blocked)); + h.engine.tick(); + assert_eq!( + h.state(&f, &other), + TaskState::Running, + "the slot went to the next Task" + ); + + // No automatic progress past the deadline; it rises as days waited. + h.advance(2 * DAY_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &blocked), TaskState::Blocked); + let inbox = h.op(Command::Inbox); + assert_eq!(inbox["items"][0]["remaining"], "2일째 기다림", "{inbox}"); + + let question = open_question(&h, &f, &blocked); + h.op(Command::Answer { + task: blocked.clone(), + question: Some(question.id), + choice: Some("suggestion".into()), + text: None, + }); + assert_eq!(h.state(&f, &blocked), TaskState::Waiting); + h.done(&f, &other); + tick_until(&mut h, &f, &blocked, TaskState::Running); + let spawned = h + .world() + .spawned + .iter() + .filter(|s| s.task == blocked) + .count(); + assert_eq!(spawned, 1, "the same session, not a new worker"); + assert!( + h.world() + .wakes + .iter() + .any(|(task, body)| *task == blocked && body.contains("sqlite")) + ); +} + +#[test] +fn verification_fails_count_toward_the_limit_and_then_stop_the_task() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Flaky", &[]); + let failed = || VerifyPoll::Failed { + check: "cargo test".into(), + link: "log".into(), + }; + h.world() + .verify + .insert(t.clone(), [failed(), failed(), failed()].into()); + for round in 1..=2 { + h.done(&f, &t); + h.engine.tick(); + assert_eq!( + h.state(&f, &t), + TaskState::Running, + "round {round} goes back to the worker" + ); + assert_eq!(h.task(&f, &t).failures, round); + let wake = h.world().wakes.last().cloned().unwrap(); + assert!(wake.1.contains(&format!("({round}/3)")), "{wake:?}"); + } + h.done(&f, &t); + h.engine.tick(); + let task = h.task(&f, &t); + assert_eq!( + (task.state, task.stop), + (TaskState::Stopped, Some(StopReason::VerifyFailed)) + ); + assert_eq!( + h.world().verify_runs.len(), + 3, + "a failure never runs again by itself (D-23)" + ); + let refused = h.op(Command::Merge { task: t.clone() }); + assert_eq!(refused["reason"], "action_not_allowed_in_state"); + assert_eq!( + refused["detail"]["allowed"], + json!(["answer", "retry", "cancel"]) + ); + h.op(Command::Retry { task: t.clone() }); + assert_eq!(h.task(&f, &t).failures, 0); + tick_until(&mut h, &f, &t, TaskState::Running); +} + +#[test] +fn an_environment_failure_is_not_counted_and_the_task_waits() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Unlucky", &[]); + h.world().verify.insert( + t.clone(), + [VerifyPoll::Environment { + signal: EnvSignal::Network, + check: "cargo test".into(), + }] + .into(), + ); + h.done(&f, &t); + h.engine.tick(); + let task = h.task(&f, &t); + assert_eq!(task.failures, 0); + assert_eq!(task.environment_failures, 1); + tick_until(&mut h, &f, &t, TaskState::Running); +} + +#[test] +fn three_tasks_failing_the_same_check_together_are_the_environment() { + let mut h = Bench::new(false); + let f = h.factory(true); + let ids: Vec = ["One", "Two", "Three"] + .iter() + .map(|t| h.ready(t, &[])) + .collect(); + for id in &ids { + h.world().verify.insert( + id.clone(), + [VerifyPoll::Failed { + check: "cargo test".into(), + link: "l".into(), + }] + .into(), + ); + h.done(&f, id); + } + h.engine.tick(); + for id in &ids { + let task = h.task(&f, id); + assert_eq!(task.failures, 0, "{id}: counts go back (B60)"); + assert_eq!(task.state, TaskState::Waiting, "{id}"); + } + h.engine.tick(); + assert!( + ids.iter().all(|id| h.state(&f, id) == TaskState::Waiting), + "new starts halt" + ); + h.advance(31 * MINUTE_MS); + h.engine.tick(); + assert!(ids.iter().all(|id| h.state(&f, id) == TaskState::Running)); +} + +#[test] +fn a_turn_ended_without_a_report_stops_the_task() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Quiet", &[]); + let since = h.world().now + MINUTE_MS; + h.world() + .worker_status + .insert(t.clone(), WorkerStatus::Resting { since }); + h.advance(2 * MINUTE_MS); + h.engine.tick(); + assert_eq!( + h.state(&f, &t), + TaskState::Running, + "one minute at rest is not yet two" + ); + h.advance(MINUTE_MS); + h.engine.tick(); + let task = h.task(&f, &t); + assert_eq!( + (task.state, task.stop), + (TaskState::Stopped, Some(StopReason::NoReport)) + ); +} + +#[test] +fn a_watch_inactivity_letter_about_a_worker_marks_it_stalled() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Stuck", &[]); + let pane = h.task(&f, &t).worker.unwrap().pane.unwrap(); + let answer = h.engine.letter(Inbound { + id: "w-1".into(), + factory: f.clone(), + sender_pane: pane, + kind: "watch".into(), + body: "no activity for 30 minutes".into(), + }); + assert_eq!(answer["ok"], true, "{answer}"); + assert_eq!(h.task(&f, &t).stop, Some(StopReason::Stalled)); +} + +#[test] +fn a_plain_letter_from_a_harness_becomes_a_blocking_question_once() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Bench", &[]); + let pane = h.task(&f, &t).worker.unwrap().pane.unwrap(); + let letter = Inbound { + id: "letter-1".into(), + factory: f.clone(), + sender_pane: pane.clone(), + kind: "block".into(), + body: "Should the API be versioned?\nRecommendation: yes, v1".into(), + }; + h.engine.letter(letter.clone()); + let duplicate = h.engine.letter(letter); + assert_eq!(duplicate["duplicate"], true); + let task = h.task(&f, &t); + assert_eq!(task.state, TaskState::Blocked); + assert_eq!(task.questions.len(), 1); + assert_eq!(task.questions[0].suggestion, "yes, v1"); + assert_eq!(task.questions[0].letter.as_deref(), Some("letter-1")); + + // A pane that is no Factory worker cannot report. + let refused = h.engine.letter(Inbound { + id: "x".into(), + factory: f, + sender_pane: "stranger".into(), + kind: "report".into(), + body: "done".into(), + }); + assert_eq!(refused["reason"], "sender_not_a_worker"); +} + +#[test] +fn a_worker_cannot_act_as_a_person() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Mine", &[]); + for command in [ + Command::Merge { task: t.clone() }, + Command::Answer { + task: t.clone(), + question: None, + choice: None, + text: Some("x".into()), + }, + Command::Config { + project: None, + set: vec![("merge_mode".into(), "manual".into())], + }, + Command::Cancel { task: t.clone() }, + ] { + let refused = h.as_worker(&f, &t, command); + assert_eq!(refused["reason"], "role_not_allowed", "{refused}"); + } + // An operator has no Task of its own to report on. + let refused = h.op(Command::Done { + summary: None, + breaking: false, + letter: None, + }); + assert_eq!(refused["reason"], "role_not_allowed"); +} + +// ---------------------------------------------------------------- discoveries + +#[test] +fn a_proposed_task_waits_for_a_person_and_its_worker_cannot_propose() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Parent", &[]); + let answer = h.as_worker( + &f, + &t, + Command::Propose { + class: DiscoveryClass::Prerequisite, + text: "needs a helper".into(), + card: Some(card("Helper", &[])), + autonomy: None, + reclassify: None, + letter: None, + }, + ); + assert_eq!(answer["task"], serde_json::Value::Null, "{answer}"); + assert_eq!( + h.engine.tasks_of(&f).count(), + 1, + "nothing starts without a person (B30)" + ); + let question = open_question(&h, &f, &t); + h.op(Command::Answer { + task: t.clone(), + question: Some(question.id), + choice: Some("approve".into()), + text: None, + }); + let child = h + .engine + .tasks_of(&f) + .find(|task| task.card.title == "Helper") + .unwrap() + .id + .clone(); + assert_eq!(h.task(&f, &child).proposed_by.as_deref(), Some(t.as_str())); + tick_until(&mut h, &f, &child, TaskState::Running); + let refused = h.as_worker( + &f, + &child, + Command::Propose { + class: DiscoveryClass::Prerequisite, + text: "and another".into(), + card: Some(card("Grandchild", &[])), + autonomy: None, + reclassify: None, + letter: None, + }, + ); + assert_eq!(refused["reason"], "proposal_depth_exceeded"); + + // Reclassifying away from a person is refused. + h.as_worker( + &f, + &t, + Command::Propose { + class: DiscoveryClass::Unrelated, + text: "odd log".into(), + card: None, + autonomy: None, + reclassify: None, + letter: None, + }, + ); + let discovery = h.task(&f, &t).discoveries.last().unwrap().id.clone(); + let refused = h.as_worker( + &f, + &t, + Command::Propose { + class: DiscoveryClass::InScope, + text: "odd log".into(), + card: None, + autonomy: None, + reclassify: Some(discovery), + letter: None, + }, + ); + assert_eq!( + refused["reason"], "reclassify_away_from_person", + "{refused}" + ); +} + +#[test] +fn an_enabled_autonomy_scope_starts_alone_and_the_third_new_task_stops_the_parent() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.op(Command::Config { + project: None, + set: vec![("autonomy".into(), "lint_format=on".into())], + }); + let t = h.ready("Parent", &[]); + for n in 1..=3 { + if h.state(&f, &t) != TaskState::Running { + h.op(Command::Resume { task: t.clone() }); + } + let answer = h.as_worker( + &f, + &t, + Command::Propose { + class: DiscoveryClass::Prerequisite, + text: format!("lint {n}"), + card: Some(card(&format!("Lint {n}"), &[])), + autonomy: Some("lint_format".into()), + reclassify: None, + letter: None, + }, + ); + assert_eq!(answer["ok"], true, "{answer}"); + let child = answer["task"].as_str().unwrap().to_owned(); + assert!( + h.task(&f, &t).card.depends_on.contains(&child), + "the parent waits on its prerequisite" + ); + if n < 3 { + // Run the prerequisite to completion so the parent runs again. + tick_until(&mut h, &f, &child, TaskState::Running); + h.done(&f, &child); + tick_until(&mut h, &f, &child, TaskState::Done); + tick_until(&mut h, &f, &t, TaskState::Running); + } + } + let task = h.task(&f, &t); + assert_eq!( + (task.state, task.stop), + (TaskState::Stopped, Some(StopReason::NewTaskCap)) + ); + assert!(matches!( + open_question(&h, &f, &t).kind, + QuestionKind::NewTaskCap + )); +} + +#[test] +fn an_autonomy_task_over_the_diff_limit_goes_to_a_person() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.op(Command::Config { + project: None, + set: vec![("autonomy".into(), "docs_links=on".into())], + }); + let t = h.ready("Parent", &[]); + let answer = h.as_worker( + &f, + &t, + Command::Propose { + class: DiscoveryClass::Prerequisite, + text: "fix links".into(), + card: Some(card("Links", &[])), + autonomy: Some("docs_links".into()), + reclassify: None, + letter: None, + }, + ); + let child = answer["task"].as_str().unwrap().to_owned(); + h.world().diff_lines = 500; + tick_until(&mut h, &f, &child, TaskState::Running); + h.done(&f, &child); + tick_until(&mut h, &f, &child, TaskState::MergeWaiting); + assert_eq!(h.task(&f, &child).gates, vec![Gate::AutonomyDiff]); +} + +// ---------------------------------------------------------------- GitHub path + +fn github_factory(h: &mut Bench, mode: MergeMode) -> String { + let created = h.op(Command::Init { + project: PROJECT.into(), + verification: Some(VerificationChoice::Ci { + checks: vec!["test".into()], + }), + merge_mode: Some(mode), + confirm: true, + }); + created["factory"]["id"].as_str().unwrap().to_owned() +} + +#[test] +fn a_manual_task_waits_for_merge_and_every_github_write_happens_once() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Manual); + let t = h.ready("Ship it", &[]); + assert_eq!(h.task(&f, &t).issue, Some(IssueRef::Github { number: 101 })); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + assert_eq!(h.task(&f, &t).gates, vec![Gate::ManualMode]); + let inbox = h.op(Command::Inbox); + assert_eq!(inbox["items"][0]["group"], "merge", "{inbox}"); + for _ in 0..5 { + h.engine.tick(); + } + let merged = h.op(Command::Merge { task: t.clone() }); + assert_eq!(merged["ok"], true, "{merged}"); + assert_eq!(h.state(&f, &t), TaskState::Done); + for _ in 0..5 { + h.engine.tick(); + } + assert_eq!( + h.world().writes, + vec![ + "label.create factory", + "issue.create T-1", + "pr.open T-1", + "merge T-1" + ], + ); + assert_eq!( + h.world().removed, + vec![t.clone()], + "worktree goes once main is green (B43)" + ); +} + +#[test] +fn human_gates_hold_an_auto_task_in_merge_waiting() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.add_card(CardInput { + review_directly: true, + ..card("Look at me", &[]) + })["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + h.engine.tick(); + let b = h.ready("Breaking", &[]); + h.done(&f, &t); + h.as_worker( + &f, + &b, + Command::Done { + summary: None, + breaking: true, + letter: None, + }, + ); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + tick_until(&mut h, &f, &b, TaskState::MergeWaiting); + assert_eq!(h.task(&f, &t).gates, vec![Gate::ReviewDirectly]); + assert_eq!(h.task(&f, &b).gates, vec![Gate::BreakingChange]); + let refused = h.op(Command::RequestChanges { + task: b.clone(), + comment: String::new(), + }); + assert_eq!(refused["reason"], "comment_required"); + h.op(Command::RequestChanges { + task: b.clone(), + comment: "keep the old name".into(), + }); + assert_eq!(h.state(&f, &b), TaskState::Running); +} + +#[test] +fn a_conflict_sends_the_worker_to_rebase_without_counting_a_failure() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Conflicts", &[]); + h.world().premerge.insert( + t.clone(), + [hide_factory::adapters::PreMerge::Conflict { + files: vec!["src/lib.rs".into()], + }] + .into(), + ); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::Running); + assert_eq!(h.task(&f, &t).failures, 0); + assert!(h.world().wakes.last().unwrap().1.contains("rebase")); +} + +#[test] +fn a_dirty_local_main_holds_the_merge() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Local", &[]); + h.world().main_dirty = true; + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + assert_eq!(h.task(&f, &t).gates, vec![Gate::DirtyMain]); + let refused = h.op(Command::Merge { task: t.clone() }); + assert_eq!(refused["reason"], "main_dirty"); + h.world().main_dirty = false; + let merged = h.op(Command::Merge { task: t.clone() }); + assert_eq!(merged["ok"], true, "{merged}"); +} + +// ------------------------------------------------------------- main breaks + +#[test] +fn a_broken_main_reverts_only_the_first_failing_merge_and_the_task_lands_again() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("A", &[]); + let b = h.ready("B", &[]); + { + let mut world = h.world(); + world + .main_checks + .insert("sha0001-T-1".into(), MainCheck::Pending); + world.main_checks.insert( + "sha0002-T-2".into(), + MainCheck::Red { + link: "run/2".into(), + }, + ); + } + h.done(&f, &a); + h.done(&f, &b); + tick_until(&mut h, &f, &b, TaskState::Landed); + h.engine.tick(); + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.main.broken, "one red run stops auto merge (B44)"); + assert_eq!( + h.writes("main.rerun"), + vec!["main.rerun sha0001-T-1"], + "the pending run is asked again once" + ); + assert!( + h.writes("revert").is_empty(), + "no revert before the culprit is known" + ); + + // A third Task verified meanwhile does not merge. + let c = h.ready("C", &[]); + h.done(&f, &c); + h.engine.tick(); + h.engine.tick(); + assert!(h.writes("merge T-3").is_empty()); + + h.world() + .main_checks + .insert("sha0001-T-1".into(), MainCheck::Green); + tick_until(&mut h, &f, &b, TaskState::Running); + assert_eq!( + h.writes("revert"), + vec!["revert.open T-2", "revert.merge T-2"] + ); + assert_eq!(h.state(&f, &a), TaskState::Done); + assert!( + h.world() + .wakes + .iter() + .any(|(task, body)| *task == b && body.contains("revert")) + ); + assert_eq!( + h.world().spawned.iter().filter(|s| s.task == b).count(), + 1, + "the same Task, no new one (B46)" + ); + tick_until(&mut h, &f, &c, TaskState::Done); + h.done(&f, &b); + tick_until(&mut h, &f, &b, TaskState::Done); + assert_eq!(h.writes("merge T-2").len(), 2); +} + +#[test] +fn an_undecidable_revert_stops_for_a_person() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("A", &[]); + h.world().main_checks.insert( + "sha0001-T-1".into(), + MainCheck::Red { + link: "run/1".into(), + }, + ); + h.world().revert_check = Some(MainCheck::Red { + link: "run/r".into(), + }); + h.done(&f, &a); + tick_until(&mut h, &f, &a, TaskState::Landed); + h.engine.tick(); + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.main.needs_person, "B48"); + let question = h + .task(&f, &a) + .open_questions() + .find(|q| matches!(q.kind, QuestionKind::Action)) + .cloned() + .unwrap(); + assert!(question.choices.contains(&"revert T-1".to_owned())); +} + +#[test] +fn an_outside_push_that_breaks_main_drafts_a_fix_and_never_reverts() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.engine.tick(); + { + let mut world = h.world(); + world.head = "outside1".into(); + world.main_checks.insert( + "outside1".into(), + MainCheck::Red { + link: "run/9".into(), + }, + ); + } + h.advance(3 * MINUTE_MS); + h.engine.tick(); + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.main.broken); + let fix = h.engine.tasks_of(&f).next().unwrap().clone(); + assert_eq!(fix.state, TaskState::Drafting, "a draft a person confirms"); + assert!(h.writes("revert").is_empty()); + + h.world() + .main_checks + .insert("outside1".into(), MainCheck::Green); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert!( + !h.engine.factories().next().unwrap().main.broken, + "green again resumes auto merge" + ); +} + +// ------------------------------------------------------------- outside work + +#[test] +fn an_outside_pull_request_takes_a_running_task_and_its_merge_finishes_it() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Outside", &[]); + let after = h.ready("After", &[&t]); + let issue = h.task(&f, &t).issue.unwrap(); + h.world().outside.push_back(OutsideEvent::ClosingPr { + issue: issue.clone(), + pr: 55, + url: "pr/55".into(), + merged: false, + }); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Outside); + assert!(h.world().stops.contains(&t), "the worker stops (B50)"); + assert!(h.world().removed.is_empty(), "the worktree stays"); + h.world().outside.push_back(OutsideEvent::ClosingPr { + issue, + pr: 55, + url: "pr/55".into(), + merged: true, + }); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Done); + tick_until(&mut h, &f, &after, TaskState::Running); +} + +#[test] +fn an_issue_closed_without_a_pull_request_cancels_and_a_label_creates_a_draft() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Closed", &[]); + let issue = h.task(&f, &t).issue.unwrap(); + { + let mut world = h.world(); + world.outside.push_back(OutsideEvent::IssueClosed { issue }); + world.outside.push_back(OutsideEvent::Labeled { + issue: IssueRef::Github { number: 7 }, + title: "From label".into(), + body: "Do it\n- [ ] works".into(), + }); + } + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Cancelled); + let labelled = h + .engine + .tasks_of(&f) + .find(|task| task.card.title == "From label") + .unwrap() + .clone(); + assert_eq!( + labelled.state, + TaskState::Drafting, + "a person confirms the card (B15)" + ); + assert_eq!(labelled.card.criteria, vec!["works"]); + let question = open_question(&h, &f, &labelled.id); + h.op(Command::Answer { + task: labelled.id.clone(), + question: Some(question.id), + choice: Some("confirm".into()), + text: None, + }); + assert_eq!( + h.writes("issue.create").len(), + 1, + "the labelled issue is not created again" + ); +} + +#[test] +fn three_failed_outside_reads_mark_the_board_stale_and_back_off() { + let mut h = Bench::new(true); + let _f = github_factory(&mut h, MergeMode::Auto); + h.world().observe_failure = Some(Failure::environment( + "observe", + EnvSignal::GithubServer, + "502", + )); + for _ in 0..3 { + h.advance(40 * MINUTE_MS); + h.engine.tick(); + } + assert!(h.engine.summary().factories[0].stale); + let reads = h.world().observed; + h.engine.tick(); + assert_eq!(h.world().observed, reads, "backed off"); +} + +// -------------------------------------------------------------- environment + +#[test] +fn a_low_disk_holds_new_starts_and_the_hold_clears_on_recheck() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().disk_free = Some(1 << 30); + let t = h.ready("Held", &[]); + assert_eq!(h.state(&f, &t), TaskState::Waiting); + assert!(h.task(&f, &t).held.is_some()); + h.world().disk_free = Some(100 << 30); + h.engine.tick(); + assert_eq!( + h.state(&f, &t), + TaskState::Waiting, + "re-checked after a minute" + ); + h.advance(MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Running); + + // Critical memory pressure holds; warn starts (B57). + let u = h.ready("Warned", &[]); + let _ = u; + h.world().memory = Some(MemoryPressure::Warn); + h.advance(MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &u), TaskState::Running); +} + +#[test] +fn a_usage_limit_moves_new_starts_to_the_other_runtime() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("First", &[]); + let mut failure = Failure::environment("worker", EnvSignal::UsageLimit, "limit"); + failure.reset_at = Some(h.world().now + HOUR_MS); + h.world().verify_start_failure = Some(failure); + h.done(&f, &t); + let u = h.ready("Second", &[]); + assert_eq!(h.state(&f, &u), TaskState::Running); + let runtimes: BTreeMap = h + .world() + .spawned + .iter() + .map(|s| (s.task.clone(), s.runtime)) + .collect(); + assert_eq!(runtimes[&t], Runtime::Claude); + assert_eq!(runtimes[&u], Runtime::Codex); +} + +// ------------------------------------------------------------ control + +#[test] +fn pause_resume_cancel_and_revive_keep_the_same_worker_and_pull_request() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Manual); + let t = h.ready("Controlled", &[]); + h.op(Command::Pause { task: t.clone() }); + assert_eq!(h.state(&f, &t), TaskState::Paused); + assert!(h.world().sleeps.contains(&t)); + h.op(Command::Resume { task: t.clone() }); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Running); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + h.op(Command::Cancel { task: t.clone() }); + assert_eq!(h.state(&f, &t), TaskState::Cancelled); + assert_eq!(h.writes("pr.close"), vec!["pr.close 1"]); + let revived = h.op(Command::Revive { task: t.clone() }); + assert_eq!(revived["ok"], true, "{revived}"); + assert_eq!(h.writes("pr.reopen"), vec!["pr.reopen 1"]); + assert_eq!(h.world().spawned.len(), 1); + + // Past the keep period the worktree goes and revive is refused. + h.op(Command::Cancel { task: t.clone() }); + h.advance(8 * DAY_MS); + h.engine.tick(); + assert!(h.world().removed.contains(&t)); + let refused = h.op(Command::Revive { task: t.clone() }); + assert_eq!(refused["reason"], "revive_expired"); +} + +#[test] +fn a_blocked_task_takes_only_an_answer() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Blocked", &[]); + h.as_worker( + &f, + &t, + Command::Block { + text: "?".into(), + suggestion: "x".into(), + deadline_hours: Some(1), + letter: None, + }, + ); + for command in [ + Command::Pause { task: t.clone() }, + Command::Cancel { task: t.clone() }, + Command::Retry { task: t.clone() }, + ] { + let refused = h.op(command); + assert_eq!( + refused["reason"], "action_not_allowed_in_state", + "{refused}" + ); + assert_eq!(refused["detail"]["allowed"], json!(["answer"])); + assert_eq!(refused["detail"]["state"], "막힘"); + } +} + +// ------------------------------------------------------------- restart + +#[test] +fn a_restart_keeps_every_task_question_and_applied_letter() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("Survives", &[]); + let b = h.ready("Also", &[&a]); + let pane = h.task(&f, &a).worker.unwrap().pane.unwrap(); + let letter = Inbound { + id: "letter-9".into(), + factory: f.clone(), + sender_pane: pane, + kind: "block".into(), + body: "Q?\nSuggestion: yes".into(), + }; + h.engine.letter(letter.clone()); + let before: Vec = h.engine.tasks_of(&f).cloned().collect(); + + let mut h = h.restart(); + let after: Vec = h.engine.tasks_of(&f).cloned().collect(); + assert_eq!(before, after); + assert_eq!( + h.engine.letter(letter)["duplicate"], + true, + "applied once across the restart (B73)" + ); + // Numbering continues: a new Task does not reuse an id. + let c = h.add("Third", &[]); + assert_eq!(c["task"]["id"], "T-3"); + let question = open_question(&h, &f, &a); + assert_eq!(question.id, "Q1"); + h.op(Command::Answer { + task: a.clone(), + question: Some(question.id), + choice: Some("suggestion".into()), + text: None, + }); + tick_until(&mut h, &f, &a, TaskState::Running); + assert_eq!(h.state(&f, &b), TaskState::Waiting); +} + +#[test] +fn a_restart_during_verification_runs_it_again() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Verifying", &[]); + h.world() + .verify + .insert(t.clone(), [VerifyPoll::Pending].into()); + h.done(&f, &t); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Verifying); + let mut h = h.restart(); + assert_eq!( + h.world().verify_runs.len(), + 2, + "the child of the old process is gone" + ); + tick_until(&mut h, &f, &t, TaskState::Done); + assert_eq!( + h.task(&f, &t) + .attempts + .iter() + .filter(|a| a.stage == AttemptStage::Task) + .count(), + 1 + ); +} + +// --------------------------------------------------------------- summary + +#[test] +fn the_inbox_orders_blocking_questions_first_then_answers_merges_and_stops() { + let mut h = Bench::new(false); + let f = h.factory(false); + let merge = h.ready("Merge me", &[]); + let blocked = h.ready("Blocked", &[]); + let asks = h.ready("Asks", &[]); + h.done(&f, &merge); + tick_until(&mut h, &f, &merge, TaskState::MergeWaiting); + h.as_worker( + &f, + &asks, + Command::Ask { + text: "a?".into(), + suggestion: "s".into(), + default_action: "d".into(), + deadline_hours: Some(5), + letter: None, + }, + ); + h.advance(MINUTE_MS); + h.as_worker( + &f, + &blocked, + Command::Block { + text: "b?".into(), + suggestion: "s".into(), + deadline_hours: Some(5), + letter: None, + }, + ); + let summary = h.engine.summary(); + let groups: Vec<(&str, &str)> = summary + .inbox + .iter() + .map(|item| (item.group.as_str(), item.task.as_str())) + .collect(); + assert_eq!( + groups, + vec![ + ("answer", blocked.as_str()), + ("answer", asks.as_str()), + ("merge", merge.as_str()) + ] + ); + assert_eq!(summary.my_turn, 3); + assert_eq!(summary.inbox[1].remaining.as_deref(), Some("5시간 남음")); + let flow = &summary.factories[0].flow; + // Merge waiting sits in the running column (D-47). + assert_eq!((flow.running, flow.waiting), (3, 0)); +} diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs new file mode 100644 index 0000000000..1595160dcd --- /dev/null +++ b/hide-factory/tests/support/mod.rs @@ -0,0 +1,597 @@ +//! One fake world behind every adapter the engine drives. Each fake records +//! the calls that would reach GitHub, git or a worker, so a test asserts what +//! was written and how many times, and answers from scripted queues. + +#![allow(dead_code)] + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use hide_factory::adapters::*; +use hide_factory::command::{CardInput, Command, VerificationChoice}; +use hide_factory::judgment::{Judgment, JudgmentAnswer, JudgmentInput, JudgmentOutcome}; +use hide_factory::model::*; +use hide_factory::role::Role; +use hide_factory::{Engine, Ports}; +use serde_json::{Value, json}; +use tempfile::TempDir; + +pub const PROJECT: &str = "/work/fixture"; + +#[derive(Default)] +pub struct World { + pub now: UnixMs, + pub github: bool, + /// Every external write, in order: `verb target`. + pub writes: Vec, + pub next_issue: u64, + pub next_pr: u64, + pub next_sha: u64, + /// Scripted verification results by Task id; `Passed` when empty. + pub verify: BTreeMap>, + pub verify_start_failure: Option, + pub verify_runs: Vec, + pub cancelled_runs: Vec, + pub premerge: BTreeMap>, + /// Main verification by commit; `Green` when absent. + pub main_checks: BTreeMap, + pub head: String, + pub main_dirty: bool, + pub revert_check: Option, + pub diff_lines: u32, + /// Worker status by Task id; `Working` when absent. + pub worker_status: BTreeMap, + pub spawned: Vec, + pub messages: Vec<(String, String)>, + pub sleeps: Vec, + pub wakes: Vec<(String, String)>, + pub stops: Vec, + pub removed: Vec, + pub spawn_failure: Option, + /// Judgments submitted and not yet answered. + pub submitted: Vec, + pub judged: Vec, + /// Intake answers by card title; a plain ready verdict when absent. + pub intake: BTreeMap, + pub drift: BTreeMap, + pub judge_down: bool, + pub hold_judgments: bool, + pub disk_free: Option, + pub memory: Option, + pub outside: VecDeque, + pub observe_failure: Option, + pub observed: u32, + pub macos: Vec, + pub producer: Vec<(String, String)>, +} + +#[derive(Clone)] +pub struct Shared(pub Arc>); + +impl Shared { + pub fn world(&self) -> MutexGuard<'_, World> { + self.0.lock().unwrap_or_else(|poison| poison.into_inner()) + } +} + +impl Clock for Shared { + fn now(&self) -> UnixMs { + self.world().now + } +} + +impl TaskSource for Shared { + fn probe(&mut self, _project: &str) -> Result { + let github = self.world().github; + Ok(ProjectProbe { + github, + repo: github.then(|| "owner/fixture".into()), + required_checks: if github { + vec!["test".into()] + } else { + Vec::new() + }, + verify_candidates: vec!["cargo test".into()], + merge_methods: vec![MergeMethod::Squash], + default_branch: "main".into(), + }) + } + fn planned_writes(&self, probe: &ProjectProbe) -> Vec { + if probe.github { + vec!["label factory".into()] + } else { + Vec::new() + } + } + fn prepare(&mut self, factory: &Factory) -> Result<(), Failure> { + if factory.source == SourceKind::Github { + self.world().writes.push("label.create factory".into()); + } + Ok(()) + } + fn create_issue( + &mut self, + factory: &Factory, + task: &Task, + _body: &str, + ) -> Result { + let mut world = self.world(); + world.next_issue += 1; + let number = world.next_issue; + world.writes.push(format!("issue.create {}", task.id)); + Ok(match factory.source { + SourceKind::Github => IssueRef::Github { + number: 100 + number, + }, + SourceKind::Local => IssueRef::Local { + number: number as u32, + }, + }) + } + fn label_issue(&mut self, _factory: &Factory, issue: &IssueRef) -> Result<(), Failure> { + self.world() + .writes + .push(format!("issue.label {}", issue.display())); + Ok(()) + } + fn read_issue(&mut self, _factory: &Factory, issue: &IssueRef) -> Result { + Ok(IssueText { + title: format!("Issue {}", issue.display()), + body: "- [ ] it works".into(), + open: true, + }) + } + fn observe( + &mut self, + _factory: &Factory, + _tasks: &[&Task], + ) -> Result, Failure> { + let mut world = self.world(); + world.observed += 1; + if let Some(failure) = world.observe_failure.clone() { + return Err(failure); + } + Ok(world.outside.drain(..).collect()) + } +} + +impl Verifier for Shared { + fn start(&mut self, _factory: &Factory, task: &Task) -> Result { + let mut world = self.world(); + if let Some(failure) = world.verify_start_failure.take() { + return Err(failure); + } + let id = format!("{}:{}", task.id, world.verify_runs.len()); + world.verify_runs.push(id.clone()); + Ok(VerifyRun { id, log: None }) + } + fn start_premerge(&mut self, factory: &Factory, task: &Task) -> Result { + self.start(factory, task) + } + fn poll(&mut self, _factory: &Factory, run: &VerifyRun) -> VerifyPoll { + let task = run.id.split(':').next().unwrap_or_default().to_owned(); + self.world() + .verify + .get_mut(&task) + .and_then(VecDeque::pop_front) + .unwrap_or(VerifyPoll::Passed) + } + fn cancel(&mut self, run: &VerifyRun) { + self.world().cancelled_runs.push(run.id.clone()); + } +} + +impl MergeTarget for Shared { + fn main_head(&mut self, _factory: &Factory) -> Result { + Ok(self.world().head.clone()) + } + fn open_pr( + &mut self, + _factory: &Factory, + task: &Task, + _body: &str, + ) -> Result, Failure> { + let mut world = self.world(); + world.next_pr += 1; + let number = world.next_pr; + world.writes.push(format!("pr.open {}", task.id)); + Ok(Some(PullRequest { + number, + url: format!("https://github.example/pr/{number}"), + head: task.branch_slug(), + by_factory: true, + open: true, + })) + } + fn close_pr(&mut self, _factory: &Factory, pr: &PullRequest) -> Result<(), Failure> { + self.world().writes.push(format!("pr.close {}", pr.number)); + Ok(()) + } + fn reopen_pr(&mut self, _factory: &Factory, pr: &PullRequest) -> Result<(), Failure> { + self.world().writes.push(format!("pr.reopen {}", pr.number)); + Ok(()) + } + fn diff_lines(&mut self, _factory: &Factory, _task: &Task) -> Result { + Ok(self.world().diff_lines) + } + fn changed_paths(&mut self, _factory: &Factory, _task: &Task) -> Result, Failure> { + Ok(vec!["src/lib.rs".into()]) + } + fn diff_text(&mut self, _factory: &Factory, task: &Task) -> Result { + Ok(format!("diff for {}", task.id)) + } + fn premerge(&mut self, _factory: &Factory, task: &Task) -> Result { + Ok(self + .world() + .premerge + .get_mut(&task.id) + .and_then(VecDeque::pop_front) + .unwrap_or(PreMerge::Clean)) + } + fn main_dirty(&mut self, _factory: &Factory) -> Result { + Ok(self.world().main_dirty) + } + fn merge( + &mut self, + _factory: &Factory, + task: &Task, + _method: MergeMethod, + ) -> Result { + let mut world = self.world(); + world.next_sha += 1; + let sha = format!("sha{:04}-{}", world.next_sha, task.id); + world.writes.push(format!("merge {}", task.id)); + world.head = sha.clone(); + Ok(sha) + } + fn main_check(&mut self, _factory: &Factory, sha: &str) -> Result { + Ok(self + .world() + .main_checks + .get(sha) + .cloned() + .unwrap_or(MainCheck::Green)) + } + fn rerun_main(&mut self, _factory: &Factory, sha: &str) -> Result<(), Failure> { + self.world().writes.push(format!("main.rerun {sha}")); + Ok(()) + } + fn revert(&mut self, _factory: &Factory, task: &Task, sha: &str) -> Result { + self.world().writes.push(format!("revert.open {}", task.id)); + Ok(RevertRef { + task: task.id.clone(), + sha: sha.to_owned(), + pr: Some(900), + commit: None, + }) + } + fn revert_check( + &mut self, + _factory: &Factory, + _revert: &RevertRef, + ) -> Result { + Ok(self + .world() + .revert_check + .clone() + .unwrap_or(MainCheck::Green)) + } + fn merge_revert(&mut self, _factory: &Factory, revert: &RevertRef) -> Result { + let mut world = self.world(); + world.next_sha += 1; + let sha = format!("sha{:04}-revert-{}", world.next_sha, revert.task); + world.writes.push(format!("revert.merge {}", revert.task)); + world.head = sha.clone(); + Ok(sha) + } +} + +impl WorkerRuntime for Shared { + fn spawn(&mut self, request: &WorkerSpawn) -> Result { + let mut world = self.world(); + if let Some(failure) = world.spawn_failure.clone() { + return Err(failure); + } + world.spawned.push(request.clone()); + world.worker_status.remove(&request.task); + Ok(WorkerRef { + name: request.name.clone(), + pane: Some(format!("pane-{}", request.task)), + runtime: request.runtime, + worktree: format!("/work/fixture.worktrees/{}", request.task), + branch: request.branch.clone(), + started_at: world.now, + asleep: false, + }) + } + fn message( + &mut self, + worker: &WorkerRef, + _intent: &str, + _reply_to: Option<&str>, + body: &str, + ) -> Result<(), Failure> { + self.world() + .messages + .push((task_of(worker), body.to_owned())); + Ok(()) + } + fn sleep(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + self.world().sleeps.push(task_of(worker)); + Ok(()) + } + fn wake(&mut self, worker: &WorkerRef, body: &str) -> Result<(), Failure> { + let mut world = self.world(); + world.wakes.push((task_of(worker), body.to_owned())); + world.worker_status.remove(&task_of(worker)); + Ok(()) + } + fn status(&mut self, worker: &WorkerRef) -> WorkerStatus { + self.world() + .worker_status + .get(&task_of(worker)) + .copied() + .unwrap_or(WorkerStatus::Working) + } + fn stop(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + self.world().stops.push(task_of(worker)); + Ok(()) + } + fn remove_worktree(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + self.world().removed.push(task_of(worker)); + Ok(()) + } + fn usage_limited(&mut self, _runtime: Runtime) -> Option { + None + } +} + +fn task_of(worker: &WorkerRef) -> String { + worker + .worktree + .rsplit('/') + .next() + .unwrap_or_default() + .to_owned() +} + +impl Judge for Shared { + fn submit(&mut self, judgment: Judgment) -> Result<(), Failure> { + let mut world = self.world(); + if world.judge_down { + return Err(Failure::task("judge", "no provider")); + } + world.submitted.push(judgment); + Ok(()) + } + fn finished(&mut self) -> Vec { + let mut world = self.world(); + if world.hold_judgments { + return Vec::new(); + } + let submitted = std::mem::take(&mut world.submitted); + let mut answers = Vec::new(); + for judgment in submitted { + let value = match &judgment.input { + JudgmentInput::IntakeReview { card, .. } => { + world.intake.get(&card.title).cloned().unwrap_or_else( + || json!({"questions": [], "dependencies": [], "flags": [], "split": []}), + ) + } + JudgmentInput::Drift { .. } | JudgmentInput::Check { .. } => judgment + .task + .as_ref() + .and_then(|task| world.drift.get(task).cloned()) + .unwrap_or_else(|| json!({"pass": true, "questions": [], "flags": []})), + JudgmentInput::Watch { .. } => json!({"warnings": []}), + JudgmentInput::EnvDiagnosis { .. } => json!({"cause": "unknown", "action": "none"}), + }; + answers.push(JudgmentAnswer { + id: judgment.id.clone(), + factory: judgment.factory.clone(), + task: judgment.task.clone(), + outcome: JudgmentOutcome::Answered { value }, + }); + world.judged.push(judgment); + } + answers + } +} + +impl Environment for Shared { + fn disk_free(&mut self, _project: &str) -> Option { + self.world().disk_free + } + fn memory_pressure(&mut self) -> MemoryPressure { + self.world().memory.unwrap_or(MemoryPressure::Normal) + } +} + +impl Notifier for Shared { + fn macos(&mut self, title: &str, _body: &str) { + self.world().macos.push(title.to_owned()); + } + fn producer(&mut self, pane: &str, body: &str) -> bool { + self.world() + .producer + .push((pane.to_owned(), body.to_owned())); + true + } +} + +/// An engine over the fake world in a private state folder. +pub struct Bench { + pub dir: TempDir, + pub shared: Shared, + pub engine: Engine, +} + +pub fn operator() -> Role { + Role::Operator { + pane: "operator".into(), + } +} + +pub fn worker(factory: &str, task: &str) -> Role { + Role::Worker { + factory: factory.into(), + task: task.into(), + } +} + +fn ports(shared: &Shared) -> Ports { + Ports { + clock: Box::new(shared.clone()), + source: Box::new(shared.clone()), + verifier: Box::new(shared.clone()), + merge: Box::new(shared.clone()), + workers: Box::new(shared.clone()), + judge: Box::new(shared.clone()), + environment: Box::new(shared.clone()), + notifier: Box::new(shared.clone()), + } +} + +impl Bench { + pub fn new(github: bool) -> Self { + let dir = tempfile::tempdir().expect("state folder"); + let world = World { + now: 1_000 * DAY_MS, + github, + head: "sha0000-base".into(), + diff_lines: 40, + disk_free: Some(100 << 30), + ..World::default() + }; + let shared = Shared(Arc::new(Mutex::new(world))); + let engine = Engine::open(dir.path(), ports(&shared)).expect("engine opens"); + Self { + dir, + shared, + engine, + } + } + + /// The same state folder and world, a new engine: a daemon restart. + pub fn restart(self) -> Self { + let Self { + dir, + shared, + engine, + } = self; + drop(engine); + let engine = Engine::open(dir.path(), ports(&shared)).expect("engine reopens"); + Self { + dir, + shared, + engine, + } + } + + pub fn world(&self) -> MutexGuard<'_, World> { + self.shared.world() + } + + pub fn advance(&mut self, ms: u64) { + self.world().now += ms; + } + + pub fn op(&mut self, command: Command) -> Value { + self.engine.command(&operator(), command) + } + + pub fn as_worker(&mut self, factory: &str, task: &str, command: Command) -> Value { + self.engine.command(&worker(factory, task), command) + } + + /// Creates a Factory; `verify` gives it a verify bundle and auto merge. + pub fn factory(&mut self, verify: bool) -> String { + self.factory_at(PROJECT, verify) + } + + pub fn factory_at(&mut self, project: &str, verify: bool) -> String { + let answer = self.op(Command::Init { + project: project.into(), + verification: Some(if verify { + VerificationChoice::Commands { + commands: vec!["cargo test".into()], + } + } else { + VerificationChoice::None + }), + merge_mode: Some(if verify { + MergeMode::Auto + } else { + MergeMode::Manual + }), + confirm: true, + }); + assert_eq!(answer["created"], true, "{answer}"); + answer["factory"]["id"] + .as_str() + .expect("factory id") + .to_owned() + } + + pub fn add(&mut self, title: &str, depends_on: &[&str]) -> Value { + self.add_card(card(title, depends_on)) + } + + pub fn add_card(&mut self, card: CardInput) -> Value { + self.op(Command::Add { + project: Some(PROJECT.into()), + task: None, + issue: None, + card, + producer_pane: None, + }) + } + + /// Adds a Task and lets its review finish; returns its id. + pub fn ready(&mut self, title: &str, depends_on: &[&str]) -> String { + let answer = self.add(title, depends_on); + assert_eq!(answer["ok"], true, "{answer}"); + let id = answer["task"]["id"].as_str().expect("task id").to_owned(); + self.engine.tick(); + id + } + + pub fn task(&self, factory: &str, id: &str) -> Task { + self.engine.task(factory, id).cloned().expect("task exists") + } + + pub fn state(&self, factory: &str, id: &str) -> TaskState { + self.task(factory, id).state + } + + pub fn done(&mut self, factory: &str, id: &str) -> Value { + self.as_worker( + factory, + id, + Command::Done { + summary: Some(format!("did {id}")), + breaking: false, + letter: None, + }, + ) + } + + pub fn writes(&self, prefix: &str) -> Vec { + self.world() + .writes + .iter() + .filter(|write| write.starts_with(prefix)) + .cloned() + .collect() + } +} + +pub fn card(title: &str, depends_on: &[&str]) -> CardInput { + CardInput { + title: Some(title.into()), + goal: Some(format!("Make {title} work")), + criteria: vec![format!("{title} passes its test")], + depends_on: depends_on.iter().map(|id| (*id).to_owned()).collect(), + ..CardInput::default() + } +} From 8434b8bb13af485319209532250082a8ed8e9124 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 03:48:52 +0900 Subject: [PATCH 03/72] Add the Factory's git, gh and verify adapters and the stage 2 summary fields Local git and gh adapters serve every Factory on the machine and choose by source; each write converges on its intent key (issue marker, head branch, merged state, forced label). The verify runner runs one bundle on the machine at a time with a time cap, owns each command's process group and keeps the last 1 MiB of output. The summary gains the full dependency set, worker panes, revive deadlines, archive folds and inbox result lines, and show answers a typed TaskDetail. --- Cargo.lock | 1 + hide-factory/Cargo.toml | 1 + hide-factory/src/command.rs | 37 +- hide-factory/src/engine.rs | 173 +--- hide-factory/src/exec.rs | 232 ++++++ hide-factory/src/lib.rs | 3 + hide-factory/src/model.rs | 58 ++ hide-factory/src/project.rs | 1319 +++++++++++++++++++++++++++++++ hide-factory/src/summary.rs | 280 ++++++- hide-factory/src/verify.rs | 465 +++++++++++ hide-factory/tests/github.rs | 342 ++++++++ hide-factory/tests/local_git.rs | 296 +++++++ 12 files changed, 3051 insertions(+), 156 deletions(-) create mode 100644 hide-factory/src/exec.rs create mode 100644 hide-factory/src/project.rs create mode 100644 hide-factory/src/verify.rs create mode 100644 hide-factory/tests/github.rs create mode 100644 hide-factory/tests/local_git.rs diff --git a/Cargo.lock b/Cargo.lock index 0522672578..8cb8cf916b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1229,6 +1229,7 @@ dependencies = [ name = "hide-factory" version = "0.1.0" dependencies = [ + "hide-platform", "rusqlite", "serde", "serde_json", diff --git a/hide-factory/Cargo.toml b/hide-factory/Cargo.toml index f40430c669..f1c5806951 100644 --- a/hide-factory/Cargo.toml +++ b/hide-factory/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" publish = false [dependencies] +hide-platform = { path = "../hide-platform" } rusqlite = { version = "=0.32.1", features = ["bundled"] } serde = { version = "=1.0.229", features = ["derive"] } serde_json = "=1.0.151" diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs index 7eb1d64c18..3ea1d0a596 100644 --- a/hide-factory/src/command.rs +++ b/hide-factory/src/command.rs @@ -422,11 +422,12 @@ fn render_status(answer: &Value) -> String { } fn render_show(task: &Value) -> String { + let card = &task["card"]; let mut text = format!( "{} {} [{}]\n", - task["display_id"].as_str().unwrap_or("?"), - task["title"].as_str().unwrap_or(""), - task["state_label"].as_str().unwrap_or("?") + card["display_id"].as_str().unwrap_or("?"), + card["title"].as_str().unwrap_or(""), + card["state_label"].as_str().unwrap_or("?") ); text.push_str(&format!("goal: {}\n", task["goal"].as_str().unwrap_or(""))); for criterion in task["criteria"].as_array().into_iter().flatten() { @@ -453,10 +454,10 @@ fn render_show(task: &Value) -> String { text.push_str(&format!( "chain: [{}] -> {} -> [{}]\n", chain("before"), - task["display_id"].as_str().unwrap_or("?"), + card["display_id"].as_str().unwrap_or("?"), chain("after") )); - if let Some(external) = task["external"] + if let Some(external) = card["external"] .as_array() .filter(|items| !items.is_empty()) { @@ -464,16 +465,32 @@ fn render_show(task: &Value) -> String { text.push_str(&format!("외부 대기: {}\n", names.join(", "))); } text.push_str(&format!( - "verification {}/{}", - task["failures"], task["failure_limit"] + "verification {}", + task["verification"].as_str().unwrap_or("?") )); if let Some(pr) = task["pr"]["url"].as_str() { text.push_str(&format!(" PR {pr}")); } - if let Some(pane) = task["worker"]["pane"].as_str() { + if let Some(pane) = card["worker_pane"].as_str() { text.push_str(&format!(" worker {pane}")); } text.push('\n'); + for attempt in task["attempts"].as_array().into_iter().flatten() { + text.push_str(&format!( + "attempt {} {} {}{}\n", + attempt["number"], + attempt["stage"].as_str().unwrap_or("?"), + attempt["outcome"].as_str().unwrap_or("?"), + attempt["check"] + .as_str() + .map(|check| format!(": {check}")) + .unwrap_or_default() + )); + } + if let Some(gates) = task["gates"].as_array().filter(|g| !g.is_empty()) { + let names: Vec<_> = gates.iter().filter_map(Value::as_str).collect(); + text.push_str(&format!("merge waits for: {}\n", names.join(", "))); + } for attachment in task["attachments"].as_array().into_iter().flatten() { text.push_str(&format!( "attachment v{} {} sha256:{}\n", @@ -504,6 +521,10 @@ fn render_show(task: &Value) -> String { question["text"].as_str().unwrap_or("") )); } + if let Some(allowed) = task["allowed"].as_array() { + let names: Vec<_> = allowed.iter().filter_map(Value::as_str).collect(); + text.push_str(&format!("allowed: {}\n", names.join(", "))); + } text } diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 67c3ff6da1..73e018c60e 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -958,6 +958,12 @@ impl Engine { .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| project.clone()), source, + repo: probe.repo.clone(), + default_branch: if probe.default_branch.is_empty() { + "main".into() + } else { + probe.default_branch.clone() + }, config, closed: false, created_at: now, @@ -1195,55 +1201,15 @@ impl Engine { let seq = factory.next_task; let id = format!("T-{seq}"); let card = self.validate_card(&factory_id, Some(&id), &input, None)?; - let mut task = Task { - factory: factory_id.clone(), - id: id.clone(), - seq, - issue: issue_ref, - card, - human: HumanFields { - review_directly: input.review_directly, - priority: input.priority.unwrap_or(0), - merge_mode: input.merge_mode, - runtime: input.runtime, - }, - state: TaskState::Drafting, - state_since: now, - created_at: now, - updated_at: now, - proposed_by: None, - autonomy: None, - attachments: Vec::new(), - questions: Vec::new(), - discoveries: Vec::new(), - decisions: Vec::new(), - flags: Vec::new(), - review: ReviewState::Pending, - producer_pane, - worker: None, - attempts: Vec::new(), - failures: 0, - environment_failures: 0, - pr: None, - merge_sha: None, - gates: Vec::new(), - stop: None, - breaking: false, - scope_approved: false, - new_tasks: 0, - new_task_cap_extended: false, - cancelled_at: None, - cancelled_from: None, - purged: false, - done_at: None, - seen: true, - last_report_at: None, - idle_since: None, - writes: BTreeSet::new(), - held: None, - label_path: false, - source_body_hash: None, + let mut task = Task::draft(&factory_id, &id, seq, card, now); + task.issue = issue_ref; + task.human = HumanFields { + review_directly: input.review_directly, + priority: input.priority.unwrap_or(0), + merge_mode: input.merge_mode, + runtime: input.runtime, }; + task.producer_pane = producer_pane; if let Some(prd) = &input.prd { let attachment = self .store @@ -2023,50 +1989,9 @@ impl Engine { f.next_task += 1; } self.save_factory(factory); - let task = Task { - factory: factory.to_owned(), - id: id.clone(), - seq, - issue: None, - card, - human: HumanFields::default(), - state: TaskState::Drafting, - state_since: now, - created_at: now, - updated_at: now, - proposed_by, - autonomy, - attachments: Vec::new(), - questions: Vec::new(), - discoveries: Vec::new(), - decisions: Vec::new(), - flags: Vec::new(), - review: ReviewState::Pending, - producer_pane: None, - worker: None, - attempts: Vec::new(), - failures: 0, - environment_failures: 0, - pr: None, - merge_sha: None, - gates: Vec::new(), - stop: None, - breaking: false, - scope_approved: false, - new_tasks: 0, - new_task_cap_extended: false, - cancelled_at: None, - cancelled_from: None, - purged: false, - done_at: None, - seen: true, - last_report_at: None, - idle_since: None, - writes: BTreeSet::new(), - held: None, - label_path: false, - source_body_hash: None, - }; + let mut task = Task::draft(factory, &id, seq, card, now); + task.proposed_by = proposed_by; + task.autonomy = autonomy; self.tasks .entry(factory.to_owned()) .or_default() @@ -3611,54 +3536,17 @@ impl Engine { Ok(serde_json::to_value(&summary).unwrap_or_default()) } - fn show(&self, factory: &str, id: &str) -> Value { - let Some(task) = self.task(factory, id) else { - return Value::Null; - }; - let config = self - .factories - .get(factory) - .map(|f| f.config.clone()) - .unwrap_or_default(); - let edges = dag::edges(self.tasks_of(factory)); - let name = |tid: &String| { - self.task(factory, tid) - .map(Task::display_id) - .unwrap_or_else(|| tid.clone()) - }; - let after: Vec = edges - .iter() - .filter(|(_, preds)| preds.contains(id)) - .map(|(tid, _)| name(tid)) - .collect(); - json!({ - "id": task.id, - "factory": task.factory, - "display_id": task.display_id(), - "title": task.card.title, - "state": task.state.as_str(), - "state_label": task.state.label(), - "stop": task.stop.map(|s| s.label()), - "goal": task.card.goal, - "criteria": task.card.criteria, - "out_of_scope": task.card.out_of_scope, - "before": task.card.depends_on.iter().map(name).collect::>(), - "after": after, - "external": task.card.external, - "failures": task.failures, - "failure_limit": config.verify_failure_limit, - "pr": task.pr, - "worker": task.worker, - "attachments": task.attachments, - "decisions": task.decisions, - "questions": task.questions, - "discoveries": task.discoveries, - "gates": task.gates.iter().map(|g| g.reason()).collect::>(), - "allowed": Self::allowed_actions(task), - "priority": task.human.priority, - "merge_sha": task.merge_sha, - "attempts": task.attempts, - }) + pub fn show(&self, factory: &str, id: &str) -> Option { + let factory = self.factories.get(factory)?; + let tasks = self.tasks.get(&factory.id)?; + let task = tasks.get(id)?; + Some(summary::detail( + factory, + task, + tasks, + Self::allowed_actions(task), + self.now(), + )) } // ------------------------------------------------------------------ letters @@ -4431,6 +4319,11 @@ impl Engine { let Ok(head) = self.ports.merge.main_head(&factory) else { continue; }; + if !factory.main.broken && !self.main_seen.contains_key(&factory.id) { + // The head found at start is the baseline, not a push (B47). + self.main_seen.insert(factory.id.clone(), head); + continue; + } let known = factory .main .merges_since_green diff --git a/hide-factory/src/exec.rs b/hide-factory/src/exec.rs new file mode 100644 index 0000000000..33fe59f0e4 --- /dev/null +++ b/hide-factory/src/exec.rs @@ -0,0 +1,232 @@ +//! Short subprocesses (`git`, `gh`) behind one seam, and the reading of their +//! failures into the structured environment signals (D-31 rule 2). Every run +//! has a deadline and a capped output (`hide_platform::process::run_to_end`); +//! tests replace the runner with a recording fake. + +use std::path::Path; +use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use hide_platform::process::{RunFailure, run_to_end}; + +use crate::adapters::{EnvSignal, Failure}; + +/// The longest a single `git` or `gh` call may take. +pub const CALL_DEADLINE: Duration = Duration::from_secs(120); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Output { + pub code: Option, + pub stdout: String, + pub stderr: String, +} + +impl Output { + pub fn ok(&self) -> bool { + self.code == Some(0) + } +} + +pub trait Runner: Send { + /// Runs `program` with `args` in `cwd`; `Err` only when it could not run + /// or answer at all. + fn run( + &mut self, + program: &str, + args: &[String], + cwd: Option<&Path>, + ) -> Result; +} + +/// The real runner. `stop` ends a call in flight when the engine shuts down. +pub struct SystemRunner { + pub stop: Arc, +} + +impl Runner for SystemRunner { + fn run( + &mut self, + program: &str, + args: &[String], + cwd: Option<&Path>, + ) -> Result { + let mut command = Command::new(program); + command.args(args); + // A pager or a prompt would wait forever for a person. + command + .env("GH_PROMPT_DISABLED", "1") + .env("GIT_TERMINAL_PROMPT", "0") + .env("GH_PAGER", "cat"); + if let Some(cwd) = cwd { + command.current_dir(cwd); + } + match run_to_end(&mut command, CALL_DEADLINE, &self.stop) { + Ok(finished) => Ok(Output { + code: finished.code, + stdout: finished.stdout, + stderr: finished.stderr, + }), + Err(RunFailure::TimedOut) => Err(if program == "gh" { + Failure::environment(program, EnvSignal::Network, "timed out") + } else { + Failure::task(program, "timed out") + }), + Err(RunFailure::Stopped) => Err(Failure::task(program, "stopped")), + Err(RunFailure::Start(error)) | Err(RunFailure::Wait(error)) => { + Err(Failure::task(program, error.to_string())) + } + } + } +} + +/// The shell a verify command or quick check runs under, and its flag. +pub fn shell() -> (&'static str, &'static str) { + if cfg!(windows) { + ("cmd", "/C") + } else { + ("/bin/sh", "-c") + } +} + +/// Runs and requires success; a failure is read for its signal. +pub fn checked( + runner: &mut dyn Runner, + stage: &str, + program: &str, + args: &[&str], + cwd: Option<&Path>, +) -> Result { + let args: Vec = args.iter().map(|arg| (*arg).to_owned()).collect(); + let output = runner.run(program, &args, cwd)?; + if output.ok() { + return Ok(output.stdout); + } + Err(classify(stage, &output)) +} + +/// Reads a failed call's output for a structured environment signal; anything +/// else is the Task's (B58). +pub fn classify(stage: &str, output: &Output) -> Failure { + let text = format!("{}\n{}", output.stderr, output.stdout); + let lower = text.to_lowercase(); + let detail = last_line(&output.stderr).unwrap_or_else(|| format!("exit {:?}", output.code)); + let signal = if lower.contains("no space left on device") { + Some(EnvSignal::DiskFull) + } else if output.code == Some(137) { + Some(EnvSignal::OutOfMemory) + } else if lower.contains("http 401") + || lower.contains("gh auth login") + || lower.contains("authentication required") + { + Some(EnvSignal::GithubAuth) + } else if lower.contains("http 429") || lower.contains("rate limit") { + Some(EnvSignal::GithubRateLimit) + } else if lower.contains("http 403") + || lower.contains("required scopes") + || lower.contains("must have admin rights") + { + Some(EnvSignal::GithubForbidden) + } else if ["http 500", "http 502", "http 503", "http 504"] + .iter() + .any(|code| lower.contains(code)) + { + Some(EnvSignal::GithubServer) + } else if [ + "could not resolve host", + "connection refused", + "network is unreachable", + "connection reset", + "tls handshake", + "i/o timeout", + ] + .iter() + .any(|needle| lower.contains(needle)) + { + Some(EnvSignal::Network) + } else { + None + }; + let mut failure = match signal { + Some(signal) => Failure::environment(stage, signal, detail), + None => Failure::task(stage, detail), + }; + if signal == Some(EnvSignal::GithubForbidden) { + failure.missing_scope = missing_scope(&text); + } + failure +} + +/// gh names a missing scope as `['scope']` or `"scope" scope`. +fn missing_scope(text: &str) -> Option { + let start = text.find("['")? + 2; + let end = text[start..].find('\'')? + start; + Some(text[start..end].to_owned()).filter(|scope| !scope.is_empty() && scope.len() < 40) +} + +fn last_line(text: &str) -> Option { + text.lines() + .rev() + .map(str::trim) + .find(|line| !line.is_empty()) + .map(|line| line.chars().take(300).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn failed(stderr: &str, code: i32) -> Output { + Output { + code: Some(code), + stdout: String::new(), + stderr: stderr.into(), + } + } + + #[test] + fn structured_signals_are_read_and_everything_else_is_the_tasks() { + let cases = [ + ("HTTP 401: Bad credentials", 1, Some(EnvSignal::GithubAuth)), + ( + "HTTP 403: Resource not accessible", + 1, + Some(EnvSignal::GithubForbidden), + ), + ( + "API rate limit exceeded", + 1, + Some(EnvSignal::GithubRateLimit), + ), + ("HTTP 502: Bad Gateway", 1, Some(EnvSignal::GithubServer)), + ( + "fatal: unable to access: Could not resolve host: github.com", + 128, + Some(EnvSignal::Network), + ), + ( + "write error: No space left on device", + 1, + Some(EnvSignal::DiskFull), + ), + ("", 137, Some(EnvSignal::OutOfMemory)), + ("error: test failed, to rerun pass --lib", 101, None), + ]; + for (stderr, code, signal) in cases { + assert_eq!( + classify("stage", &failed(stderr, code)).signal, + signal, + "{stderr}" + ); + } + let scope = classify( + "stage", + &failed( + "HTTP 403: requires one of the following scopes: ['workflow']", + 1, + ), + ); + assert_eq!(scope.missing_scope.as_deref(), Some("workflow")); + } +} diff --git a/hide-factory/src/lib.rs b/hide-factory/src/lib.rs index a992f19405..c85e6be56f 100644 --- a/hide-factory/src/lib.rs +++ b/hide-factory/src/lib.rs @@ -13,11 +13,14 @@ pub mod adapters; pub mod command; pub mod dag; pub mod engine; +pub mod exec; pub mod judgment; pub mod model; +pub mod project; pub mod role; pub mod store; pub mod summary; +pub mod verify; pub use command::{Command, Refusal}; pub use engine::{Engine, Inbound, Ports}; diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index c491773604..8e27fa7ea0 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -25,6 +25,12 @@ pub struct Factory { /// A short name the inbox shows next to each item. pub project_name: String, pub source: SourceKind, + /// `owner/name` of a GitHub Factory. + #[serde(default)] + pub repo: Option, + /// The branch Tasks merge into, read at init. + #[serde(default = "default_branch")] + pub default_branch: String, pub config: Config, pub closed: bool, pub created_at: UnixMs, @@ -45,6 +51,10 @@ pub struct Factory { pub watch_last_at: Option, } +fn default_branch() -> String { + "main".into() +} + /// Where Tasks come from and where they merge (D-04, B3). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -794,6 +804,54 @@ pub enum ReviewResult { } impl Task { + /// A new Task in drafting, before its review (D-05). + pub fn draft(factory: &str, id: &str, seq: u32, card: Card, now: UnixMs) -> Self { + Self { + factory: factory.to_owned(), + id: id.to_owned(), + seq, + issue: None, + card, + human: HumanFields::default(), + state: TaskState::Drafting, + state_since: now, + created_at: now, + updated_at: now, + proposed_by: None, + autonomy: None, + attachments: Vec::new(), + questions: Vec::new(), + discoveries: Vec::new(), + decisions: Vec::new(), + flags: Vec::new(), + review: ReviewState::Pending, + producer_pane: None, + worker: None, + attempts: Vec::new(), + failures: 0, + environment_failures: 0, + pr: None, + merge_sha: None, + gates: Vec::new(), + stop: None, + breaking: false, + scope_approved: false, + new_tasks: 0, + new_task_cap_extended: false, + cancelled_at: None, + cancelled_from: None, + purged: false, + done_at: None, + seen: true, + last_report_at: None, + idle_since: None, + writes: BTreeSet::new(), + held: None, + label_path: false, + source_body_hash: None, + } + } + pub fn display_id(&self) -> String { self.issue .as_ref() diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs new file mode 100644 index 0000000000..e05e810830 --- /dev/null +++ b/hide-factory/src/project.rs @@ -0,0 +1,1319 @@ +//! The real Task source, merge target and verifier: local git for every +//! Factory, `gh` for a GitHub Factory, the verify runner for a bundle. One +//! value serves every Factory on the machine and chooses by its source. +//! +//! Every write converges on an intent key (B73): an issue carries the Task +//! marker, a pull request is found by its head branch, a merge by its pull +//! request's state, a label create is `--force`. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use serde_json::Value; + +use crate::adapters::*; +use crate::engine::task_marker; +use crate::exec::{Runner, checked, classify}; +use crate::model::*; +use crate::store::sha256_hex; +use crate::verify::{Job, Prepare, VerifyRunner}; + +/// Local issues (`L-`) for a project without GitHub, owned by the core. +pub trait IssueBook: Send { + /// Creates an issue, or returns the one whose body carries `marker`. + fn create( + &mut self, + project: &str, + title: &str, + body: &str, + marker: &str, + ) -> Result; + fn read(&mut self, project: &str, number: u32) -> Result; +} + +pub const LABEL: &str = "factory"; +/// The check name a Factory without its own CI uses in [`MainCheck`]. +const MAIN_WORKTREE: &str = "factory-main"; + +pub struct Projects { + pub runner: Box, + pub issues: Box, + pub verify: VerifyRunner, + /// Issue bodies already seen, to tell an edit from the first read. + bodies: BTreeMap<(String, u64), String>, +} + +/// One `Projects` shared by the engine's source, merge and verifier ports. +#[derive(Clone)] +pub struct SharedProjects(pub Arc>); + +impl SharedProjects { + pub fn new(runner: Box, issues: Box, logs: PathBuf) -> Self { + Self(Arc::new(Mutex::new(Projects { + runner, + issues, + verify: VerifyRunner::new(logs), + bodies: BTreeMap::new(), + }))) + } + + fn lock(&self) -> MutexGuard<'_, Projects> { + self.0.lock().unwrap_or_else(|poison| poison.into_inner()) + } +} + +fn worktree(task: &Task) -> Result { + task.worker + .as_ref() + .map(|worker| PathBuf::from(&worker.worktree)) + .ok_or_else(|| Failure::task("worktree", "the Task has no worktree")) +} + +fn repo(factory: &Factory) -> Result { + factory + .repo + .clone() + .ok_or_else(|| Failure::task("github", "the Factory has no repository")) +} + +/// The Factory-owned checkout main verification and reverts run in. +pub fn main_worktree(factory: &Factory) -> PathBuf { + let project = Path::new(&factory.project); + let name = project + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "project".into()); + project + .with_file_name(format!("{name}.worktrees")) + .join(MAIN_WORKTREE) +} + +impl Projects { + fn git(&mut self, stage: &str, cwd: &Path, args: &[&str]) -> Result { + checked(self.runner.as_mut(), stage, "git", args, Some(cwd)) + } + + fn gh(&mut self, stage: &str, args: &[&str]) -> Result { + checked(self.runner.as_mut(), stage, "gh", args, None) + } + + fn gh_json(&mut self, stage: &str, args: &[&str]) -> Result { + let text = self.gh(stage, args)?; + serde_json::from_str(&text) + .map_err(|error| Failure::task(stage, format!("gh answered no JSON: {error}"))) + } + + /// The ref Task branches are compared and merged against. + fn base(&mut self, factory: &Factory) -> Result { + match factory.source { + SourceKind::Local => Ok(factory.default_branch.clone()), + SourceKind::Github => { + let project = PathBuf::from(&factory.project); + self.git( + "git.fetch", + &project, + &["fetch", "--quiet", "origin", &factory.default_branch], + )?; + Ok(format!("origin/{}", factory.default_branch)) + } + } + } + + fn ensure_main_worktree(&mut self, factory: &Factory) -> Result { + let path = main_worktree(factory); + if !path.join(".git").exists() { + let project = PathBuf::from(&factory.project); + let text = path.display().to_string(); + self.git( + "git.worktree", + &project, + &[ + "worktree", + "add", + "--detach", + &text, + &factory.default_branch, + ], + )?; + } + Ok(path) + } + + fn main_job(&mut self, factory: &Factory, id: &str, sha: &str) -> Result<(), Failure> { + let Verification::Commands { commands } = &factory.config.verification else { + return Ok(()); + }; + let path = self.ensure_main_worktree(factory)?; + self.verify.submit(Job { + id: id.to_owned(), + cwd: path.clone(), + commands: commands.clone(), + prepare: vec![Prepare { + program: "git".into(), + args: vec![ + "checkout".into(), + "--quiet".into(), + "--detach".into(), + sha.into(), + ], + cwd: path, + }], + timeout: Duration::from_millis(factory.config.verify_timeout_ms), + }) + } + + fn main_result( + &mut self, + factory: &Factory, + id: &str, + sha: &str, + ) -> Result { + if !self.verify.known(id) { + self.main_job(factory, id, sha)?; + } + Ok(match self.verify.poll(self.runner.as_mut(), id) { + VerifyPoll::Pending => MainCheck::Pending, + VerifyPoll::Passed => MainCheck::Green, + VerifyPoll::Failed { check, link } => MainCheck::Red { + link: format!("{check}: {link}"), + }, + VerifyPoll::Environment { check, .. } => { + // The environment's failure says nothing about main: ask again. + self.verify.forget(id); + let _ = check; + MainCheck::Pending + } + }) + } + + /// Required check runs on a commit (B35, B44). + fn checks(&mut self, factory: &Factory, sha: &str) -> Result { + let repo = repo(factory)?; + let path = format!("repos/{repo}/commits/{sha}/check-runs?per_page=100"); + let value = self.gh_json("github.checks", &["api", &path])?; + let required = match &factory.config.verification { + Verification::Ci { checks } => checks.clone(), + _ => Vec::new(), + }; + let runs: Vec<&Value> = value["check_runs"] + .as_array() + .into_iter() + .flatten() + .filter(|run| { + required.is_empty() + || required + .iter() + .any(|name| run["name"].as_str() == Some(name)) + }) + .collect(); + if runs.is_empty() { + return Ok(if required.is_empty() { + MainCheck::None + } else { + MainCheck::Pending + }); + } + if let Some(missing) = required + .iter() + .find(|name| !runs.iter().any(|run| run["name"].as_str() == Some(name))) + { + let _ = missing; + return Ok(MainCheck::Pending); + } + for run in &runs { + if run["status"].as_str() != Some("completed") { + return Ok(MainCheck::Pending); + } + } + for run in &runs { + match run["conclusion"].as_str() { + Some("success") | Some("neutral") => {} + // A skipped or cancelled run decides nothing (B45). + Some("skipped") | Some("cancelled") | Some("stale") => { + return Ok(MainCheck::Pending); + } + _ => { + let name = run["name"].as_str().unwrap_or("check"); + let url = run["html_url"].as_str().unwrap_or_default(); + return Ok(MainCheck::Red { + link: format!("{name}: {url}"), + }); + } + } + } + Ok(MainCheck::Green) + } + + fn head_sha(&mut self, task: &Task) -> Result { + let path = worktree(task)?; + Ok(self + .git("git.head", &path, &["rev-parse", "HEAD"])? + .trim() + .to_owned()) + } + + fn pr_view(&mut self, factory: &Factory, number: u64) -> Result { + let repo = repo(factory)?; + let number = number.to_string(); + self.gh_json( + "github.pr_view", + &[ + "pr", + "view", + &number, + "--repo", + &repo, + "--json", + "number,url,state,headRefName,headRefOid,mergeCommit", + ], + ) + } +} + +fn verify_id(task: &Task, stage: &str) -> String { + format!( + "{}:{}:{}:{}", + task.factory, + task.id, + stage, + task.attempts.len() + ) +} + +impl TaskSource for SharedProjects { + fn probe(&mut self, project: &str) -> Result { + let mut this = self.lock(); + let path = PathBuf::from(project); + this.git("probe", &path, &["rev-parse", "--show-toplevel"])?; + let branch = this + .git("probe", &path, &["rev-parse", "--abbrev-ref", "HEAD"])? + .trim() + .to_owned(); + let remote = checked( + this.runner.as_mut(), + "probe", + "git", + &["remote", "get-url", "origin"], + Some(&path), + ) + .unwrap_or_default(); + let mut probe = ProjectProbe { + default_branch: branch, + verify_candidates: verify_candidates(&path), + ..ProjectProbe::default() + }; + if remote.contains("github.com") { + let view = this.gh_json("probe", &["repo", "view", remote.trim(), "--json", "nameWithOwner,defaultBranchRef,mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed"])?; + probe.github = true; + probe.repo = view["nameWithOwner"].as_str().map(str::to_owned); + if let Some(branch) = view["defaultBranchRef"]["name"].as_str() { + probe.default_branch = branch.to_owned(); + } + for (key, method) in [ + ("squashMergeAllowed", MergeMethod::Squash), + ("mergeCommitAllowed", MergeMethod::Merge), + ("rebaseMergeAllowed", MergeMethod::Rebase), + ] { + if view[key].as_bool() == Some(true) { + probe.merge_methods.push(method); + } + } + let repo = probe.repo.clone().unwrap_or_default(); + let path = format!( + "repos/{repo}/branches/{}/protection/required_status_checks", + probe.default_branch + ); + let args: Vec = ["api", &path].iter().map(|a| (*a).to_owned()).collect(); + let answer = this.runner.run("gh", &args, None)?; + if answer.ok() { + let value: Value = serde_json::from_str(&answer.stdout).unwrap_or_default(); + probe.required_checks = value["contexts"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(); + } else if !answer.stderr.contains("404") { + return Err(classify("probe", &answer)); + } + } + Ok(probe) + } + + fn planned_writes(&self, probe: &ProjectProbe) -> Vec { + if probe.github { + vec![format!( + "GitHub label `{LABEL}` on {}", + probe.repo.clone().unwrap_or_default() + )] + } else { + Vec::new() + } + } + + fn prepare(&mut self, factory: &Factory) -> Result<(), Failure> { + if factory.source != SourceKind::Github { + return Ok(()); + } + let repo = repo(factory)?; + self.lock().gh( + "github.label", + &[ + "label", + "create", + LABEL, + "--repo", + &repo, + "--force", + "--color", + "5319e7", + "--description", + "Software Factory Task", + ], + )?; + Ok(()) + } + + fn create_issue( + &mut self, + factory: &Factory, + task: &Task, + body: &str, + ) -> Result { + let marker = task_marker(factory, task); + let mut this = self.lock(); + match factory.source { + SourceKind::Local => { + let number = + this.issues + .create(&factory.project, &task.card.title, body, &marker)?; + Ok(IssueRef::Local { number }) + } + SourceKind::Github => { + let repo = repo(factory)?; + let search = format!("\"{marker}\" in:body"); + let found = this.gh_json( + "github.issue_find", + &[ + "issue", + "list", + "--repo", + &repo, + "--state", + "all", + "--search", + &search, + "--json", + "number,body", + ], + )?; + if let Some(number) = found + .as_array() + .into_iter() + .flatten() + .find(|issue| issue["body"].as_str().is_some_and(|b| b.contains(&marker))) + .and_then(|issue| issue["number"].as_u64()) + { + return Ok(IssueRef::Github { number }); + } + let url = this.gh( + "github.issue_create", + &[ + "issue", + "create", + "--repo", + &repo, + "--title", + &task.card.title, + "--body", + body, + "--label", + LABEL, + ], + )?; + number_from_url(&url) + .map(|number| IssueRef::Github { number }) + .ok_or_else(|| Failure::task("github.issue_create", "gh answered no issue URL")) + } + } + } + + fn label_issue(&mut self, factory: &Factory, issue: &IssueRef) -> Result<(), Failure> { + let IssueRef::Github { number } = issue else { + return Ok(()); + }; + let repo = repo(factory)?; + let number = number.to_string(); + self.lock().gh( + "github.label_issue", + &[ + "issue", + "edit", + &number, + "--repo", + &repo, + "--add-label", + LABEL, + ], + )?; + Ok(()) + } + + fn read_issue(&mut self, factory: &Factory, issue: &IssueRef) -> Result { + let mut this = self.lock(); + match issue { + IssueRef::Local { number } => this.issues.read(&factory.project, *number), + IssueRef::Github { number } => { + let repo = repo(factory)?; + let number = number.to_string(); + let value = this.gh_json( + "github.issue_view", + &[ + "issue", + "view", + &number, + "--repo", + &repo, + "--json", + "title,body,state", + ], + )?; + Ok(IssueText { + title: value["title"].as_str().unwrap_or_default().to_owned(), + body: value["body"].as_str().unwrap_or_default().to_owned(), + open: value["state"].as_str() == Some("OPEN"), + }) + } + } + } + + fn observe( + &mut self, + factory: &Factory, + tasks: &[&Task], + ) -> Result, Failure> { + let mut this = self.lock(); + let mut events = Vec::new(); + if factory.source == SourceKind::Local { + for task in tasks { + let Some(IssueRef::Local { number }) = task.issue else { + continue; + }; + if matches!(task.state, TaskState::Done | TaskState::Cancelled) { + continue; + } + if let Ok(text) = this.issues.read(&factory.project, number) + && !text.open + { + events.push(OutsideEvent::IssueClosed { + issue: IssueRef::Local { number }, + }); + } + } + return Ok(events); + } + let repo = repo(factory)?; + let issues = this.gh_json( + "github.observe", + &[ + "issue", + "list", + "--repo", + &repo, + "--label", + LABEL, + "--state", + "all", + "--limit", + "200", + "--json", + "number,title,body,state", + ], + )?; + let prs = this.gh_json( + "github.observe", + &[ + "pr", + "list", + "--repo", + &repo, + "--state", + "all", + "--limit", + "100", + "--json", + "number,url,state,headRefName,closingIssuesReferences", + ], + )?; + let held: BTreeMap = tasks + .iter() + .filter_map(|task| match task.issue { + Some(IssueRef::Github { number }) => Some((number, task)), + _ => None, + }) + .collect(); + let labelled: BTreeMap = issues + .as_array() + .into_iter() + .flatten() + .filter_map(|issue| issue["number"].as_u64().map(|n| (n, issue))) + .collect(); + for (number, issue) in &labelled { + let issue_ref = IssueRef::Github { number: *number }; + let body = issue["body"].as_str().unwrap_or_default(); + let hash = sha256_hex(body.as_bytes()); + match held.get(number) { + None => { + if issue["state"].as_str() == Some("OPEN") + && !body.contains("".into(), + "OPEN".into(), + ), + ); + hub.issues + .insert(2, ("New one".into(), "please do".into(), "OPEN".into())); + hub.issues.insert( + 3, + ( + "Closed".into(), + "".into(), + "CLOSED".into(), + ), + ); + hub.prs.insert(9, json!({"number": 9, "url": "pr/9", "state": "OPEN", "headRefName": "someone/fix", "closingIssuesReferences": [{"number": 1}]})); + } + let held = task("T-1", Some(1)); + let closed = task("T-3", Some(3)); + let gone = task("T-4", Some(4)); + let events = p.observe(&factory, &[&held, &closed, &gone]).unwrap(); + assert!( + events.contains(&OutsideEvent::ClosingPr { + issue: IssueRef::Github { number: 1 }, + pr: 9, + url: "pr/9".into(), + merged: false + }), + "{events:?}" + ); + assert!(events.contains(&OutsideEvent::Labeled { + issue: IssueRef::Github { number: 2 }, + title: "New one".into(), + body: "please do".into() + })); + assert!(events.contains(&OutsideEvent::IssueClosed { + issue: IssueRef::Github { number: 3 } + })); + assert!(events.contains(&OutsideEvent::LabelRemoved { + issue: IssueRef::Github { number: 4 } + })); + assert!( + gh.0.lock().unwrap().writes.is_empty(), + "reading writes nothing" + ); +} + +#[test] +fn a_github_failure_carries_its_signal() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + gh.0.lock().unwrap().fail_next = + Some("HTTP 401: Bad credentials (https://api.github.com/)".into()); + let failure = p.prepare(&factory()).unwrap_err(); + assert_eq!(failure.signal, Some(EnvSignal::GithubAuth)); +} diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs new file mode 100644 index 0000000000..bfff46f0cd --- /dev/null +++ b/hide-factory/tests/local_git.rs @@ -0,0 +1,296 @@ +//! The local path against a real git repository in a private folder: the +//! pre-merge check, the verify bundle, the merge into the main checkout, the +//! main verification and the revert of one merge (B38, B42, B44, B45). +#![cfg(unix)] + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{Duration, Instant}; + +use hide_factory::adapters::*; +use hide_factory::exec::SystemRunner; +use hide_factory::model::*; +use hide_factory::project::{IssueBook, SharedProjects}; +use serde_json::json; + +#[derive(Default)] +struct Book(BTreeMap); + +impl IssueBook for Book { + fn create( + &mut self, + _project: &str, + title: &str, + body: &str, + marker: &str, + ) -> Result { + if let Some((n, _)) = self.0.iter().find(|(_, (_, b))| b.contains(marker)) { + return Ok(*n); + } + let n = self.0.len() as u32 + 1; + self.0.insert(n, (title.into(), body.into())); + Ok(n) + } + fn read(&mut self, _project: &str, number: u32) -> Result { + let (title, body) = self + .0 + .get(&number) + .cloned() + .ok_or_else(|| Failure::task("issue", "missing"))?; + Ok(IssueText { + title, + body, + open: true, + }) + } +} + +fn git(dir: &Path, args: &[&str]) -> String { + let output = Command::new("git") + .args(args) + .current_dir(dir) + .output() + .expect("git runs"); + assert!( + output.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).trim().to_owned() +} + +fn write(dir: &Path, name: &str, text: &str) { + std::fs::write(dir.join(name), text).unwrap(); +} + +struct Fixture { + _root: tempfile::TempDir, + project: PathBuf, + projects: SharedProjects, +} + +fn fixture() -> Fixture { + let root = tempfile::tempdir().unwrap(); + let project = root.path().join("repo"); + std::fs::create_dir(&project).unwrap(); + git(&project, &["init", "--quiet", "--initial-branch=main"]); + git(&project, &["config", "user.email", "factory@example.com"]); + git(&project, &["config", "user.name", "Factory"]); + write(&project, "a.txt", "one\n"); + write(&project, "Makefile", "test:\n\ttrue\n"); + git(&project, &["add", "."]); + git(&project, &["commit", "--quiet", "-m", "base"]); + let runner = SystemRunner { + stop: Arc::new(AtomicBool::new(false)), + }; + let projects = SharedProjects::new( + Box::new(runner), + Box::new(Book::default()), + root.path().join("logs"), + ); + Fixture { + _root: root, + project, + projects, + } +} + +fn factory(project: &Path, commands: &[&str]) -> Factory { + serde_json::from_value(json!({ + "id": "f-local", "project": project.display().to_string(), "project_name": "repo", "source": "local", + "default_branch": "main", + "config": Config { verification: Verification::Commands { commands: commands.iter().map(|c| (*c).to_owned()).collect() }, ..Config::default() }, + "closed": false, "created_at": 0, "next_task": 1, "next_local_issue": 1, "main": MainHealth::default(), + "outside_read_at": null, "outside_read_failures": 0, "watch_day": 0, "watch_sent_today": 0, "watch_last_at": null + })) + .unwrap() +} + +/// A Task with a worktree on its own branch carrying one commit. +fn task(fixture: &Fixture, id: &str, file: &str, text: &str) -> Task { + let mut task = Task::draft( + "f-local", + id, + 1, + Card { + title: format!("Task {id}"), + ..Card::default() + }, + 0, + ); + let branch = task.branch_slug(); + let worktree = fixture.project.with_file_name(format!("wt-{id}")); + git( + &fixture.project, + &[ + "worktree", + "add", + "--quiet", + "-b", + &branch, + worktree.to_str().unwrap(), + ], + ); + write(&worktree, file, text); + git(&worktree, &["add", "."]); + git(&worktree, &["commit", "--quiet", "-m", id]); + task.worker = Some(WorkerRef { + name: id.into(), + pane: None, + runtime: Runtime::Claude, + worktree: worktree.display().to_string(), + branch, + started_at: 0, + asleep: true, + }); + task +} + +fn settle(projects: &mut SharedProjects, factory: &Factory, run: &VerifyRun) -> VerifyPoll { + let guard = Instant::now() + Duration::from_secs(120); + loop { + let poll = projects.poll(factory, run); + if poll != VerifyPoll::Pending || Instant::now() > guard { + return poll; + } + std::thread::yield_now(); + } +} + +fn settle_main(projects: &mut SharedProjects, factory: &Factory, sha: &str) -> MainCheck { + let guard = Instant::now() + Duration::from_secs(120); + loop { + let check = projects.main_check(factory, sha).unwrap(); + if check != MainCheck::Pending || Instant::now() > guard { + return check; + } + std::thread::yield_now(); + } +} + +#[test] +fn a_local_task_is_verified_merged_checked_on_main_and_reverted_alone() { + let mut fx = fixture(); + let probe = fx.projects.probe(fx.project.to_str().unwrap()).unwrap(); + assert!(!probe.github); + assert_eq!(probe.default_branch, "main"); + assert_eq!(probe.verify_candidates, vec!["make test"]); + + let factory = factory(&fx.project, &["test -f b.txt"]); + let t = task(&fx, "T-1", "b.txt", "two\n"); + assert_eq!(fx.projects.diff_lines(&factory, &t).unwrap(), 1); + assert_eq!( + fx.projects.changed_paths(&factory, &t).unwrap(), + vec!["b.txt"] + ); + assert_eq!(fx.projects.premerge(&factory, &t).unwrap(), PreMerge::Clean); + + let run = fx.projects.start(&factory, &t).unwrap(); + assert_eq!(settle(&mut fx.projects, &factory, &run), VerifyPoll::Passed); + // main moved meanwhile: the bundle runs on main merged into the Task. + write(&fx.project, "c.txt", "three\n"); + git(&fx.project, &["add", "."]); + git(&fx.project, &["commit", "--quiet", "-m", "outside"]); + let factory = Factory { + config: Config { + verification: Verification::Commands { + commands: vec!["test -f b.txt && test -f c.txt".into()], + }, + ..factory.config.clone() + }, + ..factory + }; + let run = fx.projects.start_premerge(&factory, &t).unwrap(); + assert_eq!(settle(&mut fx.projects, &factory, &run), VerifyPoll::Passed); + + assert!(!fx.projects.main_dirty(&factory).unwrap()); + let sha = fx.projects.merge(&factory, &t, MergeMethod::Merge).unwrap(); + assert_eq!(git(&fx.project, &["rev-parse", "HEAD"]), sha); + assert!(fx.project.join("b.txt").exists()); + assert_eq!( + fx.projects.merge(&factory, &t, MergeMethod::Merge).unwrap(), + sha, + "a merged branch is not merged again" + ); + assert_eq!( + settle_main(&mut fx.projects, &factory, &sha), + MainCheck::Green + ); + + let revert = fx.projects.revert(&factory, &t, &sha).unwrap(); + assert_eq!(revert.pr, None); + let check = fx.projects.revert_check(&factory, &revert).unwrap(); + assert_eq!( + check, + MainCheck::Pending, + "the revert is verified before it lands" + ); + let guard = Instant::now() + Duration::from_secs(120); + let mut check = check; + while check == MainCheck::Pending && Instant::now() < guard { + check = fx.projects.revert_check(&factory, &revert).unwrap(); + std::thread::yield_now(); + } + // The bundle needs b.txt, which the revert removes: it fails. + assert!(matches!(check, MainCheck::Red { .. }), "{check:?}"); + let landed = fx.projects.merge_revert(&factory, &revert).unwrap(); + assert_eq!(git(&fx.project, &["rev-parse", "HEAD"]), landed); + assert!(!fx.project.join("b.txt").exists()); + assert!( + fx.project.join("c.txt").exists(), + "only that merge is undone" + ); +} + +#[test] +fn a_conflict_and_a_dirty_main_are_found_before_merge() { + let mut fx = fixture(); + let factory = factory(&fx.project, &[]); + let t = task(&fx, "T-2", "a.txt", "branch\n"); + write(&fx.project, "a.txt", "main\n"); + git(&fx.project, &["commit", "--quiet", "-am", "main edit"]); + assert_eq!( + fx.projects.premerge(&factory, &t).unwrap(), + PreMerge::Conflict { + files: vec!["a.txt".into()] + } + ); + + write(&fx.project, "a.txt", "uncommitted\n"); + assert!(fx.projects.main_dirty(&factory).unwrap()); +} + +#[test] +fn a_risk_path_and_a_quick_check_gate_the_merge() { + let mut fx = fixture(); + let mut factory = factory(&fx.project, &[]); + factory.config.risk_paths = vec!["migrations/**".into()]; + std::fs::create_dir(fx.project.with_file_name("unused")).unwrap(); + let mut t = task(&fx, "T-3", "m.sql", "x\n"); + let worktree = PathBuf::from(&t.worker.as_ref().unwrap().worktree); + std::fs::create_dir(worktree.join("migrations")).unwrap(); + write(&worktree, "migrations/001.sql", "create\n"); + git(&worktree, &["add", "."]); + git(&worktree, &["commit", "--quiet", "-m", "migration"]); + assert_eq!( + fx.projects.premerge(&factory, &t).unwrap(), + PreMerge::RiskPath { + paths: vec!["migrations/001.sql".into()] + } + ); + factory.config.quick_check = Some("test -f missing".into()); + assert_eq!( + fx.projects.premerge(&factory, &t).unwrap(), + PreMerge::QuickCheckFailed { + check: "test -f missing".into() + } + ); + t.worker = None; + assert!( + fx.projects.premerge(&factory, &t).is_err(), + "no worktree is a failure, not a pass" + ); +} From bc840057c96dbf990f143e356d46099a22c6f6ff Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 04:10:42 +0900 Subject: [PATCH 04/72] Run the Factory in the core and add the hide factory command The core starts a Factory host thread beside the delivery worker. It owns the engine, ticks it, delivers worker letters through the ledger, and judges with its own provider queue. Each Factory is a code-owned mailbox recipient factory:; only the host sends as it, a pane may only send to it, and a pane or registration under a factory: name is refused. hided forwards hide factory commands over the pane capability socket, and the session guidance names hide factory add. --- Cargo.lock | 2 + herdr-core/Cargo.toml | 1 + herdr-core/src/ai.rs | 11 + herdr-core/src/coordination/executor.rs | 39 + herdr-core/src/coordination/mod.rs | 62 +- herdr-core/src/delivery/human.rs | 5 +- herdr-core/src/delivery/mod.rs | 31 + herdr-core/src/delivery/watch.rs | 25 +- herdr-core/src/delivery/worker.rs | 47 +- herdr-core/src/factory.rs | 1101 +++++++++++++++++++++++ herdr-core/src/handle.rs | 48 + herdr-core/src/lib.rs | 1 + herdr-core/src/runtime.rs | 5 + herdr-core/src/runtime/delivery.rs | 152 ++++ herdr-core/src/runtime/factory.rs | 226 +++++ hide-agent-hooks/src/runtime.rs | 9 +- hide-factory/src/adapters.rs | 4 +- hide-factory/src/command.rs | 3 +- hide-factory/src/engine.rs | 29 +- hide-factory/src/model.rs | 11 + hide-factory/src/store.rs | 48 +- hide-factory/tests/github.rs | 2 + hide-factory/tests/local_git.rs | 2 + hide-factory/tests/support/mod.rs | 18 +- hide-kit/src/layout.rs | 12 + hided/Cargo.toml | 1 + hided/src/cli.rs | 6 + hided/src/core.rs | 49 + hided/src/factory_cli.rs | 562 ++++++++++++ hided/src/lib.rs | 1 + hided/src/server.rs | 54 +- hided/src/workspace_cli.rs | 37 +- 32 files changed, 2552 insertions(+), 52 deletions(-) create mode 100644 herdr-core/src/factory.rs create mode 100644 herdr-core/src/runtime/factory.rs create mode 100644 hided/src/factory_cli.rs diff --git a/Cargo.lock b/Cargo.lock index 8cb8cf916b..0e5825daf7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1159,6 +1159,7 @@ dependencies = [ "cap-std", "hide-agent-hooks", "hide-ai", + "hide-factory", "hide-herdr-client", "hide-host", "hide-kit", @@ -1345,6 +1346,7 @@ dependencies = [ "getrandom 0.2.16", "herdr-core", "hex", + "hide-factory", "hide-herdr-client", "hide-host", "hide-kit", diff --git a/herdr-core/Cargo.toml b/herdr-core/Cargo.toml index 2b2b7030a2..bd221da202 100644 --- a/herdr-core/Cargo.toml +++ b/herdr-core/Cargo.toml @@ -12,6 +12,7 @@ anyhow = "=1.0.104" hide-agent-hooks = { path = "../hide-agent-hooks" } hide-kit = { path = "../hide-kit" } hide-ai = { path = "../hide-ai" } +hide-factory = { path = "../hide-factory" } hide-herdr-client = { path = "../hide-herdr-client" } hide-host = { path = "../hide-host" } hide-memory = { path = "../hide-memory" } diff --git a/herdr-core/src/ai.rs b/herdr-core/src/ai.rs index 5e0f530773..cfe7c2edc3 100644 --- a/herdr-core/src/ai.rs +++ b/herdr-core/src/ai.rs @@ -160,6 +160,17 @@ pub(crate) fn memory_router(settings: &AiSettings) -> AiRouter { ) } +/// The Software Factory's own router (PRD software-factory D-13, D-44): the +/// operator's provider choice with one request in flight, separate from the +/// label and Project Memory routers so its queue never takes their budget. +pub(crate) fn factory_router(settings: &AiSettings) -> AiRouter { + AiRouter::new( + backends(&settings.models), + settings.router_config(), + Arc::new(DiagnosticLogSink), + ) +} + /// The same provider boundary for agent labels (PRD labels-in-hided D-05): /// the operator's provider and model choice, and the router's own retry, /// cooldown and budget rules. diff --git a/herdr-core/src/coordination/executor.rs b/herdr-core/src/coordination/executor.rs index 6dbf3671e8..11411dd3d6 100644 --- a/herdr-core/src/coordination/executor.rs +++ b/herdr-core/src/coordination/executor.rs @@ -293,6 +293,45 @@ fn publish_tokens(client: &Client, connector: &dyn ApiConnector, id: &str) -> Re } Ok(()) } +/// Registers a Factory's code-owned identity as the parent its workers are +/// spawned under (D-14); converges on the existing record. +pub(crate) fn register_code_owned( + client: &Client, + authority: &Authority, + actor: &Actor, +) -> Result { + if !actor.code_owned() { + return Err("reserved_name".into()); + } + let record = AgentRecord { + id: String::new(), + name: actor.name.clone(), + machine: actor.device_id.clone(), + host_scope: crate::delivery::FACTORY_KIND.into(), + native_machine: crate::delivery::FACTORY_KIND.into(), + session: actor.name.clone(), + instance: actor.pane_id.clone(), + pane: actor.pane_id.clone(), + parent: None, + project: None, + actor: actor.clone(), + ended: false, + }; + let registered = mutate( + client, + authority, + actor, + Mutation::Register { + record, + check: false, + }, + )?; + registered["id"] + .as_str() + .map(str::to_owned) + .ok_or_else(|| "parent_unavailable".into()) +} + fn spawn( client: &Client, authority: &Authority, diff --git a/herdr-core/src/coordination/mod.rs b/herdr-core/src/coordination/mod.rs index 6a72f083bc..6081273887 100644 --- a/herdr-core/src/coordination/mod.rs +++ b/herdr-core/src/coordination/mod.rs @@ -218,6 +218,14 @@ pub(crate) fn apply( ) -> Result { match mutation { Mutation::Register { record, check } => { + // Only a Factory registers under its own reserved name (D-14). + if (record.actor.code_owned() && !record.actor.same_identity(caller)) + || (!record.actor.code_owned() + && (crate::delivery::reserved_name(&record.name) + || crate::delivery::reserved_name(&record.pane))) + { + return Err("reserved_name".into()); + } if record.parent.as_ref().is_some_and(|id| { !ledger .agents @@ -523,7 +531,7 @@ fn allocate(ledger: &mut Ledger, prefix: &str) -> Result { Ok(format!("{prefix}-{id}")) } -pub(crate) use executor::{link_fork, run}; +pub(crate) use executor::{link_fork, register_code_owned, run}; #[cfg(test)] mod tests { @@ -578,6 +586,58 @@ mod tests { args: vec!["--model".into(), "fixture model".into()], } } + fn register_as( + ledger: &mut Ledger, + record: AgentRecord, + caller: &Actor, + ) -> Result { + apply( + ledger, + caller, + &Mutation::Register { + record, + check: false, + }, + 1, + ) + } + + #[test] + fn only_a_factory_registers_under_a_factory_name() { + let mut ledger = Ledger::default(); + // A pane named or placed like a Factory is refused. + let named = record("factory:f-1", "native-impostor", None); + let caller = named.actor.clone(); + assert_eq!( + register_as(&mut ledger, named, &caller).unwrap_err(), + "reserved_name" + ); + let mut placed = record("pane-1", "native-pane", None); + placed.name = "factory:f-1".into(); + let caller = placed.actor.clone(); + assert_eq!( + register_as(&mut ledger, placed, &caller).unwrap_err(), + "reserved_name" + ); + // A pane cannot register the Factory's own record either. + let factory = Actor::factory("f-1"); + let mut owned = record("factory:f-1", "factory:f-1", None); + owned.actor = factory.clone(); + let pane = record("pane-2", "native-pane-2", None).actor; + assert_eq!( + register_as(&mut ledger, owned.clone(), &pane).unwrap_err(), + "reserved_name" + ); + // The Factory registers itself, and its worker as its child. + let id = register(&mut ledger, owned, &factory); + let worker = record("worker-pane", "native-worker", Some(id.clone())); + let child = register(&mut ledger, worker, &factory); + assert_eq!( + ledger.agents.iter().find(|r| r.id == child).unwrap().parent, + Some(id) + ); + } + #[test] fn registration_check_is_read_only_and_execution_identity_replays_after_reload() { let mut ledger = Ledger::default(); diff --git a/herdr-core/src/delivery/human.rs b/herdr-core/src/delivery/human.rs index 25f170cf29..eeaeb3975d 100644 --- a/herdr-core/src/delivery/human.rs +++ b/herdr-core/src/delivery/human.rs @@ -15,7 +15,10 @@ pub(super) fn claim(ledger: &mut Ledger, now: u64) -> Vec { let Some(warning) = &letter.watch_warning else { continue; }; - if warning.ordinal != 1 + // A Factory observer stops the quiet worker itself and puts it in + // the person's inbox, which replaces this alert. + if letter.recipient.code_owned() + || warning.ordinal != 1 || now.saturating_sub(letter.created_at_unix_ms) < super::SECOND_WARNING_MS || matches!(letter.state, State::Acknowledged | State::Cancelled) || ledger.letters.iter().any(|answer| { diff --git a/herdr-core/src/delivery/mod.rs b/herdr-core/src/delivery/mod.rs index 4e4c75fd7b..998b1189c3 100644 --- a/herdr-core/src/delivery/mod.rs +++ b/herdr-core/src/delivery/mod.rs @@ -31,7 +31,33 @@ pub struct Actor { pub session: Option, } +/// The kind of a code-owned recipient: a Software Factory's engine, which +/// reads its own letters from the ledger with no pane, composer or doorbell +/// (D-14). Only the core's Factory host constructs one. +pub const FACTORY_KIND: &str = "factory"; +pub const FACTORY_PREFIX: &str = "factory:"; +/// A watch whose observer is a Factory warns after this long (PRD +/// software-factory, Technical structure: the window is per watch). +pub const FACTORY_INACTIVITY_MS: u64 = 30 * 60_000; + impl Actor { + /// The code-owned recipient `factory:` on this machine. + pub fn factory(id: &str) -> Self { + let name = format!("{FACTORY_PREFIX}{id}"); + Self { + pane_id: name.clone(), + name: name.clone(), + kind: FACTORY_KIND.into(), + device_id: "local".into(), + session: crate::wire::session_digest(&name), + } + } + + /// Whether this is a Factory's code-owned identity rather than a pane's. + pub fn code_owned(&self) -> bool { + self.kind == FACTORY_KIND && self.pane_id.starts_with(FACTORY_PREFIX) + } + /// Mailbox authority requires a positively observed native session. Watch /// targets may lack it and use status-only activity, without mailbox access. pub(crate) fn require_native_identity(&self) -> Result<(), String> { @@ -57,6 +83,11 @@ impl Actor { } } +/// A name or pane a pane may never claim: it would read as a Factory. +pub(crate) fn reserved_name(value: &str) -> bool { + value.starts_with(FACTORY_PREFIX) +} + pub(crate) fn valid_key(value: &str) -> bool { !value.is_empty() && value.len() <= 256 && !value.chars().any(char::is_control) } diff --git a/herdr-core/src/delivery/watch.rs b/herdr-core/src/delivery/watch.rs index f844a50f47..5ba6692c17 100644 --- a/herdr-core/src/delivery/watch.rs +++ b/herdr-core/src/delivery/watch.rs @@ -68,6 +68,16 @@ impl Watch { } } +/// How long a watch waits before its first warning: a Factory observer +/// stops a quiet worker after 30 minutes, every other observer after 20. +pub fn inactivity_window(watch: &Watch) -> u64 { + if watch.parent.code_owned() { + super::FACTORY_INACTIVITY_MS + } else { + INACTIVITY_MS + } +} + pub fn start( ledger: &mut Ledger, parent: &Actor, @@ -279,7 +289,7 @@ pub fn tick(ledger: &mut Ledger, readings: &[Reading], now: u64) -> Result now.saturating_sub(activity) >= INACTIVITY_MS, + (0, _) => now.saturating_sub(activity) >= inactivity_window(watch), (1, Some(first)) => now.saturating_sub(first) >= SECOND_WARNING_MS, _ => false, }; @@ -539,6 +549,19 @@ mod tests { assert_eq!(ledger, before); } + #[test] + fn a_factory_observer_warns_after_thirty_quiet_minutes_not_twenty() { + let mut ledger = Ledger::default(); + let factory = Actor::factory("f-1"); + let watch = start(&mut ledger, &factory, &actor("worker"), 10).unwrap(); + tick(&mut ledger, &[reading(&watch.id, 10)], 10 + INACTIVITY_MS).unwrap(); + assert!(ledger.letters.is_empty()); + tick(&mut ledger, &[reading(&watch.id, 10)], 10 + 30 * 60_000 - 1).unwrap(); + assert!(ledger.letters.is_empty()); + tick(&mut ledger, &[reading(&watch.id, 10)], 10 + 30 * 60_000).unwrap(); + assert_eq!(ledger.letters.len(), 1); + } + #[test] fn two_warnings_keep_the_first_deadline_across_restart_and_reset_on_activity() { let mut ledger = Ledger::default(); diff --git a/herdr-core/src/delivery/worker.rs b/herdr-core/src/delivery/worker.rs index 2fa404003d..06cc1aaa82 100644 --- a/herdr-core/src/delivery/worker.rs +++ b/herdr-core/src/delivery/worker.rs @@ -688,6 +688,14 @@ fn run( .lock() .map_err(|_| "delivery_unavailable".to_owned()) .and_then(|guard| { + if actor.code_owned() { + // Only the core's Factory host holds this + // authority; it has no pane to re-check. + return guard + .factory_authority_current(&authority.caller, actor) + .then_some(()) + .ok_or_else(|| "caller_identity_changed".into()); + } let context = guard .workspace_control_query( &actor.device_id, @@ -718,18 +726,28 @@ fn run( .lock() .map_err(|_| "delivery_unavailable".to_owned()) .and_then(|guard| { - for caller in [&authority.caller, &actor.pane_id] { - let current = guard - .workspace_control_query(&actor.device_id, caller, Query::Info) - .map_err(|_| "caller_context_changed")? - .context; - if current != authority.context { - return Err("caller_context_changed".into()); + if actor.code_owned() { + if !guard.factory_authority_current(&authority.caller, actor) { + return Err("caller_identity_changed".into()); + } + } else { + for caller in [&authority.caller, &actor.pane_id] { + let current = guard + .workspace_control_query( + &actor.device_id, + caller, + Query::Info, + ) + .map_err(|_| "caller_context_changed")? + .context; + if current != authority.context { + return Err("caller_context_changed".into()); + } + } + actor.require_native_identity()?; + if !guard.delivery_identity_current(actor) { + return Err("caller_identity_changed".into()); } - } - actor.require_native_identity()?; - if !guard.delivery_identity_current(actor) { - return Err("caller_identity_changed".into()); } if target_required { let target = target.as_ref().ok_or("target_unavailable")?; @@ -739,7 +757,12 @@ fn run( ) { target.actor.require_native_identity()?; } - if !guard.delivery_identity_current(&target.actor) { + let current = if target.actor.code_owned() { + guard.factory_recipient_current(&target.actor) + } else { + guard.delivery_identity_current(&target.actor) + }; + if !current { return Err("target_identity_changed".into()); } } diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs new file mode 100644 index 0000000000..a8dc51cef6 --- /dev/null +++ b/herdr-core/src/factory.rs @@ -0,0 +1,1101 @@ +//! The Software Factory host: the core owns one engine thread that runs every +//! Factory on this machine (PRD software-factory, Technical structure). The +//! engine never runs under `Mutex`; it takes the lock only to read +//! owned values or to ask the runtime for a delivery, a sleep or a wake. +//! +//! The engine opens its store the first time it is asked, or at start when a +//! store already exists, so a machine without a Factory pays nothing. + +use std::collections::{BTreeSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender}; +use std::sync::{Arc, Mutex, MutexGuard, Weak}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use hide_factory::adapters::{ + Clock, EnvSignal, Environment, Failure, Judge, MemoryPressure, Notifier, WorkerRuntime, + WorkerSpawn, WorkerStatus, +}; +use hide_factory::exec::SystemRunner; +use hide_factory::judgment::{Judgment, JudgmentAnswer, JudgmentOutcome}; +use hide_factory::model::{Runtime as AgentRuntime, UnixMs, WorkerRef}; +use hide_factory::project::{IssueBook, SharedProjects}; +use hide_factory::role::Role; +use hide_factory::{Command, Engine, Inbound, Ports, Refusal}; +use serde_json::{Value, json}; + +use crate::delivery; +use crate::runtime::Runtime; + +/// How often time and the outside world move the engine. +const TICK: Duration = Duration::from_secs(2); +const QUEUE_LIMIT: usize = 32; +/// The longest `add` waits for its review before answering pending (B10). +const REVIEW_WAIT: Duration = Duration::from_secs(90); +const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10); +/// A worker the snapshot does not show yet is still starting this long. +const START_GRACE_MS: u64 = 3 * 60_000; +/// The longest prompt argument; the rest is read with `hide factory show`. +const PROMPT_LIMIT: usize = 6 * 1024; +const JUDGMENT_DEADLINE: Duration = Duration::from_secs(180); + +fn now_ms() -> UnixMs { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_millis() as UnixMs) +} + +fn lock(runtime: &Weak>) -> Option>> { + runtime.upgrade() +} + +fn guard(runtime: &Arc>) -> MutexGuard<'_, Runtime> { + runtime.lock().unwrap_or_else(|poison| poison.into_inner()) +} + +/// Who is asking: the pane the command came from and the checkout it runs in. +pub struct FactoryCaller { + pub pane: Option, + pub cwd: Option, +} + +enum Request { + Command { + caller: FactoryCaller, + command: Command, + reply: SyncSender, + }, +} + +pub(crate) struct FactoryHost { + requests: SyncSender, + stop: Arc, + thread: Option>, +} + +/// A Factory command ready to run off the owner thread. +pub struct PreparedFactory { + requests: SyncSender, + caller: FactoryCaller, + command: Command, +} + +impl PreparedFactory { + pub fn run(self, timeout: Duration) -> Result { + let (reply, answer) = mpsc::sync_channel(1); + self.requests + .try_send(Request::Command { + caller: self.caller, + command: self.command, + reply, + }) + .map_err(|_| "factory_busy".to_owned())?; + answer + .recv_timeout(timeout) + .map_err(|_| "factory_timeout".to_owned()) + } +} + +impl FactoryHost { + pub(crate) fn start( + state_dir: &Path, + home: Option, + runtime: Weak>, + ) -> Result { + let (requests, receiver) = mpsc::sync_channel(QUEUE_LIMIT); + let stop = Arc::new(AtomicBool::new(false)); + let paths = Paths { + store: hide_kit::layout::factory_store(state_dir), + files: hide_kit::layout::factory_files(state_dir), + }; + let thread_stop = Arc::clone(&stop); + let thread = thread::Builder::new() + .name("herdr-core-factory".into()) + .spawn(move || run(paths, home, runtime, receiver, thread_stop)) + .map_err(|error| format!("factory engine thread could not start: {error}"))?; + Ok(Self { + requests, + stop, + thread: Some(thread), + }) + } + + pub(crate) fn prepare(&self, caller: FactoryCaller, command: Command) -> PreparedFactory { + PreparedFactory { + requests: self.requests.clone(), + caller, + command, + } + } + + pub(crate) fn shutdown(&mut self) { + self.stop.store(true, Ordering::Release); + if let Some(thread) = self.thread.take() + && thread.join().is_err() + { + crate::diagnostic!(json!({"component":"factory","kind":"engine.join_failed"})); + } + } +} + +impl Drop for FactoryHost { + fn drop(&mut self) { + self.shutdown(); + } +} + +struct Paths { + store: PathBuf, + files: PathBuf, +} + +/// A review an `add` waits for (B10). +struct Waiter { + factory: String, + task: String, + reply: SyncSender, + until: Instant, +} + +/// Shared between the engine thread and its worker port. +#[derive(Default)] +struct WorkerState { + /// Panes whose sleep was asked while the agent was still in its turn. + pending_sleep: BTreeSet, +} + +fn run( + paths: Paths, + home: Option, + runtime: Weak>, + requests: Receiver, + stop: Arc, +) { + let workers = Arc::new(Mutex::new(WorkerState::default())); + let runner_stop = Arc::clone(&stop); + let mut engine: Option = None; + let mut judge: Option = None; + let open = |judge: &mut Option| -> Option { + let started = JudgeThread::start(runtime.clone(), home.clone()); + let port = started.port(); + *judge = Some(started); + let projects = SharedProjects::new( + Box::new(SystemRunner { + stop: Arc::clone(&runner_stop), + }), + Box::new(CoreIssues { + runtime: runtime.clone(), + }), + paths.files.join("logs"), + ); + let ports = Ports { + clock: Box::new(SystemClock), + source: Box::new(projects.clone()), + verifier: Box::new(projects.clone()), + merge: Box::new(projects), + workers: Box::new(CoreWorkers { + runtime: runtime.clone(), + state: Arc::clone(&workers), + }), + judge: Box::new(port), + environment: Box::new(MachineEnvironment), + notifier: Box::new(CoreNotifier { + runtime: runtime.clone(), + }), + }; + match Engine::open(&paths.store, &paths.files, ports) { + Ok(engine) => Some(engine), + Err(error) => { + crate::diagnostic!( + json!({"component":"factory","kind":"store.open_failed","error":error.0}) + ); + None + } + } + }; + if paths.store.exists() { + engine = open(&mut judge); + publish_recipients(engine.as_ref(), &runtime); + } + let mut waiters: Vec = Vec::new(); + let mut last_tick = Instant::now(); + while !stop.load(Ordering::Acquire) { + match requests.recv_timeout(TICK) { + Ok(Request::Command { + caller, + command, + reply, + }) => { + if engine.is_none() { + engine = open(&mut judge); + } + let Some(engine) = engine.as_mut() else { + let _ = reply.send( + Refusal::new("factory_unavailable", "See the diagnostic log").to_json(), + ); + continue; + }; + let added = matches!(command, Command::Add { .. }); + let answer = handle(engine, &runtime, &caller, command); + publish_recipients(Some(engine), &runtime); + if added + && answer["result"] == "pending" + && let (Some(factory), Some(task)) = + (owner_of(engine, &answer), answer["task"]["id"].as_str()) + { + waiters.push(Waiter { + factory, + task: task.to_owned(), + reply, + until: Instant::now() + REVIEW_WAIT, + }); + continue; + } + let _ = reply.send(answer); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => break, + } + let Some(engine) = engine.as_mut() else { + continue; + }; + if last_tick.elapsed() >= TICK { + last_tick = Instant::now(); + pump_letters(engine, &runtime); + engine.tick(); + settle_sleeps(&workers, &runtime); + publish_recipients(Some(engine), &runtime); + } + waiters.retain(|waiter| { + let settled = engine.review_settled(&waiter.factory, &waiter.task); + if settled || Instant::now() >= waiter.until { + let _ = waiter + .reply + .send(engine.add_answer(&waiter.factory, &waiter.task)); + return false; + } + true + }); + } + drop(engine); + drop(judge); +} + +fn owner_of(engine: &Engine, answer: &Value) -> Option { + let task = answer["task"]["id"].as_str()?; + engine + .factories() + .find(|factory| engine.task(&factory.id, task).is_some()) + .map(|factory| factory.id.clone()) +} + +/// Open Factories become delivery recipients; closed ones stop receiving. +fn publish_recipients(engine: Option<&Engine>, runtime: &Weak>) { + let ids: BTreeSet = engine + .into_iter() + .flat_map(Engine::factories) + .filter(|factory| !factory.closed) + .map(|factory| factory.id.clone()) + .collect(); + if let Some(runtime) = lock(runtime) { + guard(&runtime).set_factory_recipients(ids); + } +} + +/// Runs one command with the caller's role (D-33). A worker's report travels +/// as a ledger letter from its own pane, so a harness that only speaks the +/// letter protocol lands on the same path (B25). +fn handle( + engine: &mut Engine, + runtime: &Weak>, + caller: &FactoryCaller, + command: Command, +) -> Value { + let role = match engine.role_for(caller.pane.as_deref(), caller.cwd.as_deref()) { + Some((factory, task)) => Role::Worker { factory, task }, + None => Role::Operator { + pane: caller.pane.clone().unwrap_or_else(|| "checkout".into()), + }, + }; + // A pending review answers the pane that added the Task (B11); that is + // the caller, never a pane the request names. + let command = match command { + Command::Add { + project, + task, + issue, + card, + producer_pane: _, + } => Command::Add { + project, + task, + issue, + card, + producer_pane: caller.pane.clone(), + }, + other => other, + }; + let kind = match &command { + Command::Ask { .. } | Command::Propose { .. } => Some("request"), + Command::Block { .. } => Some("block"), + Command::Done { .. } => Some("report"), + _ => None, + }; + let (Role::Worker { factory, .. }, Some(kind), Some(pane)) = (&role, kind, &caller.pane) else { + return engine.command(&role, command); + }; + let body = json!({"factory": command}).to_string(); + let intent = format!( + "factory-{}", + &hide_factory::store::sha256_hex(format!("{pane}\n{body}").as_bytes())[..24] + ); + let letter = (|| { + let runtime = lock(runtime).ok_or("delivery_unavailable")?; + let prepared = guard(&runtime).factory_worker_letter( + pane, + factory, + delivery::Command::Send { + target: format!("{}{factory}", delivery::FACTORY_PREFIX), + intent, + body: body.clone(), + kind: kind.into(), + }, + )?; + prepared.run(DELIVERY_TIMEOUT) + })(); + let letter = match letter { + Ok(letter) => letter, + Err(reason) => { + return Refusal::new(&reason, "Retry; the report is applied once").to_json(); + } + }; + let Some(id) = letter["id"].as_str() else { + return Refusal::new("letter_unavailable", "Retry").to_json(); + }; + let answer = engine.letter(Inbound { + id: id.to_owned(), + factory: factory.clone(), + sender_pane: pane.clone(), + kind: kind.to_owned(), + body, + }); + close_letter(runtime, factory, id, kind, &answer); + answer +} + +/// Takes a letter in and answers a request at once; a later answer from a +/// person reaches the worker as its own letter. +fn close_letter( + runtime: &Weak>, + factory: &str, + id: &str, + kind: &str, + answer: &Value, +) { + let mut commands = vec![delivery::Command::Confirm { + ids: vec![id.to_owned()], + }]; + if matches!(kind, "request" | "block") { + commands.push(delivery::Command::Reply { + id: id.to_owned(), + intent: format!("{id}-answer"), + body: answer.to_string(), + }); + } + for command in commands { + let result = (|| { + let runtime = lock(runtime).ok_or("delivery_unavailable")?; + let prepared = guard(&runtime).factory_prepare(factory, None, command)?; + prepared.run(DELIVERY_TIMEOUT) + })(); + if let Err(reason) = result { + crate::diagnostic!( + json!({"component":"factory","kind":"letter.close_failed","factory":factory,"letter":id,"reason":reason}) + ); + } + } +} + +/// Letters a harness or a watch sent to a Factory (B25, B24). +fn pump_letters(engine: &mut Engine, runtime: &Weak>) { + let Some(arc) = lock(runtime) else { return }; + let ledger = match guard(&arc).delivery_state() { + Ok(ledger) => ledger, + Err(_) => return, + }; + drop(arc); + let pending: Vec<(String, Inbound)> = ledger + .letters + .iter() + .filter(|letter| letter.recipient.code_owned() && !letter.intake_confirmed()) + .filter(|letter| !engine.letter_seen(&letter.id)) + .filter_map(|letter| { + let factory = letter + .recipient + .pane_id + .strip_prefix(delivery::FACTORY_PREFIX)? + .to_owned(); + let sender_pane = match &letter.watch_warning { + Some(warning) => warning.target.pane_id.clone(), + None => letter.sender.pane_id.clone(), + }; + Some(( + letter.kind.clone(), + Inbound { + id: letter.id.clone(), + factory, + sender_pane, + kind: letter.kind.clone(), + body: letter.body.clone(), + }, + )) + }) + .take(16) + .collect(); + for (kind, letter) in pending { + let factory = letter.factory.clone(); + let id = letter.id.clone(); + let answer = engine.letter(letter); + close_letter(runtime, &factory, &id, &kind, &answer); + } +} + +fn settle_sleeps(state: &Arc>, runtime: &Weak>) { + let panes: Vec = state + .lock() + .map(|state| state.pending_sleep.iter().cloned().collect()) + .unwrap_or_default(); + if panes.is_empty() { + return; + } + let Some(runtime) = lock(runtime) else { return }; + let mut done = Vec::new(); + { + let mut runtime = guard(&runtime); + for pane in &panes { + match runtime.factory_sleep(pane) { + Ok(true) => done.push(pane.clone()), + Ok(false) => {} + Err(reason) => { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.sleep_refused","pane_id":pane,"reason":reason}) + ); + done.push(pane.clone()); + } + } + } + } + if let Ok(mut state) = state.lock() { + for pane in done { + state.pending_sleep.remove(&pane); + } + } +} + +struct SystemClock; + +impl Clock for SystemClock { + fn now(&self) -> UnixMs { + now_ms() + } +} + +/// Starts, messages, sleeps and wakes workers through coordination, the +/// delivery ledger and agent sleep (D-14). Nothing here holds the runtime +/// lock across Herdr or ledger work. +struct CoreWorkers { + runtime: Weak>, + state: Arc>, +} + +impl CoreWorkers { + fn runtime(&self) -> Result>, Failure> { + lock(&self.runtime) + .ok_or_else(|| Failure::environment("worker", EnvSignal::HerdrSocket, "core stopped")) + } + + fn deliver( + &self, + factory: &str, + target: Option<&str>, + command: delivery::Command, + ) -> Result { + let runtime = self.runtime()?; + let prepared = guard(&runtime) + .factory_prepare(factory, target, command) + .map_err(|reason| Failure::task("delivery", reason))?; + drop(runtime); + prepared + .run(DELIVERY_TIMEOUT) + .map_err(|reason| Failure::task("delivery", reason)) + } + + /// The watch that stops a quiet worker after 30 minutes (B24). + fn watch(&self, worker: &WorkerRef) { + let Some(pane) = &worker.pane else { return }; + if let Err(failure) = self.deliver( + &worker.factory, + Some(pane), + delivery::Command::WatchStart { + target: pane.clone(), + observer: None, + actor: None, + }, + ) { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.watch_failed","pane_id":pane,"reason":failure.detail}) + ); + } + } +} + +impl WorkerRuntime for CoreWorkers { + fn spawn(&mut self, request: &WorkerSpawn) -> Result { + let runtime = self.runtime()?; + let (client, authority, actor) = guard(&runtime) + .factory_delivery(&request.factory) + .map_err(|reason| Failure::task("worker.spawn", reason))?; + drop(runtime); + let parent = crate::coordination::register_code_owned(&client, &authority, &actor) + .map_err(|reason| Failure::task("worker.spawn", reason))?; + let mut args = request.args.clone(); + args.push(prompt_argument(&request.prompt, &request.task)?); + let (intent, path) = match &request.resume { + Some(previous) => { + if let Some(agent) = &previous.agent { + let _ = crate::coordination::run( + client.clone(), + crate::delivery::worker::Authority { + caller: authority.caller.clone(), + context: authority.context.clone(), + }, + actor.clone(), + crate::coordination::Command::End { + id: agent.clone(), + actor: None, + }, + ); + } + ( + format!("factory-{}-{}-{}", request.factory, request.task, now_ms()), + Some(previous.worktree.clone()), + ) + } + None => ( + format!("factory-{}-{}", request.factory, request.task), + None, + ), + }; + let view = crate::coordination::run( + client, + authority, + actor, + crate::coordination::Command::Spawn { + parent, + name: request.name.clone(), + intent, + kind: request.runtime.as_str().into(), + repo: request.project.clone(), + branch: request.branch.clone(), + path, + no_watch: false, + args, + }, + ) + .map_err(|reason| spawn_failure(&reason))?; + Ok(WorkerRef { + factory: request.factory.clone(), + agent: view["id"].as_str().map(str::to_owned), + name: request.name.clone(), + pane: view["pane"].as_str().map(str::to_owned), + runtime: request.runtime, + worktree: view["project"].as_str().unwrap_or_default().to_owned(), + branch: request.branch.clone(), + started_at: now_ms(), + asleep: false, + }) + } + + fn message( + &mut self, + worker: &WorkerRef, + intent: &str, + reply_to: Option<&str>, + body: &str, + ) -> Result<(), Failure> { + let pane = worker + .pane + .clone() + .ok_or_else(|| Failure::task("worker.message", "no pane"))?; + let _ = reply_to; + self.deliver( + &worker.factory, + Some(&pane), + delivery::Command::Send { + target: pane.clone(), + intent: intent.to_owned(), + body: body.to_owned(), + kind: "report".into(), + }, + )?; + self.watch(worker); + Ok(()) + } + + fn sleep(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + let pane = worker + .pane + .clone() + .ok_or_else(|| Failure::task("worker.sleep", "no pane"))?; + // The agent is usually still in the turn that reported; the sleep + // lands once its turn ends. + if let Ok(mut state) = self.state.lock() { + state.pending_sleep.insert(pane); + } + Ok(()) + } + + fn wake(&mut self, worker: &WorkerRef, body: &str) -> Result<(), Failure> { + let pane = worker + .pane + .clone() + .ok_or_else(|| Failure::task("worker.wake", "no pane"))?; + let never_slept = self + .state + .lock() + .map(|mut state| state.pending_sleep.remove(&pane)) + .unwrap_or(false); + if !never_slept { + let runtime = self.runtime()?; + guard(&runtime).factory_wake(&pane); + } + // The letter waits in the ledger; the doorbell rings once the agent + // is back at its prompt. + let intent = format!("factory-wake-{}-{}", pane, now_ms()); + self.message(worker, &intent, None, body) + } + + fn status(&mut self, worker: &WorkerRef) -> WorkerStatus { + let Some(pane) = &worker.pane else { + return WorkerStatus::Gone; + }; + let pending = self + .state + .lock() + .is_ok_and(|state| state.pending_sleep.contains(pane)); + let Ok(runtime) = self.runtime() else { + return WorkerStatus::Working; + }; + let probe = guard(&runtime).factory_worker_probe(pane); + if probe.asleep || pending { + return WorkerStatus::Resting { + since: probe.status_changed_at_unix_ms, + }; + } + if !probe.present { + return if now_ms().saturating_sub(worker.started_at) < START_GRACE_MS { + WorkerStatus::Working + } else { + WorkerStatus::Gone + }; + } + if probe.working { + WorkerStatus::Working + } else if probe.waiting { + WorkerStatus::Blocked + } else { + WorkerStatus::Resting { + since: probe.status_changed_at_unix_ms, + } + } + } + + fn stop(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + let Some(agent) = &worker.agent else { + return Ok(()); + }; + if let Some(pane) = &worker.pane + && let Ok(mut state) = self.state.lock() + { + state.pending_sleep.remove(pane); + } + let runtime = self.runtime()?; + let (client, authority, actor) = guard(&runtime) + .factory_delivery(&worker.factory) + .map_err(|reason| Failure::task("worker.stop", reason))?; + drop(runtime); + crate::coordination::run( + client, + authority, + actor, + crate::coordination::Command::End { + id: agent.clone(), + actor: None, + }, + ) + .map(|_| ()) + .map_err(|reason| Failure::task("worker.stop", reason)) + } + + fn remove_worktree(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + let runtime = self.runtime()?; + let connector = guard(&runtime).delivery_connector("local"); + drop(runtime); + let connector = connector + .ok_or_else(|| Failure::environment("worktree", EnvSignal::HerdrSocket, "no Herdr"))?; + let panes: Vec = worker.pane.iter().cloned().collect(); + // The worker's panes close first so nothing runs in a removed folder. + crate::live::close_checkout_panes( + connector.as_ref(), + std::slice::from_ref(&worker.worktree), + &panes, + crate::live::ProcessWait::for_folder_removal(true), + crate::live::CONFIRM_TIMEOUT, + ) + .map_err(|reason| Failure::task("worktree.close", reason))?; + let mut runner = SystemRunner { + stop: Arc::new(AtomicBool::new(false)), + }; + if Path::new(&worker.worktree).exists() { + hide_factory::exec::checked( + &mut runner, + "worktree.remove", + "git", + &["worktree", "remove", "--force", &worker.worktree], + Path::new(&worker.worktree).parent(), + )?; + } + Ok(()) + } + + fn usage_limited(&mut self, _runtime: AgentRuntime) -> Option { + None + } +} + +fn spawn_failure(reason: &str) -> Failure { + if reason.contains("socket") + || reason.contains("delivery_unavailable") + || reason.contains("unavailable") + { + Failure::environment("worker.spawn", EnvSignal::HerdrSocket, reason) + } else { + Failure::task("worker.spawn", reason) + } +} + +/// The worker's first prompt as the one argument Herdr types into the pane +/// (`live::prompt_argument`), short enough for the spawn's argument limit; +/// the full card is one `hide factory show` away. +fn prompt_argument(prompt: &str, task: &str) -> Result { + let clean: String = prompt + .chars() + .map(|c| { + if c.is_control() && c != '\n' && c != '\t' { + ' ' + } else { + c + } + }) + .collect(); + let mut limit = PROMPT_LIMIT; + loop { + let text = if clean.len() <= limit { + clean.clone() + } else { + let mut end = limit; + while !clean.is_char_boundary(end) { + end -= 1; + } + format!( + "{}\n\n(이어지는 내용은 `hide factory show {task}`로 읽으세요.)", + &clean[..end] + ) + }; + match crate::live::prompt_argument(&text) { + Ok(argument) => return Ok(argument), + Err(_) if limit > 1024 => limit /= 2, + Err(reason) => return Err(Failure::task("worker.prompt", reason)), + } + } +} + +/// Local issues (`L-`) live in the core's local issue store (B3). +struct CoreIssues { + runtime: Weak>, +} + +impl IssueBook for CoreIssues { + fn create( + &mut self, + project: &str, + title: &str, + body: &str, + marker: &str, + ) -> Result { + let runtime = lock(&self.runtime).ok_or_else(|| Failure::task("issue", "core stopped"))?; + let number = guard(&runtime).factory_local_issue(project, title, body, marker); + number.map_err(|reason| Failure::task("issue.create", reason)) + } + + fn read( + &mut self, + project: &str, + number: u32, + ) -> Result { + let runtime = lock(&self.runtime).ok_or_else(|| Failure::task("issue", "core stopped"))?; + let issue = guard(&runtime).factory_local_issue_read(project, number); + let issue = issue.ok_or_else(|| Failure::task("issue.read", "missing"))?; + Ok(hide_factory::adapters::IssueText { + title: issue.title, + body: issue.body, + open: issue.open, + }) + } +} + +struct MachineEnvironment; + +impl Environment for MachineEnvironment { + fn disk_free(&mut self, project: &str) -> Option { + hide_platform::fs::space::free_bytes(Path::new(project)).ok() + } + + /// macOS reports 1 (normal), 2 (warn) or 4 (critical). + fn memory_pressure(&mut self) -> MemoryPressure { + if !cfg!(target_os = "macos") { + return MemoryPressure::Normal; + } + let mut runner = SystemRunner { + stop: Arc::new(AtomicBool::new(false)), + }; + match hide_factory::exec::checked( + &mut runner, + "memory", + "/usr/sbin/sysctl", + &["-n", "kern.memorystatus_vm_pressure_level"], + None, + ) + .ok() + .and_then(|text| text.trim().parse::().ok()) + { + Some(4) => MemoryPressure::Critical, + Some(2) => MemoryPressure::Warn, + _ => MemoryPressure::Normal, + } + } +} + +struct CoreNotifier { + runtime: Weak>, +} + +impl Notifier for CoreNotifier { + fn macos(&mut self, title: &str, body: &str) { + let Some(runtime) = lock(&self.runtime) else { + return; + }; + let connector = guard(&runtime).delivery_connector("local"); + drop(runtime); + if let Some(connector) = connector { + let _ = hide_herdr_client::request_small_response( + connector.as_ref(), + "notification.show", + json!({"title": title, "body": body}), + Duration::from_millis(500), + ); + } + } + + /// A pending review's result goes to the pane that added the Task (B11). + fn producer(&mut self, factory: &str, pane: &str, body: &str) -> bool { + let Some(runtime) = lock(&self.runtime) else { + return false; + }; + let prepared = guard(&runtime).factory_prepare( + factory, + Some(pane), + delivery::Command::Send { + target: pane.to_owned(), + intent: format!( + "factory-review-{}", + &hide_factory::store::sha256_hex(body.as_bytes())[..16] + ), + body: body.to_owned(), + kind: "report".into(), + }, + ); + drop(runtime); + prepared + .and_then(|prepared| prepared.run(DELIVERY_TIMEOUT)) + .is_ok() + } +} + +/// The Factory's own judgment queue on its own router (D-13, D-44): one in +/// flight, intake reviews first, 16 waiting per Factory; a full queue or a +/// failed provider is answered as failed, never skipped (B19, B68). +struct JudgeThread { + shared: Arc, + thread: Option>, +} + +struct JudgeShared { + queue: Mutex>, + answers: Mutex>, + wake: std::sync::Condvar, + stop: AtomicBool, + cancel: hide_ai::CancelToken, +} + +impl JudgeThread { + fn start(runtime: Weak>, home: Option) -> Self { + let shared = Arc::new(JudgeShared { + queue: Mutex::new(VecDeque::new()), + answers: Mutex::new(Vec::new()), + wake: std::sync::Condvar::new(), + stop: AtomicBool::new(false), + cancel: hide_ai::CancelToken::new(), + }); + let worker = Arc::clone(&shared); + let thread = thread::Builder::new() + .name("herdr-core-factory-judge".into()) + .spawn(move || judge_loop(worker, runtime, home)) + .ok(); + Self { shared, thread } + } + + fn port(&self) -> JudgePort { + JudgePort { + shared: Arc::clone(&self.shared), + alive: self.thread.is_some(), + } + } +} + +impl Drop for JudgeThread { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Release); + self.shared.cancel.cancel(); + self.shared.wake.notify_all(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +struct JudgePort { + shared: Arc, + alive: bool, +} + +impl Judge for JudgePort { + fn submit(&mut self, judgment: Judgment) -> Result<(), Failure> { + if !self.alive { + return Err(Failure::task("judge", "the judgment thread did not start")); + } + let mut queue = self + .shared + .queue + .lock() + .map_err(|_| Failure::task("judge", "queue poisoned"))?; + let waiting = queue + .iter() + .filter(|queued| queued.factory == judgment.factory) + .count(); + if waiting >= hide_factory::judgment::QUEUE_LIMIT { + return Err(Failure::task( + "judge", + "the Factory's judgment queue is full", + )); + } + // Intake reviews go ahead of every other Factory judgment (D-44). + let position = queue + .iter() + .position(|queued| queued.priority > judgment.priority) + .unwrap_or(queue.len()); + queue.insert(position, judgment); + self.shared.wake.notify_one(); + Ok(()) + } + + fn finished(&mut self) -> Vec { + self.shared + .answers + .lock() + .map(|mut answers| std::mem::take(&mut *answers)) + .unwrap_or_default() + } +} + +fn judge_loop(shared: Arc, runtime: Weak>, home: Option) { + let mut router: Option<(hide_ai::AiSettings, hide_ai::AiRouter)> = None; + loop { + let judgment = { + let Ok(mut queue) = shared.queue.lock() else { + return; + }; + loop { + if shared.stop.load(Ordering::Acquire) { + return; + } + if let Some(judgment) = queue.pop_front() { + break judgment; + } + queue = match shared.wake.wait_timeout(queue, Duration::from_secs(5)) { + Ok((queue, _)) => queue, + Err(_) => return, + }; + } + }; + let settings = lock(&runtime) + .and_then(|runtime| guard(&runtime).factory_ai_settings()) + .or_else(|| { + home.as_deref() + .and_then(|home| hide_ai::settings::load(home).ok()) + }) + .unwrap_or_default(); + if router + .as_ref() + .is_none_or(|(current, _)| *current != settings) + { + router = Some((settings.clone(), crate::ai::factory_router(&settings))); + } + let Some((_, router)) = &router else { continue }; + let request = hide_ai::AiRequest { + feature_id: judgment.feature_id(), + request_id: hide_ai::RequestId(judgment.id.clone()), + subject_id: judgment + .task + .clone() + .unwrap_or_else(|| judgment.factory.clone()), + system: judgment.system().to_owned(), + input: judgment.render_input(), + output_schema: judgment.schema(), + deadline: JUDGMENT_DEADLINE, + schema_version: hide_factory::judgment::SCHEMA_VERSION, + }; + let started = Instant::now(); + let outcome = match router.execute(&request, &shared.cancel) { + Ok(result) => JudgmentOutcome::Answered { + value: result.value, + }, + Err(error) => JudgmentOutcome::Failed { + reason: error.class().to_owned(), + }, + }; + crate::diagnostic!(json!({"component":"factory","kind":"judgment.finished", + "feature":request.feature_id,"factory":judgment.factory,"task":judgment.task, + "ok":matches!(outcome, JudgmentOutcome::Answered { .. }),"elapsed_ms":started.elapsed().as_millis() as u64})); + if let Ok(mut answers) = shared.answers.lock() { + answers.push(JudgmentAnswer { + id: judgment.id.clone(), + factory: judgment.factory.clone(), + task: judgment.task.clone(), + outcome, + }); + } + } +} diff --git a/herdr-core/src/handle.rs b/herdr-core/src/handle.rs index 57aef1a910..12357847da 100644 --- a/herdr-core/src/handle.rs +++ b/herdr-core/src/handle.rs @@ -82,6 +82,7 @@ pub struct Core { _session_search: Option, _links: Option, labels: Option>, + factory: Option, runtime: Arc>, notifier: ChangeNotifier, owner_thread: ThreadId, @@ -89,6 +90,11 @@ pub struct Core { impl Drop for Core { fn drop(&mut self) { + // First: the Factory engine sends through delivery and ends the + // verify runs and judgments it started (rule 14). + if let Some(mut factory) = self.factory.take() { + factory.shutdown(); + } self._delivery.take(); // Reserve cancellation before any coordinator shutdown can wait: a // completing attachment must not enqueue input during destruction. @@ -172,6 +178,7 @@ impl Core { _links: None, _delivery: None, labels: None, + factory: None, runtime, notifier: notifier.clone(), owner_thread: thread::current().id(), @@ -295,6 +302,24 @@ impl Core { None } }; + // The Software Factory engine; it opens its store only when a Factory + // exists or is asked for. + let factory = std::path::Path::new(&options.app_state_path) + .parent() + .filter(|directory| !directory.as_os_str().is_empty()) + .and_then(|state_dir| { + crate::factory::FactoryHost::start( + state_dir, + environment_home.clone(), + Arc::downgrade(&runtime), + ) + .map_err(|message| { + crate::diagnostic!( + serde_json::json!({"component":"factory","kind":"host.start_failed","message":message}) + ); + }) + .ok() + }); let session_sync = if let Some(socket_path) = options.herdr_socket_path.as_deref() { live::install( &runtime, @@ -390,6 +415,7 @@ impl Core { _session_search: session_search, _links: links, labels, + factory, runtime, notifier, owner_thread: thread::current().id(), @@ -427,6 +453,28 @@ impl Core { lock_recover(&self.runtime).prepare_delivery(device, caller, expected, hint, command) } + /// A `hide factory` command from a pane or checkout capability: the + /// caller is checked as delivery checks it, and the engine decides the + /// role from its own record of workers (D-33). + pub fn prepare_factory( + &self, + device: &str, + caller: &str, + expected: &crate::workspace_control::Context, + hint: Option<&str>, + command: hide_factory::Command, + ) -> Result { + if !check_owner_thread(self, "factory.prepare") { + return Err("factory_unavailable".into()); + } + if device != "local" { + return Err("factory_local_only".into()); + } + let factory = self.factory.as_ref().ok_or("factory_unavailable")?; + let caller = lock_recover(&self.runtime).factory_caller(caller, expected, hint)?; + Ok(factory.prepare(caller, command)) + } + pub fn prepare_delivery_human(&self) -> Result { if !check_owner_thread(self, "delivery.human.prepare") { return Err("delivery_unavailable".into()); diff --git a/herdr-core/src/lib.rs b/herdr-core/src/lib.rs index 4157d2afdf..44379253b0 100644 --- a/herdr-core/src/lib.rs +++ b/herdr-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod domain; mod environment; #[cfg(all(test, unix))] mod executable_fixture; +pub mod factory; #[cfg(test)] mod fake_herdr; mod files; diff --git a/herdr-core/src/runtime.rs b/herdr-core/src/runtime.rs index 2245f106b5..f650a4acb2 100644 --- a/herdr-core/src/runtime.rs +++ b/herdr-core/src/runtime.rs @@ -18,6 +18,7 @@ mod devices; mod documents; mod editor; mod events; +mod factory; mod home; mod hosts; mod issues; @@ -1068,6 +1069,9 @@ pub struct Runtime { delivery_ledger: Result, String>, delivery_client: Option, delivery_observations: HashMap, + /// Open Factories' code-owned recipients (`factory:`), set by the + /// Factory host; a letter to any other `factory:` name has no recipient. + factory_recipients: std::collections::BTreeSet, delivery_overflow: HashSet, delivery_connected: HashSet, /// Stable identities are separate from device labels: labels are mutable @@ -1772,6 +1776,7 @@ impl Runtime { delivery_ledger, delivery_client: None, delivery_observations: HashMap::new(), + factory_recipients: std::collections::BTreeSet::new(), delivery_overflow: HashSet::new(), delivery_connected: HashSet::new(), local_machine_id: options.machine_id.clone(), diff --git a/herdr-core/src/runtime/delivery.rs b/herdr-core/src/runtime/delivery.rs index 0a6dfe33dc..dfc346a04d 100644 --- a/herdr-core/src/runtime/delivery.rs +++ b/herdr-core/src/runtime/delivery.rs @@ -36,6 +36,24 @@ pub(crate) struct Observation { pub host_scope: Option, } +impl Observation { + /// A Factory's recipient as a letter target: no pane, no status. + pub(crate) fn code_owned(actor: Actor) -> Self { + Self { + raw_pane_id: actor.pane_id.clone(), + actor, + status: "idle".into(), + state_change_seq: None, + status_changed_at_unix_ms: 0, + last_input_at_unix_ms: 0, + last_submit_at_unix_ms: 0, + entered_working_at_unix_ms: 0, + session: None, + host_scope: None, + } + } +} + impl Runtime { pub(crate) fn observe_delivery( &mut self, @@ -240,6 +258,10 @@ impl Runtime { .actor .clone(); actor.require_native_identity()?; + if crate::delivery::reserved_name(&actor.name) { + // A pane named like a Factory would read as one (D-14). + return Err("reserved_name".into()); + } // Only the pane's own session proves its composer was submitted, so a // stray `hide inbox --hook` from a tool in the pane clears no draft. // The id is not a secret (D-18 external input stays outside this). The id is checked before it is @@ -306,6 +328,19 @@ impl Runtime { Command::Send { .. } if repeated => None, Command::Send { target, .. } | Command::WatchStart { target, .. } + | Command::WatchAssign { + observer: target, .. + } if target.starts_with(crate::delivery::FACTORY_PREFIX) => { + // A Factory is addressed by its code-owned name only; no + // pane can stand in for it. + let actor = Actor::factory(&target[crate::delivery::FACTORY_PREFIX.len()..]); + if !self.factory_recipient_current(&actor) { + return Err("target_unavailable".into()); + } + Some(Observation::code_owned(actor)) + } + Command::Send { target, .. } + | Command::WatchStart { target, .. } | Command::WatchAssign { observer: target, .. } => { @@ -395,6 +430,51 @@ impl Runtime { changed } + /// The Factory host publishes which Factories exist. + pub(crate) fn set_factory_recipients(&mut self, ids: std::collections::BTreeSet) { + self.factory_recipients = ids; + } + + /// A code-owned recipient is current while its Factory exists and the + /// actor is exactly the one the host constructs. + pub(crate) fn factory_recipient_current(&self, actor: &Actor) -> bool { + actor + .pane_id + .strip_prefix(crate::delivery::FACTORY_PREFIX) + .is_some_and(|id| self.factory_recipients.contains(id) && *actor == Actor::factory(id)) + } + + /// The authority the Factory host acts with: its own recipient, never a + /// pane's. + pub(crate) fn factory_authority_current(&self, caller: &str, actor: &Actor) -> bool { + caller == actor.pane_id && self.factory_recipient_current(actor) + } + + /// A delivery client and authority for the Factory host (D-14). + pub(crate) fn factory_delivery( + &self, + id: &str, + ) -> Result<(crate::delivery::worker::Client, Authority, Actor), String> { + let actor = Actor::factory(id); + if !self.factory_recipient_current(&actor) { + return Err("factory_unavailable".into()); + } + let context = Context { + device_id: "local".into(), + workspace_id: actor.pane_id.clone(), + checkout_id: actor.pane_id.clone(), + checkout_path: String::new(), + }; + Ok(( + self.delivery_client.clone().ok_or("delivery_unavailable")?, + Authority { + caller: actor.pane_id.clone(), + context, + }, + actor, + )) + } + pub(crate) fn delivery_identity_current(&self, actor: &Actor) -> bool { self.delivery_observations .get(&actor.pane_id) @@ -958,6 +1038,78 @@ pub(crate) mod tests { drop(worker); } + #[test] + fn a_pane_reaches_a_factory_only_while_it_exists_and_only_the_factory_sends_as_it() { + let root = tempfile::tempdir().unwrap(); + let (runtime, _, _, path) = fixture(root.path()); + let (worker, client) = Worker::spawn( + Arc::downgrade(&runtime), + ChangeNotifier::noop(), + path.clone(), + ) + .unwrap(); + let mut guard = runtime.lock().unwrap(); + guard.install_delivery_client(client); + let context = guard + .workspace_control_query("local", "sender", Query::Info) + .unwrap() + .context; + let send = |intent: &str| Command::Send { + target: "factory:f-1".into(), + intent: intent.into(), + body: "done".into(), + kind: "report".into(), + }; + assert_eq!( + guard + .prepare_delivery("local", "sender", &context, None, send("early")) + .err() + .as_deref(), + Some("target_unavailable"), + "no Factory f-1 exists yet" + ); + assert_eq!( + guard.factory_delivery("f-1").err().as_deref(), + Some("factory_unavailable") + ); + guard.set_factory_recipients(["f-1".to_owned()].into()); + let prepared = guard + .prepare_delivery("local", "sender", &context, None, send("once")) + .unwrap(); + drop(guard); + let result = prepared.run(Duration::from_secs(5)).unwrap(); + assert_eq!(result["recipient"]["pane_id"], "factory:f-1"); + assert_eq!(result["recipient"]["kind"], "factory"); + + // The Factory answers as itself; a pane cannot borrow its authority. + let guard = runtime.lock().unwrap(); + assert!(!guard.factory_authority_current("sender", &Actor::factory("f-1"))); + assert!(guard.factory_authority_current("factory:f-1", &Actor::factory("f-1"))); + let forged = Actor { + session: Some("forged".into()), + ..Actor::factory("f-1") + }; + assert!(!guard.factory_recipient_current(&forged)); + let prepared = guard + .factory_prepare( + "f-1", + Some("sender"), + Command::Send { + target: "sender".into(), + intent: "factory-answer".into(), + body: "noted".into(), + kind: "report".into(), + }, + ) + .unwrap(); + drop(guard); + let result = prepared.run(Duration::from_secs(5)).unwrap(); + assert_eq!(result["sender"]["pane_id"], "factory:f-1"); + let stored = crate::delivery::ledger::load(&path).unwrap(); + assert_eq!(stored.letters.len(), 2); + drop(worker); + } + #[test] fn remote_delivery_uses_attested_pane_and_native_kind_without_a_remote_store() { let root = tempfile::tempdir().unwrap(); diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs new file mode 100644 index 0000000000..dbc6ca33a8 --- /dev/null +++ b/herdr-core/src/runtime/factory.rs @@ -0,0 +1,226 @@ +//! What the Factory host reads from and asks of the runtime. Each call takes +//! the lock for owned data only; no subprocess, file or network work happens +//! here (docs/ARCHITECTURE.md). + +use crate::delivery::worker::{Authority, Prepared}; +use crate::delivery::{Actor, Command}; +use crate::runtime::delivery::Observation; +use crate::workspace_control::Query; + +use super::Runtime; + +/// A worker pane as the runtime sees it now. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct WorkerProbe { + /// Herdr shows an agent in the pane. + pub present: bool, + /// The agent sleeps (or its end is in flight). + pub asleep: bool, + pub working: bool, + /// The agent waits for the person in its own pane. + pub waiting: bool, + pub status_changed_at_unix_ms: u64, +} + +impl Runtime { + /// Checks a local caller like a delivery request does and names the pane + /// and checkout it speaks from. + pub(crate) fn factory_caller( + &self, + caller: &str, + expected: &crate::workspace_control::Context, + hint: Option<&str>, + ) -> Result { + let context = self + .workspace_control_query("local", caller, Query::Info) + .map_err(|refusal| refusal.reason.to_owned())? + .context; + if context != *expected { + return Err("caller_context_changed".into()); + } + let pane = match crate::workspace_control::Caller::parse(caller) { + crate::workspace_control::Caller::Pane(pane) => Some(pane.to_owned()), + crate::workspace_control::Caller::Checkout { .. } => hint + .filter(|pane| { + self.workspace_control_query("local", pane, Query::Info) + .is_ok_and(|answer| answer.context == context) + }) + .map(str::to_owned), + }; + Ok(crate::factory::FactoryCaller { + pane, + cwd: Some(context.checkout_path.clone()).filter(|path| !path.is_empty()), + }) + } + + /// A delivery command the Factory sends as its own recipient, to the pane + /// `target` when the command has one. + pub(crate) fn factory_prepare( + &self, + id: &str, + target: Option<&str>, + command: Command, + ) -> Result { + let (client, authority, actor) = self.factory_delivery(id)?; + let target = match target { + Some(pane) => Some( + self.delivery_observations + .get(pane) + .cloned() + .ok_or("target_unavailable")?, + ), + None => None, + }; + Ok(Prepared::new(client, authority, actor, target, command)) + } + + /// A worker's report to its Factory as a ledger letter from the worker's + /// own pane (PRD software-factory: ask/block/propose/done use delivery). + pub(crate) fn factory_worker_letter( + &self, + pane: &str, + factory: &str, + command: Command, + ) -> Result { + let observation = self + .delivery_observations + .get(pane) + .ok_or("agent_pane_required")?; + let actor = observation.actor.clone(); + actor.require_native_identity()?; + let context = self + .workspace_control_query(&actor.device_id, pane, Query::Info) + .map_err(|_| "agent_pane_required")? + .context; + let recipient = Actor::factory(factory); + if !self.factory_recipient_current(&recipient) { + return Err("target_unavailable".into()); + } + Ok(Prepared::new( + self.delivery_client.clone().ok_or("delivery_unavailable")?, + Authority { + caller: pane.to_owned(), + context, + }, + actor, + Some(Observation::code_owned(recipient)), + command, + )) + } + + pub(crate) fn factory_worker_probe(&self, pane: &str) -> WorkerProbe { + let asleep = self + .snapshot + .ui_state + .agent_sleep + .records + .contains_key(pane); + let agent = self + .snapshot + .navigator + .agents + .iter() + .find(|agent| agent.pane_id == pane); + WorkerProbe { + present: agent.is_some(), + asleep, + working: agent + .is_some_and(|agent| agent.activity == "working" || agent.group == "working"), + waiting: agent.is_some_and(|agent| agent.demand != "none" || agent.blocked), + status_changed_at_unix_ms: self + .delivery_observations + .get(pane) + .map_or(0, |observation| observation.status_changed_at_unix_ms), + } + } + + /// Puts a worker to sleep through the agent sleep path (D-14, B27). + /// `Ok(false)`: not yet, the agent is still in its turn; ask again. + pub(crate) fn factory_sleep(&mut self, pane: &str) -> Result { + if self + .snapshot + .ui_state + .agent_sleep + .records + .contains_key(pane) + { + return Ok(true); + } + let Some(agent) = self + .snapshot + .navigator + .agents + .iter() + .find(|agent| agent.pane_id == pane) + else { + return Err("This pane has no agent"); + }; + match crate::agent_sleep::sleep_refusal(agent) { + None => {} + Some("This agent is working") | Some("Hide cannot tell what this agent is doing") => { + return Ok(false); + } + Some(reason) => return Err(reason), + } + if self.live.is_none() { + return Err("Putting an agent to sleep requires a live Herdr connection"); + } + self.request_agent_sleep(pane); + Ok(true) + } + + /// Wakes a sleeping worker in the same pane and session (B27, B54). + pub(crate) fn factory_wake(&mut self, pane: &str) -> bool { + if !self + .snapshot + .ui_state + .agent_sleep + .records + .contains_key(pane) + { + return false; + } + self.request_agent_wake(super::agent_sleep::AgentWakePayload { + pane_id: pane.to_owned(), + fresh: false, + }) + } + + /// A local issue for a Factory Task, or the one already carrying its + /// marker (B13, B73). + pub(crate) fn factory_local_issue( + &mut self, + project: &str, + title: &str, + body: &str, + marker: &str, + ) -> Result { + if let Ok(store) = &self.local_issues + && let Some(existing) = store.project(project).and_then(|project| { + project + .issues + .iter() + .find(|issue| issue.body.contains(marker)) + }) + { + return Ok(existing.number); + } + self.create_local_issue(project, title, body) + } + + pub(crate) fn factory_local_issue_read( + &self, + project: &str, + number: u32, + ) -> Option { + self.local_issues + .as_ref() + .ok() + .and_then(|store| store.issue(project, number)) + .cloned() + } + + pub(crate) fn factory_ai_settings(&self) -> Option { + self.ai_settings.clone() + } +} diff --git a/hide-agent-hooks/src/runtime.rs b/hide-agent-hooks/src/runtime.rs index 3c6adb154a..e76d9ab9bc 100644 --- a/hide-agent-hooks/src/runtime.rs +++ b/hide-agent-hooks/src/runtime.rs @@ -32,7 +32,7 @@ pub const HOOK_VERSION: u32 = 6; /// Both runtimes accept the same `hookSpecificOutput.additionalContext` /// envelope, while the runtime argument remains explicit in the installed /// command so a future protocol difference has one dispatch point. -pub const PURPOSE_CONTEXT: &str = "When you create a worktree, set its one-line purpose in 40 characters or fewer by running `herdr workspace report-metadata --source --token purpose=\"…\"`. Delegate new work with `hide agent spawn --parent here …` so its lineage remains visible."; +pub const PURPOSE_CONTEXT: &str = "When you create a worktree, set its one-line purpose in 40 characters or fewer by running `herdr workspace report-metadata --source --token purpose=\"…\"`. Delegate new work with `hide agent spawn --parent here …` so its lineage remains visible. To put work into a Factory, run `hide factory add` rather than adding a GitHub label."; pub fn hook_stdout(runtime: AgentRuntime, event: HookEvent) -> Option { hook_stdout_with_context(runtime, event, None) @@ -337,6 +337,13 @@ mod tests { ); } + #[test] + fn session_guidance_sends_factory_work_through_the_factory_command() { + // PRD software-factory B18: a request to put work into a Factory + // uses `hide factory add`, not a label. + assert!(PURPOSE_CONTEXT.contains("`hide factory add`")); + } + #[test] fn both_runtimes_emit_the_purpose_instruction_only_at_session_start() { for runtime in AgentRuntime::ALL { diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index ed1df74cf4..053a34f28a 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -272,6 +272,8 @@ pub struct WorkerSpawn { pub project: String, pub branch: String, pub prompt: String, + /// The runtime's extra arguments from the Factory's configuration. + pub args: Vec, /// Reuse the worktree and session (retry, wake, relanding). pub resume: Option, } @@ -335,5 +337,5 @@ pub trait Notifier { fn macos(&mut self, title: &str, body: &str); /// Sends a pending review's result to the producer pane; false when the /// pane is gone (B11). - fn producer(&mut self, pane: &str, body: &str) -> bool; + fn producer(&mut self, factory: &str, pane: &str, body: &str) -> bool; } diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs index 3ea1d0a596..3cc82d8f76 100644 --- a/hide-factory/src/command.rs +++ b/hide-factory/src/command.rs @@ -244,8 +244,9 @@ hide factory inbox hide factory answer [--question ] [--choose suggestion|default|] [--text ] hide factory ask --question --suggestion --default [--deadline-hours ] hide factory block --question --suggestion [--deadline-hours ] -hide factory propose --class in-scope|decision|scope-change|prerequisite|unrelated --text [--title --goal --criterion ...] +hide factory propose --class in-scope|decision|scope-change|prerequisite|unrelated --text [--title --goal --criterion ...] [--autonomy ] [--reclassify ] hide factory done [--summary ] [--breaking] +hide factory decide --text hide factory config [--project ] [--set =]... hide factory priority hide factory dep add|remove --on diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 73e018c60e..a7b31c91bd 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -124,8 +124,8 @@ fn refuse(reason: &str, next: &str) -> Refusal { } impl Engine { - pub fn open(state_dir: &Path, ports: Ports) -> Result { - let store = Store::open(state_dir)?; + pub fn open(store: &Path, files: &Path, ports: Ports) -> Result { + let store = Store::open(store, files)?; let loaded = store.load()?; let mut engine = Self { store, @@ -1565,7 +1565,7 @@ impl Engine { answer["task"]["display_id"].as_str().unwrap_or(id), answer["result"].as_str().unwrap_or("pending") ); - if !self.ports.notifier.producer(&pane, &body) { + if !self.ports.notifier.producer(factory, &pane, &body) { self.with_task(factory, id, |task| task.producer_pane = None); } } @@ -3492,6 +3492,17 @@ impl Engine { config.recovery.push(action); } } + "worker_args" => { + // `claude=--flag --other`: the runtime's whole list. + let (runtime, args) = value.split_once('=').ok_or_else(bad)?; + let runtime = Runtime::parse(runtime).ok_or_else(bad)?; + let args: Vec = args.split_whitespace().map(str::to_owned).collect(); + if args.is_empty() { + config.worker_args.remove(runtime.as_str()); + } else { + config.worker_args.insert(runtime.as_str().to_owned(), args); + } + } "risk_paths" => { config.risk_paths = value .split(',') @@ -4009,6 +4020,12 @@ impl Engine { project: factory.project.clone(), branch: worker.branch.clone(), prompt: worker_prompt(&task, &factory, true), + args: factory + .config + .worker_args + .get(runtime.as_str()) + .cloned() + .unwrap_or_default(), resume: Some(worker.clone()), }; self.ports.workers.spawn(&request).map(Some) @@ -4044,6 +4061,12 @@ impl Engine { project: factory.project.clone(), branch: task.branch_slug(), prompt: worker_prompt(&task, &factory, false), + args: factory + .config + .worker_args + .get(runtime.as_str()) + .cloned() + .unwrap_or_default(), resume: None, }; match self.ports.workers.spawn(&request) { diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 8e27fa7ea0..be90e2eb12 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -223,6 +223,10 @@ pub struct Config { pub checks: Vec, pub prd_in_issue: bool, pub macos_notifications: bool, + /// Extra arguments each runtime's worker starts with, such as a + /// permission mode the operator chose. + #[serde(default)] + pub worker_args: std::collections::BTreeMap>, } impl Default for Config { @@ -255,6 +259,7 @@ impl Default for Config { checks: Vec::new(), prd_in_issue: false, macos_notifications: false, + worker_args: std::collections::BTreeMap::new(), } } } @@ -676,6 +681,12 @@ impl StopReason { /// The worker a Task runs, as the runtime adapter reported it. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct WorkerRef { + /// The Factory that spawned it. + #[serde(default)] + pub factory: String, + /// The coordination agent id, which ends it. + #[serde(default)] + pub agent: Option, pub name: String, pub pane: Option, pub runtime: Runtime, diff --git a/hide-factory/src/store.rs b/hide-factory/src/store.rs index 09115f2700..f701c03db6 100644 --- a/hide-factory/src/store.rs +++ b/hide-factory/src/store.rs @@ -16,8 +16,6 @@ use sha2::{Digest, Sha256}; use crate::model::{Attachment, Factory, Task, UnixMs}; pub const SCHEMA_VERSION: i64 = 1; -pub const STORE_FILE: &str = "factory.sqlite3"; -pub const FILES_DIR: &str = "factory-files"; /// A verify or CI log copy keeps at most its last 1 MiB per attempt (D-58). pub const LOG_TAIL_LIMIT: usize = 1024 * 1024; /// A PRD attachment larger than this is refused. @@ -119,16 +117,17 @@ pub struct Loaded { } impl Store { - /// Opens or creates the store in `state_dir`; the files folder is made - /// private (0700) on Unix. - pub fn open(state_dir: &Path) -> Result { - fs::create_dir_all(state_dir)?; - let files = state_dir.join(FILES_DIR); + /// Opens or creates the store at `path` with its private files folder + /// (0700 on Unix); `hide_kit::layout` names both. + pub fn open(path: &Path, files: &Path) -> Result { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let files = files.to_owned(); fs::create_dir_all(&files)?; private_dir(&files)?; - let path = state_dir.join(STORE_FILE); - let connection = Connection::open(&path)?; - private_file(&path)?; + let connection = Connection::open(path)?; + private_file(path)?; connection.pragma_update(None, "journal_mode", "WAL")?; connection.pragma_update(None, "synchronous", "NORMAL")?; connection.pragma_update(None, "foreign_keys", "ON")?; @@ -421,20 +420,35 @@ mod tests { #[test] fn a_newer_schema_is_refused_rather_than_read() { let folder = tempfile::tempdir().unwrap(); - drop(Store::open(folder.path()).unwrap()); - let connection = Connection::open(folder.path().join(STORE_FILE)).unwrap(); + drop( + Store::open( + &folder.path().join("factory.sqlite3"), + &folder.path().join("factory-files"), + ) + .unwrap(), + ); + let connection = Connection::open(folder.path().join("factory.sqlite3")).unwrap(); connection .pragma_update(None, "user_version", SCHEMA_VERSION + 1) .unwrap(); drop(connection); - let error = Store::open(folder.path()).err().unwrap(); + let error = Store::open( + &folder.path().join("factory.sqlite3"), + &folder.path().join("factory-files"), + ) + .err() + .unwrap(); assert!(error.0.contains("newer"), "{error}"); } #[test] fn a_log_copy_keeps_only_its_last_mebibyte() { let folder = tempfile::tempdir().unwrap(); - let store = Store::open(folder.path()).unwrap(); + let store = Store::open( + &folder.path().join("factory.sqlite3"), + &folder.path().join("factory-files"), + ) + .unwrap(); let mut bytes = vec![b'a'; LOG_TAIL_LIMIT]; bytes.extend_from_slice(b"tail"); let path = store.keep_log("f", "T-1", 1, "task", &bytes).unwrap(); @@ -446,7 +460,11 @@ mod tests { #[test] fn an_attachment_is_a_private_read_only_copy_named_by_its_hash() { let folder = tempfile::tempdir().unwrap(); - let store = Store::open(&folder.path().join("state")).unwrap(); + let store = Store::open( + &folder.path().join("state/factory.sqlite3"), + &folder.path().join("state/factory-files"), + ) + .unwrap(); let source = folder.path().join("prd.md"); fs::write(&source, "# PRD\n").unwrap(); let attachment = store.attach("f", "T-1", &source, 1).unwrap(); diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index aaaaab71ba..01ad7276f8 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -169,6 +169,8 @@ fn task(id: &str, issue: Option) -> Task { } let mut task: Task = serde_json::from_value(value).unwrap(); task.worker = Some(WorkerRef { + factory: String::new(), + agent: None, name: "w".into(), pane: None, runtime: Runtime::Claude, diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index bfff46f0cd..f9e1fb355a 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -138,6 +138,8 @@ fn task(fixture: &Fixture, id: &str, file: &str, text: &str) -> Task { git(&worktree, &["add", "."]); git(&worktree, &["commit", "--quiet", "-m", id]); task.worker = Some(WorkerRef { + factory: String::new(), + agent: None, name: id.into(), pane: None, runtime: Runtime::Claude, diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 1595160dcd..813f7f99d8 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -295,6 +295,8 @@ impl WorkerRuntime for Shared { world.spawned.push(request.clone()); world.worker_status.remove(&request.task); Ok(WorkerRef { + factory: String::new(), + agent: None, name: request.name.clone(), pane: Some(format!("pane-{}", request.task)), runtime: request.runtime, @@ -411,7 +413,7 @@ impl Notifier for Shared { fn macos(&mut self, title: &str, _body: &str) { self.world().macos.push(title.to_owned()); } - fn producer(&mut self, pane: &str, body: &str) -> bool { + fn producer(&mut self, _factory: &str, pane: &str, body: &str) -> bool { self.world() .producer .push((pane.to_owned(), body.to_owned())); @@ -464,7 +466,12 @@ impl Bench { ..World::default() }; let shared = Shared(Arc::new(Mutex::new(world))); - let engine = Engine::open(dir.path(), ports(&shared)).expect("engine opens"); + let engine = Engine::open( + &dir.path().join("factory.sqlite3"), + &dir.path().join("factory-files"), + ports(&shared), + ) + .expect("engine opens"); Self { dir, shared, @@ -480,7 +487,12 @@ impl Bench { engine, } = self; drop(engine); - let engine = Engine::open(dir.path(), ports(&shared)).expect("engine reopens"); + let engine = Engine::open( + &dir.path().join("factory.sqlite3"), + &dir.path().join("factory-files"), + ports(&shared), + ) + .expect("engine reopens"); Self { dir, shared, diff --git a/hide-kit/src/layout.rs b/hide-kit/src/layout.rs index f90782b125..6f971cbd71 100644 --- a/hide-kit/src/layout.rs +++ b/hide-kit/src/layout.rs @@ -91,6 +91,18 @@ pub fn links_store(state_dir: &Path) -> PathBuf { state_dir.join("links.sqlite3") } +/// The Software Factory store: Factories, Tasks, questions, records and +/// events; its owner is the core's Factory engine thread. +pub fn factory_store(state_dir: &Path) -> PathBuf { + state_dir.join("factory.sqlite3") +} + +/// The Factory's private files beside its store: PRD attachments by hash and +/// verify log tails. +pub fn factory_files(state_dir: &Path) -> PathBuf { + state_dir.join("factory-files") +} + /// `~/rest` of a helper root spelling under `home`; an absolute spelling as /// it is. pub fn expand_home(spelling: &str, home: &Path) -> PathBuf { diff --git a/hided/Cargo.toml b/hided/Cargo.toml index 38973a954a..c3c3cca68e 100644 --- a/hided/Cargo.toml +++ b/hided/Cargo.toml @@ -14,6 +14,7 @@ path = "src/bin/hide.rs" [dependencies] herdr-core = { path = "../herdr-core" } +hide-factory = { path = "../hide-factory" } hide-host = { path = "../hide-host" } hide-platform = { path = "../hide-platform" } hide-kit = { path = "../hide-kit" } diff --git a/hided/src/cli.rs b/hided/src/cli.rs index 68850fee2a..eb143df027 100644 --- a/hided/src/cli.rs +++ b/hided/src/cli.rs @@ -13,6 +13,8 @@ use crate::state_file::{self, DaemonState}; #[derive(Debug, Eq, PartialEq)] pub enum CommandKind { Delivery(herdr_core::delivery::Command), + /// `hide factory ...` + Factory(crate::factory_cli::FactoryRequest), Help, Open, /// `hide connect`: `open` without the browser, answered as one JSON line @@ -77,6 +79,7 @@ pub fn parse_args(args: &[String]) -> Result { Some(topic @ ("request" | "inbox" | "watch")) => { crate::delivery_cli::parse(topic, iter).map(CommandKind::Delivery) } + Some("factory") => crate::factory_cli::parse(iter).map(CommandKind::Factory), Some("browser") => parse_browser(iter), Some("workspace") => match (iter.next().map(String::as_str), iter.next()) { (Some("bootstrap"), None) => Ok(CommandKind::WorkspaceBootstrap), @@ -317,6 +320,7 @@ pub fn run(kind: CommandKind) -> Result<(), String> { if kind == CommandKind::Help { println!("{}", crate::delivery_cli::USAGE); println!("{}", crate::agent_cli::USAGE); + println!("{}", hide_factory::command::USAGE); println!( "hide workspace info\nhide file open [--beside] [--reveal] [--request-id ]\nhide diff open [--beside] [--reveal] [--request-id ]\nhide browser open [--reveal] [--wait] [--request-id ]\nhide browser connect [--display ]\nhide browser snapshot|click|fill|type|press|hover|drag|scroll|wait|screenshot|eval|console|network ...\nhide browser help\nhide view list\nhide view status \nhide view select [--reveal] [--request-id ]\nhide view close [--request-id ]\nhide view split --area --edge left|right|up|down [--request-id ]\nhide view move --area --index [--request-id ]\nhide links pr | issue | branch | session [--all-projects]\nEach Workspace command requires a live Hide renderer and a caller Hide can bind to a checkout, an attested Herdr pane or a shell inside a registered checkout; it never starts Hide. hide links needs only the caller and a running Hide, and reads the caller's Project unless --all-projects is given." ); @@ -334,6 +338,7 @@ pub fn run(kind: CommandKind) -> Result<(), String> { &kind, CommandKind::WorkspaceBootstrap | CommandKind::Delivery(_) + | CommandKind::Factory(_) | CommandKind::WorkspaceInfo | CommandKind::ViewList | CommandKind::ViewStatus { .. } @@ -365,6 +370,7 @@ pub fn run(kind: CommandKind) -> Result<(), String> { crate::delivery_cli::run(&env, command) } } + CommandKind::Factory(request) => crate::factory_cli::run(&env, request), CommandKind::Help | CommandKind::BrowserHelp => unreachable!("handled above"), CommandKind::Open => open(&env), CommandKind::Connect => connect_json(&env), diff --git a/hided/src/core.rs b/hided/src/core.rs index 8606b20aef..8eaef1b837 100644 --- a/hided/src/core.rs +++ b/hided/src/core.rs @@ -27,6 +27,13 @@ enum Command { command: herdr_core::delivery::Command, reply: Sender>, }, + FactoryPrepare { + pane_id: String, + expected: Context, + hint: Option, + command: hide_factory::Command, + reply: Sender>, + }, SetFileRoots { roots: Vec<(std::path::PathBuf, std::fs::File)>, reply: Sender>, @@ -128,6 +135,33 @@ impl CoreHandle { .map_err(|_| "delivery_unavailable".to_owned())? } + /// A `hide factory` command, checked on the owner thread like a delivery. + pub fn prepare_factory( + &self, + device: &str, + pane: &str, + expected: &Context, + hint: Option, + command: hide_factory::Command, + ) -> Result { + if device != herdr_core::workspace::LOCAL_DEVICE_ID { + return Err("factory_local_only".into()); + } + let (reply, result) = mpsc::channel(); + self.commands + .send(Command::FactoryPrepare { + pane_id: pane.to_owned(), + expected: expected.clone(), + hint, + command, + reply, + }) + .map_err(|_| "factory_unavailable".to_owned())?; + result + .recv() + .map_err(|_| "factory_unavailable".to_owned())? + } + pub fn set_file_roots( &self, roots: Vec<(std::path::PathBuf, std::fs::File)>, @@ -377,6 +411,21 @@ fn owner_loop( Command::DeliveryHuman { reply } => { let _ = reply.send(core.prepare_delivery_human()); } + Command::FactoryPrepare { + pane_id, + expected, + hint, + command, + reply, + } => { + let _ = reply.send(core.prepare_factory( + herdr_core::workspace::LOCAL_DEVICE_ID, + &pane_id, + &expected, + hint.as_deref(), + command, + )); + } Command::DeliveryPrepare { device_id, pane_id, diff --git a/hided/src/factory_cli.rs b/hided/src/factory_cli.rs new file mode 100644 index 0000000000..645fffbba2 --- /dev/null +++ b/hided/src/factory_cli.rs @@ -0,0 +1,562 @@ +//! `hide factory ...`: parses each subcommand into the typed Factory command +//! and prints the engine's answer for a person, or as JSON with `--json`. +//! Which caller may run which command is the engine's decision (D-41). + +use std::path::Path; + +use hide_factory::Command; +use hide_factory::command::{CardInput, USAGE, VerificationChoice, render_human}; +use hide_factory::model::{CheckPoint, DiscoveryClass, MergeMode, Runtime}; + +use crate::env::{self, Env}; + +#[derive(Debug, Eq, PartialEq)] +pub struct FactoryRequest { + pub command: Command, + pub json: bool, +} + +pub fn parse<'a>(args: impl Iterator) -> Result { + let mut json = false; + let mut words = Vec::new(); + for arg in args { + if arg == "--json" { + json = true; + } else { + words.push(arg.as_str()); + } + } + let cwd = std::env::current_dir().map_err(|_| "current_directory_unavailable".to_owned())?; + let command = parse_words(&words, &cwd).ok_or_else(|| USAGE.to_owned())?; + Ok(FactoryRequest { command, json }) +} + +/// The flags of one subcommand, read in order. A flag given twice where it +/// takes one value, an unknown flag, or a missing value is a usage error. +struct Flags<'a> { + rest: std::iter::Peekable>, +} + +impl<'a> Flags<'a> { + fn new(words: &'a [&'a str]) -> Self { + Self { + rest: words.iter().peekable(), + } + } + + fn next(&mut self) -> Option<&'a str> { + self.rest.next().copied() + } + + fn value(&mut self) -> Option { + self.rest + .next() + .filter(|value| !value.starts_with("--")) + .map(|value| (*value).to_owned()) + } + + /// Values up to the next flag (`--ci check-a check-b`). + fn values(&mut self) -> Vec { + let mut values = Vec::new(); + while let Some(value) = self.rest.peek() { + if value.starts_with("--") { + break; + } + values.push((**value).to_owned()); + self.rest.next(); + } + values + } +} + +fn once(slot: &mut Option, value: Option) -> Option<()> { + if slot.is_some() { + return None; + } + *slot = Some(value?); + Some(()) +} + +/// A path the daemon reads: absolute, because the daemon does not share the +/// caller's working directory. +fn absolute(cwd: &Path, value: &str) -> String { + let path = cwd.join(value); + std::fs::canonicalize(&path) + .unwrap_or(path) + .display() + .to_string() +} + +fn merge_mode(value: &str) -> Option { + match value { + "auto" => Some(MergeMode::Auto), + "manual" => Some(MergeMode::Manual), + _ => None, + } +} + +fn parse_words(words: &[&str], cwd: &Path) -> Option { + let (verb, rest) = words.split_first()?; + match *verb { + "init" => parse_init(rest, cwd), + "add" => parse_add(rest, cwd), + "status" | "close" => { + let project = project_only(rest, cwd)?; + Some(if *verb == "status" { + Command::Status { project } + } else { + Command::Close { project } + }) + } + "show" => match rest { + [task] if !task.starts_with("--") => Some(Command::Show { + task: (*task).to_owned(), + }), + _ => None, + }, + "inbox" => rest.is_empty().then_some(Command::Inbox), + "answer" => parse_answer(rest), + "ask" | "block" => parse_question(verb, rest), + "propose" => parse_propose(rest, cwd), + "done" => { + let mut flags = Flags::new(rest); + let mut summary = None; + let mut breaking = false; + while let Some(flag) = flags.next() { + match flag { + "--summary" => once(&mut summary, flags.value())?, + "--breaking" if !breaking => breaking = true, + _ => return None, + } + } + Some(Command::Done { + summary, + breaking, + letter: None, + }) + } + "decide" => match rest { + ["--text", text] => Some(Command::Decide { + text: (*text).to_owned(), + }), + _ => None, + }, + "config" => { + let mut flags = Flags::new(rest); + let mut project = None; + let mut set = Vec::new(); + while let Some(flag) = flags.next() { + match flag { + "--project" => once(&mut project, flags.value().map(|p| absolute(cwd, &p)))?, + "--set" => { + let pair = flags.value()?; + let (key, value) = pair.split_once('=')?; + if key.is_empty() { + return None; + } + set.push((key.to_owned(), value.to_owned())); + } + _ => return None, + } + } + Some(Command::Config { project, set }) + } + "priority" => match rest { + [task, priority] => Some(Command::Priority { + task: (*task).to_owned(), + priority: priority.parse().ok()?, + }), + _ => None, + }, + "dep" => match rest { + [action @ ("add" | "remove"), task, "--on", on] if !task.starts_with("--") => { + Some(Command::Dep { + task: (*task).to_owned(), + on: (*on).to_owned(), + remove: *action == "remove", + }) + } + _ => None, + }, + "pause" | "resume" | "retry" | "merge" | "cancel" | "revive" => { + let [task] = rest else { return None }; + if task.starts_with("--") { + return None; + } + let task = (*task).to_owned(); + Some(match *verb { + "pause" => Command::Pause { task }, + "resume" => Command::Resume { task }, + "retry" => Command::Retry { task }, + "merge" => Command::Merge { task }, + "cancel" => Command::Cancel { task }, + _ => Command::Revive { task }, + }) + } + "request-changes" => match rest { + [task, "--comment", comment] if !task.starts_with("--") => { + Some(Command::RequestChanges { + task: (*task).to_owned(), + comment: (*comment).to_owned(), + }) + } + _ => None, + }, + "check" => { + let mut flags = Flags::new(rest); + let mut project = None; + let mut at = None; + let mut instruction = None; + while let Some(flag) = flags.next() { + match flag { + "--project" => once(&mut project, flags.value().map(|p| absolute(cwd, &p)))?, + "--at" => once(&mut at, flags.value())?, + "--instruction" => once(&mut instruction, flags.value())?, + _ => return None, + } + } + let at = match at?.as_str() { + "intake" => CheckPoint::Intake, + "after-done" | "after_done" => CheckPoint::AfterDone, + "periodic" => CheckPoint::Periodic, + _ => return None, + }; + Some(Command::Check { + project, + at, + instruction: instruction?, + }) + } + _ => None, + } +} + +fn project_only(rest: &[&str], cwd: &Path) -> Option> { + match rest { + [] => Some(None), + ["--project", path] if !path.starts_with("--") => Some(Some(absolute(cwd, path))), + _ => None, + } +} + +fn parse_init(rest: &[&str], cwd: &Path) -> Option { + let (project, rest) = rest.split_first()?; + if project.starts_with("--") { + return None; + } + let mut flags = Flags::new(rest); + let mut ci: Option> = None; + let mut commands = Vec::new(); + let mut none = false; + let mut merge = None; + let mut confirm = false; + while let Some(flag) = flags.next() { + match flag { + "--ci" if ci.is_none() => ci = Some(flags.values()), + "--verify" => commands.push(flags.value()?), + "--no-verification" if !none => none = true, + "--merge" => once(&mut merge, flags.value())?, + "--confirm" if !confirm => confirm = true, + _ => return None, + } + } + let verification = match (ci, commands.is_empty(), none) { + (None, true, false) => None, + (Some(checks), true, false) => Some(VerificationChoice::Ci { checks }), + (None, false, false) => Some(VerificationChoice::Commands { commands }), + (None, true, true) => Some(VerificationChoice::None), + _ => return None, + }; + Some(Command::Init { + project: absolute(cwd, project), + verification, + merge_mode: match merge { + Some(value) => Some(merge_mode(&value)?), + None => None, + }, + confirm, + }) +} + +/// The card flags shared by `add` and `propose`. +fn card_flag(flag: &str, flags: &mut Flags<'_>, card: &mut CardInput, cwd: &Path) -> Option<()> { + match flag { + "--title" => once(&mut card.title, flags.value()), + "--goal" => once(&mut card.goal, flags.value()), + "--criterion" => { + card.criteria.push(flags.value()?); + Some(()) + } + "--out-of-scope" => { + card.out_of_scope.push(flags.value()?); + Some(()) + } + "--open" => { + card.open_decisions.push(flags.value()?); + Some(()) + } + "--after" => { + card.depends_on.push(flags.value()?); + Some(()) + } + "--external" => { + card.external.push(flags.value()?); + Some(()) + } + "--prd" => once(&mut card.prd, flags.value().map(|p| absolute(cwd, &p))), + "--review-directly" if !card.review_directly => { + card.review_directly = true; + Some(()) + } + "--priority" if card.priority.is_none() => { + card.priority = Some(flags.value()?.parse().ok()?); + Some(()) + } + "--merge" if card.merge_mode.is_none() => { + card.merge_mode = Some(merge_mode(&flags.value()?)?); + Some(()) + } + "--runtime" if card.runtime.is_none() => { + card.runtime = Some(Runtime::parse(&flags.value()?)?); + Some(()) + } + _ => None, + } +} + +fn parse_add(rest: &[&str], cwd: &Path) -> Option { + let (issue, rest) = match rest.split_first() { + Some((first, rest)) if !first.starts_with("--") => (Some((*first).to_owned()), rest), + _ => (None, rest), + }; + let mut flags = Flags::new(rest); + let mut card = CardInput::default(); + let mut project = None; + let mut task = None; + while let Some(flag) = flags.next() { + match flag { + "--project" => once(&mut project, flags.value().map(|p| absolute(cwd, &p)))?, + "--task" => once(&mut task, flags.value())?, + _ => card_flag(flag, &mut flags, &mut card, cwd)?, + } + } + if issue.is_some() && task.is_some() { + return None; + } + Some(Command::Add { + project, + task, + issue, + card, + producer_pane: None, + }) +} + +fn parse_answer(rest: &[&str]) -> Option { + let (task, rest) = rest.split_first()?; + if task.starts_with("--") { + return None; + } + let mut flags = Flags::new(rest); + let mut question = None; + let mut choice = None; + let mut text = None; + while let Some(flag) = flags.next() { + match flag { + "--question" => once(&mut question, flags.value())?, + "--choose" => once(&mut choice, flags.value())?, + "--text" => once(&mut text, flags.value())?, + _ => return None, + } + } + if choice.is_none() && text.is_none() { + return None; + } + Some(Command::Answer { + task: (*task).to_owned(), + question, + choice, + text, + }) +} + +fn parse_question(verb: &str, rest: &[&str]) -> Option { + let mut flags = Flags::new(rest); + let mut text = None; + let mut suggestion = None; + let mut default_action = None; + let mut deadline = None; + while let Some(flag) = flags.next() { + match flag { + "--question" => once(&mut text, flags.value())?, + "--suggestion" => once(&mut suggestion, flags.value())?, + "--default" if verb == "ask" => once(&mut default_action, flags.value())?, + "--deadline-hours" => once(&mut deadline, flags.value())?, + _ => return None, + } + } + let deadline_hours = match deadline { + Some(hours) => Some(hours.parse().ok()?), + None => None, + }; + Some(if verb == "ask" { + Command::Ask { + text: text?, + suggestion: suggestion?, + default_action: default_action?, + deadline_hours, + letter: None, + } + } else { + Command::Block { + text: text?, + suggestion: suggestion?, + deadline_hours, + letter: None, + } + }) +} + +fn parse_propose(rest: &[&str], cwd: &Path) -> Option { + let mut flags = Flags::new(rest); + let mut class = None; + let mut text = None; + let mut autonomy = None; + let mut reclassify = None; + let mut card = CardInput::default(); + while let Some(flag) = flags.next() { + match flag { + "--class" => once(&mut class, flags.value())?, + "--text" => once(&mut text, flags.value())?, + "--autonomy" => once(&mut autonomy, flags.value())?, + "--reclassify" => once(&mut reclassify, flags.value())?, + _ => card_flag(flag, &mut flags, &mut card, cwd)?, + } + } + Some(Command::Propose { + class: DiscoveryClass::parse(&class?)?, + text: text?, + card: (card != CardInput::default()).then_some(card), + autonomy, + reclassify, + letter: None, + }) +} + +pub fn run(env: &Env, request: FactoryRequest) -> Result<(), String> { + let verb = request.command.verb(); + let answer = (|| { + let (reference, ephemeral) = crate::cli::workspace_reference(env)?; + let _owner = ephemeral.then(|| crate::workspace_cli::OneShotReference(reference.clone())); + let hint = std::env::var(env::HERDR_PANE_ID).ok(); + crate::workspace_cli::request_factory(&reference, &request.command, hint.as_deref()) + })(); + // The socket answer wraps the engine's: a refusal before the engine + // (capability, daemon) has no `result`. + let answer = match answer { + Ok(answer) if answer["ok"] == true => answer["result"].clone(), + Ok(answer) => serde_json::json!({ + "ok": false, + "reason": answer["reason"], + "next_action": answer["next_action"], + }), + Err(code) => serde_json::json!({ + "ok": false, + "reason": code, + "next_action": "Check that Hide is running in this pane, then retry", + }), + }; + if request.json { + println!("{answer}"); + } else { + println!("{}", render_human(verb, &answer)); + } + if answer["ok"] == true { + Ok(()) + } else { + Err(answer["reason"] + .as_str() + .unwrap_or("factory_unavailable") + .to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse_line(line: &str) -> Option { + let words: Vec<&str> = line.split(' ').collect(); + parse_words(&words, Path::new("/work")) + } + + #[test] + fn every_documented_subcommand_parses() { + for line in [ + "init /p --verify make --merge auto --confirm", + "init /p --ci build test", + "init /p --no-verification", + "add --title t --goal g --criterion c --after T-1 --runtime codex --priority 2", + "add 12 --title t", + "add --task T-3 --goal better", + "status", + "status --project /p", + "show T-1", + "inbox", + "answer T-1 --choose suggestion", + "answer T-1 --question q-1 --text yes", + "ask --question q --suggestion s --default d --deadline-hours 4", + "block --question q --suggestion s", + "propose --class prerequisite --text t --title a --goal b --criterion c", + "propose --class decision --text t --reclassify d-1", + "done --summary s --breaking", + "decide --text t", + "config --set merge_mode=auto --set quick_check=make", + "priority T-1 -3", + "dep add T-2 --on T-1", + "dep remove T-2 --on T-1", + "pause T-1", + "revive T-1", + "request-changes T-1 --comment c", + "check --at after-done --instruction i", + "close --project /p", + ] { + assert!(parse_line(line).is_some(), "{line}"); + } + } + + #[test] + fn ambiguous_or_incomplete_lines_are_refused() { + for line in [ + "init", + "init /p --ci a --verify b", + "init /p --merge sometimes", + "add 12 --task T-1", + "add --title a --title b", + "answer T-1", + "ask --question q --suggestion s", + "block --question q --suggestion s --default d", + "propose --class nonsense --text t", + "config --set novalue", + "dep add T-2", + "pause", + "check --at weekly --instruction i", + "show", + "unknown", + ] { + assert_eq!(parse_line(line), None, "{line}"); + } + } + + #[test] + fn paths_are_made_absolute_for_the_daemon() { + let Some(Command::Init { project, .. }) = parse_line("init repo") else { + panic!("init parses"); + }; + assert_eq!(project, "/work/repo"); + let Some(Command::Add { card, .. }) = parse_line("add --prd docs/prd.md --title t") else { + panic!("add parses"); + }; + assert_eq!(card.prd.as_deref(), Some("/work/docs/prd.md")); + } +} diff --git a/hided/src/lib.rs b/hided/src/lib.rs index 55675fe675..c0e2db1350 100644 --- a/hided/src/lib.rs +++ b/hided/src/lib.rs @@ -14,6 +14,7 @@ pub mod delivery_cli; pub mod demand; pub mod device_watch; pub mod env; +pub mod factory_cli; pub mod file_url; pub mod index; pub mod mobile; diff --git a/hided/src/server.rs b/hided/src/server.rs index 181d86ebb7..1f92d51e47 100644 --- a/hided/src/server.rs +++ b/hided/src/server.rs @@ -872,6 +872,21 @@ async fn client_loop( client_gone(&state, connection, renderer, desktop); } +/// A Factory card carries a goal, criteria and decisions; a PRD travels as +/// a path, so the request stays small. +const FACTORY_REQUEST_LIMIT: usize = 256 * 1024; +/// `add` waits for its intake review up to 90 s (B11); the rest answer at once. +const FACTORY_ANSWER_TIMEOUT: Duration = Duration::from_secs(100); + +fn valid_caller_hint(value: &serde_json::Value) -> bool { + value.get("caller_pane").is_none_or(|hint| { + hint.is_null() + || hint.as_str().is_some_and(|hint| { + !hint.is_empty() && hint.len() <= 256 && !hint.chars().any(char::is_control) + }) + }) +} + enum ScopedRequest { Query(herdr_core::workspace_control::Query), Action(herdr_core::workspace_control::Action), @@ -880,6 +895,8 @@ enum ScopedRequest { /// connection, then this socket carries the CDP frames. BrowserRelay(String), Delivery(herdr_core::delivery::Command, Option), + /// `hide factory`: the Factory engine answers; it needs no shell. + Factory(hide_factory::Command, Option), /// `hide links`: a read of the link record, which needs no shell. Links(herdr_core::links::query::LinksQuery), } @@ -888,7 +905,10 @@ impl ScopedRequest { /// A request a shell must be open to answer. Delivery and the link /// record are the daemon's own and answer without one (B43). fn needs_renderer(&self) -> bool { - !matches!(self, Self::Delivery(..) | Self::Links(..)) + !matches!( + self, + Self::Delivery(..) | Self::Factory(..) | Self::Links(..) + ) } } @@ -961,16 +981,7 @@ async fn scoped_client_loop( value["command"].clone(), ) .ok() - .filter(|_| { - value.get("caller_pane").is_none_or(|hint| { - hint.is_null() - || hint.as_str().is_some_and(|hint| { - !hint.is_empty() - && hint.len() <= 256 - && !hint.chars().any(char::is_control) - }) - }) - }) + .filter(|_| valid_caller_hint(&value)) .map(|command| { ScopedRequest::Delivery( command, @@ -978,10 +989,24 @@ async fn scoped_client_loop( ) }) } + Some("factory") => serde_json::from_value::( + value["command"].clone(), + ) + .ok() + .filter(|_| valid_caller_hint(&value)) + .map(|command| { + ScopedRequest::Factory( + command, + value["caller_pane"].as_str().map(str::to_owned), + ) + }), _ => None, }; if command.is_none() - || (value["type"] != "delivery" && text.len() > 16 * 1024) + || (value["type"] != "delivery" + && value["type"] != "factory" + && text.len() > 16 * 1024) + || (value["type"] == "factory" && text.len() > FACTORY_REQUEST_LIMIT) || request_id.is_empty() || request_id.len() > 64 || !request_id @@ -1062,6 +1087,11 @@ async fn scoped_client_loop( .and_then(|prepared| prepared.run(Duration::from_secs(5))) .map_err(|code| (code, "Check the current agent pane and retry the same intent"))? } + ScopedRequest::Factory(command, hint) => { + core.prepare_factory(&cap.context.device_id, &cap.pane_id, &cap.context, hint, command) + .and_then(|prepared| prepared.run(FACTORY_ANSWER_TIMEOUT)) + .map_err(|code| (code, "Check that Hide is running and retry"))? + } ScopedRequest::Links(query) => { let scope = core.links_scope(&cap.context).ok_or(( "links_unavailable".to_owned(), diff --git a/hided/src/workspace_cli.rs b/hided/src/workspace_cli.rs index d907dd8db7..de3351f44f 100644 --- a/hided/src/workspace_cli.rs +++ b/hided/src/workspace_cli.rs @@ -21,6 +21,9 @@ use crate::pane_auth::Reference; use crate::state_file::SCHEMA_VERSION; const TIMEOUT: Duration = Duration::from_secs(10); +/// Longer than the daemon's own Factory answer limit, so the daemon's reason +/// arrives rather than a local timeout. +const FACTORY_TIMEOUT: Duration = Duration::from_secs(110); const REMOTE_BOOTSTRAP_TIMEOUT: Duration = Duration::from_secs(25); /// An auto-bootstrapped direct CLI owns its reference even if transport fails. @@ -253,6 +256,27 @@ pub fn request_delivery( ) } +/// A `hide factory` command. `add` may wait for its intake review, so the +/// answer has longer than a Workspace request to arrive. +pub fn request_factory( + path: &Path, + command: &hide_factory::Command, + hint: Option<&str>, +) -> Result { + let reference = read_reference(path)?; + let request_id = fresh_request_id()?; + run_exchange_within( + path, + &reference, + json!({ + "type":"factory", "request_id":request_id, "command":command, "caller_pane":hint + }), + &request_id, + true, + FACTORY_TIMEOUT, + ) +} + /// The relay socket for one `hide browser` page command: the same scoped /// handshake and claim as every Workspace request, after which the socket /// carries CDP frames to the caller's display. A refusal keeps the daemon's @@ -328,13 +352,24 @@ fn run_exchange( payload: Value, request_id: &str, action: bool, +) -> Result { + run_exchange_within(path, reference, payload, request_id, action, TIMEOUT) +} + +fn run_exchange_within( + path: &Path, + reference: &Reference, + payload: Value, + request_id: &str, + action: bool, + timeout: Duration, ) -> Result { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .map_err(|_| "request_unavailable".to_owned())?; let (value, mut socket) = runtime.block_on(async { - tokio::time::timeout(TIMEOUT, exchange_response(reference, payload, request_id)) + tokio::time::timeout(timeout, exchange_response(reference, payload, request_id)) .await .map_err(|_| "request_timeout".to_owned())? })?; From 9efb568bf22b6df9625c7db04a235e54dcc96d89 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 04:41:31 +0900 Subject: [PATCH 05/72] Handle slow and refused worker starts and wake letters A worker whose agent has not shown a session yet holds its slot and is asked again every 30 seconds; after ten minutes the person is told to look at its pane. A refused start stops the Task with the runtime's reason instead of retrying every tick, and each retry is a new spawn intent. Before a Codex CLI start the Factory asks the kit to read the machine. A woken worker gets its letters once its agent is back. The worker prompt names the hide program beside the daemon, and the watch no longer repeats what the inbox already shows. --- herdr-core/src/factory.rs | 163 ++++++++++++++++++++++++--- herdr-core/src/runtime/factory.rs | 14 +++ hide-factory/src/adapters.rs | 15 +++ hide-factory/src/command.rs | 5 +- hide-factory/src/engine.rs | 122 +++++++++++++++++++- hide-factory/src/model.rs | 14 ++- hide-factory/src/summary.rs | 14 ++- hide-factory/tests/engine.rs | 181 ++++++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 7 +- 9 files changed, 505 insertions(+), 30 deletions(-) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index a8dc51cef6..32a458f419 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -6,7 +6,7 @@ //! The engine opens its store the first time it is asked, or at start when a //! store already exists, so a machine without a Factory pays nothing. -use std::collections::{BTreeSet, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender}; @@ -164,8 +164,23 @@ struct Waiter { struct WorkerState { /// Panes whose sleep was asked while the agent was still in its turn. pending_sleep: BTreeSet, + /// Woken workers whose agent has not come back yet, with the letters it + /// gets once it has: a letter needs the agent's session to address. + waking: BTreeMap, } +struct Woken { + worker: WorkerRef, + letters: Vec<(String, String)>, + since: Instant, +} + +/// Letters held for one woken worker, and how long a wake may take before +/// they go to the diagnostic log instead (the engine's no-report rule then +/// stops the Task). +const WOKEN_LETTER_LIMIT: usize = 16; +const WAKE_LIMIT: Duration = Duration::from_secs(10 * 60); + fn run( paths: Paths, home: Option, @@ -206,7 +221,12 @@ fn run( }), }; match Engine::open(&paths.store, &paths.files, ports) { - Ok(engine) => Some(engine), + Ok(mut engine) => { + if let Some(program) = hide_program() { + engine.set_hide_program(program); + } + Some(engine) + } Err(error) => { crate::diagnostic!( json!({"component":"factory","kind":"store.open_failed","error":error.0}) @@ -266,6 +286,11 @@ fn run( pump_letters(engine, &runtime); engine.tick(); settle_sleeps(&workers, &runtime); + let mut port = CoreWorkers { + runtime: runtime.clone(), + state: Arc::clone(&workers), + }; + port.deliver_woken(); publish_recipients(Some(engine), &runtime); } waiters.retain(|waiter| { @@ -307,6 +332,16 @@ fn publish_recipients(engine: Option<&Engine>, runtime: &Weak>) { /// Runs one command with the caller's role (D-33). A worker's report travels /// as a ledger letter from its own pane, so a harness that only speaks the /// letter protocol lands on the same path (B25). +/// The `hide` program beside the running daemon (the app bundle's +/// Resources, or a build's target folder). +fn hide_program() -> Option { + let name = if cfg!(windows) { "hide.exe" } else { "hide" }; + let program = std::env::current_exe().ok()?.parent()?.join(name); + program + .is_file() + .then(|| program.to_string_lossy().into_owned()) +} + fn handle( engine: &mut Engine, runtime: &Weak>, @@ -511,6 +546,66 @@ struct CoreWorkers { } impl CoreWorkers { + /// Hands each woken worker its letters once its agent is back. + fn deliver_woken(&mut self) { + let panes: Vec = self + .state + .lock() + .map(|state| state.waking.keys().cloned().collect()) + .unwrap_or_default(); + for pane in panes { + let Ok(runtime) = self.runtime() else { return }; + let probe = guard(&runtime).factory_worker_probe(&pane); + drop(runtime); + let Some(woken) = self + .state + .lock() + .ok() + .and_then(|mut state| state.waking.remove(&pane)) + else { + continue; + }; + if !probe.present || probe.asleep { + if woken.since.elapsed() >= WAKE_LIMIT { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.wake_timed_out","pane_id":pane,"letters":woken.letters.len()}) + ); + } else if let Ok(mut state) = self.state.lock() { + state.waking.insert(pane, woken); + } + continue; + } + let mut left = Vec::new(); + for (intent, body) in woken.letters { + if !left.is_empty() { + left.push((intent, body)); + continue; + } + if let Err(failure) = self.message(&woken.worker, &intent, None, &body) { + // The agent is back but its session is not observed yet. + if woken.since.elapsed() >= WAKE_LIMIT { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.wake_letter_failed","pane_id":pane,"reason":failure.detail}) + ); + continue; + } + left.push((intent, body)); + } + } + if !left.is_empty() + && let Ok(mut state) = self.state.lock() + { + state.waking.insert( + pane, + Woken { + letters: left, + ..woken + }, + ); + } + } + } + fn runtime(&self) -> Result>, Failure> { lock(&self.runtime) .ok_or_else(|| Failure::environment("worker", EnvSignal::HerdrSocket, "core stopped")) @@ -554,6 +649,11 @@ impl CoreWorkers { impl WorkerRuntime for CoreWorkers { fn spawn(&mut self, request: &WorkerSpawn) -> Result { let runtime = self.runtime()?; + if request.runtime == hide_factory::model::Runtime::Codex + && !guard(&runtime).factory_kit_read() + { + return Err(Failure::starting("worker.spawn", "kit_not_read")); + } let (client, authority, actor) = guard(&runtime) .factory_delivery(&request.factory) .map_err(|reason| Failure::task("worker.spawn", reason))?; @@ -583,10 +683,17 @@ impl WorkerRuntime for CoreWorkers { Some(previous.worktree.clone()), ) } - None => ( + None if request.attempt == 0 => ( format!("factory-{}-{}", request.factory, request.task), None, ), + None => ( + format!( + "factory-{}-{}-a{}", + request.factory, request.task, request.attempt + ), + None, + ), }; let view = crate::coordination::run( client, @@ -667,14 +774,31 @@ impl WorkerRuntime for CoreWorkers { .lock() .map(|mut state| state.pending_sleep.remove(&pane)) .unwrap_or(false); - if !never_slept { - let runtime = self.runtime()?; - guard(&runtime).factory_wake(&pane); - } - // The letter waits in the ledger; the doorbell rings once the agent - // is back at its prompt. let intent = format!("factory-wake-{}-{}", pane, now_ms()); - self.message(worker, &intent, None, body) + if never_slept { + // Still in its pane: the doorbell rings at its next prompt. + return self.message(worker, &intent, None, body); + } + let runtime = self.runtime()?; + guard(&runtime).factory_wake(&pane); + drop(runtime); + let mut state = self + .state + .lock() + .map_err(|_| Failure::task("worker.wake", "state unavailable"))?; + let woken = state.waking.entry(pane).or_insert_with(|| Woken { + worker: worker.clone(), + letters: Vec::new(), + since: Instant::now(), + }); + if woken.letters.len() >= WOKEN_LETTER_LIMIT { + return Err(Failure::task( + "worker.wake", + "too many letters wait for this worker", + )); + } + woken.letters.push((intent, body.to_owned())); + Ok(()) } fn status(&mut self, worker: &WorkerRef) -> WorkerStatus { @@ -776,13 +900,18 @@ impl WorkerRuntime for CoreWorkers { } fn spawn_failure(reason: &str) -> Failure { - if reason.contains("socket") - || reason.contains("delivery_unavailable") - || reason.contains("unavailable") - { - Failure::environment("worker.spawn", EnvSignal::HerdrSocket, reason) - } else { - Failure::task("worker.spawn", reason) + match reason { + // The pane was made and the agent typed in; its session is not + // visible yet. The same intent continues the spawn later. + "native_identity_unavailable" => Failure::starting("worker.spawn", reason), + "delivery_unavailable" | "ledger_unavailable" => { + Failure::environment("worker.spawn", EnvSignal::HerdrSocket, reason) + } + // A Herdr request that could not reach the server. + _ if reason.contains("socket") || reason.contains("connect") => { + Failure::environment("worker.spawn", EnvSignal::HerdrSocket, reason) + } + _ => Failure::task("worker.spawn", reason), } } diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index dbc6ca33a8..2ebc5f6913 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -220,6 +220,20 @@ impl Runtime { .cloned() } + /// Whether this Mac's kit has answered since launch; when not, asks it to + /// read the machine. A Codex start needs that answer (`codex_launch`), + /// and the Factory starts workers with no Settings on screen. + pub(crate) fn factory_kit_read(&mut self) -> bool { + if self + .kit_states + .contains_key(crate::workspace::LOCAL_DEVICE_ID) + { + return true; + } + self.request_kit_check(); + false + } + pub(crate) fn factory_ai_settings(&self) -> Option { self.ai_settings.clone() } diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index 053a34f28a..d9c94718f1 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -29,6 +29,9 @@ pub struct Failure { pub missing_scope: Option, /// Usage limit reset time (B58). pub reset_at: Option, + /// The worker's pane exists but its agent has not shown a session yet + /// (a first-run prompt, a slow start): not a failure, ask again later. + pub starting: bool, } impl Failure { @@ -39,6 +42,14 @@ impl Failure { detail: detail.into(), missing_scope: None, reset_at: None, + starting: false, + } + } + + pub fn starting(stage: &str, detail: impl Into) -> Self { + Self { + starting: true, + ..Self::task(stage, detail) } } @@ -49,6 +60,7 @@ impl Failure { detail: detail.into(), missing_scope: None, reset_at: None, + starting: false, } } } @@ -276,6 +288,9 @@ pub struct WorkerSpawn { pub args: Vec, /// Reuse the worktree and session (retry, wake, relanding). pub resume: Option, + /// How many earlier fresh starts were refused: each attempt is its own + /// spawn intent, and the same attempt asked again converges. + pub attempt: u32, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs index 3cc82d8f76..60e9778667 100644 --- a/hide-factory/src/command.rs +++ b/hide-factory/src/command.rs @@ -310,7 +310,10 @@ pub fn render_human(verb: &str, answer: &Value) -> String { } text } - "config" => serde_json::to_string_pretty(&answer["config"]).unwrap_or_default(), + "config" => serde_json::to_string_pretty( + &serde_json::json!({"config": answer["config"], "machine": answer["machine"]}), + ) + .unwrap_or_default(), _ => { let mut text = answer["message"].as_str().unwrap_or("ok").to_owned(); if let Some(task) = answer.get("task") diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index a7b31c91bd..3fc0793b2a 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -60,6 +60,10 @@ const BACKOFF_MS: [u64; 5] = [ const PROCESSED_LETTERS: usize = 4_096; const CASCADE_WINDOW_MS: u64 = 30 * MINUTE_MS; const ENV_RECHECK_MS: u64 = MINUTE_MS; +/// How often a worker whose agent has not shown a session is asked again, +/// and when the person is told to look at its pane. +const START_RETRY_MS: u64 = 30_000; +const START_NOTICE_MS: u64 = 10 * MINUTE_MS; struct VerifyState { run: VerifyRun, @@ -104,6 +108,12 @@ pub struct Engine { /// A runtime unavailable until its usage resets (B58). runtime_blocked: BTreeMap, github_backoff: BTreeMap, + /// The `hide` program a worker runs: the one beside this daemon, so a + /// worker never reaches an older copy earlier on its PATH. + hide_program: String, + /// Workers whose agent has not shown a session yet: (first seen, next + /// ask). Each holds its slot (B57's count) until it starts or is given up. + starting: BTreeMap<(String, String), (UnixMs, UnixMs)>, machine_max_workers: u32, question_seq: u64, } @@ -124,6 +134,10 @@ fn refuse(reason: &str, next: &str) -> Refusal { } impl Engine { + pub fn set_hide_program(&mut self, program: impl Into) { + self.hide_program = program.into(); + } + pub fn open(store: &Path, files: &Path, ports: Ports) -> Result { let store = Store::open(store, files)?; let loaded = store.load()?; @@ -147,6 +161,8 @@ impl Engine { hold_reason: None, runtime_blocked: BTreeMap::new(), github_backoff: BTreeMap::new(), + hide_program: "hide".into(), + starting: BTreeMap::new(), machine_max_workers: 5, question_seq: 0, }; @@ -360,6 +376,7 @@ impl Engine { } if state != TaskState::Stopped { task.stop = None; + task.stop_detail = None; } } }); @@ -449,6 +466,7 @@ impl Engine { self.all_tasks() .filter(|task| task.state.holds_slot()) .count() as u32 + + self.starting.len() as u32 } // ----------------------------------------------------------------- commands @@ -3884,6 +3902,17 @@ impl Engine { fn start_tasks(&mut self) { let now = self.now(); + // A Task cancelled or paused while its worker was starting frees + // the slot. + let starting: Vec<_> = self.starting.keys().cloned().collect(); + for (factory, id) in starting { + if self + .task(&factory, &id) + .is_none_or(|t| t.state != TaskState::Waiting) + { + self.starting.remove(&(factory, id)); + } + } if self.halt_until.is_some_and(|until| until > now) { return; } @@ -3954,6 +3983,14 @@ impl Engine { .machine_max_workers .saturating_sub(self.running_count()); for task in candidates { + let key = (task.factory.clone(), task.id.clone()); + if let Some((_, next)) = self.starting.get(&key) { + // Its slot is already counted; ask again when due. + if *next <= now { + self.start(&task.factory, &task.id); + } + continue; + } // A relanding Task already holds its slot. let relanding = task.state == TaskState::Relanding; if free == 0 && !relanding { @@ -4019,7 +4056,7 @@ impl Engine { runtime, project: factory.project.clone(), branch: worker.branch.clone(), - prompt: worker_prompt(&task, &factory, true), + prompt: worker_prompt(&task, &factory, true, &self.hide_program), args: factory .config .worker_args @@ -4027,6 +4064,7 @@ impl Engine { .cloned() .unwrap_or_default(), resume: Some(worker.clone()), + attempt: task.spawn_refusals, }; self.ports.workers.spawn(&request).map(Some) } else { @@ -4060,7 +4098,7 @@ impl Engine { runtime, project: factory.project.clone(), branch: task.branch_slug(), - prompt: worker_prompt(&task, &factory, false), + prompt: worker_prompt(&task, &factory, false, &self.hide_program), args: factory .config .worker_args @@ -4068,9 +4106,12 @@ impl Engine { .cloned() .unwrap_or_default(), resume: None, + attempt: task.spawn_refusals, }; + let key = (factory_id.to_owned(), id.to_owned()); match self.ports.workers.spawn(&request) { Ok(worker) => { + self.starting.remove(&key); self.with_task(factory_id, id, |t| { t.worker = Some(worker); t.last_report_at = None; @@ -4084,14 +4125,62 @@ impl Engine { self.set_state(factory_id, id, TaskState::Running); true } + Err(failure) if failure.starting => { + self.worker_starting(factory_id, id, &failure); + true + } Err(failure) => { + self.starting.remove(&key); self.external_failure(factory_id, Some(id), &failure); + if failure.signal.is_none() { + // A refused start does not change by asking again; + // a person fixes the cause and retries (B54). + self.set_state(factory_id, id, TaskState::Stopped); + let detail = judgment::cut(&failure.detail, 300); + self.with_task(factory_id, id, |t| { + t.stop = Some(StopReason::WorkerStart); + t.stop_detail = Some(detail); + t.spawn_refusals += 1; + }); + } false } } } } + /// The worker's pane runs but its agent has shown no session: ask the + /// same spawn again later, and after a while tell the person to look + /// at the pane, where a first-run prompt may be waiting. + fn worker_starting(&mut self, factory: &str, id: &str, failure: &Failure) { + let now = self.now(); + let key = (factory.to_owned(), id.to_owned()); + let first = match self.starting.get(&key) { + Some((first, _)) => *first, + None => { + self.record( + factory, + Some(id), + "worker.starting", + json!({"detail": failure.detail}), + ); + now + } + }; + self.starting.insert(key, (first, now + START_RETRY_MS)); + if now.saturating_sub(first) >= START_NOTICE_MS { + let name = self + .task(factory, id) + .map(|t| worker_name(&self.factories[factory], t)) + .unwrap_or_default(); + self.once_notice( + factory, + id, + &format!("worker {name}가 시작되지 않았습니다. 그 pane에서 신뢰·로그인 같은 확인 화면이 기다리는지 보세요."), + ); + } + } + // ------------------------------------------------------------ outside work fn read_outside(&mut self) { @@ -4504,7 +4593,11 @@ impl Engine { factory, task, "external.failed", - json!({"stage": failure.stage, "signal": failure.signal.map(EnvSignal::as_str)}), + json!({ + "stage": failure.stage, + "signal": failure.signal.map(EnvSignal::as_str), + "detail": judgment::cut(&failure.detail, 200), + }), ); let now = self.now(); let Some(signal) = failure.signal else { return }; @@ -4832,6 +4925,21 @@ impl Engine { .and_then(|t| self.resolve(&Role::Engine, &t).ok().map(|(_, id)| id)) .or_else(|| self.tasks_of(factory_id).last().map(|t| t.id.clone())); let Some(anchor) = anchor else { continue }; + // A Task already waiting on a person is in the inbox; a warning + // about it would say the same thing twice (design #13). + if warning.task.is_some() + && self + .task(factory_id, &anchor) + .is_some_and(|t| t.open_questions().next().is_some()) + { + self.record( + factory_id, + Some(&anchor), + "watch.logged", + json!({"already_open": true}), + ); + continue; + } self.add_question( factory_id, &anchor, @@ -5112,7 +5220,7 @@ fn worker_name(factory: &Factory, task: &Task) -> String { /// The worker's first prompt (B22): the card, the attachments, the harness /// preset and the Factory's reporting rules. -pub fn worker_prompt(task: &Task, factory: &Factory, resumed: bool) -> String { +pub fn worker_prompt(task: &Task, factory: &Factory, resumed: bool, hide: &str) -> String { let mut prompt = String::new(); if resumed { prompt.push_str("Factory: 같은 worktree에서 이 Task를 이어서 맡습니다. 지금까지 한 일을 확인하고 이어가세요.\n\n"); @@ -5142,6 +5250,12 @@ pub fn worker_prompt(task: &Task, factory: &Factory, resumed: bool) -> String { )); } prompt.push_str(REPORTING_RULES); + if hide != "hide" { + prompt.push_str(&format!( + "- 위와 이후 편지의 `hide`는 모두 이 프로그램입니다: '{}'\n", + hide.replace('\'', "'\\''") + )); + } prompt } diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index be90e2eb12..47c50beaf4 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -199,8 +199,6 @@ pub struct Config { pub merge_method: MergeMethod, /// Optional quick check before a merge (D-46), run on the merged tree. pub quick_check: Option, - /// Concurrent workers on this machine across every Factory (D-30, D-45). - pub max_workers: u32, pub question_deadline_ms: u64, pub stall_ms: u64, pub no_report_ms: u64, @@ -236,7 +234,6 @@ impl Default for Config { merge_mode: MergeMode::Manual, merge_method: MergeMethod::Merge, quick_check: None, - max_workers: 5, question_deadline_ms: 24 * HOUR_MS, stall_ms: 30 * MINUTE_MS, no_report_ms: 2 * MINUTE_MS, @@ -664,6 +661,7 @@ pub enum StopReason { VerifyFailed, NewTaskCap, EnvironmentRepeated, + WorkerStart, } impl StopReason { @@ -674,6 +672,7 @@ impl StopReason { Self::VerifyFailed => "검증 3회 실패", Self::NewTaskCap => "새 Task 상한", Self::EnvironmentRepeated => "같은 환경 실패 반복", + Self::WorkerStart => "worker 시작 실패", } } } @@ -770,6 +769,13 @@ pub struct Task { pub merge_sha: Option, pub gates: Vec, pub stop: Option, + /// What the runtime said when the stop came from outside the Task, such + /// as a refused worker start; shown beside the stop reason. + #[serde(default)] + pub stop_detail: Option, + /// Fresh worker starts refused so far; names the next start's intent. + #[serde(default)] + pub spawn_refusals: u32, pub breaking: bool, pub scope_approved: bool, pub new_tasks: u32, @@ -845,6 +851,8 @@ impl Task { merge_sha: None, gates: Vec::new(), stop: None, + stop_detail: None, + spawn_refusals: 0, breaking: false, scope_approved: false, new_tasks: 0, diff --git a/hide-factory/src/summary.rs b/hide-factory/src/summary.rs index 0a4d1bf566..5010cd0d6c 100644 --- a/hide-factory/src/summary.rs +++ b/hide-factory/src/summary.rs @@ -425,10 +425,16 @@ pub fn inbox_items( let mut item = base( "stopped", 3, - format!( - "멈춤: {}", - task.stop.map(|reason| reason.label()).unwrap_or("?") - ), + match &task.stop_detail { + Some(detail) => format!( + "멈춤: {} - {detail}", + task.stop.map(|reason| reason.label()).unwrap_or("?") + ), + None => format!( + "멈춤: {}", + task.stop.map(|reason| reason.label()).unwrap_or("?") + ), + }, task.state_since, ); item.choices = vec!["retry".into(), "cancel".into()]; diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 853d0afdb2..fad0a60e42 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1504,3 +1504,184 @@ fn the_inbox_orders_blocking_questions_first_then_answers_merges_and_stops() { // Merge waiting sits in the running column (D-47). assert_eq!((flow.running, flow.waiting), (3, 0)); } + +// ------------------------------------------------------------ slow worker start + +#[test] +fn a_worker_whose_agent_has_not_started_holds_its_slot_and_is_asked_again_later() { + let mut h = Bench::new(false); + let f = h.factory(true); + set_workers(&mut h, &f, 1); + h.world().spawn_failure = Some(Failure::starting( + "worker.spawn", + "native_identity_unavailable", + )); + let a = h.ready("A", &[]); + h.engine.tick(); + assert_eq!(h.state(&f, &a), TaskState::Waiting); + let b = h.ready("B", &[]); + for _ in 0..3 { + h.advance(5_000); + h.engine.tick(); + } + let starting = |h: &Bench| { + h.engine + .events(&f, None, 100) + .iter() + .filter(|e| e.kind == "worker.starting") + .count() + }; + assert_eq!(starting(&h), 1, "recorded once, not once per tick"); + assert!( + h.engine + .events(&f, None, 100) + .iter() + .all(|e| e.kind != "external.failed"), + "a slow start is not a failure" + ); + assert_eq!( + h.state(&f, &b), + TaskState::Waiting, + "A's slot is still held" + ); + assert!(h.task(&f, &a).open_questions().next().is_none()); + + // Ten quiet minutes: the person is told to look at the pane. + h.advance(10 * 60_000); + h.engine.tick(); + let notice = open_question(&h, &f, &a); + assert!( + notice.text.contains("시작되지 않았습니다"), + "{}", + notice.text + ); + + // The agent comes up: the same spawn now answers, and B still waits. + h.world().spawn_failure = None; + h.advance(30_000); + h.engine.tick(); + assert_eq!(h.state(&f, &a), TaskState::Running); + assert_eq!(h.state(&f, &b), TaskState::Waiting); + assert_eq!(h.world().spawned.len(), 1); +} + +#[test] +fn a_refused_worker_start_stops_the_task_once_and_a_retry_starts_it() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().spawn_failure = Some(Failure::task( + "worker.spawn", + "Codex support could not be confirmed", + )); + let a = h.ready("A", &[]); + for _ in 0..5 { + h.advance(2_000); + h.engine.tick(); + } + let task = h.task(&f, &a); + assert_eq!(task.state, TaskState::Stopped); + assert_eq!(task.stop, Some(StopReason::WorkerStart)); + let failed = h + .engine + .events(&f, Some(&a), 100) + .iter() + .filter(|e| e.kind == "external.failed") + .count(); + assert_eq!(failed, 1, "a refusal is not asked again every tick"); + let inbox = h.engine.summary().inbox; + let item = inbox.iter().find(|i| i.task == a).expect("stopped item"); + assert!( + item.text.contains("Codex support could not be confirmed"), + "{}", + item.text + ); + + h.world().spawn_failure = None; + let answer = h.op(Command::Retry { task: a.clone() }); + assert_eq!(answer["ok"], true, "{answer}"); + h.engine.tick(); + assert_eq!(h.state(&f, &a), TaskState::Running); + assert_eq!(h.task(&f, &a).stop_detail, None); + assert_eq!( + h.world().spawned[0].attempt, + 1, + "the retry is a new start, not the refused one again" + ); +} + +// ------------------------------------------------------------------ watch + +#[test] +fn the_watch_raises_actionable_warnings_once_each_within_the_daily_cap() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("A", &[]); + let b = h.ready("B", &[]); + let asked = h.as_worker( + &f, + &a, + Command::Ask { + text: "Which name?".into(), + suggestion: "calc".into(), + default_action: "use calc".into(), + deadline_hours: Some(24), + letter: None, + }, + ); + assert_eq!(asked["ok"], true, "{asked}"); + let notices = |h: &Bench, id: &str| { + h.task(&f, id) + .open_questions() + .filter(|q| q.text.starts_with("감시:")) + .count() + }; + h.world().watch.push_back(json!({"warnings": [ + {"text": "nothing to do here"}, + {"text": "A still waits on its answer", "action": "answer A", "task": a}, + {"text": "B has been quiet", "action": "look at B", "task": b}, + ]})); + // The watch reads the board every 30 minutes (B69). + h.advance(30 * 60_000); + h.engine.tick(); + h.engine.tick(); + assert_eq!( + notices(&h, &b), + 1, + "an actionable warning reaches the inbox" + ); + assert_eq!(notices(&h, &a), 0, "A is already in the inbox"); + let logged = h + .engine + .events(&f, None, 200) + .iter() + .filter(|e| e.kind == "watch.logged") + .count(); + assert_eq!(logged, 2, "no action, or already open: the log only"); + + // At most five a day. + for n in 0..6 { + h.world().watch.push_back(json!({"warnings": [ + {"text": format!("finding {n}"), "action": "check", "task": null}, + ]})); + h.advance(30 * 60_000); + h.engine.tick(); + h.engine.tick(); + } + let sent: usize = h + .engine + .tasks_of(&f) + .map(|t| { + t.questions + .iter() + .filter(|q| q.text.starts_with("감시:")) + .count() + }) + .sum(); + assert_eq!(sent, 5, "the daily cap holds"); + assert!( + h.engine + .events(&f, None, 400) + .iter() + .any(|e| e.kind == "watch.capped") + ); +} diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 813f7f99d8..37f58dd9c9 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -54,6 +54,8 @@ pub struct World { /// Intake answers by card title; a plain ready verdict when absent. pub intake: BTreeMap, pub drift: BTreeMap, + /// Scripted watch answers, oldest first; no warnings when empty. + pub watch: VecDeque, pub judge_down: bool, pub hold_judgments: bool, pub disk_free: Option, @@ -385,7 +387,10 @@ impl Judge for Shared { .as_ref() .and_then(|task| world.drift.get(task).cloned()) .unwrap_or_else(|| json!({"pass": true, "questions": [], "flags": []})), - JudgmentInput::Watch { .. } => json!({"warnings": []}), + JudgmentInput::Watch { .. } => world + .watch + .pop_front() + .unwrap_or_else(|| json!({"warnings": []})), JudgmentInput::EnvDiagnosis { .. } => json!({"cause": "unknown", "action": "none"}), }; answers.push(JudgmentAnswer { From d9124dccf9ed7b1d4e838e4451720886994f25c2 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 04:43:27 +0900 Subject: [PATCH 06/72] Keep the Factory watch to what the inbox does not show --- hide-factory/src/judgment.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hide-factory/src/judgment.rs b/hide-factory/src/judgment.rs index 545e094528..2703724965 100644 --- a/hide-factory/src/judgment.rs +++ b/hide-factory/src/judgment.rs @@ -453,7 +453,7 @@ const INTAKE_SYSTEM: &str = "You review a software Task card before it runs, wit const DRIFT_SYSTEM: &str = "You compare a finished change with the Task card it claims to complete: its goal, completion criteria and out-of-scope list, and the decisions the worker recorded. Return JSON only. pass is true when the diff does what the card asks and nothing it rules out. When it drifts, add questions for a person, each with a suggestion and a default action that keeps the change as narrow as the card; add flags for a reported breaking change or a public contract change. You cannot send work back and you cannot approve anything wider than the card."; -const WATCH_SYSTEM: &str = "You read a Factory board summary: recent events, Task states, waits and decision records. Return JSON only: warnings a person should act on, each naming the Task id it is about when there is one and an action the person can take. A warning with no action is still allowed but goes to a log. Never propose merging, removing dependencies or widening scope on your own."; +const WATCH_SYSTEM: &str = "You read a Factory board summary: recent events, Task states, waits and decision records. Return JSON only: warnings a person should act on, each naming the Task id it is about when there is one and an action the person can take. A warning with no action is still allowed but goes to a log. Never propose merging, removing dependencies or widening scope on your own. Do not restate anything a person already sees as a question, a merge wait or a stop in the inbox, and do not report finished Tasks or ordinary progress: those are not a person's turn. Warn only about what a person cannot see there, such as work that stopped moving, a chain blocked by one wait, or a pattern of failures."; const ENV_SYSTEM: &str = "You diagnose an environment problem from facts the code collected (disk usage by owner, failure signals, which stage failed, how many Tasks). Return JSON only: a one-line cause, and either one action from the given list (or \"none\"), or an exact shell command with its impact for a person to approve. Never choose an action that is not in the list; login, deletion outside the Factory and installing tools are always a proposal."; From 1c1f223cb860dfffd5f1cfeb95594c39befab9db Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 04:55:09 +0900 Subject: [PATCH 07/72] Default a Factory command to the caller's checkout --- herdr-core/src/factory.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index 32a458f419..1989a619cb 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -356,6 +356,15 @@ fn handle( }; // A pending review answers the pane that added the Task (B11); that is // the caller, never a pane the request names. + // A command that names no project means the Factory of the caller's + // checkout, when it has one; `status` without one still shows them all. + let here = || { + caller + .cwd + .as_deref() + .and_then(|cwd| engine.factory_for_project(cwd)) + .map(|factory| factory.project.clone()) + }; let command = match command { Command::Add { project, @@ -364,12 +373,28 @@ fn handle( card, producer_pane: _, } => Command::Add { - project, + project: project.or_else(here), task, issue, card, producer_pane: caller.pane.clone(), }, + Command::Config { project, set } => Command::Config { + project: project.or_else(here), + set, + }, + Command::Close { project } => Command::Close { + project: project.or_else(here), + }, + Command::Check { + project, + at, + instruction, + } => Command::Check { + project: project.or_else(here), + at, + instruction, + }, other => other, }; let kind = match &command { From 94280f246a29168f3840e91eadfe644e31acda04 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 04:55:09 +0900 Subject: [PATCH 08/72] Describe the Software Factory in its own guide docs/factory.md owns the engine, store, Task states, roles, the mailbox recipient, worker lifecycle, judgments, verification, merge, outside work, environment handling, configuration, the hide factory command and the read model the stage 2 screen draws. delivery.md, ARCHITECTURE.md, AI_PROVIDERS.md, agent-hooks.md and the documentation map point to it. --- docs/AI_PROVIDERS.md | 12 +- docs/ARCHITECTURE.md | 9 + docs/README.md | 1 + docs/agent-hooks.md | 4 +- docs/delivery.md | 11 +- docs/factory.md | 628 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 660 insertions(+), 5 deletions(-) create mode 100644 docs/factory.md diff --git a/docs/AI_PROVIDERS.md b/docs/AI_PROVIDERS.md index 226dde7d4f..587d5e573b 100644 --- a/docs/AI_PROVIDERS.md +++ b/docs/AI_PROVIDERS.md @@ -1,7 +1,7 @@ # Background AI providers `hide-ai/` is the one boundary through which a Hide feature asks a language model for something in the background. -Its consumers are the core's agent label analyzer (`herdr-core/src/labels/analyzer.rs`), Project Memory extraction under `hide-memory/`, and the Start dialog's worktree name; later features reuse the same boundary rather than a provider client of their own. +Its consumers are the core's agent label analyzer (`herdr-core/src/labels/analyzer.rs`), Project Memory extraction under `hide-memory/`, the Software Factory's judgments (see [The Factory's judgments](#the-factorys-judgments)), and the Start dialog's worktree name; later features reuse the same boundary rather than a provider client of their own. This guide owns the boundary's rules; the code under `hide-ai/src/` and the tests under `hide-ai/tests/` are its executable authority. ## Ownership split @@ -155,6 +155,14 @@ A request that completes under the cap clears the restart count; three consecuti On a platform without the kernel query the measurement is `Unavailable`: the process caps are not enforced and the log line says `measurement=unavailable` rather than a zero. The label worker treats `OverBudget` as an environmental failure: it keeps the goal, drops the turn's line and end, and asks again after ten minutes, the same as any other environmental failure (`AnalysisFailure::retry_after`). +## The Factory's judgments + +The Software Factory asks for its intake review, drift check, natural-language checks, watch and environment diagnosis through `hide-ai`, and [factory.md](factory.md#intake-review-and-judgments) owns what each asks. +The Factory does not share the label analyzer's router: it has its own `AiRouter` (`herdr-core/src/ai.rs`, `factory_router`) and its own queue on a judgment thread, so a Factory request never waits behind a label and a label never waits behind a Factory request. +The queue's terms are one request in flight, intake reviews before every other judgment, and 16 waiting judgments per Factory; a request that does not fit, or that fails, is handed to a person and is never read as a pass. +Each request has a 180 second deadline and a schema version, and the router keeps its default caps. +Because the routers are independent, they share the account's usage and the machine's CPU but not a queue; label latency has to be measured with a Factory running under load before the two are called independent. + ## Weekly usage display The sidebar footer's Weekly Usage chips and popover ([UI_BEHAVIOR.md: Weekly usage](UI_BEHAVIOR.md#weekly-usage)) show a separate read-only capability owned by `herdr-core/src/usage.rs`. @@ -250,7 +258,7 @@ The router emits `ai.attempt`, `ai.request.finished`, `ai.request.joined`, `ai.f A line carries the request id, feature id, provider, outcome class, attempt, duration, input length, output tokens and schema version. Every codex `ai.request.finished` also carries the app-server pid and the process measurement (`app_server_pid`, `descendants`, `rss_bytes`), or `measurement=unavailable` where the platform cannot measure it. It never carries the prompt, the input, the generated text, a token, a file path from a transcript, or a provider thread id. -Hide's core writes the events of its own routers and backends (the label analyzer, the Settings probe and Project Memory) to its diagnostic log, `Logs/core.jsonl` beside `state.json`, as records with `component` `ai` and the event name as `kind`. +Hide's core writes the events of its own routers and backends (the label analyzer, the Factory's judgments, the Settings probe and Project Memory) to its diagnostic log, `Logs/core.jsonl` beside `state.json`, as records with `component` `ai` and the event name as `kind`. ## Known gaps diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cce22f019c..d84032e3a2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -854,6 +854,15 @@ Nothing runs under the runtime mutex: conversation reads run on the worker's rea `herdr-core/src/labels/tests.rs` owns the behavior and `desktop/e2e/session-labels.spec.ts` proves it end to end; [status-model.md](status-model.md#task-identity) names the regression owners. +### The Factory host + +The Software Factory's engine runs on its own thread, `herdr-core-factory`, beside the delivery worker and the label analyzer, and its judgments run on a second thread, `herdr-core-factory-judge`, with a router of their own. +The engine is the `hide-factory` crate, which does not know the runtime or Herdr; the host in `herdr-core/src/factory.rs` gives it a clock, the project's git and `gh`, the verify runner, and a worker port, and `runtime/factory.rs` holds the few places that take `Mutex` to read owned data or hand the core a request. +No file, SQLite, network or subprocess work happens under the runtime lock, and a command reaches the engine through a bounded queue instead of a call into the runtime. +`hided` routes `hide factory` over the pane-capability socket and refuses a device caller. +`Core::drop` stops the Factory host first, so its verify runs and external calls end with the daemon. +[factory.md](factory.md) owns the engine, the store, the roles and the read model. + ### The mobile companion Everything a phone touches lives in `hided/src/mobile/`, and `herdr-core` does not know phones exist; its only addition is `Runtime::remote_herdr_api`, which lends the Herdr API connection it already holds for a connected SSH device. diff --git a/docs/README.md b/docs/README.md index 2b9d9ee4e9..344e69719a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -57,6 +57,7 @@ A document's location or an old PRD citation does not make it current authority. | Local agent mailbox, safe prompt intake, durable delivery and parent inactivity watches | [delivery.md](delivery.md) | `herdr-core/src/delivery/`, `runtime/delivery.rs`, `hided/src/delivery_cli.rs`, `hide-agent-hooks/src/delivery.rs`, `hide-session/src/session_activity.rs`, `hide-host/src/{protocol,serve}.rs` | | What Hide installs on each machine (the install kit): the `hide` link, the hook entries, the retirement stage and the Codex daemon setting, on this Mac and every device, with Reinstall and device removal, and the retirement of the old labels plugin | [ARCHITECTURE.md: The install kit](ARCHITECTURE.md#the-install-kit), [INSTALL.md: What the first launch installs](INSTALL.md#what-the-first-launch-installs) | `hide-kit/` (`src/coordination_retirement.rs` retires the former coordinator, `src/labels.rs` retires the labels plugin, `src/codex_per_pane.rs` the Codex daemon part), `hide-agent-hooks/src/codex_daemon.rs`, `hide-host/src/kit.rs`, `herdr-core/src/{kit.rs,runtime/kit.rs,codex_launch.rs}`, `remote/host.rs` payload, `kit_check`, `kit_reinstall`, `kit_component_set` and `kit_agent_set` events, `DeviceSnapshot.kit`, `hide-kit/src/{agents,agent_kit}.rs` (the adapter table, detection and the skill stub), `hide-agent-hooks/src/guidance.rs`, the first-run agent choice (the `agent_onboarding_apply` event, `UiState.agent_onboarding`, the kit record's `awaiting_choice`, `web/src/AgentOnboarding.tsx`), `desktop/e2e/{device-kit.spec.ts,device-home.ts}` | | What differs between macOS, Linux and Windows, written once: the local stream under the Herdr client, the child-start helper and pid questions, the private files, locks, atomic replacement, links, file identity and disk space every crate used to answer for itself, folder watching, and where the account's things live | [ARCHITECTURE.md: The platform layer](ARCHITECTURE.md#the-platform-layer) | `hide-platform/` (`ipc`, `process`, `fs`, `watch`, `host`), `hide-platform/tests/` (run on all three systems by `.github/workflows/os-contract.yml`), `hide-herdr-client/tests/real_herdr.rs` | +| The Software Factory: its engine, the SQLite store, Task states and the dependency graph, roles, the `factory:` recipient, worker lifecycle, judgments, verification, merge and revert, outside work, environment rules, the `hide factory` command and the `FactorySummary` and `TaskDetail` read model | [factory.md](factory.md) | `hide-factory/`, `hide-factory/tests/{engine,github,local_git}.rs`, `herdr-core/src/{factory.rs,runtime/factory.rs}`, `hided/src/factory_cli.rs` | | Shared Herdr socket requests and event subscriptions | [Herdr wire boundary](ARCHITECTURE.md#the-herdr-wire-boundary) | `hide-herdr-client/`, `herdr-core/src/wire.rs`, plugin transports | | Sidebar PR details, CI rollup, refresh and failure states | [status-model.md: GitHub status](status-model.md#github-status-in-the-workspace-row) | `github.rs`, `runtime.rs`, `web/src/sidebar.tsx` | | Agent status, semantic colors, Workspace aggregation, and read/unread policy | [status-model.md](status-model.md) | `sidebar.rs`, `web/src/agentRow.ts`, `web/src/sidebar.tsx`, status tests | diff --git a/docs/agent-hooks.md b/docs/agent-hooks.md index 56d6e4bebb..12516c5e74 100644 --- a/docs/agent-hooks.md +++ b/docs/agent-hooks.md @@ -32,7 +32,7 @@ Nothing else is read from the command but the helper's quoted path, and the help ## What the hook returns and reports back -On `SessionStart`, the helper writes one runtime JSON envelope whose `hookSpecificOutput.additionalContext` combines the existing one-line worktree-purpose instruction with the bounded Project Memory capsule when Memory is enabled. +On `SessionStart`, the helper writes one runtime JSON envelope whose `hookSpecificOutput.additionalContext` combines the worktree-purpose instruction, which also tells the agent to run `hide factory add` to put work into a Factory instead of adding a GitHub label (see [factory.md](factory.md)), with the bounded Project Memory capsule when Memory is enabled. The same envelope adds Workspace commands only after `hide workspace bootstrap` and `hide workspace info` confirm a renderer-connected Workspace for the caller and report its actual capabilities. The probe does not need a pane id: the daemon binds a caller inside a Herdr pane to that pane, and any other local caller, such as a tool shell or hook inside Codex's shared app-server daemon or a plain terminal, to the registered checkout holding its cwd (`docs/ARCHITECTURE.md`, the Workspace CLI). The guidance names that checkout path, so a session can read which Workspace its commands reach. @@ -149,7 +149,7 @@ Two pieces are written per agent, and nothing else: - The guidance hook, for the agents below marked as done. It is one `SessionStart` entry, in the agent's own format, whose command is `hide-agent-hooks hook --runtime --event SessionStart`. `hide-agent-hooks` writes it (`src/guidance.rs`) and nothing else does, under the marker `hide-guidance@1` that proves an entry is Hide's and separates a current one from an older one. - Its output is the one-line worktree-purpose instruction, one fixed line that points at `hide browser help`, and the live Workspace guidance when the daemon answers, in the field the agent documents. + Its output is the worktree-purpose instruction, including the sentence that points at `hide factory add`, one fixed line that points at `hide browser help`, and the live Workspace guidance when the daemon answers, in the field the agent documents. It prints no Memory capsule, because the Memory receipt is read from Claude and Codex transcripts, and it keeps no counters and writes no file. A second delivery of the same session therefore changes nothing: the output is a pure function of the daemon's answer, and a test runs the hook twice and compares. diff --git a/docs/delivery.md b/docs/delivery.md index 148795a69b..c26863e457 100644 --- a/docs/delivery.md +++ b/docs/delivery.md @@ -109,7 +109,7 @@ Capacity errors retain existing letters and watches. | Pending delivery deadline | 60 minutes, then `undelivered`; visible through CLI | | Quiet period | 30 seconds since hide last routed a key and since Herdr last changed the pane's status | | Doorbell reservations per letter | Three total, persisted across restart | -| First inactivity warning | 20 minutes without activity | +| First inactivity warning | 20 minutes without activity; 30 minutes when the observer is a Factory | | Second inactivity warning | First-warning time plus 60 minutes, at most two warnings per episode | | Unanswered parent warning notification | First-warning time plus 60 minutes, once per native target and inactivity episode | | Intent retention and finished-letter cleanup | 30 days; open letters remain | @@ -156,6 +156,15 @@ A done target remains watched until exit, explicit stop or a completion report. The first actual post-flush confirmation records `hook_confirmed: true` and ends a matching sender-parent watch for `hide request send --kind report`, even after acknowledgement, cancellation or the delivery deadline; replay after restart preserves a watch explicitly started after that receipt. A report from an unwatched sender is an ordinary letter; the parent can restart a watch explicitly. +## The code-owned recipient `factory:` + +Each open Factory is a code-owned recipient named `factory:`, and [factory.md](factory.md#the-mailbox-recipient-factoryid) owns how it is used. +Only the Factory's engine sends as it, and the ledger accepts that authority only while the Factory exists and is open. +A pane or agent may send to it and may name it as a watch observer, and only while the Factory exists and is open; a pane or agent name that starts with `factory:` is refused at registration. +A letter to it is never pasted into a composer and never rings a doorbell: the engine reads it, confirms it and, for a request or block, replies with its answer. +The human-notice claim skips a letter whose recipient is code-owned. +A watch observed by a Factory warns after 30 minutes without activity rather than 20, and the engine acts on the first warning. + ## Agent registration and spawning `hide agent register [--check]`, `list`, `show` and `end` preserve the caller surface used by dispatch and Fork. diff --git a/docs/factory.md b/docs/factory.md new file mode 100644 index 0000000000..085732d33f --- /dev/null +++ b/docs/factory.md @@ -0,0 +1,628 @@ +# Software Factory + +The Software Factory takes Tasks whose requirements are clear, runs them through worker agents in dependency order, verifies and merges them, and hands a person only what needs a person. +This guide owns the Factory's engine, its store, its roles, its commands and the read model a screen draws. +`hide-factory/`, the host thread in `herdr-core/src/factory.rs` and `herdr-core/src/runtime/factory.rs`, and the `hide factory` route in `hided/` are its executable authority. +[delivery.md](delivery.md) owns the mailbox the Factory writes through, [AI_PROVIDERS.md](AI_PROVIDERS.md) owns the provider boundary its judgments use, and [ARCHITECTURE.md](ARCHITECTURE.md#the-factory-host) owns the thread and lock rules. + +Three deciders work in a fixed order, and a decision that ends at a lower one never rises. +Code runs the rules and enforces every boundary: states, order, slots, merges, reverts, roles and caps. +A tool-less judgment may only make work slower or safer: it adds a question, a dependency or a flag, and never removes, widens or approves. +A person sets intent, loosens a gate, widens a scope and decides what cannot be undone. + +## What a Factory is and who owns what + +A Factory is one project's work queue. +A project has at most one Factory, named by the project's canonical primary checkout path; its id is `f-` and the first ten hex digits of that path's SHA-256. +A Factory whose project has a `github.com` origin takes its Tasks from GitHub issues and merges pull requests (a GitHub Factory). +Any other Factory keeps its issues in the core's local issue store as `L-` and merges into the local default branch (a local Factory). +Closing a Factory keeps its records, and creating a Factory for the same project again brings them back. + +| Owner | What it owns | +| --- | --- | +| `hide-factory` crate | Values (`model.rs`), the store (`store.rs`), the dependency graph (`dag.rs`), roles and permissions (`role.rs`), the command contract and its printing (`command.rs`), the judgment features (`judgment.rs`), the read model (`summary.rs`), the adapter traits (`adapters.rs`), the engine (`engine.rs`) and the real git, `gh` and verify adapters (`project.rs`, `exec.rs`, `verify.rs`). It does not know the runtime or Herdr. | +| Host thread in the core | `herdr-core/src/factory.rs`: the engine thread, its request queue, the worker port (spawn, letters, sleep, wake, worktree removal), the judgment thread and the notifier. `runtime/factory.rs` holds the few reads and requests that take the runtime lock for owned data. | +| `hided` | The pane-capability `factory` request in `server.rs` (`ScopedRequest::Factory`) and the `hide factory` parser and printer in `factory_cli.rs`. | +| `hide-kit` | `hide_kit::layout::{factory_store, factory_files}` name the store and its files folder. | +| `hide-agent-hooks` | The session guidance sentence that sends agents to `hide factory add`. | + +A command travels as one scoped request. +`hide factory ...` sends a `factory` request over the pane-capability socket, which needs no open renderer and refuses a caller from a connected device with `factory_local_only`. +The request is at most 256 KiB and is answered within 100 seconds. +The core checks the caller as delivery does, so a moved checkout returns `caller_context_changed`, and queues the command for the engine thread. +The queue holds 32 commands; a full queue answers `factory_busy` and a missed answer window answers `factory_timeout`. +The engine decides the caller's role, runs the command, saves the change, and answers. +A worker's `ask`, `block`, `propose` and `done` take the letter path described under [The mailbox recipient](#the-mailbox-recipient-factoryid). + +## The store + +The source of truth for every Factory on the machine is one SQLite file, `factory.sqlite3`, in the state folder, with a private folder `factory-files/` beside it. +The file runs in WAL mode with `synchronous=NORMAL`, foreign keys on and a two-second busy timeout. +Both are private to the user: the file is mode 0600 and the folder 0700 on Unix. + +| Table | Holds | +| --- | --- | +| `factories` | One JSON record per Factory, with its project, closed flag and creation time. | +| `tasks` | One JSON record per Task, with indexed state, issue, priority and times. The record carries the card, questions, discoveries, decisions, attempts, worker, pull request and gates. | +| `dependencies` | One row per dependency edge, rewritten with its Task. | +| `events` | Ids-and-stage records of transitions, external calls and failures, never card text or secrets. | +| `meta` | The machine-wide worker limit and the ids of the last 4,096 applied letters. | + +`PRAGMA user_version` carries the schema version, now 1. +A store written by a newer build is refused rather than read: the engine does not start, the host logs `store.open_failed`, and commands answer `factory_unavailable`. +Fields added later load from older rows through serde defaults. +The engine loads the whole store at start and saves each change before the command that made it answers, so a restart resumes Factories, Tasks, questions, workers and in-flight work. +A restart starts verification again from the recorded attempt and asks a pending review again. +The engine opens the store when a store file already exists at start, or on the first command, so a machine that never created a Factory opens nothing. + +`factory-files///` holds each attached PRD as `.`, a read-only copy of at most 4 MiB, and `factory-files/logs/` holds one `.log` per local verification run. +A run's log keeps only its last 1 MiB when the run ends. + +The Factory deletes no Task, question, decision, discovery, attempt or attachment. +It removes a worker's worktree and pane when the Task is done and main verification has passed, when a cancelled Task passes its keep period, and, only under disk pressure, for finished Tasks. +The worktree removal leaves the Task's branch in place, and the Factory never deletes a remote branch. +A finished Task folds out of the board's Done column after 3 days and out of every list after 90 days; its page still opens. +Each Factory keeps its newest 20,000 events and drops older ones. +Judgment inputs and answers are not stored; the questions and flags they produce are, and the core's diagnostic log records each judgment's feature, ids, outcome and duration. + +## Tasks, states and the DAG + +A Task is the Factory's unit of execution. +It has a Factory-local id `T-` that is never reused, and, once it is Ready, an issue: `#` on GitHub or `L-` locally. +A Task is shown by its issue number when it has one and by its Task id before. +A command names a Task by Task id, issue, or `/`; a reference that matches Tasks of two Factories answers `task_ambiguous`. + +The card has a title (one line, at most 200 characters), a goal, at least one completion criterion, out-of-scope items, open decisions, dependencies (`--after`) and external waits (`--external`). +A person sets four more fields on it: direct review, priority (-100 to 100), merge mode and runtime, and an empty field takes the Factory's default. +Text fields are capped at 4,000 characters, lists at 30 items, and a Factory at 5,000 Tasks. +A card that misses a field, has no criterion, names a dependency that does not exist or is cancelled, or closes a loop is refused at once with a `card_invalid` answer that lists each field and problem. +The producer writes the card; the review may add questions, dependencies and flags and never edits the card. + +### States + +| State | Label | Meaning | Slot | Board column | +| --- | --- | --- | --- | --- | +| `drafting` | 정리 중 | Open questions remain or the review has not answered. | no | drafting | +| `waiting` | 대기 | Ready; waits for predecessors, a slot or the environment. | no | waiting | +| `running` | 실행 중 | A worker holds a slot. | yes | running | +| `paused` | 일시정지 | A person paused it; the worker sleeps. | no | running | +| `blocked` | 막힘 | Waits for an answer or a predecessor; the worker sleeps. | no | running | +| `verifying` | 검증 중 | The worker reported done; checks, verification and the pre-merge steps run. | no | running | +| `merge_waiting` | 머지 대기 | A person merges, requests changes or cancels. | no | running | +| `landed` | 머지됨 | Merged; main verification has not answered yet. | no | running | +| `done` | 완료 | Main verification passed or none exists, or an outside pull request merged. | no | done | +| `stopped` | 멈춤 | The worker went quiet, a start was refused, or a limit was reached. | no | running | +| `relanding` | 다시 올리기 | The merge was reverted; the Task runs again on the latest main. | yes | running | +| `outside` | 밖에서 진행 중 | An outside pull request closes its issue. | no | running | +| `cancelled` | 취소 | Kept for the keep period, then purged. | no | off the board | + +The main line is `drafting`, `waiting`, `running`, `verifying`, `merge_waiting` when a person merges, `landed`, `done`. +`blocked`, `paused` and `stopped` branch off `running`, and `relanding` returns to `verifying` through the worker. +A Task stops with one of these reasons: no report, stalled, verification failed three times, new-Task cap, the same environment failure repeated, or a refused worker start. + +A person's actions depend on the state, and any other action is refused with `action_not_allowed_in_state`, the current state and the allowed list. +An open question adds `answer` to any state's list. + +| State | Actions | +| --- | --- | +| `drafting` | `edit` (add again), `cancel` | +| `waiting` | `priority`, `dep-remove`, `cancel` | +| `running` | `pause`, `cancel` | +| `paused` | `resume`, `cancel` | +| `blocked` | `answer` only | +| `verifying` | `cancel` | +| `merge_waiting` | `merge`, `request-changes`, `cancel` | +| `stopped` | `retry`, `cancel` | +| `outside`, and `cancelled` inside its keep period | `revive` | +| `landed`, `done`, `relanding`, and `cancelled` after the keep period | none | + +### When a Task may start + +A `waiting` or `relanding` Task starts when all of these hold. +Its Factory is open. +Every Task in its `depends_on` is `landed` or `done`: a predecessor must be merged, and a missing one counts as unmerged. +The environment holds no start (see [Environment](#environment)). +A slot is free. +External waits are shown on the Task and never decide a start. +A Task that waits holds back only the Tasks below it in the chain; every other Task keeps running. + +Slots are counted per machine, across every Factory. +The machine-wide limit is `max_workers`, 5 by default and between 1 and 64, and it counts Tasks in `running` or `relanding` plus workers still starting. +Free slots go first to `relanding` Tasks, which already hold theirs, then by priority from high to low, then by the older creation time, then by Task number. +A priority change or a removed dependency applies at the next tick. +A person's dependency removal is the only way to loosen an order, and a worker may only add a dependency to its own Task. +Adding a dependency to a running Task whose predecessor is unmerged puts the Task to sleep as `blocked`; it waits for a slot again when the predecessor merges. + +## Roles + +Each command runs with a role the engine decides from its own store, never from the caller's claim or a file. +A caller is a worker when its pane is the pane of a live Task's worker, or when its working folder is inside a live Task's worktree; a `cancelled` or `done` Task has no worker. +Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. +The engine itself acts as a third role for deadlines and timers and is never a command caller. +A capability file holds only a token, so editing it cannot change a role. + +| Permission | Commands | Worker | Operator | +| --- | --- | --- | --- | +| Read | `status`, `show`, `inbox`, `config` without `--set` | yes | yes | +| Report | `ask`, `block`, `propose`, `done`, `decide` | its own Task | refused | +| Add a dependency | `dep add` | its own Task | yes | +| Intake | `init`, `add`, `check` | refused | yes | +| Answer | `answer` | refused | yes | +| Loosen | `dep remove`, `priority` | refused | yes | +| Merge | `merge`, `request-changes` | refused | yes | +| Control | `pause`, `resume`, `retry`, `cancel`, `revive`, `close` | refused | yes | +| Configure | `config --set` | refused | yes | + +A refusal answers `role_not_allowed` with the role and the verb. +A worker's `show` reaches its own Factory only. +An operator relays a person's words, and every answer and decision records the relaying pane as `relayed_by`. +Code cannot tell whether an operator pane's agent acted on a person's words, so it records who relayed and does not block. + +## The mailbox recipient `factory:` + +Each open Factory is a code-owned recipient named `factory:` in the delivery ledger. +[delivery.md](delivery.md#the-code-owned-recipient-factoryid) owns the ledger rules; this is how the Factory uses them. + +- Only the engine sends as the Factory. The host holds that authority, and the ledger accepts it only while the Factory exists and is open. +- A pane may send to `factory:` and may name it as a watch observer, and it can address the Factory by that name only. A pane or agent can never register under a name or pane that starts with `factory:`. +- The engine reads its letters from the ledger on each tick, up to 16 at a time, applies each once, and confirms it. A request or block letter also gets a reply carrying the engine's JSON answer. No composer input or doorbell is involved. +- The letter's sender must be a live worker of that Factory, or the letter is refused with `sender_not_a_worker` and logged. +- A worker's CLI report is a typed body `{"factory": }` sent under an intent made from the pane and the body, so a retry applies once. A harness that follows the letter protocol only is read as a question (a `request` or `block` letter becomes a blocking question with a 24 hour deadline, taking a `Recommendation:`, `Suggestion:`, `추천:` or `제안:` line as the suggestion) or as a completion (a `report` letter becomes `done`). +- A watch whose observer is the Factory warns after 30 quiet minutes instead of 20. The engine turns the first warning into a stalled stop; it does not wait for the second warning or for the human notice, which the ledger skips for a code-owned recipient. +- The Factory writes to a worker with `report` letters, and starts a watch on the worker again each time it does, because a report to its parent ends the sender's watch. + +## The worker lifecycle + +A worker starts when the Task may start. +The engine asks the core to spawn it through coordination, the same path as `hide agent spawn`, under the Factory's own agent record as parent. +The record is registered when needed and converges on the existing one. + +- **Name, branch, intent.** The worker is named `factory--` and works on `factory/-` (`factory/l-` for a local issue, `factory/` without a slug). The spawn intent is `factory--`, and each earlier refused start adds `-a`, so a refused start never repeats a spawn that already failed and a retry of the same attempt converges. +- **Runtime.** The Task's runtime, else the Factory's `default_runtime`. The arguments in `worker_args` for that runtime go to the agent before the prompt. +- **First prompt.** One argument, at most 6 KiB, cut at a character boundary with a pointer to `hide factory show ` for the rest. It holds the Task, goal, criteria, out-of-scope items, the read-only absolute path of each attachment, the harness instruction when one is set, and the reporting rules: commit on the branch, never push or merge to the default branch, finish with `hide factory done`, ask with a default or block, report discoveries, and a turn that ends without a report stops the Task. The prompt text is written in Korean. When a `hide` program sits beside the daemon, the prompt names its absolute path and says every `hide` in the rules means that program, so a worker never reaches an older copy on its `PATH`. +- **Lineage and watch.** The spawn writes lineage and starts a watch whose observer is the Factory. + +A worker whose pane exists but whose agent has not shown a session yet is still starting. +It holds its slot, the Task stays `waiting`, and the same spawn is asked again every 30 seconds. +After 10 minutes a notice asks the person to look at the pane, where a trust or login prompt may be waiting. +A Codex worker waits for this Mac's install kit to have read the machine since launch: the first start asks the kit to read and reports the worker as still starting. + +A start the runtime refuses, other than for an environment signal, stops the Task with the reason "worker start failed" and the runtime's reason (cut at 300 characters) beside it. +A person fixes the cause and retries; the next attempt uses a new spawn intent. +A start that fails with an environment signal leaves the Task `waiting` and is handled by the environment rules. + +A Task's worker is put to sleep when the Task blocks, pauses, goes to `verifying`, or waits for a slot, and woken when it runs again. +Sleep goes through agent sleep and is deferred until the agent's turn ends; a worker that never slept is sent the message instead. +A wake restarts the agent in the same pane and session. +Letters for a woken worker are held, at most 16, until its agent is back, and are dropped to the diagnostic log after 10 minutes. +A retried Task, or a worker whose pane is gone, spawns again in the same worktree and session with a fresh intent. +A worker that is `gone` is detected from its pane, with a three-minute grace after its start. + +A worker reports through `hide factory` and gets its answer in the same call. +`ask` needs a suggestion, a default action and a deadline of 1 to 720 hours, and the worker continues with the default; `block` has no default, so the Task blocks, releases its slot and sleeps. +`done` opens a pull request on a GitHub Factory when none exists, goes to `verifying`, and puts the worker to sleep. +`decide` records a decision. +A worker whose agent rests for the no-report window of 2 minutes after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for 30 minutes stops it as "stalled". + +## Intake review and judgments + +`hide factory add` checks the card's shape first, in milliseconds, then asks for an independent review. +The review sees only the card, its attachment, the repository's file names and guide, and the Factory's other Tasks, never the producer's conversation. +`add` waits up to 90 seconds and answers one of: + +- `ready`: no question is open, so the Task is Ready. +- `needs_answers`: the questions to answer, each with a suggestion. +- `split`: the review proposes two or more pieces, each with a goal, criteria and the earlier pieces it follows. +- `pending`: the review has not finished, or could not run; the result goes later to the pane that added the Task when that pane still exists. + +Adding again with `--task ` or the same issue updates the same Task and reviews it again; the same content changes nothing. +A re-add on a Task that already runs does not rewrite its card: it adds a scope-change question that a person approves or rejects. +The producer's open decisions become intake questions, and a Task is Ready only when the review is done and no question besides a notice is open. +Ready creates the issue: a GitHub Task gets an issue labelled `factory` whose body carries a hidden Task marker, the goal, the criteria and the out-of-scope items, and a local Task gets an `L-`. +A Task added from an existing issue gets the label instead. +The marker lets a retry find the issue it already created. +A split that a person accepts turns the original Task into the first piece, keeping its issue, and drafts the rest as new Tasks that depend on the pieces they follow; choosing to proceed clears the split and the Task becomes Ready when nothing else is open. +A Task is never split or made Ready by silence. + +Every judgment is a tool-less, one-shot call whose input the code bundles and cuts to 48 KiB, whose answer must match a `factory.v1` schema, and whose deadline is 180 seconds. + +| Feature id | Asked | Input | The answer may | +| --- | --- | --- | --- | +| `factory_intake_review` | On add and re-add, an edited issue body, a label-path card, a split piece, an approved proposal | The card, its attachment (24 KiB), up to 100 other Tasks, up to 400 file names, the repository guide (8 KiB) | Add questions, dependencies on listed Tasks, a split, and flags | +| `factory_drift` | After `done` | The card, the diff against main (24 KiB), the decisions | Pass, or add questions, and flags | +| `factory_check` | At intake or after `done` for each natural-language check | The instruction, the card, the diff | The same as drift | +| `factory_watch` | See [The watch](#the-watch) | The Factory's board summary | Warnings, each with an optional action | +| `factory_env_diagnosis` | See [Environment](#environment) | The collected facts and the closed action list | One action from the list, or an exact command with its impact | + +Questions that a drift or check judgment adds always carry a default action, taking the suggestion when the answer has none, so a check can only slow a Task down. +A drift question keeps the Task in `verifying`, does not wake the worker, and holds auto merge until it is answered or its deadline passes; an answer that differs from the default wakes the worker to apply it. +A judgment that cannot run is never skipped and never read as a pass. +A failed review marks the Task and puts a retry-or-cancel question in the inbox, and `add` answers `pending`. +A failed drift or check sends the Task to `merge_waiting` for a person. +A failed watch or diagnosis changes no Task and is logged. + +The Factory has its own judgment queue on its own router (see [AI_PROVIDERS.md](AI_PROVIDERS.md#the-factorys-judgments)): one request in flight, intake reviews before every other judgment, and 16 waiting judgments per Factory. +A judgment submitted to a full queue fails like a provider failure and is escalated the way above. +Natural-language checks are added with `hide factory check --at intake|after-done|periodic`. +A `periodic` check is stored with the others, and no timer runs it yet. + +## Verification + +A Factory chooses one verification, or none. +`ci` reads the required check runs of the Task's pull request and runs nothing itself. +`verify` runs a bundle of shell commands in the Task's worktree, all of which must exit 0. +With none, auto merge is unavailable, and a Task goes from `done` straight to `merge_waiting`. + +The Factory never reruns a verification: one failure is a failure, and the worker fixes and reports `done` again. +`n/3` counts those failures per Task, the limit is 3, and the third failure stops the Task as "verification failed three times" with the failing check and the worker's last summary. +A failure wakes the worker with the check name, the log path or CI link, and the count. +Environment failures and merge conflicts do not count. +`retry` resets the count. + +**CI.** The check runs of the worktree's head commit are read on each tick with `gh api`. +With a list of names, every name must have a completed run; without one, every check run on the commit is read, and a commit with no check run yet reads as passed, so name the required checks in `--ci`. +A completed run passes on `success` or `neutral`, decides nothing on `skipped`, `cancelled` or `stale` (still pending), and fails on any other conclusion with the run's link. +A GitHub error that carries an environment signal is the environment's; any other read error stays pending. + +**Verify bundle.** Bundles run one at a time on the machine, in a queue of at most 256, each command through the shell with its output in the run's log. +The cap, `verify_timeout_minutes` (60 by default), applies to each command, and a command past it fails the run. +A command that exits 137, prints "no space left on device" in its last 64 KiB, or dies with no exit code after printing "killed" is an environment failure; every other non-zero exit is the Task's. +Each run belongs to the engine, which ends its whole process tree when the Task is cancelled or the core stops. + +**Before a merge.** When the verification passed and no question holds the Task, the Factory checks the merge in seconds, for a verify or local Factory, and never reruns CI. +`git merge-tree` against the current default branch names conflicting files; a conflict sends the worker back to `running` with a rebase message and does not count as a failure. +An optional `quick_check` command then runs on the Task worktree; its failure counts as a verification failure. +Paths matching `risk_paths` add a gate. +A verify Factory then runs its bundle once more on the Task with the latest default branch merged in, and a failure there counts as a verification failure. + +## Merge + +A Task's merge mode is its own field, else the Factory's. +In `auto` mode a verified Task that meets no gate is merged by the Factory. +In `manual` mode it goes to `merge_waiting` and a person merges. +Merge mode is always `manual` for a Factory with no verification. + +A gate sends an `auto` Task to `merge_waiting` and appears in the Task page and inbox. + +| Gate | Set when | +| --- | --- | +| `review_directly` | The card asked for direct review. | +| `approved_scope_change` | A person approved a scope change on the Task. | +| `breaking_change` | The worker reported `--breaking`, or a check flagged a breaking or public-contract change. | +| `no_verification` | The Factory has no verification. | +| `risk_path` | A changed path matches `risk_paths` (empty by default). | +| `manual_mode` | The Task's mode is `manual`. | +| `open_question` | A question other than a default, scope-change or notice question is open. | +| `check_failed` | A judgment could not run. | +| `autonomy_diff` | An autonomy Task changed more than 200 lines. | +| `dirty_main` | A local merge finds the main checkout uncommitted or off the default branch. | + +A review by an agent alone never merges. +A person's `merge` runs the same merge at once; `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. + +**GitHub.** The merge is `gh pr merge` with the Factory's `merge_method` and `--match-head-commit` set to the pull request's head as read just before the merge, and a pull request already merged returns its merge commit. +`init` picks the first merge method the repository allows, in the order squash, merge, rebase, and `config` changes it. +**Local.** The Factory merges into the project's primary checkout with `git merge --no-ff`, only while that checkout is on the default branch with no uncommitted tracked changes. +Otherwise the Task stays in `merge_waiting` with `dirty_main` until it is clean. + +A merge records its commit, and the Task becomes `landed`. +Main verification is the chosen verification on that commit: the push run's check runs for `ci`, or the bundle run in `.worktrees/factory-main`, a detached worktree the Factory creates beside the project's worktrees, for `verify`. +A green result, or no main verification, makes the Task `done` and removes its worker, pane and worktree. + +A red result breaks main and stops auto merge; manual merges still run. +If the broken commit is among the Factory's own merges since the last green, the Factory finds the first failing one, asking again for runs that were skipped or cancelled, and reverts that merge alone. +On GitHub the revert is a pull request from `factory/revert-`, which the Factory force-pushes, checks and merges with `--merge`; locally it is a revert commit made in `factory-main` and fast-forwarded into the primary checkout. +A revert whose verification passes is merged on its own, and the original Task becomes `relanding`: it runs again in the same worktree and session on the latest main, with a new pull request. +When the failing commit is not the Factory's, nothing is reverted: the Factory drafts a fix Task for a person to confirm and stops auto merge. +Auto merge resumes when the head of main verifies green again. +A recovery that cannot name one merge, cannot make or merge the revert, or finds the revert red does not repeat itself: it stays stopped and puts the failed run's link, the candidate merges and these choices in the inbox: retry the revert, revert a named merge, or resume auto merge after a person fixed main. + +## Outside work + +The person wins outside the Factory, and the Factory follows. +Each open Factory reads GitHub every `outside_read_minutes` (2 by default): up to 200 issues labelled `factory` and 100 pull requests, or, locally, its local issues. +A failed read backs off 1, 2, 5, 15 and then 30 minutes on a rate-limit, server or network signal; three failures in a row mark the Factory's read stale. + +| What the Factory sees | What it does | +| --- | --- | +| A pull request the Factory did not open closes a Task's issue, and it is open | The Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | +| That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. | +| The issue closes with no pull request, or the `factory` label is removed | The Task is cancelled with a notice, kept for the keep period. | +| A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | +| A person labels an issue the Factory does not hold | A new Task is drafted from the issue, and a person confirms its card in the inbox before it is Ready. The body is not edited. | +| A finished Task's issue reopens | A notice only. | +| A push to main the Factory did not make | Main verification runs, and a red result takes the outside-push path above. | + +A pull request or issue the Factory does not hold is ignored. +Cancelling a Task closes its open Factory pull request, and reviving reopens it. + +## Questions, discoveries and autonomy + +A question belongs to a Task card and is answered with `hide factory answer [--question ] --choose suggestion|default|` or `--text`. +Every question has a suggestion, and a worker question has a deadline and may have a default action. +Its kind decides what an answer does. + +| Kind | Raised by | An answer | +| --- | --- | --- | +| `intake` | The review, a check, a producer's open decision | Clears it; the Task is Ready when nothing else is open. | +| `split` | The review | `split` splits the Task, `proceed` clears it. | +| `default` | A worker `ask`, a drift or check finding | The default keeps going; a different answer wakes the worker. After the deadline the default is the answer. | +| `blocking` | A worker `block` | Wakes the worker through a reply; the Task waits for a slot and resumes its session. No deadline decides it. | +| `scope_change` | A worker, a re-add, an edited issue | `approve` records approval and adds a gate; `reject` keeps the scope. After the deadline it is rejected. | +| `new_task_cap` | The Task reached the new-Task limit | `continue` lets it create more; any other choice leaves it stopped with a notice. | +| `proposed_task` | A prerequisite proposal outside autonomy | `approve` drafts the Task. | +| `action` | A stop, a failed review, a main break | The listed choice runs: `retry`, `retry-review`, `cancel`, `resume-auto`, `retry-revert`, `revert `. | +| `confirm_card` | A label-path card, a fix-Task draft | `confirm` lets the Task become Ready. | +| `proposal` | An environment diagnosis | Records the answer; a person runs the command. | +| `notice` | Anything a person should only see | `ok` removes it; answering it on a finished Task also clears its unread mark. | + +A question with a default lets the worker continue, and the Task waits only at the end of verification for the answer or the deadline. +A blocking question releases the slot and stays open however long it waits; the inbox shows how many days. +A worker may report five classes of discovery with `hide factory propose --class`: + +| Class | Effect | +| --- | --- | +| `in-scope` | A recorded fix inside the card. | +| `decision` | A recorded decision the agent made, reversible and inside the criteria. | +| `scope-change` | A scope-change question; the worker continues inside the current scope. | +| `prerequisite` | A new Task proposal. | +| `unrelated` | A notice in the inbox. | + +`--reclassify ` may only move a discovery toward a person, in the order `in-scope`, `decision`, `prerequisite`, `scope-change` and `unrelated` (the last two being equal); the reverse answers `reclassify_away_from_person`. +A prerequisite needs a card. +A Task that was itself proposed or started by autonomy may not propose a Task (`proposal_depth_exceeded`), and each Task may propose `new_task_limit` Tasks (3 by default) before it stops with the "new-Task cap" question. +A proposal that names an enabled `--autonomy` scope drafts the Task now and makes the proposer depend on it and sleep as `blocked`; any other proposal is a question that a person approves before the Task is drafted, and approving it does not make the proposer wait. + +Autonomy scopes are the kinds of Task a worker may start without a person. +The presets are `flaky_test`, `dependency_patch`, `lint_format` and `docs_links`, all off, and a person may add scopes by name. +An autonomy Task is reviewed like any other, may not propose Tasks, and gates to a person when it changes more than 200 lines. + +## Environment + +An environment problem is not a Task's failure and is never counted against it. + +- **Before a start.** Starts hold while free disk at the first waiting Task's project is under `disk_floor_gb` (20 by default), or while macOS reports critical memory pressure. Warn pressure starts normally, and other systems report normal. The held Tasks show the reason and are checked again after a minute. +- **At a failure.** Only a structured signal makes a failure the environment's: no space left on the device, exit 137, a GitHub 401, 403, 429 or 5xx answer, a network error, or a Herdr connection error. The adapters read the GitHub and git signals from the command's exit code and its stderr text. Everything else is the Task's. A usage-limit signal parks a runtime until its reset time, one hour by default, and moves an unpinned Task to the other runtime, and the host adapters do not report one yet. +- **Code handles each signal first.** Disk full holds starts and removes the worktrees of finished Tasks and cancelled Tasks past their keep period. Out-of-memory and Herdr connection errors send the Task back to `waiting`. A rate-limit, server or network error backs the read off as above. A 401 or 403 puts a notice in the inbox once, naming `gh auth login` or `gh auth refresh -s `, and the Factory does not perform that action or retry it. +- **Cascade.** Three different Tasks failing the same check or command within 30 minutes are read as the environment: each failure is taken back, the Tasks go to `waiting`, and new starts halt for 30 minutes. +- **If it does not clear.** A problem that outlasts 30 minutes asks `factory_env_diagnosis` once for a cause and either one action from the closed list or an exact command with its impact. + +The closed recovery list is the only set of actions the Factory runs without a person, and `recovery.=on` turns each on; all are off. + +| Action | Does | +| --- | --- | +| `remove_finished_worktrees` | Removes the worktree of a finished Task and of a cancelled Task past its keep period. | +| `restart_worker` | Starts a worker again in the same worktree and session. | +| `sleep_wake_worker` | Puts a worker to sleep or wakes it. | +| `switch_runtime` | Moves an unpinned Task to the other runtime. | +| `retry_reads_and_reconnect` | Clears read back-offs and the start hold. | + +A diagnosis naming an action that is off, or any other command, becomes a proposal in the inbox with the exact command and impact, and a person runs or dismisses it. +Logging in, deleting outside the Factory and installing tools are only ever proposals. +A Task that alone repeats an environment failure three times is the Task's: it stops as "same environment failure repeated". + +## The watch + +The watch reads a Factory's board for what a person cannot already see in the inbox, such as work that stopped moving, a chain held by one wait, or a pattern of failures. +It runs when a Task finishes, when main breaks, and every `watch_interval_minutes` (30 by default, at least 5) for a Factory that has Tasks. +It asks `factory_watch` with the Factory's board summary. +A warning without a proposed action goes to the diagnostic log only. +A warning with an action becomes a notice on the Task it names, or on the Factory's last Task, and counts against `watch_daily_limit` (5) per Factory per UTC day; a warning past the limit is logged as capped. +A warning about a Task that already waits on a person is logged and not raised. +A watch that is slow or fails changes no Task. + +## Configuration + +`hide factory config [--project ]` prints the Factory's settings and the machine's worker limit, and `--set =` changes them for the next decision. +Only an operator may set values, and an invalid key or value answers `config_invalid`. +A Factory's `merge_mode` cannot be `auto` while it has no verification (`auto_needs_verification`). + +| Key | Value | Default | +| --- | --- | --- | +| `merge_mode` | `auto` or `manual` | `manual` until `init` chose a verification, then `auto` | +| `merge_method` | `merge`, `squash` or `rebase` | The first the repository allows (squash, merge, rebase) | +| `verify` | Commands joined by `&&&`; empty clears | none | +| `ci` | Comma-separated check names | none | +| `no_verification` | Any value | none | +| `quick_check` | A shell command; empty clears | none | +| `max_workers` | 1 to 64, machine-wide | 5 | +| `question_deadline_hours` | Hours | 24 | +| `stall_minutes` | Minutes | 30 (stored; the quiet window is the watch's fixed 30 minutes) | +| `watch_interval_minutes` | Minutes, at least 5 | 30 | +| `watch_daily_limit` | Count | 5 | +| `outside_read_minutes` | Minutes, at least 1 | 2 | +| `cancel_keep_days` | Days | 7 | +| `done_fold_days` | Days | 3 | +| `new_task_limit` | Count | 3 | +| `verify_timeout_minutes` | Minutes per command, at least 1 | 60 | +| `disk_floor_gb` | Gigabytes | 20 | +| `default_runtime` | `claude` or `codex` | `claude` | +| `harness` | `:`; empty clears | none | +| `autonomy` | `=on` or `off` | all off | +| `recovery` | `=on` or `off` | all off | +| `worker_args` | `=`, split on spaces; empty clears | none | +| `risk_paths` | Comma-separated: `dir/**`, `*.ext`, or an exact path or folder | none | +| `prd_in_issue` | `on` or `off` | off | +| `macos_notifications` | `on` or `off` | off | + +`max_workers` is the machine's, not the Factory's, and any Factory's `config` sets the same value. +`worker_args` holds the whole argument list for one runtime, such as a permission mode the operator chose, and an empty list removes it. +`harness` places the named instruction in each worker's first prompt; gates never trust a harness's own claims, and a harness's own checks belong in `verify`. +The 2-minute no-report window, the 90-day fold, the 3-failure limit and the 200-line autonomy limit are fixed in the Factory's configuration record and have no key. + +## The `hide factory` command + +``` +hide factory init [--ci [...]] [--verify ]... [--no-verification] [--merge auto|manual] [--confirm] +hide factory add [--task |] --title --goal --criterion ... [--out-of-scope ]... [--open ]... [--after ]... [--external ]... [--prd ] [--review-directly] [--priority ] [--merge auto|manual] [--runtime claude|codex] [--project ] +hide factory status [--project ] +hide factory show +hide factory inbox +hide factory answer [--question ] [--choose suggestion|default|] [--text ] +hide factory ask --question --suggestion --default [--deadline-hours ] +hide factory block --question --suggestion [--deadline-hours ] +hide factory propose --class in-scope|decision|scope-change|prerequisite|unrelated --text [--title --goal --criterion ...] [--autonomy ] [--reclassify ] +hide factory done [--summary ] [--breaking] +hide factory decide --text +hide factory config [--project ] [--set =]... +hide factory priority +hide factory dep add|remove --on +hide factory pause|resume|retry|merge|cancel|revive +hide factory request-changes --comment +hide factory check --at intake|after-done|periodic --instruction [--project ] +hide factory close [--project ] +Add --json to print the answer as JSON. +``` + +| Command | Does | +| --- | --- | +| `init` | Without `--confirm`, shows the source, the verification candidates the code detected (the branch's required checks and verify commands read from `Cargo.toml`, `package.json`, `Makefile` or `pyproject.toml`), the merge mode and the GitHub writes it would make, and writes nothing. With `--confirm` and a verification choice, creates the Factory and, on GitHub, creates the `factory` label. A closed Factory is reopened with `--confirm`. A project that already has an open Factory answers with it. | +| `add` | Creates a Task or updates the named one. A positional issue reads its title and body for missing fields. `--prd` copies the file into the store. | +| `status`, `show`, `inbox` | Read the board, one Task page, and the inbox. | +| `answer` | Answers a question and records who relayed it. | +| `ask`, `block`, `propose`, `done`, `decide` | A worker's reports on its own Task. | +| `config`, `check` | Reads and sets settings, and adds a natural-language check. A check cannot be removed once added. | +| `priority`, `dep`, `pause`, `resume`, `retry`, `merge`, `request-changes`, `cancel`, `revive`, `close` | A person's actions. `close` needs no Task in the board's running column. | + +Without `--project`, `add`, `config`, `check` and `close` use the only open Factory, and answer `factory_ambiguous` when there are several. +A project path is made absolute by the CLI. +`--json` prints the engine's answer as one JSON object, and without it the answer is printed for a person. +Every answer carries `ok`. +A refusal prints `refused: `, the current state and allowed actions or the invalid fields when it has them, and `next: `, and exits non-zero; its JSON is `{"ok": false, "reason", "next_action", "detail"}`. +`add` answers `{result, task, questions}`, `init` a preview, `created` or `existing` object, `show` `{task: }`, `inbox` `{count, items}`, `status` a `FactorySummary`, and `config` `{config, machine}`. +Other actions answer `{message, task}` with the Task's id, display id and new state. +Common refusal reasons are `role_not_allowed`, `task_not_found`, `task_ambiguous`, `factory_not_found`, `factory_ambiguous`, `factory_closed`, `card_invalid`, `action_not_allowed_in_state`, `config_invalid`, `auto_needs_verification`, `github_login_required`, `github_permission_missing`, `main_dirty` and `revive_expired`. + +## The read model + +`FactorySummary` and `TaskDetail` are the contract for any screen of the Factory, and `status`, `inbox` and `show --json` print them as they are. +Every number in them is derived in `hide-factory/src/summary.rs` from the stored Tasks, and a screen computes nothing. +Fields are added and never renamed or removed. + +**`FactorySummary`** + +| Field | Meaning | +| --- | --- | +| `my_turn` | The one person-facing number: the open inbox items across all Factories. | +| `factories` | One `FactoryView` per Factory. | +| `inbox` | Every `InboxItem`, in the inbox order below. | + +**`FactoryView`** + +| Field | Meaning | +| --- | --- | +| `id`, `project`, `project_name` | The Factory's id, canonical path and short name. | +| `source` | `github` or `local`. | +| `verification` | `ci`, `verify` or `none`. | +| `closed` | Whether the Factory is closed. | +| `flow` | `drafting`, `waiting`, `running` and `done_today` counts. | +| `my_turn` | This Factory's inbox items. | +| `columns` | The four board columns, each with its Task cards in order. | +| `cancelled` | Cancelled Tasks, off the board. | +| `graph` | Nodes, reduced edges and unrelated Tasks. | +| `dependencies` | Every edge as (predecessor, Task); the graph's edges are a reduction of these. | +| `outside_read_at` | When outside work was last read. | +| `stale` | Three outside reads failed in a row. | +| `main_broken` | Auto merge is stopped by a broken main. | +| `auto_merge_available` | The Factory has a verification. | +| `merge_mode` | `auto` or `manual`, `manual` when there is no verification. | + +**`CardView`** + +| Field | Meaning | +| --- | --- | +| `task`, `display_id` | The Task id, and the issue number once Ready. | +| `column` | `drafting`, `waiting`, `running`, `done` or none. | +| `title` | The card title. | +| `state`, `state_label` | The state id and its label, with the stop reason for a stopped Task. | +| `needs_person` | The Task is blocked, stopped, `merge_waiting`, or has an open question that is not a notice. | +| `waiting_for` | For a waiting Task, the predecessors by display id, the environment hold, or `slot`; for a blocked one, `answer` or `predecessor`. | +| `priority` | The Task's priority. | +| `since` | When it entered its state. | +| `unread` | A completion nobody has looked at. | +| `folded` | A completion older than 3 days, or a purged cancelled Task. | +| `archived` | A finished Task older than 90 days. | +| `failures` | Verification failures counted against it. | +| `external` | External waits. | +| `revive_until` | When a cancelled Task can no longer be revived. | +| `worker_pane` | The worker's pane while the Task is not finished. | + +**`InboxItem`** + +| Field | Meaning | +| --- | --- | +| `group` | `answer`, `merge`, `stopped` or `notice`. | +| `kind` | The question kind, `merge` or `stopped`. | +| `rank` | The order key: 0 blocking question, 1 other answers, 2 merge, 3 stopped and action or proposal questions, 4 notices. | +| `factory`, `task`, `display_id`, `title`, `project` | Where it belongs. | +| `question` | The question id, when the item is a question. | +| `text` | Why it is the person's turn. | +| `suggestion` | The preselected answer. | +| `result` | What sending the preselected answer does. | +| `default_action` | What the worker does meanwhile. | +| `choices` | The listed answers. | +| `deadline`, `remaining` | The deadline, and a short phrase for it or for how many days a blocking question has waited. | +| `waiting_since`, `waiting_days` | When it started waiting, and whole days for a blocking question. | + +The inbox lists each open question, each `merge_waiting` Task, and each stopped Task that has no action question, in order of rank and, within a rank, the item waiting longest first. +That puts blocking questions first, then other answers, merge waits, stops and notices, so what has waited the longest to be unblocked is at the top. +A cancelled Task inside its keep period still lists its open questions. + +A Task's board column comes from its state: `drafting`, `waiting` and `done` have their own, every other state except `cancelled` is in `running`, and `cancelled` is off the board. +Inside a column the cards a person must look at (blocked, stopped, merge waiting, or holding an open question) come first, oldest first, then the rest by priority and age. +`flow` counts a Task in `done` only on the day it finished. + +**`TaskDetail`** + +| Field | Meaning | +| --- | --- | +| `card` | The Task's `CardView`. | +| `factory`, `project` | The Factory's id and path. | +| `goal`, `criteria`, `out_of_scope` | The card text. | +| `before`, `after` | The chain: predecessors, and the Tasks that wait on this one. | +| `attachments` | Each PRD copy with its path, hash, version and original path. | +| `pr` | The pull request: number, URL, head, whether the Factory opened it, whether it is open. | +| `verification` | `n/3`, or "검증 없음" without verification. | +| `attempts` | A list of `AttemptView`. | +| `decisions` | The decision records with who made them. | +| `questions` | Every question with its answer and who relayed it. | +| `discoveries` | The discoveries with their class. | +| `gates` | The reasons a merge waits for a person. | +| `allowed` | The actions the state allows. | +| `stop` | The stop reason's label. | +| `merge_sha` | The merge commit. | +| `worker_name`, `worktree`, `branch` | The worker's name, folder and branch. | + +**`AttemptView`** + +| Field | Meaning | +| --- | --- | +| `number` | The attempt, one more than the Task's failures when it started. | +| `stage` | `task` (after `done`) or `pre_merge`. | +| `started_at` | When it started. | +| `outcome` | `passed`, `failed`, `environment` or `running`. | +| `check` | The failing check or command. | +| `link` | The CI link or the log path. | +| `log_tail` | The last 4 KiB of a local log. | + +## Performance boundaries + +The engine runs on its own thread, `herdr-core-factory`, and the judgments run on a second, `herdr-core-factory-judge`. +Dropping the core stops the engine first, then ends the verify runs, the judgment in flight and any `git` or `gh` call under way, so nothing the Factory started outlives the daemon. +The engine takes the runtime lock only to read owned data (a delivery projection, a worker's pane state, the snapshot's agent rows) or to hand the core a request (a sleep, a wake, a kit read), and does no file, network or subprocess work while holding it. +Every `git` and `gh` call runs on the engine thread with a 120 second deadline, and a verify bundle runs in an owned process tree the engine polls, so a long run never waits on the thread. +The Factory adds nothing to the snapshot wire, and a Task changes no terminal, tab or scroll path. + +A machine without a Factory runs the thread's two-second wait and nothing else. +With Factories, each two-second tick does bounded work: + +- It reads the delivery projection once, applies at most 16 letters, and confirms them. +- It applies finished judgments and polls each verifying Task: a CI Factory makes one `gh api` read per verifying Task per tick, and a verify Factory polls the runner with no subprocess. +- It checks each running Task's worker once and each `landed` Task's main verification once. +- It reads outside work once per `outside_read_minutes` for each Factory, with back-off, and reads the default branch head only when that read happens or main is broken. +- It walks each Factory's Tasks a few times to move them, with one external call at most per Task step. +- It settles pending sleeps and wakes and republishes the open Factories as recipients. + +The work is bounded: 32 queued commands, 16 waiting judgments per Factory, one judgment in flight, 256 queued verify runs and one running, 16 held letters per woken worker, 4,096 remembered letters, 20,000 events and 5,000 Tasks per Factory, a 6 KiB prompt, a 48 KiB judgment input, a 256 KiB request and a 4 MiB attachment. +Crossing a cap is a reported failure and never a larger number. +A judgment and a worker start are the only places the engine waits on a provider or on Herdr, and each retries on a timer and never on a loop. From b8c556fca565b83429421087754cd0f8d16b35d6 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:00:08 +0900 Subject: [PATCH 09/72] Hold a merge to the verified commit and pace CI reads A commit with no check runs yet is pending rather than passed, the merge is pinned to the commit the last passing attempt verified, a verification time cap covers the whole command bundle, only environment failures of other Tasks clear a Task's own failure, and running checks on a commit are read again after 30 seconds rather than on every tick. --- hide-factory/src/adapters.rs | 4 ++ hide-factory/src/engine.rs | 88 ++++++++++++++++++++++--------- hide-factory/src/project.rs | 81 ++++++++++++++++++++++++---- hide-factory/src/verify.rs | 31 +++++++++-- hide-factory/tests/github.rs | 21 +++++++- hide-factory/tests/support/mod.rs | 6 ++- 6 files changed, 189 insertions(+), 42 deletions(-) diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index d9c94718f1..ab1d4ec843 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -179,6 +179,10 @@ pub struct IssueText { pub struct VerifyRun { pub id: String, pub log: Option, + /// The commit this run verifies, when it is known at the start: the + /// merge is pinned to it (B39). + #[serde(default)] + pub commit: Option, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 3fc0793b2a..0c9de4ab5d 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -82,6 +82,32 @@ enum RevertPhase { }, } +/// A failure the cascade rules read (D-31 rule 3). +struct FailureNote { + at: UnixMs, + factory: String, + task: String, + stage: String, + kind: FailureKind, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum FailureKind { + /// Read as the environment's (a structured signal). + Environment, + /// Counted against the Task (a verification failure). + Task, +} + +impl FailureKind { + fn as_str(self) -> &'static str { + match self { + Self::Environment => "environment", + Self::Task => "task", + } + } +} + pub struct Engine { store: Store, ports: Ports, @@ -97,8 +123,8 @@ pub struct Engine { main_seen: BTreeMap, processed: BTreeSet, processed_order: Vec, - /// Recent environment-class failures: (at, factory, task, stage). - env_failures: Vec<(UnixMs, String, String, String)>, + /// Recent environment and Task failures the cascade rules read. + env_failures: Vec, /// New starts halted by a cascade until this time (B60). halt_until: Option, env_problem_since: Option, @@ -2499,7 +2525,7 @@ impl Engine { self.with_task(factory_id, id, |task| { task.attempts.push(Attempt { number, - commit: None, + commit: run.commit.clone(), started_at: now, stage, outcome: None, @@ -4485,11 +4511,21 @@ impl Engine { ) { let now = self.now(); self.with_task(factory, id, |task| task.environment_failures += 1); - self.env_failures - .push((now, factory.to_owned(), id.to_owned(), stage.to_owned())); + self.env_failures.push(FailureNote { + at: now, + factory: factory.to_owned(), + task: id.to_owned(), + stage: stage.to_owned(), + kind: FailureKind::Environment, + }); let repeated = self.task(factory, id).map_or(0, |t| t.environment_failures); - let others_fine = !self.env_failures.iter().any(|(at, f, t, _)| { - now.saturating_sub(*at) <= CASCADE_WINDOW_MS && f == factory && t != id + // Another Task's environment failure in the window says the cause is + // shared; a Task failure elsewhere says nothing about it. + let others_fine = !self.env_failures.iter().any(|note| { + note.kind == FailureKind::Environment + && now.saturating_sub(note.at) <= CASCADE_WINDOW_MS + && note.factory == factory + && note.task != id }); if repeated >= 3 && others_fine { // Only this Task keeps failing this way: the Task's (B60). @@ -4526,13 +4562,14 @@ impl Engine { fn cascade_note(&mut self, factory: &str, id: &str, stage: &str, now: UnixMs) { self.env_failures - .retain(|(at, ..)| now.saturating_sub(*at) <= CASCADE_WINDOW_MS); - self.env_failures.push(( - now, - factory.to_owned(), - format!("task:{id}"), - stage.to_owned(), - )); + .retain(|note| now.saturating_sub(note.at) <= CASCADE_WINDOW_MS); + self.env_failures.push(FailureNote { + at: now, + factory: factory.to_owned(), + task: id.to_owned(), + stage: stage.to_owned(), + kind: FailureKind::Task, + }); } /// Three different Tasks failing the same stage within 30 minutes is the @@ -4543,19 +4580,19 @@ impl Engine { .env_failures .iter() .rev() - .find(|(_, f, t, _)| f == factory && *t == format!("task:{id}")) - .map(|(_, _, _, s)| s.clone()); + .find(|note| note.kind == FailureKind::Task && note.factory == factory && note.task == id) + .map(|note| note.stage.clone()); let Some(stage) = stage else { return false }; let tasks: BTreeSet = self .env_failures .iter() - .filter(|(at, f, t, s)| { - now.saturating_sub(*at) <= CASCADE_WINDOW_MS - && f == factory - && *s == stage - && t.starts_with("task:") + .filter(|note| { + note.kind == FailureKind::Task + && now.saturating_sub(note.at) <= CASCADE_WINDOW_MS + && note.factory == factory + && note.stage == stage }) - .map(|(_, _, t, _)| t.trim_start_matches("task:").to_owned()) + .map(|note| note.task.clone()) .collect(); if tasks.len() < 3 { return false; @@ -4574,8 +4611,9 @@ impl Engine { self.set_state(factory, task, TaskState::Waiting); } } - self.env_failures - .retain(|(_, f, t, s)| !(f == factory && *s == stage && t.starts_with("task:"))); + self.env_failures.retain(|note| { + !(note.kind == FailureKind::Task && note.factory == factory && note.stage == stage) + }); self.halt_until = Some(now + CASCADE_WINDOW_MS); self.env_problem_since.get_or_insert(now); self.record( @@ -4751,7 +4789,7 @@ impl Engine { let facts = json!({ "hold": self.hold_reason, "halted": self.halt_until.is_some_and(|u| u > now), - "recent_failures": self.env_failures.iter().map(|(_, _, t, s)| json!({"task": t, "stage": s})).collect::>(), + "recent_failures": self.env_failures.iter().map(|note| json!({"task": note.task, "stage": note.stage, "kind": note.kind.as_str()})).collect::>(), "disk_free": self.ports.environment.disk_free(&factory.project), }); let judgment = Judgment { diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index e05e810830..494dd1e563 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -9,7 +9,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; -use std::time::Duration; +use std::time::{Duration, Instant}; use serde_json::Value; @@ -43,8 +43,17 @@ pub struct Projects { pub verify: VerifyRunner, /// Issue bodies already seen, to tell an edit from the first read. bodies: BTreeMap<(String, u64), String>, + /// When each commit's checks last answered Pending: they are asked again + /// only after `ci_poll_every`, not on every engine tick (B75). + ci_pending: BTreeMap, + ci_poll_every: Duration, } +/// How often a commit whose checks are still running is asked again. +pub const CI_POLL_EVERY: Duration = Duration::from_secs(30); +/// Commits remembered as pending; the oldest is forgotten past this. +const CI_PENDING_LIMIT: usize = 256; + /// One `Projects` shared by the engine's source, merge and verifier ports. #[derive(Clone)] pub struct SharedProjects(pub Arc>); @@ -56,9 +65,18 @@ impl SharedProjects { issues, verify: VerifyRunner::new(logs), bodies: BTreeMap::new(), + ci_pending: BTreeMap::new(), + ci_poll_every: CI_POLL_EVERY, }))) } + /// How long a commit with running checks waits before it is asked again; + /// tests that script gh answers turn by turn pass zero. + pub fn with_ci_poll_every(self, every: Duration) -> Self { + self.lock().ci_poll_every = every; + self + } + fn lock(&self) -> MutexGuard<'_, Projects> { self.0.lock().unwrap_or_else(|poison| poison.into_inner()) } @@ -188,8 +206,35 @@ impl Projects { }) } - /// Required check runs on a commit (B35, B44). + /// Required check runs on a commit (B35, B44), read at most once per + /// `ci_poll_every` while they are pending. fn checks(&mut self, factory: &Factory, sha: &str) -> Result { + if self + .ci_pending + .get(sha) + .is_some_and(|at| at.elapsed() < self.ci_poll_every) + { + return Ok(MainCheck::Pending); + } + let answer = self.read_checks(factory, sha)?; + if answer == MainCheck::Pending { + if self.ci_pending.len() >= CI_PENDING_LIMIT + && let Some(oldest) = self + .ci_pending + .iter() + .min_by_key(|(_, at)| **at) + .map(|(sha, _)| sha.clone()) + { + self.ci_pending.remove(&oldest); + } + self.ci_pending.insert(sha.to_owned(), Instant::now()); + } else { + self.ci_pending.remove(sha); + } + Ok(answer) + } + + fn read_checks(&mut self, factory: &Factory, sha: &str) -> Result { let repo = repo(factory)?; let path = format!("repos/{repo}/commits/{sha}/check-runs?per_page=100"); let value = self.gh_json("github.checks", &["api", &path])?; @@ -208,12 +253,9 @@ impl Projects { .any(|name| run["name"].as_str() == Some(name)) }) .collect(); + // No run yet is not a pass: CI has not answered for this commit. if runs.is_empty() { - return Ok(if required.is_empty() { - MainCheck::None - } else { - MainCheck::Pending - }); + return Ok(MainCheck::Pending); } if let Some(missing) = required .iter() @@ -945,14 +987,21 @@ impl MergeTarget for SharedProjects { .unwrap_or_default() .to_owned()); } - let head = view["headRefOid"].as_str().unwrap_or_default().to_owned(); + // Pinned to the commit that passed verification: a push after + // it makes GitHub refuse the merge (B39). + let head = task + .attempts + .iter() + .rev() + .find(|attempt| matches!(attempt.outcome, Some(AttemptOutcome::Passed))) + .and_then(|attempt| attempt.commit.clone()) + .unwrap_or_else(|| view["headRefOid"].as_str().unwrap_or_default().to_owned()); let number = pr.number.to_string(); let flag = match method { MergeMethod::Merge => "--merge", MergeMethod::Squash => "--squash", MergeMethod::Rebase => "--rebase", }; - // The head SHA is pinned: a push after verification refuses the merge. this.gh( "github.merge", &[ @@ -1170,6 +1219,7 @@ impl Verifier for SharedProjects { Verification::Commands { commands } => { let id = verify_id(task, "task"); let cwd = worktree(task)?; + let commit = this.head_sha(task)?; this.verify.forget(&id); this.verify.submit(Job { id: id.clone(), @@ -1179,13 +1229,18 @@ impl Verifier for SharedProjects { timeout: Duration::from_millis(factory.config.verify_timeout_ms), })?; let log = this.verify.log_path(&id).display().to_string(); - Ok(VerifyRun { id, log: Some(log) }) + Ok(VerifyRun { + id, + log: Some(log), + commit: Some(commit), + }) } Verification::Ci { .. } => { let sha = this.head_sha(task)?; Ok(VerifyRun { id: format!("ci:{sha}"), log: task.pr.as_ref().map(|pr| pr.url.clone()), + commit: Some(sha), }) } Verification::None => Err(Failure::task("verify", "no verification")), @@ -1218,7 +1273,11 @@ impl Verifier for SharedProjects { timeout: Duration::from_millis(factory.config.verify_timeout_ms), })?; let log = this.verify.log_path(&id).display().to_string(); - Ok(VerifyRun { id, log: Some(log) }) + Ok(VerifyRun { + id, + log: Some(log), + commit: None, + }) } fn poll(&mut self, factory: &Factory, run: &VerifyRun) -> VerifyPoll { diff --git a/hide-factory/src/verify.rs b/hide-factory/src/verify.rs index aca61d097c..d86fe71557 100644 --- a/hide-factory/src/verify.rs +++ b/hide-factory/src/verify.rs @@ -41,6 +41,8 @@ struct Running { job: Job, index: usize, child: OwnedChild, + /// When the run's first command started: the time cap covers the whole + /// bundle (D-46). started: Instant, log: PathBuf, } @@ -141,8 +143,9 @@ impl VerifyRunner { if running.index < running.job.commands.len() { let job = running.job.clone(); let index = running.index; + let started = running.started; self.running = None; - self.spawn(job, index); + self.spawn(job, index, started); continue; } self.running = None; @@ -200,11 +203,11 @@ impl VerifyRunner { self.finish(&job.id, VerifyPoll::Passed); continue; } - self.spawn(job, 0); + self.spawn(job, 0, Instant::now()); } } - fn spawn(&mut self, job: Job, index: usize) { + fn spawn(&mut self, job: Job, index: usize, started: Instant) { let log = self.log_path(&job.id); let file = (|| -> std::io::Result<(File, File)> { std::fs::create_dir_all(&self.logs)?; @@ -249,7 +252,7 @@ impl VerifyRunner { job, index, child, - started: Instant::now(), + started, log, }); } @@ -442,6 +445,26 @@ mod tests { assert!(!runner.busy()); } + #[test] + fn the_time_cap_covers_the_whole_bundle_not_each_command() { + let dir = tempfile::tempdir().unwrap(); + let mut runner = VerifyRunner::new(dir.path().join("logs")); + // Each command fits the cap alone; together they do not. + runner + .submit(job( + "bundle", + dir.path(), + &["sleep 1", "sleep 1"], + Duration::from_millis(1_500), + )) + .unwrap(); + runner.pump(&mut NoRunner); + match wait(&mut runner, "bundle") { + VerifyPoll::Failed { check, .. } => assert_eq!(check, "sleep 1 (timeout 0m)"), + other => panic!("{other:?}"), + } + } + #[test] fn exit_137_is_the_environment() { let dir = tempfile::tempdir().unwrap(); diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index 01ad7276f8..e1c3352361 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -5,6 +5,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; +use std::time::Duration; use hide_factory::adapters::*; use hide_factory::exec::{Output, Runner}; @@ -19,6 +20,7 @@ struct Hub { next: u64, writes: Vec, checks: Vec, + check_reads: usize, fail_next: Option, } @@ -122,7 +124,10 @@ impl Runner for FakeGh { hub.writes.push(format!("pr reopen {number}")); ok("") } - ["api", path] if path.contains("/check-runs") => ok(json!({"check_runs": hub.checks}).to_string()), + ["api", path] if path.contains("/check-runs") => { + hub.check_reads += 1; + ok(json!({"check_runs": hub.checks}).to_string()) + } ["api", path] if path.contains("/actions/runs") => ok(json!({"workflow_runs": [{"id": 7, "conclusion": "cancelled"}, {"id": 8, "conclusion": "success"}]}).to_string()), ["run", "rerun", id, ..] => { hub.writes.push(format!("run rerun {id}")); @@ -188,6 +193,7 @@ fn projects(gh: &FakeGh) -> SharedProjects { Box::new(NoIssues), PathBuf::from("/nonexistent/logs"), ) + .with_ci_poll_every(Duration::ZERO) } #[test] @@ -276,6 +282,19 @@ fn required_checks_decide_and_a_cancelled_run_is_asked_again() { assert_eq!(p.main_check(&factory, "abc").unwrap(), MainCheck::Green); } +#[test] +fn running_checks_are_not_asked_again_on_every_tick() { + let gh = FakeGh::default(); + let mut p = projects(&gh).with_ci_poll_every(Duration::from_secs(3600)); + let factory = factory(); + gh.0.lock().unwrap().checks = vec![json!({"name": "test", "status": "in_progress"})]; + assert_eq!(p.main_check(&factory, "abc").unwrap(), MainCheck::Pending); + assert_eq!(p.main_check(&factory, "abc").unwrap(), MainCheck::Pending); + assert_eq!(gh.0.lock().unwrap().check_reads, 1); + assert_eq!(p.main_check(&factory, "def").unwrap(), MainCheck::Pending); + assert_eq!(gh.0.lock().unwrap().check_reads, 2, "each commit is asked once"); +} + #[test] fn outside_work_is_read_from_issues_and_closing_pull_requests() { let gh = FakeGh::default(); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 37f58dd9c9..181b215cec 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -165,7 +165,11 @@ impl Verifier for Shared { } let id = format!("{}:{}", task.id, world.verify_runs.len()); world.verify_runs.push(id.clone()); - Ok(VerifyRun { id, log: None }) + Ok(VerifyRun { + id, + log: None, + commit: None, + }) } fn start_premerge(&mut self, factory: &Factory, task: &Task) -> Result { self.start(factory, task) From ecdc0d12ba43fd8f58e1d289adc6dae5343bd766 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:01:57 +0900 Subject: [PATCH 10/72] Wait on an approved prerequisite and close a cancelled Task's questions An approved prerequisite proposal makes the proposer depend on the new Task and give its slot back, as an autonomous one already did; cancelling answers the Task's open questions so none reaches the inbox or a deadline; the GitHub merge method prefers a merge commit, then squash, then rebase. --- hide-factory/src/engine.rs | 57 ++++++++++++++++++++++++++---------- hide-factory/src/model.rs | 8 ++++- hide-factory/src/project.rs | 2 +- hide-factory/tests/engine.rs | 31 ++++++++++++++++++++ 4 files changed, 80 insertions(+), 18 deletions(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 0c9de4ab5d..682b8af21f 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1916,7 +1916,7 @@ impl Engine { } } } - QuestionKind::ProposedTask { draft } => { + QuestionKind::ProposedTask { draft, discovery } => { if decision == "approve" { let new_id = self.create_child(factory, id, (**draft).clone(), None); self.record( @@ -1925,6 +1925,9 @@ impl Engine { "proposal.approved", json!({"task": new_id}), ); + if let Some(discovery) = discovery { + self.wait_on_prerequisite(factory, id, discovery, &new_id); + } } } QuestionKind::Action => match decision.as_str() { @@ -2045,6 +2048,29 @@ impl Engine { id } + /// The proposer waits on the prerequisite it found and gives its slot + /// back (D-16 ④); `unblock` starts it again once the prerequisite landed. + /// A Task already past its work keeps going: the new Task is only linked. + fn wait_on_prerequisite(&mut self, factory: &str, id: &str, discovery: &str, new_id: &str) { + let mut waits = false; + self.with_task(factory, id, |task| { + if let Some(found) = task.discoveries.iter_mut().find(|d| d.id == discovery) { + found.task = Some(new_id.to_owned()); + } + waits = matches!( + task.state, + TaskState::Running | TaskState::Waiting | TaskState::Blocked | TaskState::Paused + ); + if waits && !task.card.depends_on.iter().any(|d| d == new_id) { + task.card.depends_on.push(new_id.to_owned()); + } + }); + if waits && self.task(factory, id).is_some_and(|t| t.state == TaskState::Running) { + self.put_to_sleep(factory, id); + self.set_state(factory, id, TaskState::Blocked); + } + } + fn create_child( &mut self, factory: &str, @@ -2270,6 +2296,7 @@ impl Engine { QuestionOrigin::Worker, QuestionKind::ProposedTask { draft: Box::new(draft.clone()), + discovery: Some(discovery_id.clone()), }, &format!("새 Task 제안: {}", draft.title), "approve", @@ -2281,21 +2308,9 @@ impl Engine { (None, "proposed; a person approves before it is drafted") } }; - self.with_task(factory, id, |task| { - task.new_tasks += 1; - if let Some(new_id) = &created { - if let Some(discovery) = - task.discoveries.iter_mut().find(|d| d.id == discovery_id) - { - discovery.task = Some(new_id.clone()); - } - // The current Task waits on the prerequisite (D-16 ④). - task.card.depends_on.push(new_id.clone()); - } - }); - if created.is_some() { - self.put_to_sleep(factory, id); - self.set_state(factory, id, TaskState::Blocked); + self.with_task(factory, id, |task| task.new_tasks += 1); + if let Some(new_id) = &created { + self.wait_on_prerequisite(factory, id, &discovery_id, new_id); } let reached = self .task(factory, id) @@ -3290,6 +3305,16 @@ impl Engine { if let Some(worker) = &mut task.worker { worker.asleep = true; } + // A cancelled Task asks nothing of a person, and no deadline + // applies a default to it; a revived worker asks again. + for question in task.questions.iter_mut().filter(|q| q.open()) { + question.answer = Some(Answer { + text: "취소됨".into(), + chose: None, + relayed_by: "cancel".into(), + at: now, + }); + } }); self.set_state(factory_id, id, TaskState::Cancelled); } diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 47c50beaf4..1c88bfaa02 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -512,7 +512,13 @@ pub enum QuestionKind { /// The new-task cap was reached (B31). NewTaskCap, /// A worker proposed a new Task outside autonomy (B30). - ProposedTask { draft: Box }, + ProposedTask { + draft: Box, + /// The prerequisite discovery it answers; on approval the proposer + /// waits on the new Task (D-16 ④). + #[serde(default, skip_serializing_if = "Option::is_none")] + discovery: Option, + }, /// A stop, a main break or a recovery that needs a person; the choices /// are the actions. Action, diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 494dd1e563..5859789676 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -354,8 +354,8 @@ impl TaskSource for SharedProjects { probe.default_branch = branch.to_owned(); } for (key, method) in [ - ("squashMergeAllowed", MergeMethod::Squash), ("mergeCommitAllowed", MergeMethod::Merge), + ("squashMergeAllowed", MergeMethod::Squash), ("rebaseMergeAllowed", MergeMethod::Rebase), ] { if view[key].as_bool() == Some(true) { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index fad0a60e42..fea342cfb0 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -793,6 +793,12 @@ fn a_proposed_task_waits_for_a_person_and_its_worker_cannot_propose() { .id .clone(); assert_eq!(h.task(&f, &child).proposed_by.as_deref(), Some(t.as_str())); + assert_eq!(h.task(&f, &t).card.depends_on, vec![child.clone()]); + assert_eq!( + h.task(&f, &t).state, + TaskState::Blocked, + "the proposer waits on the approved prerequisite and gives its slot back (D-16)" + ); tick_until(&mut h, &f, &child, TaskState::Running); let refused = h.as_worker( &f, @@ -1351,6 +1357,31 @@ fn pause_resume_cancel_and_revive_keep_the_same_worker_and_pull_request() { assert_eq!(refused["reason"], "revive_expired"); } +#[test] +fn a_cancelled_task_leaves_no_question_for_a_person_or_a_deadline() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Asks then goes", &[]); + h.as_worker( + &f, + &t, + Command::Ask { + text: "Name the flag?".into(), + suggestion: "--fast".into(), + default_action: "use --fast".into(), + deadline_hours: Some(1), + letter: None, + }, + ); + h.op(Command::Cancel { task: t.clone() }); + assert_eq!(h.task(&f, &t).open_questions().count(), 0); + h.advance(2 * HOUR_MS); + h.engine.tick(); + let question = &h.task(&f, &t).questions[0]; + assert_eq!(question.answer.as_ref().unwrap().relayed_by, "cancel"); + assert_eq!(h.state(&f, &t), TaskState::Cancelled); +} + #[test] fn a_blocked_task_takes_only_an_answer() { let mut h = Bench::new(false); From 9fc102beaa32180bab3e07fe20f59ceff6f3e6f5 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:05:24 +0900 Subject: [PATCH 11/72] Remove a finished worker's worktree from its own repository Worktree removal ran git from the folder above the worktree, which is outside the repository, so no finished Task's worktree was ever removed. It now resolves the main checkout and reuses the host's guarded removal. A Task an outside pull request merged frees its worktree too, a Task an outside pull request took is cleaned up after the keep period like a cancelled one, and both lose their local branch then (D-58). --- herdr-core/src/factory.rs | 101 +++++++++++++++++++++++++++--- hide-factory/src/adapters.rs | 10 ++- hide-factory/src/engine.rs | 83 ++++++++++++++---------- hide-factory/src/summary.rs | 10 +-- hide-factory/tests/engine.rs | 10 ++- hide-factory/tests/github.rs | 6 +- hide-factory/tests/support/mod.rs | 6 +- 7 files changed, 176 insertions(+), 50 deletions(-) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index 1989a619cb..a716cd5671 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -888,7 +888,17 @@ impl WorkerRuntime for CoreWorkers { .map_err(|reason| Failure::task("worker.stop", reason)) } - fn remove_worktree(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + fn remove_worktree(&mut self, worker: &WorkerRef, delete_branch: bool) -> Result<(), Failure> { + let checkout = Path::new(&worker.worktree); + let mut runner = SystemRunner { + stop: Arc::new(AtomicBool::new(false)), + }; + // The repository the worktree belongs to, read before it goes; a + // folder already gone leaves only the branch to delete. + let root = match checkout.exists() { + true => Some(repository_root(&mut runner, checkout)?), + false => None, + }; let runtime = self.runtime()?; let connector = guard(&runtime).delivery_connector("local"); drop(runtime); @@ -904,16 +914,19 @@ impl WorkerRuntime for CoreWorkers { crate::live::CONFIRM_TIMEOUT, ) .map_err(|reason| Failure::task("worktree.close", reason))?; - let mut runner = SystemRunner { - stop: Arc::new(AtomicBool::new(false)), + let Some(root) = root else { + return Ok(()); }; - if Path::new(&worker.worktree).exists() { + // The Factory made this worktree, so what is left in it goes too. + hide_host::worktrees::remove_worktree(&root, checkout, true) + .map_err(|reason| Failure::task("worktree.remove", reason))?; + if delete_branch { hide_factory::exec::checked( &mut runner, - "worktree.remove", + "branch.delete", "git", - &["worktree", "remove", "--force", &worker.worktree], - Path::new(&worker.worktree).parent(), + &["branch", "-D", "--", &worker.branch], + Some(&root), )?; } Ok(()) @@ -924,6 +937,23 @@ impl WorkerRuntime for CoreWorkers { } } +/// The main checkout of the repository a linked worktree belongs to. +fn repository_root(runner: &mut SystemRunner, checkout: &Path) -> Result { + let output = hide_factory::exec::checked( + runner, + "worktree.root", + "git", + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + Some(checkout), + )?; + let common = PathBuf::from(output.trim()); + common + .parent() + .filter(|_| common.file_name().is_some_and(|name| name == ".git")) + .map(Path::to_path_buf) + .ok_or_else(|| Failure::task("worktree.root", "the repository has no main checkout")) +} + fn spawn_failure(reason: &str) -> Failure { match reason { // The pane was made and the agent typed in; its session is not @@ -1253,3 +1283,60 @@ fn judge_loop(shared: Arc, runtime: Weak>, home: Opt } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn git(cwd: &Path, args: &[&str]) { + let status = std::process::Command::new("git") + .arg("-C") + .arg(cwd) + .args(args) + .status() + .unwrap(); + assert!(status.success(), "git {args:?}"); + } + + #[test] + fn a_worker_worktree_outside_its_repository_resolves_to_the_main_checkout() { + let root = tempfile::tempdir().unwrap(); + let main = root.path().join("project"); + std::fs::create_dir(&main).unwrap(); + git(&main, &["init", "--quiet", "-b", "main"]); + git( + &main, + &[ + "-c", + "user.email=f@example.com", + "-c", + "user.name=F", + "commit", + "--quiet", + "--allow-empty", + "-m", + "base", + ], + ); + // Spawned worktrees live in a folder of their own, not in the repository. + let worktree = root.path().join("worktrees/project/factory-l1-task"); + git( + &main, + &[ + "worktree", + "add", + "--quiet", + "-b", + "factory/1-task", + worktree.to_str().unwrap(), + ], + ); + let mut runner = SystemRunner { + stop: Arc::new(AtomicBool::new(false)), + }; + let found = repository_root(&mut runner, &worktree).unwrap(); + assert_eq!(found.canonicalize().unwrap(), main.canonicalize().unwrap()); + hide_host::worktrees::remove_worktree(&found, &worktree, true).unwrap(); + assert!(!worktree.exists()); + } +} diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index ab1d4ec843..00ba8a24aa 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -324,8 +324,14 @@ pub trait WorkerRuntime { fn wake(&mut self, worker: &crate::model::WorkerRef, body: &str) -> Result<(), Failure>; fn status(&mut self, worker: &crate::model::WorkerRef) -> WorkerStatus; fn stop(&mut self, worker: &crate::model::WorkerRef) -> Result<(), Failure>; - /// Removes the Task's worktree and local branch (B43, B62, B71). - fn remove_worktree(&mut self, worker: &crate::model::WorkerRef) -> Result<(), Failure>; + /// Removes the Task's worktree (B43, B62, B71) and, with + /// `delete_branch`, its local branch (D-58); the remote branch stays. + /// Removing what is already gone succeeds. + fn remove_worktree( + &mut self, + worker: &crate::model::WorkerRef, + delete_branch: bool, + ) -> Result<(), Failure>; fn usage_limited(&mut self, runtime: Runtime) -> Option; } diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 682b8af21f..78c7d34fda 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -826,9 +826,9 @@ impl Engine { TaskState::MergeWaiting => vec!["merge", "request-changes", "cancel"], TaskState::Stopped => vec!["retry", "cancel"], TaskState::Landed | TaskState::Done | TaskState::Relanding => vec![], - TaskState::Outside => vec!["revive"], + TaskState::Outside if !task.purged => vec!["revive"], TaskState::Cancelled if !task.purged => vec!["revive"], - TaskState::Cancelled => vec![], + TaskState::Cancelled | TaskState::Outside => vec![], }; if task.open_questions().next().is_some() { actions.insert(0, "answer"); @@ -2065,7 +2065,11 @@ impl Engine { task.card.depends_on.push(new_id.to_owned()); } }); - if waits && self.task(factory, id).is_some_and(|t| t.state == TaskState::Running) { + if waits + && self + .task(factory, id) + .is_some_and(|t| t.state == TaskState::Running) + { self.put_to_sleep(factory, id); self.set_state(factory, id, TaskState::Blocked); } @@ -2935,21 +2939,35 @@ impl Engine { } self.save_factory(factory_id); // Worker tab and worktree go once main is green (B43). - if let Some(worker) = self.task(factory_id, id).and_then(|t| t.worker.clone()) { - let _ = self.ports.workers.stop(&worker); - if let Err(failure) = self.ports.workers.remove_worktree(&worker) { - self.record( - factory_id, - Some(id), - "cleanup.failed", - json!({"stage": failure.stage}), - ); - } - } + self.release_worker(factory_id, id); // A finished Task is a watch event (D-32). self.watch_due(factory_id, true); } + /// A finished Task's worker ends and its worktree goes; the branch stays + /// with the merge. A failure is logged and the disk recovery retries it. + fn release_worker(&mut self, factory_id: &str, id: &str) { + let Some(worker) = self.task(factory_id, id).and_then(|t| t.worker.clone()) else { + return; + }; + let _ = self.ports.workers.stop(&worker); + match self.ports.workers.remove_worktree(&worker, false) { + Ok(()) => { + self.with_task(factory_id, id, |t| t.purged = true); + } + Err(failure) => self.cleanup_failed(factory_id, id, &failure), + } + } + + fn cleanup_failed(&mut self, factory_id: &str, id: &str, failure: &Failure) { + self.record( + factory_id, + Some(id), + "cleanup.failed", + json!({"stage": failure.stage, "detail": failure.detail}), + ); + } + // ------------------------------------------------------------- main break fn main_broken(&mut self, factory_id: &str, sha: &str, link: &str) { @@ -4312,10 +4330,9 @@ impl Engine { "outside.merged", json!({"pr": pr}), ); - if let Some(worker) = &task.worker { - let _ = self.ports.workers.stop(worker); - } + self.cancel_verification(factory_id, &task.id); self.set_state(factory_id, &task.id, TaskState::Done); + self.release_worker(factory_id, &task.id); } TaskState::Outside => {} TaskState::Running @@ -4358,6 +4375,7 @@ impl Engine { if task.state == TaskState::Outside { // Its outside PR closed the issue: follow it to done. self.set_state(factory_id, &task.id, TaskState::Done); + self.release_worker(factory_id, &task.id); return; } self.cancel(factory_id, &task.id); @@ -4605,7 +4623,9 @@ impl Engine { .env_failures .iter() .rev() - .find(|note| note.kind == FailureKind::Task && note.factory == factory && note.task == id) + .find(|note| { + note.kind == FailureKind::Task && note.factory == factory && note.task == id + }) .map(|note| note.stage.clone()); let Some(stage) = stage else { return false }; let tasks: BTreeSet = self @@ -4766,7 +4786,7 @@ impl Engine { .get(&t.factory) .map_or(7 * DAY_MS, |f| f.config.cancel_keep_ms); t.state == TaskState::Done - || (t.state == TaskState::Cancelled + || (matches!(t.state, TaskState::Cancelled | TaskState::Outside) && t.cancelled_at .is_some_and(|at| now.saturating_sub(at) > keep)) }) @@ -4777,17 +4797,15 @@ impl Engine { }) .collect(); for (factory, id, worker) in targets { - match self.ports.workers.remove_worktree(&worker) { + let finished = self + .task(&factory, &id) + .is_some_and(|t| t.state == TaskState::Done); + match self.ports.workers.remove_worktree(&worker, !finished) { Ok(()) => { self.with_task(&factory, &id, |t| t.purged = true); self.record(&factory, Some(&id), "cleanup.worktree", json!({})); } - Err(failure) => self.record( - &factory, - Some(&id), - "cleanup.failed", - json!({"stage": failure.stage}), - ), + Err(failure) => self.cleanup_failed(&factory, &id, &failure), } } } @@ -5024,11 +5042,13 @@ impl Engine { // --------------------------------------------------------------- retention + /// Cancelled Tasks, and Tasks an outside pull request took, past their + /// keep period lose their worktree and local branch (D-58, B50). fn retention(&mut self) { let now = self.now(); let expired: Vec<(String, String)> = self .all_tasks() - .filter(|t| t.state == TaskState::Cancelled && !t.purged) + .filter(|t| matches!(t.state, TaskState::Cancelled | TaskState::Outside) && !t.purged) .filter(|t| { let keep = self .factories @@ -5041,14 +5061,9 @@ impl Engine { .collect(); for (factory, id) in expired { if let Some(worker) = self.task(&factory, &id).and_then(|t| t.worker.clone()) - && let Err(failure) = self.ports.workers.remove_worktree(&worker) + && let Err(failure) = self.ports.workers.remove_worktree(&worker, true) { - self.record( - &factory, - Some(&id), - "cleanup.failed", - json!({"stage": failure.stage}), - ); + self.cleanup_failed(&factory, &id, &failure); continue; } self.with_task(&factory, &id, |t| t.purged = true); diff --git a/hide-factory/src/summary.rs b/hide-factory/src/summary.rs index 5010cd0d6c..ecf6d0a5af 100644 --- a/hide-factory/src/summary.rs +++ b/hide-factory/src/summary.rs @@ -288,14 +288,14 @@ pub fn card_view( }; let finished_at = match task.state { TaskState::Done => task.done_at, - TaskState::Cancelled => task.cancelled_at, + TaskState::Cancelled | TaskState::Outside => task.cancelled_at, _ => None, }; let folded = match task.state { TaskState::Done => { finished_at.is_some_and(|at| now.saturating_sub(at) > factory.config.done_fold_ms) } - TaskState::Cancelled => task.purged, + TaskState::Cancelled | TaskState::Outside => task.purged, _ => false, }; let archived = @@ -322,7 +322,9 @@ pub fn card_view( external: task.card.external.clone(), revive_until: task .cancelled_at - .filter(|_| task.state == TaskState::Cancelled && !task.purged) + .filter(|_| { + matches!(task.state, TaskState::Cancelled | TaskState::Outside) && !task.purged + }) .map(|at| at + factory.config.cancel_keep_ms), worker_pane: task .worker @@ -341,7 +343,7 @@ pub fn inbox_items( ) -> Vec { let mut items = Vec::new(); for task in tasks.values() { - if matches!(task.state, TaskState::Cancelled) && task.purged { + if matches!(task.state, TaskState::Cancelled | TaskState::Outside) && task.purged { continue; } let base = |group: &str, rank: u8, text: String, since: UnixMs| InboxItem { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index fea342cfb0..62cf6c87d6 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1208,6 +1208,12 @@ fn an_outside_pull_request_takes_a_running_task_and_its_merge_finishes_it() { h.advance(3 * MINUTE_MS); h.engine.tick(); assert_eq!(h.state(&f, &t), TaskState::Done); + assert_eq!( + h.world().removed, + vec![t.clone()], + "its merge frees the worktree" + ); + assert!(h.world().branches_deleted.is_empty()); tick_until(&mut h, &f, &after, TaskState::Running); } @@ -1348,11 +1354,13 @@ fn pause_resume_cancel_and_revive_keep_the_same_worker_and_pull_request() { assert_eq!(h.writes("pr.reopen"), vec!["pr.reopen 1"]); assert_eq!(h.world().spawned.len(), 1); - // Past the keep period the worktree goes and revive is refused. + // Past the keep period the worktree and local branch go and revive is + // refused (D-58). h.op(Command::Cancel { task: t.clone() }); h.advance(8 * DAY_MS); h.engine.tick(); assert!(h.world().removed.contains(&t)); + assert!(h.world().branches_deleted.contains(&t)); let refused = h.op(Command::Revive { task: t.clone() }); assert_eq!(refused["reason"], "revive_expired"); } diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index e1c3352361..4779cea3c6 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -292,7 +292,11 @@ fn running_checks_are_not_asked_again_on_every_tick() { assert_eq!(p.main_check(&factory, "abc").unwrap(), MainCheck::Pending); assert_eq!(gh.0.lock().unwrap().check_reads, 1); assert_eq!(p.main_check(&factory, "def").unwrap(), MainCheck::Pending); - assert_eq!(gh.0.lock().unwrap().check_reads, 2, "each commit is asked once"); + assert_eq!( + gh.0.lock().unwrap().check_reads, + 2, + "each commit is asked once" + ); } #[test] diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 181b215cec..2bcfd876cf 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -47,6 +47,7 @@ pub struct World { pub wakes: Vec<(String, String)>, pub stops: Vec, pub removed: Vec, + pub branches_deleted: Vec, pub spawn_failure: Option, /// Judgments submitted and not yet answered. pub submitted: Vec, @@ -345,8 +346,11 @@ impl WorkerRuntime for Shared { self.world().stops.push(task_of(worker)); Ok(()) } - fn remove_worktree(&mut self, worker: &WorkerRef) -> Result<(), Failure> { + fn remove_worktree(&mut self, worker: &WorkerRef, delete_branch: bool) -> Result<(), Failure> { self.world().removed.push(task_of(worker)); + if delete_branch { + self.world().branches_deleted.push(task_of(worker)); + } Ok(()) } fn usage_limited(&mut self, _runtime: Runtime) -> Option { From d6e03731d9601f48f3b52651992aefebdd938675 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:09:07 +0900 Subject: [PATCH 12/72] Apply a re-added card and PRD once its scope change is approved A card or PRD added again while its Task runs rides on the scope change question and becomes the Task's card and next PRD version on approval; the worker gets the new card and the copy's path in the reply, and a newer re-add replaces a pending one. The test repositories no longer inherit the machine's commit signing setting. --- herdr-core/src/factory.rs | 2 + hide-factory/src/engine.rs | 91 ++++++++++++++++++++++----------- hide-factory/src/model.rs | 15 +++++- hide-factory/src/summary.rs | 4 +- hide-factory/tests/engine.rs | 54 +++++++++++++++++++ hide-factory/tests/local_git.rs | 2 + 6 files changed, 134 insertions(+), 34 deletions(-) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index a716cd5671..b8d591dbd5 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -1311,6 +1311,8 @@ mod tests { "user.email=f@example.com", "-c", "user.name=F", + "-c", + "commit.gpgsign=false", "commit", "--quiet", "--allow-empty", diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 78c7d34fda..16441b1d27 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1334,13 +1334,7 @@ impl Engine { if unchanged { return Ok(self.add_answer(factory_id, id)); } - if let Some(attachment) = attachment { - self.with_task(factory_id, id, |task| { - task.flags.push(format!( - "pending PRD v{} {}", - attachment.version, attachment.sha256 - )); - }); + if let Some(attachment) = &attachment { self.record( factory_id, Some(id), @@ -1348,11 +1342,26 @@ impl Engine { json!({"version": attachment.version}), ); } + // A newer re-add replaces a pending one rather than queueing two. + self.with_task(factory_id, id, |task| { + for question in task.questions.iter_mut().filter(|q| { + q.open() && matches!(&q.kind, QuestionKind::ScopeChange { change: Some(_) }) + }) { + question.answer = Some(Answer { + text: "replaced by a newer re-add".into(), + chose: None, + relayed_by: "re-add".into(), + at: now, + }); + } + }); self.add_question( factory_id, id, QuestionOrigin::Engine, - QuestionKind::ScopeChange, + QuestionKind::ScopeChange { + change: Some(Box::new(CardChange { card, attachment })), + }, "실행 중에 카드나 PRD가 바뀌었습니다. 새 범위를 승인할까요?", "approve", Some("지금 범위로 진행".into()), @@ -1868,20 +1877,34 @@ impl Engine { } self.advance_merge(factory, id); } - QuestionKind::ScopeChange => { + QuestionKind::ScopeChange { change } => { let approved = decision == "approve"; + let mut prd = None; self.with_task(factory, id, |task| { if approved { task.scope_approved = true; - if let Some(flag) = - task.flags.iter().position(|f| f.starts_with("pending PRD")) - { - task.flags.remove(flag); + if let Some(change) = change { + task.card = change.card.clone(); + if let Some(attachment) = &change.attachment { + prd = Some(format!( + "\nPRD v{}: {} (읽기 전용)", + attachment.version, attachment.path + )); + task.attachments.push(attachment.clone()); + } } } }); + let card = match (approved, change) { + (true, Some(_)) => self + .task(factory, id) + .map(|t| format!("\n새 카드:\n{}", card_text(&t.card))) + .unwrap_or_default(), + _ => String::new(), + }; + let prd = prd.unwrap_or_default(); self.reply(factory, id, target.letter.as_deref(), &if approved { - format!("Factory: 범위 변경이 승인되었습니다. {text}") + format!("Factory: 범위 변경이 승인되었습니다. {text}{card}{prd}") } else { format!("Factory: 범위 변경은 승인되지 않았습니다. 지금 범위 안에서 진행하세요. {text}") }); @@ -2240,7 +2263,7 @@ impl Engine { factory, id, QuestionOrigin::Worker, - QuestionKind::ScopeChange, + QuestionKind::ScopeChange { change: None }, &format!("범위 변경: {text}"), "approve", Some("범위를 넓히지 않고 진행".into()), @@ -2723,8 +2746,10 @@ impl Engine { let now = self.now(); // Questions with a default wait only here, until answer or deadline (B26). let waiting_question = task.open_questions().any(|q| { - matches!(q.kind, QuestionKind::Default | QuestionKind::ScopeChange) - && q.deadline.is_none_or(|d| d > now) + matches!( + q.kind, + QuestionKind::Default | QuestionKind::ScopeChange { .. } + ) && q.deadline.is_none_or(|d| d > now) }); if waiting_question { return; @@ -2814,7 +2839,7 @@ impl Engine { if task.open_questions().any(|q| { !matches!( q.kind, - QuestionKind::Notice | QuestionKind::Default | QuestionKind::ScopeChange + QuestionKind::Notice | QuestionKind::Default | QuestionKind::ScopeChange { .. } ) }) { gates.push(Gate::OpenQuestion); @@ -3887,7 +3912,7 @@ impl Engine { for question in task.open_questions() { if matches!( question.kind, - QuestionKind::Default | QuestionKind::ScopeChange + QuestionKind::Default | QuestionKind::ScopeChange { .. } ) && question.deadline.is_some_and(|d| d <= now) { expired.push(( @@ -4425,7 +4450,7 @@ impl Engine { factory_id, &task.id, QuestionOrigin::Engine, - QuestionKind::ScopeChange, + QuestionKind::ScopeChange { change: None }, "사람이 issue 본문을 고쳤습니다. 새 범위를 승인할까요?", "approve", Some("지금 범위로 진행".into()), @@ -5296,6 +5321,21 @@ fn worker_name(factory: &Factory, task: &Task) -> String { ) } +/// The card as a worker reads it: goal, criteria and what is out of scope. +fn card_text(card: &Card) -> String { + let mut text = format!("목표:\n{}\n\n완료 조건:\n", card.goal); + for criterion in &card.criteria { + text.push_str(&format!("- {criterion}\n")); + } + if !card.out_of_scope.is_empty() { + text.push_str("\n범위 밖 (하지 마세요):\n"); + for item in &card.out_of_scope { + text.push_str(&format!("- {item}\n")); + } + } + text +} + /// The worker's first prompt (B22): the card, the attachments, the harness /// preset and the Factory's reporting rules. pub fn worker_prompt(task: &Task, factory: &Factory, resumed: bool, hide: &str) -> String { @@ -5308,16 +5348,7 @@ pub fn worker_prompt(task: &Task, factory: &Factory, resumed: bool, hide: &str) task.display_id(), task.card.title )); - prompt.push_str(&format!("목표:\n{}\n\n완료 조건:\n", task.card.goal)); - for criterion in &task.card.criteria { - prompt.push_str(&format!("- {criterion}\n")); - } - if !task.card.out_of_scope.is_empty() { - prompt.push_str("\n범위 밖 (하지 마세요):\n"); - for item in &task.card.out_of_scope { - prompt.push_str(&format!("- {item}\n")); - } - } + prompt.push_str(&card_text(&task.card)); for attachment in &task.attachments { prompt.push_str(&format!("\n첨부 (읽기 전용): {}\n", attachment.path)); } diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 1c88bfaa02..b29a0ba58f 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -476,6 +476,12 @@ impl IssueRef { } } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CardChange { + pub card: Card, + pub attachment: Option, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Attachment { /// Absolute path of the private copy the worker reads. @@ -507,8 +513,13 @@ pub enum QuestionKind { Default, /// A worker question that cannot proceed without an answer (B27). Blocking, - /// A scope change: a person approves a wider scope (B29 ③). - ScopeChange, + /// A scope change: a person approves a wider scope (B29 ③). A card or + /// PRD added again while the Task runs carries it here and becomes the + /// Task's on approval (B16). + ScopeChange { + #[serde(default, skip_serializing_if = "Option::is_none")] + change: Option>, + }, /// The new-task cap was reached (B31). NewTaskCap, /// A worker proposed a new Task outside autonomy (B30). diff --git a/hide-factory/src/summary.rs b/hide-factory/src/summary.rs index ecf6d0a5af..58cd525412 100644 --- a/hide-factory/src/summary.rs +++ b/hide-factory/src/summary.rs @@ -456,7 +456,7 @@ fn question_kind(kind: &QuestionKind) -> &'static str { QuestionKind::Split { .. } => "split", QuestionKind::Default => "default", QuestionKind::Blocking => "blocking", - QuestionKind::ScopeChange => "scope_change", + QuestionKind::ScopeChange { .. } => "scope_change", QuestionKind::NewTaskCap => "new_task_cap", QuestionKind::ProposedTask { .. } => "proposed_task", QuestionKind::Action => "action", @@ -470,7 +470,7 @@ fn question_kind(kind: &QuestionKind) -> &'static str { fn answer_result(task: &Task, kind: &QuestionKind, tasks: &BTreeMap) -> String { match kind { QuestionKind::Blocking => unblocks("worker를 깨워 이어감", task, tasks), - QuestionKind::Default | QuestionKind::ScopeChange => { + QuestionKind::Default | QuestionKind::ScopeChange { .. } => { "기본 행동과 다르면 worker가 반영, 같으면 머지로 감".into() } QuestionKind::Intake | QuestionKind::ConfirmCard => "남은 질문이 없으면 Ready".into(), diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 62cf6c87d6..3b853ea191 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -232,6 +232,60 @@ fn review_questions_hold_the_task_until_answered_and_re_adding_is_idempotent() { assert_eq!(h.writes("issue.create").len(), 1); } +#[test] +fn a_prd_changed_while_running_becomes_the_task_s_only_once_approved() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Spec", &[]); + assert_eq!(h.state(&f, &t), TaskState::Running); + let prd = h.dir.path().join("prd.md"); + std::fs::write(&prd, "# v2\n").unwrap(); + let mut changed = card("Spec", &[]); + changed.goal = Some("Make Spec work the v2 way".into()); + changed.prd = Some(prd.to_string_lossy().into_owned()); + let readd = |h: &mut Bench, card: CardInput| { + h.op(Command::Add { + project: None, + task: Some(t.clone()), + issue: None, + card, + producer_pane: None, + }) + }; + readd(&mut h, changed.clone()); + readd(&mut h, changed); + let before = h.task(&f, &t); + assert_eq!( + before.card.goal, "Make Spec work", + "nothing changes before approval" + ); + assert!(before.attachments.is_empty()); + assert_eq!( + before.open_questions().count(), + 1, + "a second re-add replaces the first" + ); + + let question = open_question(&h, &f, &t); + h.op(Command::Answer { + task: t.clone(), + question: Some(question.id), + choice: Some("approve".into()), + text: None, + }); + let after = h.task(&f, &t); + assert_eq!(after.card.goal, "Make Spec work the v2 way"); + assert_eq!(after.attachments.len(), 1); + let path = after.attachments[0].path.clone(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "# v2\n"); + let told = h + .world() + .messages + .iter() + .any(|(task, body)| *task == t && body.contains(&path) && body.contains("the v2 way")); + assert!(told, "the worker gets the new card and the PRD copy"); +} + // --------------------------------------------------------------------- DAG /// Six Tasks with a fork and a join run in topological order with at most diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index f9e1fb355a..04d64243b0 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -79,6 +79,8 @@ fn fixture() -> Fixture { git(&project, &["init", "--quiet", "--initial-branch=main"]); git(&project, &["config", "user.email", "factory@example.com"]); git(&project, &["config", "user.name", "Factory"]); + // The machine's own signing setting must not reach the fixture. + git(&project, &["config", "commit.gpgsign", "false"]); write(&project, "a.txt", "one\n"); write(&project, "Makefile", "test:\n\ttrue\n"); git(&project, &["add", "."]); From c1a2182dbe6763384e15fc066ef894b043de9a1e Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:10:36 +0900 Subject: [PATCH 13/72] Run periodic checks on the watch cadence and watch at the new-Task cap A periodic user check reads each running Task's card when the watch interval comes due and only adds questions or marks; one that cannot be queued is logged, as nothing waits on it. Reaching a Task's new-Task cap reads the board like a finished Task or a main break does. --- hide-factory/src/engine.rs | 69 ++++++++++++++++++++++++++++++++++++ hide-factory/tests/engine.rs | 57 +++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 16441b1d27..3e935d9f96 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -149,6 +149,9 @@ enum Purpose { Intake, Drift, Check, + /// A periodic user check on a running Task: it adds questions or marks + /// and never holds a merge (B67). + Periodic, Watch, Env, } @@ -2343,6 +2346,8 @@ impl Engine { .task(factory, id) .is_some_and(|t| t.new_tasks >= limit && !t.new_task_cap_extended); if reached { + // Reaching the cap is a watch event (B69). + self.watch_due(factory, true); self.put_to_sleep(factory, id); self.with_task(factory, id, |task| task.stop = Some(StopReason::NewTaskCap)); self.set_state(factory, id, TaskState::Stopped); @@ -3885,6 +3890,17 @@ impl Engine { } self.advance_merge(&factory, &task); } + (JudgmentOutcome::Answered { value }, Purpose::Periodic, Some(task)) => { + match judgment::parse_finding(value) { + Ok(_) => self.apply_finding(&factory, &task, value), + Err(_) => self.record( + &factory, + Some(&task), + "judgment.failed", + json!({"purpose": "Periodic", "reason": "unreadable"}), + ), + } + } (JudgmentOutcome::Answered { value }, Purpose::Watch, _) => { self.apply_watch(&factory, value) } @@ -4992,6 +5008,59 @@ impl Engine { self.judgments .insert(judgment.id, (factory_id.to_owned(), None, Purpose::Watch)); } + if interval_due { + self.periodic_checks(&factory, now); + } + } + + /// The periodic user checks run on the watch cadence over each running + /// Task's card (B67); one that cannot be queued is logged, since nothing + /// waits on it. + fn periodic_checks(&mut self, factory: &Factory, now: UnixMs) { + let checks: Vec = factory + .config + .checks + .iter() + .filter(|c| c.at == CheckPoint::Periodic) + .map(|c| c.instruction.clone()) + .collect(); + if checks.is_empty() { + return; + } + let running: Vec<(String, Card)> = self + .tasks_of(&factory.id) + .filter(|t| t.state == TaskState::Running) + .map(|t| (t.id.clone(), t.card.clone())) + .collect(); + for (id, card) in running { + for (index, instruction) in checks.iter().enumerate() { + let judgment = Judgment { + id: format!("{}:{id}:periodic:{index}:{now}", factory.id), + factory: factory.id.clone(), + task: Some(id.clone()), + priority: Priority::Factory, + input: JudgmentInput::Check { + instruction: instruction.clone(), + card: card.clone(), + diff: None, + }, + }; + match self.ports.judge.submit(judgment.clone()) { + Ok(()) => { + self.judgments.insert( + judgment.id, + (factory.id.clone(), Some(id.clone()), Purpose::Periodic), + ); + } + Err(failure) => self.record( + &factory.id, + Some(&id), + "check.skipped", + json!({"at": "periodic", "stage": failure.stage}), + ), + } + } + } } fn apply_watch(&mut self, factory_id: &str, value: &Value) { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 3b853ea191..d36f97ddad 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -10,6 +10,7 @@ use hide_factory::adapters::{ EnvSignal, Failure, MainCheck, MemoryPressure, OutsideEvent, VerifyPoll, WorkerStatus, }; use hide_factory::command::{CardInput, Command, VerificationChoice}; +use hide_factory::judgment::JudgmentInput; use hide_factory::model::*; use serde_json::json; use support::*; @@ -909,10 +910,21 @@ fn an_enabled_autonomy_scope_starts_alone_and_the_third_new_task_stops_the_paren set: vec![("autonomy".into(), "lint_format=on".into())], }); let t = h.ready("Parent", &[]); + let watches = |h: &Bench| { + let world = h.world(); + world + .submitted + .iter() + .chain(&world.judged) + .filter(|j| matches!(j.input, JudgmentInput::Watch { .. })) + .count() + }; + let mut watched = 0; for n in 1..=3 { if h.state(&f, &t) != TaskState::Running { h.op(Command::Resume { task: t.clone() }); } + watched = watches(&h); let answer = h.as_worker( &f, &t, @@ -944,6 +956,11 @@ fn an_enabled_autonomy_scope_starts_alone_and_the_third_new_task_stops_the_paren (task.state, task.stop), (TaskState::Stopped, Some(StopReason::NewTaskCap)) ); + assert_eq!( + watches(&h), + watched + 1, + "reaching the cap reads the board (B69)" + ); assert!(matches!( open_question(&h, &f, &t).kind, QuestionKind::NewTaskCap @@ -1704,6 +1721,46 @@ fn a_refused_worker_start_stops_the_task_once_and_a_retry_starts_it() { // ------------------------------------------------------------------ watch +#[test] +fn a_periodic_check_reads_each_running_task_on_the_watch_cadence() { + let mut h = Bench::new(false); + let f = h.factory(true); + let answer = h.op(Command::Check { + project: None, + at: CheckPoint::Periodic, + instruction: "Does it still match the card?".into(), + }); + assert_eq!(answer["ok"], true, "{answer}"); + let running = h.ready("Running", &[]); + let waiting = h.ready("Waiting", &[&running]); + h.world().drift.insert( + running.clone(), + json!({"pass": false, "questions": [{"text": "Drifting?", "suggestion": "keep", "default_action": "keep going"}], "flags": []}), + ); + let periodic = |h: &Bench| { + h.world() + .judged + .iter() + .filter(|j| j.id.contains(":periodic:")) + .filter_map(|j| j.task.clone()) + .collect::>() + }; + h.engine.tick(); + assert!(periodic(&h).is_empty(), "nothing before the interval"); + h.advance(30 * 60_000); + h.engine.tick(); + h.engine.tick(); + assert_eq!(periodic(&h), vec![running.clone()]); + let question = open_question(&h, &f, &running); + assert_eq!(question.text, "Drifting?"); + assert_eq!( + h.state(&f, &running), + TaskState::Running, + "a check never stops the work" + ); + assert_eq!(h.task(&f, &waiting).open_questions().count(), 0); +} + #[test] fn the_watch_raises_actionable_warnings_once_each_within_the_daily_cap() { let mut h = Bench::new(false); From d35ac3d75c6951c93d4833b3258335f96583689f Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:15:42 +0900 Subject: [PATCH 14/72] Make every D-30 default settable, including the stall window stall_minutes now sets the quiet window of each worker's watch: the host publishes each open Factory with its window and the watch readings carry it, so a change applies at the next reading. no_report_minutes, archive_fold_days, verify_failure_limit and autonomy_diff_limit gain keys. The delivery test fixtures name the new reading field. --- docs/delivery.md | 4 ++-- docs/factory.md | 13 ++++++++----- herdr-core/src/delivery/human.rs | 2 ++ herdr-core/src/delivery/watch.rs | 29 +++++++++++++++++++++++++++-- herdr-core/src/delivery/worker.rs | 4 ++++ herdr-core/src/factory.rs | 4 ++-- herdr-core/src/runtime.rs | 5 +++-- herdr-core/src/runtime/delivery.rs | 20 ++++++++++++++++---- hide-factory/src/engine.rs | 6 +++++- 9 files changed, 69 insertions(+), 18 deletions(-) diff --git a/docs/delivery.md b/docs/delivery.md index c26863e457..cf3e09c0ce 100644 --- a/docs/delivery.md +++ b/docs/delivery.md @@ -109,7 +109,7 @@ Capacity errors retain existing letters and watches. | Pending delivery deadline | 60 minutes, then `undelivered`; visible through CLI | | Quiet period | 30 seconds since hide last routed a key and since Herdr last changed the pane's status | | Doorbell reservations per letter | Three total, persisted across restart | -| First inactivity warning | 20 minutes without activity; 30 minutes when the observer is a Factory | +| First inactivity warning | 20 minutes without activity; the Factory's stall window (30 minutes by default) when the observer is a Factory | | Second inactivity warning | First-warning time plus 60 minutes, at most two warnings per episode | | Unanswered parent warning notification | First-warning time plus 60 minutes, once per native target and inactivity episode | | Intent retention and finished-letter cleanup | 30 days; open letters remain | @@ -163,7 +163,7 @@ Only the Factory's engine sends as it, and the ledger accepts that authority onl A pane or agent may send to it and may name it as a watch observer, and only while the Factory exists and is open; a pane or agent name that starts with `factory:` is refused at registration. A letter to it is never pasted into a composer and never rings a doorbell: the engine reads it, confirms it and, for a request or block, replies with its answer. The human-notice claim skips a letter whose recipient is code-owned. -A watch observed by a Factory warns after 30 minutes without activity rather than 20, and the engine acts on the first warning. +A watch observed by a Factory warns after that Factory's stall window (`stall_minutes`, 30 by default) rather than 20, and the engine acts on the first warning. ## Agent registration and spawning diff --git a/docs/factory.md b/docs/factory.md index 085732d33f..4a34f8619a 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -168,7 +168,7 @@ Each open Factory is a code-owned recipient named `factory:` in the - The engine reads its letters from the ledger on each tick, up to 16 at a time, applies each once, and confirms it. A request or block letter also gets a reply carrying the engine's JSON answer. No composer input or doorbell is involved. - The letter's sender must be a live worker of that Factory, or the letter is refused with `sender_not_a_worker` and logged. - A worker's CLI report is a typed body `{"factory": }` sent under an intent made from the pane and the body, so a retry applies once. A harness that follows the letter protocol only is read as a question (a `request` or `block` letter becomes a blocking question with a 24 hour deadline, taking a `Recommendation:`, `Suggestion:`, `추천:` or `제안:` line as the suggestion) or as a completion (a `report` letter becomes `done`). -- A watch whose observer is the Factory warns after 30 quiet minutes instead of 20. The engine turns the first warning into a stalled stop; it does not wait for the second warning or for the human notice, which the ledger skips for a code-owned recipient. +- A watch whose observer is the Factory warns after the Factory's `stall_minutes` (30 by default) instead of 20; the host hands each open Factory's window to the watch readings, so a change applies at the next reading. The engine turns the first warning into a stalled stop; it does not wait for the second warning or for the human notice, which the ledger skips for a code-owned recipient. - The Factory writes to a worker with `report` letters, and starts a watch on the worker again each time it does, because a report to its parent ends the sender's watch. ## The worker lifecycle @@ -202,7 +202,7 @@ A worker reports through `hide factory` and gets its answer in the same call. `ask` needs a suggestion, a default action and a deadline of 1 to 720 hours, and the worker continues with the default; `block` has no default, so the Task blocks, releases its slot and sleeps. `done` opens a pull request on a GitHub Factory when none exists, goes to `verifying`, and puts the worker to sleep. `decide` records a decision. -A worker whose agent rests for the no-report window of 2 minutes after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for 30 minutes stops it as "stalled". +A worker whose agent rests for the no-report window (`no_report_minutes`, 2) after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for the stall window (`stall_minutes`, 30) stops it as "stalled". ## Intake review and judgments @@ -420,20 +420,24 @@ A Factory's `merge_mode` cannot be `auto` while it has no verification (`auto_ne | Key | Value | Default | | --- | --- | --- | | `merge_mode` | `auto` or `manual` | `manual` until `init` chose a verification, then `auto` | -| `merge_method` | `merge`, `squash` or `rebase` | The first the repository allows (squash, merge, rebase) | +| `merge_method` | `merge`, `squash` or `rebase` | The first the repository allows (merge, squash, rebase) | | `verify` | Commands joined by `&&&`; empty clears | none | | `ci` | Comma-separated check names | none | | `no_verification` | Any value | none | | `quick_check` | A shell command; empty clears | none | | `max_workers` | 1 to 64, machine-wide | 5 | | `question_deadline_hours` | Hours | 24 | -| `stall_minutes` | Minutes | 30 (stored; the quiet window is the watch's fixed 30 minutes) | +| `stall_minutes` | Minutes, at least 1: the quiet window of each worker's watch | 30 | +| `no_report_minutes` | Minutes, at least 1, after a turn ends without a report | 2 | | `watch_interval_minutes` | Minutes, at least 5 | 30 | | `watch_daily_limit` | Count | 5 | | `outside_read_minutes` | Minutes, at least 1 | 2 | | `cancel_keep_days` | Days | 7 | | `done_fold_days` | Days | 3 | +| `archive_fold_days` | Days before a finished Task leaves the list | 90 | | `new_task_limit` | Count | 3 | +| `verify_failure_limit` | Count, at least 1 | 3 | +| `autonomy_diff_limit` | Changed lines an autonomous Task may merge alone | 200 | | `verify_timeout_minutes` | Minutes per command, at least 1 | 60 | | `disk_floor_gb` | Gigabytes | 20 | | `default_runtime` | `claude` or `codex` | `claude` | @@ -448,7 +452,6 @@ A Factory's `merge_mode` cannot be `auto` while it has no verification (`auto_ne `max_workers` is the machine's, not the Factory's, and any Factory's `config` sets the same value. `worker_args` holds the whole argument list for one runtime, such as a permission mode the operator chose, and an empty list removes it. `harness` places the named instruction in each worker's first prompt; gates never trust a harness's own claims, and a harness's own checks belong in `verify`. -The 2-minute no-report window, the 90-day fold, the 3-failure limit and the 200-line autonomy limit are fixed in the Factory's configuration record and have no key. ## The `hide factory` command diff --git a/herdr-core/src/delivery/human.rs b/herdr-core/src/delivery/human.rs index eeaeb3975d..537e73e00d 100644 --- a/herdr-core/src/delivery/human.rs +++ b/herdr-core/src/delivery/human.rs @@ -105,6 +105,7 @@ mod tests { session_modified_at_unix_ms: None, failure: None, gone: false, + inactivity_ms: None, }; watch::tick(ledger, &[reading], activity + INACTIVITY_MS).unwrap(); started @@ -188,6 +189,7 @@ mod tests { session_modified_at_unix_ms: None, failure: None, gone: false, + inactivity_ms: None, }; watch::tick(&mut ledger, &[reading(10)], due).unwrap(); assert_eq!(ledger.watches[0].warning_count, 2); diff --git a/herdr-core/src/delivery/watch.rs b/herdr-core/src/delivery/watch.rs index 5ba6692c17..f765173299 100644 --- a/herdr-core/src/delivery/watch.rs +++ b/herdr-core/src/delivery/watch.rs @@ -69,7 +69,8 @@ impl Watch { } /// How long a watch waits before its first warning: a Factory observer -/// stops a quiet worker after 30 minutes, every other observer after 20. +/// stops a quiet worker after 30 minutes unless the reading carries the +/// Factory's own window, every other observer after 20. pub fn inactivity_window(watch: &Watch) -> u64 { if watch.parent.code_owned() { super::FACTORY_INACTIVITY_MS @@ -182,6 +183,9 @@ pub struct Reading { pub session_modified_at_unix_ms: Option, pub failure: Option, pub gone: bool, + /// A window that replaces [`inactivity_window`] for this watch: a + /// Factory's stall setting (D-30). + pub inactivity_ms: Option, } #[derive(Default)] @@ -289,7 +293,12 @@ pub fn tick(ledger: &mut Ledger, readings: &[Reading], now: u64) -> Result now.saturating_sub(activity) >= inactivity_window(watch), + (0, _) => { + now.saturating_sub(activity) + >= reading + .inactivity_ms + .unwrap_or_else(|| inactivity_window(watch)) + } (1, Some(first)) => now.saturating_sub(first) >= SECOND_WARNING_MS, _ => false, }; @@ -424,6 +433,7 @@ mod tests { session_modified_at_unix_ms: None, failure: None, gone: false, + inactivity_ms: None, } } @@ -562,6 +572,20 @@ mod tests { assert_eq!(ledger.letters.len(), 1); } + #[test] + fn a_factory_s_stall_setting_replaces_the_thirty_minute_window() { + let mut ledger = Ledger::default(); + let watch = start(&mut ledger, &Actor::factory("f-1"), &actor("worker"), 10).unwrap(); + let within = |id: &str| Reading { + inactivity_ms: Some(45 * 60_000), + ..reading(id, 10) + }; + tick(&mut ledger, &[within(&watch.id)], 10 + 45 * 60_000 - 1).unwrap(); + assert!(ledger.letters.is_empty()); + tick(&mut ledger, &[within(&watch.id)], 10 + 45 * 60_000).unwrap(); + assert_eq!(ledger.letters.len(), 1); + } + #[test] fn two_warnings_keep_the_first_deadline_across_restart_and_reset_on_activity() { let mut ledger = Ledger::default(); @@ -689,6 +713,7 @@ mod tests { session_modified_at_unix_ms: None, failure: None, gone: false, + inactivity_ms: None, }; reading.gone = true; tick(&mut ledger, &[reading], 2 + INACTIVITY_MS).unwrap(); diff --git a/herdr-core/src/delivery/worker.rs b/herdr-core/src/delivery/worker.rs index 06cc1aaa82..50dbaea76b 100644 --- a/herdr-core/src/delivery/worker.rs +++ b/herdr-core/src/delivery/worker.rs @@ -215,6 +215,8 @@ pub(crate) struct WatchWork { pub status_changed_at_unix_ms: u64, pub home: Option, pub channel: Option>, + /// The watching Factory's own stall window, when it set one. + pub inactivity_ms: Option, } fn read_activity(work: WatchWork) -> watch::Reading { @@ -227,6 +229,7 @@ fn read_activity(work: WatchWork) -> watch::Reading { session_modified_at_unix_ms: None, failure: None, gone: work.gone, + inactivity_ms: work.inactivity_ms, }; if work.gone { return reading; @@ -965,6 +968,7 @@ mod tests { status_changed_at_unix_ms: 1, home: None, channel: Some(channel.clone()), + inactivity_ms: None, }) .collect(); let readings: Vec<_> = group_targets(work) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index b8d591dbd5..f1dbd90fd8 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -318,11 +318,11 @@ fn owner_of(engine: &Engine, answer: &Value) -> Option { /// Open Factories become delivery recipients; closed ones stop receiving. fn publish_recipients(engine: Option<&Engine>, runtime: &Weak>) { - let ids: BTreeSet = engine + let ids: BTreeMap = engine .into_iter() .flat_map(Engine::factories) .filter(|factory| !factory.closed) - .map(|factory| factory.id.clone()) + .map(|factory| (factory.id.clone(), factory.config.stall_ms)) .collect(); if let Some(runtime) = lock(runtime) { guard(&runtime).set_factory_recipients(ids); diff --git a/herdr-core/src/runtime.rs b/herdr-core/src/runtime.rs index f650a4acb2..b428f06aad 100644 --- a/herdr-core/src/runtime.rs +++ b/herdr-core/src/runtime.rs @@ -1071,7 +1071,8 @@ pub struct Runtime { delivery_observations: HashMap, /// Open Factories' code-owned recipients (`factory:`), set by the /// Factory host; a letter to any other `factory:` name has no recipient. - factory_recipients: std::collections::BTreeSet, + /// Each open Factory's id with its stall window (D-30, B24). + factory_recipients: std::collections::BTreeMap, delivery_overflow: HashSet, delivery_connected: HashSet, /// Stable identities are separate from device labels: labels are mutable @@ -1776,7 +1777,7 @@ impl Runtime { delivery_ledger, delivery_client: None, delivery_observations: HashMap::new(), - factory_recipients: std::collections::BTreeSet::new(), + factory_recipients: std::collections::BTreeMap::new(), delivery_overflow: HashSet::new(), delivery_connected: HashSet::new(), local_machine_id: options.machine_id.clone(), diff --git a/herdr-core/src/runtime/delivery.rs b/herdr-core/src/runtime/delivery.rs index dfc346a04d..b9f12432c1 100644 --- a/herdr-core/src/runtime/delivery.rs +++ b/herdr-core/src/runtime/delivery.rs @@ -431,8 +431,13 @@ impl Runtime { } /// The Factory host publishes which Factories exist. - pub(crate) fn set_factory_recipients(&mut self, ids: std::collections::BTreeSet) { - self.factory_recipients = ids; + /// The open Factories, each with the inactivity window its workers' + /// watches use. + pub(crate) fn set_factory_recipients( + &mut self, + factories: std::collections::BTreeMap, + ) { + self.factory_recipients = factories; } /// A code-owned recipient is current while its Factory exists and the @@ -441,7 +446,9 @@ impl Runtime { actor .pane_id .strip_prefix(crate::delivery::FACTORY_PREFIX) - .is_some_and(|id| self.factory_recipients.contains(id) && *actor == Actor::factory(id)) + .is_some_and(|id| { + self.factory_recipients.contains_key(id) && *actor == Actor::factory(id) + }) } /// The authority the Factory host acts with: its own recipient, never a @@ -596,6 +603,11 @@ impl Runtime { status_changed_at_unix_ms: watch.status_changed_at_unix_ms, home: self.home_path.clone(), channel, + inactivity_ms: watch + .parent + .pane_id + .strip_prefix(crate::delivery::FACTORY_PREFIX) + .and_then(|id| self.factory_recipients.get(id).copied()), } }) .collect() @@ -1072,7 +1084,7 @@ pub(crate) mod tests { guard.factory_delivery("f-1").err().as_deref(), Some("factory_unavailable") ); - guard.set_factory_recipients(["f-1".to_owned()].into()); + guard.set_factory_recipients([("f-1".to_owned(), 30 * 60_000)].into()); let prepared = guard .prepare_delivery("local", "sender", &context, None, send("once")) .unwrap(); diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 3e935d9f96..390728b5f8 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -3564,7 +3564,11 @@ impl Engine { } "max_workers" => machine_workers = Some(number()?.clamp(1, 64) as u32), "question_deadline_hours" => config.question_deadline_ms = number()? * HOUR_MS, - "stall_minutes" => config.stall_ms = number()? * MINUTE_MS, + "stall_minutes" => config.stall_ms = number()?.max(1) * MINUTE_MS, + "no_report_minutes" => config.no_report_ms = number()?.max(1) * MINUTE_MS, + "archive_fold_days" => config.archive_fold_ms = number()? * DAY_MS, + "verify_failure_limit" => config.verify_failure_limit = number()?.max(1) as u32, + "autonomy_diff_limit" => config.autonomy_diff_limit = number()? as u32, "watch_interval_minutes" => config.watch_interval_ms = number()?.max(5) * MINUTE_MS, "watch_daily_limit" => config.watch_daily_limit = number()? as u32, "outside_read_minutes" => config.outside_read_ms = number()?.max(1) * MINUTE_MS, From 45f24f8d03a32b3df7c7ca0d6b2b914e3688e303 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:17:59 +0900 Subject: [PATCH 15/72] Keep judgment and letter bodies with their Task Each judgment's input and output and each letter to or from a worker is kept in a records table, cut at 256 KiB and never deleted automatically (D-58). The unused log copy helper goes; a verification run already keeps its own last mebibyte. The guide describes this, the cleanup, re-add and prerequisite changes, cancelled questions and periodic checks. --- docs/factory.md | 20 ++++--- hide-factory/src/engine.rs | 74 ++++++++++++++++++++++--- hide-factory/src/store.rs | 104 +++++++++++++++++++++++++++-------- hide-factory/tests/engine.rs | 32 +++++++++++ 4 files changed, 191 insertions(+), 39 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 4a34f8619a..99a68ff25c 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -46,6 +46,7 @@ Both are private to the user: the file is mode 0600 and the folder 0700 on Unix. | `tasks` | One JSON record per Task, with indexed state, issue, priority and times. The record carries the card, questions, discoveries, decisions, attempts, worker, pull request and gates. | | `dependencies` | One row per dependency edge, rewritten with its Task. | | `events` | Ids-and-stage records of transitions, external calls and failures, never card text or secrets. | +| `records` | Each judgment's input and output and each letter's body to or from a worker, kept with its Task and cut at 256 KiB (D-58). | | `meta` | The machine-wide worker limit and the ids of the last 4,096 applied letters. | `PRAGMA user_version` carries the schema version, now 1. @@ -59,11 +60,12 @@ The engine opens the store when a store file already exists at start, or on the A run's log keeps only its last 1 MiB when the run ends. The Factory deletes no Task, question, decision, discovery, attempt or attachment. -It removes a worker's worktree and pane when the Task is done and main verification has passed, when a cancelled Task passes its keep period, and, only under disk pressure, for finished Tasks. -The worktree removal leaves the Task's branch in place, and the Factory never deletes a remote branch. +It removes a worker's worktree and pane when the Task is done and main verification has passed or an outside pull request merged it, when a cancelled Task or one an outside pull request took passes its keep period, and, only under disk pressure, for finished Tasks. +The removal runs from the repository's main checkout through the host's guarded worktree removal. +A finished Task keeps its branch; a cancelled or outside Task loses its local branch with its worktree, and the Factory never deletes a remote branch. A finished Task folds out of the board's Done column after 3 days and out of every list after 90 days; its page still opens. Each Factory keeps its newest 20,000 events and drops older ones. -Judgment inputs and answers are not stored; the questions and flags they produce are, and the core's diagnostic log records each judgment's feature, ids, outcome and duration. +Judgment inputs and answers and letter bodies are kept in `records` and never deleted automatically; `Engine::records` reads a Task's, and the core's diagnostic log records each judgment's feature, ids, outcome and duration. ## Tasks, states and the DAG @@ -244,7 +246,7 @@ A failed watch or diagnosis changes no Task and is logged. The Factory has its own judgment queue on its own router (see [AI_PROVIDERS.md](AI_PROVIDERS.md#the-factorys-judgments)): one request in flight, intake reviews before every other judgment, and 16 waiting judgments per Factory. A judgment submitted to a full queue fails like a provider failure and is escalated the way above. Natural-language checks are added with `hide factory check --at intake|after-done|periodic`. -A `periodic` check is stored with the others, and no timer runs it yet. +A `periodic` check runs over each running Task's card whenever the watch interval comes due; like an after-done check it only adds questions or marks, it never holds a merge, and one that cannot be queued is logged and asked again at the next interval. ## Verification @@ -348,9 +350,9 @@ Its kind decides what an answer does. | `split` | The review | `split` splits the Task, `proceed` clears it. | | `default` | A worker `ask`, a drift or check finding | The default keeps going; a different answer wakes the worker. After the deadline the default is the answer. | | `blocking` | A worker `block` | Wakes the worker through a reply; the Task waits for a slot and resumes its session. No deadline decides it. | -| `scope_change` | A worker, a re-add, an edited issue | `approve` records approval and adds a gate; `reject` keeps the scope. After the deadline it is rejected. | +| `scope_change` | A worker, a re-add, an edited issue | `approve` records approval and adds a gate, and a re-added card and PRD become the Task's, sent to the worker in the reply; `reject` keeps the scope. After the deadline it is rejected. A newer re-add replaces a pending one. | | `new_task_cap` | The Task reached the new-Task limit | `continue` lets it create more; any other choice leaves it stopped with a notice. | -| `proposed_task` | A prerequisite proposal outside autonomy | `approve` drafts the Task. | +| `proposed_task` | A prerequisite proposal outside autonomy | `approve` drafts the Task, and the proposer depends on it and gives its slot back until it lands. | | `action` | A stop, a failed review, a main break | The listed choice runs: `retry`, `retry-review`, `cancel`, `resume-auto`, `retry-revert`, `revert `. | | `confirm_card` | A label-path card, a fix-Task draft | `confirm` lets the Task become Ready. | | `proposal` | An environment diagnosis | Records the answer; a person runs the command. | @@ -404,7 +406,7 @@ A Task that alone repeats an environment failure three times is the Task's: it s ## The watch The watch reads a Factory's board for what a person cannot already see in the inbox, such as work that stopped moving, a chain held by one wait, or a pattern of failures. -It runs when a Task finishes, when main breaks, and every `watch_interval_minutes` (30 by default, at least 5) for a Factory that has Tasks. +It runs when a Task finishes, when main breaks, when a Task reaches its new-Task limit, and every `watch_interval_minutes` (30 by default, at least 5) for a Factory that has Tasks. It asks `factory_watch` with the Factory's board summary. A warning without a proposed action goes to the diagnostic log only. A warning with an action becomes a notice on the Task it names, or on the Factory's last Task, and counts against `watch_daily_limit` (5) per Factory per UTC day; a warning past the limit is logged as capped. @@ -569,7 +571,7 @@ Fields are added and never renamed or removed. The inbox lists each open question, each `merge_waiting` Task, and each stopped Task that has no action question, in order of rank and, within a rank, the item waiting longest first. That puts blocking questions first, then other answers, merge waits, stops and notices, so what has waited the longest to be unblocked is at the top. -A cancelled Task inside its keep period still lists its open questions. +Cancelling a Task answers its open questions as `cancel`, so a cancelled Task lists none and no deadline applies a default to it. A Task's board column comes from its state: `drafting`, `waiting` and `done` have their own, every other state except `cancelled` is in `running`, and `cancelled` is off the board. Inside a column the cards a person must look at (blocked, stopped, merge waiting, or holding an open question) come first, oldest first, then the rest by priority and age. @@ -626,6 +628,6 @@ With Factories, each two-second tick does bounded work: - It walks each Factory's Tasks a few times to move them, with one external call at most per Task step. - It settles pending sleeps and wakes and republishes the open Factories as recipients. -The work is bounded: 32 queued commands, 16 waiting judgments per Factory, one judgment in flight, 256 queued verify runs and one running, 16 held letters per woken worker, 4,096 remembered letters, 20,000 events and 5,000 Tasks per Factory, a 6 KiB prompt, a 48 KiB judgment input, a 256 KiB request and a 4 MiB attachment. +The work is bounded: 32 queued commands, 16 waiting judgments per Factory, one judgment in flight, 256 queued verify runs and one running, 16 held letters per woken worker, 4,096 remembered letters, 20,000 events and 5,000 Tasks per Factory, a 256 KiB kept record, a 6 KiB prompt, a 48 KiB judgment input, a 256 KiB request and a 4 MiB attachment. Crossing a cap is a reported failure and never a larger number. A judgment and a worker start are the only places the engine waits on a provider or on Herdr, and each retries on a timer and never on a loop. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 390728b5f8..8731a8995d 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -19,7 +19,7 @@ use crate::dag; use crate::judgment::{self, Judgment, JudgmentInput, JudgmentOutcome, OtherTask, Priority}; use crate::model::*; use crate::role::{ROLE_NOT_ALLOWED, Role}; -use crate::store::{Event, Store, StoreError, sha256_hex}; +use crate::store::{Event, Record, Store, StoreError, sha256_hex}; use crate::summary::{self, FactorySummary}; /// The world the engine acts on. @@ -345,6 +345,39 @@ impl Engine { let _ = self.store.append_event(&event); } + /// Keeps a judgment or letter body with its Task (D-58); like an event, + /// a failed write never changes a decision. + fn keep(&self, factory: &str, task: Option<&str>, kind: &str, reference: &str, body: &str) { + let record = Record { + factory: factory.to_owned(), + task: task.map(str::to_owned), + at: self.now(), + kind: kind.to_owned(), + reference: reference.to_owned(), + body: body.to_owned(), + }; + if let Err(error) = self.store.keep_record(&record) { + self.record( + factory, + task, + "store.failed", + json!({"stage": "record", "error": error.0}), + ); + } + } + + /// Every judgment's input is kept before it is queued (D-58). + fn submit_judgment(&mut self, judgment: Judgment) -> Result<(), Failure> { + self.keep( + &judgment.factory, + judgment.task.as_deref(), + "judgment.input", + &judgment.id, + &judgment.render_input(), + ); + self.ports.judge.submit(judgment) + } + fn save_factory(&mut self, id: &str) { if let Some(factory) = self.factories.get(id) && let Err(error) = self.store.put_factory(factory) @@ -1543,7 +1576,7 @@ impl Engine { self.with_task(factory, id, |task| { task.review = ReviewState::Requested { at: now } }); - match self.ports.judge.submit(judgment) { + match self.submit_judgment(judgment) { Ok(()) => { self.judgments.insert( judgment_id, @@ -1565,7 +1598,7 @@ impl Engine { diff: None, }, }; - if self.ports.judge.submit(judgment).is_ok() { + if self.submit_judgment(judgment).is_ok() { self.judgments.insert( check_id, (factory.to_owned(), Some(id.to_owned()), Purpose::Check), @@ -2464,7 +2497,7 @@ impl Engine { decisions, }, }; - match self.ports.judge.submit(drift.clone()) { + match self.submit_judgment(drift.clone()) { Ok(()) => { self.judgments.insert( drift.id, @@ -2492,7 +2525,7 @@ impl Engine { diff: Some(diff.clone()), }, }; - match self.ports.judge.submit(judgment.clone()) { + match self.submit_judgment(judgment.clone()) { Ok(()) => { self.judgments.insert( judgment.id, @@ -3284,6 +3317,7 @@ impl Engine { let Some(worker) = self.task(factory, id).and_then(|t| t.worker.clone()) else { return; }; + self.keep(factory, Some(id), "letter.out", "wake", body); let result = if worker.asleep { self.ports.workers.wake(&worker, body) } else { @@ -3318,6 +3352,13 @@ impl Engine { return; } let intent = format!("factory-{id}-reply-{}", self.now()); + self.keep( + factory, + Some(id), + "letter.out", + letter.unwrap_or(&intent), + body, + ); if let Err(failure) = self.ports.workers.message(&worker, &intent, letter, body) { self.external_failure(factory, Some(id), &failure); } @@ -3668,6 +3709,11 @@ impl Engine { Ok(serde_json::to_value(&summary).unwrap_or_default()) } + /// A Task's kept judgment and letter bodies, oldest first (D-58). + pub fn records(&self, factory: &str, id: &str, limit: usize) -> Vec { + self.store.records(factory, id, limit).unwrap_or_default() + } + pub fn show(&self, factory: &str, id: &str) -> Option { let factory = self.factories.get(factory)?; let tasks = self.tasks.get(&factory.id)?; @@ -3712,6 +3758,7 @@ impl Engine { ) .to_json(); } + self.keep(&factory, Some(&task), "letter.in", &letter.id, &letter.body); let role = Role::Worker { factory: factory.clone(), task: task.clone(), @@ -3851,6 +3898,17 @@ impl Engine { let Some((factory, task, purpose)) = self.judgments.remove(&answer.id) else { continue; }; + let output = match &answer.outcome { + JudgmentOutcome::Answered { value } => value.to_string(), + JudgmentOutcome::Failed { reason } => json!({"failed": reason}).to_string(), + }; + self.keep( + &factory, + task.as_deref(), + "judgment.output", + &answer.id, + &output, + ); match (&answer.outcome, purpose, task) { (JudgmentOutcome::Answered { value }, Purpose::Intake, Some(task)) => { self.apply_intake(&factory, &task, value) @@ -4890,7 +4948,7 @@ impl Engine { actions: RecoveryAction::ALL.to_vec(), }, }; - if self.ports.judge.submit(judgment.clone()).is_ok() { + if self.submit_judgment(judgment.clone()).is_ok() { self.judgments .insert(judgment.id, (factory.id.clone(), None, Purpose::Env)); } @@ -5008,7 +5066,7 @@ impl Engine { f.watch_last_at = Some(now); } self.save_factory(factory_id); - if self.ports.judge.submit(judgment.clone()).is_ok() { + if self.submit_judgment(judgment.clone()).is_ok() { self.judgments .insert(judgment.id, (factory_id.to_owned(), None, Purpose::Watch)); } @@ -5049,7 +5107,7 @@ impl Engine { diff: None, }, }; - match self.ports.judge.submit(judgment.clone()) { + match self.submit_judgment(judgment.clone()) { Ok(()) => { self.judgments.insert( judgment.id, diff --git a/hide-factory/src/store.rs b/hide-factory/src/store.rs index f701c03db6..e81e4a36d5 100644 --- a/hide-factory/src/store.rs +++ b/hide-factory/src/store.rs @@ -16,12 +16,12 @@ use sha2::{Digest, Sha256}; use crate::model::{Attachment, Factory, Task, UnixMs}; pub const SCHEMA_VERSION: i64 = 1; -/// A verify or CI log copy keeps at most its last 1 MiB per attempt (D-58). -pub const LOG_TAIL_LIMIT: usize = 1024 * 1024; /// A PRD attachment larger than this is refused. pub const ATTACHMENT_LIMIT: u64 = 4 * 1024 * 1024; /// Events kept per Factory; the oldest are dropped past it. pub const EVENT_LIMIT: i64 = 20_000; +/// A kept judgment or letter body is cut to its first this many bytes. +pub const RECORD_LIMIT: usize = 256 * 1024; const SCHEMA: &str = " CREATE TABLE IF NOT EXISTS factories ( @@ -59,6 +59,16 @@ CREATE TABLE IF NOT EXISTS events ( detail TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS events_factory ON events(factory, seq); +CREATE TABLE IF NOT EXISTS records ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + factory TEXT NOT NULL, + task TEXT, + at INTEGER NOT NULL, + kind TEXT NOT NULL, + reference TEXT NOT NULL, + body TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS records_task ON records(factory, task, seq); CREATE TABLE IF NOT EXISTS meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL @@ -103,6 +113,19 @@ pub struct Event { pub detail: serde_json::Value, } +/// A judgment's input or output, or a letter body, kept with its Task. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Record { + pub factory: String, + pub task: Option, + pub at: UnixMs, + /// `judgment.input`, `judgment.output`, `letter.in` or `letter.out`. + pub kind: String, + /// The judgment or letter id. + pub reference: String, + pub body: String, +} + pub struct Store { connection: Connection, files: PathBuf, @@ -333,22 +356,47 @@ impl Store { }) } - /// Keeps the last [`LOG_TAIL_LIMIT`] bytes of a log for one attempt. - pub fn keep_log( + /// Keeps a judgment's input or output or a letter's body (D-58); none + /// is deleted automatically. + pub fn keep_record(&self, record: &Record) -> Result<(), StoreError> { + self.connection.execute( + "INSERT INTO records (factory, task, at, kind, reference, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + record.factory, + record.task, + record.at as i64, + record.kind, + record.reference, + crate::judgment::cut(&record.body, RECORD_LIMIT) + ], + )?; + Ok(()) + } + + /// A Task's kept records, oldest first, at most `limit` of the newest. + pub fn records( &self, factory: &str, task: &str, - attempt: u32, - stage: &str, - bytes: &[u8], - ) -> Result { - let folder = self.files.join(factory).join(task).join("logs"); - fs::create_dir_all(&folder)?; - private_dir(&folder)?; - let tail = &bytes[bytes.len().saturating_sub(LOG_TAIL_LIMIT)..]; - let path = folder.join(format!("attempt-{attempt}-{stage}.log")); - write_private(&path, tail)?; - Ok(path) + limit: usize, + ) -> Result, StoreError> { + let mut statement = self.connection.prepare( + "SELECT factory, task, at, kind, reference, body FROM records + WHERE factory = ?1 AND task = ?2 ORDER BY seq DESC LIMIT ?3", + )?; + let rows = statement.query_map(params![factory, task, limit as i64], |row| { + Ok(Record { + factory: row.get(0)?, + task: row.get(1)?, + at: row.get::<_, i64>(2)? as u64, + kind: row.get(3)?, + reference: row.get(4)?, + body: row.get(5)?, + }) + })?; + let mut records = rows.collect::, _>>()?; + records.reverse(); + Ok(records) } } @@ -442,19 +490,31 @@ mod tests { } #[test] - fn a_log_copy_keeps_only_its_last_mebibyte() { + fn records_are_kept_per_task_and_a_long_body_is_cut() { let folder = tempfile::tempdir().unwrap(); let store = Store::open( &folder.path().join("factory.sqlite3"), &folder.path().join("factory-files"), ) .unwrap(); - let mut bytes = vec![b'a'; LOG_TAIL_LIMIT]; - bytes.extend_from_slice(b"tail"); - let path = store.keep_log("f", "T-1", 1, "task", &bytes).unwrap(); - let kept = fs::read(path).unwrap(); - assert_eq!(kept.len(), LOG_TAIL_LIMIT); - assert!(kept.ends_with(b"tail")); + let record = |task: &str, body: String| Record { + factory: "f".into(), + task: Some(task.into()), + at: 1, + kind: "letter.in".into(), + reference: "letter-1".into(), + body, + }; + store.keep_record(&record("T-1", "first".into())).unwrap(); + store.keep_record(&record("T-2", "other".into())).unwrap(); + store + .keep_record(&record("T-1", "x".repeat(RECORD_LIMIT + 10))) + .unwrap(); + let kept = store.records("f", "T-1", 10).unwrap(); + assert_eq!(kept.len(), 2); + assert_eq!(kept[0].body, "first"); + assert!(kept[1].body.len() <= RECORD_LIMIT + 32); + assert!(kept[1].body.ends_with("[cut 10 bytes]")); } #[test] diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index d36f97ddad..6838100a01 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1436,6 +1436,38 @@ fn pause_resume_cancel_and_revive_keep_the_same_worker_and_pull_request() { assert_eq!(refused["reason"], "revive_expired"); } +#[test] +fn judgment_bodies_and_letters_are_kept_with_their_task() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Kept", &[]); + h.engine.letter(Inbound { + id: "letter-9".into(), + factory: f.clone(), + sender_pane: h.task(&f, &t).worker.unwrap().pane.unwrap(), + kind: "request".into(), + body: "Factory: which name? please".into(), + }); + let kinds: Vec<(String, String)> = h + .engine + .records(&f, &t, 50) + .into_iter() + .map(|r| (r.kind, r.reference)) + .collect(); + assert!( + kinds.iter().any(|(k, _)| k == "judgment.input"), + "{kinds:?}" + ); + assert!( + kinds.iter().any(|(k, _)| k == "judgment.output"), + "{kinds:?}" + ); + assert!( + kinds.contains(&("letter.in".into(), "letter-9".into())), + "{kinds:?}" + ); +} + #[test] fn a_cancelled_task_leaves_no_question_for_a_person_or_a_deadline() { let mut h = Bench::new(false); From 2a421e23f33723a7cfeddbd50e9aa731b9bc352d Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:18:57 +0900 Subject: [PATCH 16/72] Default a new Factory's workers to the runtime this machine has init reads the path for Claude Code, then Codex CLI, and the first found becomes the default runtime (D-45); the preview shows it. --- docs/factory.md | 2 +- hide-factory/src/adapters.rs | 2 ++ hide-factory/src/engine.rs | 5 +++++ hide-factory/src/project.rs | 12 ++++++++++++ hide-factory/tests/engine.rs | 23 +++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 3 +++ 6 files changed, 46 insertions(+), 1 deletion(-) diff --git a/docs/factory.md b/docs/factory.md index 99a68ff25c..c58a73a2c8 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -442,7 +442,7 @@ A Factory's `merge_mode` cannot be `auto` while it has no verification (`auto_ne | `autonomy_diff_limit` | Changed lines an autonomous Task may merge alone | 200 | | `verify_timeout_minutes` | Minutes per command, at least 1 | 60 | | `disk_floor_gb` | Gigabytes | 20 | -| `default_runtime` | `claude` or `codex` | `claude` | +| `default_runtime` | `claude` or `codex` | Claude Code when `init` finds it on the path, else Codex when it finds that, else `claude` | | `harness` | `:`; empty clears | none | | `autonomy` | `=on` or `off` | all off | | `recovery` | `=on` or `off` | all off | diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index 00ba8a24aa..481f4cc6ba 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -107,6 +107,8 @@ pub struct ProjectProbe { pub verify_candidates: Vec, pub merge_methods: Vec, pub default_branch: String, + /// Agent runtimes on this machine's path, Claude Code first (D-45). + pub runtimes: Vec, } /// What changed outside the Factory since the last read (D-27). diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 8731a8995d..1d53efba2f 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1011,6 +1011,7 @@ impl Engine { "candidates": candidates, "merge_mode": "auto", "auto_unavailable": auto_unavailable, + "default_runtime": probe.runtimes.first().copied().unwrap_or(Runtime::Claude), "writes": writes, })); } @@ -1030,6 +1031,10 @@ impl Engine { if let Some(method) = probe.merge_methods.first() { config.merge_method = *method; } + // Installed Claude Code first, else Codex (D-45). + if let Some(runtime) = probe.runtimes.first() { + config.default_runtime = *runtime; + } let factory = Factory { id: id.clone(), project: project.clone(), diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 5859789676..a928e0faee 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -82,6 +82,17 @@ impl SharedProjects { } } +/// The runtimes a worker can start with here, in the order D-45 prefers. +fn installed_runtimes() -> Vec { + let Ok(path) = hide_platform::host::login_path() else { + return Vec::new(); + }; + [Runtime::Claude, Runtime::Codex] + .into_iter() + .filter(|runtime| hide_platform::host::find_program(&path, runtime.as_str()).is_some()) + .collect() +} + fn worktree(task: &Task) -> Result { task.worker .as_ref() @@ -344,6 +355,7 @@ impl TaskSource for SharedProjects { let mut probe = ProjectProbe { default_branch: branch, verify_candidates: verify_candidates(&path), + runtimes: installed_runtimes(), ..ProjectProbe::default() }; if remote.contains("github.com") { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 6838100a01..847873efbb 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -81,6 +81,8 @@ fn init_previews_without_writing_and_creates_once_confirmed() { }); assert_eq!(created["created"], true, "{created}"); assert_eq!(h.writes("label.create"), vec!["label.create factory"]); + let factory = h.engine.factories().next().unwrap().clone(); + assert_eq!(factory.config.default_runtime, Runtime::Claude); // The same project again shows the existing Factory (B5). let again = h.op(Command::Init { @@ -93,6 +95,27 @@ fn init_previews_without_writing_and_creates_once_confirmed() { assert_eq!(h.writes("label.create").len(), 1); } +#[test] +fn a_machine_with_only_codex_defaults_new_workers_to_codex() { + let mut h = Bench::new(false); + h.world().runtimes = vec![Runtime::Codex]; + let preview = h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: Some(MergeMode::Manual), + confirm: false, + }); + assert_eq!(preview["default_runtime"], "codex", "{preview}"); + h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: Some(MergeMode::Manual), + confirm: true, + }); + let factory = h.engine.factories().next().unwrap().clone(); + assert_eq!(factory.config.default_runtime, Runtime::Codex); +} + #[test] fn a_closed_factory_refuses_tasks_and_comes_back_with_its_records() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 2bcfd876cf..13e077546c 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -48,6 +48,8 @@ pub struct World { pub stops: Vec, pub removed: Vec, pub branches_deleted: Vec, + /// Runtimes the probe finds installed; none when empty. + pub runtimes: Vec, pub spawn_failure: Option, /// Judgments submitted and not yet answered. pub submitted: Vec, @@ -97,6 +99,7 @@ impl TaskSource for Shared { verify_candidates: vec!["cargo test".into()], merge_methods: vec![MergeMethod::Squash], default_branch: "main".into(), + runtimes: self.world().runtimes.clone(), }) } fn planned_writes(&self, probe: &ProjectProbe) -> Vec { From 093a9fa9c14502d1677ad3bdea24b25968ec0fab Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:21:26 +0900 Subject: [PATCH 17/72] Read a runtime's usage limit from the provider usage rows A runtime whose usage row or bucket shows a used-up window is parked until its reset: new starts go to the other runtime, and a worker that stops without a report while limited waits for a slot rather than stopping (B58). The engine now asks the adapter, which it never did. --- docs/factory.md | 2 +- herdr-core/src/factory.rs | 5 +- herdr-core/src/runtime/factory.rs | 83 +++++++++++++++++++++++++++++++ hide-factory/src/engine.rs | 24 +++++++++ hide-factory/tests/engine.rs | 27 ++++++++++ hide-factory/tests/support/mod.rs | 6 ++- 6 files changed, 142 insertions(+), 5 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index c58a73a2c8..52315cf47c 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -384,7 +384,7 @@ An autonomy Task is reviewed like any other, may not propose Tasks, and gates to An environment problem is not a Task's failure and is never counted against it. - **Before a start.** Starts hold while free disk at the first waiting Task's project is under `disk_floor_gb` (20 by default), or while macOS reports critical memory pressure. Warn pressure starts normally, and other systems report normal. The held Tasks show the reason and are checked again after a minute. -- **At a failure.** Only a structured signal makes a failure the environment's: no space left on the device, exit 137, a GitHub 401, 403, 429 or 5xx answer, a network error, or a Herdr connection error. The adapters read the GitHub and git signals from the command's exit code and its stderr text. Everything else is the Task's. A usage-limit signal parks a runtime until its reset time, one hour by default, and moves an unpinned Task to the other runtime, and the host adapters do not report one yet. +- **At a failure.** Only a structured signal makes a failure the environment's: no space left on the device, exit 137, a GitHub 401, 403, 429 or 5xx answer, a network error, or a Herdr connection error. The adapters read the GitHub and git signals from the command's exit code and its stderr text. Everything else is the Task's. A runtime's usage limit comes from the core's provider usage rows (the toolbar's Weekly Usage reader): a main row or bucket at 100 percent with a reset ahead parks that runtime until the reset, new starts of an unpinned Task use the other runtime, and a worker that ends its turn without a report while its runtime is limited waits for a slot instead of stopping. The rows refresh every 5 minutes only while a window shows them, so a daemon with no window open learns of a limit late. - **Code handles each signal first.** Disk full holds starts and removes the worktrees of finished Tasks and cancelled Tasks past their keep period. Out-of-memory and Herdr connection errors send the Task back to `waiting`. A rate-limit, server or network error backs the read off as above. A 401 or 403 puts a notice in the inbox once, naming `gh auth login` or `gh auth refresh -s `, and the Factory does not perform that action or retry it. - **Cascade.** Three different Tasks failing the same check or command within 30 minutes are read as the environment: each failure is taken back, the Tasks go to `waiting`, and new starts halt for 30 minutes. - **If it does not clear.** A problem that outlasts 30 minutes asks `factory_env_diagnosis` once for a cause and either one action from the closed list or an exact command with its impact. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index f1dbd90fd8..a18c6c930c 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -932,8 +932,9 @@ impl WorkerRuntime for CoreWorkers { Ok(()) } - fn usage_limited(&mut self, _runtime: AgentRuntime) -> Option { - None + fn usage_limited(&mut self, runtime: AgentRuntime) -> Option { + let core = self.runtime().ok()?; + guard(&core).factory_usage_limit(runtime.as_str(), now_ms()) } } diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index 2ebc5f6913..6edc2c5e74 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -234,7 +234,90 @@ impl Runtime { false } + /// When `provider`'s usage limit resets, while the usage rows show a + /// window used up (B58). + pub(crate) fn factory_usage_limit(&self, provider: &str, now_unix_ms: u64) -> Option { + usage_limit( + &self.snapshot.navigator.provider_usage, + provider, + now_unix_ms, + ) + } + pub(crate) fn factory_ai_settings(&self) -> Option { self.ai_settings.clone() } } + +/// The latest reset of a used-up window of `provider` still ahead of now, +/// in milliseconds: the main row or any bucket at 100 percent. +fn usage_limit( + rows: &[crate::model::ProviderUsageSnapshot], + provider: &str, + now_unix_ms: u64, +) -> Option { + let row = rows.iter().find(|row| row.provider == provider)?; + std::iter::once((row.used_percent, row.resets_at_unix_seconds)) + .chain( + row.buckets + .iter() + .map(|bucket| (bucket.used_percent, bucket.resets_at_unix_seconds)), + ) + .filter_map(|(used, resets)| match (used, resets) { + (Some(used), Some(resets)) if used >= 100.0 => Some(resets.saturating_mul(1_000)), + _ => None, + }) + .filter(|resets| *resets > now_unix_ms) + .max() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{ProviderUsageBucketSnapshot, ProviderUsageSnapshot}; + + fn row(provider: &str, used: f64, bucket: Option<(f64, u64)>) -> ProviderUsageSnapshot { + ProviderUsageSnapshot { + provider: provider.into(), + label: provider.into(), + window_minutes: 10_080, + state: "available".into(), + used_percent: Some(used), + resets_at_unix_seconds: Some(5_000), + message: None, + last_checked_at_unix_ms: None, + last_success_at_unix_ms: None, + last_error_kind: None, + buckets: bucket + .map(|(used, resets)| ProviderUsageBucketSnapshot { + label: "Current session".into(), + state: "available".into(), + used_percent: Some(used), + resets_at_unix_seconds: Some(resets), + message: None, + }) + .into_iter() + .collect(), + } + } + + #[test] + fn a_used_up_window_limits_its_runtime_until_its_reset() { + let rows = [ + row("claude", 40.0, Some((100.0, 2_000))), + row("codex", 99.0, None), + ]; + assert_eq!(usage_limit(&rows, "claude", 1_000_000), Some(2_000_000)); + assert_eq!( + usage_limit(&rows, "claude", 2_000_000), + None, + "the reset passed" + ); + assert_eq!( + usage_limit(&rows, "codex", 1_000_000), + None, + "99 percent still runs" + ); + assert_eq!(usage_limit(&[], "claude", 0), None); + } +} diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 1d53efba2f..5cb29d2658 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -4056,6 +4056,18 @@ impl Engine { // A turn that ended with no Factory report since it began (B24). let reported = last_report.is_some_and(|at| at >= rest.min(since).max(since)); if !reported && now.saturating_sub(rest) >= no_report && rest >= since { + // A worker its usage limit stopped waits for a slot + // and is not the Task's fault (B58). + if let Some(until) = self.ports.workers.usage_limited(worker.runtime) { + let mut failure = Failure::environment( + "worker", + EnvSignal::UsageLimit, + "usage limit", + ); + failure.reset_at = Some(until); + self.external_failure(&factory, Some(&id), &failure); + continue; + } self.with_task(&factory, &id, |task| { task.stop = Some(StopReason::NoReport) }); @@ -4179,6 +4191,17 @@ impl Engine { } } + /// A runtime whose usage the machine reports used up is not started + /// until its reset (B58). + fn read_usage_limits(&mut self) { + for runtime in [Runtime::Claude, Runtime::Codex] { + if let Some(until) = self.ports.workers.usage_limited(runtime) { + let entry = self.runtime_blocked.entry(runtime).or_insert(until); + *entry = (*entry).max(until); + } + } + } + fn start(&mut self, factory_id: &str, id: &str) -> bool { let Some(factory) = self.factories.get(factory_id).cloned() else { return false; @@ -4187,6 +4210,7 @@ impl Engine { return false; }; let now = self.now(); + self.read_usage_limits(); let mut runtime = task.runtime(&factory); if let Some(until) = self.runtime_blocked.get(&runtime).copied() { if until > now { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 847873efbb..532b777256 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1425,6 +1425,33 @@ fn a_usage_limit_moves_new_starts_to_the_other_runtime() { assert_eq!(runtimes[&u], Runtime::Codex); } +#[test] +fn a_worker_its_usage_limit_stopped_waits_and_the_next_start_uses_the_other_runtime() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Limited", &[]); + let now = h.world().now; + h.world() + .worker_status + .insert(t.clone(), WorkerStatus::Resting { since: now }); + h.world() + .usage_limits + .insert(Runtime::Claude, now + HOUR_MS); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + let task = h.task(&f, &t); + assert_ne!(task.state, TaskState::Stopped, "not a no-report stop"); + assert_eq!(task.failures, 0); + let u = h.ready("Next", &[]); + let spawned = h + .world() + .spawned + .iter() + .find(|s| s.task == u) + .map(|s| s.runtime); + assert_eq!(spawned, Some(Runtime::Codex)); +} + // ------------------------------------------------------------ control #[test] diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 13e077546c..742fc55e29 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -50,6 +50,8 @@ pub struct World { pub branches_deleted: Vec, /// Runtimes the probe finds installed; none when empty. pub runtimes: Vec, + /// Usage-limit resets the machine reports by runtime. + pub usage_limits: BTreeMap, pub spawn_failure: Option, /// Judgments submitted and not yet answered. pub submitted: Vec, @@ -356,8 +358,8 @@ impl WorkerRuntime for Shared { } Ok(()) } - fn usage_limited(&mut self, _runtime: Runtime) -> Option { - None + fn usage_limited(&mut self, runtime: Runtime) -> Option { + self.world().usage_limits.get(&runtime).copied() } } From 777102ceeb5af8c64ad1ebcc9df1e5092f936260 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:22:17 +0900 Subject: [PATCH 18/72] Clear a finished Task's unread mark when a person opens it An operator's show of a done Task marks it seen, as answering its notice already did; a worker reading it does not. --- docs/factory.md | 2 +- hide-factory/src/engine.rs | 8 ++++++++ hide-factory/tests/engine.rs | 23 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/factory.md b/docs/factory.md index 52315cf47c..d6f075ec8b 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -544,7 +544,7 @@ Fields are added and never renamed or removed. | `waiting_for` | For a waiting Task, the predecessors by display id, the environment hold, or `slot`; for a blocked one, `answer` or `predecessor`. | | `priority` | The Task's priority. | | `since` | When it entered its state. | -| `unread` | A completion nobody has looked at. | +| `unread` | A completion nobody has looked at: an operator's `show` of the Task, or answering a notice on it, clears it. | | `folded` | A completion older than 3 days, or a purged cancelled Task. | | `archived` | A finished Task older than 90 days. | | `failures` | Verification failures counted against it. | diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 5cb29d2658..640bb1bcf5 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -588,6 +588,14 @@ impl Engine { Command::Status { project } => self.status(project.as_deref()), Command::Show { task } => { let (factory, id) = self.resolve(role, &task)?; + // A person opening a finished Task has seen it (D-30). + if matches!(role, Role::Operator { .. }) + && self + .task(&factory, &id) + .is_some_and(|t| t.state == TaskState::Done && !t.seen) + { + self.with_task(&factory, &id, |task| task.seen = true); + } Ok(json!({"task": self.show(&factory, &id)})) } Command::Inbox => { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 532b777256..8ab7c007cd 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1452,6 +1452,29 @@ fn a_worker_its_usage_limit_stopped_waits_and_the_next_start_uses_the_other_runt assert_eq!(spawned, Some(Runtime::Codex)); } +#[test] +fn a_finished_task_is_unread_until_a_person_opens_it() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Read me", &[]); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::Done); + let unread = |h: &Bench| { + h.engine.summary().factories[0] + .columns + .iter() + .flat_map(|column| column.cards.iter()) + .find(|card| card.task == t) + .unwrap() + .unread + }; + assert!(unread(&h)); + h.as_worker(&f, &t, Command::Show { task: t.clone() }); + assert!(unread(&h), "a worker reading it is not the person"); + h.op(Command::Show { task: t.clone() }); + assert!(!unread(&h)); +} + // ------------------------------------------------------------ control #[test] From 3252ad662af37cdc06f8e67c594e15d2c4780137 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:22:36 +0900 Subject: [PATCH 19/72] List the Factory host in the resident work ledger --- docs/PERFORMANCE_TESTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/PERFORMANCE_TESTING.md b/docs/PERFORMANCE_TESTING.md index 7756f52362..36e5730c1f 100644 --- a/docs/PERFORMANCE_TESTING.md +++ b/docs/PERFORMANCE_TESTING.md @@ -69,6 +69,7 @@ The missing bounds and shutdown gaps below describe the current implementation; | Phone connection/detail: `hided/src/mobile/phone.rs`, `mobile/mod.rs` | Live ping 20 s; open pane detail refresh 1 s. | Ping/check silence and read the open detail's pane/conversation. | 2 live connections per phone, 8 queued detail frames, 16 KiB inbound frame, 10 s send bound and 45 s silent limit. | Socket close/revoke/eviction ends its loop; dropping the open detail aborts its detail task. | | Desktop daemon watch: `desktop/src/main/host.ts`, `spawn.ts` | Health recheck 2 s after each response; lost-daemon status poll 3 s after completion. | One HTTP health read or attach-only `hide status`; discovery replaces the watch. | One watch timer and one CLI child; health deadline 1.5 s, status deadline 5 s; 2 health misses mark lost. | Host quit or new discovery clears the timer; quit kills its in-flight CLI child and leaves detached daemons alone. | | GitHub project re-read and store: `runtime/projects.rs` (`reread_stale_github`, `read_sighted_pull_requests`), `labels/worker.rs` (`note_sighted`), `github.rs`, `github_store.rs` | UI-attached gate, like the other capability readers: no read and no clock comparison while no window is attached. Then a comparison on each coordinator wake; a project is asked for again 5 min after its last answer, and not while its previous ask is unanswered; one `gh` pass per changed request. A pull request a local session printed is compared on the labels path whether or not a window is attached, inside the lock section that already hands the worker the pull request times, and only when a read found one; its `gh` read still waits for the gate. | Compare the instants of at most 64 projects (`GithubClock`), advance the generation of the due ones, and let the single reader read only those; after an answer that changed, copy the snapshot under the lock and write it on the store thread. Per transcript read, the worker checks each sighting against the times it holds (no lock); per exchange that carries sightings, the runtime looks each up in the times and its remembered set, and scans the read projects' first pull request and the navigator's panes once per new address; each clock comparison also drops the remembered addresses that grew old and the waiting projects no longer read (at most 64 entries). | 64 projects, the one in front and the ones a screen named first (a count past it is logged as `projects.over_limit` when it changes); at most 32 sightings wait in the worker between two exchanges, the newest kept and the rest logged as `read.sighted_capped`; at most 64 owned addresses remembered for 15 minutes or until an answer holds them, one past it not read and logged as `read.sighted_over_limit`; one reader worker; one store thread with one pending slot, so a burst writes the latest; the file is capped at 32 MiB on read. | The store's Drop joins its thread, so a queued write lands before quit; the reader keeps its existing `BackgroundRead` ownership. | +| Factory host: `herdr-core/src/factory.rs`, `hide-factory/src/engine.rs`, `verify.rs`, `project.rs` | One thread per Core waits on its command channel for up to 2 s; a command is answered at once, and the engine ticks at most every 2 s. Without a Factory store the wake does nothing until the first `hide factory` command opens one. Due inside a tick: the outside world every `outside_read_minutes` (2), running CI checks on one commit again after 30 s, the watch and periodic checks every `watch_interval_minutes` (30). | Pump worker letters, apply finished judgments and verification runs, expire questions, probe each running worker, read the outside world when due, start Tasks into free slots, settle sleeps, deliver woken letters and publish the open Factories with their stall windows. Every subprocess (`git`, `gh`, verify commands) and every SQLite write runs on the host or verify thread; each runtime call takes `Mutex` for owned data only. | 32 queued commands, one judgment in flight with 16 waiting per Factory, one verify run with 256 queued, 16 held letters per woken worker, 256 pending CI commits, 20,000 events and 5,000 Tasks per Factory, worker slots by `max_workers` (5) per machine; kept judgment and letter records grow without a count cap (D-58, each cut at 256 KiB). | `FactoryHost::drop` shuts the engine thread down and joins it; `JudgeThread::drop` cancels the provider and joins; a verify run's child is stopped through its stop flag. | | Elapsed display clock: `web/src/components/elapsed.tsx` | One shared 1 s timer per window while subscribed. | Update the time and notify elapsed-span subscribers in memory; no core snapshot. | One timer; listener count has no fixed numeric cap and fan-out follows the mounted elapsed spans. | Last unsubscribe clears the timer; window destruction ends it. | Worktree, GitHub and disk readers also run on changed explicit requests; those requests are not extra permanent timers (`worktrees.rs`, `github.rs`, `disk.rs`). From e5157267f3d3e7fbfe4d1408d096f478fd748f49 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 05:47:42 +0900 Subject: [PATCH 20/72] Start workers off the Factory host thread A worker start waits for Herdr to make the worktree and start the agent, which held every command and worker report behind it for up to ten seconds in the live run; a report must be recorded within a second (B23). Starts now run on a starter thread with a bounded queue: the engine keeps the slot, asks again on the next tick, and a start the engine gave up on while it ran is ended when it arrives. --- docs/ARCHITECTURE.md | 2 +- docs/PERFORMANCE_TESTING.md | 2 +- docs/factory.md | 1 + herdr-core/src/factory.rs | 268 ++++++++++++++++++++++++++--------- hide-factory/src/adapters.rs | 19 +++ hide-factory/src/engine.rs | 4 +- hide-factory/tests/engine.rs | 13 ++ 7 files changed, 241 insertions(+), 68 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d84032e3a2..bea0ffe466 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -856,7 +856,7 @@ Nothing runs under the runtime mutex: conversation reads run on the worker's rea ### The Factory host -The Software Factory's engine runs on its own thread, `herdr-core-factory`, beside the delivery worker and the label analyzer, and its judgments run on a second thread, `herdr-core-factory-judge`, with a router of their own. +The Software Factory's engine runs on its own thread, `herdr-core-factory`, beside the delivery worker and the label analyzer, its judgments run on a second thread, `herdr-core-factory-judge`, with a router of their own, and worker starts, which wait for Herdr, run on a third, `factory-starts`, so a start never holds a command or a worker's report. The engine is the `hide-factory` crate, which does not know the runtime or Herdr; the host in `herdr-core/src/factory.rs` gives it a clock, the project's git and `gh`, the verify runner, and a worker port, and `runtime/factory.rs` holds the few places that take `Mutex` to read owned data or hand the core a request. No file, SQLite, network or subprocess work happens under the runtime lock, and a command reaches the engine through a bounded queue instead of a call into the runtime. `hided` routes `hide factory` over the pane-capability socket and refuses a device caller. diff --git a/docs/PERFORMANCE_TESTING.md b/docs/PERFORMANCE_TESTING.md index 36e5730c1f..fbc3ab137d 100644 --- a/docs/PERFORMANCE_TESTING.md +++ b/docs/PERFORMANCE_TESTING.md @@ -69,7 +69,7 @@ The missing bounds and shutdown gaps below describe the current implementation; | Phone connection/detail: `hided/src/mobile/phone.rs`, `mobile/mod.rs` | Live ping 20 s; open pane detail refresh 1 s. | Ping/check silence and read the open detail's pane/conversation. | 2 live connections per phone, 8 queued detail frames, 16 KiB inbound frame, 10 s send bound and 45 s silent limit. | Socket close/revoke/eviction ends its loop; dropping the open detail aborts its detail task. | | Desktop daemon watch: `desktop/src/main/host.ts`, `spawn.ts` | Health recheck 2 s after each response; lost-daemon status poll 3 s after completion. | One HTTP health read or attach-only `hide status`; discovery replaces the watch. | One watch timer and one CLI child; health deadline 1.5 s, status deadline 5 s; 2 health misses mark lost. | Host quit or new discovery clears the timer; quit kills its in-flight CLI child and leaves detached daemons alone. | | GitHub project re-read and store: `runtime/projects.rs` (`reread_stale_github`, `read_sighted_pull_requests`), `labels/worker.rs` (`note_sighted`), `github.rs`, `github_store.rs` | UI-attached gate, like the other capability readers: no read and no clock comparison while no window is attached. Then a comparison on each coordinator wake; a project is asked for again 5 min after its last answer, and not while its previous ask is unanswered; one `gh` pass per changed request. A pull request a local session printed is compared on the labels path whether or not a window is attached, inside the lock section that already hands the worker the pull request times, and only when a read found one; its `gh` read still waits for the gate. | Compare the instants of at most 64 projects (`GithubClock`), advance the generation of the due ones, and let the single reader read only those; after an answer that changed, copy the snapshot under the lock and write it on the store thread. Per transcript read, the worker checks each sighting against the times it holds (no lock); per exchange that carries sightings, the runtime looks each up in the times and its remembered set, and scans the read projects' first pull request and the navigator's panes once per new address; each clock comparison also drops the remembered addresses that grew old and the waiting projects no longer read (at most 64 entries). | 64 projects, the one in front and the ones a screen named first (a count past it is logged as `projects.over_limit` when it changes); at most 32 sightings wait in the worker between two exchanges, the newest kept and the rest logged as `read.sighted_capped`; at most 64 owned addresses remembered for 15 minutes or until an answer holds them, one past it not read and logged as `read.sighted_over_limit`; one reader worker; one store thread with one pending slot, so a burst writes the latest; the file is capped at 32 MiB on read. | The store's Drop joins its thread, so a queued write lands before quit; the reader keeps its existing `BackgroundRead` ownership. | -| Factory host: `herdr-core/src/factory.rs`, `hide-factory/src/engine.rs`, `verify.rs`, `project.rs` | One thread per Core waits on its command channel for up to 2 s; a command is answered at once, and the engine ticks at most every 2 s. Without a Factory store the wake does nothing until the first `hide factory` command opens one. Due inside a tick: the outside world every `outside_read_minutes` (2), running CI checks on one commit again after 30 s, the watch and periodic checks every `watch_interval_minutes` (30). | Pump worker letters, apply finished judgments and verification runs, expire questions, probe each running worker, read the outside world when due, start Tasks into free slots, settle sleeps, deliver woken letters and publish the open Factories with their stall windows. Every subprocess (`git`, `gh`, verify commands) and every SQLite write runs on the host or verify thread; each runtime call takes `Mutex` for owned data only. | 32 queued commands, one judgment in flight with 16 waiting per Factory, one verify run with 256 queued, 16 held letters per woken worker, 256 pending CI commits, 20,000 events and 5,000 Tasks per Factory, worker slots by `max_workers` (5) per machine; kept judgment and letter records grow without a count cap (D-58, each cut at 256 KiB). | `FactoryHost::drop` shuts the engine thread down and joins it; `JudgeThread::drop` cancels the provider and joins; a verify run's child is stopped through its stop flag. | +| Factory host: `herdr-core/src/factory.rs`, `hide-factory/src/engine.rs`, `verify.rs`, `project.rs` | One thread per Core waits on its command channel for up to 2 s; a command is answered at once, and the engine ticks at most every 2 s. Without a Factory store the wake does nothing until the first `hide factory` command opens one. Due inside a tick: the outside world every `outside_read_minutes` (2), running CI checks on one commit again after 30 s, the watch and periodic checks every `watch_interval_minutes` (30). | Pump worker letters, apply finished judgments and verification runs, expire questions, probe each running worker, read the outside world when due, start Tasks into free slots, settle sleeps, deliver woken letters and publish the open Factories with their stall windows. Every subprocess (`git`, `gh`, verify commands) and every SQLite write runs on the host or verify thread; each runtime call takes `Mutex` for owned data only. | 32 queued commands, one judgment in flight with 16 waiting per Factory, one verify run with 256 queued, one worker start with 16 queued on the starter thread, 16 held letters per woken worker, 256 pending CI commits, 20,000 events and 5,000 Tasks per Factory, worker slots by `max_workers` (5) per machine; kept judgment and letter records grow without a count cap (D-58, each cut at 256 KiB). | `FactoryHost::drop` shuts the engine thread down and joins it, and the engine thread closes the start queue and joins the starter after its running start; `JudgeThread::drop` cancels the provider and joins; a verify run's child is stopped through its stop flag. | | Elapsed display clock: `web/src/components/elapsed.tsx` | One shared 1 s timer per window while subscribed. | Update the time and notify elapsed-span subscribers in memory; no core snapshot. | One timer; listener count has no fixed numeric cap and fan-out follows the mounted elapsed spans. | Last unsubscribe clears the timer; window destruction ends it. | Worktree, GitHub and disk readers also run on changed explicit requests; those requests are not extra permanent timers (`worktrees.rs`, `github.rs`, `disk.rs`). diff --git a/docs/factory.md b/docs/factory.md index d6f075ec8b..cfb4487bdc 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -177,6 +177,7 @@ Each open Factory is a code-owned recipient named `factory:` in the A worker starts when the Task may start. The engine asks the core to spawn it through coordination, the same path as `hide agent spawn`, under the Factory's own agent record as parent. +The spawn runs on the host's starter thread, one at a time with at most 16 waiting, because it waits for Herdr to make the worktree and start the agent: the engine keeps the Task's slot, answers commands and worker reports meanwhile, and takes the started worker on the next tick. A Task cancelled or paused while its worker starts has that worker ended when it arrives. The record is registered when needed and converges on the existing one. - **Name, branch, intent.** The worker is named `factory--` and works on `factory/-` (`factory/l-` for a local issue, `factory/` without a slug). The spawn intent is `factory--`, and each earlier refused start adds `-a`, so a refused start never repeats a spawn that already failed and a retry of the same attempt converges. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index a18c6c930c..10d45562a2 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -167,6 +167,59 @@ struct WorkerState { /// Woken workers whose agent has not come back yet, with the letters it /// gets once it has: a letter needs the agent's session to address. waking: BTreeMap, + /// Worker starts, carried out on the starter thread so a start that + /// waits for Herdr never holds a command or a worker's report (B23). + starts: Starts, +} + +/// Starts by `factory/task`: queued or running, finished and not yet asked +/// for, and ones the engine gave up on while they ran. +#[derive(Default)] +struct Starts { + queue: Option>, + in_flight: BTreeSet, + done: BTreeMap>, + abandoned: BTreeSet, +} + +/// Starts waiting for the starter thread; one past it is asked again later. +const START_QUEUE_LIMIT: usize = 16; + +fn start_key(factory: &str, task: &str) -> String { + format!("{factory}/{task}") +} + +/// Runs queued worker starts one at a time until the host drops the queue. +fn run_starts( + jobs: Receiver, + runtime: Weak>, + state: Arc>, +) { + for job in jobs { + let key = start_key(&job.factory, &job.task); + let result = start_worker(&runtime, &job); + let abandoned = { + let Ok(mut state) = state.lock() else { return }; + state.starts.in_flight.remove(&key); + if state.starts.abandoned.remove(&key) { + true + } else { + state.starts.done.insert(key, result.clone()); + false + } + }; + if abandoned && let Ok(worker) = result { + let mut port = CoreWorkers { + runtime: runtime.clone(), + state: Arc::clone(&state), + }; + if let Err(failure) = port.stop(&worker) { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.abandon_failed","task":job.task,"stage":failure.stage}) + ); + } + } + } } struct Woken { @@ -189,6 +242,17 @@ fn run( stop: Arc, ) { let workers = Arc::new(Mutex::new(WorkerState::default())); + let (start_queue, start_jobs) = mpsc::sync_channel(START_QUEUE_LIMIT); + if let Ok(mut state) = workers.lock() { + state.starts.queue = Some(start_queue); + } + let starter = { + let runtime = runtime.clone(); + let state = Arc::clone(&workers); + thread::Builder::new() + .name("factory-starts".into()) + .spawn(move || run_starts(start_jobs, runtime, state)) + }; let runner_stop = Arc::clone(&stop); let mut engine: Option = None; let mut judge: Option = None; @@ -306,6 +370,15 @@ fn run( } drop(engine); drop(judge); + // Closing the queue ends the starter after the start it is running. + if let Ok(mut state) = workers.lock() { + state.starts.queue = None; + } + if let Ok(starter) = starter + && starter.join().is_err() + { + crate::diagnostic!(json!({"component":"factory","kind":"starts.join_failed"})); + } } fn owner_of(engine: &Engine, answer: &Value) -> Option { @@ -672,82 +745,68 @@ impl CoreWorkers { } impl WorkerRuntime for CoreWorkers { + /// Hands a finished start back, or queues one for the starter thread + /// and answers that it is pending. fn spawn(&mut self, request: &WorkerSpawn) -> Result { + let key = start_key(&request.factory, &request.task); + { + let mut state = self + .state + .lock() + .map_err(|_| Failure::task("worker.spawn", "state_unavailable"))?; + if let Some(result) = state.starts.done.remove(&key) { + return result; + } + if state.starts.in_flight.contains(&key) { + return Err(Failure::start_pending("worker.spawn")); + } + } let runtime = self.runtime()?; if request.runtime == hide_factory::model::Runtime::Codex && !guard(&runtime).factory_kit_read() { return Err(Failure::starting("worker.spawn", "kit_not_read")); } - let (client, authority, actor) = guard(&runtime) - .factory_delivery(&request.factory) - .map_err(|reason| Failure::task("worker.spawn", reason))?; drop(runtime); - let parent = crate::coordination::register_code_owned(&client, &authority, &actor) - .map_err(|reason| Failure::task("worker.spawn", reason))?; - let mut args = request.args.clone(); - args.push(prompt_argument(&request.prompt, &request.task)?); - let (intent, path) = match &request.resume { - Some(previous) => { - if let Some(agent) = &previous.agent { - let _ = crate::coordination::run( - client.clone(), - crate::delivery::worker::Authority { - caller: authority.caller.clone(), - context: authority.context.clone(), - }, - actor.clone(), - crate::coordination::Command::End { - id: agent.clone(), - actor: None, - }, - ); + let mut state = self + .state + .lock() + .map_err(|_| Failure::task("worker.spawn", "state_unavailable"))?; + let queue = state + .starts + .queue + .clone() + .ok_or_else(|| Failure::task("worker.spawn", "starter_stopped"))?; + match queue.try_send(request.clone()) { + Ok(()) => { + state.starts.in_flight.insert(key); + } + Err(mpsc::TrySendError::Full(_)) => {} + Err(mpsc::TrySendError::Disconnected(_)) => { + return Err(Failure::task("worker.spawn", "starter_stopped")); + } + } + Err(Failure::start_pending("worker.spawn")) + } + + fn abandon_start(&mut self, factory: &str, task: &str) { + let key = start_key(factory, task); + let finished = match self.state.lock() { + Ok(mut state) => { + if state.starts.in_flight.contains(&key) { + state.starts.abandoned.insert(key.clone()); } - ( - format!("factory-{}-{}-{}", request.factory, request.task, now_ms()), - Some(previous.worktree.clone()), - ) + state.starts.done.remove(&key) } - None if request.attempt == 0 => ( - format!("factory-{}-{}", request.factory, request.task), - None, - ), - None => ( - format!( - "factory-{}-{}-a{}", - request.factory, request.task, request.attempt - ), - None, - ), + Err(_) => None, }; - let view = crate::coordination::run( - client, - authority, - actor, - crate::coordination::Command::Spawn { - parent, - name: request.name.clone(), - intent, - kind: request.runtime.as_str().into(), - repo: request.project.clone(), - branch: request.branch.clone(), - path, - no_watch: false, - args, - }, - ) - .map_err(|reason| spawn_failure(&reason))?; - Ok(WorkerRef { - factory: request.factory.clone(), - agent: view["id"].as_str().map(str::to_owned), - name: request.name.clone(), - pane: view["pane"].as_str().map(str::to_owned), - runtime: request.runtime, - worktree: view["project"].as_str().unwrap_or_default().to_owned(), - branch: request.branch.clone(), - started_at: now_ms(), - asleep: false, - }) + if let Some(Ok(worker)) = finished + && let Err(failure) = self.stop(&worker) + { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.abandon_failed","task":task,"stage":failure.stage}) + ); + } } fn message( @@ -955,6 +1014,85 @@ fn repository_root(runner: &mut SystemRunner, checkout: &Path) -> Result>, + request: &WorkerSpawn, +) -> Result { + let runtime = runtime + .upgrade() + .ok_or_else(|| Failure::task("worker.spawn", "runtime_gone"))?; + let (client, authority, actor) = guard(&runtime) + .factory_delivery(&request.factory) + .map_err(|reason| Failure::task("worker.spawn", reason))?; + drop(runtime); + let parent = crate::coordination::register_code_owned(&client, &authority, &actor) + .map_err(|reason| Failure::task("worker.spawn", reason))?; + let mut args = request.args.clone(); + args.push(prompt_argument(&request.prompt, &request.task)?); + let (intent, path) = match &request.resume { + Some(previous) => { + if let Some(agent) = &previous.agent { + let _ = crate::coordination::run( + client.clone(), + crate::delivery::worker::Authority { + caller: authority.caller.clone(), + context: authority.context.clone(), + }, + actor.clone(), + crate::coordination::Command::End { + id: agent.clone(), + actor: None, + }, + ); + } + ( + format!("factory-{}-{}-{}", request.factory, request.task, now_ms()), + Some(previous.worktree.clone()), + ) + } + None if request.attempt == 0 => ( + format!("factory-{}-{}", request.factory, request.task), + None, + ), + None => ( + format!( + "factory-{}-{}-a{}", + request.factory, request.task, request.attempt + ), + None, + ), + }; + let view = crate::coordination::run( + client, + authority, + actor, + crate::coordination::Command::Spawn { + parent, + name: request.name.clone(), + intent, + kind: request.runtime.as_str().into(), + repo: request.project.clone(), + branch: request.branch.clone(), + path, + no_watch: false, + args, + }, + ) + .map_err(|reason| spawn_failure(&reason))?; + Ok(WorkerRef { + factory: request.factory.clone(), + agent: view["id"].as_str().map(str::to_owned), + name: request.name.clone(), + pane: view["pane"].as_str().map(str::to_owned), + runtime: request.runtime, + worktree: view["project"].as_str().unwrap_or_default().to_owned(), + branch: request.branch.clone(), + started_at: now_ms(), + asleep: false, + }) +} + fn spawn_failure(reason: &str) -> Failure { match reason { // The pane was made and the agent typed in; its session is not diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index 481f4cc6ba..292493fedb 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -32,6 +32,10 @@ pub struct Failure { /// The worker's pane exists but its agent has not shown a session yet /// (a first-run prompt, a slow start): not a failure, ask again later. pub starting: bool, + /// When a still-starting worker is asked about again; the engine's own + /// interval when absent. + #[serde(default)] + pub again_in_ms: Option, } impl Failure { @@ -43,6 +47,16 @@ impl Failure { missing_scope: None, reset_at: None, starting: false, + again_in_ms: None, + } + } + + /// A start the adapter is carrying out off the engine's thread: ask + /// again on the next tick. + pub fn start_pending(stage: &str) -> Self { + Self { + again_in_ms: Some(0), + ..Self::starting(stage, "start_in_flight") } } @@ -61,6 +75,7 @@ impl Failure { missing_scope: None, reset_at: None, starting: false, + again_in_ms: None, } } } @@ -314,6 +329,10 @@ pub enum WorkerStatus { /// Starts, messages, sleeps and wakes workers (D-14). pub trait WorkerRuntime { fn spawn(&mut self, request: &WorkerSpawn) -> Result; + /// The engine no longer wants the worker a pending start makes (the + /// Task was cancelled or paused while it started); the adapter ends it + /// when it arrives. + fn abandon_start(&mut self, _factory: &str, _task: &str) {} /// Sends a reply or wake message through the mailbox. fn message( &mut self, diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 640bb1bcf5..b32f07aed2 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -4107,6 +4107,7 @@ impl Engine { .task(&factory, &id) .is_none_or(|t| t.state != TaskState::Waiting) { + self.ports.workers.abandon_start(&factory, &id); self.starting.remove(&(factory, id)); } } @@ -4376,7 +4377,8 @@ impl Engine { now } }; - self.starting.insert(key, (first, now + START_RETRY_MS)); + let again = failure.again_in_ms.unwrap_or(START_RETRY_MS); + self.starting.insert(key, (first, now + again)); if now.saturating_sub(first) >= START_NOTICE_MS { let name = self .task(factory, id) diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 8ab7c007cd..5b162aa305 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1722,6 +1722,19 @@ fn the_inbox_orders_blocking_questions_first_then_answers_merges_and_stops() { // ------------------------------------------------------------ slow worker start +#[test] +fn a_start_carried_out_off_the_engine_is_asked_for_again_on_the_next_tick() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().spawn_failure = Some(Failure::start_pending("worker.spawn")); + let a = h.ready("A", &[]); + h.engine.tick(); + assert_eq!(h.state(&f, &a), TaskState::Waiting); + h.world().spawn_failure = None; + h.engine.tick(); + assert_eq!(h.state(&f, &a), TaskState::Running, "no 30-second wait"); +} + #[test] fn a_worker_whose_agent_has_not_started_holds_its_slot_and_is_asked_again_later() { let mut h = Bench::new(false); From a1688d93d4c670bdcfa739e6de56c6ae4dc847ac Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:03:58 +0900 Subject: [PATCH 21/72] Stop a verify run at a failed prepare step and ask again for an unnamed merge commit or a held issue past the list --- hide-factory/src/project.rs | 58 ++++++++++++++++------ hide-factory/src/verify.rs | 94 +++++++++++++++++++++++++++--------- hide-factory/tests/github.rs | 73 +++++++++++++++++++++++++++- 3 files changed, 187 insertions(+), 38 deletions(-) diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index a928e0faee..c22214b42d 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -609,12 +609,41 @@ impl TaskSource for SharedProjects { _ => None, }) .collect(); - let labelled: BTreeMap = issues + let mut labelled: BTreeMap = issues .as_array() .into_iter() .flatten() - .filter_map(|issue| issue["number"].as_u64().map(|n| (n, issue))) + .filter_map(|issue| issue["number"].as_u64().map(|n| (n, issue.clone()))) .collect(); + // The list holds the newest issues only, so a held issue missing from + // it is asked for by number before its label counts as removed. + for (number, task) in &held { + if labelled.contains_key(number) + || matches!(task.state, TaskState::Done | TaskState::Cancelled) + { + continue; + } + let issue = this.gh_json( + "github.observe", + &[ + "issue", + "view", + &number.to_string(), + "--repo", + &repo, + "--json", + "number,title,body,state,labels", + ], + )?; + let still = issue["labels"] + .as_array() + .into_iter() + .flatten() + .any(|label| label["name"].as_str() == Some(LABEL)); + if still { + labelled.insert(*number, issue); + } + } for (number, issue) in &labelled { let issue_ref = IssueRef::Github { number: *number }; let body = issue["body"].as_str().unwrap_or_default(); @@ -994,10 +1023,7 @@ impl MergeTarget for SharedProjects { .ok_or_else(|| Failure::task("github.merge", "the Task has no pull request"))?; let view = this.pr_view(factory, pr.number)?; if view["state"].as_str() == Some("MERGED") { - return Ok(view["mergeCommit"]["oid"] - .as_str() - .unwrap_or_default() - .to_owned()); + return merge_commit("github.merge", &view); } // Pinned to the commit that passed verification: a push after // it makes GitHub refuse the merge (B39). @@ -1028,10 +1054,7 @@ impl MergeTarget for SharedProjects { ], )?; let view = this.pr_view(factory, pr.number)?; - Ok(view["mergeCommit"]["oid"] - .as_str() - .unwrap_or_default() - .to_owned()) + merge_commit("github.merge", &view) } } } @@ -1206,10 +1229,7 @@ impl MergeTarget for SharedProjects { )?; } let view = this.pr_view(factory, number)?; - Ok(view["mergeCommit"]["oid"] - .as_str() - .unwrap_or_default() - .to_owned()) + merge_commit("github.revert_merge", &view) } _ => { let project = PathBuf::from(&factory.project); @@ -1322,6 +1342,16 @@ impl Verifier for SharedProjects { } /// `prefix/**`, `*.ext` or an exact path. +/// The merge commit of a merged pull request. GitHub can answer a merge +/// before it names the commit (a merge queue, a lagging read): that is asked +/// again rather than recorded as an empty commit. +fn merge_commit(stage: &str, view: &Value) -> Result { + match view["mergeCommit"]["oid"].as_str() { + Some(oid) if !oid.is_empty() => Ok(oid.to_owned()), + _ => Err(Failure::task(stage, "merge commit not named yet")), + } +} + fn path_matches(pattern: &str, path: &str) -> bool { if let Some(prefix) = pattern.strip_suffix("/**") { return path.starts_with(&format!("{prefix}/")); diff --git a/hide-factory/src/verify.rs b/hide-factory/src/verify.rs index d86fe71557..86161cd15f 100644 --- a/hide-factory/src/verify.rs +++ b/hide-factory/src/verify.rs @@ -176,28 +176,11 @@ impl VerifyRunner { let Some(job) = self.queue.pop_front() else { return; }; - for step in &job.prepare { - let args: Vec<&str> = step.args.iter().map(String::as_str).collect(); - if let Err(failure) = checked( - runner, - "verify.prepare", - &step.program, - &args, - Some(&step.cwd), - ) { - let poll = match failure.signal { - Some(signal) => VerifyPoll::Environment { - signal, - check: format!("{} {}", step.program, step.args.join(" ")), - }, - None => VerifyPoll::Failed { - check: format!("{} {}", step.program, step.args.join(" ")), - link: failure.detail, - }, - }; - self.finish(&job.id, poll); - continue; - } + // A failed step ends the run: the commands never run in a tree + // the step did not prepare. + if let Err(poll) = prepare(runner, &job.prepare) { + self.finish(&job.id, poll); + continue; } if job.commands.is_empty() { self.finish(&job.id, VerifyPoll::Passed); @@ -283,6 +266,30 @@ impl VerifyRunner { } } +/// Runs the steps in order and stops at the first failure. +fn prepare(runner: &mut dyn Runner, steps: &[Prepare]) -> Result<(), VerifyPoll> { + for step in steps { + let args: Vec<&str> = step.args.iter().map(String::as_str).collect(); + if let Err(failure) = checked( + runner, + "verify.prepare", + &step.program, + &args, + Some(&step.cwd), + ) { + let check = format!("{} {}", step.program, step.args.join(" ")); + return Err(match failure.signal { + Some(signal) => VerifyPoll::Environment { signal, check }, + None => VerifyPoll::Failed { + check, + link: failure.detail, + }, + }); + } + } + Ok(()) +} + /// A failed command: exit 137 or a full disk in its output is the /// environment's; anything else is the Task's. fn read_failure(command: &str, code: Option, log: &Path) -> VerifyPoll { @@ -465,6 +472,49 @@ mod tests { } } + struct FailingRunner; + impl Runner for FailingRunner { + fn run( + &mut self, + _program: &str, + _args: &[String], + _cwd: Option<&Path>, + ) -> Result { + Ok(Output { + code: Some(1), + stdout: String::new(), + stderr: "error: your local changes would be overwritten".into(), + }) + } + } + + #[test] + fn a_failed_prepare_step_ends_the_run_before_any_command() { + let dir = tempfile::tempdir().unwrap(); + let mut runner = VerifyRunner::new(dir.path().join("logs")); + let step = Prepare { + program: "git".into(), + args: vec!["checkout".into(), "--detach".into(), "abc".into()], + cwd: dir.path().to_owned(), + }; + for (id, commands) in [("with", vec!["touch ran.txt"]), ("without", Vec::new())] { + let mut job = job(id, dir.path(), &commands, Duration::from_secs(60)); + job.prepare = vec![step.clone()]; + runner.submit(job).unwrap(); + match runner.poll(&mut FailingRunner, id) { + VerifyPoll::Failed { check, .. } => assert_eq!(check, "git checkout --detach abc"), + other => panic!("{other:?}"), + } + assert!(!runner.busy(), "nothing runs after the failed step"); + // The failure stays the answer. + assert!(matches!( + runner.poll(&mut FailingRunner, id), + VerifyPoll::Failed { .. } + )); + } + assert!(!dir.path().join("ran.txt").exists()); + } + #[test] fn exit_137_is_the_environment() { let dir = tempfile::tempdir().unwrap(); diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index 4779cea3c6..ab2694df72 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -22,6 +22,10 @@ struct Hub { checks: Vec, check_reads: usize, fail_next: Option, + /// GitHub answers the merge before it names the merge commit. + commit_later: bool, + /// The most issues one list answers, newest first. + list_cap: Option, } #[derive(Clone, Default)] @@ -75,9 +79,17 @@ impl Runner for FakeGh { ok(Value::Array(found).to_string()) } ["issue", "list", ..] => { - let all: Vec = hub.issues.iter().map(|(n, (title, body, state))| json!({"number": n, "title": title, "body": body, "state": state})).collect(); + let all: Vec = hub.issues.iter().rev().take(hub.list_cap.unwrap_or(usize::MAX)).map(|(n, (title, body, state))| json!({"number": n, "title": title, "body": body, "state": state})).collect(); ok(Value::Array(all).to_string()) } + ["issue", "view", number, ..] => { + let number: u64 = number.parse().unwrap(); + ok(match hub.issues.get(&number) { + Some((title, body, state)) => json!({"number": number, "title": title, "body": body, "state": state, "labels": [{"name": "factory"}]}), + None => json!({"number": number, "title": "", "body": "", "state": "OPEN", "labels": []}), + } + .to_string()) + } ["issue", "create", ..] => { hub.next += 1; let number = hub.next; @@ -106,9 +118,10 @@ impl Runner for FakeGh { ["pr", "merge", number, ..] => { let number: u64 = number.parse().unwrap(); assert_eq!(flag(args, "--match-head-commit"), Some("headsha"), "the head SHA is pinned"); + let later = hub.commit_later; let pr = hub.prs.get_mut(&number).unwrap(); pr["state"] = json!("MERGED"); - pr["mergeCommit"] = json!({"oid": format!("merge{number}")}); + pr["mergeCommit"] = if later { Value::Null } else { json!({"oid": format!("merge{number}")}) }; hub.writes.push(format!("pr merge {number}")); ok("") } @@ -246,6 +259,33 @@ fn each_github_write_happens_once_when_retried() { ); } +#[test] +fn a_merge_without_its_commit_yet_is_asked_again_and_not_merged_twice() { + let gh = FakeGh::default(); + gh.0.lock().unwrap().commit_later = true; + let mut p = projects(&gh); + let factory = factory(); + let mut t = task("T-1", Some(1)); + t.pr = p.open_pr(&factory, &t, "body").unwrap(); + let number = t.pr.as_ref().unwrap().number; + let failure = p.merge(&factory, &t, MergeMethod::Merge).unwrap_err(); + assert_eq!(failure.stage, "github.merge"); + assert!( + p.merge(&factory, &t, MergeMethod::Merge).is_err(), + "still unnamed" + ); + gh.0.lock().unwrap().prs.get_mut(&number).unwrap()["mergeCommit"] = json!({"oid": "m1"}); + assert_eq!(p.merge(&factory, &t, MergeMethod::Merge).unwrap(), "m1"); + let merges = + gh.0.lock() + .unwrap() + .writes + .iter() + .filter(|w| w.starts_with("pr merge")) + .count(); + assert_eq!(merges, 1, "the merge is made once"); +} + #[test] fn required_checks_decide_and_a_cancelled_run_is_asked_again() { let gh = FakeGh::default(); @@ -356,6 +396,35 @@ fn outside_work_is_read_from_issues_and_closing_pull_requests() { ); } +#[test] +fn a_held_issue_past_the_list_limit_keeps_its_task() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + { + let mut hub = gh.0.lock().unwrap(); + hub.issues.insert( + 1, + ( + "Old".into(), + "".into(), + "OPEN".into(), + ), + ); + hub.issues + .insert(2, ("Newer".into(), "later".into(), "OPEN".into())); + hub.list_cap = Some(1); + } + let held = task("T-1", Some(1)); + let events = p.observe(&factory, &[&held]).unwrap(); + assert!( + !events.contains(&OutsideEvent::LabelRemoved { + issue: IssueRef::Github { number: 1 } + }), + "{events:?}" + ); +} + #[test] fn a_github_failure_carries_its_signal() { let gh = FakeGh::default(); From 1758af3441947cf7ee0c9a346bc65e1806494dd2 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:05:44 +0900 Subject: [PATCH 22/72] Keep a finished Task's worker a worker and put a stopped worker to sleep --- docs/factory.md | 4 ++- herdr-core/src/factory.rs | 11 ++++--- hide-factory/src/engine.rs | 60 +++++++++++++++--------------------- hide-factory/tests/engine.rs | 18 +++++++++++ 4 files changed, 53 insertions(+), 40 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index cfb4487bdc..118aedf1b5 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -138,7 +138,8 @@ Adding a dependency to a running Task whose predecessor is unmerged puts the Tas ## Roles Each command runs with a role the engine decides from its own store, never from the caller's claim or a file. -A caller is a worker when its pane is the pane of a live Task's worker, or when its working folder is inside a live Task's worktree; a `cancelled` or `done` Task has no worker. +A caller is a worker when its pane is the pane of a Task's worker, or when its working folder is inside a Task's worktree. +A `cancelled` or `done` Task's worker stays a worker, so its pane never gains an operator's commands, and the Task's state refuses its reports; a live Task wins when a pane or folder was reused. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. @@ -196,6 +197,7 @@ A start that fails with an environment signal leaves the Task `waiting` and is h A Task's worker is put to sleep when the Task blocks, pauses, goes to `verifying`, or waits for a slot, and woken when it runs again. Sleep goes through agent sleep and is deferred until the agent's turn ends; a worker that never slept is sent the message instead. +Stopping a worker, when its Task is cancelled or an outside pull request takes it over, ends its ledger record at once and puts its agent to sleep the same way, so the pane and session stay for `revive`. A wake restarts the agent in the same pane and session. Letters for a woken worker are held, at most 16, until its agent is back, and are dropped to the diagnostic log after 10 minutes. A retried Task, or a worker whose pane is gone, spawns again in the same worktree and session with a fresh intent. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index 10d45562a2..40d51f6e6f 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -921,14 +921,17 @@ impl WorkerRuntime for CoreWorkers { } fn stop(&mut self, worker: &WorkerRef) -> Result<(), Failure> { - let Some(agent) = &worker.agent else { - return Ok(()); - }; + // The agent ends through agent sleep once its turn ends, so its pane + // and session stay for a revive (B50, B55); the ledger record ends now. if let Some(pane) = &worker.pane && let Ok(mut state) = self.state.lock() { - state.pending_sleep.remove(pane); + state.pending_sleep.insert(pane.clone()); } + let agent = worker + .agent + .as_ref() + .ok_or_else(|| Failure::task("worker.stop", "worker has no agent"))?; let runtime = self.runtime()?; let (client, authority, actor) = guard(&runtime) .factory_delivery(&worker.factory) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index b32f07aed2..16720d92aa 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -288,41 +288,24 @@ impl Engine { } /// The role of a caller (D-33): a pane the Factory spawned, or a cwd - /// inside a Factory worktree, is a worker of that Task. + /// inside a Factory worktree, is a worker of that Task. A finished or + /// cancelled Task's worker stays a worker, so its pane never gains the + /// operator's commands; a live Task wins when a pane or folder was reused. pub fn role_for(&self, pane: Option<&str>, cwd: Option<&str>) -> Option<(String, String)> { - for task in self.all_tasks() { - let Some(worker) = &task.worker else { continue }; - if matches!(task.state, TaskState::Cancelled | TaskState::Done) { - continue; - } + let bound = |task: &&Task| { + let Some(worker) = &task.worker else { + return false; + }; if pane.is_some() && worker.pane.as_deref() == pane { - return Some((task.factory.clone(), task.id.clone())); - } - if let Some(cwd) = cwd { - let root = Path::new(&worker.worktree); - if Path::new(cwd).starts_with(root) { - return Some((task.factory.clone(), task.id.clone())); - } + return true; } - } - None - } - - /// Worker panes and worktrees, for the daemon's role registry. - pub fn worker_bindings(&self) -> Vec<(String, String, Option, String)> { - self.all_tasks() - .filter(|task| !matches!(task.state, TaskState::Cancelled | TaskState::Done)) - .filter_map(|task| { - task.worker.as_ref().map(|worker| { - ( - task.factory.clone(), - task.id.clone(), - worker.pane.clone(), - worker.worktree.clone(), - ) - }) - }) - .collect() + !worker.worktree.is_empty() + && cwd.is_some_and(|cwd| Path::new(cwd).starts_with(&worker.worktree)) + }; + let finished = |task: &&Task| matches!(task.state, TaskState::Cancelled | TaskState::Done); + let live = self.all_tasks().filter(|t| !finished(t)).find(&bound); + live.or_else(|| self.all_tasks().filter(&finished).find(&bound)) + .map(|task| (task.factory.clone(), task.id.clone())) } pub fn factory_for_project(&self, project: &str) -> Option<&Factory> { @@ -3022,11 +3005,18 @@ impl Engine { /// A finished Task's worker ends and its worktree goes; the branch stays /// with the merge. A failure is logged and the disk recovery retries it. + /// Stops a worker; a refusal is recorded against its Task. + fn stop_worker(&mut self, factory_id: &str, id: &str, worker: &WorkerRef) { + if let Err(failure) = self.ports.workers.stop(worker) { + self.external_failure(factory_id, Some(id), &failure); + } + } + fn release_worker(&mut self, factory_id: &str, id: &str) { let Some(worker) = self.task(factory_id, id).and_then(|t| t.worker.clone()) else { return; }; - let _ = self.ports.workers.stop(&worker); + self.stop_worker(factory_id, id, &worker); match self.ports.workers.remove_worktree(&worker, false) { Ok(()) => { self.with_task(factory_id, id, |t| t.purged = true); @@ -3384,7 +3374,7 @@ impl Engine { let now = self.now(); self.cancel_verification(factory_id, id); if let Some(worker) = &task.worker { - let _ = self.ports.workers.stop(worker); + self.stop_worker(factory_id, id, worker); } if let (Some(factory), Some(pr)) = (self.factories.get(factory_id).cloned(), &task.pr) && pr.by_factory @@ -4486,7 +4476,7 @@ impl Engine { // Stop the worker; the worktree stays 7 days (B50). self.cancel_verification(factory_id, &task.id); if let Some(worker) = &task.worker { - let _ = self.ports.workers.stop(worker); + self.stop_worker(factory_id, &task.id, worker); } self.with_task(factory_id, &task.id, |t| { t.cancelled_at = Some(t.updated_at); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 5b162aa305..028caa626c 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -800,6 +800,24 @@ fn a_plain_letter_from_a_harness_becomes_a_blocking_question_once() { assert_eq!(refused["reason"], "sender_not_a_worker"); } +#[test] +fn a_cancelled_task_s_worker_stays_a_worker_and_is_stopped() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Mine", &[]); + let worker = h.task(&f, &t).worker.unwrap(); + let pane = worker.pane.clone().unwrap(); + let answer = h.op(Command::Cancel { task: t.clone() }); + assert_eq!(answer["ok"], true, "{answer}"); + assert_eq!(h.task(&f, &t).state, TaskState::Cancelled); + assert!(h.world().stops.contains(&t), "the worker is stopped"); + // Its pane and its folder still name the Task, never an operator. + let bound = Some((f.clone(), t.clone())); + assert_eq!(h.engine.role_for(Some(&pane), None), bound); + let inside = format!("{}/src", worker.worktree); + assert_eq!(h.engine.role_for(None, Some(&inside)), bound); +} + #[test] fn a_worker_cannot_act_as_a_person() { let mut h = Bench::new(false); From f6c8923c5704675d117fc400194c03ddc157b9fb Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:08:15 +0900 Subject: [PATCH 23/72] Keep an outside-taken Task's worktree for the keep period from the takeover --- docs/factory.md | 5 ++-- hide-factory/src/engine.rs | 54 ++++++++++++++++++++++++------------ hide-factory/tests/engine.rs | 46 ++++++++++++++++++++++++++---- 3 files changed, 80 insertions(+), 25 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 118aedf1b5..a053923e81 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -60,7 +60,8 @@ The engine opens the store when a store file already exists at start, or on the A run's log keeps only its last 1 MiB when the run ends. The Factory deletes no Task, question, decision, discovery, attempt or attachment. -It removes a worker's worktree and pane when the Task is done and main verification has passed or an outside pull request merged it, when a cancelled Task or one an outside pull request took passes its keep period, and, only under disk pressure, for finished Tasks. +It removes a worker's worktree and pane when the Task is done and main verification has passed, when a cancelled Task or one an outside pull request took passes its keep period, and, only under disk pressure, for finished Tasks. +An outside pull request that takes a Task stops its worker and starts the keep period at that moment; the worktree waits the period out even when that pull request merges and the Task is done, because the worker's own work was never merged. The removal runs from the repository's main checkout through the host's guarded worktree removal. A finished Task keeps its branch; a cancelled or outside Task loses its local branch with its worktree, and the Factory never deletes a remote branch. A finished Task folds out of the board's Done column after 3 days and out of every list after 90 days; its page still opens. @@ -331,7 +332,7 @@ A failed read backs off 1, 2, 5, 15 and then 30 minutes on a rate-limit, server | What the Factory sees | What it does | | --- | --- | | A pull request the Factory did not open closes a Task's issue, and it is open | The Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | -| That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. | +| That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. A stopped worker's worktree still waits out its keep period. | | The issue closes with no pull request, or the `factory` label is removed | The Task is cancelled with a notice, kept for the keep period. | | A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | | A person labels an issue the Factory does not hold | A new Task is drafted from the issue, and a person confirms its card in the inbox before it is Ready. The body is not edited. | diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 16720d92aa..b0d5fc28bd 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -3012,6 +3012,25 @@ impl Engine { } } + /// An outside pull request takes the Task over (D-27, B50): a worker is + /// stopped and its worktree kept for the keep period from now, so the + /// work it had not reported survives until then. + fn follow_outside(&mut self, factory_id: &str, task: &Task) { + let Some(worker) = &task.worker else { return }; + if task.purged { + return; + } + self.stop_worker(factory_id, &task.id, worker); + let now = self.now(); + self.with_task(factory_id, &task.id, |t| { + t.cancelled_at = Some(now); + t.cancelled_from = Some(t.state); + if let Some(w) = &mut t.worker { + w.asleep = true; + } + }); + } + fn release_worker(&mut self, factory_id: &str, id: &str) { let Some(worker) = self.task(factory_id, id).and_then(|t| t.worker.clone()) else { return; @@ -4463,8 +4482,8 @@ impl Engine { json!({"pr": pr}), ); self.cancel_verification(factory_id, &task.id); + self.follow_outside(factory_id, &task); self.set_state(factory_id, &task.id, TaskState::Done); - self.release_worker(factory_id, &task.id); } TaskState::Outside => {} TaskState::Running @@ -4473,18 +4492,8 @@ impl Engine { | TaskState::Paused | TaskState::MergeWaiting | TaskState::Stopped => { - // Stop the worker; the worktree stays 7 days (B50). self.cancel_verification(factory_id, &task.id); - if let Some(worker) = &task.worker { - self.stop_worker(factory_id, &task.id, worker); - } - self.with_task(factory_id, &task.id, |t| { - t.cancelled_at = Some(t.updated_at); - t.cancelled_from = Some(t.state); - if let Some(w) = &mut t.worker { - w.asleep = true; - } - }); + self.follow_outside(factory_id, &task); self.set_state(factory_id, &task.id, TaskState::Outside); self.notice(factory_id, &task.id, &format!("밖의 PR이 이 Task의 issue를 닫습니다: {url}. worker를 멈췄고 worktree는 7일 남습니다. 되살리려면 hide factory revive {}", task.display_id())); } @@ -4505,9 +4514,9 @@ impl Engine { return; } if task.state == TaskState::Outside { - // Its outside PR closed the issue: follow it to done. + // Its outside PR closed the issue: follow it to done; the + // stopped worker's worktree keeps its period (B50). self.set_state(factory_id, &task.id, TaskState::Done); - self.release_worker(factory_id, &task.id); return; } self.cancel(factory_id, &task.id); @@ -4917,8 +4926,8 @@ impl Engine { .factories .get(&t.factory) .map_or(7 * DAY_MS, |f| f.config.cancel_keep_ms); - t.state == TaskState::Done - || (matches!(t.state, TaskState::Cancelled | TaskState::Outside) + (t.state == TaskState::Done && t.cancelled_at.is_none()) + || (kept_for_revive(t) && t.cancelled_at .is_some_and(|at| now.saturating_sub(at) > keep)) }) @@ -5233,7 +5242,7 @@ impl Engine { let now = self.now(); let expired: Vec<(String, String)> = self .all_tasks() - .filter(|t| matches!(t.state, TaskState::Cancelled | TaskState::Outside) && !t.purged) + .filter(|t| kept_for_revive(t) && !t.purged) .filter(|t| { let keep = self .factories @@ -5257,6 +5266,17 @@ impl Engine { } } +/// A Task whose worktree waits out the keep period: cancelled, taken over +/// by an outside pull request, or done through one (its worker's own work was +/// never merged). +fn kept_for_revive(task: &Task) -> bool { + match task.state { + TaskState::Cancelled | TaskState::Outside => true, + TaskState::Done => task.cancelled_at.is_some(), + _ => false, + } +} + fn with_letter(command: Command, letter: &str) -> Option { let letter = Some(letter.to_owned()); Some(match command { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 028caa626c..87985c8284 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1320,13 +1320,47 @@ fn an_outside_pull_request_takes_a_running_task_and_its_merge_finishes_it() { h.advance(3 * MINUTE_MS); h.engine.tick(); assert_eq!(h.state(&f, &t), TaskState::Done); - assert_eq!( - h.world().removed, - vec![t.clone()], - "its merge frees the worktree" - ); - assert!(h.world().branches_deleted.is_empty()); tick_until(&mut h, &f, &after, TaskState::Running); + // The stopped worker's own work was never merged: its worktree keeps the + // keep period from the takeover, not from the Task's last change. + h.advance(6 * DAY_MS); + h.engine.tick(); + assert!(h.world().removed.is_empty(), "the worktree stays 7 days"); + h.advance(2 * DAY_MS); + h.engine.tick(); + assert_eq!(h.world().removed, vec![t.clone()]); +} + +#[test] +fn a_task_waiting_long_on_a_person_keeps_its_worktree_after_an_outside_pull_request() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Waits", &[]); + let pane = h.task(&f, &t).worker.unwrap().pane.unwrap(); + h.engine.letter(Inbound { + id: "letter-1".into(), + factory: f.clone(), + sender_pane: pane, + kind: "block".into(), + body: "Which license?".into(), + }); + assert_eq!(h.state(&f, &t), TaskState::Blocked); + h.advance(9 * DAY_MS); + let issue = h.task(&f, &t).issue.unwrap(); + h.world().outside.push_back(OutsideEvent::ClosingPr { + issue, + pr: 56, + url: "pr/56".into(), + merged: false, + }); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Outside); + h.advance(6 * DAY_MS); + h.engine.tick(); + assert!(h.world().removed.is_empty(), "{:?}", h.world().removed); + let revived = h.op(Command::Revive { task: t.clone() }); + assert_eq!(revived["ok"], true, "{revived}"); } #[test] From 9be5b03c71094a93ebba77447d6876e24a803354 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:12:15 +0900 Subject: [PATCH 24/72] Send a refused merge to a person, recheck before a manual merge, and read a pending or broken main at a paced interval --- docs/factory.md | 10 +- hide-factory/src/engine.rs | 210 +++++++++++++++++++++++------- hide-factory/src/model.rs | 2 + hide-factory/src/project.rs | 7 +- hide-factory/tests/engine.rs | 87 +++++++++++++ hide-factory/tests/support/mod.rs | 19 +++ 6 files changed, 280 insertions(+), 55 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index a053923e81..b1f22107c4 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -302,12 +302,15 @@ A gate sends an `auto` Task to `merge_waiting` and appears in the Task page and | `check_failed` | A judgment could not run. | | `autonomy_diff` | An autonomy Task changed more than 200 lines. | | `dirty_main` | A local merge finds the main checkout uncommitted or off the default branch. | +| `merge_refused` | GitHub or git refused the merge for a reason that is not the environment's, such as a branch policy; the reason is in the Task's events and in the answer to a person's `merge`. | A review by an agent alone never merges. -A person's `merge` runs the same merge at once; `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. +A person's `merge` runs merge-tree and the quick check again on the latest main, then the same merge at once; a conflict sends the worker to rebase and a failed quick check counts as a verification failure. +A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again. +`request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. **GitHub.** The merge is `gh pr merge` with the Factory's `merge_method` and `--match-head-commit` set to the pull request's head as read just before the merge, and a pull request already merged returns its merge commit. -`init` picks the first merge method the repository allows, in the order squash, merge, rebase, and `config` changes it. +`init` picks the first merge method the repository allows, in the order merge, squash, rebase, and `config` changes it. **Local.** The Factory merges into the project's primary checkout with `git merge --no-ff`, only while that checkout is on the default branch with no uncommitted tracked changes. Otherwise the Task stays in `merge_waiting` with `dirty_main` until it is clean. @@ -316,6 +319,7 @@ Main verification is the chosen verification on that commit: the push run's chec A green result, or no main verification, makes the Task `done` and removes its worker, pane and worktree. A red result breaks main and stops auto merge; manual merges still run. +While main is broken an `auto` Task that passed verification waits in `verifying` without merge-tree or quick-check reads, unless a person's gate sends it to `merge_waiting`; main is read again every 30 seconds. If the broken commit is among the Factory's own merges since the last green, the Factory finds the first failing one, asking again for runs that were skipped or cancelled, and reverts that merge alone. On GitHub the revert is a pull request from `factory/revert-`, which the Factory force-pushes, checks and merges with `--merge`; locally it is a revert commit made in `factory-main` and fast-forwarded into the primary checkout. A revert whose verification passes is merged on its own, and the original Task becomes `relanding`: it runs again in the same worktree and session on the latest main, with a new pull request. @@ -337,7 +341,7 @@ A failed read backs off 1, 2, 5, 15 and then 30 minutes on a rate-limit, server | A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | | A person labels an issue the Factory does not hold | A new Task is drafted from the issue, and a person confirms its card in the inbox before it is Ready. The body is not edited. | | A finished Task's issue reopens | A notice only. | -| A push to main the Factory did not make | Main verification runs, and a red result takes the outside-push path above. | +| A push to main the Factory did not make | Main verification runs; while its checks are still running the head is read again every 30 seconds, and a red result takes the outside-push path above. | A pull request or issue the Factory does not hold is ignored. Cancelling a Task closes its open Factory pull request, and reviving reopens it. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index b0d5fc28bd..c871df824e 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -63,6 +63,11 @@ const ENV_RECHECK_MS: u64 = MINUTE_MS; /// How often a worker whose agent has not shown a session is asked again, /// and when the person is told to look at its pane. const START_RETRY_MS: u64 = 30_000; +/// How often a broken main, or a main head with checks still running, is +/// read again. +const MAIN_CHECK_EVERY_MS: u64 = 30_000; +/// When a merge that GitHub answered without its commit is asked again. +pub const MERGE_COMMIT_AGAIN_MS: u64 = 30_000; const START_NOTICE_MS: u64 = 10 * MINUTE_MS; struct VerifyState { @@ -121,6 +126,12 @@ pub struct Engine { reverts: BTreeMap, /// Main heads already checked per Factory. main_seen: BTreeMap, + /// Factories whose main head has a check still running: read again at + /// the paced interval until it finishes (B47). + main_pending: BTreeSet, + /// When each Factory's main was last read, to pace a broken or pending + /// main to [`MAIN_CHECK_EVERY_MS`]. + main_checked_at: BTreeMap, processed: BTreeSet, processed_order: Vec, /// Recent environment and Task failures the cascade rules read. @@ -180,6 +191,8 @@ impl Engine { checks_running: BTreeMap::new(), reverts: BTreeMap::new(), main_seen: BTreeMap::new(), + main_pending: BTreeSet::new(), + main_checked_at: BTreeMap::new(), processed: BTreeSet::new(), processed_order: Vec::new(), env_failures: Vec::new(), @@ -2789,23 +2802,25 @@ impl Engine { return; } let mode = task.merge_mode(&factory); + if factory.main.broken && mode == MergeMode::Auto { + // Auto merge is stopped until main is green again (B44, D-47): + // a person's gate still shows now, and nothing is read per tick. + let mut gates = self.person_gates(&factory, &task, mode); + if waits_on_answer(&task) { + gates.push(Gate::OpenQuestion); + } + if !gates.is_empty() { + self.with_task(factory_id, id, |task| task.gates = gates.clone()); + self.set_state(factory_id, id, TaskState::MergeWaiting); + } + return; + } // Merge-tree and the quick check, in seconds (B38). if factory.config.verification.exists() || factory.source == SourceKind::Local { match self.ports.merge.premerge(&factory, &task) { Ok(PreMerge::Clean) => {} Ok(PreMerge::Conflict { files }) => { - // A rebase is not a verification failure. - self.record( - factory_id, - Some(id), - "merge.conflict", - json!({"files": files.len()}), - ); - self.set_state(factory_id, id, TaskState::Running); - self.wake(factory_id, id, &format!( - "Factory: 최신 main과 충돌합니다 ({}). main 위로 rebase한 뒤 다시 hide factory done 하세요. 이 일은 검증 실패로 세지 않습니다.", - files.join(", ") - )); + self.send_to_rebase(factory_id, id, &files); return; } Ok(PreMerge::QuickCheckFailed { check }) => { @@ -2845,21 +2860,7 @@ impl Engine { .copied() .filter(|g| matches!(g, Gate::RiskPath | Gate::CheckFailed)) .collect(); - if task.human.review_directly { - gates.push(Gate::ReviewDirectly); - } - if task.scope_approved { - gates.push(Gate::ApprovedScopeChange); - } - if task.breaking { - gates.push(Gate::BreakingChange); - } - if !factory.config.verification.exists() { - gates.push(Gate::NoVerification); - } - if mode == MergeMode::Manual { - gates.push(Gate::ManualMode); - } + gates.extend(self.person_gates(&factory, &task, mode)); if task.autonomy.is_some() { let lines = self .ports @@ -2870,12 +2871,7 @@ impl Engine { gates.push(Gate::AutonomyDiff); } } - if task.open_questions().any(|q| { - !matches!( - q.kind, - QuestionKind::Notice | QuestionKind::Default | QuestionKind::ScopeChange { .. } - ) - }) { + if waits_on_answer(&task) { gates.push(Gate::OpenQuestion); } gates.dedup(); @@ -2885,15 +2881,61 @@ impl Engine { return; } if factory.main.broken { - // Auto merge is stopped until main is green again (B44, D-47). + // A manual Task always has its gate; nothing merges on red. return; } - self.merge_now(factory_id, id); + let _ = self.merge_now(factory_id, id); + } + + /// A conflict with main sends the worker to rebase; it is not a + /// verification failure (B40). + fn send_to_rebase(&mut self, factory_id: &str, id: &str, files: &[String]) { + self.record( + factory_id, + Some(id), + "merge.conflict", + json!({"files": files.len()}), + ); + self.with_task(factory_id, id, |task| task.gates.clear()); + self.set_state(factory_id, id, TaskState::Running); + self.wake(factory_id, id, &format!( + "Factory: 최신 main과 충돌합니다 ({}). main 위로 rebase한 뒤 다시 hide factory done 하세요. 이 일은 검증 실패로 세지 않습니다.", + files.join(", ") + )); + } + + /// The gates a person decides that need no git read (D-25). + fn person_gates(&self, factory: &Factory, task: &Task, mode: MergeMode) -> Vec { + let mut gates = Vec::new(); + if task.human.review_directly { + gates.push(Gate::ReviewDirectly); + } + if task.scope_approved { + gates.push(Gate::ApprovedScopeChange); + } + if task.breaking { + gates.push(Gate::BreakingChange); + } + if !factory.config.verification.exists() { + gates.push(Gate::NoVerification); + } + if mode == MergeMode::Manual { + gates.push(Gate::ManualMode); + } + gates } - fn merge_now(&mut self, factory_id: &str, id: &str) -> Option { - let factory = self.factories.get(factory_id).cloned()?; - let task = self.task(factory_id, id).cloned()?; + /// Merges now. A refusal that is neither the environment's nor a merge + /// GitHub has not finished naming waits for a person with its reason + /// instead of being retried every tick. + fn merge_now(&mut self, factory_id: &str, id: &str) -> Result { + let unknown = || Failure::task("merge", "unknown Task"); + let factory = self + .factories + .get(factory_id) + .cloned() + .ok_or_else(unknown)?; + let task = self.task(factory_id, id).cloned().ok_or_else(unknown)?; if factory.source == SourceKind::Local { match self.ports.merge.main_dirty(&factory) { Ok(true) => { @@ -2903,12 +2945,12 @@ impl Engine { } }); self.set_state(factory_id, id, TaskState::MergeWaiting); - return None; + return Err(Failure::task("merge", "main_dirty")); } Ok(false) => {} Err(failure) => { self.external_failure(factory_id, Some(id), &failure); - return None; + return Err(failure); } } } @@ -2936,11 +2978,25 @@ impl Engine { self.record(factory_id, Some(id), "merge.done", json!({"sha": sha})); self.set_state(factory_id, id, TaskState::Landed); self.check_landed(factory_id, id); - Some(sha) + Ok(sha) } Err(failure) => { self.external_failure(factory_id, Some(id), &failure); - None + if failure.signal.is_none() && failure.again_in_ms.is_none() { + self.with_task(factory_id, id, |task| { + if !task.gates.contains(&Gate::MergeRefused) { + task.gates.push(Gate::MergeRefused); + } + }); + self.record( + factory_id, + Some(id), + "merge.refused", + json!({"stage": failure.stage, "detail": judgment::cut(&failure.detail, 300)}), + ); + self.set_state(factory_id, id, TaskState::MergeWaiting); + } + Err(failure) } } } @@ -2959,13 +3015,41 @@ impl Engine { "Commit or stash the changes in the main checkout, then merge", )); } + // Main may have moved since the Task waited: merge-tree and the + // quick check run again right before a person's merge (B38, B40). + if let Some(task) = self.task(factory_id, id).cloned() { + match self.ports.merge.premerge(&factory, &task) { + Ok(PreMerge::Clean) | Ok(PreMerge::RiskPath { .. }) => {} + Ok(PreMerge::Conflict { files }) => { + self.send_to_rebase(factory_id, id, &files); + return Err(refuse( + "merge_conflict", + "The Task conflicts with main; its worker rebases and reports again", + )); + } + Ok(PreMerge::QuickCheckFailed { check }) => { + self.verification_failed(factory_id, id, &check, "quick check"); + return Err(refuse( + "quick_check_failed", + "The quick check failed on the latest main; its worker was told", + )); + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + return Err(refuse( + "merge_failed", + &format!("{}: {}", failure.stage, judgment::cut(&failure.detail, 300)), + )); + } + } + } match self.merge_now(factory_id, id) { - Some(sha) => Ok( + Ok(sha) => Ok( json!({"message": "merged", "sha": sha, "task": self.task_answer(factory_id, id, "")["task"]}), ), - None => Err(refuse( + Err(failure) => Err(refuse( "merge_failed", - "See hide factory show for the reason", + &format!("{}: {}", failure.stage, judgment::cut(&failure.detail, 300)), )), } } @@ -3003,8 +3087,6 @@ impl Engine { self.watch_due(factory_id, true); } - /// A finished Task's worker ends and its worktree goes; the branch stays - /// with the merge. A failure is logged and the disk recovery retries it. /// Stops a worker; a refusal is recorded against its Task. fn stop_worker(&mut self, factory_id: &str, id: &str, worker: &WorkerRef) { if let Err(failure) = self.ports.workers.stop(worker) { @@ -3031,6 +3113,8 @@ impl Engine { }); } + /// A finished Task's worker ends and its worktree goes; the branch stays + /// with the merge. A failure is logged and the disk recovery retries it. fn release_worker(&mut self, factory_id: &str, id: &str) { let Some(worker) = self.task(factory_id, id).and_then(|t| t.worker.clone()) else { return; @@ -4630,14 +4714,20 @@ impl Engine { .cloned() .collect(); for factory in factories { - let due = factory.main.broken + let now = self.now(); + let paced = self + .main_checked_at + .get(&factory.id) + .is_some_and(|at| now.saturating_sub(*at) < MAIN_CHECK_EVERY_MS); + let due = !self.main_seen.contains_key(&factory.id) || factory .outside_read_at - .is_some_and(|at| self.now().saturating_sub(at) < 1000) - || !self.main_seen.contains_key(&factory.id); + .is_some_and(|at| now.saturating_sub(at) < 1000) + || ((factory.main.broken || self.main_pending.contains(&factory.id)) && !paced); if !due { continue; } + self.main_checked_at.insert(factory.id.clone(), now); let Ok(head) = self.ports.merge.main_head(&factory) else { continue; }; @@ -4656,6 +4746,7 @@ impl Engine { } match self.ports.merge.main_check(&factory, &head) { Ok(MainCheck::Green) => { + self.main_pending.remove(&factory.id); self.main_seen.insert(factory.id.clone(), head.clone()); if factory.main.broken && !self.reverts.contains_key(&factory.id) { // Green again: auto merge resumes (D-47). @@ -4670,10 +4761,19 @@ impl Engine { } } Ok(MainCheck::Red { link }) if !known && !factory.main.broken => { + self.main_pending.remove(&factory.id); self.main_seen.insert(factory.id.clone(), head.clone()); self.main_broken(&factory.id, &head, &link); } + // Not finished: the head is not seen yet, so a red result + // that arrives later still counts (B47). + Ok(MainCheck::Pending) => { + if !factory.main.broken { + self.main_pending.insert(factory.id.clone()); + } + } Ok(_) => { + self.main_pending.remove(&factory.id); if !factory.main.broken { self.main_seen.insert(factory.id.clone(), head); } @@ -5266,6 +5366,16 @@ impl Engine { } } +/// An open question a person answers before the Task merges. +fn waits_on_answer(task: &Task) -> bool { + task.open_questions().any(|q| { + !matches!( + q.kind, + QuestionKind::Notice | QuestionKind::Default | QuestionKind::ScopeChange { .. } + ) + }) +} + /// A Task whose worktree waits out the keep period: cancelled, taken over /// by an outside pull request, or done through one (its worker's own work was /// never merged). diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index b29a0ba58f..8f2ba2c5ad 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -650,6 +650,7 @@ pub enum Gate { CheckFailed, AutonomyDiff, DirtyMain, + MergeRefused, } impl Gate { @@ -665,6 +666,7 @@ impl Gate { Self::CheckFailed => "점검을 하지 못함", Self::AutonomyDiff => "자율 처리 diff 상한 초과", Self::DirtyMain => "main checkout에 커밋 안 된 변경", + Self::MergeRefused => "머지가 거절됨", } } } diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index c22214b42d..c2024cfbf5 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -14,7 +14,7 @@ use std::time::{Duration, Instant}; use serde_json::Value; use crate::adapters::*; -use crate::engine::task_marker; +use crate::engine::{MERGE_COMMIT_AGAIN_MS, task_marker}; use crate::exec::{Runner, checked, classify}; use crate::model::*; use crate::store::sha256_hex; @@ -1348,7 +1348,10 @@ impl Verifier for SharedProjects { fn merge_commit(stage: &str, view: &Value) -> Result { match view["mergeCommit"]["oid"].as_str() { Some(oid) if !oid.is_empty() => Ok(oid.to_owned()), - _ => Err(Failure::task(stage, "merge commit not named yet")), + _ => Err(Failure { + again_in_ms: Some(MERGE_COMMIT_AGAIN_MS), + ..Failure::task(stage, "merge commit not named yet") + }), } } diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 87985c8284..a5a9e3fd44 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1160,6 +1160,93 @@ fn a_dirty_local_main_holds_the_merge() { assert_eq!(merged["ok"], true, "{merged}"); } +#[test] +fn a_refused_merge_waits_for_a_person_with_its_reason_and_is_tried_once() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Refused", &[]); + h.world().merge_refusal = Some(hide_factory::adapters::Failure::task( + "github.merge", + "base branch policy prohibits the merge", + )); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + for _ in 0..10 { + h.engine.tick(); + } + assert_eq!(h.world().merge_attempts, 1, "not retried every tick"); + assert_eq!(h.task(&f, &t).gates, vec![Gate::MergeRefused]); + // A person's merge tries again and lands. + let merged = h.op(Command::Merge { task: t.clone() }); + assert_eq!(merged["ok"], true, "{merged}"); +} + +#[test] +fn a_broken_main_holds_auto_merge_without_reading_it_every_tick() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.engine.tick(); + { + let mut world = h.world(); + world.head = "outside1".into(); + world.main_checks.insert( + "outside1".into(), + MainCheck::Red { + link: "run/9".into(), + }, + ); + } + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert!(h.engine.factories().next().unwrap().main.broken); + let t = h.ready("Held", &[]); + h.done(&f, &t); + let before = h.world().premerge_calls; + for _ in 0..20 { + h.engine.tick(); + } + assert_eq!(h.world().premerge_calls, before, "no merge-tree on red"); + assert_eq!(h.state(&f, &t), TaskState::Verifying); + assert!(h.writes("merge").is_empty()); +} + +#[test] +fn an_outside_push_still_running_its_checks_is_read_until_it_finishes() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.engine.tick(); + { + let mut world = h.world(); + world.head = "outside2".into(); + world.main_checks.insert( + "outside2".into(), + MainCheck::Red { + link: "run/10".into(), + }, + ); + world.main_check_script.insert( + "outside2".into(), + [ + MainCheck::Pending, + MainCheck::Pending, + MainCheck::Red { + link: "run/10".into(), + }, + ] + .into(), + ); + } + // The push is read at the next outside read, then every paced interval. + for _ in 0..6 { + h.advance(MINUTE_MS); + h.engine.tick(); + } + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.main.broken, "the late red result counts (B47)"); + assert!(h.world().main_check_script["outside2"].is_empty()); + assert_eq!(factory.id, f); +} + // ------------------------------------------------------------- main breaks #[test] diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 742fc55e29..95108bc6b6 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -33,6 +33,12 @@ pub struct World { pub verify_runs: Vec, pub cancelled_runs: Vec, pub premerge: BTreeMap>, + pub premerge_calls: u32, + /// The next merge is refused with this failure. + pub merge_refusal: Option, + pub merge_attempts: u32, + /// Main verification answers by commit, read before `main_checks`. + pub main_check_script: BTreeMap>, /// Main verification by commit; `Green` when absent. pub main_checks: BTreeMap, pub head: String, @@ -233,6 +239,7 @@ impl MergeTarget for Shared { Ok(format!("diff for {}", task.id)) } fn premerge(&mut self, _factory: &Factory, task: &Task) -> Result { + self.world().premerge_calls += 1; Ok(self .world() .premerge @@ -250,6 +257,10 @@ impl MergeTarget for Shared { _method: MergeMethod, ) -> Result { let mut world = self.world(); + world.merge_attempts += 1; + if let Some(failure) = world.merge_refusal.take() { + return Err(failure); + } world.next_sha += 1; let sha = format!("sha{:04}-{}", world.next_sha, task.id); world.writes.push(format!("merge {}", task.id)); @@ -257,6 +268,14 @@ impl MergeTarget for Shared { Ok(sha) } fn main_check(&mut self, _factory: &Factory, sha: &str) -> Result { + if let Some(next) = self + .world() + .main_check_script + .get_mut(sha) + .and_then(VecDeque::pop_front) + { + return Ok(next); + } Ok(self .world() .main_checks From e15a9509614948a74fd9982a9c624cb402bab868 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:15:26 +0900 Subject: [PATCH 25/72] Push every GitHub report from the tick and merge only the verified commit --- docs/factory.md | 9 ++- hide-factory/src/adapters.rs | 5 +- hide-factory/src/engine.rs | 99 ++++++++++++++++++++++++++----- hide-factory/src/project.rs | 92 +++++++++++++++++++++------- hide-factory/tests/engine.rs | 25 ++++++++ hide-factory/tests/github.rs | 64 +++++++++++++++++++- hide-factory/tests/local_git.rs | 10 +++- hide-factory/tests/support/mod.rs | 6 ++ 8 files changed, 267 insertions(+), 43 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index b1f22107c4..ca61350958 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -206,7 +206,9 @@ A worker that is `gone` is detected from its pane, with a three-minute grace aft A worker reports through `hide factory` and gets its answer in the same call. `ask` needs a suggestion, a default action and a deadline of 1 to 720 hours, and the worker continues with the default; `block` has no default, so the Task blocks, releases its slot and sleeps. -`done` opens a pull request on a GitHub Factory when none exists, goes to `verifying`, and puts the worker to sleep. +`done` answers at once, goes to `verifying`, and puts the worker to sleep. +On a GitHub Factory the next tick pushes the worktree's commits to the Task branch (with a lease, so a rebase goes through), then finds the open pull request for that branch or opens one, and only then reads CI on the pushed commit; every report pushes, so a fix after a failed check reaches the same pull request, and a merged pull request from before a revert is never reused. +A failed push or pull request is tried again a minute later. `decide` records a decision. A worker whose agent rests for the no-report window (`no_report_minutes`, 2) after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for the stall window (`stall_minutes`, 30) stops it as "stalled". @@ -309,9 +311,10 @@ A person's `merge` runs merge-tree and the quick check again on the latest main, A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again. `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. -**GitHub.** The merge is `gh pr merge` with the Factory's `merge_method` and `--match-head-commit` set to the pull request's head as read just before the merge, and a pull request already merged returns its merge commit. +**GitHub.** The merge is `gh pr merge` with the Factory's `merge_method` and `--match-head-commit` set to the commit the Task-stage verification passed on, so a push after it makes GitHub refuse the merge; a Factory without verification pins the head a person reviewed. +A verified Factory with no passed commit refuses to merge, a pull request already merged returns its merge commit, and a merge GitHub answered before naming its commit is read again rather than recorded empty. `init` picks the first merge method the repository allows, in the order merge, squash, rebase, and `config` changes it. -**Local.** The Factory merges into the project's primary checkout with `git merge --no-ff`, only while that checkout is on the default branch with no uncommitted tracked changes. +**Local.** The Factory merges the verified commit, not the branch's current tip, into the project's primary checkout with `git merge --no-ff`, only while that checkout is on the default branch with no uncommitted tracked changes; a merge that fails is aborted, so the checkout is never left mid-merge. Otherwise the Task stays in `merge_waiting` with `dirty_main` until it is clean. A merge records its commit, and the Task becomes `landed`. diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index 292493fedb..47fc1a9c2f 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -252,8 +252,9 @@ pub enum MainCheck { /// Branches, pull requests, merges and reverts. pub trait MergeTarget { fn main_head(&mut self, factory: &Factory) -> Result; - /// Pushes the branch and opens the pull request, or finds the one a - /// harness opened (B36). + /// Pushes the worktree's commits to the Task branch on every report, then + /// finds the open pull request for it (a harness's or an earlier + /// report's) or opens one (B36). fn open_pr( &mut self, factory: &Factory, diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index c871df824e..2cadd73d25 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -68,6 +68,10 @@ const START_RETRY_MS: u64 = 30_000; const MAIN_CHECK_EVERY_MS: u64 = 30_000; /// When a merge that GitHub answered without its commit is asked again. pub const MERGE_COMMIT_AGAIN_MS: u64 = 30_000; +/// When a failed push or pull request of a reported Task is tried again. +const PUBLISH_RETRY_MS: u64 = 60_000; +/// A GitHub Task's report whose commits are not pushed yet. +const PUBLISH_PENDING: &str = "publish_pending"; const START_NOTICE_MS: u64 = 10 * MINUTE_MS; struct VerifyState { @@ -132,6 +136,8 @@ pub struct Engine { /// When each Factory's main was last read, to pace a broken or pending /// main to [`MAIN_CHECK_EVERY_MS`]. main_checked_at: BTreeMap, + /// When a failed push or pull request is tried again, per Task. + publish_retry: BTreeMap<(String, String), UnixMs>, processed: BTreeSet, processed_order: Vec, /// Recent environment and Task failures the cascade rules read. @@ -193,6 +199,7 @@ impl Engine { main_seen: BTreeMap::new(), main_pending: BTreeSet::new(), main_checked_at: BTreeMap::new(), + publish_retry: BTreeMap::new(), processed: BTreeSet::new(), processed_order: Vec::new(), env_failures: Vec::new(), @@ -2453,23 +2460,76 @@ impl Engine { }); let _ = letter; self.put_to_sleep(factory_id, id); - // B36: a pull request for a GitHub Factory before CI is read. - if factory.source == SourceKind::Github && task.pr.is_none() { - let body = pr_body(&task, &factory); - match self.ports.merge.open_pr(&factory, &task, &body) { - Ok(pr) => { - self.with_task(factory_id, id, |task| { - task.pr = pr; - task.writes.insert("pr".into()); + self.set_state(factory_id, id, TaskState::Verifying); + if factory.source == SourceKind::Github { + // B35, B36: the reply comes now; the next tick pushes this report's + // commits and opens the pull request, then reads CI. + self.with_task(factory_id, id, |task| { + task.writes.insert(PUBLISH_PENDING.into()); + }); + self.publish_retry + .remove(&(factory_id.to_owned(), id.to_owned())); + return Ok( + json!({"message": "검증 중: 결과는 편지로 갑니다. 지금은 차례를 끝내세요.", "state": "verifying"}), + ); + } + self.begin_verification(factory_id, id) + } + + /// Pushes a GitHub Task's branch and finds or opens its pull request, + /// then starts the checks and verification on the pushed commit (B36). + fn publish(&mut self, factory_id: &str, id: &str) { + let key = (factory_id.to_owned(), id.to_owned()); + let now = self.now(); + if self.publish_retry.get(&key).is_some_and(|at| *at > now) { + return; + } + let (Some(factory), Some(task)) = ( + self.factories.get(factory_id).cloned(), + self.task(factory_id, id).cloned(), + ) else { + return; + }; + let body = pr_body(&task, &factory); + match self.ports.merge.open_pr(&factory, &task, &body) { + Ok(pr) => { + let opened = pr.as_ref().is_some_and(|pr| pr.by_factory) + && task.pr.as_ref().map(|own| own.number) != pr.as_ref().map(|pr| pr.number); + self.with_task(factory_id, id, |task| { + // The Factory's own pull request found again stays its own. + let own = task.pr.as_ref().is_some_and(|own| { + own.by_factory && pr.as_ref().is_some_and(|pr| pr.number == own.number) }); - self.record(factory_id, Some(id), "github.pr_opened", json!({})); - } - Err(failure) => { - self.external_failure(factory_id, Some(id), &failure); - } + task.pr = pr.map(|pr| PullRequest { + by_factory: pr.by_factory || own, + ..pr + }); + task.writes.insert("pr".into()); + task.writes.remove(PUBLISH_PENDING); + }); + self.publish_retry.remove(&key); + self.record( + factory_id, + Some(id), + "github.published", + json!({"opened": opened}), + ); + let _ = self.begin_verification(factory_id, id); + } + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + self.publish_retry.insert(key, now + PUBLISH_RETRY_MS); } } - self.set_state(factory_id, id, TaskState::Verifying); + } + + /// Starts the checks and the Task-stage verification of a reported Task. + fn begin_verification(&mut self, factory_id: &str, id: &str) -> Reply { + let factory = self + .factories + .get(factory_id) + .cloned() + .ok_or_else(|| refuse("factory_not_found", "?"))?; self.start_checks(factory_id, id); if !factory.config.verification.exists() { // No verification: straight to merge waiting (B2, B35). @@ -2771,6 +2831,9 @@ impl Engine { if task.state != TaskState::Verifying { return; } + if task.writes.contains(PUBLISH_PENDING) { + return; + } let key = (factory_id.to_owned(), id.to_owned()); if self.verifying.contains_key(&key) { return; @@ -3946,6 +4009,14 @@ impl Engine { for factory in &factories { self.drive_revert(factory); self.unblock(factory); + let publishing: Vec = self + .tasks_of(factory) + .filter(|t| t.state == TaskState::Verifying && t.writes.contains(PUBLISH_PENDING)) + .map(|t| t.id.clone()) + .collect(); + for id in publishing { + self.publish(factory, &id); + } let verifying: Vec = self .tasks_of(factory) .filter(|t| t.state == TaskState::Verifying) diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index c2024cfbf5..b53f53ce5d 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -758,6 +758,23 @@ impl MergeTarget for SharedProjects { .map(|w| w.branch.clone()) .unwrap_or_else(|| task.branch_slug()); let mut this = self.lock(); + // Every report publishes its commits, so CI reads what the worker + // committed since the last one; a rebase needs the lease (B36, B40). + let path = worktree(task)?; + this.git( + "git.push", + &path, + &[ + "push", + "--quiet", + "--force-with-lease", + "--set-upstream", + "origin", + &format!("HEAD:refs/heads/{branch}"), + ], + )?; + // Only an open pull request is this report's: a merged one from before + // a revert is history, and a relanding opens a new one (B46). let existing = this.gh_json( "github.pr_find", &[ @@ -768,27 +785,24 @@ impl MergeTarget for SharedProjects { "--head", &branch, "--state", - "all", + "open", "--json", "number,url,state,headRefName", ], )?; if let Some(pr) = existing.as_array().and_then(|prs| prs.first()) { // A harness opened it, or an earlier attempt did (B36, B73). + let number = pr["number"] + .as_u64() + .ok_or_else(|| Failure::task("github.pr_find", "pull request has no number"))?; return Ok(Some(PullRequest { - number: pr["number"].as_u64().unwrap_or_default(), + number, url: pr["url"].as_str().unwrap_or_default().to_owned(), head: branch, by_factory: false, - open: pr["state"].as_str() == Some("OPEN"), + open: true, })); } - let path = worktree(task)?; - this.git( - "git.push", - &path, - &["push", "--quiet", "--set-upstream", "origin", &branch], - )?; let url = this.gh( "github.pr_create", &[ @@ -987,12 +1001,19 @@ impl MergeTarget for SharedProjects { .as_ref() .map(|w| w.branch.clone()) .unwrap_or_else(|| task.branch_slug()); + // The commit that passed verification, never a later tip of + // the branch (B39); a Factory without verification merges the + // branch a person reviewed. + let target = match verified_commit(factory, task)? { + Some(commit) => commit, + None => branch.clone(), + }; let ancestor = this.runner.run( "git", &[ "merge-base".into(), "--is-ancestor".into(), - branch.clone(), + target.clone(), "HEAD".into(), ], Some(&project), @@ -1004,11 +1025,19 @@ impl MergeTarget for SharedProjects { branch, task.card.title ); - this.git( + if let Err(failure) = this.git( "git.merge", &project, - &["merge", "--no-ff", "--no-edit", "-m", &message, &branch], - )?; + &["merge", "--no-ff", "--no-edit", "-m", &message, &target], + ) { + // Never leave the operator's checkout mid-merge. + let _ = this.runner.run( + "git", + &["merge".into(), "--abort".into()], + Some(&project), + ); + return Err(failure); + } } Ok(this .git("git.merge", &project, &["rev-parse", "HEAD"])? @@ -1026,14 +1055,16 @@ impl MergeTarget for SharedProjects { return merge_commit("github.merge", &view); } // Pinned to the commit that passed verification: a push after - // it makes GitHub refuse the merge (B39). - let head = task - .attempts - .iter() - .rev() - .find(|attempt| matches!(attempt.outcome, Some(AttemptOutcome::Passed))) - .and_then(|attempt| attempt.commit.clone()) - .unwrap_or_else(|| view["headRefOid"].as_str().unwrap_or_default().to_owned()); + // it makes GitHub refuse the merge (B39). Without verification + // the head a person reviewed is the pin. + let head = match verified_commit(factory, task)? { + Some(commit) => commit, + None => view["headRefOid"] + .as_str() + .filter(|oid| !oid.is_empty()) + .ok_or_else(|| Failure::task("github.merge", "pull request has no head"))? + .to_owned(), + }; let number = pr.number.to_string(); let flag = match method { MergeMethod::Merge => "--merge", @@ -1341,7 +1372,23 @@ impl Verifier for SharedProjects { } } -/// `prefix/**`, `*.ext` or an exact path. +/// The commit the Task-stage verification passed on; `None` only for a +/// Factory without verification. A verified Factory with no passed commit is +/// refused rather than merged at whatever the branch holds now. +fn verified_commit(factory: &Factory, task: &Task) -> Result, Failure> { + if !factory.config.verification.exists() { + return Ok(None); + } + task.attempts + .iter() + .rev() + .find(|attempt| attempt.stage == AttemptStage::Task) + .filter(|attempt| attempt.outcome == Some(AttemptOutcome::Passed)) + .and_then(|attempt| attempt.commit.clone()) + .map(Some) + .ok_or_else(|| Failure::task("merge", "no verified commit to merge")) +} + /// The merge commit of a merged pull request. GitHub can answer a merge /// before it names the commit (a merge queue, a lagging read): that is asked /// again rather than recorded as an empty commit. @@ -1355,6 +1402,7 @@ fn merge_commit(stage: &str, view: &Value) -> Result { } } +/// `prefix/**`, `*.ext` or an exact path. fn path_matches(pattern: &str, path: &str) -> bool { if let Some(prefix) = pattern.strip_suffix("/**") { return path.starts_with(&format!("{prefix}/")); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index a5a9e3fd44..01dc15c752 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1051,6 +1051,31 @@ fn github_factory(h: &mut Bench, mode: MergeMode) -> String { created["factory"]["id"].as_str().unwrap().to_owned() } +#[test] +fn each_github_report_pushes_before_its_checks_are_read_and_answers_at_once() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Fix again", &[]); + h.world().verify.insert( + t.clone(), + [VerifyPoll::Failed { + check: "test".into(), + link: "ci".into(), + }] + .into(), + ); + let answer = h.done(&f, &t); + assert_eq!(answer["state"], "verifying", "{answer}"); + assert!(h.world().pushes.is_empty(), "the reply does not wait on git"); + assert!(h.world().verify_runs.is_empty()); + tick_until(&mut h, &f, &t, TaskState::Running); + assert_eq!(h.world().pushes, vec![t.clone()]); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::Done); + assert_eq!(h.world().pushes, vec![t.clone(), t.clone()]); + assert_eq!(h.writes("pr.open").len(), 1, "one pull request"); +} + #[test] fn a_manual_task_waits_for_merge_and_every_github_write_happens_once() { let mut h = Bench::new(true); diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index ab2694df72..11efaa6c39 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -26,6 +26,8 @@ struct Hub { commit_later: bool, /// The most issues one list answers, newest first. list_cap: Option, + /// Each `git push` refspec, in order. + pushes: Vec, } #[derive(Clone, Default)] @@ -57,6 +59,10 @@ impl Runner for FakeGh { if program == "git" { return Ok(match args.first().map(String::as_str) { Some("rev-parse") => ok("headsha\n"), + Some("push") => { + hub.pushes.push(args.last().cloned().unwrap_or_default()); + ok("") + } _ => ok(""), }); } @@ -103,7 +109,8 @@ impl Runner for FakeGh { } ["pr", "list", ..] => { let head = flag(args, "--head"); - let all: Vec = hub.prs.values().filter(|pr| head.is_none_or(|h| pr["headRefName"] == h)).cloned().collect(); + let open = flag(args, "--state") == Some("open"); + let all: Vec = hub.prs.values().filter(|pr| head.is_none_or(|h| pr["headRefName"] == h)).filter(|pr| !open || pr["state"] == "OPEN").cloned().collect(); ok(Value::Array(all).to_string()) } ["pr", "create", ..] => { @@ -186,6 +193,15 @@ fn task(id: &str, issue: Option) -> Task { .or_insert(default.clone()); } let mut task: Task = serde_json::from_value(value).unwrap(); + // The Task-stage verification passed on the pushed head. + task.attempts.push(Attempt { + number: 1, + commit: Some("headsha".into()), + started_at: 0, + stage: AttemptStage::Task, + outcome: Some(AttemptOutcome::Passed), + log: None, + }); task.worker = Some(WorkerRef { factory: String::new(), agent: None, @@ -286,6 +302,52 @@ fn a_merge_without_its_commit_yet_is_asked_again_and_not_merged_twice() { assert_eq!(merges, 1, "the merge is made once"); } +#[test] +fn every_report_pushes_and_a_merged_pull_request_is_not_reused() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + let mut t = task("T-1", Some(1)); + let first = p.open_pr(&factory, &t, "body").unwrap().unwrap(); + // A second report after a failed check pushes the fix to the same pull + // request. + let second = p.open_pr(&factory, &t, "body").unwrap().unwrap(); + assert_eq!(second.number, first.number); + assert_eq!( + gh.0.lock().unwrap().pushes, + vec!["HEAD:refs/heads/factory/1-add-it"; 2] + ); + // Merged, reverted and relanding: a new pull request, never the old one. + t.pr = Some(first.clone()); + p.merge(&factory, &t, MergeMethod::Merge).unwrap(); + let reland = p.open_pr(&factory, &t, "body").unwrap().unwrap(); + assert_ne!(reland.number, first.number); + assert!(reland.by_factory); +} + +#[test] +fn a_merge_without_a_verified_commit_is_refused() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + let mut t = task("T-1", Some(1)); + t.pr = p.open_pr(&factory, &t, "body").unwrap(); + t.attempts.last_mut().unwrap().outcome = Some(AttemptOutcome::Failed { + check: "test".into(), + link: String::new(), + }); + let failure = p.merge(&factory, &t, MergeMethod::Merge).unwrap_err(); + assert_eq!(failure.detail, "no verified commit to merge"); + assert!( + !gh.0 + .lock() + .unwrap() + .writes + .iter() + .any(|w| w.starts_with("pr merge")) + ); +} + #[test] fn required_checks_decide_and_a_cancelled_run_is_asked_again() { let gh = FakeGh::default(); diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index 04d64243b0..5c870c6b63 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -184,7 +184,7 @@ fn a_local_task_is_verified_merged_checked_on_main_and_reverted_alone() { assert_eq!(probe.verify_candidates, vec!["make test"]); let factory = factory(&fx.project, &["test -f b.txt"]); - let t = task(&fx, "T-1", "b.txt", "two\n"); + let mut t = task(&fx, "T-1", "b.txt", "two\n"); assert_eq!(fx.projects.diff_lines(&factory, &t).unwrap(), 1); assert_eq!( fx.projects.changed_paths(&factory, &t).unwrap(), @@ -194,6 +194,14 @@ fn a_local_task_is_verified_merged_checked_on_main_and_reverted_alone() { let run = fx.projects.start(&factory, &t).unwrap(); assert_eq!(settle(&mut fx.projects, &factory, &run), VerifyPoll::Passed); + t.attempts.push(Attempt { + number: 1, + commit: run.commit.clone(), + started_at: 0, + stage: AttemptStage::Task, + outcome: Some(AttemptOutcome::Passed), + log: None, + }); // main moved meanwhile: the bundle runs on main merged into the Task. write(&fx.project, "c.txt", "three\n"); git(&fx.project, &["add", "."]); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 95108bc6b6..230a583b05 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -37,6 +37,8 @@ pub struct World { /// The next merge is refused with this failure. pub merge_refusal: Option, pub merge_attempts: u32, + /// Each report a GitHub Task pushed, by Task id. + pub pushes: Vec, /// Main verification answers by commit, read before `main_checks`. pub main_check_script: BTreeMap>, /// Main verification by commit; `Green` when absent. @@ -210,6 +212,10 @@ impl MergeTarget for Shared { _body: &str, ) -> Result, Failure> { let mut world = self.world(); + world.pushes.push(task.id.clone()); + if let Some(pr) = task.pr.clone().filter(|pr| pr.open) { + return Ok(Some(pr)); + } world.next_pr += 1; let number = world.next_pr; world.writes.push(format!("pr.open {}", task.id)); From f9b8d13181ddcd43b56feb80339e12871d58f867 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:16:35 +0900 Subject: [PATCH 26/72] Land a local revert only into a clean default branch --- docs/factory.md | 2 +- hide-factory/src/project.rs | 44 +++++++++++++++++++++------------ hide-factory/tests/engine.rs | 5 +++- hide-factory/tests/local_git.rs | 21 +++++++++++++++- 4 files changed, 53 insertions(+), 19 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index ca61350958..ca6c7fea8d 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -324,7 +324,7 @@ A green result, or no main verification, makes the Task `done` and removes its w A red result breaks main and stops auto merge; manual merges still run. While main is broken an `auto` Task that passed verification waits in `verifying` without merge-tree or quick-check reads, unless a person's gate sends it to `merge_waiting`; main is read again every 30 seconds. If the broken commit is among the Factory's own merges since the last green, the Factory finds the first failing one, asking again for runs that were skipped or cancelled, and reverts that merge alone. -On GitHub the revert is a pull request from `factory/revert-`, which the Factory force-pushes, checks and merges with `--merge`; locally it is a revert commit made in `factory-main` and fast-forwarded into the primary checkout. +On GitHub the revert is a pull request from `factory/revert-`, which the Factory force-pushes, checks and merges with `--merge`; locally it is a revert commit made in `factory-main` and fast-forwarded into the primary checkout, only while that checkout is on the default branch and clean, as for a Task merge. A revert whose verification passes is merged on its own, and the original Task becomes `relanding`: it runs again in the same worktree and session on the latest main, with a new pull request. When the failing commit is not the Factory's, nothing is reverted: the Factory drafts a fix Task for a person to confirm and stops auto merge. Auto merge resumes when the head of main verifies green again. diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index b53f53ce5d..8f24e32722 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -128,6 +128,26 @@ impl Projects { checked(self.runner.as_mut(), stage, "gh", args, None) } + /// The primary checkout is off the default branch or has uncommitted + /// tracked changes: nothing merges into it then. + fn main_dirty(&mut self, factory: &Factory) -> Result { + let project = PathBuf::from(&factory.project); + let branch = self.git( + "git.status", + &project, + &["rev-parse", "--abbrev-ref", "HEAD"], + )?; + if branch.trim() != factory.default_branch { + return Ok(true); + } + let status = self.git( + "git.status", + &project, + &["status", "--porcelain", "--untracked-files=no"], + )?; + Ok(!status.trim().is_empty()) + } + fn gh_json(&mut self, stage: &str, args: &[&str]) -> Result { let text = self.gh(stage, args)?; serde_json::from_str(&text) @@ -968,22 +988,7 @@ impl MergeTarget for SharedProjects { } fn main_dirty(&mut self, factory: &Factory) -> Result { - let mut this = self.lock(); - let project = PathBuf::from(&factory.project); - let branch = this.git( - "git.status", - &project, - &["rev-parse", "--abbrev-ref", "HEAD"], - )?; - if branch.trim() != factory.default_branch { - return Ok(true); - } - let status = this.git( - "git.status", - &project, - &["status", "--porcelain", "--untracked-files=no"], - )?; - Ok(!status.trim().is_empty()) + self.lock().main_dirty(factory) } fn merge( @@ -1263,6 +1268,13 @@ impl MergeTarget for SharedProjects { merge_commit("github.revert_merge", &view) } _ => { + if commit.is_empty() { + return Err(Failure::task("git.revert_merge", "revert has no commit")); + } + // Only into the default branch, clean, as a Task merge (D-46). + if this.main_dirty(factory)? { + return Err(Failure::task("git.revert_merge", "main_dirty")); + } let project = PathBuf::from(&factory.project); this.git( "git.revert_merge", diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 01dc15c752..3e1a43afa8 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1066,7 +1066,10 @@ fn each_github_report_pushes_before_its_checks_are_read_and_answers_at_once() { ); let answer = h.done(&f, &t); assert_eq!(answer["state"], "verifying", "{answer}"); - assert!(h.world().pushes.is_empty(), "the reply does not wait on git"); + assert!( + h.world().pushes.is_empty(), + "the reply does not wait on git" + ); assert!(h.world().verify_runs.is_empty()); tick_until(&mut h, &f, &t, TaskState::Running); assert_eq!(h.world().pushes, vec![t.clone()]); diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index 5c870c6b63..223d6561e8 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -248,6 +248,12 @@ fn a_local_task_is_verified_merged_checked_on_main_and_reverted_alone() { } // The bundle needs b.txt, which the revert removes: it fails. assert!(matches!(check, MainCheck::Red { .. }), "{check:?}"); + // The operator is on another branch: the revert does not land there. + git(&fx.project, &["checkout", "--quiet", "-b", "elsewhere"]); + let refused = fx.projects.merge_revert(&factory, &revert).unwrap_err(); + assert_eq!(refused.detail, "main_dirty"); + assert!(fx.project.join("b.txt").exists()); + git(&fx.project, &["checkout", "--quiet", "main"]); let landed = fx.projects.merge_revert(&factory, &revert).unwrap(); assert_eq!(git(&fx.project, &["rev-parse", "HEAD"]), landed); assert!(!fx.project.join("b.txt").exists()); @@ -261,7 +267,7 @@ fn a_local_task_is_verified_merged_checked_on_main_and_reverted_alone() { fn a_conflict_and_a_dirty_main_are_found_before_merge() { let mut fx = fixture(); let factory = factory(&fx.project, &[]); - let t = task(&fx, "T-2", "a.txt", "branch\n"); + let mut t = task(&fx, "T-2", "a.txt", "branch\n"); write(&fx.project, "a.txt", "main\n"); git(&fx.project, &["commit", "--quiet", "-am", "main edit"]); assert_eq!( @@ -270,6 +276,19 @@ fn a_conflict_and_a_dirty_main_are_found_before_merge() { files: vec!["a.txt".into()] } ); + // Merged anyway, the conflict fails the merge and leaves no MERGE_HEAD. + let worktree = PathBuf::from(&t.worker.as_ref().unwrap().worktree); + t.attempts.push(Attempt { + number: 1, + commit: Some(git(&worktree, &["rev-parse", "HEAD"])), + started_at: 0, + stage: AttemptStage::Task, + outcome: Some(AttemptOutcome::Passed), + log: None, + }); + assert!(fx.projects.merge(&factory, &t, MergeMethod::Merge).is_err()); + assert!(!fx.project.join(".git/MERGE_HEAD").exists()); + assert!(!fx.projects.main_dirty(&factory).unwrap()); write(&fx.project, "a.txt", "uncommitted\n"); assert!(fx.projects.main_dirty(&factory).unwrap()); From 1104572e5cc3c68e18ef415eeffd06637ddc4d3a Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:17:42 +0900 Subject: [PATCH 27/72] Decide CI only by named checks and take the required checks when none are named --- docs/factory.md | 3 ++- hide-factory/src/engine.rs | 35 +++++++++++++++++++++++++++-------- hide-factory/src/project.rs | 9 +++++---- hide-factory/tests/engine.rs | 25 +++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 13 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index ca6c7fea8d..f7d795404a 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -268,7 +268,8 @@ Environment failures and merge conflicts do not count. `retry` resets the count. **CI.** The check runs of the worktree's head commit are read on each tick with `gh api`. -With a list of names, every name must have a completed run; without one, every check run on the commit is read, and a commit with no check run yet reads as passed, so name the required checks in `--ci`. +Every named check must have a completed run, and only named checks decide; a commit with no run of a named check yet is pending, never passed. +`--ci` with no names takes the default branch's required checks from its protection, and `init` and `config ci=` refuse a Factory that would name no check (`ci_checks_required`). A completed run passes on `success` or `neutral`, decides nothing on `skipped`, `cancelled` or `stale` (still pending), and fails on any other conclusion with the run's link. A GitHub error that carries an environment signal is the environment's; any other read error stays pending. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 2cadd73d25..2b2e6eafa1 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -982,6 +982,20 @@ impl Engine { "A project without GitHub verifies with --verify ", )); } + // A check named nowhere would let any finished run decide: + // the branch protection's required checks stand in, and with + // none the person names them (D-21, D-53). + let checks = if checks.is_empty() { + probe.required_checks.clone() + } else { + checks + }; + if checks.is_empty() { + return Err(refuse( + "ci_checks_required", + "The default branch requires no checks: name them with --ci ", + )); + } Verification::Ci { checks } } Some(VerificationChoice::Commands { commands }) => { @@ -3759,14 +3773,19 @@ impl Engine { }; } "ci" => { - config.verification = Verification::Ci { - checks: value - .split(',') - .map(str::trim) - .filter(|c| !c.is_empty()) - .map(str::to_owned) - .collect(), - }; + let checks: Vec = value + .split(',') + .map(str::trim) + .filter(|c| !c.is_empty()) + .map(str::to_owned) + .collect(); + if checks.is_empty() { + return Err(refuse( + "ci_checks_required", + "Name the checks that decide: ci=", + )); + } + config.verification = Verification::Ci { checks }; } "no_verification" => config.verification = Verification::None, "quick_check" => { diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 8f24e32722..1891ce3da6 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -273,15 +273,16 @@ impl Projects { Verification::Ci { checks } => checks.clone(), _ => Vec::new(), }; + // Only named checks decide; a Factory that names none never reads a + // pass from whichever run finished first. let runs: Vec<&Value> = value["check_runs"] .as_array() .into_iter() .flatten() .filter(|run| { - required.is_empty() - || required - .iter() - .any(|name| run["name"].as_str() == Some(name)) + required + .iter() + .any(|name| run["name"].as_str() == Some(name)) }) .collect(); // No run yet is not a pass: CI has not answered for this commit. diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 3e1a43afa8..dfca40d5ea 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1051,6 +1051,31 @@ fn github_factory(h: &mut Bench, mode: MergeMode) -> String { created["factory"]["id"].as_str().unwrap().to_owned() } +#[test] +fn ci_with_no_named_check_takes_the_required_checks_and_never_none() { + let mut h = Bench::new(true); + let created = h.op(Command::Init { + project: PROJECT.into(), + verification: Some(VerificationChoice::Ci { checks: vec![] }), + merge_mode: Some(MergeMode::Auto), + confirm: true, + }); + assert_eq!(created["ok"], true, "{created}"); + let factory = h.engine.factories().next().unwrap().clone(); + assert_eq!( + factory.config.verification, + Verification::Ci { + checks: vec!["test".into()] + }, + "the branch protection's required checks stand in" + ); + let refused = h.op(Command::Config { + project: Some(PROJECT.into()), + set: vec![("ci".into(), " , ".into())], + }); + assert_eq!(refused["reason"], "ci_checks_required", "{refused}"); +} + #[test] fn each_github_report_pushes_before_its_checks_are_read_and_answers_at_once() { let mut h = Bench::new(true); From 5acb7eedb0ded5a7194854007778a859f5bdf408 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:18:13 +0900 Subject: [PATCH 28/72] Let an open pull request from a fork take no Task until it merges --- docs/factory.md | 2 +- hide-factory/src/project.rs | 8 +++++++- hide-factory/tests/github.rs | 26 +++++++++++++++++++++++++- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index f7d795404a..c9f00bb76f 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -339,7 +339,7 @@ A failed read backs off 1, 2, 5, 15 and then 30 minutes on a rate-limit, server | What the Factory sees | What it does | | --- | --- | -| A pull request the Factory did not open closes a Task's issue, and it is open | The Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | +| A pull request the Factory did not open closes a Task's issue, and it is open | A pull request from a fork counts only once it is merged, since anyone can open one. Otherwise the Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | | That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. A stopped worker's worktree still waits out its keep period. | | The issue closes with no pull request, or the `factory` label is removed | The Task is cancelled with a notice, kept for the keep period. | | A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 1891ce3da6..7ecfcd3aed 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -620,7 +620,7 @@ impl TaskSource for SharedProjects { "--limit", "100", "--json", - "number,url,state,headRefName,closingIssuesReferences", + "number,url,state,headRefName,isCrossRepository,closingIssuesReferences", ], )?; let held: BTreeMap = tasks @@ -714,6 +714,12 @@ impl TaskSource for SharedProjects { .filter(|pr| { pr["headRefName"].as_str() != Some(task.branch_slug().as_str()) }) + // Anyone can open a pull request from a fork: it takes + // a Task only once a maintainer merged it (D-27). + .filter(|pr| { + pr["state"].as_str() == Some("MERGED") + || pr["isCrossRepository"].as_bool() != Some(true) + }) .collect(); if let Some(pr) = closing .iter() diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index 11efaa6c39..a39b36c13d 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -427,11 +427,35 @@ fn outside_work_is_read_from_issues_and_closing_pull_requests() { ), ); hub.prs.insert(9, json!({"number": 9, "url": "pr/9", "state": "OPEN", "headRefName": "someone/fix", "closingIssuesReferences": [{"number": 1}]})); + // An open pull request from a fork closes issue 3's held Task's issue + // too, but anyone can open one: it takes nothing until merged. + hub.prs.insert(10, json!({"number": 10, "url": "pr/10", "state": "OPEN", "headRefName": "fix", "isCrossRepository": true, "closingIssuesReferences": [{"number": 5}]})); + hub.issues.insert( + 5, + ( + "Forked".into(), + "".into(), + "OPEN".into(), + ), + ); } let held = task("T-1", Some(1)); let closed = task("T-3", Some(3)); let gone = task("T-4", Some(4)); - let events = p.observe(&factory, &[&held, &closed, &gone]).unwrap(); + let forked = task("T-5", Some(5)); + let events = p + .observe(&factory, &[&held, &closed, &gone, &forked]) + .unwrap(); + assert!( + !events.iter().any(|event| matches!( + event, + OutsideEvent::ClosingPr { + issue: IssueRef::Github { number: 5 }, + .. + } + )), + "{events:?}" + ); assert!( events.contains(&OutsideEvent::ClosingPr { issue: IssueRef::Github { number: 1 }, From 067ed128f22dd088e3f226a4ad2e73918269e1ec Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:19:45 +0900 Subject: [PATCH 29/72] Hand a main recovery cut by a restart to a person --- docs/factory.md | 1 + hide-factory/src/engine.rs | 51 ++++++++++++++++++++++++++++-------- hide-factory/src/model.rs | 3 +++ hide-factory/tests/engine.rs | 40 ++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 11 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index c9f00bb76f..8987bbcbc0 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -54,6 +54,7 @@ A store written by a newer build is refused rather than read: the engine does no Fields added later load from older rows through serde defaults. The engine loads the whole store at start and saves each change before the command that made it answers, so a restart resumes Factories, Tasks, questions, workers and in-flight work. A restart starts verification again from the recorded attempt and asks a pending review again. +A main recovery the restart cut short is not guessed again, since which merge it was finding or reverting lived only in the old process: it goes to a person with the same choices as a recovery that could not decide. The engine opens the store when a store file already exists at start, or on the first command, so a machine that never created a Factory opens nothing. `factory-files///` holds each attached PRD as `.`, a read-only copy of at most 4 MiB, and `factory-files/logs/` holds one `.log` per local verification run. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 2b2e6eafa1..ebf7d67075 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -271,6 +271,17 @@ impl Engine { engine.request_review(&factory, &id, now); } } + // A main recovery cut by the restart is not guessed again: which + // merge it was reverting is gone, so a person picks the next step. + let cut: Vec<(String, Vec)> = engine + .factories + .values() + .filter(|f| f.main.broken && f.main.recovering && !f.main.needs_person) + .map(|f| (f.id.clone(), f.main.merges_since_green.clone())) + .collect(); + for (factory, merges) in cut { + engine.revert_needs_person(&factory, "hided가 다시 시작해 복구가 끊겼습니다", &merges); + } Ok(engine) } @@ -2040,7 +2051,7 @@ impl Engine { if let Some(f) = self.factories.get_mut(factory) { f.main.needs_person = false; } - self.reverts.remove(factory); + self.set_recovery(factory, None); self.save_factory(factory); } other if other.starts_with("revert ") => { @@ -3279,8 +3290,7 @@ impl Engine { if !anchor.is_empty() { self.notice(factory_id, &anchor, &format!("main 깨짐: Factory 머지 뒤 main 검증이 실패했습니다. 자동 머지를 멈추고 원인 머지를 찾습니다. {link}")); } - self.reverts - .insert(factory_id.to_owned(), RevertPhase::Bisecting { index: 0 }); + self.set_recovery(factory_id, Some(RevertPhase::Bisecting { index: 0 })); self.watch_due(factory_id, true); self.drive_revert(factory_id); } @@ -3334,8 +3344,7 @@ impl Engine { t.writes.insert(key); }); } - self.reverts - .insert(factory_id.to_owned(), RevertPhase::Bisecting { index }); + self.set_recovery(factory_id, Some(RevertPhase::Bisecting { index })); return; } Ok(MainCheck::None) | Err(_) => break, @@ -3353,7 +3362,7 @@ impl Engine { Ok(MainCheck::Green) | Ok(MainCheck::None) => { match self.ports.merge.merge_revert(&factory, &revert) { Ok(sha) => { - self.reverts.remove(factory_id); + self.set_recovery(factory_id, None); self.record( factory_id, Some(&task), @@ -3425,12 +3434,12 @@ impl Engine { self.with_task(factory_id, task, |t| { t.writes.insert(format!("revert:{sha}")); }); - self.reverts.insert( - factory_id.to_owned(), - RevertPhase::Reverting { + self.set_recovery( + factory_id, + Some(RevertPhase::Reverting { revert, task: task.to_owned(), - }, + }), ); self.drive_revert(factory_id); } @@ -3442,12 +3451,32 @@ impl Engine { } } + /// The recovery phase lives in memory, and `main.recovering` in the store + /// says one was running, so a restart can hand it to a person (B72). + fn set_recovery(&mut self, factory_id: &str, phase: Option) { + let running = phase.is_some(); + match phase { + Some(phase) => { + self.reverts.insert(factory_id.to_owned(), phase); + } + None => { + self.reverts.remove(factory_id); + } + } + if let Some(f) = self.factories.get_mut(factory_id) + && f.main.recovering != running + { + f.main.recovering = running; + self.save_factory(factory_id); + } + } + fn revert_needs_person(&mut self, factory_id: &str, why: &str, merges: &[LandedMerge]) { if let Some(f) = self.factories.get_mut(factory_id) { f.main.needs_person = true; } self.save_factory(factory_id); - self.reverts.remove(factory_id); + self.set_recovery(factory_id, None); let anchor = merges.last().map(|m| m.task.clone()); let Some(anchor) = anchor else { return }; let mut choices = vec!["retry-revert".to_owned()]; diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 8f2ba2c5ad..1cb9d7eba4 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -76,6 +76,9 @@ pub struct MainHealth { pub needs_person: bool, /// Merges Factory made since the last green, oldest first. pub merges_since_green: Vec, + /// A recovery (finding or reverting the failing merge) is running. + #[serde(default)] + pub recovering: bool, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index dfca40d5ea..5b5b9549a6 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1302,6 +1302,46 @@ fn an_outside_push_still_running_its_checks_is_read_until_it_finishes() { // ------------------------------------------------------------- main breaks +#[test] +fn a_recovery_cut_by_a_restart_goes_to_a_person() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("A", &[]); + let b = h.ready("B", &[]); + { + let mut world = h.world(); + world + .main_checks + .insert("sha0001-T-1".into(), MainCheck::Pending); + world.main_checks.insert( + "sha0002-T-2".into(), + MainCheck::Red { + link: "run/2".into(), + }, + ); + } + h.done(&f, &a); + h.done(&f, &b); + tick_until(&mut h, &f, &b, TaskState::Landed); + h.engine.tick(); + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.main.broken && factory.main.recovering); + + let mut h = h.restart(); + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.main.needs_person, "nothing guesses the cut phase"); + assert!(!factory.main.recovering); + let action = h + .task(&f, &b) + .open_questions() + .find(|q| q.kind == QuestionKind::Action) + .cloned() + .expect("an action for a person"); + assert!(action.choices.contains(&"retry-revert".to_owned())); + h.engine.tick(); + assert!(h.writes("revert").is_empty()); +} + #[test] fn a_broken_main_reverts_only_the_first_failing_merge_and_the_task_lands_again() { let mut h = Bench::new(false); From 5951a8e3fc7216c32e869dd24d2f19f9ffc668f3 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:20:22 +0900 Subject: [PATCH 30/72] Keep review and person dependencies when a producer adds a card again --- docs/factory.md | 1 + hide-factory/src/engine.rs | 11 ++++++++++- hide-factory/tests/engine.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/docs/factory.md b/docs/factory.md index 8987bbcbc0..6483332e36 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -226,6 +226,7 @@ The review sees only the card, its attachment, the repository's file names and g Adding again with `--task ` or the same issue updates the same Task and reviews it again; the same content changes nothing. A re-add on a Task that already runs does not rewrite its card: it adds a scope-change question that a person approves or rejects. +A re-add adds dependencies but never drops one the review or a person added, so a producer that resends the card it knows changes nothing; removing a dependency is a person's `dep remove`. The producer's open decisions become intake questions, and a Task is Ready only when the review is done and no question besides a notice is open. Ready creates the issue: a GitHub Task gets an issue labelled `factory` whose body carries a hidden Task marker, the goal, the criteria and the out-of-scope items, and a local Task gets an `L-`. A Task added from an existing issue gets the label instead. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index ebf7d67075..9013dd07bc 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1388,7 +1388,16 @@ impl Engine { "Revive it first with hide factory revive", )); } - let card = self.validate_card(factory_id, Some(id), &input, Some(&task.card))?; + let mut card = self.validate_card(factory_id, Some(id), &input, Some(&task.card))?; + // A producer adds dependencies but never removes one a review or a + // person added: removal is a person's `dep remove` (D-02, D-08). + let mut depends_on = task.card.depends_on.clone(); + for dependency in card.depends_on.drain(..) { + if !depends_on.contains(&dependency) { + depends_on.push(dependency); + } + } + card.depends_on = depends_on; let attachment = match &input.prd { Some(prd) => { let version = task.attachments.last().map_or(1, |a| a.version + 1); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 5b5b9549a6..34786cb329 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -256,6 +256,42 @@ fn review_questions_hold_the_task_until_answered_and_re_adding_is_idempotent() { assert_eq!(h.writes("issue.create").len(), 1); } +#[test] +fn a_re_add_keeps_a_dependency_a_person_added() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("First", &[]); + let b = h.add("Second", &[])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let added = h.op(Command::Dep { + task: b.clone(), + on: a.clone(), + remove: false, + }); + assert_eq!(added["ok"], true, "{added}"); + h.engine.tick(); + // The producer sends the card it knows, without that edge. + for _ in 0..2 { + h.op(Command::Add { + project: None, + task: Some(b.clone()), + issue: None, + card: card("Second", &[]), + producer_pane: None, + }); + } + let task = h.task(&f, &b); + assert_eq!(task.card.depends_on, vec![a.clone()]); + assert!( + !task + .open_questions() + .any(|q| matches!(q.kind, QuestionKind::ScopeChange { .. })), + "the same card is no scope change" + ); +} + #[test] fn a_prd_changed_while_running_becomes_the_task_s_only_once_approved() { let mut h = Bench::new(false); From 2b72da0bbf7a71f69333a96326b44d5eab7b5e35 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:22:22 +0900 Subject: [PATCH 31/72] Run the restart, sleep-wake and runtime-switch recovery actions, and run an approved one --- docs/factory.md | 10 +-- hide-factory/src/engine.rs | 120 +++++++++++++++++++++++++----- hide-factory/tests/engine.rs | 57 ++++++++++++++ hide-factory/tests/support/mod.rs | 7 +- 4 files changed, 168 insertions(+), 26 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 6483332e36..827278e89b 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -403,17 +403,17 @@ An environment problem is not a Task's failure and is never counted against it. - **Cascade.** Three different Tasks failing the same check or command within 30 minutes are read as the environment: each failure is taken back, the Tasks go to `waiting`, and new starts halt for 30 minutes. - **If it does not clear.** A problem that outlasts 30 minutes asks `factory_env_diagnosis` once for a cause and either one action from the closed list or an exact command with its impact. -The closed recovery list is the only set of actions the Factory runs without a person, and `recovery.=on` turns each on; all are off. +The closed recovery list is the only set of actions the Factory runs without a person, and `config --set recovery==on` turns each on; all are off. Each action touches only the diagnosed Factory's Tasks. | Action | Does | | --- | --- | | `remove_finished_worktrees` | Removes the worktree of a finished Task and of a cancelled Task past its keep period. | -| `restart_worker` | Starts a worker again in the same worktree and session. | -| `sleep_wake_worker` | Puts a worker to sleep or wakes it. | -| `switch_runtime` | Moves an unpinned Task to the other runtime. | +| `restart_worker` | A Task stopped by a refused start, a repeated environment failure, no report or a stall goes back to `waiting`, and its worker starts again in the same worktree and session. | +| `sleep_wake_worker` | A running worker waiting on input is put to sleep and woken in the same session with a note to carry on. | +| `switch_runtime` | New starts of unpinned Tasks leave the Factory's default runtime for an hour, while the other runtime is not limited. | | `retry_reads_and_reconnect` | Clears read back-offs and the start hold. | -A diagnosis naming an action that is off, or any other command, becomes a proposal in the inbox with the exact command and impact, and a person runs or dismisses it. +A diagnosis naming an action that is off becomes a proposal that the Factory runs once a person answers `approve`; any other command becomes a proposal with the exact command and impact, which a person runs themselves or dismisses. Logging in, deleting outside the Factory and installing tools are only ever proposals. A Task that alone repeats an environment failure three times is the Task's: it stops as "same environment failure repeated". diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 9013dd07bc..3036b3c18e 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -2073,15 +2073,23 @@ impl Engine { } _ => {} }, - QuestionKind::Proposal { .. } => { + QuestionKind::Proposal { command, .. } => { // A person runs a proposed command themselves; the Factory - // runs only its typed recovery actions (D-54). + // runs only its typed recovery actions, once approved (B61, + // D-54). self.record( factory, Some(id), "proposal.answered", json!({"decision": decision}), ); + if decision == "approve" + && let Some(action) = RecoveryAction::ALL + .into_iter() + .find(|action| action.as_str() == command) + { + self.run_recovery(factory, action); + } } QuestionKind::Notice => { if task.state == TaskState::Done { @@ -5220,6 +5228,95 @@ impl Engine { } } + /// One action of the closed list (D-54), on this Factory's Tasks only. + fn run_recovery(&mut self, factory: &str, action: RecoveryAction) { + self.record( + factory, + None, + "recovery.run", + json!({"action": action.as_str()}), + ); + match action { + RecoveryAction::RemoveFinishedWorktrees => self.remove_finished_worktrees(), + RecoveryAction::RetryReadsAndReconnect => { + self.github_backoff.clear(); + self.hold_reason = None; + } + // A Task the environment stopped starts its worker again in the + // same worktree and session (B54). + RecoveryAction::RestartWorker => { + let stopped: Vec = self + .tasks_of(factory) + .filter(|t| t.state == TaskState::Stopped) + .filter(|t| { + matches!( + t.stop, + Some( + StopReason::WorkerStart + | StopReason::EnvironmentRepeated + | StopReason::NoReport + | StopReason::Stalled + ) + ) + }) + .map(|t| t.id.clone()) + .collect(); + for id in stopped { + self.with_task(factory, &id, |task| task.environment_failures = 0); + self.record(factory, Some(&id), "recovery.restart_worker", json!({})); + self.set_state(factory, &id, TaskState::Waiting); + } + } + // A running worker waiting on input is put to sleep and woken + // in the same session with a note to carry on. + RecoveryAction::SleepWakeWorker => { + let stuck: Vec<(String, WorkerRef)> = self + .tasks_of(factory) + .filter(|t| t.state == TaskState::Running) + .filter_map(|t| t.worker.clone().map(|w| (t.id.clone(), w))) + .collect(); + for (id, worker) in stuck { + if self.ports.workers.status(&worker) != WorkerStatus::Blocked { + continue; + } + self.record(factory, Some(&id), "recovery.sleep_wake_worker", json!({})); + self.put_to_sleep(factory, &id); + self.wake( + factory, + &id, + "Factory: 환경 복구로 다시 깨웠습니다. 하던 일을 이어가고 끝나면 hide factory done 하세요.", + ); + } + } + // New starts of an unpinned Task leave the Factory's default + // runtime for an hour, while the other one is not limited. + RecoveryAction::SwitchRuntime => { + let Some(runtime) = self + .factories + .get(factory) + .map(|f| f.config.default_runtime) + else { + return; + }; + let other = match runtime { + Runtime::Claude => Runtime::Codex, + Runtime::Codex => Runtime::Claude, + }; + let now = self.now(); + if self + .runtime_blocked + .get(&other) + .is_some_and(|until| *until > now) + { + return; + } + let until = now + HOUR_MS; + let entry = self.runtime_blocked.entry(runtime).or_insert(until); + *entry = (*entry).max(until); + } + } + } + fn apply_diagnosis(&mut self, factory: &str, value: &Value) { let Ok(diagnosis) = judgment::parse_env(value) else { return; @@ -5232,24 +5329,7 @@ impl Engine { let anchor = self.tasks_of(factory).last().map(|t| t.id.clone()); match diagnosis.action { Some(action) if enabled.contains(&action) => { - self.record( - factory, - None, - "recovery.run", - json!({"action": action.as_str()}), - ); - match action { - RecoveryAction::RemoveFinishedWorktrees => self.remove_finished_worktrees(), - RecoveryAction::RetryReadsAndReconnect => { - self.github_backoff.clear(); - self.hold_reason = None; - } - RecoveryAction::RestartWorker - | RecoveryAction::SleepWakeWorker - | RecoveryAction::SwitchRuntime => { - self.runtime_blocked.clear(); - } - } + self.run_recovery(factory, action); } Some(action) => { if let Some(anchor) = anchor { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 34786cb329..d55eb513e9 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1672,6 +1672,63 @@ fn a_low_disk_holds_new_starts_and_the_hold_clears_on_recheck() { assert_eq!(h.state(&f, &u), TaskState::Running); } +#[test] +fn a_diagnosis_runs_an_enabled_recovery_and_an_approved_proposal_runs_too() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().spawn_failure = Some(Failure::task("worker.spawn", "refused")); + let stopped = h.ready("Refused", &[]); + assert_eq!(h.state(&f, &stopped), TaskState::Stopped); + h.world().spawn_failure = None; + h.world().disk_free = Some(1 << 30); + let _held = h.ready("Held", &[]); + let enabled = h.op(Command::Config { + project: Some(PROJECT.into()), + set: vec![("recovery".into(), "restart_worker=on".into())], + }); + assert_eq!(enabled["ok"], true, "{enabled}"); + h.world().env_diagnosis = Some(json!({"cause": "disk", "action": "restart_worker"})); + h.advance(31 * MINUTE_MS); + h.engine.tick(); + h.engine.tick(); + assert_ne!( + h.state(&f, &stopped), + TaskState::Stopped, + "the enabled action ran (B61)" + ); + + // An action outside the enabled scope is a proposal; approving runs it. + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().spawn_failure = Some(Failure::task("worker.spawn", "refused")); + let stopped = h.ready("Refused", &[]); + h.world().spawn_failure = None; + h.world().disk_free = Some(1 << 30); + let _held = h.ready("Held", &[]); + h.world().env_diagnosis = Some(json!({"cause": "disk", "action": "restart_worker"})); + h.advance(31 * MINUTE_MS); + h.engine.tick(); + h.engine.tick(); + assert_eq!(h.state(&f, &stopped), TaskState::Stopped); + let (owner, proposal) = h + .engine + .tasks_of(&f) + .find_map(|t| { + t.open_questions() + .find(|q| matches!(q.kind, QuestionKind::Proposal { .. })) + .map(|q| (t.id.clone(), q.id.clone())) + }) + .expect("a proposal for a person"); + let answered = h.op(Command::Answer { + task: owner, + question: Some(proposal), + choice: Some("approve".into()), + text: None, + }); + assert_eq!(answered["ok"], true, "{answered}"); + assert_ne!(h.state(&f, &stopped), TaskState::Stopped); +} + #[test] fn a_usage_limit_moves_new_starts_to_the_other_runtime() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 230a583b05..cf72a5ec47 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -70,6 +70,8 @@ pub struct World { /// Scripted watch answers, oldest first; no warnings when empty. pub watch: VecDeque, pub judge_down: bool, + /// The environment diagnosis's answer; an unknown cause when absent. + pub env_diagnosis: Option, pub hold_judgments: bool, pub disk_free: Option, pub memory: Option, @@ -429,7 +431,10 @@ impl Judge for Shared { .watch .pop_front() .unwrap_or_else(|| json!({"warnings": []})), - JudgmentInput::EnvDiagnosis { .. } => json!({"cause": "unknown", "action": "none"}), + JudgmentInput::EnvDiagnosis { .. } => world + .env_diagnosis + .clone() + .unwrap_or_else(|| json!({"cause": "unknown", "action": "none"})), }; answers.push(JudgmentAnswer { id: judgment.id.clone(), From 6ac886de3443511428acacfcb859bc9a38d559be Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:23:31 +0900 Subject: [PATCH 32/72] Cap a Task's reports and a verify run's output --- docs/factory.md | 3 ++- hide-factory/src/engine.rs | 19 +++++++++++++++++- hide-factory/src/project.rs | 3 +++ hide-factory/src/verify.rs | 39 ++++++++++++++++++++++++++++++++++++ hide-factory/tests/engine.rs | 29 +++++++++++++++++++++++++++ 5 files changed, 91 insertions(+), 2 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 827278e89b..e13c5f81c0 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -58,7 +58,7 @@ A main recovery the restart cut short is not guessed again, since which merge it The engine opens the store when a store file already exists at start, or on the first command, so a machine that never created a Factory opens nothing. `factory-files///` holds each attached PRD as `.`, a read-only copy of at most 4 MiB, and `factory-files/logs/` holds one `.log` per local verification run. -A run's log keeps only its last 1 MiB when the run ends. +A run's log keeps only its last 1 MiB when the run ends; a run that writes more than 256 MiB is ended and fails as "output over the log cap". The Factory deletes no Task, question, decision, discovery, attempt or attachment. It removes a worker's worktree and pane when the Task is done and main verification has passed, when a cancelled Task or one an outside pull request took passes its keep period, and, only under disk pressure, for finished Tasks. @@ -159,6 +159,7 @@ A capability file holds only a token, so editing it cannot change a role. | Configure | `config --set` | refused | yes | A refusal answers `role_not_allowed` with the role and the verb. +A Task keeps at most 500 questions, decisions and discoveries together; past that a worker's report is refused with `report_limit`. A worker's `show` reaches its own Factory only. An operator relays a person's words, and every answer and decision records the relaying pane as `relayed_by`. Code cannot tell whether an operator pane's agent acted on a person's words, so it records who relayed and does not block. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 3036b3c18e..acd4442459 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -18,7 +18,7 @@ use crate::command::{CardInput, Command, Refusal, VerificationChoice}; use crate::dag; use crate::judgment::{self, Judgment, JudgmentInput, JudgmentOutcome, OtherTask, Priority}; use crate::model::*; -use crate::role::{ROLE_NOT_ALLOWED, Role}; +use crate::role::{Permission, ROLE_NOT_ALLOWED, Role}; use crate::store::{Event, Record, Store, StoreError, sha256_hex}; use crate::summary::{self, FactorySummary}; @@ -63,6 +63,9 @@ const ENV_RECHECK_MS: u64 = MINUTE_MS; /// How often a worker whose agent has not shown a session is asked again, /// and when the person is told to look at its pane. const START_RETRY_MS: u64 = 30_000; +/// The most questions, decisions and discoveries one Task keeps; a worker +/// report past it is refused. +pub const REPORT_LIMIT: usize = 500; /// How often a broken main, or a main head with checks still running, is /// read again. const MAIN_CHECK_EVERY_MS: u64 = 30_000; @@ -557,6 +560,20 @@ impl Engine { .to_json(); } let verb = command.verb(); + // A worker's reports grow its Task record: past the cap a report is + // refused, never stored (rule 15). + if command.permission() == Permission::Report + && let Role::Worker { factory, task } = role + && let Some(task) = self.task(factory, task) + && task.questions.len() + task.decisions.len() + task.discoveries.len() >= REPORT_LIMIT + { + return Refusal::new( + "report_limit", + "This Task holds too many questions and decisions; finish with hide factory done", + ) + .with(json!({"limit": REPORT_LIMIT})) + .to_json(); + } let answer = self.run_command(role, command); match answer { Ok(mut value) => { diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 7ecfcd3aed..3f96ad7616 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -210,6 +210,7 @@ impl Projects { cwd: path, }], timeout: Duration::from_millis(factory.config.verify_timeout_ms), + output_limit: crate::verify::RUN_OUTPUT_LIMIT, }) } @@ -1309,6 +1310,7 @@ impl Verifier for SharedProjects { commands: commands.clone(), prepare: Vec::new(), timeout: Duration::from_millis(factory.config.verify_timeout_ms), + output_limit: crate::verify::RUN_OUTPUT_LIMIT, })?; let log = this.verify.log_path(&id).display().to_string(); Ok(VerifyRun { @@ -1353,6 +1355,7 @@ impl Verifier for SharedProjects { commands: commands.clone(), prepare, timeout: Duration::from_millis(factory.config.verify_timeout_ms), + output_limit: crate::verify::RUN_OUTPUT_LIMIT, })?; let log = this.verify.log_path(&id).display().to_string(); Ok(VerifyRun { diff --git a/hide-factory/src/verify.rs b/hide-factory/src/verify.rs index 86161cd15f..8139ba5b72 100644 --- a/hide-factory/src/verify.rs +++ b/hide-factory/src/verify.rs @@ -19,6 +19,9 @@ const RESULT_LIMIT: usize = 1_024; /// The most runs waiting; a full queue is a reported failure (rule 15). pub const QUEUE_LIMIT: usize = 256; pub const LOG_LIMIT: u64 = 1024 * 1024; +/// The most output a running bundle may write before it is ended; the log +/// is cut to [`LOG_LIMIT`] only after the run (rule 15). +pub const RUN_OUTPUT_LIMIT: u64 = 256 * 1024 * 1024; /// A step run before the commands, such as checking out a commit. #[derive(Clone, Debug, PartialEq, Eq)] @@ -35,6 +38,8 @@ pub struct Job { pub commands: Vec, pub prepare: Vec, pub timeout: Duration, + /// [`RUN_OUTPUT_LIMIT`] outside tests. + pub output_limit: u64, } struct Running { @@ -133,6 +138,22 @@ impl VerifyRunner { ); continue; } + let written = std::fs::metadata(&running.log).map_or(0, |meta| meta.len()); + if written > running.job.output_limit { + let _ = running.child.kill_tree(); + let id = running.job.id.clone(); + let log = running.log.clone(); + self.running = None; + trim(&log); + self.finish( + &id, + VerifyPoll::Failed { + check: format!("{command} (output over the log cap)"), + link: log.display().to_string(), + }, + ); + continue; + } match running.child.try_wait() { Ok(None) => return, Ok(Some(status)) => { @@ -371,6 +392,7 @@ mod tests { commands: commands.iter().map(|c| (*c).to_owned()).collect(), prepare: Vec::new(), timeout, + output_limit: RUN_OUTPUT_LIMIT, } } @@ -515,6 +537,23 @@ mod tests { assert!(!dir.path().join("ran.txt").exists()); } + #[test] + fn a_run_writing_past_the_output_cap_is_ended_and_failed() { + let dir = tempfile::tempdir().unwrap(); + let mut runner = VerifyRunner::new(dir.path().join("logs")); + let mut loud = job("loud", dir.path(), &["yes"], Duration::from_secs(60)); + loud.output_limit = 64 * 1024; + runner.submit(loud).unwrap(); + match wait(&mut runner, "loud") { + VerifyPoll::Failed { check, link } => { + assert_eq!(check, "yes (output over the log cap)"); + assert!(std::fs::metadata(link).unwrap().len() <= LOG_LIMIT); + } + other => panic!("{other:?}"), + } + assert!(!runner.busy()); + } + #[test] fn exit_137_is_the_environment() { let dir = tempfile::tempdir().unwrap(); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index d55eb513e9..e48c34d60d 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -854,6 +854,35 @@ fn a_cancelled_task_s_worker_stays_a_worker_and_is_stopped() { assert_eq!(h.engine.role_for(None, Some(&inside)), bound); } +#[test] +fn a_worker_s_reports_stop_at_the_cap() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Chatty", &[]); + for n in 0..hide_factory::engine::REPORT_LIMIT { + let kept = h.as_worker( + &f, + &t, + Command::Decide { + text: format!("d{n}"), + }, + ); + assert_eq!(kept["ok"], true, "{kept}"); + } + let refused = h.as_worker( + &f, + &t, + Command::Decide { + text: "one more".into(), + }, + ); + assert_eq!(refused["reason"], "report_limit", "{refused}"); + assert_eq!( + h.task(&f, &t).decisions.len(), + hide_factory::engine::REPORT_LIMIT + ); +} + #[test] fn a_worker_cannot_act_as_a_person() { let mut h = Bench::new(false); From 6b84d246b7f3562664016594f78a451ec5033bde Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:25:22 +0900 Subject: [PATCH 33/72] Start an autonomy Task alone only when the intake review finds it fits the scope --- docs/factory.md | 5 ++-- hide-factory/src/engine.rs | 43 +++++++++++++++++++++++++++++- hide-factory/src/judgment.rs | 15 +++++++++-- hide-factory/tests/engine.rs | 44 +++++++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 2 +- 5 files changed, 103 insertions(+), 6 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index e13c5f81c0..7c5c4febf6 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -239,7 +239,7 @@ Every judgment is a tool-less, one-shot call whose input the code bundles and cu | Feature id | Asked | Input | The answer may | | --- | --- | --- | --- | -| `factory_intake_review` | On add and re-add, an edited issue body, a label-path card, a split piece, an approved proposal | The card, its attachment (24 KiB), up to 100 other Tasks, up to 400 file names, the repository guide (8 KiB) | Add questions, dependencies on listed Tasks, a split, and flags | +| `factory_intake_review` | On add and re-add, an edited issue body, a label-path card, a split piece, an approved proposal | The card, its attachment (24 KiB), up to 100 other Tasks, up to 400 file names, the repository guide (8 KiB), and the description of an autonomy scope the Task claims | Add questions, dependencies on listed Tasks, a split, and flags, and say whether the card fits the claimed scope | | `factory_drift` | After `done` | The card, the diff against main (24 KiB), the decisions | Pass, or add questions, and flags | | `factory_check` | At intake or after `done` for each natural-language check | The instruction, the card, the diff | The same as drift | | `factory_watch` | See [The watch](#the-watch) | The Factory's board summary | Warnings, each with an optional action | @@ -388,7 +388,8 @@ A worker may report five classes of discovery with `hide factory propose --class `--reclassify ` may only move a discovery toward a person, in the order `in-scope`, `decision`, `prerequisite`, `scope-change` and `unrelated` (the last two being equal); the reverse answers `reclassify_away_from_person`. A prerequisite needs a card. A Task that was itself proposed or started by autonomy may not propose a Task (`proposal_depth_exceeded`), and each Task may propose `new_task_limit` Tasks (3 by default) before it stops with the "new-Task cap" question. -A proposal that names an enabled `--autonomy` scope drafts the Task now and makes the proposer depend on it and sleep as `blocked`; any other proposal is a question that a person approves before the Task is drafted, and approving it does not make the proposer wait. +A proposal that names an enabled `--autonomy` scope drafts the Task now and makes the proposer depend on it and sleep as `blocked`; any other proposal is a question that a person approves before the Task is drafted, and approving a prerequisite makes the proposer wait on it the same way. +The worker's claim is not the fit: the intake review reads the scope's description and must answer that the card fits it, or the Task loses its autonomy and stays `drafting` with a question a person answers before it runs. Autonomy scopes are the kinds of Task a worker may start without a person. The presets are `flaky_test`, `dependency_patch`, `lint_format` and `docs_links`, all off, and a person may add scopes by name. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index acd4442459..9292cfd5b6 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1638,6 +1638,7 @@ impl Engine { other_tasks, repo_files, guide, + autonomy_scope: self.autonomy_scope(factory, &task), }, }; self.with_task(factory, id, |task| { @@ -1726,13 +1727,53 @@ impl Engine { } } + /// The description of the enabled scope a Task claims. + fn autonomy_scope(&self, factory: &str, task: &Task) -> Option { + let scope = task.autonomy.as_ref()?; + self.factories + .get(factory)? + .config + .autonomy + .iter() + .find(|s| s.id == *scope && s.enabled) + .map(|s| s.description.clone()) + } + fn apply_intake(&mut self, factory: &str, id: &str, value: &Value) { let verdict = match judgment::parse_intake(value) { Ok(verdict) => verdict, Err(reason) => return self.review_failed(factory, id, &reason), }; - let result = verdict.result(); + let mut result = verdict.result(); let now = self.now(); + // A worker's claim is not the fit: only a review that says the card + // fits its enabled scope lets it start without a person (B30). + if let Some(task) = self.task(factory, id).cloned() + && task.autonomy.is_some() + && verdict.fits_scope != Some(true) + { + let scope = self + .autonomy_scope(factory, &task) + .unwrap_or_else(|| task.autonomy.clone().unwrap_or_default()); + self.with_task(factory, id, |task| task.autonomy = None); + self.record(factory, Some(id), "review.outside_scope", json!({})); + self.add_question( + factory, + id, + QuestionOrigin::Review, + QuestionKind::Intake, + &format!( + "worker가 자율 처리 범위 '{}'로 제안한 Task인데 검토가 범위에 맞다고 보지 않았습니다. 사람이 승인하면 진행합니다.", + judgment::cut(&scope, 200) + ), + "진행", + None, + None, + Vec::new(), + None, + ); + result = ReviewResult::NeedsAnswers; + } // The review only adds (D-02, B8): questions, dependencies, flags. for question in &verdict.questions { self.add_question( diff --git a/hide-factory/src/judgment.rs b/hide-factory/src/judgment.rs index 2703724965..75ed29a1f9 100644 --- a/hide-factory/src/judgment.rs +++ b/hide-factory/src/judgment.rs @@ -40,6 +40,10 @@ pub enum JudgmentInput { other_tasks: Vec, repo_files: Vec, guide: Option, + /// The autonomy scope a worker's proposal claims, by its description: + /// the review decides whether the card fits it (B30). + #[serde(default)] + autonomy_scope: Option, }, Drift { card: Card, @@ -117,12 +121,14 @@ impl Judgment { other_tasks, repo_files, guide, + autonomy_scope, } => json!({ "card": card, "attachment": attachment.as_deref().map(|text| cut(text, ATTACHMENT_LIMIT)), "other_tasks": other_tasks, "repo_files": repo_files.iter().take(400).collect::>(), "guide": guide.as_deref().map(|text| cut(text, 8 * 1024)), + "autonomy_scope": autonomy_scope, }), JudgmentInput::Drift { card, @@ -195,6 +201,9 @@ pub struct IntakeVerdict { pub dependencies: Vec, pub split: Vec, pub flags: Vec, + /// Whether the card fits the claimed autonomy scope; `None` when no + /// scope was claimed or the review did not say. + pub fits_scope: Option, } impl IntakeVerdict { @@ -246,6 +255,7 @@ pub fn parse_intake(value: &Value) -> Result { dependencies, split, flags, + fits_scope: value["fits_scope"].as_bool(), }) } @@ -384,10 +394,11 @@ fn intake_schema() -> Value { json!({ "type": "object", "additionalProperties": false, - "required": ["questions", "dependencies", "split", "flags"], + "required": ["questions", "dependencies", "split", "flags", "fits_scope"], "properties": { "questions": {"type": "array", "items": question_item()}, "dependencies": {"type": "array", "items": {"type": "string"}}, + "fits_scope": {"type": ["boolean", "null"]}, "split": {"type": "array", "items": { "type": "object", "additionalProperties": false, @@ -449,7 +460,7 @@ fn env_schema() -> Value { }) } -const INTAKE_SYSTEM: &str = "You review a software Task card before it runs, with no knowledge of the conversation that wrote it. You see only the card, its attached PRD, the repository's file list and guide, and the other Tasks of the same Factory. Return JSON only. You may only add: questions a person must answer before the Task can run safely (each with a concrete suggestion and a default action), dependencies on other listed Tasks by id when this Task cannot start until that one is merged, a split when the Task is clearly too large for one pull request (two or more pieces, each with a goal and checkable criteria, `after` naming earlier pieces), and short flags. Ask about untestable completion criteria, hidden decisions, and mismatch between the card and the PRD. Never rewrite the card. Do not add a dependency only because two Tasks touch the same file. Return empty arrays when the card is ready."; +const INTAKE_SYSTEM: &str = "You review a software Task card before it runs, with no knowledge of the conversation that wrote it. You see only the card, its attached PRD, the repository's file list and guide, and the other Tasks of the same Factory. Return JSON only. You may only add: questions a person must answer before the Task can run safely (each with a concrete suggestion and a default action), dependencies on other listed Tasks by id when this Task cannot start until that one is merged, a split when the Task is clearly too large for one pull request (two or more pieces, each with a goal and checkable criteria, `after` naming earlier pieces), and short flags. Ask about untestable completion criteria, hidden decisions, and mismatch between the card and the PRD. Never rewrite the card. Do not add a dependency only because two Tasks touch the same file. Return empty arrays when the card is ready. When autonomy_scope is given, set fits_scope to true only when the card plainly falls within that description and false otherwise; when it is null, set fits_scope to null."; const DRIFT_SYSTEM: &str = "You compare a finished change with the Task card it claims to complete: its goal, completion criteria and out-of-scope list, and the decisions the worker recorded. Return JSON only. pass is true when the diff does what the card asks and nothing it rules out. When it drifts, add questions for a person, each with a suggestion and a default action that keeps the change as narrow as the card; add flags for a reported breaking change or a public contract change. You cannot send work back and you cannot approve anything wider than the card."; diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index e48c34d60d..88444aaadd 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1007,6 +1007,50 @@ fn a_proposed_task_waits_for_a_person_and_its_worker_cannot_propose() { ); } +#[test] +fn a_proposal_the_review_finds_outside_its_scope_waits_for_a_person() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.op(Command::Config { + project: None, + set: vec![("autonomy".into(), "lint_format=on".into())], + }); + h.world().intake.insert( + "Rewrite the parser".into(), + json!({"questions": [], "dependencies": [], "flags": [], "split": [], "fits_scope": false}), + ); + let t = h.ready("Parent", &[]); + let answer = h.as_worker( + &f, + &t, + Command::Propose { + class: DiscoveryClass::Prerequisite, + text: "needs a new parser".into(), + card: Some(card("Rewrite the parser", &[])), + autonomy: Some("lint_format".into()), + reclassify: None, + letter: None, + }, + ); + let child = answer["task"].as_str().unwrap().to_owned(); + for _ in 0..5 { + h.engine.tick(); + } + let task = h.task(&f, &child); + assert_eq!(task.state, TaskState::Drafting, "it does not start alone"); + assert_eq!(task.autonomy, None); + let question = open_question(&h, &f, &child); + assert!(question.text.contains("Lint and format"), "{}", question.text); + // A person's approval lets it run as an ordinary Task. + h.op(Command::Answer { + task: child.clone(), + question: Some(question.id), + choice: Some("suggestion".into()), + text: None, + }); + tick_until(&mut h, &f, &child, TaskState::Running); +} + #[test] fn an_enabled_autonomy_scope_starts_alone_and_the_third_new_task_stops_the_parent() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index cf72a5ec47..f4b19748e2 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -419,7 +419,7 @@ impl Judge for Shared { let value = match &judgment.input { JudgmentInput::IntakeReview { card, .. } => { world.intake.get(&card.title).cloned().unwrap_or_else( - || json!({"questions": [], "dependencies": [], "flags": [], "split": []}), + || json!({"questions": [], "dependencies": [], "flags": [], "split": [], "fits_scope": true}), ) } JudgmentInput::Drift { .. } | JudgmentInput::Check { .. } => judgment From 60c56ccdd7c03f341911118e323ae2e0358a4308 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:25:31 +0900 Subject: [PATCH 34/72] Say the verify time cap covers the whole bundle --- docs/factory.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 7c5c4febf6..c470b7fe24 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -277,7 +277,7 @@ A completed run passes on `success` or `neutral`, decides nothing on `skipped`, A GitHub error that carries an environment signal is the environment's; any other read error stays pending. **Verify bundle.** Bundles run one at a time on the machine, in a queue of at most 256, each command through the shell with its output in the run's log. -The cap, `verify_timeout_minutes` (60 by default), applies to each command, and a command past it fails the run. +The cap, `verify_timeout_minutes` (60 by default), applies to the whole bundle from its first command, and the command running when it passes fails the run. A command that exits 137, prints "no space left on device" in its last 64 KiB, or dies with no exit code after printing "killed" is an environment failure; every other non-zero exit is the Task's. Each run belongs to the engine, which ends its whole process tree when the Task is cancelled or the core stops. @@ -456,7 +456,7 @@ A Factory's `merge_mode` cannot be `auto` while it has no verification (`auto_ne | `new_task_limit` | Count | 3 | | `verify_failure_limit` | Count, at least 1 | 3 | | `autonomy_diff_limit` | Changed lines an autonomous Task may merge alone | 200 | -| `verify_timeout_minutes` | Minutes per command, at least 1 | 60 | +| `verify_timeout_minutes` | Minutes per bundle run, at least 1 | 60 | | `disk_floor_gb` | Gigabytes | 20 | | `default_runtime` | `claude` or `codex` | Claude Code when `init` finds it on the path, else Codex when it finds that, else `claude` | | `harness` | `:`; empty clears | none | From 2d15fd33e6a0edcfd9978dd5117bdad7fd154391 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:29:56 +0900 Subject: [PATCH 35/72] Drop queued starts at shutdown, release abandoned starts, and hold a slot for a resumed worker still starting --- docs/PERFORMANCE_TESTING.md | 2 +- docs/factory.md | 2 +- herdr-core/src/factory.rs | 315 +++++++++++++++++++++++++----- hide-factory/src/engine.rs | 11 ++ hide-factory/src/model.rs | 2 +- hide-factory/tests/engine.rs | 58 +++++- hide-factory/tests/support/mod.rs | 8 + 7 files changed, 343 insertions(+), 55 deletions(-) diff --git a/docs/PERFORMANCE_TESTING.md b/docs/PERFORMANCE_TESTING.md index fbc3ab137d..4e60f47c61 100644 --- a/docs/PERFORMANCE_TESTING.md +++ b/docs/PERFORMANCE_TESTING.md @@ -69,7 +69,7 @@ The missing bounds and shutdown gaps below describe the current implementation; | Phone connection/detail: `hided/src/mobile/phone.rs`, `mobile/mod.rs` | Live ping 20 s; open pane detail refresh 1 s. | Ping/check silence and read the open detail's pane/conversation. | 2 live connections per phone, 8 queued detail frames, 16 KiB inbound frame, 10 s send bound and 45 s silent limit. | Socket close/revoke/eviction ends its loop; dropping the open detail aborts its detail task. | | Desktop daemon watch: `desktop/src/main/host.ts`, `spawn.ts` | Health recheck 2 s after each response; lost-daemon status poll 3 s after completion. | One HTTP health read or attach-only `hide status`; discovery replaces the watch. | One watch timer and one CLI child; health deadline 1.5 s, status deadline 5 s; 2 health misses mark lost. | Host quit or new discovery clears the timer; quit kills its in-flight CLI child and leaves detached daemons alone. | | GitHub project re-read and store: `runtime/projects.rs` (`reread_stale_github`, `read_sighted_pull_requests`), `labels/worker.rs` (`note_sighted`), `github.rs`, `github_store.rs` | UI-attached gate, like the other capability readers: no read and no clock comparison while no window is attached. Then a comparison on each coordinator wake; a project is asked for again 5 min after its last answer, and not while its previous ask is unanswered; one `gh` pass per changed request. A pull request a local session printed is compared on the labels path whether or not a window is attached, inside the lock section that already hands the worker the pull request times, and only when a read found one; its `gh` read still waits for the gate. | Compare the instants of at most 64 projects (`GithubClock`), advance the generation of the due ones, and let the single reader read only those; after an answer that changed, copy the snapshot under the lock and write it on the store thread. Per transcript read, the worker checks each sighting against the times it holds (no lock); per exchange that carries sightings, the runtime looks each up in the times and its remembered set, and scans the read projects' first pull request and the navigator's panes once per new address; each clock comparison also drops the remembered addresses that grew old and the waiting projects no longer read (at most 64 entries). | 64 projects, the one in front and the ones a screen named first (a count past it is logged as `projects.over_limit` when it changes); at most 32 sightings wait in the worker between two exchanges, the newest kept and the rest logged as `read.sighted_capped`; at most 64 owned addresses remembered for 15 minutes or until an answer holds them, one past it not read and logged as `read.sighted_over_limit`; one reader worker; one store thread with one pending slot, so a burst writes the latest; the file is capped at 32 MiB on read. | The store's Drop joins its thread, so a queued write lands before quit; the reader keeps its existing `BackgroundRead` ownership. | -| Factory host: `herdr-core/src/factory.rs`, `hide-factory/src/engine.rs`, `verify.rs`, `project.rs` | One thread per Core waits on its command channel for up to 2 s; a command is answered at once, and the engine ticks at most every 2 s. Without a Factory store the wake does nothing until the first `hide factory` command opens one. Due inside a tick: the outside world every `outside_read_minutes` (2), running CI checks on one commit again after 30 s, the watch and periodic checks every `watch_interval_minutes` (30). | Pump worker letters, apply finished judgments and verification runs, expire questions, probe each running worker, read the outside world when due, start Tasks into free slots, settle sleeps, deliver woken letters and publish the open Factories with their stall windows. Every subprocess (`git`, `gh`, verify commands) and every SQLite write runs on the host or verify thread; each runtime call takes `Mutex` for owned data only. | 32 queued commands, one judgment in flight with 16 waiting per Factory, one verify run with 256 queued, one worker start with 16 queued on the starter thread, 16 held letters per woken worker, 256 pending CI commits, 20,000 events and 5,000 Tasks per Factory, worker slots by `max_workers` (5) per machine; kept judgment and letter records grow without a count cap (D-58, each cut at 256 KiB). | `FactoryHost::drop` shuts the engine thread down and joins it, and the engine thread closes the start queue and joins the starter after its running start; `JudgeThread::drop` cancels the provider and joins; a verify run's child is stopped through its stop flag. | +| Factory host: `herdr-core/src/factory.rs`, `hide-factory/src/engine.rs`, `verify.rs`, `project.rs` | One thread per Core waits on its command channel for up to 2 s; a command is answered at once, and the engine ticks at most every 2 s. Without a Factory store the wake does nothing until the first `hide factory` command opens one. Due inside a tick: the outside world every `outside_read_minutes` (2), running CI checks on one commit again after 30 s, the watch and periodic checks every `watch_interval_minutes` (30). | Pump worker letters, apply finished judgments and verification runs, expire questions, probe each running worker, read the outside world when due, start Tasks into free slots, settle sleeps, deliver woken letters and publish the open Factories with their stall windows. Every subprocess (`git`, `gh`, verify commands) and every SQLite write runs on the host or verify thread; each runtime call takes `Mutex` for owned data only. | 32 queued commands, one judgment in flight with 16 waiting per Factory, one verify run with 256 queued, one worker start with 16 queued on the starter thread, 16 held letters per woken worker, 256 pending CI commits, 20,000 events and 5,000 Tasks per Factory, worker slots by `max_workers` (5) per machine; kept judgment and letter records grow without a count cap (D-58, each cut at 256 KiB). | `FactoryHost::drop` shuts the engine thread down and joins it, and the engine thread closes the start queue and joins the starter after its running start, dropping the starts still queued; `JudgeThread::drop` cancels the provider and joins; a verify run's child is stopped through its stop flag. | | Elapsed display clock: `web/src/components/elapsed.tsx` | One shared 1 s timer per window while subscribed. | Update the time and notify elapsed-span subscribers in memory; no core snapshot. | One timer; listener count has no fixed numeric cap and fan-out follows the mounted elapsed spans. | Last unsubscribe clears the timer; window destruction ends it. | Worktree, GitHub and disk readers also run on changed explicit requests; those requests are not extra permanent timers (`worktrees.rs`, `github.rs`, `disk.rs`). diff --git a/docs/factory.md b/docs/factory.md index c470b7fe24..20287fd4b8 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -181,7 +181,7 @@ Each open Factory is a code-owned recipient named `factory:` in the A worker starts when the Task may start. The engine asks the core to spawn it through coordination, the same path as `hide agent spawn`, under the Factory's own agent record as parent. -The spawn runs on the host's starter thread, one at a time with at most 16 waiting, because it waits for Herdr to make the worktree and start the agent: the engine keeps the Task's slot, answers commands and worker reports meanwhile, and takes the started worker on the next tick. A Task cancelled or paused while its worker starts has that worker ended when it arrives. +The spawn runs on the host's starter thread, one at a time with at most 16 waiting, because it waits for Herdr to make the worktree and start the agent: the engine keeps the Task's slot, answers commands and worker reports meanwhile, and takes the started worker on the next tick. A Task cancelled or paused while its worker starts has that worker ended when it arrives, and a worktree that start made removed; its next start is a new attempt with its own spawn intent. A restart of a gone worker waits on the starter the same way and holds its slot meanwhile, and a spawn lock another spawn holds is asked again in two seconds. When the host stops, starts still queued are dropped, not run. The record is registered when needed and converges on the existing one. - **Name, branch, intent.** The worker is named `factory--` and works on `factory/-` (`factory/l-` for a local issue, `factory/` without a slug). The spawn intent is `factory--`, and each earlier refused start adds `-a`, so a refused start never repeats a spawn that already failed and a retry of the same attempt converges. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index 40d51f6e6f..10740e9c21 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -178,10 +178,17 @@ struct WorkerState { struct Starts { queue: Option>, in_flight: BTreeSet, - done: BTreeMap>, + done: BTreeMap, abandoned: BTreeSet, } +/// A start the engine has not asked for yet. +struct Finished { + /// A new worker, whose worktree the start made. + fresh: bool, + result: Result, +} + /// Starts waiting for the starter thread; one past it is asked again later. const START_QUEUE_LIMIT: usize = 16; @@ -190,34 +197,81 @@ fn start_key(factory: &str, task: &str) -> String { } /// Runs queued worker starts one at a time until the host drops the queue. +/// Once the host stops, a start still queued is dropped rather than run. +/// A start the engine gave up on while it ran is released: its worker +/// stopped and, for a new worker, the worktree it made removed. fn run_starts( jobs: Receiver, - runtime: Weak>, state: Arc>, + stop: Arc, + start: impl Fn(&WorkerSpawn) -> Result, + release: impl Fn(&WorkerSpawn, &WorkerRef), ) { for job in jobs { let key = start_key(&job.factory, &job.task); - let result = start_worker(&runtime, &job); + if stop.load(Ordering::Acquire) { + if let Ok(mut state) = state.lock() { + state.starts.in_flight.remove(&key); + } + continue; + } + let result = start(&job); let abandoned = { let Ok(mut state) = state.lock() else { return }; state.starts.in_flight.remove(&key); if state.starts.abandoned.remove(&key) { true } else { - state.starts.done.insert(key, result.clone()); + state.starts.done.insert( + key, + Finished { + fresh: job.resume.is_none(), + result: result.clone(), + }, + ); false } }; if abandoned && let Ok(worker) = result { - let mut port = CoreWorkers { - runtime: runtime.clone(), - state: Arc::clone(&state), - }; - if let Err(failure) = port.stop(&worker) { - crate::diagnostic!( - json!({"component":"factory","kind":"worker.abandon_failed","task":job.task,"stage":failure.stage}) - ); - } + release(&job, &worker); + } + } +} + +/// A finished start, `start_pending` while one is queued or running, or +/// `None` when this Task has no start yet. +fn poll_start(state: &Mutex, key: &str) -> Option> { + let Ok(mut state) = state.lock() else { + return Some(Err(Failure::task("worker.spawn", "state_unavailable"))); + }; + if let Some(finished) = state.starts.done.remove(key) { + return Some(finished.result); + } + state + .starts + .in_flight + .contains(key) + .then(|| Err(Failure::start_pending("worker.spawn"))) +} + +/// Hands a start to the starter thread; a full queue is asked again on a +/// later tick, never waited on. +fn queue_start(state: &Mutex, request: &WorkerSpawn) -> Failure { + let key = start_key(&request.factory, &request.task); + let Ok(mut state) = state.lock() else { + return Failure::task("worker.spawn", "state_unavailable"); + }; + let Some(queue) = state.starts.queue.clone() else { + return Failure::starting("worker.spawn", "starter_stopped"); + }; + match queue.try_send(request.clone()) { + Ok(()) => { + state.starts.in_flight.insert(key); + Failure::start_pending("worker.spawn") + } + Err(mpsc::TrySendError::Full(_)) => Failure::start_pending("worker.spawn"), + Err(mpsc::TrySendError::Disconnected(_)) => { + Failure::starting("worker.spawn", "starter_stopped") } } } @@ -249,10 +303,26 @@ fn run( let starter = { let runtime = runtime.clone(); let state = Arc::clone(&workers); + let stop = Arc::clone(&stop); thread::Builder::new() .name("factory-starts".into()) - .spawn(move || run_starts(start_jobs, runtime, state)) + .spawn(move || { + let start = |job: &WorkerSpawn| start_worker(&runtime, job); + let release = |job: &WorkerSpawn, worker: &WorkerRef| { + let mut port = CoreWorkers { + runtime: runtime.clone(), + state: Arc::clone(&state), + }; + port.release_start(&job.task, job.resume.is_none(), worker); + }; + run_starts(start_jobs, Arc::clone(&state), stop, start, release); + }) }; + if let Err(error) = &starter { + crate::diagnostic!( + json!({"component":"factory","kind":"starts.spawn_failed","error":error.to_string()}) + ); + } let runner_stop = Arc::clone(&stop); let mut engine: Option = None; let mut judge: Option = None; @@ -370,7 +440,8 @@ fn run( } drop(engine); drop(judge); - // Closing the queue ends the starter after the start it is running. + // The stop flag is set: closing the queue ends the starter after the + // start it is running, and the starts still queued are dropped. if let Ok(mut state) = workers.lock() { state.starts.queue = None; } @@ -644,6 +715,19 @@ struct CoreWorkers { } impl CoreWorkers { + /// A start no Task claims: its worker stops and, when the start made a + /// new worktree, that worktree and its branch go too. + fn release_start(&mut self, task: &str, fresh: bool, worker: &WorkerRef) { + let mut result = self.stop(worker); + if fresh && result.is_ok() { + result = self.remove_worktree(worker, true); + } + if let Err(failure) = result { + crate::diagnostic!( + json!({"component":"factory","kind":"worker.abandon_failed","task":task,"stage":failure.stage}) + ); + } + } /// Hands each woken worker its letters once its agent is back. fn deliver_woken(&mut self) { let panes: Vec = self @@ -749,17 +833,8 @@ impl WorkerRuntime for CoreWorkers { /// and answers that it is pending. fn spawn(&mut self, request: &WorkerSpawn) -> Result { let key = start_key(&request.factory, &request.task); - { - let mut state = self - .state - .lock() - .map_err(|_| Failure::task("worker.spawn", "state_unavailable"))?; - if let Some(result) = state.starts.done.remove(&key) { - return result; - } - if state.starts.in_flight.contains(&key) { - return Err(Failure::start_pending("worker.spawn")); - } + if let Some(answer) = poll_start(&self.state, &key) { + return answer; } let runtime = self.runtime()?; if request.runtime == hide_factory::model::Runtime::Codex @@ -768,25 +843,7 @@ impl WorkerRuntime for CoreWorkers { return Err(Failure::starting("worker.spawn", "kit_not_read")); } drop(runtime); - let mut state = self - .state - .lock() - .map_err(|_| Failure::task("worker.spawn", "state_unavailable"))?; - let queue = state - .starts - .queue - .clone() - .ok_or_else(|| Failure::task("worker.spawn", "starter_stopped"))?; - match queue.try_send(request.clone()) { - Ok(()) => { - state.starts.in_flight.insert(key); - } - Err(mpsc::TrySendError::Full(_)) => {} - Err(mpsc::TrySendError::Disconnected(_)) => { - return Err(Failure::task("worker.spawn", "starter_stopped")); - } - } - Err(Failure::start_pending("worker.spawn")) + Err(queue_start(&self.state, request)) } fn abandon_start(&mut self, factory: &str, task: &str) { @@ -800,12 +857,12 @@ impl WorkerRuntime for CoreWorkers { } Err(_) => None, }; - if let Some(Ok(worker)) = finished - && let Err(failure) = self.stop(&worker) + if let Some(Finished { + fresh, + result: Ok(worker), + }) = finished { - crate::diagnostic!( - json!({"component":"factory","kind":"worker.abandon_failed","task":task,"stage":failure.stage}) - ); + self.release_start(task, fresh, &worker); } } @@ -1049,8 +1106,13 @@ fn start_worker( }, ); } + // Stable per previous worker and attempt, so a start that is + // asked again continues the same spawn (rule 11). ( - format!("factory-{}-{}-{}", request.factory, request.task, now_ms()), + format!( + "factory-{}-{}-r{}-a{}", + request.factory, request.task, previous.started_at, request.attempt + ), Some(previous.worktree.clone()), ) } @@ -1101,6 +1163,11 @@ fn spawn_failure(reason: &str) -> Failure { // The pane was made and the agent typed in; its session is not // visible yet. The same intent continues the spawn later. "native_identity_unavailable" => Failure::starting("worker.spawn", reason), + // Another spawn on this machine holds the spawn lock: ask again soon. + "spawn_busy" => Failure { + again_in_ms: Some(2_000), + ..Failure::starting("worker.spawn", reason) + }, "delivery_unavailable" | "ledger_unavailable" => { Failure::environment("worker.spawn", EnvSignal::HerdrSocket, reason) } @@ -1429,6 +1496,152 @@ fn judge_loop(shared: Arc, runtime: Weak>, home: Opt #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; + + fn request(task: &str, resume: Option) -> WorkerSpawn { + WorkerSpawn { + factory: "f-1".into(), + task: task.into(), + name: format!("w-{task}"), + runtime: hide_factory::model::Runtime::Claude, + project: "/work/p".into(), + branch: format!("factory/{task}"), + prompt: "p".into(), + args: Vec::new(), + resume, + attempt: 0, + } + } + + fn worker(job: &WorkerSpawn) -> WorkerRef { + WorkerRef { + factory: job.factory.clone(), + agent: Some(format!("agent-{}", job.task)), + name: job.name.clone(), + pane: Some(format!("pane-{}", job.task)), + runtime: job.runtime, + worktree: format!("/work/p.worktrees/{}", job.task), + branch: job.branch.clone(), + started_at: 1, + asleep: false, + } + } + + /// A starter state with a queue of `capacity`, and the queue's far end. + fn starter(capacity: usize) -> (Arc>, Receiver) { + let state = Arc::new(Mutex::new(WorkerState::default())); + let (queue, jobs) = mpsc::sync_channel(capacity); + state.lock().unwrap().starts.queue = Some(queue); + (state, jobs) + } + + fn close(state: &Mutex) { + state.lock().unwrap().starts.queue = None; + } + + #[test] + fn a_start_is_pending_until_the_starter_finishes_and_is_answered_once() { + let (state, jobs) = starter(4); + let job = request("T-1", None); + let key = start_key("f-1", "T-1"); + assert_eq!(poll_start(&state, &key).map(|r| r.is_ok()), None); + let pending = queue_start(&state, &job); + assert_eq!((pending.starting, pending.again_in_ms), (true, Some(0))); + assert!(matches!(poll_start(&state, &key), Some(Err(f)) if f.starting)); + close(&state); + run_starts( + jobs, + Arc::clone(&state), + Arc::new(AtomicBool::new(false)), + |job| Ok(worker(job)), + |_, _| panic!("nothing was abandoned"), + ); + let answer = poll_start(&state, &key).unwrap().unwrap(); + assert_eq!(answer.agent.as_deref(), Some("agent-T-1")); + assert!(poll_start(&state, &key).is_none(), "answered once"); + } + + #[test] + fn a_full_queue_is_asked_again_later_and_never_waited_on() { + let (state, _jobs) = starter(1); + queue_start(&state, &request("T-1", None)); + let full = queue_start(&state, &request("T-2", None)); + assert!(full.starting); + assert!( + poll_start(&state, &start_key("f-1", "T-2")).is_none(), + "not queued, so the next tick queues it" + ); + close(&state); + let stopped = queue_start(&state, &request("T-3", None)); + assert_eq!(stopped.detail, "starter_stopped"); + assert!( + stopped.starting, + "a stopping host is not the Task's failure" + ); + } + + #[test] + fn an_abandoned_start_releases_its_worker_and_a_new_worktree() { + let (state, jobs) = starter(4); + let resumed = request("T-2", Some(worker(&request("T-2", None)))); + queue_start(&state, &request("T-1", None)); + queue_start(&state, &resumed); + { + let mut state = state.lock().unwrap(); + state.starts.abandoned.insert(start_key("f-1", "T-1")); + state.starts.abandoned.insert(start_key("f-1", "T-2")); + } + close(&state); + let released = RefCell::new(Vec::new()); + run_starts( + jobs, + Arc::clone(&state), + Arc::new(AtomicBool::new(false)), + |job| Ok(worker(job)), + |job, worker| { + released + .borrow_mut() + .push((worker.agent.clone().unwrap(), job.resume.is_none())) + }, + ); + assert_eq!( + released.into_inner(), + vec![("agent-T-1".into(), true), ("agent-T-2".into(), false)], + "a resumed worker keeps the Task's worktree" + ); + let state = state.lock().unwrap(); + assert!(state.starts.done.is_empty() && state.starts.in_flight.is_empty()); + assert!(state.starts.abandoned.is_empty()); + } + + #[test] + fn a_stopped_host_drops_the_starts_still_queued() { + let (state, jobs) = starter(4); + queue_start(&state, &request("T-1", None)); + queue_start(&state, &request("T-2", None)); + close(&state); + let started = RefCell::new(0); + run_starts( + jobs, + Arc::clone(&state), + Arc::new(AtomicBool::new(true)), + |job| { + *started.borrow_mut() += 1; + Ok(worker(job)) + }, + |_, _| {}, + ); + assert_eq!(started.into_inner(), 0); + assert!(state.lock().unwrap().starts.in_flight.is_empty()); + } + + #[test] + fn a_busy_spawn_lock_is_asked_again_soon() { + let busy = spawn_failure("spawn_busy"); + assert!(busy.starting && busy.signal.is_none()); + assert_eq!(busy.again_in_ms, Some(2_000)); + assert!(!spawn_failure("worktree_create_failed").starting); + } fn git(cwd: &Path, args: &[&str]) { let status = std::process::Command::new("git") diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 9292cfd5b6..0b1bf16cc1 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -4395,6 +4395,9 @@ impl Engine { .is_none_or(|t| t.state != TaskState::Waiting) { self.ports.workers.abandon_start(&factory, &id); + // A later start is a new attempt, never the abandoned one + // replayed by its intent. + self.with_task(&factory, &id, |t| t.spawn_refusals += 1); self.starting.remove(&(factory, id)); } } @@ -4567,8 +4570,10 @@ impl Engine { } else { self.ports.workers.wake(&worker, &body).map(|()| None) }; + let key = (factory_id.to_owned(), id.to_owned()); match restarted { Ok(new_worker) => { + self.starting.remove(&key); self.with_task(factory_id, id, |t| { if let Some(w) = new_worker { t.worker = Some(w); @@ -4582,7 +4587,13 @@ impl Engine { self.set_state(factory_id, id, TaskState::Running); true } + // A restart still on its way holds the slot like a new one. + Err(failure) if failure.starting => { + self.worker_starting(factory_id, id, &failure); + true + } Err(failure) => { + self.starting.remove(&key); self.external_failure(factory_id, Some(id), &failure); false } diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 1cb9d7eba4..5f1c1f1bb3 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -795,7 +795,7 @@ pub struct Task { /// as a refused worker start; shown beside the stop reason. #[serde(default)] pub stop_detail: Option, - /// Fresh worker starts refused so far; names the next start's intent. + /// Worker starts refused or abandoned so far; names the next start's intent. #[serde(default)] pub spawn_refusals: u32, pub breaking: bool, diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 88444aaadd..ece7810cef 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1040,7 +1040,11 @@ fn a_proposal_the_review_finds_outside_its_scope_waits_for_a_person() { assert_eq!(task.state, TaskState::Drafting, "it does not start alone"); assert_eq!(task.autonomy, None); let question = open_question(&h, &f, &child); - assert!(question.text.contains("Lint and format"), "{}", question.text); + assert!( + question.text.contains("Lint and format"), + "{}", + question.text + ); // A person's approval lets it run as an ordinary Task. h.op(Command::Answer { task: child.clone(), @@ -2133,6 +2137,58 @@ fn a_start_carried_out_off_the_engine_is_asked_for_again_on_the_next_tick() { assert_eq!(h.state(&f, &a), TaskState::Running, "no 30-second wait"); } +#[test] +fn a_start_cancelled_on_its_way_is_abandoned_and_a_revive_is_a_new_attempt() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().spawn_failure = Some(Failure::start_pending("worker.spawn")); + let t = h.ready("On its way", &[]); + assert_eq!(h.state(&f, &t), TaskState::Waiting); + h.op(Command::Cancel { task: t.clone() }); + h.engine.tick(); + assert_eq!(h.world().abandoned, vec![t.clone()]); + h.world().spawn_failure = None; + h.op(Command::Revive { task: t.clone() }); + tick_until(&mut h, &f, &t, TaskState::Running); + let attempts: Vec = h.world().spawn_asks.iter().map(|r| r.attempt).collect(); + assert_eq!(attempts.first(), Some(&0)); + assert_eq!(attempts.last(), Some(&1), "never the abandoned intent"); +} + +#[test] +fn a_resumed_worker_still_starting_holds_its_slot_without_a_failure_per_tick() { + let mut h = Bench::new(false); + let f = h.factory(true); + set_workers(&mut h, &f, 1); + let t = h.ready("Resumed", &[]); + h.world() + .worker_status + .insert(t.clone(), WorkerStatus::Gone); + h.advance(5 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Stopped); + h.world().spawn_failure = Some(Failure::start_pending("worker.spawn")); + h.op(Command::Retry { task: t.clone() }); + let other = h.ready("Other", &[]); + for _ in 0..5 { + h.engine.tick(); + } + assert_eq!(h.state(&f, &other), TaskState::Waiting, "the slot is held"); + let failures = h + .engine + .events(&f, Some(&t), 200) + .iter() + .filter(|e| e.kind == "external.failed") + .count(); + assert_eq!(failures, 0, "a pending start is not a failure"); + assert!( + h.world() + .spawn_asks + .iter() + .any(|r| r.task == t && r.resume.is_some()) + ); +} + #[test] fn a_worker_whose_agent_has_not_started_holds_its_slot_and_is_asked_again_later() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index f4b19748e2..ace97b55b3 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -61,6 +61,10 @@ pub struct World { /// Usage-limit resets the machine reports by runtime. pub usage_limits: BTreeMap, pub spawn_failure: Option, + /// Every spawn the engine asked for, answered or not. + pub spawn_asks: Vec, + /// Starts the engine gave up on, by Task id. + pub abandoned: Vec, /// Judgments submitted and not yet answered. pub submitted: Vec, pub judged: Vec, @@ -328,6 +332,7 @@ impl MergeTarget for Shared { impl WorkerRuntime for Shared { fn spawn(&mut self, request: &WorkerSpawn) -> Result { let mut world = self.world(); + world.spawn_asks.push(request.clone()); if let Some(failure) = world.spawn_failure.clone() { return Err(failure); } @@ -374,6 +379,9 @@ impl WorkerRuntime for Shared { .copied() .unwrap_or(WorkerStatus::Working) } + fn abandon_start(&mut self, _factory: &str, task: &str) { + self.world().abandoned.push(task.to_owned()); + } fn stop(&mut self, worker: &WorkerRef) -> Result<(), Failure> { self.world().stops.push(task_of(worker)); Ok(()) From 985e4d4c47ac71cd91d05843bc3938795682555f Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:31:41 +0900 Subject: [PATCH 36/72] Count failed store writes, show them in status and log them from the host --- docs/factory.md | 1 + herdr-core/src/factory.rs | 10 ++++++ hide-factory/src/command.rs | 5 +++ hide-factory/src/engine.rs | 62 +++++++++++++++++++++++++++++++++--- hide-factory/tests/engine.rs | 27 ++++++++++++++++ 5 files changed, 100 insertions(+), 5 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 20287fd4b8..4b5ed8a633 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -54,6 +54,7 @@ A store written by a newer build is refused rather than read: the engine does no Fields added later load from older rows through serde defaults. The engine loads the whole store at start and saves each change before the command that made it answers, so a restart resumes Factories, Tasks, questions, workers and in-flight work. A restart starts verification again from the recorded attempt and asks a pending review again. +A store write that fails does not stop the engine: it is counted, `hide factory status` says how many failed since start, and the host writes each one to the diagnostic log (`store.write_failed`, with the Factory, Task and stage). A main recovery the restart cut short is not guessed again, since which merge it was finding or reverting lived only in the old process: it goes to a person with the same choices as a recovery that could not decide. The engine opens the store when a store file already exists at start, or on the first command, so a machine that never created a Factory opens nothing. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index 10740e9c21..edf9fe0293 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -427,6 +427,16 @@ fn run( port.deliver_woken(); publish_recipients(Some(engine), &runtime); } + for failure in engine.take_store_failures() { + crate::diagnostic!(json!({ + "component": "factory", + "kind": "store.write_failed", + "factory_id": failure.factory, + "task_id": failure.task, + "stage": failure.stage, + "error": failure.error, + })); + } waiters.retain(|waiter| { let settled = engine.review_settled(&waiter.factory, &waiter.task); if settled || Instant::now() >= waiter.until { diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs index 60e9778667..ccab169f17 100644 --- a/hide-factory/src/command.rs +++ b/hide-factory/src/command.rs @@ -373,6 +373,11 @@ fn render_init(answer: &Value) -> String { fn render_status(answer: &Value) -> String { let mut text = String::new(); + if let Some(failures) = answer["store_failures"].as_u64().filter(|n| *n > 0) { + text.push_str(&format!( + "store writes failed {failures} times since start; see the diagnostic log\n" + )); + } for factory in answer["factories"].as_array().into_iter().flatten() { let flow = &factory["flow"]; text.push_str(&format!( diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 0b1bf16cc1..65bfdf6b8b 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -4,6 +4,7 @@ //! `tick` for time and the outside world. Each change is saved before the //! answer leaves (B72). +use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; @@ -82,6 +83,25 @@ struct VerifyState { stage: AttemptStage, } +/// Failed store writes: a running count, and the ones the host has not +/// logged yet (at most [`STORE_FAILURE_LIMIT`]). +#[derive(Default)] +struct StoreFailures { + total: u64, + unlogged: Vec, +} + +/// One failed store write, for the diagnostic log. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoreFailure { + pub factory: String, + pub task: Option, + pub stage: String, + pub error: String, +} + +const STORE_FAILURE_LIMIT: usize = 64; + #[derive(Clone)] enum RevertPhase { /// A skipped or cancelled run was asked again; waits for its result. @@ -133,6 +153,9 @@ pub struct Engine { reverts: BTreeMap, /// Main heads already checked per Factory. main_seen: BTreeMap, + /// Store writes that failed: the host logs the new ones and `status` + /// shows the count, since an event about a failed write may fail too. + store_failures: RefCell, /// Factories whose main head has a check still running: read again at /// the paced interval until it finishes (B47). main_pending: BTreeSet, @@ -200,6 +223,7 @@ impl Engine { checks_running: BTreeMap::new(), reverts: BTreeMap::new(), main_seen: BTreeMap::new(), + store_failures: RefCell::new(StoreFailures::default()), main_pending: BTreeSet::new(), main_checked_at: BTreeMap::new(), publish_retry: BTreeMap::new(), @@ -358,8 +382,29 @@ impl Engine { kind: kind.to_owned(), detail, }; - // A failed diagnostic write never changes a decision. - let _ = self.store.append_event(&event); + // A failed event write never changes a decision; it is counted and + // reaches the diagnostic log through the host. + if let Err(error) = self.store.append_event(&event) { + self.store_failed(factory, task, "event", &error.0); + } + } + + fn store_failed(&self, factory: &str, task: Option<&str>, stage: &str, error: &str) { + let mut failures = self.store_failures.borrow_mut(); + failures.total += 1; + if failures.unlogged.len() < STORE_FAILURE_LIMIT { + failures.unlogged.push(StoreFailure { + factory: factory.to_owned(), + task: task.map(str::to_owned), + stage: stage.to_owned(), + error: judgment::cut(error, 300), + }); + } + } + + /// Failed store writes since the last call, for the diagnostic log. + pub fn take_store_failures(&self) -> Vec { + std::mem::take(&mut self.store_failures.borrow_mut().unlogged) } /// Keeps a judgment or letter body with its Task (D-58); like an event, @@ -374,6 +419,7 @@ impl Engine { body: body.to_owned(), }; if let Err(error) = self.store.keep_record(&record) { + self.store_failed(factory, task, "record", &error.0); self.record( factory, task, @@ -399,6 +445,7 @@ impl Engine { if let Some(factory) = self.factories.get(id) && let Err(error) = self.store.put_factory(factory) { + self.store_failed(id, None, "factory", &error.0); self.record( id, None, @@ -418,6 +465,7 @@ impl Engine { return; }; if let Err(error) = self.store.put_task(&task) { + self.store_failed(factory, Some(id), "task", &error.0); self.record( factory, Some(id), @@ -3998,7 +4046,9 @@ impl Engine { let id = self.factory_id(Some(project))?; summary.factories.retain(|f| f.id == id); } - Ok(serde_json::to_value(&summary).unwrap_or_default()) + let mut value = serde_json::to_value(&summary).unwrap_or_default(); + value["store_failures"] = json!(self.store_failures.borrow().total); + Ok(value) } /// A Task's kept judgment and letter bodies, oldest first (D-58). @@ -4094,10 +4144,12 @@ impl Engine { let old = self.processed_order.remove(0); self.processed.remove(&old); } - let _ = self.store.set_meta( + if let Err(error) = self.store.set_meta( "processed_letters", &serde_json::to_string(&self.processed_order).unwrap_or_default(), - ); + ) { + self.store_failed("-", None, "letters", &error.0); + } } } diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index ece7810cef..d43eb1da91 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1806,6 +1806,33 @@ fn a_diagnosis_runs_an_enabled_recovery_and_an_approved_proposal_runs_too() { assert_ne!(h.state(&f, &stopped), TaskState::Stopped); } +#[test] +fn a_failed_store_write_is_counted_and_handed_to_the_host_log() { + let mut h = Bench::new(false); + let f = h.factory(true); + assert!(h.engine.take_store_failures().is_empty()); + // Another connection makes every task write fail, as a full disk would. + let db = rusqlite::Connection::open(h.dir.path().join("factory.sqlite3")).unwrap(); + db.execute_batch( + "CREATE TRIGGER refuse_tasks BEFORE INSERT ON tasks BEGIN SELECT RAISE(FAIL, 'disk full'); END; + CREATE TRIGGER refuse_task_updates BEFORE UPDATE ON tasks BEGIN SELECT RAISE(FAIL, 'disk full'); END;", + ) + .unwrap(); + let _ = h.add("Unsaved", &[]); + let failures = h.engine.take_store_failures(); + assert!( + failures.iter().any(|failure| failure.stage == "task"), + "{failures:?}" + ); + assert!(failures.iter().all(|failure| failure.factory == f)); + assert!( + h.engine.take_store_failures().is_empty(), + "handed over once" + ); + let status = h.op(Command::Status { project: None }); + assert!(status["store_failures"].as_u64().unwrap() > 0, "{status}"); +} + #[test] fn a_usage_limit_moves_new_starts_to_the_other_runtime() { let mut h = Bench::new(false); From 874a4971b0cc2a6ac9c65bfd7d7dbdf35ce20b73 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:32:08 +0900 Subject: [PATCH 37/72] Tell a timed-out factory command to check status before retrying --- hided/src/server.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/hided/src/server.rs b/hided/src/server.rs index 1f92d51e47..191ef0d803 100644 --- a/hided/src/server.rs +++ b/hided/src/server.rs @@ -1090,7 +1090,16 @@ async fn scoped_client_loop( ScopedRequest::Factory(command, hint) => { core.prepare_factory(&cap.context.device_id, &cap.pane_id, &cap.context, hint, command) .and_then(|prepared| prepared.run(FACTORY_ANSWER_TIMEOUT)) - .map_err(|code| (code, "Check that Hide is running and retry"))? + // A timed-out command may still apply: retrying blind + // can add a Task twice, so look first. + .map_err(|code| { + let next = if code == "factory_timeout" { + "The command may still apply; check hide factory status before retrying" + } else { + "Check that Hide is running and retry" + }; + (code, next) + })? } ScopedRequest::Links(query) => { let scope = core.links_scope(&cap.context).ok_or(( From 6900e59e6c4bb8886d1449058a00e6a24e6a5b78 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:34:58 +0900 Subject: [PATCH 38/72] Bind a worker's spawned agents and claimed panes to its worker role --- docs/factory.md | 1 + herdr-core/src/factory.rs | 19 ++++++- herdr-core/src/runtime/factory.rs | 93 +++++++++++++++++++++++++++++++ hide-factory/src/engine.rs | 15 +++++ hide-factory/tests/engine.rs | 19 +++++++ hide-factory/tests/support/mod.rs | 2 +- 6 files changed, 147 insertions(+), 2 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 4b5ed8a633..dad9a65d48 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -143,6 +143,7 @@ Adding a dependency to a running Task whose predecessor is unmerged puts the Tas Each command runs with a role the engine decides from its own store, never from the caller's claim or a file. A caller is a worker when its pane is the pane of a Task's worker, or when its working folder is inside a Task's worktree. A `cancelled` or `done` Task's worker stays a worker, so its pane never gains an operator's commands, and the Task's state refuses its reports; a live Task wins when a pane or folder was reused. +An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up), and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index edf9fe0293..ff8c0c1c12 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -59,6 +59,12 @@ fn guard(runtime: &Arc>) -> MutexGuard<'_, Runtime> { pub struct FactoryCaller { pub pane: Option, pub cwd: Option, + /// A pane the caller named but could not be checked against: it can only + /// make the caller a worker, never an operator. + pub claimed: Option, + /// The agents above the caller in the spawn lineage, nearest first: a + /// worker's child is a worker of the same Task (D-33). + pub ancestors: Vec, } enum Request { @@ -502,7 +508,18 @@ fn handle( caller: &FactoryCaller, command: Command, ) -> Value { - let role = match engine.role_for(caller.pane.as_deref(), caller.cwd.as_deref()) { + // Everything that names a worker binds to it: the caller's own pane or + // folder, a pane it claimed, or an agent above it in the spawn lineage. + let bound = engine + .role_for(caller.pane.as_deref(), caller.cwd.as_deref()) + .or_else(|| { + caller + .claimed + .as_deref() + .and_then(|pane| engine.role_for(Some(pane), None)) + }) + .or_else(|| engine.role_for_agents(&caller.ancestors)); + let role = match bound { Some((factory, task)) => Role::Worker { factory, task }, None => Role::Operator { pane: caller.pane.clone().unwrap_or_else(|| "checkout".into()), diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index 6edc2c5e74..5edf6f1dab 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -22,6 +22,9 @@ pub(crate) struct WorkerProbe { pub status_changed_at_unix_ms: u64, } +/// How far up the spawn lineage a caller is followed to its worker. +const LINEAGE_LIMIT: usize = 16; + impl Runtime { /// Checks a local caller like a delivery request does and names the pane /// and checkout it speaks from. @@ -47,12 +50,50 @@ impl Runtime { }) .map(str::to_owned), }; + let claimed = hint + .filter(|hint| pane.as_deref() != Some(*hint)) + .map(str::to_owned); + let ancestors = pane + .as_deref() + .or(claimed.as_deref()) + .map(|pane| self.factory_lineage(pane)) + .unwrap_or_default(); Ok(crate::factory::FactoryCaller { pane, cwd: Some(context.checkout_path.clone()).filter(|path| !path.is_empty()), + claimed, + ancestors, }) } + /// The agent ids above `pane` in the spawn lineage, nearest first, from + /// the ledger in memory; at most [`LINEAGE_LIMIT`] steps. + fn factory_lineage(&self, pane: &str) -> Vec { + let Ok(ledger) = self.delivery_state() else { + return Vec::new(); + }; + let parent_of = |agent: &crate::coordination::AgentRecord| agent.parent.clone(); + let mut next = ledger + .agents + .iter() + .rev() + .find(|agent| agent.pane == pane) + .and_then(parent_of); + let mut ancestors = Vec::new(); + while let Some(id) = next { + if ancestors.len() >= LINEAGE_LIMIT || ancestors.contains(&id) { + break; + } + next = ledger + .agents + .iter() + .find(|agent| agent.id == id) + .and_then(parent_of); + ancestors.push(id); + } + ancestors + } + /// A delivery command the Factory sends as its own recipient, to the pane /// `target` when the command has one. pub(crate) fn factory_prepare( @@ -274,7 +315,59 @@ fn usage_limit( #[cfg(test)] mod tests { use super::*; + use crate::coordination::AgentRecord; + use crate::delivery::ledger::Ledger; use crate::model::{ProviderUsageBucketSnapshot, ProviderUsageSnapshot}; + use std::sync::Arc; + + fn agent(id: &str, pane: &str, parent: Option<&str>) -> AgentRecord { + AgentRecord { + id: id.into(), + name: id.into(), + machine: "local".into(), + host_scope: "fixture".into(), + native_machine: "fixture-machine".into(), + session: id.into(), + instance: pane.into(), + pane: pane.into(), + parent: parent.map(str::to_owned), + project: None, + actor: Actor { + pane_id: pane.into(), + name: id.into(), + kind: "claude".into(), + device_id: "local".into(), + session: crate::wire::session_digest(id), + }, + ended: false, + } + } + + #[test] + fn a_caller_s_lineage_names_every_agent_above_it_and_stops_at_a_loop() { + let mut runtime = crate::runtime::tests::runtime(); + runtime.delivery_ledger = Ok(Arc::new(Ledger { + agents: vec![ + agent("agent-factory", "factory:f-1", None), + agent("agent-worker", "w1:p1", Some("agent-factory")), + agent("agent-child", "w2:p1", Some("agent-worker")), + agent("agent-grandchild", "w3:p1", Some("agent-child")), + agent("agent-a", "w9:p1", Some("agent-b")), + agent("agent-b", "w9:p2", Some("agent-a")), + ], + ..Ledger::default() + })); + assert_eq!( + runtime.factory_lineage("w3:p1"), + vec!["agent-child", "agent-worker", "agent-factory"] + ); + assert!(runtime.factory_lineage("w0:p1").is_empty()); + assert_eq!( + runtime.factory_lineage("w9:p1"), + vec!["agent-b", "agent-a"], + "a loop ends the walk" + ); + } fn row(provider: &str, used: f64, bucket: Option<(f64, u64)>) -> ProviderUsageSnapshot { ProviderUsageSnapshot { diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 65bfdf6b8b..bb86e14585 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -345,6 +345,21 @@ impl Engine { self.store.events(factory, task, limit).unwrap_or_default() } + /// The Task whose worker is one of `agents` (a caller's spawn lineage): + /// a worker's child acts as that worker (D-33). + pub fn role_for_agents(&self, agents: &[String]) -> Option<(String, String)> { + let bound = |task: &&Task| { + task.worker + .as_ref() + .and_then(|worker| worker.agent.as_ref()) + .is_some_and(|agent| agents.contains(agent)) + }; + let finished = |task: &&Task| matches!(task.state, TaskState::Cancelled | TaskState::Done); + let live = self.all_tasks().filter(|t| !finished(t)).find(&bound); + live.or_else(|| self.all_tasks().filter(&finished).find(&bound)) + .map(|task| (task.factory.clone(), task.id.clone())) + } + /// The role of a caller (D-33): a pane the Factory spawned, or a cwd /// inside a Factory worktree, is a worker of that Task. A finished or /// cancelled Task's worker stays a worker, so its pane never gains the diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index d43eb1da91..27b03b49cb 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -883,6 +883,25 @@ fn a_worker_s_reports_stop_at_the_cap() { ); } +#[test] +fn an_agent_a_worker_spawned_acts_as_that_worker() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Parent", &[]); + let agent = h.task(&f, &t).worker.unwrap().agent.unwrap(); + // The child's own pane and folder name no Task; its lineage does. + assert_eq!( + h.engine.role_for(Some("child-pane"), Some("/elsewhere")), + None + ); + assert_eq!( + h.engine + .role_for_agents(&["agent-child".into(), agent, "agent-factory".into()]), + Some((f.clone(), t.clone())) + ); + assert_eq!(h.engine.role_for_agents(&["agent-other".into()]), None); +} + #[test] fn a_worker_cannot_act_as_a_person() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index ace97b55b3..cd82f57fc8 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -340,7 +340,7 @@ impl WorkerRuntime for Shared { world.worker_status.remove(&request.task); Ok(WorkerRef { factory: String::new(), - agent: None, + agent: Some(format!("agent-{}", request.task)), name: request.name.clone(), pane: Some(format!("pane-{}", request.task)), runtime: request.runtime, From 316e930def9af1f63ab46111fb3e385a247fd41a Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:35:51 +0900 Subject: [PATCH 39/72] Test the Factory judgment queue's order and per-Factory limit --- herdr-core/src/factory.rs | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index ff8c0c1c12..c46b37bc06 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -1662,6 +1662,61 @@ mod tests { assert!(state.lock().unwrap().starts.in_flight.is_empty()); } + fn judgment(factory: &str, id: &str, priority: hide_factory::judgment::Priority) -> Judgment { + Judgment { + id: id.into(), + factory: factory.into(), + task: None, + priority, + input: hide_factory::judgment::JudgmentInput::Watch { board: json!({}) }, + } + } + + #[test] + fn intake_reviews_go_first_and_each_factory_queues_at_most_its_limit() { + use hide_factory::judgment::{Priority, QUEUE_LIMIT}; + let shared = Arc::new(JudgeShared { + queue: Mutex::new(VecDeque::new()), + answers: Mutex::new(Vec::new()), + wake: std::sync::Condvar::new(), + stop: AtomicBool::new(false), + cancel: hide_ai::CancelToken::new(), + }); + let mut port = JudgePort { + shared: Arc::clone(&shared), + alive: true, + }; + port.submit(judgment("f-1", "watch", Priority::Factory)) + .unwrap(); + port.submit(judgment("f-1", "intake", Priority::Intake)) + .unwrap(); + port.submit(judgment("f-1", "drift", Priority::Factory)) + .unwrap(); + let order: Vec = shared + .queue + .lock() + .unwrap() + .iter() + .map(|j| j.id.clone()) + .collect(); + assert_eq!(order, vec!["intake", "watch", "drift"]); + for n in 3..QUEUE_LIMIT { + port.submit(judgment("f-1", &format!("j{n}"), Priority::Factory)) + .unwrap(); + } + let full = port + .submit(judgment("f-1", "one more", Priority::Intake)) + .unwrap_err(); + assert_eq!(full.detail, "the Factory's judgment queue is full"); + port.submit(judgment("f-2", "another factory", Priority::Factory)) + .expect("the limit is per Factory"); + let mut dead = JudgePort { + shared, + alive: false, + }; + assert!(dead.submit(judgment("f-3", "x", Priority::Intake)).is_err()); + } + #[test] fn a_busy_spawn_lock_is_asked_again_soon() { let busy = spawn_failure("spawn_busy"); From 65be37e824ef3c10c6600d2eb22f6ef021e09720 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:37:50 +0900 Subject: [PATCH 40/72] Test that a GitHub revert opens one pull request and merges it once at its commit --- hide-factory/tests/github.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index a39b36c13d..5aaf782f17 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -348,6 +348,33 @@ fn a_merge_without_a_verified_commit_is_refused() { ); } +#[test] +fn a_github_revert_is_one_pull_request_merged_once_at_its_commit() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + let t = task("T-1", Some(1)); + let revert = p.revert(&factory, &t, "bad1").unwrap(); + let number = revert.pr.expect("a revert pull request"); + assert_eq!(revert.commit.as_deref(), Some("headsha")); + // Asked again after a lost answer: the open pull request is found. + let again = p.revert(&factory, &t, "bad1").unwrap(); + assert_eq!(again.pr, Some(number)); + let landed = p.merge_revert(&factory, &revert).unwrap(); + assert_eq!(landed, format!("merge{number}")); + assert_eq!(p.merge_revert(&factory, &revert).unwrap(), landed); + let hub = gh.0.lock().unwrap(); + assert_eq!( + hub.writes, + vec![format!("pr create {number}"), format!("pr merge {number}")] + ); + assert!( + hub.pushes + .iter() + .all(|refspec| refspec == "HEAD:refs/heads/factory/revert-t-1") + ); +} + #[test] fn required_checks_decide_and_a_cancelled_run_is_asked_again() { let gh = FakeGh::default(); From eb7318fd267e7022aa7c6003cd10ad327d013f7e Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:56:55 +0900 Subject: [PATCH 41/72] Let a worker finish past the report cap and bind no caller to a Task whose worktree is gone --- docs/factory.md | 5 +++-- hide-factory/src/engine.rs | 15 ++++++++++----- hide-factory/tests/engine.rs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index dad9a65d48..cac4440ff7 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -142,7 +142,8 @@ Adding a dependency to a running Task whose predecessor is unmerged puts the Tas Each command runs with a role the engine decides from its own store, never from the caller's claim or a file. A caller is a worker when its pane is the pane of a Task's worker, or when its working folder is inside a Task's worktree. -A `cancelled` or `done` Task's worker stays a worker, so its pane never gains an operator's commands, and the Task's state refuses its reports; a live Task wins when a pane or folder was reused. +A `cancelled` or `done` Task's worker stays a worker while its worktree and pane stay, so its pane never gains an operator's commands, and the Task's state refuses its reports; a live Task wins when a pane or folder was reused. +Once a Task's worktree is removed it binds no pane or folder, because Herdr can give a closed pane id to the operator's next pane. An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up), and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. @@ -161,7 +162,7 @@ A capability file holds only a token, so editing it cannot change a role. | Configure | `config --set` | refused | yes | A refusal answers `role_not_allowed` with the role and the verb. -A Task keeps at most 500 questions, decisions and discoveries together; past that a worker's report is refused with `report_limit`. +A Task keeps at most 500 questions, decisions and discoveries together; past that a worker's report is refused with `report_limit`, except `done`, which still finishes the Task without storing its summary. A worker's `show` reaches its own Factory only. An operator relays a person's words, and every answer and decision records the relaying pane as `relayed_by`. Code cannot tell whether an operator pane's agent acted on a person's words, so it records who relayed and does not block. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index bb86e14585..531497296f 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -362,11 +362,13 @@ impl Engine { /// The role of a caller (D-33): a pane the Factory spawned, or a cwd /// inside a Factory worktree, is a worker of that Task. A finished or - /// cancelled Task's worker stays a worker, so its pane never gains the - /// operator's commands; a live Task wins when a pane or folder was reused. + /// cancelled Task's worker stays a worker while its worktree and pane + /// stay, so its pane never gains the operator's commands; a live Task + /// wins when a pane or folder was reused. A purged Task binds nothing, + /// because Herdr can give its closed pane id to the operator's next pane. pub fn role_for(&self, pane: Option<&str>, cwd: Option<&str>) -> Option<(String, String)> { let bound = |task: &&Task| { - let Some(worker) = &task.worker else { + let Some(worker) = task.worker.as_ref().filter(|_| !task.purged) else { return false; }; if pane.is_some() && worker.pane.as_deref() == pane { @@ -624,8 +626,9 @@ impl Engine { } let verb = command.verb(); // A worker's reports grow its Task record: past the cap a report is - // refused, never stored (rule 15). + // refused, never stored (rule 15). `done` still finishes the Task. if command.permission() == Permission::Report + && !matches!(command, Command::Done { .. }) && let Role::Worker { factory, task } = role && let Some(task) = self.task(factory, task) && task.questions.len() + task.decisions.len() + task.discoveries.len() >= REPORT_LIMIT @@ -2612,7 +2615,9 @@ impl Engine { self.with_task(factory_id, id, |task| { task.last_report_at = Some(now); task.breaking |= breaking; - if let Some(text) = &summary_text { + let full = task.questions.len() + task.decisions.len() + task.discoveries.len() + >= REPORT_LIMIT; + if let Some(text) = summary_text.as_ref().filter(|_| !full) { task.decisions.push(DecisionRecord { text: format!("done: {}", judgment::cut(text, TEXT_LIMIT)), by: format!("worker:{id}"), diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 27b03b49cb..21ef86eafe 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -854,6 +854,22 @@ fn a_cancelled_task_s_worker_stays_a_worker_and_is_stopped() { assert_eq!(h.engine.role_for(None, Some(&inside)), bound); } +#[test] +fn a_finished_task_whose_pane_is_gone_binds_no_caller() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Landed", &[]); + let worker = h.task(&f, &t).worker.unwrap(); + let pane = worker.pane.clone().unwrap(); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::Done); + assert!(h.task(&f, &t).purged, "the worktree and pane are gone"); + // Herdr can give that pane id to the operator's next pane. + assert_eq!(h.engine.role_for(Some(&pane), None), None); + let inside = format!("{}/src", worker.worktree); + assert_eq!(h.engine.role_for(None, Some(&inside)), None); +} + #[test] fn a_worker_s_reports_stop_at_the_cap() { let mut h = Bench::new(false); @@ -881,6 +897,21 @@ fn a_worker_s_reports_stop_at_the_cap() { h.task(&f, &t).decisions.len(), hide_factory::engine::REPORT_LIMIT ); + // The worker can still finish; its summary is not stored past the cap. + let done = h.as_worker( + &f, + &t, + Command::Done { + summary: Some("all of it".into()), + breaking: false, + letter: None, + }, + ); + assert_eq!(done["state"], "verifying", "{done}"); + assert_eq!( + h.task(&f, &t).decisions.len(), + hide_factory::engine::REPORT_LIMIT + ); } #[test] From d64498cb5d40df1b1ec043e1317a01b0bf9612ba Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 06:59:06 +0900 Subject: [PATCH 42/72] Keep a relanding Task's restart and replay a spawn whose agent had not shown after a revive --- docs/factory.md | 2 +- herdr-core/src/factory.rs | 13 +++++--- hide-factory/src/adapters.rs | 8 +++-- hide-factory/src/engine.rs | 18 ++++++----- hide-factory/tests/engine.rs | 54 +++++++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 11 +++++-- 6 files changed, 88 insertions(+), 18 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index cac4440ff7..6d1058bcc3 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -184,7 +184,7 @@ Each open Factory is a code-owned recipient named `factory:` in the A worker starts when the Task may start. The engine asks the core to spawn it through coordination, the same path as `hide agent spawn`, under the Factory's own agent record as parent. -The spawn runs on the host's starter thread, one at a time with at most 16 waiting, because it waits for Herdr to make the worktree and start the agent: the engine keeps the Task's slot, answers commands and worker reports meanwhile, and takes the started worker on the next tick. A Task cancelled or paused while its worker starts has that worker ended when it arrives, and a worktree that start made removed; its next start is a new attempt with its own spawn intent. A restart of a gone worker waits on the starter the same way and holds its slot meanwhile, and a spawn lock another spawn holds is asked again in two seconds. When the host stops, starts still queued are dropped, not run. +The spawn runs on the host's starter thread, one at a time with at most 16 waiting, because it waits for Herdr to make the worktree and start the agent: the engine keeps the Task's slot, answers commands and worker reports meanwhile, and takes the started worker on the next tick. A Task cancelled or paused while its worker starts on the starter has that worker ended when it arrives, and a worktree that start made removed; its next start is a new attempt with its own spawn intent. A Task cancelled while its agent had not shown its session yet keeps its attempt, so a revive asks the same spawn again and gets the pane and worktree it already made. A Task relanding after a revert keeps its restart while it waits. A restart of a gone worker waits on the starter the same way and holds its slot meanwhile, and a spawn lock another spawn holds is asked again in two seconds. When the host stops, starts still queued are dropped, not run. The record is registered when needed and converges on the existing one. - **Name, branch, intent.** The worker is named `factory--` and works on `factory/-` (`factory/l-` for a local issue, `factory/` without a slug). The spawn intent is `factory--`, and each earlier refused start adds `-a`, so a refused start never repeats a spawn that already failed and a retry of the same attempt converges. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index c46b37bc06..aabae6a8df 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -873,17 +873,19 @@ impl WorkerRuntime for CoreWorkers { Err(queue_start(&self.state, request)) } - fn abandon_start(&mut self, factory: &str, task: &str) { + fn abandon_start(&mut self, factory: &str, task: &str) -> bool { let key = start_key(factory, task); - let finished = match self.state.lock() { + let (in_flight, finished) = match self.state.lock() { Ok(mut state) => { - if state.starts.in_flight.contains(&key) { + let in_flight = state.starts.in_flight.contains(&key); + if in_flight { state.starts.abandoned.insert(key.clone()); } - state.starts.done.remove(&key) + (in_flight, state.starts.done.remove(&key)) } - Err(_) => None, + Err(_) => (false, None), }; + let taken = in_flight || finished.is_some(); if let Some(Finished { fresh, result: Ok(worker), @@ -891,6 +893,7 @@ impl WorkerRuntime for CoreWorkers { { self.release_start(task, fresh, &worker); } + taken } fn message( diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index 47fc1a9c2f..a358f8fdec 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -332,8 +332,12 @@ pub trait WorkerRuntime { fn spawn(&mut self, request: &WorkerSpawn) -> Result; /// The engine no longer wants the worker a pending start makes (the /// Task was cancelled or paused while it started); the adapter ends it - /// when it arrives. - fn abandon_start(&mut self, _factory: &str, _task: &str) {} + /// when it arrives. True when the adapter took a start over, so the next + /// start is a new attempt; false when it held none, so the next start + /// asks the same spawn again and gets what it already reserved (rule 11). + fn abandon_start(&mut self, _factory: &str, _task: &str) -> bool { + false + } /// Sends a reply or wake message through the mailbox. fn message( &mut self, diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 531497296f..e86dbe37e2 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -4462,14 +4462,16 @@ impl Engine { // the slot. let starting: Vec<_> = self.starting.keys().cloned().collect(); for (factory, id) in starting { - if self - .task(&factory, &id) - .is_none_or(|t| t.state != TaskState::Waiting) - { - self.ports.workers.abandon_start(&factory, &id); - // A later start is a new attempt, never the abandoned one - // replayed by its intent. - self.with_task(&factory, &id, |t| t.spawn_refusals += 1); + if self.task(&factory, &id).is_none_or(|t| { + !matches!(t.state, TaskState::Waiting | TaskState::Relanding) + }) { + // A start the adapter took over is never replayed by its + // intent: a later start is a new attempt. A spawn whose agent + // had not shown yet is asked again as the same attempt, so a + // revive gets the pane and worktree it already made. + if self.ports.workers.abandon_start(&factory, &id) { + self.with_task(&factory, &id, |t| t.spawn_refusals += 1); + } self.starting.remove(&(factory, id)); } } diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 21ef86eafe..adfce92a76 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -2232,6 +2232,60 @@ fn a_start_cancelled_on_its_way_is_abandoned_and_a_revive_is_a_new_attempt() { assert_eq!(attempts.last(), Some(&1), "never the abandoned intent"); } +#[test] +fn a_start_whose_agent_had_not_shown_is_asked_again_as_the_same_attempt_after_a_revive() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().spawn_failure = Some(Failure::starting( + "worker.spawn", + "native_identity_unavailable", + )); + let t = h.ready("Slow", &[]); + h.op(Command::Cancel { task: t.clone() }); + h.engine.tick(); + assert_eq!(h.task(&f, &t).spawn_refusals, 0, "nothing was taken over"); + h.world().spawn_failure = None; + h.op(Command::Revive { task: t.clone() }); + tick_until(&mut h, &f, &t, TaskState::Running); + let attempts: Vec = h.world().spawn_asks.iter().map(|r| r.attempt).collect(); + assert!( + attempts.iter().all(|attempt| *attempt == 0), + "the reserved spawn is asked again: {attempts:?}" + ); +} + +#[test] +fn a_relanding_task_whose_worker_restarts_slowly_keeps_its_start() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("A", &[]); + h.world() + .main_checks + .insert("sha0001-T-1".into(), MainCheck::Pending); + h.done(&f, &a); + tick_until(&mut h, &f, &a, TaskState::Landed); + { + let mut world = h.world(); + world.worker_status.insert(a.clone(), WorkerStatus::Gone); + world.spawn_failure = Some(Failure::start_pending("worker.spawn")); + world.main_checks.insert( + "sha0001-T-1".into(), + MainCheck::Red { + link: "run/1".into(), + }, + ); + } + h.advance(60_000); + tick_until(&mut h, &f, &a, TaskState::Relanding); + for _ in 0..10 { + h.engine.tick(); + } + assert!(h.world().abandoned.is_empty(), "its own restart is kept"); + assert_eq!(h.task(&f, &a).spawn_refusals, 0); + h.world().spawn_failure = None; + tick_until(&mut h, &f, &a, TaskState::Running); +} + #[test] fn a_resumed_worker_still_starting_holds_its_slot_without_a_failure_per_tick() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index cd82f57fc8..efdad66d39 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -379,8 +379,15 @@ impl WorkerRuntime for Shared { .copied() .unwrap_or(WorkerStatus::Working) } - fn abandon_start(&mut self, _factory: &str, task: &str) { - self.world().abandoned.push(task.to_owned()); + fn abandon_start(&mut self, _factory: &str, task: &str) -> bool { + let mut world = self.world(); + world.abandoned.push(task.to_owned()); + // A pending start is still in flight; a consumed `starting` answer + // left nothing in the adapter's hands. + world + .spawn_failure + .as_ref() + .is_some_and(|failure| failure.again_in_ms == Some(0)) } fn stop(&mut self, worker: &WorkerRef) -> Result<(), Failure> { self.world().stops.push(task_of(worker)); From 56b7b23fa78dc0d3f790aabd559fdbaafc75d13d Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:01:13 +0900 Subject: [PATCH 43/72] Ask a waiting merge again at its time and do not read its unnamed commit as an outside push --- docs/factory.md | 3 +- hide-factory/src/engine.rs | 48 +++++++++++++++++++++++++++++++ hide-factory/tests/engine.rs | 42 +++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 9 ++++++ 4 files changed, 101 insertions(+), 1 deletion(-) diff --git a/docs/factory.md b/docs/factory.md index 6d1058bcc3..eee72c9073 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -315,7 +315,8 @@ A gate sends an `auto` Task to `merge_waiting` and appears in the Task page and A review by an agent alone never merges. A person's `merge` runs merge-tree and the quick check again on the latest main, then the same merge at once; a conflict sends the worker to rebase and a failed quick check counts as a verification failure. -A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again. +A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a signal and every 30 seconds for an unnamed commit, with no merge-tree or quick check in between. +While a merge's commit is unnamed, a red run on a main head the Factory has not recorded is read as pending, not as an outside push. `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. **GitHub.** The merge is `gh pr merge` with the Factory's `merge_method` and `--match-head-commit` set to the commit the Task-stage verification passed on, so a push after it makes GitHub refuse the merge; a Factory without verification pins the head a person reviewed. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index e86dbe37e2..4554823d42 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -164,6 +164,9 @@ pub struct Engine { main_checked_at: BTreeMap, /// When a failed push or pull request is tried again, per Task. publish_retry: BTreeMap<(String, String), UnixMs>, + /// When a merge asked to wait is tried again, per Task, and whether the + /// merge may already have landed with its commit not named yet. + merge_retry: BTreeMap<(String, String), (UnixMs, bool)>, processed: BTreeSet, processed_order: Vec, /// Recent environment and Task failures the cascade rules read. @@ -227,6 +230,7 @@ impl Engine { main_pending: BTreeSet::new(), main_checked_at: BTreeMap::new(), publish_retry: BTreeMap::new(), + merge_retry: BTreeMap::new(), processed: BTreeSet::new(), processed_order: Vec::new(), env_failures: Vec::new(), @@ -3003,6 +3007,14 @@ impl Engine { return; } let key = (factory_id.to_owned(), id.to_owned()); + // A merge asked to wait is not read again before its time (B39). + if self + .merge_retry + .get(&key) + .is_some_and(|(at, _)| *at > self.now()) + { + return; + } if self.verifying.contains_key(&key) { return; } @@ -3192,6 +3204,8 @@ impl Engine { { Ok(sha) => { let now = self.now(); + self.merge_retry + .remove(&(factory_id.to_owned(), id.to_owned())); self.with_task(factory_id, id, |task| { task.merge_sha = Some(sha.clone()); task.writes.insert("merge".into()); @@ -3213,6 +3227,23 @@ impl Engine { } Err(failure) => { self.external_failure(factory_id, Some(id), &failure); + let now = self.now(); + // Asked to wait (a merge commit not named yet, or GitHub or + // the network down): tried again at its time, not per tick. + let wait = failure.again_in_ms.or_else(|| { + failure.signal.map(|_| { + self.github_backoff + .get(factory_id) + .map(|(_, until)| until.saturating_sub(now)) + .unwrap_or(PUBLISH_RETRY_MS) + }) + }); + if let Some(wait) = wait { + self.merge_retry.insert( + (factory_id.to_owned(), id.to_owned()), + (now + wait.max(1), failure.again_in_ms.is_some()), + ); + } if failure.signal.is_none() && failure.again_in_ms.is_none() { self.with_task(factory_id, id, |task| { if !task.gates.contains(&Gate::MergeRefused) { @@ -5039,6 +5070,11 @@ impl Engine { self.record(&factory.id, None, "main.green", json!({"sha": head})); } } + // A merge that may have landed without its commit named yet + // is not an outside push: wait until the commit is known. + Ok(MainCheck::Red { .. }) if !known && self.merge_unnamed(&factory.id) => { + self.main_pending.insert(factory.id.clone()); + } Ok(MainCheck::Red { link }) if !known && !factory.main.broken => { self.main_pending.remove(&factory.id); self.main_seen.insert(factory.id.clone(), head.clone()); @@ -5062,6 +5098,18 @@ impl Engine { } } + /// A Task of this Factory still verifying whose merge answered without + /// naming its commit. + fn merge_unnamed(&self, factory_id: &str) -> bool { + self.merge_retry + .iter() + .filter(|((factory, _), (_, unnamed))| factory == factory_id && *unnamed) + .any(|((factory, id), _)| { + self.task(factory, id) + .is_some_and(|t| t.state == TaskState::Verifying) + }) + } + // ------------------------------------------------------------- environment /// A failure the Task did not cause is not counted (D-31 rule 2, B58). diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index adfce92a76..e6b10c7619 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1397,6 +1397,48 @@ fn a_refused_merge_waits_for_a_person_with_its_reason_and_is_tried_once() { assert_eq!(merged["ok"], true, "{merged}"); } +#[test] +fn a_merge_asked_to_wait_is_read_again_at_its_time_and_main_is_not_misread_meanwhile() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + h.engine.tick(); + let t = h.ready("Queued", &[]); + h.world().merge_unnamed = 100; + h.done(&f, &t); + for _ in 0..3 { + h.engine.tick(); + } + assert_eq!(h.world().merge_attempts, 1); + let premerges = h.world().premerge_calls; + // GitHub moved main to a commit the Factory has not been told of, and + // its run is red: that is this merge, not an outside push. + { + let mut world = h.world(); + world.head = "landed-unnamed".into(); + world.main_checks.insert( + "landed-unnamed".into(), + MainCheck::Red { + link: "run/1".into(), + }, + ); + } + for _ in 0..20 { + h.advance(2_000); + h.engine.tick(); + } + assert_eq!(h.world().merge_attempts, 2, "once per 30 seconds over 40"); + assert!(h.world().premerge_calls <= premerges + 1); + // The next outside read finds the new head. + h.advance(2 * MINUTE_MS); + h.engine.tick(); + h.engine.tick(); + assert!( + !h.engine.factories().next().unwrap().main.broken, + "not read as an outside push" + ); + assert_eq!(h.state(&f, &t), TaskState::Verifying); +} + #[test] fn a_broken_main_holds_auto_merge_without_reading_it_every_tick() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index efdad66d39..a5f65af69a 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -36,6 +36,8 @@ pub struct World { pub premerge_calls: u32, /// The next merge is refused with this failure. pub merge_refusal: Option, + /// This many merges answer before GitHub names the merge commit. + pub merge_unnamed: u32, pub merge_attempts: u32, /// Each report a GitHub Task pushed, by Task id. pub pushes: Vec, @@ -273,6 +275,13 @@ impl MergeTarget for Shared { if let Some(failure) = world.merge_refusal.take() { return Err(failure); } + if world.merge_unnamed > 0 { + world.merge_unnamed -= 1; + return Err(Failure { + again_in_ms: Some(hide_factory::engine::MERGE_COMMIT_AGAIN_MS), + ..Failure::task("github.merge", "merge commit not named yet") + }); + } world.next_sha += 1; let sha = format!("sha{:04}-{}", world.next_sha, task.id); world.writes.push(format!("merge {}", task.id)); From 057b6cda2df2ff4d5bdffc256b1daeaa586a81ef Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:03:35 +0900 Subject: [PATCH 44/72] Push a Task branch the remote deleted and stop a Task whose push is refused twice for a person --- docs/factory.md | 2 + hide-factory/src/engine.rs | 31 +++++++++++++- hide-factory/src/model.rs | 2 + hide-factory/src/project.rs | 15 +++++++ hide-factory/tests/engine.rs | 25 ++++++++++++ hide-factory/tests/local_git.rs | 67 +++++++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 5 +++ 7 files changed, 146 insertions(+), 1 deletion(-) diff --git a/docs/factory.md b/docs/factory.md index eee72c9073..0c266fc369 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -213,6 +213,8 @@ A worker reports through `hide factory` and gets its answer in the same call. `ask` needs a suggestion, a default action and a deadline of 1 to 720 hours, and the worker continues with the default; `block` has no default, so the Task blocks, releases its slot and sleeps. `done` answers at once, goes to `verifying`, and puts the worker to sleep. On a GitHub Factory the next tick pushes the worktree's commits to the Task branch (with a lease, so a rebase goes through), then finds the open pull request for that branch or opens one, and only then reads CI on the pushed commit; every report pushes, so a fix after a failed check reaches the same pull request, and a merged pull request from before a revert is never reused. +A Task branch the remote deleted, as automatic branch deletion does after a merge, is pushed again rather than refused by a stale lease. +A push or pull request refused twice in a row with no environment signal (a protected branch, a hook) stops the Task as "push 거절됨" with the reason; a person fixes the cause and retries. One with an environment signal is asked again every minute. A failed push or pull request is tried again a minute later. `decide` records a decision. A worker whose agent rests for the no-report window (`no_report_minutes`, 2) after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for the stall window (`stall_minutes`, 30) stops it as "stalled". diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 4554823d42..21ae310edd 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -164,6 +164,9 @@ pub struct Engine { main_checked_at: BTreeMap, /// When a failed push or pull request is tried again, per Task. publish_retry: BTreeMap<(String, String), UnixMs>, + /// Refusals in a row of a Task's push or pull request that no + /// environment signal explains. + publish_refusals: BTreeMap<(String, String), u32>, /// When a merge asked to wait is tried again, per Task, and whether the /// merge may already have landed with its commit not named yet. merge_retry: BTreeMap<(String, String), (UnixMs, bool)>, @@ -230,6 +233,7 @@ impl Engine { main_pending: BTreeSet::new(), main_checked_at: BTreeMap::new(), publish_retry: BTreeMap::new(), + publish_refusals: BTreeMap::new(), merge_retry: BTreeMap::new(), processed: BTreeSet::new(), processed_order: Vec::new(), @@ -2680,6 +2684,7 @@ impl Engine { task.writes.remove(PUBLISH_PENDING); }); self.publish_retry.remove(&key); + self.publish_refusals.remove(&key); self.record( factory_id, Some(id), @@ -2690,7 +2695,31 @@ impl Engine { } Err(failure) => { self.external_failure(factory_id, Some(id), &failure); - self.publish_retry.insert(key, now + PUBLISH_RETRY_MS); + let refusals = if failure.signal.is_none() { + let n = self.publish_refusals.entry(key.clone()).or_default(); + *n += 1; + *n + } else { + 0 + }; + if refusals >= 2 { + // A protected branch or a hook refuses the same way each + // time: a person fixes the cause and retries (rule 10). + self.publish_refusals.remove(&key); + self.publish_retry.remove(&key); + let detail = judgment::cut(&failure.detail, 300); + self.with_task(factory_id, id, |t| { + t.writes.remove(PUBLISH_PENDING); + t.stop = Some(StopReason::PublishRefused); + t.stop_detail = Some(detail); + }); + self.set_state(factory_id, id, TaskState::Stopped); + self.with_task(factory_id, id, |t| { + t.stop = Some(StopReason::PublishRefused); + }); + } else { + self.publish_retry.insert(key, now + PUBLISH_RETRY_MS); + } } } } diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 5f1c1f1bb3..409f49ab0e 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -684,6 +684,7 @@ pub enum StopReason { NewTaskCap, EnvironmentRepeated, WorkerStart, + PublishRefused, } impl StopReason { @@ -695,6 +696,7 @@ impl StopReason { Self::NewTaskCap => "새 Task 상한", Self::EnvironmentRepeated => "같은 환경 실패 반복", Self::WorkerStart => "worker 시작 실패", + Self::PublishRefused => "push 거절됨", } } } diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 3f96ad7616..f183ee193a 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -789,6 +789,21 @@ impl MergeTarget for SharedProjects { // Every report publishes its commits, so CI reads what the worker // committed since the last one; a rebase needs the lease (B36, B40). let path = worktree(task)?; + // A branch the remote deleted (a merged pull request with automatic + // branch deletion, before a relanding) leaves a stale tracking ref + // the lease would refuse; drop it so the push makes the branch again. + let remote = this.git( + "git.push", + &path, + &["ls-remote", "--heads", "origin", &format!("refs/heads/{branch}")], + )?; + if remote.trim().is_empty() { + this.git( + "git.push", + &path, + &["update-ref", "-d", &format!("refs/remotes/origin/{branch}")], + )?; + } this.git( "git.push", &path, diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index e6b10c7619..50deb84515 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1267,6 +1267,31 @@ fn each_github_report_pushes_before_its_checks_are_read_and_answers_at_once() { assert_eq!(h.writes("pr.open").len(), 1, "one pull request"); } +#[test] +fn a_push_refused_twice_stops_the_task_for_a_person_with_its_reason() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Protected", &[]); + h.world().publish_refusal = Some(hide_factory::adapters::Failure::task( + "git.push", + "protected branch hook declined", + )); + h.done(&f, &t); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Verifying, "asked again once"); + h.advance(MINUTE_MS + 1); + h.engine.tick(); + let task = h.task(&f, &t); + assert_eq!(task.state, TaskState::Stopped); + assert_eq!(task.stop, Some(StopReason::PublishRefused)); + assert!(task.stop_detail.unwrap().contains("hook declined")); + for _ in 0..5 { + h.advance(MINUTE_MS + 1); + h.engine.tick(); + } + assert_eq!(h.world().pushes.len(), 2, "no push while stopped"); +} + #[test] fn a_manual_task_waits_for_merge_and_every_github_write_happens_once() { let mut h = Bench::new(true); diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index 223d6561e8..5244578050 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -325,3 +325,70 @@ fn a_risk_path_and_a_quick_check_gate_the_merge() { "no worktree is a failure, not a pass" ); } + +/// Real git against a bare remote; `gh` answers that no pull request is open +/// and opens one when asked. +struct RealGitFakeGh(SystemRunner); + +impl hide_factory::exec::Runner for RealGitFakeGh { + fn run( + &mut self, + program: &str, + args: &[String], + cwd: Option<&Path>, + ) -> Result { + if program == "git" { + return self.0.run(program, args, cwd); + } + let stdout = match args.get(1).map(String::as_str) { + Some("list") => "[]".to_owned(), + Some("create") => "https://github.com/o/r/pull/7\n".to_owned(), + other => panic!("unexpected gh {other:?}"), + }; + Ok(hide_factory::exec::Output { + code: Some(0), + stdout, + stderr: String::new(), + }) + } +} + +#[test] +fn a_report_after_the_remote_deleted_the_task_branch_still_pushes() { + let fx = fixture(); + let remote = fx.project.with_file_name("remote.git"); + git( + fx.project.parent().unwrap(), + &["init", "--quiet", "--bare", remote.to_str().unwrap()], + ); + git( + &fx.project, + &["remote", "add", "origin", remote.to_str().unwrap()], + ); + git(&fx.project, &["push", "--quiet", "origin", "main"]); + let mut projects = SharedProjects::new( + Box::new(RealGitFakeGh(SystemRunner { + stop: Arc::new(AtomicBool::new(false)), + })), + Box::new(Book::default()), + fx.project.with_file_name("gh-logs"), + ); + let mut factory = factory(&fx.project, &[]); + factory.source = SourceKind::Github; + factory.repo = Some("o/r".into()); + let t = task(&fx, "T-1", "b.txt", "two\n"); + let branch = t.worker.as_ref().unwrap().branch.clone(); + let worktree = PathBuf::from(&t.worker.as_ref().unwrap().worktree); + let pr = projects.open_pr(&factory, &t, "body").unwrap().unwrap(); + assert_eq!(pr.number, 7); + // The pull request merged and the remote deleted its branch; the Task + // was reverted and reports again with a new commit. + git(&remote, &["update-ref", "-d", &format!("refs/heads/{branch}")]); + write(&worktree, "b.txt", "three\n"); + git(&worktree, &["commit", "--quiet", "-am", "again"]); + projects.open_pr(&factory, &t, "body").unwrap(); + assert_eq!( + git(&remote, &["rev-parse", &format!("refs/heads/{branch}")]), + git(&worktree, &["rev-parse", "HEAD"]), + ); +} diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index a5f65af69a..e67a96171b 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -39,6 +39,8 @@ pub struct World { /// This many merges answer before GitHub names the merge commit. pub merge_unnamed: u32, pub merge_attempts: u32, + /// Every push is refused with this failure. + pub publish_refusal: Option, /// Each report a GitHub Task pushed, by Task id. pub pushes: Vec, /// Main verification answers by commit, read before `main_checks`. @@ -221,6 +223,9 @@ impl MergeTarget for Shared { ) -> Result, Failure> { let mut world = self.world(); world.pushes.push(task.id.clone()); + if let Some(failure) = world.publish_refusal.clone() { + return Err(failure); + } if let Some(pr) = task.pr.clone().filter(|pr| pr.open) { return Ok(Some(pr)); } From 3c2666d808eb69636d3a41d442c7872be9f3f9b9 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:05:31 +0900 Subject: [PATCH 45/72] Keep the outside read going past an unreadable held issue and let no Factory pull request take another Task --- docs/factory.md | 3 +- hide-factory/src/engine.rs | 18 ++++-- hide-factory/src/project.rs | 78 +++++++++++++++++++++----- hide-factory/tests/github.rs | 103 +++++++++++++++++++++++++++++++++++ 4 files changed, 183 insertions(+), 19 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 0c266fc369..3248aca0b4 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -345,10 +345,11 @@ A recovery that cannot name one merge, cannot make or merge the revert, or finds The person wins outside the Factory, and the Factory follows. Each open Factory reads GitHub every `outside_read_minutes` (2 by default): up to 200 issues labelled `factory` and 100 pull requests, or, locally, its local issues. A failed read backs off 1, 2, 5, 15 and then 30 minutes on a rate-limit, server or network signal; three failures in a row mark the Factory's read stale. +A held issue missing from that list is looked up by number, at most 20 per read and continuing where the last read stopped; one that cannot be read now keeps its Task, and a deleted one counts as its label removed. | What the Factory sees | What it does | | --- | --- | -| A pull request the Factory did not open closes a Task's issue, and it is open | A pull request from a fork counts only once it is merged, since anyone can open one. Otherwise the Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | +| A pull request the Factory did not open closes a Task's issue, and it is open | A pull request one of the Factory's own Tasks opened never counts, whatever its worker wrote; the decisions a worker records sit in a code block in its pull request body, so a "Fixes #N" there stays text. A pull request from a fork counts only once it is merged, since anyone can open one. Otherwise the Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | | That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. A stopped worker's worktree still waits out its keep period. | | The issue closes with no pull request, or the `factory` label is removed | The Task is cancelled with a notice, kept for the keep period. | | A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 21ae310edd..dfbb54b4ae 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -6012,10 +6012,20 @@ pub fn issue_body(task: &Task, factory: &Factory) -> String { pub fn pr_body(task: &Task, factory: &Factory) -> String { let mut body = issue_body(task, factory); if !task.decisions.is_empty() { - body.push_str("\n## 결정 기록\n"); - for decision in &task.decisions { - body.push_str(&format!("- {}\n", decision.text)); - } + // A worker wrote these: in a code block, a "Fixes #N" in them is + // text, never a closing reference to another Task's issue (D-33). + let text: String = task + .decisions + .iter() + .map(|decision| format!("- {}\n", decision.text)) + .collect(); + let longest = text + .split(|c| c != '`') + .map(str::len) + .max() + .unwrap_or(0); + let fence = "`".repeat(longest.max(2) + 1); + body.push_str(&format!("\n## 결정 기록\n{fence}text\n{text}{fence}\n")); } match &task.issue { Some(IssueRef::Github { number }) => body.push_str(&format!("\nCloses #{number}\n")), diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index f183ee193a..bc754633fd 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -6,7 +6,7 @@ //! marker, a pull request is found by its head branch, a merge by its pull //! request's state, a label create is `--force`. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, Instant}; @@ -47,8 +47,15 @@ pub struct Projects { /// only after `ci_poll_every`, not on every engine tick (B75). ci_pending: BTreeMap, ci_poll_every: Duration, + /// The last held issue each Factory looked up by number, so the next + /// read continues after it. + held_cursor: BTreeMap, } +/// Held issues looked up by number in one outside read; the rest wait for +/// the next read and keep their Tasks meanwhile. +pub const HELD_LOOKUP_LIMIT: usize = 20; + /// How often a commit whose checks are still running is asked again. pub const CI_POLL_EVERY: Duration = Duration::from_secs(30); /// Commits remembered as pending; the oldest is forgotten past this. @@ -67,6 +74,7 @@ impl SharedProjects { bodies: BTreeMap::new(), ci_pending: BTreeMap::new(), ci_poll_every: CI_POLL_EVERY, + held_cursor: BTreeMap::new(), }))) } @@ -638,14 +646,29 @@ impl TaskSource for SharedProjects { .filter_map(|issue| issue["number"].as_u64().map(|n| (n, issue.clone()))) .collect(); // The list holds the newest issues only, so a held issue missing from - // it is asked for by number before its label counts as removed. - for (number, task) in &held { - if labelled.contains_key(number) - || matches!(task.state, TaskState::Done | TaskState::Cancelled) - { - continue; - } - let issue = this.gh_json( + // it is asked for by number before its label counts as removed: a + // capped number per read, continuing where the last read stopped. + // One that cannot be read now keeps its Task; a deleted one is gone. + let missing: Vec = held + .iter() + .filter(|(number, task)| { + !labelled.contains_key(number) + && !matches!(task.state, TaskState::Done | TaskState::Cancelled) + }) + .map(|(number, _)| *number) + .collect(); + let after = this.held_cursor.get(&factory.id).copied().unwrap_or(0); + let start = missing.iter().position(|n| *n > after).unwrap_or(0); + let asked: Vec = missing + .iter() + .cycle() + .skip(start) + .take(missing.len().min(HELD_LOOKUP_LIMIT)) + .copied() + .collect(); + let mut unread: BTreeSet = missing.iter().copied().collect(); + for number in &asked { + let issue = match this.gh_json( "github.observe", &[ "issue", @@ -656,7 +679,16 @@ impl TaskSource for SharedProjects { "--json", "number,title,body,state,labels", ], - )?; + ) { + Ok(issue) => issue, + Err(failure) if failure.signal.is_some() => return Err(failure), + Err(failure) if failure.detail.contains("Could not resolve to an issue") => { + unread.remove(number); + continue; + } + Err(_) => continue, + }; + unread.remove(number); let still = issue["labels"] .as_array() .into_iter() @@ -666,6 +698,22 @@ impl TaskSource for SharedProjects { labelled.insert(*number, issue); } } + if let Some(last) = asked.last() { + this.held_cursor.insert(factory.id.clone(), *last); + } + // Pull requests this Factory's own Tasks opened never take another + // Task, whatever a worker wrote in them (D-33). + let own_prs: BTreeSet = tasks + .iter() + .filter_map(|task| task.pr.as_ref().map(|pr| pr.number)) + .collect(); + let own_heads: BTreeSet = tasks + .iter() + .flat_map(|task| { + [Some(task.branch_slug()), task.worker.as_ref().map(|w| w.branch.clone())] + }) + .flatten() + .collect(); for (number, issue) in &labelled { let issue_ref = IssueRef::Github { number: *number }; let body = issue["body"].as_str().unwrap_or_default(); @@ -708,12 +756,13 @@ impl TaskSource for SharedProjects { .any(|i| i["number"].as_u64() == Some(*number)) }) .filter(|pr| { - task.pr - .as_ref() - .is_none_or(|own| pr["number"].as_u64() != Some(own.number)) + pr["number"].as_u64().is_none_or(|n| !own_prs.contains(&n)) }) .filter(|pr| { - pr["headRefName"].as_str() != Some(task.branch_slug().as_str()) + pr["isCrossRepository"].as_bool() == Some(true) + || pr["headRefName"] + .as_str() + .is_none_or(|head| !own_heads.contains(head)) }) // Anyone can open a pull request from a fork: it takes // a Task only once a maintainer merged it (D-27). @@ -748,6 +797,7 @@ impl TaskSource for SharedProjects { } for (number, task) in held { if !labelled.contains_key(&number) + && !unread.contains(&number) && !matches!(task.state, TaskState::Done | TaskState::Cancelled) { events.push(OutsideEvent::LabelRemoved { diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index 5aaf782f17..35472dd2ba 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -28,6 +28,8 @@ struct Hub { list_cap: Option, /// Each `git push` refspec, in order. pushes: Vec, + /// `issue view` answers this error for these numbers. + view_errors: BTreeMap, } #[derive(Clone, Default)] @@ -90,6 +92,13 @@ impl Runner for FakeGh { } ["issue", "view", number, ..] => { let number: u64 = number.parse().unwrap(); + if let Some(stderr) = hub.view_errors.get(&number) { + return Ok(Output { + code: Some(1), + stdout: String::new(), + stderr: stderr.clone(), + }); + } ok(match hub.issues.get(&number) { Some((title, body, state)) => json!({"number": number, "title": title, "body": body, "state": state, "labels": [{"name": "factory"}]}), None => json!({"number": number, "title": "", "body": "", "state": "OPEN", "labels": []}), @@ -538,6 +547,100 @@ fn a_held_issue_past_the_list_limit_keeps_its_task() { ); } +#[test] +fn a_held_issue_that_cannot_be_read_keeps_its_task_and_a_deleted_one_is_gone() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + { + let mut hub = gh.0.lock().unwrap(); + hub.issues + .insert(9, ("Listed".into(), "body".into(), "CLOSED".into())); + hub.list_cap = Some(1); + hub.view_errors + .insert(1, "issue view refused: transferred to another repository".into()); + hub.view_errors.insert( + 2, + "GraphQL: Could not resolve to an issue or pull request with the number of 2.".into(), + ); + } + let odd = task("T-1", Some(1)); + let deleted = task("T-2", Some(2)); + let listed = task("T-9", Some(9)); + let events = p.observe(&factory, &[&odd, &deleted, &listed]).unwrap(); + assert!( + !events.contains(&OutsideEvent::LabelRemoved { + issue: IssueRef::Github { number: 1 } + }), + "{events:?}" + ); + assert!(events.contains(&OutsideEvent::LabelRemoved { + issue: IssueRef::Github { number: 2 } + })); + // The other Tasks' reads go on. + assert!(events.contains(&OutsideEvent::IssueClosed { + issue: IssueRef::Github { number: 9 } + })); +} + +#[test] +fn another_task_s_pull_request_naming_an_issue_takes_no_task() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + { + let mut hub = gh.0.lock().unwrap(); + for n in [1, 2] { + hub.issues.insert( + n, + ( + format!("Issue {n}"), + format!(""), + "OPEN".into(), + ), + ); + } + hub.prs.insert( + 5, + json!({"number": 5, "url": "https://github.com/o/r/pull/5", "state": "OPEN", + "headRefName": "factory/1-add-it", "isCrossRepository": false, + "closingIssuesReferences": [{"number": 1}, {"number": 2}]}), + ); + } + let mut a = task("T-1", Some(1)); + a.pr = Some(PullRequest { + number: 5, + url: "https://github.com/o/r/pull/5".into(), + head: "factory/1-add-it".into(), + by_factory: true, + open: true, + }); + let b = task("T-2", Some(2)); + let events = p.observe(&factory, &[&a, &b]).unwrap(); + assert!( + !events + .iter() + .any(|e| matches!(e, OutsideEvent::ClosingPr { .. })), + "{events:?}" + ); +} + +#[test] +fn a_worker_s_closing_keyword_in_a_decision_stays_text() { + let mut t = task("T-1", Some(1)); + t.decisions.push(DecisionRecord { + text: "done: Fixes #2 and ``` too".into(), + by: "worker:T-1".into(), + at: 0, + }); + let body = hide_factory::engine::pr_body(&t, &factory()); + let fence = body.find("````text").expect("a fence longer than the text's"); + let fixes = body.find("Fixes #2").unwrap(); + let close = body[fixes..].find("````").map(|i| i + fixes).unwrap(); + assert!(fence < fixes && fixes < close, "{body}"); + assert!(body.trim_end().ends_with("Closes #1")); +} + #[test] fn a_github_failure_carries_its_signal() { let gh = FakeGh::default(); From e8ba27c7350efc206ed05f24df8dee64f88ce58c Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:06:14 +0900 Subject: [PATCH 46/72] Adopt only a same-repository pull request as a Task's or a revert's --- docs/factory.md | 1 + hide-factory/src/project.rs | 17 +++++++++++++---- hide-factory/tests/github.rs | 26 +++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 3248aca0b4..e3fe389e61 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -214,6 +214,7 @@ A worker reports through `hide factory` and gets its answer in the same call. `done` answers at once, goes to `verifying`, and puts the worker to sleep. On a GitHub Factory the next tick pushes the worktree's commits to the Task branch (with a lease, so a rebase goes through), then finds the open pull request for that branch or opens one, and only then reads CI on the pushed commit; every report pushes, so a fix after a failed check reaches the same pull request, and a merged pull request from before a revert is never reused. A Task branch the remote deleted, as automatic branch deletion does after a merge, is pushed again rather than refused by a stale lease. +Only a pull request from the repository's own branch is a Task's or a revert's; a fork's pull request on the same branch name is never adopted. A push or pull request refused twice in a row with no environment signal (a protected branch, a hook) stops the Task as "push 거절됨" with the reason; a person fixes the cause and retries. One with an environment signal is asked again every minute. A failed push or pull request is tried again a minute later. `decide` records a decision. diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index bc754633fd..431464339d 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -108,6 +108,13 @@ fn worktree(task: &Task) -> Result { .ok_or_else(|| Failure::task("worktree", "the Task has no worktree")) } +/// The first pull request in a `gh pr list` answer whose head branch lives +/// in the repository itself, never a fork's branch of the same name. +fn same_repo(prs: &[Value]) -> Option<&Value> { + prs.iter() + .find(|pr| pr["isCrossRepository"].as_bool() == Some(false)) +} + fn repo(factory: &Factory) -> Result { factory .repo @@ -880,10 +887,12 @@ impl MergeTarget for SharedProjects { "--state", "open", "--json", - "number,url,state,headRefName", + "number,url,state,headRefName,isCrossRepository", ], )?; - if let Some(pr) = existing.as_array().and_then(|prs| prs.first()) { + // `--head` matches a branch name in any fork; only this repository's + // own branch is the Task's. + if let Some(pr) = existing.as_array().and_then(|prs| same_repo(prs)) { // A harness opened it, or an earlier attempt did (B36, B73). let number = pr["number"] .as_u64() @@ -1252,12 +1261,12 @@ impl MergeTarget for SharedProjects { "github.pr_find", &[ "pr", "list", "--repo", &repo, "--head", &branch, "--state", "open", "--json", - "number", + "number,isCrossRepository", ], )?; let number = match existing .as_array() - .and_then(|prs| prs.first()) + .and_then(|prs| same_repo(prs)) .and_then(|pr| pr["number"].as_u64()) { Some(number) => number, diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index 35472dd2ba..4c20204a92 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -126,7 +126,7 @@ impl Runner for FakeGh { hub.next += 1; let number = hub.next; let head = flag(args, "--head").unwrap().to_owned(); - hub.prs.insert(number, json!({"number": number, "url": format!("https://github.com/o/r/pull/{number}"), "state": "OPEN", "headRefName": head, "headRefOid": "headsha", "mergeCommit": null, "closingIssuesReferences": []})); + hub.prs.insert(number, json!({"number": number, "url": format!("https://github.com/o/r/pull/{number}"), "state": "OPEN", "headRefName": head, "isCrossRepository": false, "headRefOid": "headsha", "mergeCommit": null, "closingIssuesReferences": []})); hub.writes.push(format!("pr create {number}")); ok(format!("https://github.com/o/r/pull/{number}\n")) } @@ -641,6 +641,30 @@ fn a_worker_s_closing_keyword_in_a_decision_stays_text() { assert!(body.trim_end().ends_with("Closes #1")); } +#[test] +fn a_fork_pull_request_on_the_task_or_revert_branch_name_is_never_adopted() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = factory(); + let t = task("T-1", Some(1)); + { + let mut hub = gh.0.lock().unwrap(); + for (number, head) in [(40, t.branch_slug()), (41, "factory/revert-t-1".into())] { + hub.prs.insert( + number, + json!({"number": number, "url": format!("https://github.com/x/r/pull/{number}"), + "state": "OPEN", "headRefName": head, "isCrossRepository": true, + "headRefOid": "strangersha", "closingIssuesReferences": []}), + ); + } + } + let pr = p.open_pr(&factory, &t, "body").unwrap().unwrap(); + assert!(pr.by_factory, "the Factory opened its own"); + assert_ne!(pr.number, 40); + let revert = p.revert(&factory, &t, "bad1").unwrap(); + assert_ne!(revert.pr, Some(41)); +} + #[test] fn a_github_failure_carries_its_signal() { let gh = FakeGh::default(); From 108d18df30a568e31e6f2b4c22519f12f0ab6044 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:09:06 +0900 Subject: [PATCH 47/72] Bind a caller through its ancestors' panes and let a caller whose lineage is cut only read --- docs/factory.md | 3 +- herdr-core/src/factory.rs | 56 +++++++++++++++++--------- herdr-core/src/runtime/factory.rs | 63 +++++++++++++++-------------- hide-factory/src/engine.rs | 46 +++++++++++++++++++++ hide-factory/tests/engine.rs | 66 +++++++++++++++++++++++++++++++ 5 files changed, 185 insertions(+), 49 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index e3fe389e61..8d39590ca8 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -144,7 +144,8 @@ Each command runs with a role the engine decides from its own store, never from A caller is a worker when its pane is the pane of a Task's worker, or when its working folder is inside a Task's worktree. A `cancelled` or `done` Task's worker stays a worker while its worktree and pane stay, so its pane never gains an operator's commands, and the Task's state refuses its reports; a live Task wins when a pane or folder was reused. Once a Task's worktree is removed it binds no pane or folder, because Herdr can give a closed pane id to the operator's next pane. -An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up), and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. +An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up) and binds an ancestor by its agent id or by the pane it was registered on, and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. +A lineage the host cannot read to its root (the ledger unreadable, a missing record, a loop, more than 16 agents) may hide a worker above, so that caller can only read; anything else is refused with `lineage_unknown`. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index aabae6a8df..f48ac758a2 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -62,9 +62,32 @@ pub struct FactoryCaller { /// A pane the caller named but could not be checked against: it can only /// make the caller a worker, never an operator. pub claimed: Option, - /// The agents above the caller in the spawn lineage, nearest first: a - /// worker's child is a worker of the same Task (D-33). - pub ancestors: Vec, + /// The agents above the caller in the spawn lineage: a worker's child is + /// a worker of the same Task (D-33). + pub ancestors: Lineage, +} + +/// The spawn lineage above a caller, nearest first. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Lineage { + pub agents: Vec, + /// The pane each of `agents` was registered on, where the ledger has it. + pub panes: Vec, + /// The walk reached an agent with no parent. A cut walk (the ledger + /// unreadable, a missing record, a loop, the step limit) cannot rule out + /// a worker above the caller. + pub complete: bool, +} + +impl Lineage { + /// No lineage: a caller with no agent record above it. + pub fn none() -> Self { + Self { + agents: Vec::new(), + panes: Vec::new(), + complete: true, + } + } } enum Request { @@ -508,22 +531,17 @@ fn handle( caller: &FactoryCaller, command: Command, ) -> Value { - // Everything that names a worker binds to it: the caller's own pane or - // folder, a pane it claimed, or an agent above it in the spawn lineage. - let bound = engine - .role_for(caller.pane.as_deref(), caller.cwd.as_deref()) - .or_else(|| { - caller - .claimed - .as_deref() - .and_then(|pane| engine.role_for(Some(pane), None)) - }) - .or_else(|| engine.role_for_agents(&caller.ancestors)); - let role = match bound { - Some((factory, task)) => Role::Worker { factory, task }, - None => Role::Operator { - pane: caller.pane.clone().unwrap_or_else(|| "checkout".into()), - }, + let facts = hide_factory::engine::Caller { + pane: caller.pane.as_deref(), + cwd: caller.cwd.as_deref(), + claimed: caller.claimed.as_deref(), + ancestor_agents: &caller.ancestors.agents, + ancestor_panes: &caller.ancestors.panes, + lineage_complete: caller.ancestors.complete, + }; + let role = match engine.caller_role(&facts, &command) { + Ok(role) => role, + Err(refusal) => return refusal.to_json(), }; // A pending review answers the pane that added the Task (B11); that is // the caller, never a pane the request names. diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index 5edf6f1dab..270c39216d 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -56,8 +56,9 @@ impl Runtime { let ancestors = pane .as_deref() .or(claimed.as_deref()) - .map(|pane| self.factory_lineage(pane)) - .unwrap_or_default(); + .map_or_else(crate::factory::Lineage::none, |pane| { + self.factory_lineage(pane) + }); Ok(crate::factory::FactoryCaller { pane, cwd: Some(context.checkout_path.clone()).filter(|path| !path.is_empty()), @@ -66,32 +67,34 @@ impl Runtime { }) } - /// The agent ids above `pane` in the spawn lineage, nearest first, from + /// The agents above `pane` in the spawn lineage, nearest first, from /// the ledger in memory; at most [`LINEAGE_LIMIT`] steps. - fn factory_lineage(&self, pane: &str) -> Vec { + fn factory_lineage(&self, pane: &str) -> crate::factory::Lineage { + let mut lineage = crate::factory::Lineage { + complete: false, + ..crate::factory::Lineage::none() + }; let Ok(ledger) = self.delivery_state() else { - return Vec::new(); + return lineage; + }; + let mut next = match ledger.agents.iter().rev().find(|agent| agent.pane == pane) { + Some(agent) => agent.parent.clone(), + None => None, }; - let parent_of = |agent: &crate::coordination::AgentRecord| agent.parent.clone(); - let mut next = ledger - .agents - .iter() - .rev() - .find(|agent| agent.pane == pane) - .and_then(parent_of); - let mut ancestors = Vec::new(); while let Some(id) = next { - if ancestors.len() >= LINEAGE_LIMIT || ancestors.contains(&id) { - break; + if lineage.agents.len() >= LINEAGE_LIMIT || lineage.agents.contains(&id) { + return lineage; } - next = ledger - .agents - .iter() - .find(|agent| agent.id == id) - .and_then(parent_of); - ancestors.push(id); + let Some(agent) = ledger.agents.iter().find(|agent| agent.id == id) else { + lineage.agents.push(id); + return lineage; + }; + lineage.agents.push(id); + lineage.panes.push(agent.pane.clone()); + next = agent.parent.clone(); } - ancestors + lineage.complete = true; + lineage } /// A delivery command the Factory sends as its own recipient, to the pane @@ -357,16 +360,18 @@ mod tests { ], ..Ledger::default() })); + let full = runtime.factory_lineage("w3:p1"); assert_eq!( - runtime.factory_lineage("w3:p1"), + full.agents, vec!["agent-child", "agent-worker", "agent-factory"] ); - assert!(runtime.factory_lineage("w0:p1").is_empty()); - assert_eq!( - runtime.factory_lineage("w9:p1"), - vec!["agent-b", "agent-a"], - "a loop ends the walk" - ); + assert_eq!(full.panes, vec!["w2:p1", "w1:p1", "factory:f-1"]); + assert!(full.complete); + let none = runtime.factory_lineage("w0:p1"); + assert!(none.agents.is_empty() && none.complete); + let looped = runtime.factory_lineage("w9:p1"); + assert_eq!(looped.agents, vec!["agent-b", "agent-a"], "a loop ends the walk"); + assert!(!looped.complete, "a loop cannot rule out a worker above"); } fn row(provider: &str, used: f64, bucket: Option<(f64, u64)>) -> ProviderUsageSnapshot { diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index dfbb54b4ae..fd0ca2df83 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -353,6 +353,36 @@ impl Engine { self.store.events(factory, task, limit).unwrap_or_default() } + /// The role of a caller as the host saw it (D-33). Everything that names + /// a worker binds to it: the caller's own pane or folder, a pane it + /// claimed, or an agent above it in the spawn lineage, by its id or by + /// the pane it was registered on. A lineage cut short may hide a worker + /// above, so such a caller only reads, never acts as an operator. + pub fn caller_role(&self, caller: &Caller<'_>, command: &Command) -> Result { + let bound = self + .role_for(caller.pane, caller.cwd) + .or_else(|| caller.claimed.and_then(|pane| self.role_for(Some(pane), None))) + .or_else(|| self.role_for_agents(caller.ancestor_agents)) + .or_else(|| { + caller + .ancestor_panes + .iter() + .find_map(|pane| self.role_for(Some(pane), None)) + }); + match bound { + Some((factory, task)) => Ok(Role::Worker { factory, task }), + None if !caller.lineage_complete && command.permission() != Permission::Read => { + Err(Refusal::new( + "lineage_unknown", + "The caller's spawn lineage could not be read to its root; run this from an operator pane", + )) + } + None => Ok(Role::Operator { + pane: caller.pane.unwrap_or("checkout").to_owned(), + }), + } + } + /// The Task whose worker is one of `agents` (a caller's spawn lineage): /// a worker's child acts as that worker (D-33). pub fn role_for_agents(&self, agents: &[String]) -> Option<(String, String)> { @@ -6009,6 +6039,22 @@ pub fn issue_body(task: &Task, factory: &Factory) -> String { body } +/// A command's caller as the host saw it. +#[derive(Clone, Copy, Debug)] +pub struct Caller<'a> { + pub pane: Option<&'a str>, + pub cwd: Option<&'a str>, + /// A pane the caller named but could not be checked against: it can only + /// make the caller a worker, never an operator. + pub claimed: Option<&'a str>, + /// The agents above the caller in the spawn lineage, nearest first. + pub ancestor_agents: &'a [String], + /// The pane each of those agents was registered on. + pub ancestor_panes: &'a [String], + /// The lineage walk reached an agent with no parent. + pub lineage_complete: bool, +} + pub fn pr_body(task: &Task, factory: &Factory) -> String { let mut body = issue_body(task, factory); if !task.decisions.is_empty() { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 50deb84515..78b22ef7e5 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -933,6 +933,72 @@ fn an_agent_a_worker_spawned_acts_as_that_worker() { assert_eq!(h.engine.role_for_agents(&["agent-other".into()]), None); } +#[test] +fn a_caller_binds_through_a_claimed_pane_or_an_ancestor_s_pane_and_a_cut_lineage_only_reads() { + use hide_factory::engine::Caller; + use hide_factory::role::Role; + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Parent", &[]); + let worker_pane = h.task(&f, &t).worker.unwrap().pane.unwrap(); + let worker = Role::Worker { + factory: f.clone(), + task: t.clone(), + }; + let status = Command::Status { project: None }; + let merge = Command::Merge { task: t.clone() }; + let caller = Caller { + pane: Some("child-pane"), + cwd: Some("/elsewhere"), + claimed: None, + ancestor_agents: &[], + ancestor_panes: &[], + lineage_complete: true, + }; + // A worker stopped mid-turn spawned a helper: its parent is a new, + // parentless record on the worker's own pane. + let panes = [worker_pane.clone()]; + let agents = ["agent-new".to_owned()]; + let helper = Caller { + ancestor_agents: &agents, + ancestor_panes: &panes, + ..caller + }; + assert_eq!(h.engine.caller_role(&helper, &merge).unwrap(), worker); + // A checkout caller that names a worker's pane is that worker. + let checkout = Caller { + pane: None, + claimed: Some(&worker_pane), + ..caller + }; + assert_eq!(h.engine.caller_role(&checkout, &merge).unwrap(), worker); + // A lineage cut short reads, and acts as no operator. + let cut = Caller { + lineage_complete: false, + ..caller + }; + assert!(matches!( + h.engine.caller_role(&cut, &status), + Ok(Role::Operator { .. }) + )); + for command in [ + merge.clone(), + Command::Answer { + task: t.clone(), + question: None, + choice: None, + text: Some("yes".into()), + }, + ] { + let refused = h.engine.caller_role(&cut, &command).unwrap_err(); + assert_eq!(refused.reason, "lineage_unknown"); + } + assert!(matches!( + h.engine.caller_role(&caller, &merge), + Ok(Role::Operator { .. }) + )); +} + #[test] fn a_worker_cannot_act_as_a_person() { let mut h = Bench::new(false); From 733dc0edeb83af1d39056164028fa97044691df7 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:09:36 +0900 Subject: [PATCH 48/72] Read only the tail of a capped verify log when cutting it --- hide-factory/src/verify.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/hide-factory/src/verify.rs b/hide-factory/src/verify.rs index 8139ba5b72..c9ba6a4ff6 100644 --- a/hide-factory/src/verify.rs +++ b/hide-factory/src/verify.rs @@ -346,8 +346,16 @@ fn trim(log: &Path) { if meta.len() <= LOG_LIMIT { return; } - if let Ok(bytes) = std::fs::read(log) { - let tail = &bytes[bytes.len() - LOG_LIMIT as usize..]; + // Only the tail is read: a log cut at the output cap can be hundreds of + // megabytes (rule 15). + let tail = std::fs::File::open(log).and_then(|mut file| { + use std::io::{Read, Seek, SeekFrom}; + file.seek(SeekFrom::Start(meta.len() - LOG_LIMIT))?; + let mut tail = Vec::with_capacity(LOG_LIMIT as usize); + file.take(LOG_LIMIT).read_to_end(&mut tail)?; + Ok(tail) + }); + if let Ok(tail) = tail { let _ = std::fs::write(log, tail); } } @@ -537,6 +545,19 @@ mod tests { assert!(!dir.path().join("ran.txt").exists()); } + #[test] + fn a_long_log_keeps_its_last_bytes() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("run.log"); + let mut text = vec![b'a'; LOG_LIMIT as usize + 10]; + text.extend_from_slice(b"the end"); + std::fs::write(&log, &text).unwrap(); + trim(&log); + let kept = std::fs::read(&log).unwrap(); + assert_eq!(kept.len() as u64, LOG_LIMIT); + assert!(kept.ends_with(b"the end")); + } + #[test] fn a_run_writing_past_the_output_cap_is_ended_and_failed() { let dir = tempfile::tempdir().unwrap(); From 750738db7c4aee4b8ba96ff62de00041e351636c Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:11:06 +0900 Subject: [PATCH 49/72] Scope recovery actions to the diagnosed Factory, say what sleep-wake can do for an agent waiting on a person, and test them --- docs/factory.md | 10 ++++---- hide-factory/src/engine.rs | 22 ++++++++++------ hide-factory/tests/engine.rs | 49 ++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 12 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 8d39590ca8..9959736265 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -414,15 +414,15 @@ An environment problem is not a Task's failure and is never counted against it. - **Cascade.** Three different Tasks failing the same check or command within 30 minutes are read as the environment: each failure is taken back, the Tasks go to `waiting`, and new starts halt for 30 minutes. - **If it does not clear.** A problem that outlasts 30 minutes asks `factory_env_diagnosis` once for a cause and either one action from the closed list or an exact command with its impact. -The closed recovery list is the only set of actions the Factory runs without a person, and `config --set recovery==on` turns each on; all are off. Each action touches only the diagnosed Factory's Tasks. +The closed recovery list is the only set of actions the Factory runs without a person, and `config --set recovery==on` turns each on; all are off. Each action touches only the diagnosed Factory's Tasks, except the start hold and the runtime switch, which belong to the machine. | Action | Does | | --- | --- | -| `remove_finished_worktrees` | Removes the worktree of a finished Task and of a cancelled Task past its keep period. | +| `remove_finished_worktrees` | Removes the worktree of the Factory's finished Tasks and of its cancelled Tasks past their keep period. | | `restart_worker` | A Task stopped by a refused start, a repeated environment failure, no report or a stall goes back to `waiting`, and its worker starts again in the same worktree and session. | -| `sleep_wake_worker` | A running worker waiting on input is put to sleep and woken in the same session with a note to carry on. | -| `switch_runtime` | New starts of unpinned Tasks leave the Factory's default runtime for an hour, while the other runtime is not limited. | -| `retry_reads_and_reconnect` | Clears read back-offs and the start hold. | +| `sleep_wake_worker` | A running worker waiting on input is asked to sleep and woken in the same session with a note to carry on. Herdr does not put an agent that waits for a person to sleep, so for such an agent the note waits for its next prompt. | +| `switch_runtime` | New starts of unpinned Tasks leave the Factory's default runtime for an hour, while the other runtime is not limited; the runtime is the machine's, so this holds for every Factory. | +| `retry_reads_and_reconnect` | Clears the Factory's read back-off and the machine's start hold. | A diagnosis naming an action that is off becomes a proposal that the Factory runs once a person answers `approve`; any other command becomes a proposal with the exact command and impact, which a person runs themselves or dismisses. Logging in, deleting outside the Factory and installing tools are only ever proposals. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index fd0ca2df83..e99bf35614 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -5350,7 +5350,7 @@ impl Engine { EnvSignal::DiskFull => { self.hold_reason = Some("디스크 부족".into()); self.hold_checked_at = Some(now); - self.remove_finished_worktrees(); + self.remove_finished_worktrees(None); } EnvSignal::OutOfMemory => { if let Some(task) = task @@ -5401,11 +5401,13 @@ impl Engine { } /// D-54 ①: only worktrees of finished Tasks and of cancelled Tasks past - /// their keep period (B62). - fn remove_finished_worktrees(&mut self) { + /// their keep period (B62), of one Factory or, below the disk floor, of + /// every Factory. + fn remove_finished_worktrees(&mut self, only: Option<&str>) { let now = self.now(); let targets: Vec<(String, String, WorkerRef)> = self .all_tasks() + .filter(|t| only.is_none_or(|factory| t.factory == factory)) .filter(|t| !t.purged) .filter(|t| { let keep = self @@ -5487,9 +5489,13 @@ impl Engine { json!({"action": action.as_str()}), ); match action { - RecoveryAction::RemoveFinishedWorktrees => self.remove_finished_worktrees(), + RecoveryAction::RemoveFinishedWorktrees => { + self.remove_finished_worktrees(Some(factory)); + } + // The start hold is the machine's (disk, memory): reading it again + // is not one Factory's to keep. RecoveryAction::RetryReadsAndReconnect => { - self.github_backoff.clear(); + self.github_backoff.remove(factory); self.hold_reason = None; } // A Task the environment stopped starts its worker again in the @@ -5517,8 +5523,10 @@ impl Engine { self.set_state(factory, &id, TaskState::Waiting); } } - // A running worker waiting on input is put to sleep and woken - // in the same session with a note to carry on. + // A running worker waiting on input is asked to sleep and woken + // in the same session with a note to carry on. Herdr does not put + // an agent waiting for a person to sleep, so for such an agent the + // note waits for its next prompt. RecoveryAction::SleepWakeWorker => { let stuck: Vec<(String, WorkerRef)> = self .tasks_of(factory) diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 78b22ef7e5..337c3a2bc1 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1989,6 +1989,55 @@ fn a_diagnosis_runs_an_enabled_recovery_and_an_approved_proposal_runs_too() { assert_ne!(h.state(&f, &stopped), TaskState::Stopped); } +/// Turns `action` on, holds starts below the disk floor so a problem +/// outlasts 30 minutes, and lets the diagnosis name `action`. +fn diagnose(h: &mut Bench, action: &str) -> String { + let enabled = h.op(Command::Config { + project: Some(PROJECT.into()), + set: vec![("recovery".into(), format!("{action}=on"))], + }); + assert_eq!(enabled["ok"], true, "{enabled}"); + h.world().disk_free = Some(1 << 30); + let held = h.ready("Held", &[]); + h.world().env_diagnosis = Some(json!({"cause": "disk", "action": action})); + h.advance(31 * MINUTE_MS); + h.engine.tick(); + h.engine.tick(); + held +} + +#[test] +fn sleep_wake_reaches_only_a_worker_waiting_on_input() { + let mut h = Bench::new(false); + let f = h.factory(true); + let blocked = h.ready("Blocked", &[]); + let working = h.ready("Working", &[]); + h.world() + .worker_status + .insert(blocked.clone(), WorkerStatus::Blocked); + diagnose(&mut h, "sleep_wake_worker"); + let world = h.world(); + assert!(world.sleeps.contains(&blocked)); + assert!(world.wakes.iter().any(|(task, _)| *task == blocked)); + assert!(!world.sleeps.contains(&working)); + assert!(!world.wakes.iter().any(|(task, _)| *task == working)); + drop(world); + assert_eq!(h.state(&f, &blocked), TaskState::Running); +} + +#[test] +fn switching_runtime_moves_new_starts_to_the_other_runtime() { + let mut h = Bench::new(false); + let f = h.factory(true); + let held = diagnose(&mut h, "switch_runtime"); + h.world().disk_free = None; + h.advance(2 * MINUTE_MS); + tick_until(&mut h, &f, &held, TaskState::Running); + let default = h.engine.factories().next().unwrap().config.default_runtime; + let started = h.task(&f, &held).worker.unwrap().runtime; + assert_ne!(started, default, "the default runtime rests for an hour"); +} + #[test] fn a_failed_store_write_is_counted_and_handed_to_the_host_log() { let mut h = Bench::new(false); From 332af055e3d779fb0e40af6ddcc690dbcb975f28 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:12:20 +0900 Subject: [PATCH 50/72] Give an outside-taken Task with no worker its keep period, keep the first takeover's period, start a restarted Task's checks once, and test a manual merge's recheck --- hide-factory/src/engine.rs | 21 ++++++++++++---- hide-factory/tests/engine.rs | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index e99bf35614..42bee3abe0 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -2939,7 +2939,13 @@ impl Engine { }); self.start_verification(factory, id, stage); } - self.start_checks(factory, id); + // A report still to be published starts its checks once pushed. + if self + .task(factory, id) + .is_some_and(|task| !task.writes.contains(PUBLISH_PENDING)) + { + self.start_checks(factory, id); + } } fn cancel_verification(&mut self, factory: &str, id: &str) { @@ -3419,15 +3425,21 @@ impl Engine { /// stopped and its worktree kept for the keep period from now, so the /// work it had not reported survives until then. fn follow_outside(&mut self, factory_id: &str, task: &Task) { - let Some(worker) = &task.worker else { return }; - if task.purged { + // A Task already taken keeps the keep period of its first takeover. + if task.state == TaskState::Outside && task.cancelled_at.is_some() { return; } - self.stop_worker(factory_id, &task.id, worker); let now = self.now(); self.with_task(factory_id, &task.id, |t| { t.cancelled_at = Some(now); t.cancelled_from = Some(t.state); + }); + let Some(worker) = &task.worker else { return }; + if task.purged { + return; + } + self.stop_worker(factory_id, &task.id, worker); + self.with_task(factory_id, &task.id, |t| { if let Some(w) = &mut t.worker { w.asleep = true; } @@ -4951,6 +4963,7 @@ impl Engine { self.notice(factory_id, &task.id, &format!("밖의 PR이 이 Task의 issue를 닫습니다: {url}. worker를 멈췄고 worktree는 7일 남습니다. 되살리려면 hide factory revive {}", task.display_id())); } _ => { + self.follow_outside(factory_id, &task); self.set_state(factory_id, &task.id, TaskState::Outside); self.record(factory_id, Some(&task.id), "outside.pr", json!({"pr": pr})); } diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 337c3a2bc1..97b66f4d7a 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1451,6 +1451,28 @@ fn a_conflict_sends_the_worker_to_rebase_without_counting_a_failure() { assert!(h.world().wakes.last().unwrap().1.contains("rebase")); } +#[test] +fn a_manual_merge_checks_main_again_and_a_conflict_goes_back_to_rebase() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Manual); + let t = h.ready("Waits", &[]); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + // Main moved while the Task waited for a person. + h.world().premerge.insert( + t.clone(), + [hide_factory::adapters::PreMerge::Conflict { + files: vec!["src/lib.rs".into()], + }] + .into(), + ); + let refused = h.op(Command::Merge { task: t.clone() }); + assert_eq!(refused["reason"], "merge_conflict", "{refused}"); + assert_eq!(h.state(&f, &t), TaskState::Running); + assert!(h.world().wakes.last().unwrap().1.contains("rebase")); + assert!(h.writes("merge").is_empty(), "nothing merged"); +} + #[test] fn a_dirty_local_main_holds_the_merge() { let mut h = Bench::new(false); @@ -1807,6 +1829,30 @@ fn an_outside_pull_request_takes_a_running_task_and_its_merge_finishes_it() { assert_eq!(h.world().removed, vec![t.clone()]); } +#[test] +fn a_task_taken_before_its_start_expires_after_the_keep_period() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + set_workers(&mut h, &f, 1); + let _running = h.ready("Running", &[]); + let t = h.ready("Waiting", &[]); + assert_eq!(h.state(&f, &t), TaskState::Waiting); + let issue = h.task(&f, &t).issue.unwrap(); + h.world().outside.push_back(OutsideEvent::ClosingPr { + issue, + pr: 56, + url: "pr/56".into(), + merged: false, + }); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Outside); + assert!(h.task(&f, &t).cancelled_at.is_some(), "its keep period runs"); + h.advance(8 * DAY_MS); + h.engine.tick(); + assert!(h.task(&f, &t).purged, "folded after the keep period"); +} + #[test] fn a_task_waiting_long_on_a_person_keeps_its_worktree_after_an_outside_pull_request() { let mut h = Bench::new(true); From 809b95623d3c2dfee29a849f4eb34e8068e32fe2 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:17:24 +0900 Subject: [PATCH 51/72] Format the review fixes --- herdr-core/src/runtime/factory.rs | 6 +++++- hide-factory/src/engine.rs | 19 ++++++++++--------- hide-factory/src/project.rs | 26 ++++++++++++++++++++------ hide-factory/tests/engine.rs | 5 ++++- hide-factory/tests/github.rs | 10 +++++++--- hide-factory/tests/local_git.rs | 5 ++++- 6 files changed, 50 insertions(+), 21 deletions(-) diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index 270c39216d..ad36cbd4cc 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -370,7 +370,11 @@ mod tests { let none = runtime.factory_lineage("w0:p1"); assert!(none.agents.is_empty() && none.complete); let looped = runtime.factory_lineage("w9:p1"); - assert_eq!(looped.agents, vec!["agent-b", "agent-a"], "a loop ends the walk"); + assert_eq!( + looped.agents, + vec!["agent-b", "agent-a"], + "a loop ends the walk" + ); assert!(!looped.complete, "a loop cannot rule out a worker above"); } diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 42bee3abe0..55d2d5e622 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -361,7 +361,11 @@ impl Engine { pub fn caller_role(&self, caller: &Caller<'_>, command: &Command) -> Result { let bound = self .role_for(caller.pane, caller.cwd) - .or_else(|| caller.claimed.and_then(|pane| self.role_for(Some(pane), None))) + .or_else(|| { + caller + .claimed + .and_then(|pane| self.role_for(Some(pane), None)) + }) .or_else(|| self.role_for_agents(caller.ancestor_agents)) .or_else(|| { caller @@ -4564,9 +4568,10 @@ impl Engine { // the slot. let starting: Vec<_> = self.starting.keys().cloned().collect(); for (factory, id) in starting { - if self.task(&factory, &id).is_none_or(|t| { - !matches!(t.state, TaskState::Waiting | TaskState::Relanding) - }) { + if self + .task(&factory, &id) + .is_none_or(|t| !matches!(t.state, TaskState::Waiting | TaskState::Relanding)) + { // A start the adapter took over is never replayed by its // intent: a later start is a new attempt. A spawn whose agent // had not shown yet is asked again as the same attempt, so a @@ -6086,11 +6091,7 @@ pub fn pr_body(task: &Task, factory: &Factory) -> String { .iter() .map(|decision| format!("- {}\n", decision.text)) .collect(); - let longest = text - .split(|c| c != '`') - .map(str::len) - .max() - .unwrap_or(0); + let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0); let fence = "`".repeat(longest.max(2) + 1); body.push_str(&format!("\n## 결정 기록\n{fence}text\n{text}{fence}\n")); } diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 431464339d..2dcdb94a1c 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -717,7 +717,10 @@ impl TaskSource for SharedProjects { let own_heads: BTreeSet = tasks .iter() .flat_map(|task| { - [Some(task.branch_slug()), task.worker.as_ref().map(|w| w.branch.clone())] + [ + Some(task.branch_slug()), + task.worker.as_ref().map(|w| w.branch.clone()), + ] }) .flatten() .collect(); @@ -762,9 +765,7 @@ impl TaskSource for SharedProjects { .flatten() .any(|i| i["number"].as_u64() == Some(*number)) }) - .filter(|pr| { - pr["number"].as_u64().is_none_or(|n| !own_prs.contains(&n)) - }) + .filter(|pr| pr["number"].as_u64().is_none_or(|n| !own_prs.contains(&n))) .filter(|pr| { pr["isCrossRepository"].as_bool() == Some(true) || pr["headRefName"] @@ -852,7 +853,12 @@ impl MergeTarget for SharedProjects { let remote = this.git( "git.push", &path, - &["ls-remote", "--heads", "origin", &format!("refs/heads/{branch}")], + &[ + "ls-remote", + "--heads", + "origin", + &format!("refs/heads/{branch}"), + ], )?; if remote.trim().is_empty() { this.git( @@ -1260,7 +1266,15 @@ impl MergeTarget for SharedProjects { let existing = this.gh_json( "github.pr_find", &[ - "pr", "list", "--repo", &repo, "--head", &branch, "--state", "open", "--json", + "pr", + "list", + "--repo", + &repo, + "--head", + &branch, + "--state", + "open", + "--json", "number,isCrossRepository", ], )?; diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 97b66f4d7a..6d98f72e92 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1847,7 +1847,10 @@ fn a_task_taken_before_its_start_expires_after_the_keep_period() { h.advance(3 * MINUTE_MS); h.engine.tick(); assert_eq!(h.state(&f, &t), TaskState::Outside); - assert!(h.task(&f, &t).cancelled_at.is_some(), "its keep period runs"); + assert!( + h.task(&f, &t).cancelled_at.is_some(), + "its keep period runs" + ); h.advance(8 * DAY_MS); h.engine.tick(); assert!(h.task(&f, &t).purged, "folded after the keep period"); diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index 4c20204a92..d25782f059 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -557,8 +557,10 @@ fn a_held_issue_that_cannot_be_read_keeps_its_task_and_a_deleted_one_is_gone() { hub.issues .insert(9, ("Listed".into(), "body".into(), "CLOSED".into())); hub.list_cap = Some(1); - hub.view_errors - .insert(1, "issue view refused: transferred to another repository".into()); + hub.view_errors.insert( + 1, + "issue view refused: transferred to another repository".into(), + ); hub.view_errors.insert( 2, "GraphQL: Could not resolve to an issue or pull request with the number of 2.".into(), @@ -634,7 +636,9 @@ fn a_worker_s_closing_keyword_in_a_decision_stays_text() { at: 0, }); let body = hide_factory::engine::pr_body(&t, &factory()); - let fence = body.find("````text").expect("a fence longer than the text's"); + let fence = body + .find("````text") + .expect("a fence longer than the text's"); let fixes = body.find("Fixes #2").unwrap(); let close = body[fixes..].find("````").map(|i| i + fixes).unwrap(); assert!(fence < fixes && fixes < close, "{body}"); diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index 5244578050..053de34d12 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -383,7 +383,10 @@ fn a_report_after_the_remote_deleted_the_task_branch_still_pushes() { assert_eq!(pr.number, 7); // The pull request merged and the remote deleted its branch; the Task // was reverted and reports again with a new commit. - git(&remote, &["update-ref", "-d", &format!("refs/heads/{branch}")]); + git( + &remote, + &["update-ref", "-d", &format!("refs/heads/{branch}")], + ); write(&worktree, "b.txt", "three\n"); git(&worktree, &["commit", "--quiet", "-am", "again"]); projects.open_pr(&factory, &t, "body").unwrap(); From 2a88be8ce8a9afb8701fd3f954e0835744f9695c Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:38:11 +0900 Subject: [PATCH 52/72] Read only the commit of an unnamed merge and cap it, back off only on GitHub signals, count git transport errors as the network, let an ended or orphaned agent act as no operator, and let block pass the report cap --- docs/factory.md | 9 ++- herdr-core/src/factory.rs | 4 + herdr-core/src/runtime/factory.rs | 60 ++++++++++++--- hide-factory/src/engine.rs | 119 +++++++++++++++++++++++------- hide-factory/src/exec.rs | 26 +++++++ hide-factory/tests/engine.rs | 81 +++++++++++++++++++- hide-factory/tests/support/mod.rs | 5 ++ 7 files changed, 262 insertions(+), 42 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 9959736265..0012ba19ea 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -146,6 +146,7 @@ A `cancelled` or `done` Task's worker stays a worker while its worktree and pane Once a Task's worktree is removed it binds no pane or folder, because Herdr can give a closed pane id to the operator's next pane. An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up) and binds an ancestor by its agent id or by the pane it was registered on, and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. A lineage the host cannot read to its root (the ledger unreadable, a missing record, a loop, more than 16 agents) may hide a worker above, so that caller can only read; anything else is refused with `lineage_unknown`. +An agent that has ended speaks for no pane, since Herdr reuses pane ids, and an agent a Factory started that no Task holds as its worker (a start abandoned on its way) can only read; anything else is refused with `factory_agent_unbound`. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. @@ -163,7 +164,7 @@ A capability file holds only a token, so editing it cannot change a role. | Configure | `config --set` | refused | yes | A refusal answers `role_not_allowed` with the role and the verb. -A Task keeps at most 500 questions, decisions and discoveries together; past that a worker's report is refused with `report_limit`, except `done`, which still finishes the Task without storing its summary. +A Task keeps at most 500 questions, decisions and discoveries together; past that a worker's report is refused with `report_limit`, except `done`, which still finishes the Task without storing its summary, and `block`, which still stops it for a person. A worker's `show` reaches its own Factory only. An operator relays a person's words, and every answer and decision records the relaying pane as `relayed_by`. Code cannot tell whether an operator pane's agent acted on a person's words, so it records who relayed and does not block. @@ -216,7 +217,7 @@ A worker reports through `hide factory` and gets its answer in the same call. On a GitHub Factory the next tick pushes the worktree's commits to the Task branch (with a lease, so a rebase goes through), then finds the open pull request for that branch or opens one, and only then reads CI on the pushed commit; every report pushes, so a fix after a failed check reaches the same pull request, and a merged pull request from before a revert is never reused. A Task branch the remote deleted, as automatic branch deletion does after a merge, is pushed again rather than refused by a stale lease. Only a pull request from the repository's own branch is a Task's or a revert's; a fork's pull request on the same branch name is never adopted. -A push or pull request refused twice in a row with no environment signal (a protected branch, a hook) stops the Task as "push 거절됨" with the reason; a person fixes the cause and retries. One with an environment signal is asked again every minute. +A push or pull request refused twice in a row with no environment signal in between (a protected branch, a hook; git's transport errors such as a 5xx answer, a timeout or a hung-up remote count as the network's) stops the Task as "push 거절됨" with the reason; a person fixes the cause and retries. One with an environment signal is asked again every minute. A failed push or pull request is tried again a minute later. `decide` records a decision. A worker whose agent rests for the no-report window (`no_report_minutes`, 2) after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for the stall window (`stall_minutes`, 30) stops it as "stalled". @@ -319,7 +320,7 @@ A gate sends an `auto` Task to `merge_waiting` and appears in the Task page and A review by an agent alone never merges. A person's `merge` runs merge-tree and the quick check again on the latest main, then the same merge at once; a conflict sends the worker to rebase and a failed quick check counts as a verification failure. -A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a signal and every 30 seconds for an unnamed commit, with no merge-tree or quick check in between. +A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a rate-limit, server or network signal (a minute for any other signal) and every 30 seconds for an unnamed commit, which reads only the merge commit, with no merge-tree or quick check in between; a commit still unnamed after 10 minutes waits for a person as a refused merge. While a merge's commit is unnamed, a red run on a main head the Factory has not recorded is read as pending, not as an outside push. `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. @@ -351,7 +352,7 @@ A held issue missing from that list is looked up by number, at most 20 per read | What the Factory sees | What it does | | --- | --- | -| A pull request the Factory did not open closes a Task's issue, and it is open | A pull request one of the Factory's own Tasks opened never counts, whatever its worker wrote; the decisions a worker records sit in a code block in its pull request body, so a "Fixes #N" there stays text. A pull request from a fork counts only once it is merged, since anyone can open one. Otherwise the Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | +| A pull request the Factory did not open closes a Task's issue, and it is open | A pull request one of the Factory's own Tasks opened never counts, whatever its worker wrote; the decisions a worker records sit in a code block in its pull request body, so a "Fixes #N" there stays text. GitHub can still close another Task's issue from a closing keyword a worker put in a commit message or in a card it proposed, when that merge lands; the other Task is then cancelled and kept for revive. A pull request from a fork counts only once it is merged, since anyone can open one. Otherwise the Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | | That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. A stopped worker's worktree still waits out its keep period. | | The issue closes with no pull request, or the `factory` label is removed | The Task is cancelled with a notice, kept for the keep period. | | A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index f48ac758a2..a13c9e1f0a 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -77,6 +77,8 @@ pub struct Lineage { /// unreadable, a missing record, a loop, the step limit) cannot rule out /// a worker above the caller. pub complete: bool, + /// A Factory's own agent is above the caller. + pub factory_spawned: bool, } impl Lineage { @@ -86,6 +88,7 @@ impl Lineage { agents: Vec::new(), panes: Vec::new(), complete: true, + factory_spawned: false, } } } @@ -538,6 +541,7 @@ fn handle( ancestor_agents: &caller.ancestors.agents, ancestor_panes: &caller.ancestors.panes, lineage_complete: caller.ancestors.complete, + factory_spawned: caller.ancestors.factory_spawned, }; let role = match engine.caller_role(&facts, &command) { Ok(role) => role, diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index ad36cbd4cc..54f01cd368 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -77,7 +77,13 @@ impl Runtime { let Ok(ledger) = self.delivery_state() else { return lineage; }; - let mut next = match ledger.agents.iter().rev().find(|agent| agent.pane == pane) { + // Herdr reuses pane ids: only an agent still on the pane speaks for it. + let mut next = match ledger + .agents + .iter() + .rev() + .find(|agent| agent.pane == pane && !agent.ended) + { Some(agent) => agent.parent.clone(), None => None, }; @@ -90,7 +96,11 @@ impl Runtime { return lineage; }; lineage.agents.push(id); - lineage.panes.push(agent.pane.clone()); + lineage.factory_spawned |= agent.actor.code_owned(); + // An ended agent's pane may be someone else's now. + if !agent.ended { + lineage.panes.push(agent.pane.clone()); + } next = agent.parent.clone(); } lineage.complete = true; @@ -335,12 +345,15 @@ mod tests { pane: pane.into(), parent: parent.map(str::to_owned), project: None, - actor: Actor { - pane_id: pane.into(), - name: id.into(), - kind: "claude".into(), - device_id: "local".into(), - session: crate::wire::session_digest(id), + actor: match pane.strip_prefix("factory:") { + Some(factory) => Actor::factory(factory), + None => Actor { + pane_id: pane.into(), + name: id.into(), + kind: "claude".into(), + device_id: "local".into(), + session: crate::wire::session_digest(id), + }, }, ended: false, } @@ -366,7 +379,7 @@ mod tests { vec!["agent-child", "agent-worker", "agent-factory"] ); assert_eq!(full.panes, vec!["w2:p1", "w1:p1", "factory:f-1"]); - assert!(full.complete); + assert!(full.complete && full.factory_spawned); let none = runtime.factory_lineage("w0:p1"); assert!(none.agents.is_empty() && none.complete); let looped = runtime.factory_lineage("w9:p1"); @@ -376,6 +389,35 @@ mod tests { "a loop ends the walk" ); assert!(!looped.complete, "a loop cannot rule out a worker above"); + assert!(!looped.factory_spawned); + } + + #[test] + fn an_ended_agent_speaks_for_no_pane() { + let mut runtime = crate::runtime::tests::runtime(); + let ended = |mut record: AgentRecord| { + record.ended = true; + record + }; + runtime.delivery_ledger = Ok(Arc::new(Ledger { + agents: vec![ + agent("agent-factory", "factory:f-1", None), + ended(agent("agent-worker", "w1:p1", Some("agent-factory"))), + ended(agent("agent-child", "w2:p1", Some("agent-worker"))), + agent("agent-grandchild", "w3:p1", Some("agent-child")), + ], + ..Ledger::default() + })); + // A person's shell on a pane whose id an ended agent had. + let reused = runtime.factory_lineage("w2:p1"); + assert!(reused.agents.is_empty() && reused.complete && !reused.factory_spawned); + // Ended ancestors stay in the walk but lend no pane to bind by. + let live = runtime.factory_lineage("w3:p1"); + assert_eq!( + live.agents, + vec!["agent-child", "agent-worker", "agent-factory"] + ); + assert_eq!(live.panes, vec!["factory:f-1"]); } fn row(provider: &str, used: f64, bucket: Option<(f64, u64)>) -> ProviderUsageSnapshot { diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 55d2d5e622..437bcd35f6 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -72,6 +72,9 @@ pub const REPORT_LIMIT: usize = 500; const MAIN_CHECK_EVERY_MS: u64 = 30_000; /// When a merge that GitHub answered without its commit is asked again. pub const MERGE_COMMIT_AGAIN_MS: u64 = 30_000; +/// How long a merge GitHub answered without naming its commit is read again +/// before a person looks. +pub const MERGE_UNNAMED_LIMIT_MS: u64 = 10 * 60_000; /// When a failed push or pull request of a reported Task is tried again. const PUBLISH_RETRY_MS: u64 = 60_000; /// A GitHub Task's report whose commits are not pushed yet. @@ -167,9 +170,9 @@ pub struct Engine { /// Refusals in a row of a Task's push or pull request that no /// environment signal explains. publish_refusals: BTreeMap<(String, String), u32>, - /// When a merge asked to wait is tried again, per Task, and whether the - /// merge may already have landed with its commit not named yet. - merge_retry: BTreeMap<(String, String), (UnixMs, bool)>, + /// When a merge asked to wait is tried again, per Task, and since when + /// the merge may have landed with its commit not named yet. + merge_retry: BTreeMap<(String, String), (UnixMs, Option)>, processed: BTreeSet, processed_order: Vec, /// Recent environment and Task failures the cascade rules read. @@ -381,6 +384,14 @@ impl Engine { "The caller's spawn lineage could not be read to its root; run this from an operator pane", )) } + // An agent a Factory started that is no Task's worker now (a + // start abandoned on its way) is never an operator. + None if caller.factory_spawned && command.permission() != Permission::Read => { + Err(Refusal::new( + "factory_agent_unbound", + "This agent was started by a Factory for a Task it no longer holds; run this from an operator pane", + )) + } None => Ok(Role::Operator { pane: caller.pane.unwrap_or("checkout").to_owned(), }), @@ -391,10 +402,12 @@ impl Engine { /// a worker's child acts as that worker (D-33). pub fn role_for_agents(&self, agents: &[String]) -> Option<(String, String)> { let bound = |task: &&Task| { - task.worker - .as_ref() - .and_then(|worker| worker.agent.as_ref()) - .is_some_and(|agent| agents.contains(agent)) + !task.purged + && task + .worker + .as_ref() + .and_then(|worker| worker.agent.as_ref()) + .is_some_and(|agent| agents.contains(agent)) }; let finished = |task: &&Task| matches!(task.state, TaskState::Cancelled | TaskState::Done); let live = self.all_tasks().filter(|t| !finished(t)).find(&bound); @@ -567,6 +580,12 @@ impl Engine { } }); if let Some(from) = from { + if from == TaskState::Verifying { + // A merge or push asked again belongs to this verifying stay. + let key = (factory.to_owned(), id.to_owned()); + self.merge_retry.remove(&key); + self.publish_refusals.remove(&key); + } self.record( factory, Some(id), @@ -668,9 +687,10 @@ impl Engine { } let verb = command.verb(); // A worker's reports grow its Task record: past the cap a report is - // refused, never stored (rule 15). `done` still finishes the Task. + // refused, never stored (rule 15). `done` still finishes the Task, and + // `block` still stops it for a person; each needs a running Task. if command.permission() == Permission::Report - && !matches!(command, Command::Done { .. }) + && !matches!(command, Command::Done { .. } | Command::Block { .. }) && let Role::Worker { factory, task } = role && let Some(task) = self.task(factory, task) && task.questions.len() + task.decisions.len() + task.discoveries.len() >= REPORT_LIMIT @@ -2729,11 +2749,13 @@ impl Engine { } Err(failure) => { self.external_failure(factory_id, Some(id), &failure); + // An environment signal in between breaks the run of refusals. let refusals = if failure.signal.is_none() { let n = self.publish_refusals.entry(key.clone()).or_default(); *n += 1; *n } else { + self.publish_refusals.remove(&key); 0 }; if refusals >= 2 { @@ -3077,12 +3099,16 @@ impl Engine { } let key = (factory_id.to_owned(), id.to_owned()); // A merge asked to wait is not read again before its time (B39). - if self - .merge_retry - .get(&key) - .is_some_and(|(at, _)| *at > self.now()) - { - return; + if let Some((at, unnamed)) = self.merge_retry.get(&key).copied() { + if at > self.now() { + return; + } + // GitHub took the merge and has not named its commit: only that + // is read again, never main merged in or the quick check. + if unnamed.is_some() { + let _ = self.merge_now(factory_id, id); + return; + } } if self.verifying.contains_key(&key) { return; @@ -3297,21 +3323,56 @@ impl Engine { Err(failure) => { self.external_failure(factory_id, Some(id), &failure); let now = self.now(); + let key = (factory_id.to_owned(), id.to_owned()); // Asked to wait (a merge commit not named yet, or GitHub or // the network down): tried again at its time, not per tick. - let wait = failure.again_in_ms.or_else(|| { - failure.signal.map(|_| { - self.github_backoff - .get(factory_id) - .map(|(_, until)| until.saturating_sub(now)) - .unwrap_or(PUBLISH_RETRY_MS) - }) - }); - if let Some(wait) = wait { - self.merge_retry.insert( - (factory_id.to_owned(), id.to_owned()), - (now + wait.max(1), failure.again_in_ms.is_some()), + let backoff = self + .github_backoff + .get(factory_id) + .map(|(_, until)| *until) + .filter(|until| *until > now) + .filter(|_| { + matches!( + failure.signal, + Some( + EnvSignal::GithubRateLimit + | EnvSignal::GithubServer + | EnvSignal::Network + ) + ) + }); + let retry_at = match (failure.again_in_ms, failure.signal) { + (Some(wait), _) => Some(now + wait.max(1)), + (None, Some(_)) => Some(backoff.unwrap_or(now + PUBLISH_RETRY_MS)), + (None, None) => None, + }; + let since = self.merge_retry.get(&key).and_then(|(_, since)| *since); + let unnamed = failure.again_in_ms.is_some().then(|| since.unwrap_or(now)); + if unnamed.is_some_and(|since| now.saturating_sub(since) >= MERGE_UNNAMED_LIMIT_MS) + { + // GitHub never named the commit: a person looks (rule 15). + self.merge_retry.remove(&key); + self.with_task(factory_id, id, |task| { + if !task.gates.contains(&Gate::MergeRefused) { + task.gates.push(Gate::MergeRefused); + } + }); + self.record( + factory_id, + Some(id), + "merge.refused", + json!({"stage": failure.stage, "detail": "the merge commit was not named in 10 minutes"}), ); + self.set_state(factory_id, id, TaskState::MergeWaiting); + return Err(failure); + } + match retry_at { + Some(at) => { + self.merge_retry.insert(key, (at, unnamed)); + } + None => { + self.merge_retry.remove(&key); + } } if failure.signal.is_none() && failure.again_in_ms.is_none() { self.with_task(factory_id, id, |task| { @@ -5180,7 +5241,7 @@ impl Engine { fn merge_unnamed(&self, factory_id: &str) -> bool { self.merge_retry .iter() - .filter(|((factory, _), (_, unnamed))| factory == factory_id && *unnamed) + .filter(|((factory, _), (_, unnamed))| factory == factory_id && unnamed.is_some()) .any(|((factory, id), _)| { self.task(factory, id) .is_some_and(|t| t.state == TaskState::Verifying) @@ -6079,6 +6140,8 @@ pub struct Caller<'a> { pub ancestor_panes: &'a [String], /// The lineage walk reached an agent with no parent. pub lineage_complete: bool, + /// A Factory's own agent is in the lineage. + pub factory_spawned: bool, } pub fn pr_body(task: &Task, factory: &Factory) -> String { diff --git a/hide-factory/src/exec.rs b/hide-factory/src/exec.rs index 33fe59f0e4..c014e05310 100644 --- a/hide-factory/src/exec.rs +++ b/hide-factory/src/exec.rs @@ -131,6 +131,7 @@ pub fn classify(stage: &str, output: &Output) -> Failure { } else if ["http 500", "http 502", "http 503", "http 504"] .iter() .any(|code| lower.contains(code)) + || lower.contains("the requested url returned error: 5") { Some(EnvSignal::GithubServer) } else if [ @@ -140,6 +141,11 @@ pub fn classify(stage: &str, output: &Output) -> Failure { "connection reset", "tls handshake", "i/o timeout", + "operation timed out", + "remote end hung up", + "early eof", + "unexpected disconnect", + "could not read from remote repository", ] .iter() .any(|needle| lower.contains(needle)) @@ -211,6 +217,26 @@ mod tests { Some(EnvSignal::DiskFull), ), ("", 137, Some(EnvSignal::OutOfMemory)), + ( + "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 502", + 128, + Some(EnvSignal::GithubServer), + ), + ( + "ssh: connect to host github.com port 22: Operation timed out\nfatal: Could not read from remote repository.", + 128, + Some(EnvSignal::Network), + ), + ( + "fatal: the remote end hung up unexpectedly", + 128, + Some(EnvSignal::Network), + ), + ( + " ! [remote rejected] HEAD -> factory/1-x (protected branch hook declined)", + 1, + None, + ), ("error: test failed, to rerun pass --lib", 101, None), ]; for (stderr, code, signal) in cases { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 6d98f72e92..4e0f08fa0d 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -954,6 +954,7 @@ fn a_caller_binds_through_a_claimed_pane_or_an_ancestor_s_pane_and_a_cut_lineage ancestor_agents: &[], ancestor_panes: &[], lineage_complete: true, + factory_spawned: false, }; // A worker stopped mid-turn spawned a helper: its parent is a new, // parentless record on the worker's own pane. @@ -997,6 +998,16 @@ fn a_caller_binds_through_a_claimed_pane_or_an_ancestor_s_pane_and_a_cut_lineage h.engine.caller_role(&caller, &merge), Ok(Role::Operator { .. }) )); + // An agent a Factory started that holds no Task now only reads. + let orphan = Caller { + factory_spawned: true, + ..caller + }; + assert_eq!( + h.engine.caller_role(&orphan, &merge).unwrap_err().reason, + "factory_agent_unbound" + ); + assert!(h.engine.caller_role(&orphan, &status).is_ok()); } #[test] @@ -1358,6 +1369,28 @@ fn a_push_refused_twice_stops_the_task_for_a_person_with_its_reason() { assert_eq!(h.world().pushes.len(), 2, "no push while stopped"); } +#[test] +fn a_signal_between_two_push_refusals_breaks_the_run() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Flaky remote", &[]); + let refused = hide_factory::adapters::Failure::task("git.push", "hook declined"); + h.world().publish_refusal = Some(refused.clone()); + h.done(&f, &t); + h.engine.tick(); + h.world().publish_refusal = Some(Failure::environment( + "git.push", + EnvSignal::Network, + "remote end hung up", + )); + h.advance(MINUTE_MS + 1); + h.engine.tick(); + h.world().publish_refusal = Some(refused); + h.advance(MINUTE_MS + 1); + h.engine.tick(); + assert_eq!(h.state(&f, &t), TaskState::Verifying, "not two in a row"); +} + #[test] fn a_manual_task_waits_for_merge_and_every_github_write_happens_once() { let mut h = Bench::new(true); @@ -1540,7 +1573,11 @@ fn a_merge_asked_to_wait_is_read_again_at_its_time_and_main_is_not_misread_meanw h.engine.tick(); } assert_eq!(h.world().merge_attempts, 2, "once per 30 seconds over 40"); - assert!(h.world().premerge_calls <= premerges + 1); + assert_eq!( + h.world().premerge_calls, + premerges, + "only the merge commit is read again" + ); // The next outside read finds the new head. h.advance(2 * MINUTE_MS); h.engine.tick(); @@ -1550,6 +1587,48 @@ fn a_merge_asked_to_wait_is_read_again_at_its_time_and_main_is_not_misread_meanw "not read as an outside push" ); assert_eq!(h.state(&f, &t), TaskState::Verifying); + // GitHub never names it: after 10 minutes a person looks. + for _ in 0..12 { + h.advance(MINUTE_MS); + h.engine.tick(); + } + assert_eq!(h.state(&f, &t), TaskState::MergeWaiting); + assert_eq!(h.task(&f, &t).gates, vec![Gate::MergeRefused]); +} + +#[test] +fn a_merge_failing_on_a_signal_after_an_old_back_off_is_not_retried_every_tick() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + // A network blip left a back-off that has since run out. + h.world().observe_failure = Some(Failure::environment( + "github.observe", + EnvSignal::Network, + "connection reset", + )); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + h.world().observe_failure = None; + h.advance(MINUTE_MS); + let t = h.ready("Auth lapsed", &[]); + h.world().merge_failure = Some(Failure::environment( + "github.merge", + EnvSignal::GithubAuth, + "HTTP 401", + )); + h.done(&f, &t); + for _ in 0..3 { + h.engine.tick(); + } + let merges = h.world().merge_attempts; + let premerges = h.world().premerge_calls; + assert_eq!(merges, 1); + for _ in 0..20 { + h.advance(2_000); + h.engine.tick(); + } + assert!(h.world().merge_attempts <= merges + 1); + assert!(h.world().premerge_calls <= premerges + 1); } #[test] diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index e67a96171b..c26a3474ce 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -41,6 +41,8 @@ pub struct World { pub merge_attempts: u32, /// Every push is refused with this failure. pub publish_refusal: Option, + /// Every merge fails with this failure. + pub merge_failure: Option, /// Each report a GitHub Task pushed, by Task id. pub pushes: Vec, /// Main verification answers by commit, read before `main_checks`. @@ -280,6 +282,9 @@ impl MergeTarget for Shared { if let Some(failure) = world.merge_refusal.take() { return Err(failure); } + if let Some(failure) = world.merge_failure.clone() { + return Err(failure); + } if world.merge_unnamed > 0 { world.merge_unnamed -= 1; return Err(Failure { From 1f2e63a3d4cb2713bce8bcdb4735ce801e10a2fd Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:39:19 +0900 Subject: [PATCH 53/72] Keep every merge gate on an unnamed merge's retry and skip only the merge-tree and quick check --- docs/factory.md | 2 +- hide-factory/src/engine.rs | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 0012ba19ea..e6d5416c33 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -320,7 +320,7 @@ A gate sends an `auto` Task to `merge_waiting` and appears in the Task page and A review by an agent alone never merges. A person's `merge` runs merge-tree and the quick check again on the latest main, then the same merge at once; a conflict sends the worker to rebase and a failed quick check counts as a verification failure. -A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a rate-limit, server or network signal (a minute for any other signal) and every 30 seconds for an unnamed commit, which reads only the merge commit, with no merge-tree or quick check in between; a commit still unnamed after 10 minutes waits for a person as a refused merge. +A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a rate-limit, server or network signal (a minute for any other signal) and every 30 seconds for an unnamed commit, with no merge-tree or quick check in between while every gate still holds; a commit still unnamed after 10 minutes waits for a person as a refused merge. While a merge's commit is unnamed, a red run on a main head the Factory has not recorded is read as pending, not as an outside push. `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 437bcd35f6..5e518aaf03 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -3099,16 +3099,14 @@ impl Engine { } let key = (factory_id.to_owned(), id.to_owned()); // A merge asked to wait is not read again before its time (B39). - if let Some((at, unnamed)) = self.merge_retry.get(&key).copied() { + // GitHub took a merge and has not named its commit: main merged in + // and the quick check are not run again, but every gate still holds. + let mut unnamed = false; + if let Some((at, since)) = self.merge_retry.get(&key).copied() { if at > self.now() { return; } - // GitHub took the merge and has not named its commit: only that - // is read again, never main merged in or the quick check. - if unnamed.is_some() { - let _ = self.merge_now(factory_id, id); - return; - } + unnamed = since.is_some(); } if self.verifying.contains_key(&key) { return; @@ -3154,7 +3152,8 @@ impl Engine { return; } // Merge-tree and the quick check, in seconds (B38). - if factory.config.verification.exists() || factory.source == SourceKind::Local { + if !unnamed && (factory.config.verification.exists() || factory.source == SourceKind::Local) + { match self.ports.merge.premerge(&factory, &task) { Ok(PreMerge::Clean) => {} Ok(PreMerge::Conflict { files }) => { @@ -3185,7 +3184,8 @@ impl Engine { } } // Verify factories run the bundle once on the latest main merged in. - if matches!(factory.config.verification, Verification::Commands { .. }) + if !unnamed + && matches!(factory.config.verification, Verification::Commands { .. }) && !task.writes.contains("premerge_passed") { self.start_verification(factory_id, id, AttemptStage::PreMerge); From af1b82d4108425167d72dec6bc03565aec3d6696 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:47:51 +0900 Subject: [PATCH 54/72] Read an unnamed merge without merging again, keep an agent that ended its own record below its worker, and leave lasting git refusals and a quick check's text to a person --- docs/factory.md | 6 +- herdr-core/src/runtime/factory.rs | 24 ++-- hide-factory/src/adapters.rs | 10 ++ hide-factory/src/engine.rs | 226 ++++++++++++++++-------------- hide-factory/src/exec.rs | 14 +- hide-factory/src/project.rs | 19 ++- hide-factory/tests/engine.rs | 42 +++++- hide-factory/tests/support/mod.rs | 28 ++++ 8 files changed, 244 insertions(+), 125 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index e6d5416c33..7bece3b9a8 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -146,7 +146,7 @@ A `cancelled` or `done` Task's worker stays a worker while its worktree and pane Once a Task's worktree is removed it binds no pane or folder, because Herdr can give a closed pane id to the operator's next pane. An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up) and binds an ancestor by its agent id or by the pane it was registered on, and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. A lineage the host cannot read to its root (the ledger unreadable, a missing record, a loop, more than 16 agents) may hide a worker above, so that caller can only read; anything else is refused with `lineage_unknown`. -An agent that has ended speaks for no pane, since Herdr reuses pane ids, and an agent a Factory started that no Task holds as its worker (a start abandoned on its way) can only read; anything else is refused with `factory_agent_unbound`. +The walk starts from the newest record on the caller's pane even when that record has ended, because an agent can end its own record and keep running; an ended ancestor lends no pane to bind by, because Herdr reuses pane ids. A caller below a Factory's own agent that no Task holds as its worker (a start abandoned on its way, or a shell on a reused pane id) can only read; anything else is refused with `factory_agent_unbound`. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. @@ -217,7 +217,7 @@ A worker reports through `hide factory` and gets its answer in the same call. On a GitHub Factory the next tick pushes the worktree's commits to the Task branch (with a lease, so a rebase goes through), then finds the open pull request for that branch or opens one, and only then reads CI on the pushed commit; every report pushes, so a fix after a failed check reaches the same pull request, and a merged pull request from before a revert is never reused. A Task branch the remote deleted, as automatic branch deletion does after a merge, is pushed again rather than refused by a stale lease. Only a pull request from the repository's own branch is a Task's or a revert's; a fork's pull request on the same branch name is never adopted. -A push or pull request refused twice in a row with no environment signal in between (a protected branch, a hook; git's transport errors such as a 5xx answer, a timeout or a hung-up remote count as the network's) stops the Task as "push 거절됨" with the reason; a person fixes the cause and retries. One with an environment signal is asked again every minute. +A push or pull request refused twice in a row with no environment signal in between (a protected branch, a hook; git's transport errors such as a 5xx answer or a timeout count as the network's, while a missing key, a gone repository or a hung-up remote reach a person) stops the Task as "push 거절됨" with the reason; a person fixes the cause and retries. One with an environment signal is asked again every minute. A failed push or pull request is tried again a minute later. `decide` records a decision. A worker whose agent rests for the no-report window (`no_report_minutes`, 2) after a turn that reported nothing stops the Task as "no report"; a worker that goes quiet for the stall window (`stall_minutes`, 30) stops it as "stalled". @@ -320,7 +320,7 @@ A gate sends an `auto` Task to `merge_waiting` and appears in the Task page and A review by an agent alone never merges. A person's `merge` runs merge-tree and the quick check again on the latest main, then the same merge at once; a conflict sends the worker to rebase and a failed quick check counts as a verification failure. -A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a rate-limit, server or network signal (a minute for any other signal) and every 30 seconds for an unnamed commit, with no merge-tree or quick check in between while every gate still holds; a commit still unnamed after 10 minutes waits for a person as a refused merge. +A refused merge is tried once and then waits for a person, never once per tick; only an environment signal, or a merge GitHub answered before naming its commit, is asked again, at the GitHub back-off for a rate-limit, server or network signal (a minute for any other signal) and every 30 seconds for an unnamed commit, which is only read and never merged again: a pull request that merged lands whatever gate appeared since, because nothing can undo it, and one that did not merge goes through every check again before another merge; a commit still unnamed after 10 minutes waits for a person as a refused merge. While a merge's commit is unnamed, a red run on a main head the Factory has not recorded is read as pending, not as an outside push. `request-changes --comment` returns the Task to `running`, clears its gates and sends the worker the comment. diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index 54f01cd368..770c2a77eb 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -77,14 +77,13 @@ impl Runtime { let Ok(ledger) = self.delivery_state() else { return lineage; }; - // Herdr reuses pane ids: only an agent still on the pane speaks for it. - let mut next = match ledger - .agents - .iter() - .rev() - .find(|agent| agent.pane == pane && !agent.ended) - { - Some(agent) => agent.parent.clone(), + // The newest record on the pane, ended or not: an agent can end its + // own record and keep running, so ending it never makes an operator. + let mut next = match ledger.agents.iter().rev().find(|agent| agent.pane == pane) { + Some(agent) => { + lineage.factory_spawned |= agent.actor.code_owned(); + agent.parent.clone() + } None => None, }; while let Some(id) = next { @@ -393,7 +392,7 @@ mod tests { } #[test] - fn an_ended_agent_speaks_for_no_pane() { + fn an_ended_agent_still_walks_up_but_lends_no_pane() { let mut runtime = crate::runtime::tests::runtime(); let ended = |mut record: AgentRecord| { record.ended = true; @@ -408,9 +407,10 @@ mod tests { ], ..Ledger::default() })); - // A person's shell on a pane whose id an ended agent had. - let reused = runtime.factory_lineage("w2:p1"); - assert!(reused.agents.is_empty() && reused.complete && !reused.factory_spawned); + // An agent that ended its own record still walks up to its worker. + let ended_child = runtime.factory_lineage("w2:p1"); + assert_eq!(ended_child.agents, vec!["agent-worker", "agent-factory"]); + assert!(ended_child.complete && ended_child.factory_spawned); // Ended ancestors stay in the walk but lend no pane to bind by. let live = runtime.factory_lineage("w3:p1"); assert_eq!( diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index a358f8fdec..ba1463002a 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -252,6 +252,16 @@ pub enum MainCheck { /// Branches, pull requests, merges and reverts. pub trait MergeTarget { fn main_head(&mut self, factory: &Factory) -> Result; + /// Reads, without merging, whether the Task's pull request merged: its + /// merge commit, `None` when it has not merged, or a failure asking + /// again when GitHub merged it without naming the commit yet. + fn merged_commit( + &mut self, + _factory: &Factory, + _task: &Task, + ) -> Result, Failure> { + Ok(None) + } /// Pushes the worktree's commits to the Task branch on every report, then /// finds the open pull request for it (a harness's or an earlier /// report's) or opens one (B36). diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 5e518aaf03..181b01ba78 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -580,12 +580,10 @@ impl Engine { } }); if let Some(from) = from { - if from == TaskState::Verifying { - // A merge or push asked again belongs to this verifying stay. - let key = (factory.to_owned(), id.to_owned()); - self.merge_retry.remove(&key); - self.publish_refusals.remove(&key); - } + // A merge or push asked again belongs to the stay it was asked in. + let key = (factory.to_owned(), id.to_owned()); + self.merge_retry.remove(&key); + self.publish_refusals.remove(&key); self.record( factory, Some(id), @@ -3099,14 +3097,28 @@ impl Engine { } let key = (factory_id.to_owned(), id.to_owned()); // A merge asked to wait is not read again before its time (B39). - // GitHub took a merge and has not named its commit: main merged in - // and the quick check are not run again, but every gate still holds. - let mut unnamed = false; if let Some((at, since)) = self.merge_retry.get(&key).copied() { if at > self.now() { return; } - unnamed = since.is_some(); + // GitHub answered a merge without naming its commit: only read + // whether it merged. A merged one landed whatever a gate says + // now; one that did not merge goes through every check again. + if since.is_some() { + match self.ports.merge.merged_commit(&factory, &task) { + Ok(Some(sha)) => { + self.landed(factory_id, id, &sha); + return; + } + Ok(None) => { + self.merge_retry.remove(&key); + } + Err(failure) => { + self.merge_failed(factory_id, id, &failure); + return; + } + } + } } if self.verifying.contains_key(&key) { return; @@ -3152,8 +3164,7 @@ impl Engine { return; } // Merge-tree and the quick check, in seconds (B38). - if !unnamed && (factory.config.verification.exists() || factory.source == SourceKind::Local) - { + if factory.config.verification.exists() || factory.source == SourceKind::Local { match self.ports.merge.premerge(&factory, &task) { Ok(PreMerge::Clean) => {} Ok(PreMerge::Conflict { files }) => { @@ -3184,8 +3195,7 @@ impl Engine { } } // Verify factories run the bundle once on the latest main merged in. - if !unnamed - && matches!(factory.config.verification, Verification::Commands { .. }) + if matches!(factory.config.verification, Verification::Commands { .. }) && !task.writes.contains("premerge_passed") { self.start_verification(factory_id, id, AttemptStage::PreMerge); @@ -3298,101 +3308,108 @@ impl Engine { .merge(&factory, &task, factory.config.merge_method) { Ok(sha) => { - let now = self.now(); - self.merge_retry - .remove(&(factory_id.to_owned(), id.to_owned())); - self.with_task(factory_id, id, |task| { - task.merge_sha = Some(sha.clone()); - task.writes.insert("merge".into()); - task.gates.clear(); - }); - if let Some(f) = self.factories.get_mut(factory_id) { - f.main.merges_since_green.push(LandedMerge { - task: id.to_owned(), - sha: sha.clone(), - at: now, - }); - } - self.save_factory(factory_id); - self.main_seen.insert(factory_id.to_owned(), sha.clone()); - self.record(factory_id, Some(id), "merge.done", json!({"sha": sha})); - self.set_state(factory_id, id, TaskState::Landed); - self.check_landed(factory_id, id); + self.landed(factory_id, id, &sha); Ok(sha) } Err(failure) => { - self.external_failure(factory_id, Some(id), &failure); - let now = self.now(); - let key = (factory_id.to_owned(), id.to_owned()); - // Asked to wait (a merge commit not named yet, or GitHub or - // the network down): tried again at its time, not per tick. - let backoff = self - .github_backoff - .get(factory_id) - .map(|(_, until)| *until) - .filter(|until| *until > now) - .filter(|_| { - matches!( - failure.signal, - Some( - EnvSignal::GithubRateLimit - | EnvSignal::GithubServer - | EnvSignal::Network - ) - ) - }); - let retry_at = match (failure.again_in_ms, failure.signal) { - (Some(wait), _) => Some(now + wait.max(1)), - (None, Some(_)) => Some(backoff.unwrap_or(now + PUBLISH_RETRY_MS)), - (None, None) => None, - }; - let since = self.merge_retry.get(&key).and_then(|(_, since)| *since); - let unnamed = failure.again_in_ms.is_some().then(|| since.unwrap_or(now)); - if unnamed.is_some_and(|since| now.saturating_sub(since) >= MERGE_UNNAMED_LIMIT_MS) - { - // GitHub never named the commit: a person looks (rule 15). - self.merge_retry.remove(&key); - self.with_task(factory_id, id, |task| { - if !task.gates.contains(&Gate::MergeRefused) { - task.gates.push(Gate::MergeRefused); - } - }); - self.record( - factory_id, - Some(id), - "merge.refused", - json!({"stage": failure.stage, "detail": "the merge commit was not named in 10 minutes"}), - ); - self.set_state(factory_id, id, TaskState::MergeWaiting); - return Err(failure); - } - match retry_at { - Some(at) => { - self.merge_retry.insert(key, (at, unnamed)); - } - None => { - self.merge_retry.remove(&key); - } - } - if failure.signal.is_none() && failure.again_in_ms.is_none() { - self.with_task(factory_id, id, |task| { - if !task.gates.contains(&Gate::MergeRefused) { - task.gates.push(Gate::MergeRefused); - } - }); - self.record( - factory_id, - Some(id), - "merge.refused", - json!({"stage": failure.stage, "detail": judgment::cut(&failure.detail, 300)}), - ); - self.set_state(factory_id, id, TaskState::MergeWaiting); - } + self.merge_failed(factory_id, id, &failure); Err(failure) } } } + /// Records a merge that landed on main (B39, B44). + fn landed(&mut self, factory_id: &str, id: &str, sha: &str) { + let sha = sha.to_owned(); + let now = self.now(); + self.merge_retry + .remove(&(factory_id.to_owned(), id.to_owned())); + self.with_task(factory_id, id, |task| { + task.merge_sha = Some(sha.clone()); + task.writes.insert("merge".into()); + task.gates.clear(); + }); + if let Some(f) = self.factories.get_mut(factory_id) { + f.main.merges_since_green.push(LandedMerge { + task: id.to_owned(), + sha: sha.clone(), + at: now, + }); + } + self.save_factory(factory_id); + self.main_seen.insert(factory_id.to_owned(), sha.clone()); + self.record(factory_id, Some(id), "merge.done", json!({"sha": sha})); + self.set_state(factory_id, id, TaskState::Landed); + self.check_landed(factory_id, id); + } + + /// A merge that did not land: asked again at its time when it was asked + /// to wait, or held for a person when it was refused. + fn merge_failed(&mut self, factory_id: &str, id: &str, failure: &Failure) { + self.external_failure(factory_id, Some(id), failure); + let now = self.now(); + let key = (factory_id.to_owned(), id.to_owned()); + // Asked to wait (a merge commit not named yet, or GitHub or + // the network down): tried again at its time, not per tick. + let backoff = self + .github_backoff + .get(factory_id) + .map(|(_, until)| *until) + .filter(|until| *until > now) + .filter(|_| { + matches!( + failure.signal, + Some(EnvSignal::GithubRateLimit | EnvSignal::GithubServer | EnvSignal::Network) + ) + }); + let retry_at = match (failure.again_in_ms, failure.signal) { + (Some(wait), _) => Some(now + wait.max(1)), + (None, Some(_)) => Some(backoff.unwrap_or(now + PUBLISH_RETRY_MS)), + (None, None) => None, + }; + let since = self.merge_retry.get(&key).and_then(|(_, since)| *since); + let unnamed = failure.again_in_ms.is_some().then(|| since.unwrap_or(now)); + if unnamed.is_some_and(|since| now.saturating_sub(since) >= MERGE_UNNAMED_LIMIT_MS) { + // GitHub never named the commit: a person looks (rule 15). + self.merge_retry.remove(&key); + self.with_task(factory_id, id, |task| { + if !task.gates.contains(&Gate::MergeRefused) { + task.gates.push(Gate::MergeRefused); + } + }); + self.record( + factory_id, + Some(id), + "merge.refused", + json!({"stage": failure.stage, "detail": "the merge commit was not named in 10 minutes"}), + ); + self.set_state(factory_id, id, TaskState::MergeWaiting); + return; + } + match retry_at { + Some(at) => { + self.merge_retry.insert(key, (at, unnamed)); + } + None => { + self.merge_retry.remove(&key); + } + } + if failure.signal.is_none() && failure.again_in_ms.is_none() { + self.with_task(factory_id, id, |task| { + if !task.gates.contains(&Gate::MergeRefused) { + task.gates.push(Gate::MergeRefused); + } + }); + self.record( + factory_id, + Some(id), + "merge.refused", + json!({"stage": failure.stage, "detail": judgment::cut(&failure.detail, 300)}), + ); + self.set_state(factory_id, id, TaskState::MergeWaiting); + } + } + fn manual_merge(&mut self, _role: &Role, factory_id: &str, id: &str) -> Reply { let factory = self .factories @@ -5241,7 +5258,12 @@ impl Engine { fn merge_unnamed(&self, factory_id: &str) -> bool { self.merge_retry .iter() - .filter(|((factory, _), (_, unnamed))| factory == factory_id && unnamed.is_some()) + .filter(|((factory, _), (_, since))| { + factory == factory_id + && since.is_some_and(|since| { + self.now().saturating_sub(since) < MERGE_UNNAMED_LIMIT_MS + }) + }) .any(|((factory, id), _)| { self.task(factory, id) .is_some_and(|t| t.state == TaskState::Verifying) diff --git a/hide-factory/src/exec.rs b/hide-factory/src/exec.rs index c014e05310..e1adaa1ef9 100644 --- a/hide-factory/src/exec.rs +++ b/hide-factory/src/exec.rs @@ -142,10 +142,7 @@ pub fn classify(stage: &str, output: &Output) -> Failure { "tls handshake", "i/o timeout", "operation timed out", - "remote end hung up", - "early eof", "unexpected disconnect", - "could not read from remote repository", ] .iter() .any(|needle| lower.contains(needle)) @@ -227,10 +224,17 @@ mod tests { 128, Some(EnvSignal::Network), ), + // These close lasting refusals too (a missing key, a gone + // repository, a pack too large): they reach a person. ( - "fatal: the remote end hung up unexpectedly", + "git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.", 128, - Some(EnvSignal::Network), + None, + ), + ( + "error: RPC failed; HTTP 413\nfatal: the remote end hung up unexpectedly", + 128, + None, ), ( " ! [remote rejected] HEAD -> factory/1-x (protected branch hook declined)", diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 2dcdb94a1c..bcd15c460a 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -818,6 +818,18 @@ impl TaskSource for SharedProjects { } impl MergeTarget for SharedProjects { + fn merged_commit(&mut self, factory: &Factory, task: &Task) -> Result, Failure> { + if factory.source != SourceKind::Github { + return Ok(None); + } + let Some(pr) = &task.pr else { return Ok(None) }; + let view = self.lock().pr_view(factory, pr.number)?; + if view["state"].as_str() != Some("MERGED") { + return Ok(None); + } + merge_commit("github.merged", &view).map(Some) + } + fn main_head(&mut self, factory: &Factory) -> Result { let mut this = self.lock(); let base = this.base(factory)?; @@ -1044,8 +1056,13 @@ impl MergeTarget for SharedProjects { let args = vec![flag.to_owned(), check.clone()]; let output = this.runner.run(program, &args, Some(&path))?; if !output.ok() { + // The project's own check speaks for the machine only when + // the disk or memory ran out; any other text is its result. let failure = classify("quick_check", &output); - if failure.signal.is_some() { + if matches!( + failure.signal, + Some(EnvSignal::DiskFull | EnvSignal::OutOfMemory) + ) { return Err(failure); } return Ok(PreMerge::QuickCheckFailed { check }); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 4e0f08fa0d..1f318c7335 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1572,11 +1572,16 @@ fn a_merge_asked_to_wait_is_read_again_at_its_time_and_main_is_not_misread_meanw h.advance(2_000); h.engine.tick(); } - assert_eq!(h.world().merge_attempts, 2, "once per 30 seconds over 40"); + assert_eq!(h.world().merge_attempts, 1, "never merged again"); + assert_eq!( + h.world().merged_reads, + 1, + "read once per 30 seconds over 40" + ); assert_eq!( h.world().premerge_calls, premerges, - "only the merge commit is read again" + "only whether it merged is read again" ); // The next outside read finds the new head. h.advance(2 * MINUTE_MS); @@ -1596,6 +1601,39 @@ fn a_merge_asked_to_wait_is_read_again_at_its_time_and_main_is_not_misread_meanw assert_eq!(h.task(&f, &t).gates, vec![Gate::MergeRefused]); } +#[test] +fn an_unnamed_merge_lands_once_named_and_one_that_did_not_merge_is_checked_again() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Named later", &[]); + h.world().merge_unnamed = 1; + h.done(&f, &t); + for _ in 0..3 { + h.engine.tick(); + } + h.advance(31_000); + h.engine.tick(); + assert!(h.state(&f, &t).merged(), "{:?}", h.state(&f, &t)); + assert_eq!(h.world().merge_attempts, 1); + assert!(h.task(&f, &t).merge_sha.is_some()); + + let u = h.ready("Dropped", &[]); + h.world().merge_unnamed = 1; + h.done(&f, &u); + for _ in 0..3 { + h.engine.tick(); + } + let premerges = h.world().premerge_calls; + h.world().merge_dropped = true; + h.advance(31_000); + h.engine.tick(); + assert!( + h.world().premerge_calls > premerges, + "every check runs again" + ); + assert_eq!(h.world().merge_attempts, 3, "merged again only after them"); +} + #[test] fn a_merge_failing_on_a_signal_after_an_old_back_off_is_not_retried_every_tick() { let mut h = Bench::new(true); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index c26a3474ce..5c8855cee9 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -38,6 +38,10 @@ pub struct World { pub merge_refusal: Option, /// This many merges answer before GitHub names the merge commit. pub merge_unnamed: u32, + /// Reads of whether a merge GitHub answered has landed. + pub merged_reads: u32, + /// The pull request turns out not to have merged (a queue dropped it). + pub merge_dropped: bool, pub merge_attempts: u32, /// Every push is refused with this failure. pub publish_refusal: Option, @@ -298,6 +302,30 @@ impl MergeTarget for Shared { world.head = sha.clone(); Ok(sha) } + fn merged_commit( + &mut self, + _factory: &Factory, + task: &Task, + ) -> Result, Failure> { + let mut world = self.world(); + world.merged_reads += 1; + if world.merge_dropped { + world.merge_dropped = false; + return Ok(None); + } + if world.merge_unnamed > 0 { + world.merge_unnamed -= 1; + return Err(Failure { + again_in_ms: Some(hide_factory::engine::MERGE_COMMIT_AGAIN_MS), + ..Failure::task("github.merged", "merge commit not named yet") + }); + } + world.next_sha += 1; + let sha = format!("sha{:04}-{}", world.next_sha, task.id); + world.writes.push(format!("merge {}", task.id)); + world.head = sha.clone(); + Ok(Some(sha)) + } fn main_check(&mut self, _factory: &Factory, sha: &str) -> Result { if let Some(next) = self .world() From 7d3f843cbf4d58365a70812a597aaa0bb7691a19 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:49:49 +0900 Subject: [PATCH 55/72] Remove a finished Task's worktree only when clean and tell a person about leftovers; discard only an expired or abandoned one --- docs/factory.md | 1 + herdr-core/src/factory.rs | 16 ++++++----- hide-factory/src/adapters.rs | 19 ++++++++++--- hide-factory/src/engine.rs | 41 +++++++++++++++++++++------ hide-factory/tests/engine.rs | 46 +++++++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 20 ++++++++++---- 6 files changed, 119 insertions(+), 24 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 7bece3b9a8..62c27fe69c 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -66,6 +66,7 @@ It removes a worker's worktree and pane when the Task is done and main verificat An outside pull request that takes a Task stops its worker and starts the keep period at that moment; the worktree waits the period out even when that pull request merges and the Task is done, because the worker's own work was never merged. The removal runs from the repository's main checkout through the host's guarded worktree removal. A finished Task keeps its branch; a cancelled or outside Task loses its local branch with its worktree, and the Factory never deletes a remote branch. +A finished Task's worktree goes only when it is clean: uncommitted or untracked leftovers keep it, and a notice names the folder for a person to look at. Only a cancelled or outside Task past its keep period, or a start abandoned on its way, has what is left in its worktree discarded. A finished Task folds out of the board's Done column after 3 days and out of every list after 90 days; its page still opens. Each Factory keeps its newest 20,000 events and drops older ones. Judgment inputs and answers and letter bodies are kept in `records` and never deleted automatically; `Engine::records` reads a Task's, and the core's diagnostic log records each judgment's feature, ids, outcome and duration. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index a13c9e1f0a..d38635dfda 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -15,8 +15,8 @@ use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use hide_factory::adapters::{ - Clock, EnvSignal, Environment, Failure, Judge, MemoryPressure, Notifier, WorkerRuntime, - WorkerSpawn, WorkerStatus, + Clock, EnvSignal, Environment, Failure, Judge, MemoryPressure, Notifier, Removal, + WorkerRuntime, WorkerSpawn, WorkerStatus, }; use hide_factory::exec::SystemRunner; use hide_factory::judgment::{Judgment, JudgmentAnswer, JudgmentOutcome}; @@ -769,7 +769,7 @@ impl CoreWorkers { fn release_start(&mut self, task: &str, fresh: bool, worker: &WorkerRef) { let mut result = self.stop(worker); if fresh && result.is_ok() { - result = self.remove_worktree(worker, true); + result = self.remove_worktree(worker, Removal::Discarded); } if let Err(failure) = result { crate::diagnostic!( @@ -1059,7 +1059,8 @@ impl WorkerRuntime for CoreWorkers { .map_err(|reason| Failure::task("worker.stop", reason)) } - fn remove_worktree(&mut self, worker: &WorkerRef, delete_branch: bool) -> Result<(), Failure> { + fn remove_worktree(&mut self, worker: &WorkerRef, removal: Removal) -> Result<(), Failure> { + let discard = removal == Removal::Discarded; let checkout = Path::new(&worker.worktree); let mut runner = SystemRunner { stop: Arc::new(AtomicBool::new(false)), @@ -1088,10 +1089,11 @@ impl WorkerRuntime for CoreWorkers { let Some(root) = root else { return Ok(()); }; - // The Factory made this worktree, so what is left in it goes too. - hide_host::worktrees::remove_worktree(&root, checkout, true) + // Leftovers in a finished Task's worktree are the operator's to look + // at: only a discarded one is forced (D-58). + hide_host::worktrees::remove_worktree(&root, checkout, discard) .map_err(|reason| Failure::task("worktree.remove", reason))?; - if delete_branch { + if discard { hide_factory::exec::checked( &mut runner, "branch.delete", diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index ba1463002a..ef67130937 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -337,6 +337,18 @@ pub enum WorkerStatus { Gone, } +/// How much of a Task's worktree a removal may take. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Removal { + /// A finished Task: a clean worktree goes and its branch stays with the + /// merge; uncommitted leftovers keep the worktree and fail the removal, + /// so a person sees them (D-58). + Finished, + /// A Task cancelled or taken over past its keep period, or a start + /// abandoned on its way: what is left goes, with the local branch. + Discarded, +} + /// Starts, messages, sleeps and wakes workers (D-14). pub trait WorkerRuntime { fn spawn(&mut self, request: &WorkerSpawn) -> Result; @@ -360,13 +372,12 @@ pub trait WorkerRuntime { fn wake(&mut self, worker: &crate::model::WorkerRef, body: &str) -> Result<(), Failure>; fn status(&mut self, worker: &crate::model::WorkerRef) -> WorkerStatus; fn stop(&mut self, worker: &crate::model::WorkerRef) -> Result<(), Failure>; - /// Removes the Task's worktree (B43, B62, B71) and, with - /// `delete_branch`, its local branch (D-58); the remote branch stays. - /// Removing what is already gone succeeds. + /// Removes the Task's worktree (B43, B62, B71); the remote branch stays + /// (D-58). Removing what is already gone succeeds. fn remove_worktree( &mut self, worker: &crate::model::WorkerRef, - delete_branch: bool, + removal: Removal, ) -> Result<(), Failure>; fn usage_limited(&mut self, runtime: Runtime) -> Option; } diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 181b01ba78..fc8203511e 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -12,8 +12,8 @@ use serde_json::{Value, json}; use crate::adapters::{ Clock, EnvSignal, Environment, Failure, Judge, MainCheck, MemoryPressure, MergeTarget, - Notifier, OutsideEvent, PreMerge, RevertRef, TaskSource, Verifier, VerifyPoll, VerifyRun, - WorkerRuntime, WorkerSpawn, WorkerStatus, + Notifier, OutsideEvent, PreMerge, Removal, RevertRef, TaskSource, Verifier, VerifyPoll, + VerifyRun, WorkerRuntime, WorkerSpawn, WorkerStatus, }; use crate::command::{CardInput, Command, Refusal, VerificationChoice}; use crate::dag; @@ -3535,7 +3535,11 @@ impl Engine { return; }; self.stop_worker(factory_id, id, &worker); - match self.ports.workers.remove_worktree(&worker, false) { + match self + .ports + .workers + .remove_worktree(&worker, Removal::Finished) + { Ok(()) => { self.with_task(factory_id, id, |t| t.purged = true); } @@ -3550,6 +3554,23 @@ impl Engine { "cleanup.failed", json!({"stage": failure.stage, "detail": failure.detail}), ); + // A worktree that refuses to go (leftovers in a finished Task's) is + // a person's to look at; the environment's failures are retried. + if failure.signal.is_none() + && let Some(worktree) = self + .task(factory_id, id) + .and_then(|t| t.worker.as_ref()) + .map(|w| w.worktree.clone()) + { + self.once_notice( + factory_id, + id, + &format!( + "worktree를 지우지 못했습니다: {worktree} ({}). 남은 변경을 확인한 뒤 직접 지우세요.", + judgment::cut(&failure.detail, 200) + ), + ); + } } // ------------------------------------------------------------- main break @@ -5527,10 +5548,11 @@ impl Engine { }) .collect(); for (factory, id, worker) in targets { - let finished = self - .task(&factory, &id) - .is_some_and(|t| t.state == TaskState::Done); - match self.ports.workers.remove_worktree(&worker, !finished) { + let removal = match self.task(&factory, &id).is_some_and(kept_for_revive) { + true => Removal::Discarded, + false => Removal::Finished, + }; + match self.ports.workers.remove_worktree(&worker, removal) { Ok(()) => { self.with_task(&factory, &id, |t| t.purged = true); self.record(&factory, Some(&id), "cleanup.worktree", json!({})); @@ -5922,7 +5944,10 @@ impl Engine { .collect(); for (factory, id) in expired { if let Some(worker) = self.task(&factory, &id).and_then(|t| t.worker.clone()) - && let Err(failure) = self.ports.workers.remove_worktree(&worker, true) + && let Err(failure) = self + .ports + .workers + .remove_worktree(&worker, Removal::Discarded) { self.cleanup_failed(&factory, &id, &failure); continue; diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 1f318c7335..63a89640f1 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1946,6 +1946,52 @@ fn an_outside_pull_request_takes_a_running_task_and_its_merge_finishes_it() { assert_eq!(h.world().removed, vec![t.clone()]); } +#[test] +fn a_finished_task_s_leftovers_keep_its_worktree_for_a_person() { + let mut h = Bench::new(false); + let f = h.factory(true); + let dirty = h.ready("Leftovers", &[]); + let clean = h.ready("Clean", &[]); + h.world().dirty_worktrees.insert(dirty.clone()); + h.done(&f, &dirty); + tick_until(&mut h, &f, &dirty, TaskState::Done); + h.done(&f, &clean); + tick_until(&mut h, &f, &clean, TaskState::Done); + let world = h.world(); + assert!(!world.removed.contains(&dirty), "never forced"); + assert!(world.removed.contains(&clean)); + assert!( + world.branches_deleted.is_empty(), + "branches stay with merges" + ); + drop(world); + assert!(!h.task(&f, &dirty).purged); + let notice = h + .task(&f, &dirty) + .open_questions() + .any(|q| q.text.contains("worktree를 지우지 못했습니다")); + assert!(notice, "a person is told"); + assert!( + h.engine + .events(&f, Some(&dirty), 50) + .iter() + .any(|e| e.kind == "cleanup.failed") + ); +} + +#[test] +fn an_expired_cancel_discards_its_worktree_and_branch() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Dropped", &[]); + h.world().dirty_worktrees.insert(t.clone()); + h.op(Command::Cancel { task: t.clone() }); + h.advance(8 * DAY_MS); + h.engine.tick(); + assert!(h.task(&f, &t).purged); + assert_eq!(h.world().branches_deleted, vec![t.clone()]); +} + #[test] fn a_task_taken_before_its_start_expires_after_the_keep_period() { let mut h = Bench::new(true); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 5c8855cee9..6676d3453f 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -4,7 +4,7 @@ #![allow(dead_code)] -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::sync::{Arc, Mutex, MutexGuard}; use hide_factory::adapters::*; @@ -65,6 +65,8 @@ pub struct World { pub wakes: Vec<(String, String)>, pub stops: Vec, pub removed: Vec, + /// Worktrees holding uncommitted leftovers, by Task id. + pub dirty_worktrees: BTreeSet, pub branches_deleted: Vec, /// Runtimes the probe finds installed; none when empty. pub runtimes: Vec, @@ -440,10 +442,18 @@ impl WorkerRuntime for Shared { self.world().stops.push(task_of(worker)); Ok(()) } - fn remove_worktree(&mut self, worker: &WorkerRef, delete_branch: bool) -> Result<(), Failure> { - self.world().removed.push(task_of(worker)); - if delete_branch { - self.world().branches_deleted.push(task_of(worker)); + fn remove_worktree(&mut self, worker: &WorkerRef, removal: Removal) -> Result<(), Failure> { + let mut world = self.world(); + let task = task_of(worker); + if removal == Removal::Finished && world.dirty_worktrees.contains(&task) { + return Err(Failure::task( + "worktree.remove", + "the worktree contains modified or untracked files", + )); + } + world.removed.push(task.clone()); + if removal == Removal::Discarded { + world.branches_deleted.push(task); } Ok(()) } From 939b97c9e8cf1a70893b1ffd9733a723e6fa6fd5 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:55:11 +0900 Subject: [PATCH 56/72] Name the GitHub account, repository and access at init and refuse writes without a recorded approval The init preview names the gh login, the repository and every GitHub read and write the Factory makes; --confirm records that approval in the Factory and its history, and the gh adapter refuses every write to a Factory that carries none. --- docs/factory.md | 5 +- hide-factory/src/adapters.rs | 4 +- hide-factory/src/command.rs | 15 ++++- hide-factory/src/engine.rs | 60 +++++++++++++++++++- hide-factory/src/model.rs | 14 +++++ hide-factory/src/project.rs | 47 +++++++++------- hide-factory/tests/engine.rs | 93 ++++++++++++++++++++++++++++++- hide-factory/tests/github.rs | 39 ++++++++++++- hide-factory/tests/local_git.rs | 5 ++ hide-factory/tests/support/mod.rs | 11 ++-- 10 files changed, 255 insertions(+), 38 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 62c27fe69c..5396dd967a 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -16,6 +16,7 @@ A Factory is one project's work queue. A project has at most one Factory, named by the project's canonical primary checkout path; its id is `f-` and the first ten hex digits of that path's SHA-256. A Factory whose project has a `github.com` origin takes its Tasks from GitHub issues and merges pull requests (a GitHub Factory). Any other Factory keeps its issues in the core's local issue store as `L-` and merges into the local default branch (a local Factory). +A GitHub Factory acts as the login `gh` is signed in as, and only after a person approved that account, the repository and the list of reads and writes `init` shows; the Factory keeps that approval as `github_approval`, and a Factory without one refuses every GitHub write (`github.approval`) before calling `gh` or pushing. Closing a Factory keeps its records, and creating a Factory for the same project again brings them back. | Owner | What it owns | @@ -508,7 +509,7 @@ Add --json to print the answer as JSON. | Command | Does | | --- | --- | -| `init` | Without `--confirm`, shows the source, the verification candidates the code detected (the branch's required checks and verify commands read from `Cargo.toml`, `package.json`, `Makefile` or `pyproject.toml`), the merge mode and the GitHub writes it would make, and writes nothing. With `--confirm` and a verification choice, creates the Factory and, on GitHub, creates the `factory` label. A closed Factory is reopened with `--confirm`. A project that already has an open Factory answers with it. | +| `init` | Without `--confirm`, shows the source, the verification candidates the code detected (the branch's required checks and verify commands read from `Cargo.toml`, `package.json`, `Makefile` or `pyproject.toml`), the merge mode and, on GitHub, the login `gh api user` names, the repository, and everything the Factory reads and writes there, and writes nothing. With `--confirm` and a verification choice, creates the Factory, records that approval (account, repository, time) in its history as `github.approved`, and, on GitHub, creates the `factory` label. A closed Factory is reopened with `--confirm`. A project that already has an open Factory answers with it. | | `add` | Creates a Task or updates the named one. A positional issue reads its title and body for missing fields. `--prd` copies the file into the store. | | `status`, `show`, `inbox` | Read the board, one Task page, and the inbox. | | `answer` | Answers a question and records who relayed it. | @@ -521,7 +522,7 @@ A project path is made absolute by the CLI. `--json` prints the engine's answer as one JSON object, and without it the answer is printed for a person. Every answer carries `ok`. A refusal prints `refused: `, the current state and allowed actions or the invalid fields when it has them, and `next: `, and exits non-zero; its JSON is `{"ok": false, "reason", "next_action", "detail"}`. -`add` answers `{result, task, questions}`, `init` a preview, `created` or `existing` object, `show` `{task: }`, `inbox` `{count, items}`, `status` a `FactorySummary`, and `config` `{config, machine}`. +`add` answers `{result, task, questions}`, `init` a preview (its `github` is `{account, repo, reads, writes}` or `null` for a local project), `created` or `existing` object, `show` `{task: }`, `inbox` `{count, items}`, `status` a `FactorySummary`, and `config` `{config, machine}`. Other actions answer `{message, task}` with the Task's id, display id and new state. Common refusal reasons are `role_not_allowed`, `task_not_found`, `task_ambiguous`, `factory_not_found`, `factory_ambiguous`, `factory_closed`, `card_invalid`, `action_not_allowed_in_state`, `config_invalid`, `auto_needs_verification`, `github_login_required`, `github_permission_missing`, `main_dirty` and `revive_expired`. diff --git a/hide-factory/src/adapters.rs b/hide-factory/src/adapters.rs index ef67130937..c8c75e9838 100644 --- a/hide-factory/src/adapters.rs +++ b/hide-factory/src/adapters.rs @@ -116,6 +116,8 @@ impl EnvSignal { pub struct ProjectProbe { pub github: bool, pub repo: Option, + /// The `gh` login a GitHub Factory acts as. + pub account: Option, /// Required checks of the default branch's protection. pub required_checks: Vec, /// Verify command candidates read from repository files. @@ -167,8 +169,6 @@ pub enum OutsideEvent { /// Issues, labels and outside work (GitHub or local). pub trait TaskSource { fn probe(&mut self, project: &str) -> Result; - /// Writes needed when the Factory is created (the `factory` label). - fn planned_writes(&self, probe: &ProjectProbe) -> Vec; fn prepare(&mut self, factory: &Factory) -> Result<(), Failure>; /// Creates the Task's issue with the card summary and the label; converges /// on an existing issue carrying the same Task marker (B73). diff --git a/hide-factory/src/command.rs b/hide-factory/src/command.rs index ccab169f17..a32d00b965 100644 --- a/hide-factory/src/command.rs +++ b/hide-factory/src/command.rs @@ -364,8 +364,19 @@ fn render_init(answer: &Value) -> String { if let Some(note) = answer["auto_unavailable"].as_str() { text.push_str(&format!("auto: unavailable ({note})\n")); } - for write in answer["writes"].as_array().into_iter().flatten() { - text.push_str(&format!("will write: {}\n", write.as_str().unwrap_or(""))); + let github = &answer["github"]; + if github.is_object() { + text.push_str(&format!( + "GitHub: acts as {} on {}\n", + github["account"].as_str().unwrap_or("?"), + github["repo"].as_str().unwrap_or("?") + )); + for key in ["reads", "writes"] { + text.push_str(&format!(" {key}:\n")); + for item in github[key].as_array().into_iter().flatten() { + text.push_str(&format!(" - {}\n", item.as_str().unwrap_or(""))); + } + } } text.push_str("Nothing was written. Choose a verification and add --confirm."); text diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index fc8203511e..1b9ebbfb3f 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -72,6 +72,23 @@ pub const REPORT_LIMIT: usize = 500; const MAIN_CHECK_EVERY_MS: u64 = 30_000; /// When a merge that GitHub answered without its commit is asked again. pub const MERGE_COMMIT_AGAIN_MS: u64 = 30_000; +/// What a GitHub Factory reads, as `init` names it before a person confirms. +pub const GITHUB_READS: [&str; 5] = [ + "issues labelled factory", + "pull requests", + "check runs and commit statuses", + "workflow runs", + "the default branch's required checks", +]; +/// What a GitHub Factory writes, as `init` names it before a person confirms. +pub const GITHUB_WRITES: [&str; 6] = [ + "the factory label", + "issue create and edit", + "branch push to factory/*", + "pull request open, merge and close", + "revert pull request", + "rerun of a failed workflow run", +]; /// How long a merge GitHub answered without naming its commit is read again /// before a person looks. pub const MERGE_UNNAMED_LIMIT_MS: u64 = 10 * 60_000; @@ -1127,7 +1144,6 @@ impl Engine { for command in &probe.verify_candidates { candidates.push(json!({"kind": "verify", "value": command})); } - let writes = self.ports.source.planned_writes(&probe); let verification = match verification { Some(VerificationChoice::Ci { checks }) => { if !probe.github { @@ -1182,6 +1198,27 @@ impl Engine { ) .with(json!({"candidates": candidates}))); } + // A GitHub Factory names the login it acts as, the repository and + // everything it reads and writes there before a person confirms + // (D-62); the create screen shows this same list. + let github = match (probe.github, &probe.repo) { + (false, _) => None, + (true, Some(repo)) => { + let Some(account) = probe.account.clone() else { + return Err(refuse( + "github_login_required", + "Run gh auth login, then retry", + )); + }; + Some((account, repo.clone())) + } + (true, None) => { + return Err(refuse( + "init_failed", + "GitHub did not name the repository; check the origin remote and retry", + )); + } + }; if !confirm { return Ok(json!({ "preview": true, @@ -1191,7 +1228,12 @@ impl Engine { "merge_mode": "auto", "auto_unavailable": auto_unavailable, "default_runtime": probe.runtimes.first().copied().unwrap_or(Runtime::Claude), - "writes": writes, + "github": github.as_ref().map(|(account, repo)| json!({ + "account": account, + "repo": repo, + "reads": GITHUB_READS, + "writes": GITHUB_WRITES, + })), })); } if !matches!( @@ -1239,10 +1281,16 @@ impl Engine { watch_day: 0, watch_sent_today: 0, watch_last_at: None, + github_approval: github.map(|(account, repo)| GithubApproval { + account, + repo, + at: now, + }), }; if let Err(failure) = self.ports.source.prepare(&factory) { return Err(self.github_refusal(&failure, "init")); } + let approval = factory.github_approval.clone(); self.factories.insert(id.clone(), factory); self.tasks.entry(id.clone()).or_default(); self.save_factory(&id); @@ -1252,6 +1300,14 @@ impl Engine { "factory.created", json!({"source": source_name(source)}), ); + if let Some(approval) = approval { + self.record( + &id, + None, + "github.approved", + json!({"account": approval.account, "repo": approval.repo, "at": approval.at}), + ); + } Ok(json!({"created": true, "factory": {"id": id, "project": project}})) } diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index 409f49ab0e..a1efefb5ba 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -49,6 +49,20 @@ pub struct Factory { pub watch_day: u64, pub watch_sent_today: u32, pub watch_last_at: Option, + /// The person's approval of this Factory's GitHub reads and writes; no + /// GitHub write happens without it (D-62). + #[serde(default)] + pub github_approval: Option, +} + +/// Who approved a GitHub Factory's access, for which repository, and when, +/// recorded at `init --confirm` (D-62). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GithubApproval { + /// The `gh` login the Factory acts as. + pub account: String, + pub repo: String, + pub at: UnixMs, } fn default_branch() -> String { diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index bcd15c460a..6a4922ed28 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -115,6 +115,18 @@ fn same_repo(prs: &[Value]) -> Option<&Value> { .find(|pr| pr["isCrossRepository"].as_bool() == Some(false)) } +/// The repository of a GitHub write: refused until a person approved the +/// Factory's GitHub access at `init --confirm` (D-62). +fn write_repo(factory: &Factory) -> Result { + if factory.github_approval.is_none() { + return Err(Failure::task( + "github.approval", + "no recorded GitHub approval: confirm the Factory with hide factory init --confirm", + )); + } + repo(factory) +} + fn repo(factory: &Factory) -> Result { factory .repo @@ -399,6 +411,10 @@ impl TaskSource for SharedProjects { let view = this.gh_json("probe", &["repo", "view", remote.trim(), "--json", "nameWithOwner,defaultBranchRef,mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed"])?; probe.github = true; probe.repo = view["nameWithOwner"].as_str().map(str::to_owned); + // The login every GitHub read and write runs as (D-62). + probe.account = this.gh_json("probe", &["api", "user"])?["login"] + .as_str() + .map(str::to_owned); if let Some(branch) = view["defaultBranchRef"]["name"].as_str() { probe.default_branch = branch.to_owned(); } @@ -434,22 +450,11 @@ impl TaskSource for SharedProjects { Ok(probe) } - fn planned_writes(&self, probe: &ProjectProbe) -> Vec { - if probe.github { - vec![format!( - "GitHub label `{LABEL}` on {}", - probe.repo.clone().unwrap_or_default() - )] - } else { - Vec::new() - } - } - fn prepare(&mut self, factory: &Factory) -> Result<(), Failure> { if factory.source != SourceKind::Github { return Ok(()); } - let repo = repo(factory)?; + let repo = write_repo(factory)?; self.lock().gh( "github.label", &[ @@ -484,7 +489,7 @@ impl TaskSource for SharedProjects { Ok(IssueRef::Local { number }) } SourceKind::Github => { - let repo = repo(factory)?; + let repo = write_repo(factory)?; let search = format!("\"{marker}\" in:body"); let found = this.gh_json( "github.issue_find", @@ -536,7 +541,7 @@ impl TaskSource for SharedProjects { let IssueRef::Github { number } = issue else { return Ok(()); }; - let repo = repo(factory)?; + let repo = write_repo(factory)?; let number = number.to_string(); self.lock().gh( "github.label_issue", @@ -849,7 +854,7 @@ impl MergeTarget for SharedProjects { if factory.source != SourceKind::Github { return Ok(None); } - let repo = repo(factory)?; + let repo = write_repo(factory)?; let branch = task .worker .as_ref() @@ -952,7 +957,7 @@ impl MergeTarget for SharedProjects { } fn close_pr(&mut self, factory: &Factory, pr: &PullRequest) -> Result<(), Failure> { - let repo = repo(factory)?; + let repo = write_repo(factory)?; let number = pr.number.to_string(); let mut this = self.lock(); let state = this.pr_view(factory, pr.number)?; @@ -967,7 +972,7 @@ impl MergeTarget for SharedProjects { } fn reopen_pr(&mut self, factory: &Factory, pr: &PullRequest) -> Result<(), Failure> { - let repo = repo(factory)?; + let repo = write_repo(factory)?; let number = pr.number.to_string(); let mut this = self.lock(); let state = this.pr_view(factory, pr.number)?; @@ -1155,7 +1160,7 @@ impl MergeTarget for SharedProjects { .to_owned()) } SourceKind::Github => { - let repo = repo(factory)?; + let repo = write_repo(factory)?; let pr = task .pr .clone() @@ -1216,7 +1221,7 @@ impl MergeTarget for SharedProjects { let mut this = self.lock(); match &factory.config.verification { Verification::Ci { .. } => { - let repo = repo(factory)?; + let repo = write_repo(factory)?; let path = format!("repos/{repo}/actions/runs?head_sha={sha}&per_page=50"); let runs = this.gh_json("github.runs", &["api", &path])?; for run in runs["workflow_runs"].as_array().into_iter().flatten() { @@ -1272,7 +1277,7 @@ impl MergeTarget for SharedProjects { commit: Some(commit), }); } - let repo = repo(factory)?; + let repo = write_repo(factory)?; let branch = format!("factory/revert-{}", task.id.to_ascii_lowercase()); let refspec = format!("HEAD:refs/heads/{branch}"); this.git( @@ -1359,7 +1364,7 @@ impl MergeTarget for SharedProjects { let commit = revert.commit.clone().unwrap_or_default(); match (factory.source, revert.pr) { (SourceKind::Github, Some(number)) => { - let repo = repo(factory)?; + let repo = write_repo(factory)?; let view = this.pr_view(factory, number)?; if view["state"].as_str() != Some("MERGED") { let number = number.to_string(); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 63a89640f1..a79d624575 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -60,7 +60,44 @@ fn init_previews_without_writing_and_creates_once_confirmed() { assert_eq!(preview["preview"], true, "{preview}"); assert!(h.world().writes.is_empty(), "a preview writes nothing"); assert!(h.engine.factories().next().is_none()); - assert_eq!(preview["writes"], json!(["label factory"])); + // The preview names who acts, where, and everything read and written + // there, before anything is written (B1). + assert_eq!(preview["github"]["account"], "octo", "{preview}"); + assert_eq!(preview["github"]["repo"], "owner/fixture", "{preview}"); + let named = |list: &serde_json::Value| -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|item| item.as_str().unwrap().to_owned()) + .collect() + }; + let reads = named(&preview["github"]["reads"]); + for read in [ + "issues", + "pull requests", + "check runs", + "workflow runs", + "required checks", + ] { + assert!( + reads.iter().any(|r| r.contains(read)), + "{read} in {reads:?}" + ); + } + let writes = named(&preview["github"]["writes"]); + for write in [ + "factory label", + "issue create", + "branch push", + "merge", + "revert", + "rerun", + ] { + assert!( + writes.iter().any(|w| w.contains(write)), + "{write} in {writes:?}" + ); + } // Auto merge needs a verification (B2). let refused = h.op(Command::Init { @@ -83,6 +120,24 @@ fn init_previews_without_writing_and_creates_once_confirmed() { assert_eq!(h.writes("label.create"), vec!["label.create factory"]); let factory = h.engine.factories().next().unwrap().clone(); assert_eq!(factory.config.default_runtime, Runtime::Claude); + // Confirming records the approval: the account, the repository, when. + let approval = factory + .github_approval + .clone() + .expect("a recorded approval"); + assert_eq!( + (approval.account.as_str(), approval.repo.as_str()), + ("octo", "owner/fixture") + ); + assert_eq!(approval.at, h.world().now); + let approved: Vec<_> = h + .engine + .events(&factory.id, None, 50) + .into_iter() + .filter(|e| e.kind == "github.approved") + .collect(); + assert_eq!(approved.len(), 1); + assert_eq!(approved[0].detail["account"], "octo"); // The same project again shows the existing Factory (B5). let again = h.op(Command::Init { @@ -95,6 +150,42 @@ fn init_previews_without_writing_and_creates_once_confirmed() { assert_eq!(h.writes("label.create").len(), 1); } +#[test] +fn a_local_project_names_no_github_access_and_records_no_approval() { + let mut h = Bench::new(false); + let preview = h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: None, + confirm: false, + }); + assert_eq!(preview["github"], serde_json::Value::Null, "{preview}"); + h.op(Command::Init { + project: PROJECT.into(), + verification: Some(VerificationChoice::Commands { + commands: vec!["true".into()], + }), + merge_mode: None, + confirm: true, + }); + let factory = h.engine.factories().next().unwrap().clone(); + assert!(factory.github_approval.is_none()); +} + +#[test] +fn a_github_project_without_a_logged_in_account_is_not_created() { + let mut h = Bench::new(true); + h.world().account = None; + let refused = h.op(Command::Init { + project: PROJECT.into(), + verification: None, + merge_mode: None, + confirm: false, + }); + assert_eq!(refused["reason"], "github_login_required", "{refused}"); + assert!(h.engine.factories().next().is_none()); +} + #[test] fn a_machine_with_only_codex_defaults_new_workers_to_codex() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/github.rs b/hide-factory/tests/github.rs index d25782f059..9de4ed1376 100644 --- a/hide-factory/tests/github.rs +++ b/hide-factory/tests/github.rs @@ -182,7 +182,8 @@ fn factory() -> Factory { "id": "f-1", "project": "/work/r", "project_name": "r", "source": "github", "repo": "o/r", "default_branch": "main", "config": Config { verification: Verification::Ci { checks: vec!["test".into()] }, ..Config::default() }, "closed": false, "created_at": 0, "next_task": 2, "next_local_issue": 1, "main": MainHealth::default(), - "outside_read_at": null, "outside_read_failures": 0, "watch_day": 0, "watch_sent_today": 0, "watch_last_at": null + "outside_read_at": null, "outside_read_failures": 0, "watch_day": 0, "watch_sent_today": 0, "watch_last_at": null, + "github_approval": {"account": "octo", "repo": "o/r", "at": 0} })) .unwrap() } @@ -334,6 +335,42 @@ fn every_report_pushes_and_a_merged_pull_request_is_not_reused() { assert!(reland.by_factory); } +#[test] +fn a_factory_without_a_recorded_approval_writes_nothing_to_github() { + let gh = FakeGh::default(); + let mut p = projects(&gh); + let factory = Factory { + github_approval: None, + ..factory() + }; + let mut t = task("T-1", Some(1)); + t.pr = Some(PullRequest { + number: 2, + url: String::new(), + head: "factory/1-add-it".into(), + by_factory: true, + open: true, + }); + let pr = t.pr.clone().unwrap(); + let refusals = [ + p.prepare(&factory).err(), + p.create_issue(&factory, &task("T-2", None), "body").err(), + p.label_issue(&factory, &IssueRef::Github { number: 1 }) + .err(), + p.open_pr(&factory, &task("T-3", Some(3)), "body").err(), + p.close_pr(&factory, &pr).err(), + p.reopen_pr(&factory, &pr).err(), + p.merge(&factory, &t, MergeMethod::Squash).err(), + p.rerun_main(&factory, "headsha").err(), + ]; + for refusal in refusals { + assert_eq!(refusal.expect("refused").stage, "github.approval"); + } + let hub = gh.0.lock().unwrap(); + assert!(hub.writes.is_empty(), "{:?}", hub.writes); + assert!(hub.pushes.is_empty(), "{:?}", hub.pushes); +} + #[test] fn a_merge_without_a_verified_commit_is_refused() { let gh = FakeGh::default(); diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index 053de34d12..ce785096bf 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -376,6 +376,11 @@ fn a_report_after_the_remote_deleted_the_task_branch_still_pushes() { let mut factory = factory(&fx.project, &[]); factory.source = SourceKind::Github; factory.repo = Some("o/r".into()); + factory.github_approval = Some(GithubApproval { + account: "octo".into(), + repo: "o/r".into(), + at: 0, + }); let t = task(&fx, "T-1", "b.txt", "two\n"); let branch = t.worker.as_ref().unwrap().branch.clone(); let worktree = PathBuf::from(&t.worker.as_ref().unwrap().worktree); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 6676d3453f..7d7243b816 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -22,6 +22,8 @@ pub const PROJECT: &str = "/work/fixture"; pub struct World { pub now: UnixMs, pub github: bool, + /// The GitHub login `gh api user` answers; `None` when logged out. + pub account: Option, /// Every external write, in order: `verb target`. pub writes: Vec, pub next_issue: u64, @@ -119,6 +121,7 @@ impl TaskSource for Shared { Ok(ProjectProbe { github, repo: github.then(|| "owner/fixture".into()), + account: github.then(|| self.world().account.clone()).flatten(), required_checks: if github { vec!["test".into()] } else { @@ -130,13 +133,6 @@ impl TaskSource for Shared { runtimes: self.world().runtimes.clone(), }) } - fn planned_writes(&self, probe: &ProjectProbe) -> Vec { - if probe.github { - vec!["label factory".into()] - } else { - Vec::new() - } - } fn prepare(&mut self, factory: &Factory) -> Result<(), Failure> { if factory.source == SourceKind::Github { self.world().writes.push("label.create factory".into()); @@ -579,6 +575,7 @@ impl Bench { let dir = tempfile::tempdir().expect("state folder"); let world = World { now: 1_000 * DAY_MS, + account: Some("octo".into()), github, head: "sha0000-base".into(), diff_lines: 40, From 02499ca892cdf0c87102408965d91b86a7d22300 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 07:55:42 +0900 Subject: [PATCH 57/72] Say that only hide agent end ends an agent record in the lineage rule --- docs/factory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/factory.md b/docs/factory.md index 5396dd967a..b500d32acd 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -148,7 +148,7 @@ A `cancelled` or `done` Task's worker stays a worker while its worktree and pane Once a Task's worktree is removed it binds no pane or folder, because Herdr can give a closed pane id to the operator's next pane. An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up) and binds an ancestor by its agent id or by the pane it was registered on, and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. A lineage the host cannot read to its root (the ledger unreadable, a missing record, a loop, more than 16 agents) may hide a worker above, so that caller can only read; anything else is refused with `lineage_unknown`. -The walk starts from the newest record on the caller's pane even when that record has ended, because an agent can end its own record and keep running; an ended ancestor lends no pane to bind by, because Herdr reuses pane ids. A caller below a Factory's own agent that no Task holds as its worker (a start abandoned on its way, or a shell on a reused pane id) can only read; anything else is refused with `factory_agent_unbound`. +The walk starts from the newest record on the caller's pane even when that record has ended, because an agent can end its own record and keep running; an ended ancestor lends no pane to bind by, because Herdr reuses pane ids. A record ends only through `hide agent end`; closing a pane does not end it, so an ancestor whose pane was closed without that still lends its pane id until the record is purged. A caller below a Factory's own agent that no Task holds as its worker (a start abandoned on its way, or a shell on a reused pane id) can only read; anything else is refused with `factory_agent_unbound`. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. From aa9bfd4f68a1f0c1663fc663189c1dd348898c0e Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 08:11:36 +0900 Subject: [PATCH 58/72] Log a watch warning about a Task that moved after the board was read instead of raising it --- hide-factory/src/engine.rs | 32 ++++++++++++++++++++++++++------ hide-factory/tests/engine.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 1b9ebbfb3f..550edb10a4 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -221,7 +221,10 @@ enum Purpose { /// A periodic user check on a running Task: it adds questions or marks /// and never holds a merge (B67). Periodic, - Watch, + /// The board the watch read, as of this time. + Watch { + read_at: UnixMs, + }, Env, } @@ -4596,8 +4599,8 @@ impl Engine { ), } } - (JudgmentOutcome::Answered { value }, Purpose::Watch, _) => { - self.apply_watch(&factory, value) + (JudgmentOutcome::Answered { value }, Purpose::Watch { read_at }, _) => { + self.apply_watch(&factory, value, read_at) } (JudgmentOutcome::Answered { value }, Purpose::Env, _) => { self.apply_diagnosis(&factory, value) @@ -5850,8 +5853,10 @@ impl Engine { } self.save_factory(factory_id); if self.submit_judgment(judgment.clone()).is_ok() { - self.judgments - .insert(judgment.id, (factory_id.to_owned(), None, Purpose::Watch)); + self.judgments.insert( + judgment.id, + (factory_id.to_owned(), None, Purpose::Watch { read_at: now }), + ); } if interval_due { self.periodic_checks(&factory, now); @@ -5908,7 +5913,7 @@ impl Engine { } } - fn apply_watch(&mut self, factory_id: &str, value: &Value) { + fn apply_watch(&mut self, factory_id: &str, value: &Value, read_at: UnixMs) { let Ok(warnings) = judgment::parse_watch(value) else { return; }; @@ -5945,6 +5950,21 @@ impl Engine { .and_then(|t| self.resolve(&Role::Engine, &t).ok().map(|(_, id)| id)) .or_else(|| self.tasks_of(factory_id).last().map(|t| t.id.clone())); let Some(anchor) = anchor else { continue }; + // The board was read before the judgment answered; a Task that + // moved since is no longer what the warning describes. + if warning.task.is_some() + && self + .task(factory_id, &anchor) + .is_some_and(|t| t.state_since > read_at) + { + self.record( + factory_id, + Some(&anchor), + "watch.logged", + json!({"stale": true}), + ); + continue; + } // A Task already waiting on a person is in the inbox; a warning // about it would say the same thing twice (design #13). if warning.task.is_some() diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index a79d624575..5a6184983e 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -2949,6 +2949,39 @@ fn a_periodic_check_reads_each_running_task_on_the_watch_cadence() { assert_eq!(h.task(&f, &waiting).open_questions().count(), 0); } +#[test] +fn a_watch_warning_about_a_task_that_moved_since_the_board_was_read_is_only_logged() { + let mut h = Bench::new(false); + let f = h.factory(true); + let b = h.ready("B", &[]); + h.world().watch.push_back(json!({"warnings": [ + {"text": "B still waits for a slot", "action": "look at B", "task": b}, + ]})); + h.advance(30 * 60_000); + // The watch reads the board; before it answers, B moves on. + h.world().hold_judgments = true; + h.engine.tick(); + h.advance(1_000); + h.op(Command::Pause { task: b.clone() }); + h.world().hold_judgments = false; + h.engine.tick(); + assert_eq!( + h.task(&f, &b) + .questions + .iter() + .filter(|q| q.text.starts_with("감시:")) + .count(), + 0, + "the warning describes a board that is gone" + ); + assert!( + h.engine + .events(&f, Some(&b), 100) + .iter() + .any(|e| e.kind == "watch.logged" && e.detail["stale"] == true) + ); +} + #[test] fn the_watch_raises_actionable_warnings_once_each_within_the_daily_cap() { let mut h = Bench::new(false); From a0bcd9b38afd07a47cb9aea194bcbad435f15594 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 08:14:28 +0900 Subject: [PATCH 59/72] Keep an unnamed merge unnamed when reading it fails on a signal --- hide-factory/src/engine.rs | 7 ++++++- hide-factory/tests/engine.rs | 32 +++++++++++++++++++++++++++++++ hide-factory/tests/support/mod.rs | 5 +++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 550edb10a4..f84f9e2a14 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -3427,7 +3427,12 @@ impl Engine { (None, None) => None, }; let since = self.merge_retry.get(&key).and_then(|(_, since)| *since); - let unnamed = failure.again_in_ms.is_some().then(|| since.unwrap_or(now)); + // A signal while reading an unnamed merge keeps it unnamed: the + // merge may already have happened, and the 10 minutes still count + // from GitHub's first answer. + let unnamed = (failure.again_in_ms.is_some() + || (failure.signal.is_some() && since.is_some())) + .then(|| since.unwrap_or(now)); if unnamed.is_some_and(|since| now.saturating_sub(since) >= MERGE_UNNAMED_LIMIT_MS) { // GitHub never named the commit: a person looks (rule 15). self.merge_retry.remove(&key); diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 5a6184983e..90f4bdb388 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -1725,6 +1725,38 @@ fn an_unnamed_merge_lands_once_named_and_one_that_did_not_merge_is_checked_again assert_eq!(h.world().merge_attempts, 3, "merged again only after them"); } +#[test] +fn a_network_failure_reading_an_unnamed_merge_keeps_it_unnamed() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let t = h.ready("Read fails once", &[]); + h.world().merge_unnamed = 1; + h.done(&f, &t); + for _ in 0..3 { + h.engine.tick(); + } + let premerges = h.world().premerge_calls; + h.world().merged_read_failure = Some(Failure::environment( + "github.merged", + EnvSignal::Network, + "connection reset", + )); + h.advance(31_000); + h.engine.tick(); + assert_eq!(h.world().merged_reads, 1); + h.advance(2 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.world().merged_reads, 2, "read again, not merged again"); + assert!(h.state(&f, &t).merged(), "{:?}", h.state(&f, &t)); + assert!(h.task(&f, &t).merge_sha.is_some()); + assert_eq!(h.world().merge_attempts, 1); + assert_eq!( + h.world().premerge_calls, + premerges, + "no check reruns on merged work" + ); +} + #[test] fn a_merge_failing_on_a_signal_after_an_old_back_off_is_not_retried_every_tick() { let mut h = Bench::new(true); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 7d7243b816..aae931ac08 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -44,6 +44,8 @@ pub struct World { pub merged_reads: u32, /// The pull request turns out not to have merged (a queue dropped it). pub merge_dropped: bool, + /// The next read of whether a merge landed fails with this failure. + pub merged_read_failure: Option, pub merge_attempts: u32, /// Every push is refused with this failure. pub publish_refusal: Option, @@ -307,6 +309,9 @@ impl MergeTarget for Shared { ) -> Result, Failure> { let mut world = self.world(); world.merged_reads += 1; + if let Some(failure) = world.merged_read_failure.take() { + return Err(failure); + } if world.merge_dropped { world.merge_dropped = false; return Ok(None); From 6e34fde190b7a501e031523bf976f670adbcc520 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 08:16:42 +0900 Subject: [PATCH 60/72] Keep an agent that registered again without a parent below its worker --- docs/factory.md | 2 +- herdr-core/src/runtime/factory.rs | 50 ++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index b500d32acd..6fed307399 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -148,7 +148,7 @@ A `cancelled` or `done` Task's worker stays a worker while its worktree and pane Once a Task's worktree is removed it binds no pane or folder, because Herdr can give a closed pane id to the operator's next pane. An agent a worker spawned acts as that worker: the host follows the caller's spawn lineage in the delivery ledger (up to 16 agents up) and binds an ancestor by its agent id or by the pane it was registered on, and a pane a checkout caller names but cannot prove only ever makes it a worker, never an operator. A lineage the host cannot read to its root (the ledger unreadable, a missing record, a loop, more than 16 agents) may hide a worker above, so that caller can only read; anything else is refused with `lineage_unknown`. -The walk starts from the newest record on the caller's pane even when that record has ended, because an agent can end its own record and keep running; an ended ancestor lends no pane to bind by, because Herdr reuses pane ids. A record ends only through `hide agent end`; closing a pane does not end it, so an ancestor whose pane was closed without that still lends its pane id until the record is purged. A caller below a Factory's own agent that no Task holds as its worker (a start abandoned on its way, or a shell on a reused pane id) can only read; anything else is refused with `factory_agent_unbound`. +The walk starts from the newest record on the caller's pane even when that record has ended, because an agent can end its own record and keep running, and from that same agent's newest record that names a parent when it registered again without one; an ended ancestor lends no pane to bind by, because Herdr reuses pane ids. A record ends only through `hide agent end`; closing a pane does not end it, so an ancestor whose pane was closed without that still lends its pane id until the record is purged. A caller below a Factory's own agent that no Task holds as its worker (a start abandoned on its way, or a shell on a reused pane id) can only read; anything else is refused with `factory_agent_unbound`. Every other caller is an operator, recorded by pane id, or `checkout` when the caller has no pane. The engine itself acts as a third role for deadlines and timers and is never a command caller. A capability file holds only a token, so editing it cannot change a role. diff --git a/herdr-core/src/runtime/factory.rs b/herdr-core/src/runtime/factory.rs index 770c2a77eb..d7e129573b 100644 --- a/herdr-core/src/runtime/factory.rs +++ b/herdr-core/src/runtime/factory.rs @@ -79,7 +79,19 @@ impl Runtime { }; // The newest record on the pane, ended or not: an agent can end its // own record and keep running, so ending it never makes an operator. - let mut next = match ledger.agents.iter().rev().find(|agent| agent.pane == pane) { + // Nor does registering again without a parent: the same agent's + // newest record that names one still decides where it sits. + let newest = ledger.agents.iter().rev().find(|agent| agent.pane == pane); + let start = newest.and_then(|newest| { + ledger + .agents + .iter() + .rev() + .filter(|agent| agent.pane == pane && agent.actor.same_identity(&newest.actor)) + .find(|agent| agent.parent.is_some()) + .or(Some(newest)) + }); + let mut next = match start { Some(agent) => { lineage.factory_spawned |= agent.actor.code_owned(); agent.parent.clone() @@ -420,6 +432,42 @@ mod tests { assert_eq!(live.panes, vec!["factory:f-1"]); } + #[test] + fn registering_again_without_a_parent_keeps_an_agent_below_its_worker() { + let mut runtime = crate::runtime::tests::runtime(); + let mut child = agent("agent-child", "w2:p1", Some("agent-worker")); + child.ended = true; + // The same agent, on the same pane and session, registered again + // with no parent after ending its first record. + let again = AgentRecord { + id: "agent-child-again".into(), + parent: None, + ..child.clone() + }; + // A different agent later on a reused pane id is its own. + let mut reused = agent("agent-other", "w3:p1", None); + let mut gone = agent("agent-gone", "w3:p1", Some("agent-worker")); + gone.ended = true; + reused.ended = false; + runtime.delivery_ledger = Ok(Arc::new(Ledger { + agents: vec![ + agent("agent-factory", "factory:f-1", None), + agent("agent-worker", "w1:p1", Some("agent-factory")), + child, + again, + gone, + reused, + ], + ..Ledger::default() + })); + let walked = runtime.factory_lineage("w2:p1"); + assert_eq!(walked.agents, vec!["agent-worker", "agent-factory"]); + assert!(walked.factory_spawned); + let other = runtime.factory_lineage("w3:p1"); + assert!(other.agents.is_empty(), "{:?}", other.agents); + assert!(!other.factory_spawned); + } + fn row(provider: &str, used: f64, bucket: Option<(f64, u64)>) -> ProviderUsageSnapshot { ProviderUsageSnapshot { provider: provider.into(), From 26c7860003555b18160ae526ae094cb025c4f890 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 08:16:48 +0900 Subject: [PATCH 61/72] Name reopening a pull request among a GitHub Factory's writes --- hide-factory/src/engine.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index f84f9e2a14..758c15f1d3 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -85,7 +85,7 @@ pub const GITHUB_WRITES: [&str; 6] = [ "the factory label", "issue create and edit", "branch push to factory/*", - "pull request open, merge and close", + "pull request open, merge, close and reopen", "revert pull request", "rerun of a failed workflow run", ]; From b188d5de3b9c0cebcf6cac51be7283e40ad609f7 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 08:33:29 +0900 Subject: [PATCH 62/72] Put a code beside every sentence the Factory summary carries CardView gains waiting_code, waiting_on, env_hold and stop; InboxItem gains result_code, unblocks, gates, stop and remaining_hours; TaskDetail gains gate_codes and stop_code. The environment hold is kept as a code too. Every code enum has an ALL list pinned by its wire value. --- docs/factory.md | 22 +++ hide-factory/src/engine.rs | 27 +-- hide-factory/src/model.rs | 51 ++++++ hide-factory/src/summary.rs | 340 +++++++++++++++++++++++++++++++---- hide-factory/tests/engine.rs | 71 ++++++++ 5 files changed, 470 insertions(+), 41 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 6fed307399..9d4658669f 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -531,6 +531,7 @@ Common refusal reasons are `role_not_allowed`, `task_not_found`, `task_ambiguous `FactorySummary` and `TaskDetail` are the contract for any screen of the Factory, and `status`, `inbox` and `show --json` print them as they are. Every number in them is derived in `hide-factory/src/summary.rs` from the stored Tasks, and a screen computes nothing. Fields are added and never renamed or removed. +Every sentence the engine writes into them (`state_label`, `waiting_for`, `text`, `result`, `remaining`, `gates`, `stop`) has a code beside it, so a screen can say it in any language; the codes are listed under [Codes](#codes) and pinned by `every_summary_code_is_pinned` in `summary.rs`. **`FactorySummary`** @@ -570,6 +571,10 @@ Fields are added and never renamed or removed. | `state`, `state_label` | The state id and its label, with the stop reason for a stopped Task. | | `needs_person` | The Task is blocked, stopped, `merge_waiting`, or has an open question that is not a notice. | | `waiting_for` | For a waiting Task, the predecessors by display id, the environment hold, or `slot`; for a blocked one, `answer` or `predecessor`. | +| `waiting_code` | The same as a `WaitingFor` code. | +| `waiting_on` | For `predecessors` on a waiting Task, the predecessors' display ids. | +| `env_hold` | For `environment`, the `EnvHold` code. | +| `stop` | For a stopped Task, the `StopReason` code behind `state_label`. | | `priority` | The Task's priority. | | `since` | When it entered its state. | | `unread` | A completion nobody has looked at: an operator's `show` of the Task, or answering a notice on it, clears it. | @@ -592,9 +597,14 @@ Fields are added and never renamed or removed. | `text` | Why it is the person's turn. | | `suggestion` | The preselected answer. | | `result` | What sending the preselected answer does. | +| `result_code` | The same as a `ResultCode`. | +| `unblocks` | For a blocking question or a merge, the display ids of the waiting Tasks that depend on this one. | +| `gates` | For a merge item, the `Gate` codes it waits on. | +| `stop` | For an item of a stopped Task, the `StopReason` code. | | `default_action` | What the worker does meanwhile. | | `choices` | The listed answers. | | `deadline`, `remaining` | The deadline, and a short phrase for it or for how many days a blocking question has waited. | +| `remaining_hours` | Whole hours left before the deadline, rounded up, 0 once it passed; none for a blocking question. | | `waiting_since`, `waiting_days` | When it started waiting, and whole days for a blocking question. | The inbox lists each open question, each `merge_waiting` Task, and each stopped Task that has no action question, in order of rank and, within a rank, the item waiting longest first. @@ -621,8 +631,10 @@ Inside a column the cards a person must look at (blocked, stopped, merge waiting | `questions` | Every question with its answer and who relayed it. | | `discoveries` | The discoveries with their class. | | `gates` | The reasons a merge waits for a person. | +| `gate_codes` | The same as `Gate` codes. | | `allowed` | The actions the state allows. | | `stop` | The stop reason's label. | +| `stop_code` | The same as a `StopReason` code. | | `merge_sha` | The merge commit. | | `worker_name`, `worktree`, `branch` | The worker's name, folder and branch. | @@ -638,6 +650,16 @@ Inside a column the cards a person must look at (blocked, stopped, merge waiting | `link` | The CI link or the log path. | | `log_tail` | The last 4 KiB of a local log. | +### Codes + +| Code | Values | +| --- | --- | +| `WaitingFor` | `predecessors`, `slot`, `environment`, `answer` | +| `EnvHold` | `disk_floor` (free disk below the floor), `disk_full` (a command found no space), `memory_critical` | +| `StopReason` | `no_report`, `stalled`, `verify_failed`, `new_task_cap`, `environment_repeated`, `worker_start`, `publish_refused` | +| `Gate` | `review_directly`, `approved_scope_change`, `breaking_change`, `no_verification`, `risk_path`, `manual_mode`, `open_question`, `check_failed`, `autonomy_diff`, `dirty_main`, `merge_refused` | +| `ResultCode` | `wake_worker`, `apply_or_merge`, `ready`, `split`, `drafting`, `new_task_cap_choice`, `run_action`, `acknowledge`, `merge`, `restart_worker` | + ## Performance boundaries The engine runs on its own thread, `herdr-core-factory`, and the judgments run on a second, `herdr-core-factory-judge`. diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 758c15f1d3..42d522be7a 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -199,7 +199,7 @@ pub struct Engine { env_problem_since: Option, env_diagnosed: bool, hold_checked_at: Option, - hold_reason: Option, + hold_reason: Option, /// A runtime unavailable until its usage resets (B58). runtime_blocked: BTreeMap, github_backoff: BTreeMap, @@ -4791,24 +4791,29 @@ impl Engine { .disk_free(&project) .is_some_and(|free| free < floor) { - self.hold_reason = Some("디스크 여유가 기준보다 작음".into()); + self.hold_reason = Some(EnvHold::DiskFloor); } else if self.ports.environment.memory_pressure() == MemoryPressure::Critical { - self.hold_reason = Some("메모리 압박 critical".into()); + self.hold_reason = Some(EnvHold::MemoryCritical); } } - if let Some(reason) = self.hold_reason.clone() { + if let Some(reason) = self.hold_reason { self.env_problem_since.get_or_insert(now); for task in &candidates { - if task.held.as_deref() != Some(reason.as_str()) { - let held = reason.clone(); - self.with_task(&task.factory, &task.id, |t| t.held = Some(held)); + if task.held_code != Some(reason) { + self.with_task(&task.factory, &task.id, |t| { + t.held = Some(reason.label().to_owned()); + t.held_code = Some(reason); + }); } } return; } for task in &candidates { - if task.held.is_some() { - self.with_task(&task.factory, &task.id, |t| t.held = None); + if task.held.is_some() || task.held_code.is_some() { + self.with_task(&task.factory, &task.id, |t| { + t.held = None; + t.held_code = None; + }); } } let mut free = self @@ -5534,7 +5539,7 @@ impl Engine { } } EnvSignal::DiskFull => { - self.hold_reason = Some("디스크 부족".into()); + self.hold_reason = Some(EnvHold::DiskFull); self.hold_checked_at = Some(now); self.remove_finished_worktrees(None); } @@ -5646,7 +5651,7 @@ impl Engine { }; self.env_diagnosed = true; let facts = json!({ - "hold": self.hold_reason, + "hold": self.hold_reason.map(EnvHold::label), "halted": self.halt_until.is_some_and(|u| u > now), "recent_failures": self.env_failures.iter().map(|note| json!({"task": note.task, "stage": note.stage, "kind": note.kind.as_str()})).collect::>(), "disk_free": self.ports.environment.disk_free(&factory.project), diff --git a/hide-factory/src/model.rs b/hide-factory/src/model.rs index a1efefb5ba..674c314ee9 100644 --- a/hide-factory/src/model.rs +++ b/hide-factory/src/model.rs @@ -671,6 +671,20 @@ pub enum Gate { } impl Gate { + pub const ALL: [Self; 11] = [ + Self::ReviewDirectly, + Self::ApprovedScopeChange, + Self::BreakingChange, + Self::NoVerification, + Self::RiskPath, + Self::ManualMode, + Self::OpenQuestion, + Self::CheckFailed, + Self::AutonomyDiff, + Self::DirtyMain, + Self::MergeRefused, + ]; + pub fn reason(self) -> &'static str { match self { Self::ReviewDirectly => "직접 확인 표시", @@ -702,6 +716,16 @@ pub enum StopReason { } impl StopReason { + pub const ALL: [Self; 7] = [ + Self::NoReport, + Self::Stalled, + Self::VerifyFailed, + Self::NewTaskCap, + Self::EnvironmentRepeated, + Self::WorkerStart, + Self::PublishRefused, + ]; + pub fn label(self) -> &'static str { match self { Self::NoReport => "보고 없이 멈춤", @@ -715,6 +739,29 @@ impl StopReason { } } +/// Why no new worker starts on this machine (B57). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvHold { + /// Free disk is below the Factory's floor. + DiskFloor, + /// A command failed with no space left on the device. + DiskFull, + MemoryCritical, +} + +impl EnvHold { + pub const ALL: [Self; 3] = [Self::DiskFloor, Self::DiskFull, Self::MemoryCritical]; + + pub fn label(self) -> &'static str { + match self { + Self::DiskFloor => "디스크 여유가 기준보다 작음", + Self::DiskFull => "디스크 부족", + Self::MemoryCritical => "메모리 압박 critical", + } + } +} + /// The worker a Task runs, as the runtime adapter reported it. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct WorkerRef { @@ -832,6 +879,9 @@ pub struct Task { pub writes: BTreeSet, /// Environment hold: a start was refused by the pre-start check (B57). pub held: Option, + /// The same hold as a code. + #[serde(default)] + pub held_code: Option, pub label_path: bool, pub source_body_hash: Option, } @@ -904,6 +954,7 @@ impl Task { idle_since: None, writes: BTreeSet::new(), held: None, + held_code: None, label_path: false, source_body_hash: None, } diff --git a/hide-factory/src/summary.rs b/hide-factory/src/summary.rs index 58cd525412..2654ad997a 100644 --- a/hide-factory/src/summary.rs +++ b/hide-factory/src/summary.rs @@ -10,11 +10,76 @@ use serde::{Deserialize, Serialize}; use crate::dag; use crate::model::{ - Attachment, AttemptOutcome, AttemptStage, Column, DAY_MS, DecisionRecord, Discovery, Factory, - MergeMode, PullRequest, Question, QuestionKind, SourceKind, Task, TaskState, UnixMs, - Verification, + Attachment, AttemptOutcome, AttemptStage, Column, DAY_MS, DecisionRecord, Discovery, EnvHold, + Factory, Gate, MergeMode, PullRequest, Question, QuestionKind, SourceKind, StopReason, Task, + TaskState, UnixMs, Verification, }; +/// What a card waits for, as a code beside `waiting_for`'s words, so a +/// screen can say it in any language (stage 2 B24). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WaitingFor { + /// Tasks it depends on; `waiting_on` names them. + Predecessors, + /// A free worker slot. + Slot, + /// The machine holds new starts; `env_hold` says why. + Environment, + /// A person's answer to a blocking question. + Answer, +} + +impl WaitingFor { + pub const ALL: [Self; 4] = [ + Self::Predecessors, + Self::Slot, + Self::Environment, + Self::Answer, + ]; +} + +/// What sending an inbox item's preselected answer does, as a code beside +/// `result`'s words; `unblocks` names the Tasks it frees. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ResultCode { + /// The sleeping worker wakes and continues. + WakeWorker, + /// An answer that differs from the default goes to the worker; the same + /// one goes on to merge. + ApplyOrMerge, + /// With no question left the Task is Ready. + Ready, + /// The Task is split into the proposed pieces. + Split, + /// The approved Task enters drafting. + Drafting, + /// The chosen of split, continue or stop. + NewTaskCapChoice, + /// The chosen action runs. + RunAction, + Acknowledge, + Merge, + /// The worker restarts in the same worktree. + RestartWorker, +} + +impl ResultCode { + pub const ALL: [Self; 10] = [ + Self::WakeWorker, + Self::ApplyOrMerge, + Self::Ready, + Self::Split, + Self::Drafting, + Self::NewTaskCapChoice, + Self::RunAction, + Self::Acknowledge, + Self::Merge, + Self::RestartWorker, + ]; +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FactorySummary { /// The one person-facing number: open inbox items across Factories (D-37). @@ -76,6 +141,14 @@ pub struct CardView { pub needs_person: bool, /// What a waiting Task waits for, in words (D-36). pub waiting_for: Option, + /// The same as a code. + pub waiting_code: Option, + /// The display ids of the predecessors it waits on. + pub waiting_on: Vec, + /// Why the machine holds new starts, for `environment`. + pub env_hold: Option, + /// The stop reason behind a stopped card's `state_label`. + pub stop: Option, pub priority: i32, pub since: UnixMs, /// A completion the person has not looked at (D-30). @@ -126,9 +199,19 @@ pub struct InboxItem { pub choices: Vec, pub deadline: Option, pub remaining: Option, + /// Whole hours left before the deadline, rounded up; 0 once it passed. + pub remaining_hours: Option, pub waiting_since: UnixMs, /// Whole days a blocking question has waited. pub waiting_days: u64, + /// `result` as a code. + pub result_code: ResultCode, + /// The display ids of waiting Tasks this item frees once it is done. + pub unblocks: Vec, + /// Why a merge item waits for a person. + pub gates: Vec, + /// Why a stopped item stopped. + pub stop: Option, } pub fn build(factories: &[&Factory], tasks: &[&Task], now: UnixMs) -> FactorySummary { @@ -264,28 +347,42 @@ pub fn card_view( now: UnixMs, ) -> CardView { let waiting = dag::waiting_for(task, tasks); - let waiting_for = match task.state { - TaskState::Waiting if !waiting.is_empty() => Some( - waiting - .iter() - .map(|id| { - tasks - .get(id) - .map(Task::display_id) - .unwrap_or_else(|| id.clone()) - }) - .collect::>() - .join(", "), - ), - TaskState::Waiting => task.held.clone().or_else(|| Some("slot".into())), - TaskState::Blocked => Some( - task.open_questions() - .find(|question| matches!(question.kind, QuestionKind::Blocking)) - .map(|_| "answer".to_owned()) - .unwrap_or_else(|| "predecessor".to_owned()), - ), + let waiting_on: Vec = waiting + .iter() + .map(|id| { + tasks + .get(id) + .map(Task::display_id) + .unwrap_or_else(|| id.clone()) + }) + .collect(); + let waiting_code = match task.state { + TaskState::Waiting if !waiting_on.is_empty() => Some(WaitingFor::Predecessors), + TaskState::Waiting if task.held.is_some() || task.held_code.is_some() => { + Some(WaitingFor::Environment) + } + TaskState::Waiting => Some(WaitingFor::Slot), + TaskState::Blocked + if task + .open_questions() + .any(|question| matches!(question.kind, QuestionKind::Blocking)) => + { + Some(WaitingFor::Answer) + } + TaskState::Blocked => Some(WaitingFor::Predecessors), _ => None, }; + let waiting_for = match waiting_code { + Some(WaitingFor::Predecessors) if task.state == TaskState::Waiting => { + Some(waiting_on.join(", ")) + } + Some(WaitingFor::Predecessors) => Some("predecessor".to_owned()), + Some(WaitingFor::Environment) => task.held.clone(), + Some(WaitingFor::Slot) => Some("slot".to_owned()), + Some(WaitingFor::Answer) => Some("answer".to_owned()), + None => None, + }; + let stop = task.stop.filter(|_| task.state == TaskState::Stopped); let finished_at = match task.state { TaskState::Done => task.done_at, TaskState::Cancelled | TaskState::Outside => task.cancelled_at, @@ -306,12 +403,20 @@ pub fn card_view( column: task.state.column().map(|column| column.as_str().to_owned()), title: task.card.title.clone(), state: task.state.as_str().to_owned(), - state_label: task - .stop - .filter(|_| task.state == TaskState::Stopped) + state_label: stop .map(|reason| format!("{} ({})", task.state.label(), reason.label())) .unwrap_or_else(|| task.state.label().to_owned()), needs_person: task.needs_person(), + waiting_on: if waiting_code == Some(WaitingFor::Predecessors) { + waiting_on + } else { + Vec::new() + }, + env_hold: task + .held_code + .filter(|_| waiting_code == Some(WaitingFor::Environment)), + waiting_code, + stop, waiting_for, priority: task.human.priority, since: task.state_since, @@ -363,9 +468,15 @@ pub fn inbox_items( choices: Vec::new(), deadline: None, remaining: None, + remaining_hours: None, waiting_since: since, waiting_days: 0, + result_code: ResultCode::Acknowledge, + unblocks: Vec::new(), + gates: Vec::new(), + stop: None, }; + let frees = waiting_on_this(task, tasks); for question in task.open_questions() { let (group, rank) = match question.kind { QuestionKind::Blocking => ("answer", 0), @@ -376,6 +487,11 @@ pub fn inbox_items( let mut item = base(group, rank, question.text.clone(), question.asked_at); item.kind = question_kind(&question.kind).to_owned(); item.result = answer_result(task, &question.kind, tasks); + item.result_code = answer_code(&question.kind); + item.stop = task.stop.filter(|_| task.state == TaskState::Stopped); + if matches!(question.kind, QuestionKind::Blocking) { + item.unblocks = frees.clone(); + } if matches!(question.kind, QuestionKind::Blocking) { item.waiting_days = now.saturating_sub(question.asked_at) / DAY_MS; } @@ -384,6 +500,13 @@ pub fn inbox_items( item.default_action = question.default_action.clone(); item.choices = question.choices.clone(); item.deadline = question.deadline; + item.remaining_hours = match (&question.kind, question.deadline) { + (QuestionKind::Blocking, _) => None, + (_, Some(deadline)) => { + Some(deadline.saturating_sub(now).div_ceil(crate::model::HOUR_MS)) + } + _ => None, + }; item.remaining = match (&question.kind, question.deadline) { (QuestionKind::Blocking, _) => { let days = now.saturating_sub(question.asked_at) / DAY_MS; @@ -414,6 +537,9 @@ pub fn inbox_items( item.choices = vec!["merge".into(), "request-changes".into(), "cancel".into()]; item.suggestion = "merge".into(); item.result = unblocks("머지", task, tasks); + item.result_code = ResultCode::Merge; + item.unblocks = frees.clone(); + item.gates = task.gates.clone(); items.push(item); } TaskState::Stopped @@ -442,6 +568,8 @@ pub fn inbox_items( item.choices = vec!["retry".into(), "cancel".into()]; item.suggestion = "retry".into(); item.result = "같은 worktree에서 worker를 다시 시작".into(); + item.result_code = ResultCode::RestartWorker; + item.stop = task.stop; items.push(item); } _ => {} @@ -482,14 +610,32 @@ fn answer_result(task: &Task, kind: &QuestionKind, tasks: &BTreeMap , 끝나면 #421이 풀림"` when a waiting Task depends on this one. -fn unblocks(what: &str, task: &Task, tasks: &BTreeMap) -> String { - let waiting: Vec = tasks +fn answer_code(kind: &QuestionKind) -> ResultCode { + match kind { + QuestionKind::Blocking => ResultCode::WakeWorker, + QuestionKind::Default | QuestionKind::ScopeChange { .. } => ResultCode::ApplyOrMerge, + QuestionKind::Intake | QuestionKind::ConfirmCard => ResultCode::Ready, + QuestionKind::Split { .. } => ResultCode::Split, + QuestionKind::ProposedTask { .. } => ResultCode::Drafting, + QuestionKind::NewTaskCap => ResultCode::NewTaskCapChoice, + QuestionKind::Action | QuestionKind::Proposal { .. } => ResultCode::RunAction, + QuestionKind::Notice => ResultCode::Acknowledge, + } +} + +/// The waiting Tasks that depend on `task`, by display id. +fn waiting_on_this(task: &Task, tasks: &BTreeMap) -> Vec { + tasks .values() .filter(|other| other.card.depends_on.contains(&task.id)) .filter(|other| matches!(other.state, TaskState::Waiting | TaskState::Blocked)) .map(Task::display_id) - .collect(); + .collect() +} + +/// `" , 끝나면 #421이 풀림"` when a waiting Task depends on this one. +fn unblocks(what: &str, task: &Task, tasks: &BTreeMap) -> String { + let waiting = waiting_on_this(task, tasks); if waiting.is_empty() { what.to_owned() } else { @@ -520,9 +666,13 @@ pub struct TaskDetail { pub discoveries: Vec, /// Why merge waits for a person (D-25). pub gates: Vec, + /// The same as codes. + pub gate_codes: Vec, /// The actions this state allows (Q29). pub allowed: Vec, pub stop: Option, + /// `stop` as a code. + pub stop_code: Option, pub merge_sha: Option, pub worker_name: Option, pub worktree: Option, @@ -620,8 +770,10 @@ pub fn detail( .iter() .map(|gate| gate.reason().to_owned()) .collect(), + gate_codes: task.gates.clone(), allowed: allowed.into_iter().map(str::to_owned).collect(), stop: task.stop.map(|reason| reason.label().to_owned()), + stop_code: task.stop, merge_sha: task.merge_sha.clone(), worker_name: task.worker.as_ref().map(|worker| worker.name.clone()), worktree: task.worker.as_ref().map(|worker| worker.worktree.clone()), @@ -640,3 +792,131 @@ fn log_tail(path: &str) -> Option { file.read_to_end(&mut bytes).ok()?; Some(String::from_utf8_lossy(&bytes).into_owned()) } + +#[cfg(test)] +mod tests { + //! The codes stage 2 decodes are a contract. Each list is matched + //! exhaustively, so a new variant fails to compile here until it is + //! listed, and then fails until its wire value is pinned below and in + //! `docs/factory.md`. + use super::*; + + fn wire(values: &[T]) -> Vec { + values + .iter() + .map(|value| match serde_json::to_value(value).unwrap() { + serde_json::Value::String(text) => text, + other => panic!("a code serializes as a string, got {other}"), + }) + .collect() + } + + fn complete(all: &[T], index: fn(T) -> usize) { + let indexes: Vec = all.iter().map(|value| index(*value)).collect(); + assert_eq!( + indexes, + (0..all.len()).collect::>(), + "ALL lists every variant once, in order" + ); + } + + #[test] + fn every_summary_code_is_pinned() { + complete(&Gate::ALL, |gate| match gate { + Gate::ReviewDirectly => 0, + Gate::ApprovedScopeChange => 1, + Gate::BreakingChange => 2, + Gate::NoVerification => 3, + Gate::RiskPath => 4, + Gate::ManualMode => 5, + Gate::OpenQuestion => 6, + Gate::CheckFailed => 7, + Gate::AutonomyDiff => 8, + Gate::DirtyMain => 9, + Gate::MergeRefused => 10, + }); + assert_eq!( + wire(&Gate::ALL), + [ + "review_directly", + "approved_scope_change", + "breaking_change", + "no_verification", + "risk_path", + "manual_mode", + "open_question", + "check_failed", + "autonomy_diff", + "dirty_main", + "merge_refused", + ] + ); + complete(&StopReason::ALL, |reason| match reason { + StopReason::NoReport => 0, + StopReason::Stalled => 1, + StopReason::VerifyFailed => 2, + StopReason::NewTaskCap => 3, + StopReason::EnvironmentRepeated => 4, + StopReason::WorkerStart => 5, + StopReason::PublishRefused => 6, + }); + assert_eq!( + wire(&StopReason::ALL), + [ + "no_report", + "stalled", + "verify_failed", + "new_task_cap", + "environment_repeated", + "worker_start", + "publish_refused", + ] + ); + complete(&EnvHold::ALL, |hold| match hold { + EnvHold::DiskFloor => 0, + EnvHold::DiskFull => 1, + EnvHold::MemoryCritical => 2, + }); + assert_eq!( + wire(&EnvHold::ALL), + ["disk_floor", "disk_full", "memory_critical"] + ); + complete(&WaitingFor::ALL, |waiting| match waiting { + WaitingFor::Predecessors => 0, + WaitingFor::Slot => 1, + WaitingFor::Environment => 2, + WaitingFor::Answer => 3, + }); + assert_eq!( + wire(&WaitingFor::ALL), + ["predecessors", "slot", "environment", "answer"] + ); + complete(&ResultCode::ALL, |code| match code { + ResultCode::WakeWorker => 0, + ResultCode::ApplyOrMerge => 1, + ResultCode::Ready => 2, + ResultCode::Split => 3, + ResultCode::Drafting => 4, + ResultCode::NewTaskCapChoice => 5, + ResultCode::RunAction => 6, + ResultCode::Acknowledge => 7, + ResultCode::Merge => 8, + ResultCode::RestartWorker => 9, + }); + assert_eq!( + wire(&ResultCode::ALL), + [ + "wake_worker", + "apply_or_merge", + "ready", + "split", + "drafting", + "new_task_cap_choice", + "run_action", + "acknowledge", + "merge", + "restart_worker", + ] + ); + } +} diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 90f4bdb388..8eaa80046c 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -38,6 +38,20 @@ fn tick_until(h: &mut Bench, factory: &str, id: &str, state: TaskState) { ); } +/// The summary card of `id`, as the JSON stage 2 reads. +fn card_json(h: &Bench, id: &str) -> serde_json::Value { + let summary = serde_json::to_value(h.engine.summary()).unwrap(); + summary["factories"] + .as_array() + .unwrap() + .iter() + .flat_map(|f| f["columns"].as_array().unwrap().iter()) + .flat_map(|c| c["cards"].as_array().unwrap().iter()) + .find(|card| card["task"] == id) + .cloned() + .unwrap_or_else(|| panic!("no card {id}")) +} + fn open_question(h: &Bench, factory: &str, id: &str) -> Question { h.task(factory, id) .open_questions() @@ -554,6 +568,9 @@ fn a_dependent_starts_only_after_its_predecessor_merged_not_when_it_is_verifying ); let card = h.engine.summary().factories[0].columns[1].cards.clone(); assert_eq!(card[0].waiting_for.as_deref(), Some("L-1")); + let card = card_json(&h, &b); + assert_eq!(card["waiting_code"], "predecessors", "{card}"); + assert_eq!(card["waiting_on"], json!(["L-1"])); tick_until(&mut h, &f, &a, TaskState::Done); tick_until(&mut h, &f, &b, TaskState::Running); } @@ -660,6 +677,28 @@ fn a_different_answer_before_the_deadline_sends_the_worker_back() { ); } +#[test] +fn a_blocking_answer_names_the_waiting_tasks_it_frees() { + let mut h = Bench::new(false); + let f = h.factory(true); + let a = h.ready("Blocks", &[]); + let b = h.ready("After", &[&a]); + h.as_worker( + &f, + &a, + Command::Block { + text: "Which?".into(), + suggestion: "this one".into(), + deadline_hours: Some(24), + letter: None, + }, + ); + let inbox = h.op(Command::Inbox); + let item = &inbox["items"][0]; + assert_eq!(item["result_code"], "wake_worker", "{inbox}"); + assert_eq!(item["unblocks"], json!([h.task(&f, &b).display_id()])); +} + #[test] fn a_question_needs_a_suggestion_and_a_deadline() { let mut h = Bench::new(false); @@ -710,6 +749,9 @@ fn a_blocking_question_releases_the_slot_and_the_answer_wakes_the_same_session() ); assert_eq!(h.state(&f, &blocked), TaskState::Blocked); assert!(h.world().sleeps.contains(&blocked)); + assert_eq!(card_json(&h, &blocked)["waiting_code"], "answer"); + let inbox = h.op(Command::Inbox); + assert_eq!(inbox["items"][0]["result_code"], "wake_worker", "{inbox}"); h.engine.tick(); assert_eq!( h.state(&f, &other), @@ -780,6 +822,19 @@ fn verification_fails_count_toward_the_limit_and_then_stop_the_task() { (task.state, task.stop), (TaskState::Stopped, Some(StopReason::VerifyFailed)) ); + assert_eq!(card_json(&h, &t)["stop"], "verify_failed"); + let inbox = h.op(Command::Inbox); + let stopped = inbox["items"] + .as_array() + .unwrap() + .iter() + .find(|item| item["group"] == "stopped") + .cloned() + .unwrap(); + assert_eq!(stopped["stop"], "verify_failed", "{stopped}"); + assert_eq!(stopped["result_code"], "run_action"); + let shown = h.op(Command::Show { task: t.clone() }); + assert_eq!(shown["task"]["stop_code"], "verify_failed", "{shown}"); assert_eq!( h.world().verify_runs.len(), 3, @@ -1493,6 +1548,19 @@ fn a_manual_task_waits_for_merge_and_every_github_write_happens_once() { assert_eq!(h.task(&f, &t).gates, vec![Gate::ManualMode]); let inbox = h.op(Command::Inbox); assert_eq!(inbox["items"][0]["group"], "merge", "{inbox}"); + // Codes beside the sentences, for a screen in any language. + assert_eq!( + inbox["items"][0]["gates"], + json!(["manual_mode"]), + "{inbox}" + ); + assert_eq!(inbox["items"][0]["result_code"], "merge"); + let shown = h.op(Command::Show { task: t.clone() }); + assert_eq!( + shown["task"]["gate_codes"], + json!(["manual_mode"]), + "{shown}" + ); for _ in 0..5 { h.engine.tick(); } @@ -2247,6 +2315,9 @@ fn a_low_disk_holds_new_starts_and_the_hold_clears_on_recheck() { let t = h.ready("Held", &[]); assert_eq!(h.state(&f, &t), TaskState::Waiting); assert!(h.task(&f, &t).held.is_some()); + let card = card_json(&h, &t); + assert_eq!(card["waiting_code"], "environment", "{card}"); + assert_eq!(card["env_hold"], "disk_floor"); h.world().disk_free = Some(100 << 30); h.engine.tick(); assert_eq!( From 0668f2afb61d3a5dc28f53f047f898cd33a590c2 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 08:46:33 +0900 Subject: [PATCH 63/72] Tell a person to turn Hide AI on when a review is refused as disabled, and say which summary sentences have codes --- docs/factory.md | 6 ++++-- hide-factory/src/engine.rs | 9 ++++++++- hide-factory/tests/engine.rs | 20 +++++++++++++++++++- hide-factory/tests/support/mod.rs | 11 +++++++++++ 4 files changed, 42 insertions(+), 4 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 9d4658669f..64689eb2ac 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -259,6 +259,7 @@ Questions that a drift or check judgment adds always carry a default action, tak A drift question keeps the Task in `verifying`, does not wake the worker, and holds auto merge until it is answered or its deadline passes; an answer that differs from the default wakes the worker to apply it. A judgment that cannot run is never skipped and never read as a pass. A failed review marks the Task and puts a retry-or-cancel question in the inbox, and `add` answers `pending`. +While Hide AI is off or no agent is chosen to run it, every judgment fails as `disabled`, and the question says to turn it on in Settings › Hide AI. A failed drift or check sends the Task to `merge_waiting` for a person. A failed watch or diagnosis changes no Task and is logged. @@ -531,7 +532,8 @@ Common refusal reasons are `role_not_allowed`, `task_not_found`, `task_ambiguous `FactorySummary` and `TaskDetail` are the contract for any screen of the Factory, and `status`, `inbox` and `show --json` print them as they are. Every number in them is derived in `hide-factory/src/summary.rs` from the stored Tasks, and a screen computes nothing. Fields are added and never renamed or removed. -Every sentence the engine writes into them (`state_label`, `waiting_for`, `text`, `result`, `remaining`, `gates`, `stop`) has a code beside it, so a screen can say it in any language; the codes are listed under [Codes](#codes) and pinned by `every_summary_code_is_pinned` in `summary.rs`. +The engine's sentences in `state_label`, `waiting_for`, `result`, `remaining`, `gates` and `stop` have a code beside them, so a screen can say them in any language; the codes are listed under [Codes](#codes) and pinned by `every_summary_code_is_pinned` in `summary.rs`. +An inbox item's `text` carries only its `kind`, and a question's own text, a split's piece count, a stop's detail and `TaskDetail.verification` have no code yet. **`FactorySummary`** @@ -572,7 +574,7 @@ Every sentence the engine writes into them (`state_label`, `waiting_for`, `text` | `needs_person` | The Task is blocked, stopped, `merge_waiting`, or has an open question that is not a notice. | | `waiting_for` | For a waiting Task, the predecessors by display id, the environment hold, or `slot`; for a blocked one, `answer` or `predecessor`. | | `waiting_code` | The same as a `WaitingFor` code. | -| `waiting_on` | For `predecessors` on a waiting Task, the predecessors' display ids. | +| `waiting_on` | For `predecessors` on a waiting Task, the display ids of the predecessors it waits on, for a waiting or blocked Task. | | `env_hold` | For `environment`, the `EnvHold` code. | | `stop` | For a stopped Task, the `StopReason` code behind `state_label`. | | `priority` | The Task's priority. | diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 42d522be7a..84e708972e 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1878,12 +1878,19 @@ impl Engine { .any(|q| q.text.starts_with("검토를 하지 못했습니다")) }); if !already { + // Hide AI off, or no agent chosen to run it, refuses every + // judgment as `disabled`; fixing a provider would not help. + let text = if reason == "disabled" { + "검토를 하지 못했습니다. Settings › Hide AI에서 Hide AI를 켜고 Runs on을 고른 뒤 다시 검토하세요." + } else { + "검토를 하지 못했습니다. Settings › Hide AI에서 provider를 고친 뒤 다시 검토하세요." + }; self.add_question( factory, id, QuestionOrigin::Engine, QuestionKind::Action, - "검토를 하지 못했습니다. Settings › Background AI에서 provider를 고친 뒤 다시 검토하세요.", + text, "retry-review", None, None, diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 8eaa80046c..b065b6a7e4 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -291,6 +291,24 @@ fn a_dependency_that_closes_a_loop_is_refused_with_its_path() { assert_eq!(refused["detail"]["cycle"], json!([c, b, a])); } +#[test] +fn a_review_refused_because_hide_ai_is_off_says_to_turn_it_on_once() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().judgment_failure = Some("disabled".into()); + let answer = h.add("Needs review", &[]); + let id = answer["task"]["id"].as_str().unwrap().to_owned(); + h.engine.tick(); + h.engine.tick(); + let questions: Vec = h + .task(&f, &id) + .open_questions() + .map(|q| q.text.clone()) + .collect(); + assert_eq!(questions.len(), 1, "{questions:?}"); + assert!(questions[0].contains("Hide AI를 켜고"), "{questions:?}"); +} + #[test] fn a_review_that_cannot_run_keeps_the_task_drafting_and_asks_for_the_provider() { let mut h = Bench::new(false); @@ -306,7 +324,7 @@ fn a_review_that_cannot_run_keeps_the_task_drafting_and_asks_for_the_provider() inbox["items"][0]["text"] .as_str() .unwrap() - .contains("Background AI"), + .contains("Settings › Hide AI"), "{inbox}" ); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index aae931ac08..6835856d6d 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -90,6 +90,8 @@ pub struct World { /// Scripted watch answers, oldest first; no warnings when empty. pub watch: VecDeque, pub judge_down: bool, + /// Every judgment answers as failed with this reason. + pub judgment_failure: Option, /// The environment diagnosis's answer; an unknown cause when absent. pub env_diagnosis: Option, pub hold_judgments: bool, @@ -489,6 +491,15 @@ impl Judge for Shared { let submitted = std::mem::take(&mut world.submitted); let mut answers = Vec::new(); for judgment in submitted { + if let Some(reason) = world.judgment_failure.clone() { + answers.push(JudgmentAnswer { + id: judgment.id.clone(), + factory: judgment.factory.clone(), + task: judgment.task.clone(), + outcome: JudgmentOutcome::Failed { reason }, + }); + continue; + } let value = match &judgment.input { JudgmentInput::IntakeReview { card, .. } => { world.intake.get(&card.title).cloned().unwrap_or_else( From 11ac5da23751f05fab6bbd5ae558fc458db39443 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:02:24 +0900 Subject: [PATCH 64/72] Apply a worker's same report again once its Task moved, and resolve dependency and watch references within their Factory --- herdr-core/src/factory.rs | 40 +++++++++++++++++++++++++++++++----- hide-factory/src/engine.rs | 40 +++++++++++++++++++++++++++++------- hide-factory/tests/engine.rs | 27 ++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 12 deletions(-) diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index d38635dfda..f891ade921 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -518,6 +518,16 @@ fn publish_recipients(engine: Option<&Engine>, runtime: &Weak>) { /// Runs one command with the caller's role (D-33). A worker's report travels /// as a ledger letter from its own pane, so a harness that only speaks the /// letter protocol lands on the same path (B25). +/// The delivery intent of a worker's report. A retry of the same report in +/// the same Task state is one letter; the same words after the Task moved +/// (a `done` again once verification sent it back) are a new report. +fn report_intent(pane: &str, epoch: u64, body: &str) -> String { + format!( + "factory-{}", + &hide_factory::store::sha256_hex(format!("{pane}\n{epoch}\n{body}").as_bytes())[..24] + ) +} + /// The `hide` program beside the running daemon (the app bundle's /// Resources, or a build's target folder). fn hide_program() -> Option { @@ -596,14 +606,15 @@ fn handle( Command::Done { .. } => Some("report"), _ => None, }; - let (Role::Worker { factory, .. }, Some(kind), Some(pane)) = (&role, kind, &caller.pane) else { + let (Role::Worker { factory, task }, Some(kind), Some(pane)) = (&role, kind, &caller.pane) + else { return engine.command(&role, command); }; let body = json!({"factory": command}).to_string(); - let intent = format!( - "factory-{}", - &hide_factory::store::sha256_hex(format!("{pane}\n{body}").as_bytes())[..24] - ); + let epoch = engine + .task(factory, task) + .map_or(0, |task| task.state_since); + let intent = report_intent(pane, epoch, &body); let letter = (|| { let runtime = lock(runtime).ok_or("delivery_unavailable")?; let prepared = guard(&runtime).factory_worker_letter( @@ -1552,6 +1563,25 @@ mod tests { use super::*; use std::cell::RefCell; + #[test] + fn the_same_report_after_the_task_moved_is_a_new_letter() { + let body = r#"{"factory":{"done":{}}}"#; + assert_eq!( + report_intent("w1:p1", 10, body), + report_intent("w1:p1", 10, body), + "a retry in the same state is one letter" + ); + assert_ne!( + report_intent("w1:p1", 10, body), + report_intent("w1:p1", 20, body), + "done again after verification sent the Task back" + ); + assert_ne!( + report_intent("w1:p1", 10, body), + report_intent("w2:p1", 10, body) + ); + } + fn request(task: &str, resume: Option) -> WorkerSpawn { WorkerSpawn { factory: "f-1".into(), diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 84e708972e..7d13e3e237 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -998,6 +998,20 @@ impl Engine { /// A Task by its id (`T-3`), issue (`#412`, `L-12`) or `factory/T-3`. fn resolve(&self, role: &Role, reference: &str) -> Result<(String, String), Refusal> { + let within = match role { + Role::Worker { factory, .. } => Some(factory.as_str()), + _ => None, + }; + self.resolve_within(within, reference) + } + + /// A Task reference, inside `factory` when one is given: a dependency or + /// a watch warning names a Task of its own Factory. + fn resolve_within( + &self, + factory: Option<&str>, + reference: &str, + ) -> Result<(String, String), Refusal> { let reference = reference.trim(); let mut found = Vec::new(); for task in self.all_tasks() { @@ -1011,7 +1025,7 @@ impl Engine { found.push((task.factory.clone(), task.id.clone())); } } - if let Role::Worker { factory, .. } = role { + if let Some(factory) = factory { found.retain(|(f, _)| f == factory); } match found.as_slice() { @@ -4096,7 +4110,7 @@ impl Engine { "A worker changes only its own Task", )); } - let (_, on_id) = self.resolve(role, on)?; + let (_, on_id) = self.resolve_within(Some(&factory), on)?; let current = self .task(&factory, &id) .cloned() @@ -5961,11 +5975,23 @@ impl Engine { self.record(factory_id, None, "watch.capped", json!({})); continue; } - let anchor = warning - .task - .clone() - .and_then(|t| self.resolve(&Role::Engine, &t).ok().map(|(_, id)| id)) - .or_else(|| self.tasks_of(factory_id).last().map(|t| t.id.clone())); + let anchor = match &warning.task { + // A warning about a Task this Factory does not have is about + // nothing a person can act on here. + Some(reference) => match self.resolve_within(Some(factory_id), reference) { + Ok((_, id)) => Some(id), + Err(_) => { + self.record( + factory_id, + None, + "watch.logged", + json!({"unresolved": true}), + ); + continue; + } + }, + None => self.tasks_of(factory_id).last().map(|t| t.id.clone()), + }; let Some(anchor) = anchor else { continue }; // The board was read before the judgment answered; a Task that // moved since is no longer what the warning describes. diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index b065b6a7e4..2a0128e765 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -621,6 +621,33 @@ fn slots_go_by_priority_then_age_across_factories() { tick_until(&mut h, &f1, &old, TaskState::Running); } +#[test] +fn a_dependency_names_a_task_of_the_same_factory() { + let mut h = Bench::new(false); + let f1 = h.factory(true); + let f2 = h.factory_at("/work/other", true); + h.world().hold_judgments = true; + let a = h.add("A", &[])["task"]["id"].as_str().unwrap().to_owned(); + let b = h.add("B", &[])["task"]["id"].as_str().unwrap().to_owned(); + let other = h.op(Command::Add { + project: Some("/work/other".into()), + task: None, + issue: None, + card: card("Elsewhere", &[]), + producer_pane: None, + }); + // Both Factories have a Task with A's id. + assert_eq!(other["task"]["id"].as_str(), Some(a.as_str()), "{other}"); + let added = h.op(Command::Dep { + task: format!("{f1}/{b}"), + on: a.clone(), + remove: false, + }); + assert_eq!(added["ok"], true, "{added}"); + assert_eq!(h.task(&f1, &b).card.depends_on, vec![a.clone()]); + assert!(h.task(&f2, &a).card.depends_on.is_empty()); +} + // ------------------------------------------------------------- worker reports #[test] From 7e531ebec82bf05f4ab389c287a6b66784524d65 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:03:14 +0900 Subject: [PATCH 65/72] Hold the merge when a check fails with nothing to ask or cannot read the diff --- hide-factory/src/engine.rs | 11 ++++++++++- hide-factory/tests/engine.rs | 20 ++++++++++++++++++++ hide-factory/tests/support/mod.rs | 5 +++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 7d13e3e237..453067c7f9 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -2886,7 +2886,11 @@ impl Engine { let Some(f) = self.factories.get(factory).cloned() else { return; }; - let diff = self.ports.merge.diff_text(&f, &task).unwrap_or_default(); + // A diff that cannot be read gives the checks nothing to judge; that + // is a check that cannot run, never a pass (B68). + let Ok(diff) = self.ports.merge.diff_text(&f, &task) else { + return self.check_failed(factory, id); + }; let mut count = 0; let decisions = task.decisions.iter().map(|d| d.text.clone()).collect(); let attempt = task.attempts.len(); @@ -2959,6 +2963,11 @@ impl Engine { Ok(finding) => finding, Err(_) => return self.check_failed(factory, id), }; + // A failing answer with nothing to ask or flag still holds the merge + // for a person. + if !finding.pass && finding.questions.is_empty() && finding.flags.is_empty() { + return self.check_failed(factory, id); + } let now = self.now(); let deadline = self .factories diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 2a0128e765..41c84ac058 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -3055,6 +3055,26 @@ fn a_refused_worker_start_stops_the_task_once_and_a_retry_starts_it() { ); } +#[test] +fn a_failing_check_with_nothing_to_ask_or_an_unreadable_diff_holds_the_merge() { + let mut h = Bench::new(false); + let f = h.factory(true); + let t = h.ready("Fails quietly", &[]); + h.world().drift.insert( + t.clone(), + json!({"pass": false, "questions": [], "flags": []}), + ); + h.done(&f, &t); + tick_until(&mut h, &f, &t, TaskState::MergeWaiting); + assert_eq!(h.task(&f, &t).gates, vec![Gate::CheckFailed]); + + let u = h.ready("No diff", &[]); + h.world().diff_failure = true; + h.done(&f, &u); + tick_until(&mut h, &f, &u, TaskState::MergeWaiting); + assert_eq!(h.task(&f, &u).gates, vec![Gate::CheckFailed]); +} + // ------------------------------------------------------------------ watch #[test] diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 6835856d6d..18be4675c4 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -90,6 +90,8 @@ pub struct World { /// Scripted watch answers, oldest first; no warnings when empty. pub watch: VecDeque, pub judge_down: bool, + /// The Task's diff cannot be read. + pub diff_failure: bool, /// Every judgment answers as failed with this reason. pub judgment_failure: Option, /// The environment diagnosis's answer; an unknown cause when absent. @@ -263,6 +265,9 @@ impl MergeTarget for Shared { Ok(vec!["src/lib.rs".into()]) } fn diff_text(&mut self, _factory: &Factory, task: &Task) -> Result { + if self.world().diff_failure { + return Err(Failure::task("git.diff", "unreadable")); + } Ok(format!("diff for {}", task.id)) } fn premerge(&mut self, _factory: &Factory, task: &Task) -> Result { From 6af707b9302baa5b15d4b70a7bdc606974b394d8 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:04:10 +0900 Subject: [PATCH 66/72] Read a person's first edit to an issue the Factory wrote against the body it wrote --- hide-factory/src/engine.rs | 10 ++++++++-- hide-factory/src/project.rs | 3 +-- hide-factory/src/store.rs | 7 +++++++ hide-factory/tests/engine.rs | 21 +++++++++++++++++++++ 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 453067c7f9..7bff777087 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -2097,7 +2097,13 @@ impl Engine { f.next_local_issue = f.next_local_issue.max(number + 1); } self.save_factory(factory_id); - self.with_task(factory_id, id, |task| task.issue = Some(issue)); + // The body it wrote is the one a later edit is read + // against, so the first edit a person makes counts. + let written = crate::store::body_hash(&body); + self.with_task(factory_id, id, |task| { + task.issue = Some(issue); + task.source_body_hash = Some(written); + }); } Err(failure) => { self.external_failure(factory_id, Some(id), &failure); @@ -5266,7 +5272,7 @@ impl Engine { t.issue = Some(issue.clone()); t.label_path = true; t.writes.insert("label".into()); - t.source_body_hash = Some(sha256_hex(body.as_bytes())); + t.source_body_hash = Some(crate::store::body_hash(&body)); }); self.add_question( factory_id, diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 6a4922ed28..f781cbdb5b 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -17,7 +17,6 @@ use crate::adapters::*; use crate::engine::{MERGE_COMMIT_AGAIN_MS, task_marker}; use crate::exec::{Runner, checked, classify}; use crate::model::*; -use crate::store::sha256_hex; use crate::verify::{Job, Prepare, VerifyRunner}; /// Local issues (`L-`) for a project without GitHub, owned by the core. @@ -732,7 +731,7 @@ impl TaskSource for SharedProjects { for (number, issue) in &labelled { let issue_ref = IssueRef::Github { number: *number }; let body = issue["body"].as_str().unwrap_or_default(); - let hash = sha256_hex(body.as_bytes()); + let hash = crate::store::body_hash(body); match held.get(number) { None => { if issue["state"].as_str() == Some("OPEN") diff --git a/hide-factory/src/store.rs b/hide-factory/src/store.rs index e81e4a36d5..e8385be855 100644 --- a/hide-factory/src/store.rs +++ b/hide-factory/src/store.rs @@ -408,6 +408,13 @@ pub fn sha256_hex(bytes: &[u8]) -> String { hex(&Sha256::digest(bytes)) } +/// An issue body's identity: line endings and surrounding blank space do +/// not make an edit, so the body the Factory wrote matches what GitHub +/// answers for it. +pub fn body_hash(body: &str) -> String { + sha256_hex(body.replace("\r\n", "\n").trim().as_bytes()) +} + fn write_private(path: &Path, bytes: &[u8]) -> Result<(), StoreError> { let temporary = path.with_extension("partial"); { diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 41c84ac058..f7c5ed4f4e 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -2144,6 +2144,27 @@ fn an_outside_push_that_breaks_main_drafts_a_fix_and_never_reverts() { // ------------------------------------------------------------- outside work +#[test] +fn the_first_edit_to_an_issue_the_factory_wrote_sends_the_task_back_to_review() { + let mut h = Bench::new(true); + let f = github_factory(&mut h, MergeMode::Auto); + let a = h.ready("First", &[]); + let b = h.ready("Second", &[&a]); + assert_eq!(h.state(&f, &b), TaskState::Waiting); + assert!( + h.task(&f, &b).source_body_hash.is_some(), + "the written body is known" + ); + let issue = h.task(&f, &b).issue.unwrap(); + h.world().outside.push_back(OutsideEvent::BodyEdited { + issue, + body_hash: "edited".into(), + }); + h.advance(3 * MINUTE_MS); + h.engine.tick(); + assert_eq!(h.state(&f, &b), TaskState::Drafting, "re-reviewed (B52)"); +} + #[test] fn an_outside_pull_request_takes_a_running_task_and_its_merge_finishes_it() { let mut h = Bench::new(true); From d4150f5dcd50bda8de9d7910cd694085aae7e9b5 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:04:41 +0900 Subject: [PATCH 67/72] Drop a judgment that answers after its Task was cancelled or finished --- hide-factory/src/engine.rs | 25 +++++++++++++++++++++++++ hide-factory/tests/engine.rs | 19 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 7bff777087..64eaa25582 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -4586,6 +4586,31 @@ impl Engine { &answer.id, &output, ); + // A judgment that answers after its Task was cancelled, taken + // outside or finished asks nothing of a person. + if let Some(id) = task.as_deref() + && self.task(&factory, id).is_none_or(|t| { + matches!( + t.state, + TaskState::Cancelled | TaskState::Outside | TaskState::Done + ) + }) + { + if matches!(purpose, Purpose::Drift | Purpose::Check) + && let Some(count) = self + .checks_running + .get_mut(&(factory.clone(), id.to_owned())) + { + *count = count.saturating_sub(1); + } + self.record( + &factory, + Some(id), + "judgment.dropped", + json!({"purpose": format!("{purpose:?}")}), + ); + continue; + } match (&answer.outcome, purpose, task) { (JudgmentOutcome::Answered { value }, Purpose::Intake, Some(task)) => { self.apply_intake(&factory, &task, value) diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index f7c5ed4f4e..811d30e4da 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -309,6 +309,25 @@ fn a_review_refused_because_hide_ai_is_off_says_to_turn_it_on_once() { assert!(questions[0].contains("Hide AI를 켜고"), "{questions:?}"); } +#[test] +fn a_review_answering_after_its_task_was_cancelled_asks_nothing() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().hold_judgments = true; + h.world().judgment_failure = Some("transient".into()); + let id = h.add("Cancelled early", &[])["task"]["id"] + .as_str() + .unwrap() + .to_owned(); + let cancelled = h.op(Command::Cancel { task: id.clone() }); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + h.world().hold_judgments = false; + h.engine.tick(); + assert_eq!(h.state(&f, &id), TaskState::Cancelled); + assert_eq!(h.task(&f, &id).open_questions().count(), 0); + assert_eq!(h.op(Command::Inbox)["count"], 0); +} + #[test] fn a_review_that_cannot_run_keeps_the_task_drafting_and_asks_for_the_provider() { let mut h = Bench::new(false); From 37ef611da3b790befc337dc5332ea75eb4156b76 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:06:24 +0900 Subject: [PATCH 68/72] Read the machine before a start only when a start can happen, and again when a worker stops --- hide-factory/src/engine.rs | 25 +++++++++++++++++++------ hide-factory/tests/engine.rs | 20 ++++++++++++++++++++ hide-factory/tests/support/mod.rs | 3 +++ 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 64eaa25582..5ca8584830 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -3598,6 +3598,8 @@ impl Engine { /// Stops a worker; a refusal is recorded against its Task. fn stop_worker(&mut self, factory_id: &str, id: &str, worker: &WorkerRef) { + // A worker that ends frees disk and memory: read them again (B57). + self.hold_checked_at = None; if let Err(failure) = self.ports.workers.stop(worker) { self.external_failure(factory_id, Some(id), &failure); } @@ -4809,12 +4811,6 @@ impl Engine { if self.halt_until.is_some_and(|until| until > now) { return; } - // Rule 1: hold starts below the disk floor or at critical memory - // pressure; re-checked when a worker ends or a minute passes (B57). - let due = self - .hold_checked_at - .is_none_or(|at| now.saturating_sub(at) >= ENV_RECHECK_MS) - || self.hold_reason.is_none(); let mut candidates: Vec = self .all_tasks() .filter(|t| self.factories.get(&t.factory).is_some_and(|f| !f.closed)) @@ -4834,6 +4830,23 @@ impl Engine { .cmp(&(a.state == TaskState::Relanding)) .then_with(|| dag::slot_order(a, b)) }); + // Rule 1: hold starts below the disk floor or at critical memory + // pressure; re-checked when a worker ends or a minute passes (B57). + // Without a hold the machine is read before a start, and only when + // one can happen: a backlog waiting on full slots does not read the + // disk and fork `sysctl` on every tick. + let can_start = self.machine_max_workers > self.running_count() + || candidates.iter().any(|t| { + t.state == TaskState::Relanding + || self + .starting + .get(&(t.factory.clone(), t.id.clone())) + .is_some_and(|(_, next)| *next <= now) + }); + let due = self + .hold_checked_at + .is_none_or(|at| now.saturating_sub(at) >= ENV_RECHECK_MS) + || (self.hold_reason.is_none() && can_start); if due { self.hold_checked_at = Some(now); self.hold_reason = None; diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 811d30e4da..a912239d6a 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -2392,6 +2392,26 @@ fn three_failed_outside_reads_mark_the_board_stale_and_back_off() { // -------------------------------------------------------------- environment +#[test] +fn a_backlog_waiting_for_slots_reads_the_machine_once_a_minute() { + let mut h = Bench::new(false); + let f = h.factory(true); + set_workers(&mut h, &f, 1); + let running = h.ready("Running", &[]); + let _waiting = h.ready("Waiting", &[]); + assert_eq!(h.state(&f, &running), TaskState::Running); + let reads = h.world().disk_reads; + for _ in 0..20 { + h.advance(2_000); + h.engine.tick(); + } + assert!( + h.world().disk_reads <= reads + 1, + "{} reads in 40 s", + h.world().disk_reads - reads + ); +} + #[test] fn a_low_disk_holds_new_starts_and_the_hold_clears_on_recheck() { let mut h = Bench::new(false); diff --git a/hide-factory/tests/support/mod.rs b/hide-factory/tests/support/mod.rs index 18be4675c4..3de63e727a 100644 --- a/hide-factory/tests/support/mod.rs +++ b/hide-factory/tests/support/mod.rs @@ -90,6 +90,8 @@ pub struct World { /// Scripted watch answers, oldest first; no warnings when empty. pub watch: VecDeque, pub judge_down: bool, + /// How many times the free disk was read. + pub disk_reads: u32, /// The Task's diff cannot be read. pub diff_failure: bool, /// Every judgment answers as failed with this reason. @@ -539,6 +541,7 @@ impl Judge for Shared { impl Environment for Shared { fn disk_free(&mut self, _project: &str) -> Option { + self.world().disk_reads += 1; self.world().disk_free } fn memory_pressure(&mut self) -> MemoryPressure { From 63c06382a203933f897d7178b61988634247f788 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:07:00 +0900 Subject: [PATCH 69/72] Abort a revert that fails in the Factory's main worktree --- hide-factory/src/project.rs | 7 ++++++- hide-factory/tests/local_git.rs | 35 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index f781cbdb5b..48358783fa 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -1263,7 +1263,12 @@ impl MergeTarget for SharedProjects { args.extend(["-m", "1"]); } args.push(sha); - this.git("git.revert", &path, &args)?; + if let Err(failure) = this.git("git.revert", &path, &args) { + // A conflicting revert leaves its state in the Factory's own main + // worktree, and every later checkout there would fail on it. + let _ = this.git("git.revert", &path, &["revert", "--abort"]); + return Err(failure); + } let commit = this .git("git.revert", &path, &["rev-parse", "HEAD"])? .trim() diff --git a/hide-factory/tests/local_git.rs b/hide-factory/tests/local_git.rs index ce785096bf..2c7139ed62 100644 --- a/hide-factory/tests/local_git.rs +++ b/hide-factory/tests/local_git.rs @@ -263,6 +263,41 @@ fn a_local_task_is_verified_merged_checked_on_main_and_reverted_alone() { ); } +#[test] +fn a_revert_that_conflicts_leaves_the_factory_main_worktree_clean() { + let mut fx = fixture(); + let factory = factory(&fx.project, &["true"]); + let mut t = task(&fx, "T-1", "b.txt", "two\n"); + let run = fx.projects.start(&factory, &t).unwrap(); + assert_eq!(settle(&mut fx.projects, &factory, &run), VerifyPoll::Passed); + t.attempts.push(Attempt { + number: 1, + commit: run.commit.clone(), + started_at: 0, + stage: AttemptStage::Task, + outcome: Some(AttemptOutcome::Passed), + log: None, + }); + let sha = fx.projects.merge(&factory, &t, MergeMethod::Merge).unwrap(); + // A later change to the same file makes undoing the merge conflict. + write(&fx.project, "b.txt", "changed\n"); + git(&fx.project, &["add", "."]); + git(&fx.project, &["commit", "--quiet", "-m", "later"]); + assert!(fx.projects.revert(&factory, &t, &sha).is_err()); + let main = fx + .project + .with_file_name("repo.worktrees") + .join("factory-main"); + assert!(main.is_dir(), "{}", main.display()); + let pending = std::process::Command::new("git") + .args(["rev-parse", "-q", "--verify", "REVERT_HEAD"]) + .current_dir(&main) + .output() + .unwrap(); + assert!(!pending.status.success(), "no revert left in progress"); + assert_eq!(git(&main, &["status", "--porcelain"]), ""); +} + #[test] fn a_conflict_and_a_dirty_main_are_found_before_merge() { let mut fx = fixture(); From 8f541adb05cde424b2505d2a11dc7616acf07f39 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:07:32 +0900 Subject: [PATCH 70/72] Keep a card's external waits and open decisions when a re-add leaves them out --- hide-factory/src/engine.rs | 15 +++++++++++++-- hide-factory/tests/engine.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index 5ca8584830..d98f6e09ff 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -1467,9 +1467,20 @@ impl Engine { } else { card.out_of_scope.clone() }, - open_decisions: card.open_decisions.clone(), + // A re-add that leaves a list out keeps it, as for criteria. + open_decisions: if card.open_decisions.is_empty() { + existing + .map(|c| c.open_decisions.clone()) + .unwrap_or_default() + } else { + card.open_decisions.clone() + }, depends_on: depends, - external: card.external.clone(), + external: if card.external.is_empty() { + existing.map(|c| c.external.clone()).unwrap_or_default() + } else { + card.external.clone() + }, }) } diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index a912239d6a..35a2d3b432 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -398,6 +398,38 @@ fn review_questions_hold_the_task_until_answered_and_re_adding_is_idempotent() { assert_eq!(h.writes("issue.create").len(), 1); } +#[test] +fn a_re_add_that_leaves_lists_out_keeps_them() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.world().hold_judgments = true; + let first = h.op(Command::Add { + project: None, + task: None, + issue: None, + card: CardInput { + external: vec!["other/repo#7".into()], + open_decisions: vec!["Which format?".into()], + ..card("Lists", &[]) + }, + producer_pane: None, + }); + let id = first["task"]["id"].as_str().unwrap().to_owned(); + h.op(Command::Add { + project: None, + task: Some(id.clone()), + issue: None, + card: CardInput { + goal: Some("Make Lists work".into()), + ..CardInput::default() + }, + producer_pane: None, + }); + let card = h.task(&f, &id).card; + assert_eq!(card.external, vec!["other/repo#7".to_owned()]); + assert_eq!(card.open_decisions, vec!["Which format?".to_owned()]); +} + #[test] fn a_re_add_keeps_a_dependency_a_person_added() { let mut h = Bench::new(false); From 31f7d9076f195a64f4948e7d12df9a3a75d11912 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:07:50 +0900 Subject: [PATCH 71/72] Describe the code review fixes in the Factory guide --- docs/factory.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 64689eb2ac..30df59cb34 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -180,7 +180,7 @@ Each open Factory is a code-owned recipient named `factory:` in the - A pane may send to `factory:` and may name it as a watch observer, and it can address the Factory by that name only. A pane or agent can never register under a name or pane that starts with `factory:`. - The engine reads its letters from the ledger on each tick, up to 16 at a time, applies each once, and confirms it. A request or block letter also gets a reply carrying the engine's JSON answer. No composer input or doorbell is involved. - The letter's sender must be a live worker of that Factory, or the letter is refused with `sender_not_a_worker` and logged. -- A worker's CLI report is a typed body `{"factory": }` sent under an intent made from the pane and the body, so a retry applies once. A harness that follows the letter protocol only is read as a question (a `request` or `block` letter becomes a blocking question with a 24 hour deadline, taking a `Recommendation:`, `Suggestion:`, `추천:` or `제안:` line as the suggestion) or as a completion (a `report` letter becomes `done`). +- A worker's CLI report is a typed body `{"factory": }` sent under an intent made from the pane, the Task's current state time and the body, so a retry in the same state applies once and the same report after the Task moved (a `done` again once verification sent it back) is a new letter. A harness that follows the letter protocol only is read as a question (a `request` or `block` letter becomes a blocking question with a 24 hour deadline, taking a `Recommendation:`, `Suggestion:`, `추천:` or `제안:` line as the suggestion) or as a completion (a `report` letter becomes `done`). - A watch whose observer is the Factory warns after the Factory's `stall_minutes` (30 by default) instead of 20; the host hands each open Factory's window to the watch readings, so a change applies at the next reading. The engine turns the first warning into a stalled stop; it does not wait for the second warning or for the human notice, which the ledger skips for a code-owned recipient. - The Factory writes to a worker with `report` letters, and starts a watch on the worker again each time it does, because a report to its parent ends the sender's watch. @@ -238,6 +238,8 @@ The review sees only the card, its attachment, the repository's file names and g Adding again with `--task ` or the same issue updates the same Task and reviews it again; the same content changes nothing. A re-add on a Task that already runs does not rewrite its card: it adds a scope-change question that a person approves or rejects. A re-add adds dependencies but never drops one the review or a person added, so a producer that resends the card it knows changes nothing; removing a dependency is a person's `dep remove`. +A re-add that leaves out criteria, out-of-scope items, open decisions or external waits keeps the card's. +`dep add` names a Task of the same Factory as the Task it changes, and a watch warning names a Task of the Factory it watched; a warning naming none is only logged. The producer's open decisions become intake questions, and a Task is Ready only when the review is done and no question besides a notice is open. Ready creates the issue: a GitHub Task gets an issue labelled `factory` whose body carries a hidden Task marker, the goal, the criteria and the out-of-scope items, and a local Task gets an `L-`. A Task added from an existing issue gets the label instead. @@ -260,7 +262,8 @@ A drift question keeps the Task in `verifying`, does not wake the worker, and ho A judgment that cannot run is never skipped and never read as a pass. A failed review marks the Task and puts a retry-or-cancel question in the inbox, and `add` answers `pending`. While Hide AI is off or no agent is chosen to run it, every judgment fails as `disabled`, and the question says to turn it on in Settings › Hide AI. -A failed drift or check sends the Task to `merge_waiting` for a person. +A failed drift or check sends the Task to `merge_waiting` for a person, and so does a check that answers `pass: false` with nothing to ask or flag, or one that cannot read the Task's diff. +A judgment that answers after its Task was cancelled, taken outside or finished is dropped and logged as `judgment.dropped`. A failed watch or diagnosis changes no Task and is logged. The Factory has its own judgment queue on its own router (see [AI_PROVIDERS.md](AI_PROVIDERS.md#the-factorys-judgments)): one request in flight, intake reviews before every other judgment, and 16 waiting judgments per Factory. @@ -341,6 +344,7 @@ A red result breaks main and stops auto merge; manual merges still run. While main is broken an `auto` Task that passed verification waits in `verifying` without merge-tree or quick-check reads, unless a person's gate sends it to `merge_waiting`; main is read again every 30 seconds. If the broken commit is among the Factory's own merges since the last green, the Factory finds the first failing one, asking again for runs that were skipped or cancelled, and reverts that merge alone. On GitHub the revert is a pull request from `factory/revert-`, which the Factory force-pushes, checks and merges with `--merge`; locally it is a revert commit made in `factory-main` and fast-forwarded into the primary checkout, only while that checkout is on the default branch and clean, as for a Task merge. +A revert that conflicts is aborted in `factory-main`, so that worktree stays usable for main verification and the next revert. A revert whose verification passes is merged on its own, and the original Task becomes `relanding`: it runs again in the same worktree and session on the latest main, with a new pull request. When the failing commit is not the Factory's, nothing is reverted: the Factory drafts a fix Task for a person to confirm and stops auto merge. Auto merge resumes when the head of main verifies green again. @@ -358,7 +362,7 @@ A held issue missing from that list is looked up by number, at most 20 per read | A pull request the Factory did not open closes a Task's issue, and it is open | A pull request one of the Factory's own Tasks opened never counts, whatever its worker wrote; the decisions a worker records sit in a code block in its pull request body, so a "Fixes #N" there stays text. GitHub can still close another Task's issue from a closing keyword a worker put in a commit message or in a card it proposed, when that merge lands; the other Task is then cancelled and kept for revive. A pull request from a fork counts only once it is merged, since anyone can open one. Otherwise the Task becomes `outside`. A running worker is stopped, its worktree stays for the keep period, and a notice offers `revive`. | | That pull request merges | The Task is `done`, and a dependent Task's predecessor counts as merged. A stopped worker's worktree still waits out its keep period. | | The issue closes with no pull request, or the `factory` label is removed | The Task is cancelled with a notice, kept for the keep period. | -| A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. | +| A person edits the issue body | A Task before its start goes back to `drafting` and is reviewed again. A running Task gets a scope-change question. The body is compared with the one the Factory wrote, ignoring line endings and surrounding space, so the first edit counts. | | A person labels an issue the Factory does not hold | A new Task is drafted from the issue, and a person confirms its card in the inbox before it is Ready. The body is not edited. | | A finished Task's issue reopens | A notice only. | | A push to main the Factory did not make | Main verification runs; while its checks are still running the head is read again every 30 seconds, and a red result takes the outside-push path above. | @@ -412,7 +416,7 @@ An autonomy Task is reviewed like any other, may not propose Tasks, and gates to An environment problem is not a Task's failure and is never counted against it. -- **Before a start.** Starts hold while free disk at the first waiting Task's project is under `disk_floor_gb` (20 by default), or while macOS reports critical memory pressure. Warn pressure starts normally, and other systems report normal. The held Tasks show the reason and are checked again after a minute. +- **Before a start.** Starts hold while free disk at the first waiting Task's project is under `disk_floor_gb` (20 by default), or while macOS reports critical memory pressure. Warn pressure starts normally, and other systems report normal. The held Tasks show the reason and are checked again after a minute or when a worker stops; without a hold the machine is read only on a tick where a start can happen, so a backlog waiting on full slots is not read every tick. - **At a failure.** Only a structured signal makes a failure the environment's: no space left on the device, exit 137, a GitHub 401, 403, 429 or 5xx answer, a network error, or a Herdr connection error. The adapters read the GitHub and git signals from the command's exit code and its stderr text. Everything else is the Task's. A runtime's usage limit comes from the core's provider usage rows (the toolbar's Weekly Usage reader): a main row or bucket at 100 percent with a reset ahead parks that runtime until the reset, new starts of an unpinned Task use the other runtime, and a worker that ends its turn without a report while its runtime is limited waits for a slot instead of stopping. The rows refresh every 5 minutes only while a window shows them, so a daemon with no window open learns of a limit late. - **Code handles each signal first.** Disk full holds starts and removes the worktrees of finished Tasks and cancelled Tasks past their keep period. Out-of-memory and Herdr connection errors send the Task back to `waiting`. A rate-limit, server or network error backs the read off as above. A 401 or 403 puts a notice in the inbox once, naming `gh auth login` or `gh auth refresh -s `, and the Factory does not perform that action or retry it. - **Cascade.** Three different Tasks failing the same check or command within 30 minutes are read as the environment: each failure is taken back, the Tasks go to `waiting`, and new starts halt for 30 minutes. From 3988c4e28a682d99cf4edafa118e9d00455c2cc2 Mon Sep 17 00:00:00 2001 From: yansfil Date: Wed, 7 Oct 2026 09:26:02 +0900 Subject: [PATCH 72/72] Hold the merge only on merge checks, log why a check failed, read the machine only when a runtime can start, and report a failed revert abort --- docs/factory.md | 2 +- herdr-core/src/factory.rs | 6 ++-- hide-factory/src/engine.rs | 45 ++++++++++++++++++--------- hide-factory/src/project.rs | 9 ++++-- hide-factory/tests/engine.rs | 60 ++++++++++++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 21 deletions(-) diff --git a/docs/factory.md b/docs/factory.md index 30df59cb34..f9bfcc211f 100644 --- a/docs/factory.md +++ b/docs/factory.md @@ -416,7 +416,7 @@ An autonomy Task is reviewed like any other, may not propose Tasks, and gates to An environment problem is not a Task's failure and is never counted against it. -- **Before a start.** Starts hold while free disk at the first waiting Task's project is under `disk_floor_gb` (20 by default), or while macOS reports critical memory pressure. Warn pressure starts normally, and other systems report normal. The held Tasks show the reason and are checked again after a minute or when a worker stops; without a hold the machine is read only on a tick where a start can happen, so a backlog waiting on full slots is not read every tick. +- **Before a start.** Starts hold while free disk at the first waiting Task's project is under `disk_floor_gb` (20 by default), or while macOS reports critical memory pressure. Warn pressure starts normally, and other systems report normal. The held Tasks show the reason and are checked again after a minute or when a worker stops; without a hold the machine is read on a tick where a start can happen (a free slot and a runtime not at its usage limit) and otherwise once a minute, so a backlog waiting on full slots is not read every tick. - **At a failure.** Only a structured signal makes a failure the environment's: no space left on the device, exit 137, a GitHub 401, 403, 429 or 5xx answer, a network error, or a Herdr connection error. The adapters read the GitHub and git signals from the command's exit code and its stderr text. Everything else is the Task's. A runtime's usage limit comes from the core's provider usage rows (the toolbar's Weekly Usage reader): a main row or bucket at 100 percent with a reset ahead parks that runtime until the reset, new starts of an unpinned Task use the other runtime, and a worker that ends its turn without a report while its runtime is limited waits for a slot instead of stopping. The rows refresh every 5 minutes only while a window shows them, so a daemon with no window open learns of a limit late. - **Code handles each signal first.** Disk full holds starts and removes the worktrees of finished Tasks and cancelled Tasks past their keep period. Out-of-memory and Herdr connection errors send the Task back to `waiting`. A rate-limit, server or network error backs the read off as above. A 401 or 403 puts a notice in the inbox once, naming `gh auth login` or `gh auth refresh -s `, and the Factory does not perform that action or retry it. - **Cascade.** Three different Tasks failing the same check or command within 30 minutes are read as the environment: each failure is taken back, the Tasks go to `waiting`, and new starts halt for 30 minutes. diff --git a/herdr-core/src/factory.rs b/herdr-core/src/factory.rs index f891ade921..a1391e4ed1 100644 --- a/herdr-core/src/factory.rs +++ b/herdr-core/src/factory.rs @@ -515,9 +515,6 @@ fn publish_recipients(engine: Option<&Engine>, runtime: &Weak>) { } } -/// Runs one command with the caller's role (D-33). A worker's report travels -/// as a ledger letter from its own pane, so a harness that only speaks the -/// letter protocol lands on the same path (B25). /// The delivery intent of a worker's report. A retry of the same report in /// the same Task state is one letter; the same words after the Task moved /// (a `done` again once verification sent it back) are a new report. @@ -538,6 +535,9 @@ fn hide_program() -> Option { .then(|| program.to_string_lossy().into_owned()) } +/// Runs one command with the caller's role (D-33). A worker's report travels +/// as a ledger letter from its own pane, so a harness that only speaks the +/// letter protocol lands on the same path (B25). fn handle( engine: &mut Engine, runtime: &Weak>, diff --git a/hide-factory/src/engine.rs b/hide-factory/src/engine.rs index d98f6e09ff..d2a7e423dc 100644 --- a/hide-factory/src/engine.rs +++ b/hide-factory/src/engine.rs @@ -2905,8 +2905,11 @@ impl Engine { }; // A diff that cannot be read gives the checks nothing to judge; that // is a check that cannot run, never a pass (B68). - let Ok(diff) = self.ports.merge.diff_text(&f, &task) else { - return self.check_failed(factory, id); + let diff = match self.ports.merge.diff_text(&f, &task) { + Ok(diff) => diff, + Err(failure) => { + return self.check_failed(factory, id, &format!("diff: {}", failure.detail)); + } }; let mut count = 0; let decisions = task.decisions.iter().map(|d| d.text.clone()).collect(); @@ -2930,7 +2933,7 @@ impl Engine { ); count += 1; } - Err(_) => self.check_failed(factory, id), + Err(failure) => self.check_failed(factory, id, &format!("submit: {}", failure.stage)), } for (index, check) in f .config @@ -2958,7 +2961,9 @@ impl Engine { ); count += 1; } - Err(_) => self.check_failed(factory, id), + Err(failure) => { + self.check_failed(factory, id, &format!("submit: {}", failure.stage)) + } } } self.checks_running @@ -2966,24 +2971,28 @@ impl Engine { } /// A check that could not run is never skipped: merge waits for a person (B68). - fn check_failed(&mut self, factory: &str, id: &str) { + fn check_failed(&mut self, factory: &str, id: &str, reason: &str) { self.with_task(factory, id, |task| { if !task.gates.contains(&Gate::CheckFailed) { task.gates.push(Gate::CheckFailed); } }); - self.record(factory, Some(id), "check.failed", json!({})); + self.record(factory, Some(id), "check.failed", json!({"reason": reason})); } - fn apply_finding(&mut self, factory: &str, id: &str, value: &Value) { + /// `holds_merge` is true for the drift and after-done checks; a + /// periodic check on a running Task only asks and flags (B67). + fn apply_finding(&mut self, factory: &str, id: &str, value: &Value, holds_merge: bool) { let finding = match judgment::parse_finding(value) { Ok(finding) => finding, - Err(_) => return self.check_failed(factory, id), + Err(reason) if holds_merge => return self.check_failed(factory, id, &reason), + Err(_) => return, }; // A failing answer with nothing to ask or flag still holds the merge // for a person. - if !finding.pass && finding.questions.is_empty() && finding.flags.is_empty() { - return self.check_failed(factory, id); + if holds_merge && !finding.pass && finding.questions.is_empty() && finding.flags.is_empty() + { + return self.check_failed(factory, id, "failed with nothing to ask"); } let now = self.now(); let deadline = self @@ -4660,16 +4669,18 @@ impl Engine { } } JudgmentOutcome::Answered { value } => { - self.apply_finding(&factory, &task, value) + self.apply_finding(&factory, &task, value, true) } JudgmentOutcome::Failed { .. } if drafting => {} - JudgmentOutcome::Failed { .. } => self.check_failed(&factory, &task), + JudgmentOutcome::Failed { reason } => { + self.check_failed(&factory, &task, reason) + } } self.advance_merge(&factory, &task); } (JudgmentOutcome::Answered { value }, Purpose::Periodic, Some(task)) => { match judgment::parse_finding(value) { - Ok(_) => self.apply_finding(&factory, &task, value), + Ok(_) => self.apply_finding(&factory, &task, value, false), Err(_) => self.record( &factory, Some(&task), @@ -4846,7 +4857,13 @@ impl Engine { // Without a hold the machine is read before a start, and only when // one can happen: a backlog waiting on full slots does not read the // disk and fork `sysctl` on every tick. - let can_start = self.machine_max_workers > self.running_count() + let usable = |runtime: Runtime| { + self.runtime_blocked + .get(&runtime) + .is_none_or(|until| *until <= now) + }; + let can_start = (self.machine_max_workers > self.running_count() + && (usable(Runtime::Claude) || usable(Runtime::Codex))) || candidates.iter().any(|t| { t.state == TaskState::Relanding || self diff --git a/hide-factory/src/project.rs b/hide-factory/src/project.rs index 48358783fa..5000fd1d53 100644 --- a/hide-factory/src/project.rs +++ b/hide-factory/src/project.rs @@ -1263,10 +1263,13 @@ impl MergeTarget for SharedProjects { args.extend(["-m", "1"]); } args.push(sha); - if let Err(failure) = this.git("git.revert", &path, &args) { + if let Err(mut failure) = this.git("git.revert", &path, &args) { // A conflicting revert leaves its state in the Factory's own main - // worktree, and every later checkout there would fail on it. - let _ = this.git("git.revert", &path, &["revert", "--abort"]); + // worktree, and every later checkout there would fail on it; an + // abort that fails too is named in the failure a person reads. + if let Err(abort) = this.git("git.revert", &path, &["revert", "--abort"]) { + failure.detail = format!("{}; abort failed: {}", failure.detail, abort.detail); + } return Err(failure); } let commit = this diff --git a/hide-factory/tests/engine.rs b/hide-factory/tests/engine.rs index 35a2d3b432..e3f0f81260 100644 --- a/hide-factory/tests/engine.rs +++ b/hide-factory/tests/engine.rs @@ -2444,6 +2444,27 @@ fn a_backlog_waiting_for_slots_reads_the_machine_once_a_minute() { ); } +#[test] +fn a_backlog_held_by_usage_limits_reads_the_machine_once_a_minute() { + let mut h = Bench::new(false); + let f = h.factory(true); + let until = h.world().now + 60 * MINUTE_MS; + h.world().usage_limits.insert(Runtime::Claude, until); + h.world().usage_limits.insert(Runtime::Codex, until); + let t = h.ready("Limited", &[]); + assert_eq!(h.state(&f, &t), TaskState::Waiting); + let reads = h.world().disk_reads; + for _ in 0..20 { + h.advance(2_000); + h.engine.tick(); + } + assert!( + h.world().disk_reads <= reads + 1, + "{} reads in 40 s", + h.world().disk_reads - reads + ); +} + #[test] fn a_low_disk_holds_new_starts_and_the_hold_clears_on_recheck() { let mut h = Bench::new(false); @@ -3165,6 +3186,45 @@ fn a_failing_check_with_nothing_to_ask_or_an_unreadable_diff_holds_the_merge() { h.done(&f, &u); tick_until(&mut h, &f, &u, TaskState::MergeWaiting); assert_eq!(h.task(&f, &u).gates, vec![Gate::CheckFailed]); + let failed = h + .engine + .events(&f, Some(&u), 50) + .into_iter() + .find(|e| e.kind == "check.failed") + .unwrap(); + assert!( + failed.detail["reason"] + .as_str() + .unwrap() + .starts_with("diff"), + "the log says what failed: {}", + failed.detail + ); +} + +#[test] +fn a_periodic_check_failing_with_nothing_to_ask_holds_nothing() { + let mut h = Bench::new(false); + let f = h.factory(true); + h.op(Command::Check { + project: None, + at: CheckPoint::Periodic, + instruction: "Still on track?".into(), + }); + let t = h.ready("Running", &[]); + h.world().drift.insert( + t.clone(), + json!({"pass": false, "questions": [], "flags": []}), + ); + h.advance(30 * 60_000); + h.engine.tick(); + h.engine.tick(); + assert!( + h.task(&f, &t).gates.is_empty(), + "{:?}", + h.task(&f, &t).gates + ); + assert_eq!(h.state(&f, &t), TaskState::Running); } // ------------------------------------------------------------------ watch