diff --git a/Cargo.lock b/Cargo.lock index 4a4dfe36ec..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", @@ -1225,6 +1226,18 @@ dependencies = [ "tempfile", ] +[[package]] +name = "hide-factory" +version = "0.1.0" +dependencies = [ + "hide-platform", + "rusqlite", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", +] + [[package]] name = "hide-herdr-client" version = "0.1.0" @@ -1333,6 +1346,7 @@ dependencies = [ "getrandom 0.2.16", "herdr-core", "hex", + "hide-factory", "hide-herdr-client", "hide-host", "hide-kit", 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/docs/AI_PROVIDERS.md b/docs/AI_PROVIDERS.md index d15b6bcefb..54664d09b2 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 @@ -236,6 +236,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`. @@ -338,7 +346,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 `ai.request.finished` of a provider that declares itself measurable (`AiBackend::measurable()`, today only codex, whose app-server is resident) 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 6d0bc89183..8fbe00333b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -872,6 +872,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, 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. +`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/PERFORMANCE_TESTING.md b/docs/PERFORMANCE_TESTING.md index df30172410..6467de893c 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, 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/README.md b/docs/README.md index 910ceb0232..3ef2a20f2f 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 seven agents' skill, guidance hook and Herdr integration, the retirement stage and the one-time retirement of thirteen former agents, 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/retired_agents.rs` the thirteen former agents, `src/herdr_integration.rs` Herdr's integrations), `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` 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 7cbb6849c0..07c47c3658 100644 --- a/docs/agent-hooks.md +++ b/docs/agent-hooks.md @@ -34,7 +34,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. @@ -183,7 +183,7 @@ Two pieces are written per agent into the agent's own files, and nothing else; a - 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 9a7beffd0c..ac31473ad3 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; 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 | @@ -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 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 `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..f9bfcc211f --- /dev/null +++ b/docs/factory.md @@ -0,0 +1,689 @@ +# 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). +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 | +| --- | --- | +| `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. | +| `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. +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. +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. + +`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 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. +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. + +## 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 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 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, 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. + +| 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 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. + +## 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, 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. + +## 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 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. +- **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. +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. +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` 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 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". + +## 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. +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. +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), 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 | +| `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`. +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, 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. +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 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 + +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`. +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. + +**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 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. + +**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. | +| `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 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 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. + +**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 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`. +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. +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. +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. +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 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. 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. | + +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, 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, 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. | +| `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 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. +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 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. +- **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, except the start hold and the runtime switch, which belong to the machine. + +| Action | Does | +| --- | --- | +| `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 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. +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, 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. +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 (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, 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 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 | +| `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 `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, 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. | +| `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 (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`. + +## 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. +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`** + +| 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`. | +| `waiting_code` | The same as a `WaitingFor` code. | +| `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. | +| `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. | +| `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. | +| `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. +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. +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. +`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. | +| `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. | + +**`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. | + +### 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`. +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 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/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 def79bd944..d401911f89 100644 --- a/herdr-core/src/ai.rs +++ b/herdr-core/src/ai.rs @@ -208,6 +208,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_by_provider(), None), + 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..537e73e00d 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| { @@ -102,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 @@ -185,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/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..f765173299 100644 --- a/herdr-core/src/delivery/watch.rs +++ b/herdr-core/src/delivery/watch.rs @@ -68,6 +68,17 @@ impl Watch { } } +/// How long a watch waits before its first warning: a Factory observer +/// 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 + } else { + INACTIVITY_MS + } +} + pub fn start( ledger: &mut Ledger, parent: &Actor, @@ -172,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)] @@ -279,7 +293,12 @@ pub fn tick(ledger: &mut Ledger, readings: &[Reading], now: u64) -> Result now.saturating_sub(activity) >= INACTIVITY_MS, + (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, }; @@ -414,6 +433,7 @@ mod tests { session_modified_at_unix_ms: None, failure: None, gone: false, + inactivity_ms: None, } } @@ -539,6 +559,33 @@ 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 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(); @@ -666,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 2fa404003d..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; @@ -688,6 +691,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 +729,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 +760,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()); } } @@ -942,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 new file mode 100644 index 0000000000..a1391e4ed1 --- /dev/null +++ b/herdr-core/src/factory.rs @@ -0,0 +1,1838 @@ +//! 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::{BTreeMap, 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, Removal, + 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, + /// 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: 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, + /// A Factory's own agent is above the caller. + pub factory_spawned: 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, + factory_spawned: false, + } + } +} + +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, + /// 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, +} + +/// 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; + +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. +/// 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, + 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); + 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, + Finished { + fresh: job.resume.is_none(), + result: result.clone(), + }, + ); + false + } + }; + if abandoned && let Ok(worker) = result { + 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") + } + } +} + +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, + runtime: Weak>, + requests: Receiver, + 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); + let stop = Arc::clone(&stop); + thread::Builder::new() + .name("factory-starts".into()) + .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; + 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(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}) + ); + 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); + let mut port = CoreWorkers { + runtime: runtime.clone(), + state: Arc::clone(&workers), + }; + 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 { + let _ = waiter + .reply + .send(engine.add_answer(&waiter.factory, &waiter.task)); + return false; + } + true + }); + } + drop(engine); + drop(judge); + // 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; + } + 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 { + 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: BTreeMap = engine + .into_iter() + .flat_map(Engine::factories) + .filter(|factory| !factory.closed) + .map(|factory| (factory.id.clone(), factory.config.stall_ms)) + .collect(); + if let Some(runtime) = lock(runtime) { + guard(&runtime).set_factory_recipients(ids); + } +} + +/// 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 { + 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()) +} + +/// 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 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, + factory_spawned: caller.ancestors.factory_spawned, + }; + 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. + // 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, + task, + issue, + card, + producer_pane: _, + } => Command::Add { + 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 { + Command::Ask { .. } | Command::Propose { .. } => Some("request"), + Command::Block { .. } => Some("block"), + Command::Done { .. } => Some("report"), + _ => None, + }; + 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 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( + 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 { + /// 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, Removal::Discarded); + } + 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 + .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")) + } + + 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 { + /// 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); + if let Some(answer) = poll_start(&self.state, &key) { + return answer; + } + 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")); + } + drop(runtime); + Err(queue_start(&self.state, request)) + } + + fn abandon_start(&mut self, factory: &str, task: &str) -> bool { + let key = start_key(factory, task); + let (in_flight, finished) = match self.state.lock() { + Ok(mut state) => { + let in_flight = state.starts.in_flight.contains(&key); + if in_flight { + state.starts.abandoned.insert(key.clone()); + } + (in_flight, state.starts.done.remove(&key)) + } + Err(_) => (false, None), + }; + let taken = in_flight || finished.is_some(); + if let Some(Finished { + fresh, + result: Ok(worker), + }) = finished + { + self.release_start(task, fresh, &worker); + } + taken + } + + 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); + let intent = format!("factory-wake-{}-{}", pane, now_ms()); + 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 { + 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> { + // 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.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) + .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, 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)), + }; + // 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); + 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 Some(root) = root else { + return Ok(()); + }; + // 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 discard { + hide_factory::exec::checked( + &mut runner, + "branch.delete", + "git", + &["branch", "-D", "--", &worker.branch], + Some(&root), + )?; + } + Ok(()) + } + + fn usage_limited(&mut self, runtime: AgentRuntime) -> Option { + let core = self.runtime().ok()?; + guard(&core).factory_usage_limit(runtime.as_str(), now_ms()) + } +} + +/// 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")) +} + +/// One worker start through the coordination path, on the starter thread. +fn start_worker( + runtime: &Weak>, + 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, + }, + ); + } + // Stable per previous worker and attempt, so a start that is + // asked again continues the same spawn (rule 11). + ( + format!( + "factory-{}-{}-r{}-a{}", + request.factory, request.task, previous.started_at, request.attempt + ), + 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 + // 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) + } + // 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), + } +} + +/// 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, + }); + } + } +} + +#[cfg(test)] +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(), + 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()); + } + + 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"); + 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") + .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", + "-c", + "commit.gpgsign=false", + "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/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 46614adb79..9a8e511697 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 743b01e5f9..11959e9f0f 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; @@ -1059,6 +1060,10 @@ 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. + /// 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,6 +1781,7 @@ impl Runtime { delivery_ledger, delivery_client: None, delivery_observations: HashMap::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 0a6dfe33dc..b9f12432c1 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,58 @@ impl Runtime { changed } + /// The Factory host publishes which Factories exist. + /// 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 + /// 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_key(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) @@ -516,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() @@ -958,6 +1050,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(), 30 * 60_000)].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..d7e129573b --- /dev/null +++ b/herdr-core/src/runtime/factory.rs @@ -0,0 +1,515 @@ +//! 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, +} + +/// 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. + 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), + }; + let claimed = hint + .filter(|hint| pane.as_deref() != Some(*hint)) + .map(str::to_owned); + let ancestors = pane + .as_deref() + .or(claimed.as_deref()) + .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()), + claimed, + ancestors, + }) + } + + /// 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) -> crate::factory::Lineage { + let mut lineage = crate::factory::Lineage { + complete: false, + ..crate::factory::Lineage::none() + }; + let Ok(ledger) = self.delivery_state() else { + return lineage; + }; + // 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. + // 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() + } + None => None, + }; + while let Some(id) = next { + if lineage.agents.len() >= LINEAGE_LIMIT || lineage.agents.contains(&id) { + return lineage; + } + let Some(agent) = ledger.agents.iter().find(|agent| agent.id == id) else { + lineage.agents.push(id); + return lineage; + }; + lineage.agents.push(id); + 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; + lineage + } + + /// 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() + } + + /// 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 + } + + /// 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::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: 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, + } + } + + #[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() + })); + let full = runtime.factory_lineage("w3:p1"); + assert_eq!( + full.agents, + vec!["agent-child", "agent-worker", "agent-factory"] + ); + assert_eq!(full.panes, vec!["w2:p1", "w1:p1", "factory:f-1"]); + 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"); + 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"); + assert!(!looped.factory_spawned); + } + + #[test] + 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; + 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() + })); + // 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!( + live.agents, + vec!["agent-child", "agent-worker", "agent-factory"] + ); + 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(), + 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-agent-hooks/src/runtime.rs b/hide-agent-hooks/src/runtime.rs index f0eabbbae5..6f2c9948d5 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) @@ -393,6 +393,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/Cargo.toml b/hide-factory/Cargo.toml new file mode 100644 index 0000000000..f1c5806951 --- /dev/null +++ b/hide-factory/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "hide-factory" +version = "0.1.0" +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" +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..c8c75e9838 --- /dev/null +++ b/hide-factory/src/adapters.rs @@ -0,0 +1,413 @@ +//! 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, + /// 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 { + 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, + 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") + } + } + + pub fn starting(stage: &str, detail: impl Into) -> Self { + Self { + starting: true, + ..Self::task(stage, detail) + } + } + + 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, + starting: false, + again_in_ms: 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, + /// 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. + 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). +#[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; + 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, + /// 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)] +#[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; + /// 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). + 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>; + /// 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). + 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, + /// The runtime's extra arguments from the Factory's configuration. + 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)] +#[serde(rename_all = "snake_case")] +pub enum WorkerStatus { + Working, + /// At rest (idle or done) since the given time. + Resting { + since: UnixMs, + }, + Blocked, + 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; + /// 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. 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, + 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 (B43, B62, B71); the remote branch stays + /// (D-58). Removing what is already gone succeeds. + fn remove_worktree( + &mut self, + worker: &crate::model::WorkerRef, + removal: Removal, + ) -> 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, factory: &str, 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..a32d00b965 --- /dev/null +++ b/hide-factory/src/command.rs @@ -0,0 +1,582 @@ +//! 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, + /// 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 { + 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 ...] [--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."; + +/// 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( + &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") + && 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")); + } + 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 +} + +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!( + "{} {} 정리 중 {} · 대기 {} · 실행 중 {} · 완료 오늘 {} 내 차례 {}\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 card = &task["card"]; + let mut text = format!( + "{} {} [{}]\n", + 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() { + 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"), + card["display_id"].as_str().unwrap_or("?"), + chain("after") + )); + if let Some(external) = card["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["verification"].as_str().unwrap_or("?") + )); + if let Some(pr) = task["pr"]["url"].as_str() { + text.push_str(&format!(" PR {pr}")); + } + 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", + 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("") + )); + } + 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 +} + +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/engine.rs b/hide-factory/src/engine.rs new file mode 100644 index 0000000000..d2a7e423dc --- /dev/null +++ b/hide-factory/src/engine.rs @@ -0,0 +1,6486 @@ +//! 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::cell::RefCell; +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, Removal, 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::{Permission, ROLE_NOT_ALLOWED, Role}; +use crate::store::{Event, Record, 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; +/// 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; +/// 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, close and reopen", + "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; +/// 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 { + run: VerifyRun, + 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. + Bisecting { + index: usize, + }, + Reverting { + revert: RevertRef, + task: String, + }, +} + +/// 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, + 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, + /// 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, + /// 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>, + /// 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 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. + env_failures: Vec, + /// 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, + /// 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, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +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, + /// The board the watch read, as of this time. + Watch { + read_at: UnixMs, + }, + Env, +} + +type Reply = Result; + +fn refuse(reason: &str, next: &str) -> Refusal { + Refusal::new(reason, next) +} + +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()?; + 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(), + store_failures: RefCell::new(StoreFailures::default()), + 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(), + 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(), + hide_program: "hide".into(), + starting: 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); + } + } + // 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) + } + + 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 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", + )) + } + // 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(), + }), + } + } + + /// 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.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); + 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 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.as_ref().filter(|_| !task.purged) else { + return false; + }; + if pane.is_some() && worker.pane.as_deref() == pane { + return true; + } + !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> { + 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 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, + /// 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.store_failed(factory, task, "record", &error.0); + 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) + { + self.store_failed(id, None, "factory", &error.0); + 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.store_failed(factory, Some(id), "task", &error.0); + 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; + task.stop_detail = None; + } + } + }); + if let Some(from) = from { + // 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), + "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 + + self.starting.len() 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(); + // A worker's reports grow its Task record: past the cap a report is + // 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 { .. } | 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 + { + 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) => { + 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)?; + // 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 => { + 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 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() { + 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 Some(factory) = factory { + 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 if !task.purged => vec!["revive"], + TaskState::Cancelled if !task.purged => vec!["revive"], + TaskState::Cancelled | TaskState::Outside => 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 verification = match verification { + Some(VerificationChoice::Ci { checks }) => { + if !probe.github { + return Err(refuse( + "ci_unavailable", + "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 }) => { + 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}))); + } + // 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, + "project": project, + "source": if probe.github { "github" } else { "local" }, + "candidates": candidates, + "merge_mode": "auto", + "auto_unavailable": auto_unavailable, + "default_runtime": probe.runtimes.first().copied().unwrap_or(Runtime::Claude), + "github": github.as_ref().map(|(account, repo)| json!({ + "account": account, + "repo": repo, + "reads": GITHUB_READS, + "writes": GITHUB_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; + } + // 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(), + project_name: Path::new(&project) + .file_name() + .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, + 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, + 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); + self.record( + &id, + None, + "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}})) + } + + 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() + }, + // 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: if card.external.is_empty() { + existing.map(|c| c.external.clone()).unwrap_or_default() + } else { + 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::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 + .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 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); + 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.record( + factory_id, + Some(id), + "attachment.pending", + 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 { + change: Some(Box::new(CardChange { card, attachment })), + }, + "실행 중에 카드나 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, + autonomy_scope: self.autonomy_scope(factory, &task), + }, + }; + self.with_task(factory, id, |task| { + task.review = ReviewState::Requested { at: now } + }); + match self.submit_judgment(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.submit_judgment(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 { + // 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, + text, + "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(factory, &pane, &body) { + self.with_task(factory, id, |task| task.producer_pane = None); + } + } + + /// 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 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( + 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); + // 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); + 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 { change } => { + let approved = decision == "approve"; + let mut prd = None; + self.with_task(factory, id, |task| { + if approved { + task.scope_approved = true; + 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}{card}{prd}") + } 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, discovery } => { + 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}), + ); + if let Some(discovery) = discovery { + self.wait_on_prerequisite(factory, id, discovery, &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.set_recovery(factory, None); + 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 { command, .. } => { + // A person runs a proposed command themselves; the Factory + // 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 { + 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 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() + .insert(id.clone(), task); + self.save(factory, &id); + self.record(factory, Some(&id), "task.added", json!({"via": "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, + 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 { change: None }, + &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()), + discovery: Some(discovery_id.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 { + self.wait_on_prerequisite(factory, id, &discovery_id, new_id); + } + let reached = self + .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); + 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; + 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}"), + at: now, + }); + } + task.gates.clear(); + }); + let _ = letter; + self.put_to_sleep(factory_id, id); + 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) + }); + 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.publish_refusals.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); + // 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 { + // 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); + } + } + } + } + + /// 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). + 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; + }; + // A diff that cannot be read gives the checks nothing to judge; that + // is a check that cannot run, never a pass (B68). + 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(); + 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.submit_judgment(drift.clone()) { + Ok(()) => { + self.judgments.insert( + drift.id, + (factory.to_owned(), Some(id.to_owned()), Purpose::Drift), + ); + count += 1; + } + Err(failure) => self.check_failed(factory, id, &format!("submit: {}", failure.stage)), + } + 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.submit_judgment(judgment.clone()) { + Ok(()) => { + self.judgments.insert( + judgment.id, + (factory.to_owned(), Some(id.to_owned()), Purpose::Check), + ); + count += 1; + } + Err(failure) => { + self.check_failed(factory, id, &format!("submit: {}", failure.stage)) + } + } + } + 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, 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!({"reason": reason})); + } + + /// `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(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 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 + .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: run.commit.clone(), + 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); + } + // 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) { + 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; + } + if task.writes.contains(PUBLISH_PENDING) { + return; + } + 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, since)) = self.merge_retry.get(&key).copied() { + if at > self.now() { + return; + } + // 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; + } + 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); + 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 }) => { + self.send_to_rebase(factory_id, id, &files); + 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(); + gates.extend(self.person_gates(&factory, &task, mode)); + 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 waits_on_answer(&task) { + 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 { + // A manual Task always has its gate; nothing merges on red. + return; + } + 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 + } + + /// 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) => { + 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 Err(Failure::task("merge", "main_dirty")); + } + Ok(false) => {} + Err(failure) => { + self.external_failure(factory_id, Some(id), &failure); + return Err(failure); + } + } + } + match self + .ports + .merge + .merge(&factory, &task, factory.config.merge_method) + { + Ok(sha) => { + self.landed(factory_id, id, &sha); + Ok(sha) + } + Err(failure) => { + 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); + // 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); + 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 + .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", + )); + } + // 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) { + Ok(sha) => Ok( + json!({"message": "merged", "sha": sha, "task": self.task_answer(factory_id, id, "")["task"]}), + ), + Err(failure) => Err(refuse( + "merge_failed", + &format!("{}: {}", failure.stage, judgment::cut(&failure.detail, 300)), + )), + } + } + + 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). + self.release_worker(factory_id, id); + // A finished Task is a watch event (D-32). + self.watch_due(factory_id, true); + } + + /// 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); + } + } + + /// 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) { + // A Task already taken keeps the keep period of its first takeover. + if task.state == TaskState::Outside && task.cancelled_at.is_some() { + return; + } + 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; + } + }); + } + + /// 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; + }; + self.stop_worker(factory_id, id, &worker); + match self + .ports + .workers + .remove_worktree(&worker, Removal::Finished) + { + 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}), + ); + // 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 + + 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.set_recovery(factory_id, Some(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.set_recovery(factory_id, Some(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.set_recovery(factory_id, None); + 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.set_recovery( + factory_id, + Some(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); + } + } + } + + /// 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.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()]; + 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; + }; + self.keep(factory, Some(id), "letter.out", "wake", body); + 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()); + 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); + } + } + + 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 { + self.stop_worker(factory_id, id, 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; + } + // 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); + } + + 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_within(Some(&factory), 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" => { + 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" => { + 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()?.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, + "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); + } + } + "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(',') + .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); + } + 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). + 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)?; + let task = tasks.get(id)?; + Some(summary::detail( + factory, + task, + tasks, + Self::allowed_actions(task), + self.now(), + )) + } + + // ------------------------------------------------------------------ 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(); + } + self.keep(&factory, Some(&task), "letter.in", &letter.id, &letter.body); + 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); + } + 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); + } + } + } + + 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 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) + .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; + }; + 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, + ); + // 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) + } + (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, true) + } + JudgmentOutcome::Failed { .. } if drafting => {} + 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, false), + Err(_) => self.record( + &factory, + Some(&task), + "judgment.failed", + json!({"purpose": "Periodic", "reason": "unreadable"}), + ), + } + } + (JudgmentOutcome::Answered { value }, Purpose::Watch { read_at }, _) => { + self.apply_watch(&factory, value, read_at) + } + (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 { + // 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) + }); + 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(); + // 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| !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)); + } + } + if self.halt_until.is_some_and(|until| until > now) { + return; + } + 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)) + }); + // 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 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 + .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; + 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(EnvHold::DiskFloor); + } else if self.ports.environment.memory_pressure() == MemoryPressure::Critical { + self.hold_reason = Some(EnvHold::MemoryCritical); + } + } + if let Some(reason) = self.hold_reason { + self.env_problem_since.get_or_insert(now); + for task in &candidates { + 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() || task.held_code.is_some() { + self.with_task(&task.factory, &task.id, |t| { + t.held = None; + t.held_code = None; + }); + } + } + let mut free = self + .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 { + continue; + } + if self.start(&task.factory, &task.id) && !relanding { + free -= 1; + } + } + } + + /// 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; + }; + let Some(task) = self.task(factory_id, id).cloned() else { + 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 { + 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, &self.hide_program), + args: factory + .config + .worker_args + .get(runtime.as_str()) + .cloned() + .unwrap_or_default(), + resume: Some(worker.clone()), + attempt: task.spawn_refusals, + }; + self.ports.workers.spawn(&request).map(Some) + } 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); + } + 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 + } + // 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 + } + } + } 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, &self.hide_program), + args: factory + .config + .worker_args + .get(runtime.as_str()) + .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; + }); + self.record( + factory_id, + Some(id), + "worker.started", + json!({"runtime": runtime.as_str()}), + ); + 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 + } + }; + 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) + .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) { + 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}), + ); + self.cancel_verification(factory_id, &task.id); + self.follow_outside(factory_id, &task); + self.set_state(factory_id, &task.id, TaskState::Done); + } + TaskState::Outside => {} + TaskState::Running + | TaskState::Verifying + | TaskState::Blocked + | TaskState::Paused + | TaskState::MergeWaiting + | TaskState::Stopped => { + self.cancel_verification(factory_id, &task.id); + 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())); + } + _ => { + 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})); + } + } + } + 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; the + // stopped worker's worktree keeps its period (B50). + 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 { change: None }, + "사람이 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(crate::store::body_hash(&body)); + }); + 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 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| 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; + }; + 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 + .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_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). + 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})); + } + } + // 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()); + 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); + } + } + Err(failure) => self.external_failure(&factory.id, None, &failure), + } + } + } + + /// 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, _), (_, 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) + }) + } + + // ------------------------------------------------------------- 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(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); + // 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). + 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(|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 + /// 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(|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(|note| { + note.kind == FailureKind::Task + && now.saturating_sub(note.at) <= CASCADE_WINDOW_MS + && note.factory == factory + && note.stage == stage + }) + .map(|note| note.task.clone()) + .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(|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( + 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), + "detail": judgment::cut(&failure.detail, 200), + }), + ); + 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(EnvHold::DiskFull); + self.hold_checked_at = Some(now); + self.remove_finished_worktrees(None); + } + 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), 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 + .factories + .get(&t.factory) + .map_or(7 * DAY_MS, |f| f.config.cancel_keep_ms); + (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)) + }) + .filter_map(|t| { + t.worker + .clone() + .map(|w| (t.factory.clone(), t.id.clone(), w)) + }) + .collect(); + for (factory, id, worker) in targets { + 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!({})); + } + Err(failure) => self.cleanup_failed(&factory, &id, &failure), + } + } + } + + 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.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), + }); + 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.submit_judgment(judgment.clone()).is_ok() { + self.judgments + .insert(judgment.id, (factory.id.clone(), None, Purpose::Env)); + } + } + + /// 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(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.remove(factory); + 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 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) + .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; + }; + 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.run_recovery(factory, action); + } + 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.submit_judgment(judgment.clone()).is_ok() { + self.judgments.insert( + judgment.id, + (factory_id.to_owned(), None, Purpose::Watch { read_at: now }), + ); + } + 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.submit_judgment(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, read_at: UnixMs) { + 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 = 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. + 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() + && 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, + 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 + + /// 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| kept_for_revive(t) && !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, Removal::Discarded) + { + self.cleanup_failed(&factory, &id, &failure); + continue; + } + self.with_task(&factory, &id, |t| t.purged = true); + self.record(&factory, Some(&id), "cleanup.cancelled", json!({})); + } + } +} + +/// 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). +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 { + 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 +} + +/// 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, + /// A Factory's own agent is in the lineage. + pub factory_spawned: bool, +} + +pub fn pr_body(task: &Task, factory: &Factory) -> String { + let mut body = issue_body(task, factory); + if !task.decisions.is_empty() { + // 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")), + 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 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 { + 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(&card_text(&task.card)); + 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); + if hide != "hide" { + prompt.push_str(&format!( + "- 위와 이후 편지의 `hide`는 모두 이 프로그램입니다: '{}'\n", + hide.replace('\'', "'\\''") + )); + } + 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/exec.rs b/hide-factory/src/exec.rs new file mode 100644 index 0000000000..e1adaa1ef9 --- /dev/null +++ b/hide-factory/src/exec.rs @@ -0,0 +1,262 @@ +//! 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)) + || lower.contains("the requested url returned error: 5") + { + Some(EnvSignal::GithubServer) + } else if [ + "could not resolve host", + "connection refused", + "network is unreachable", + "connection reset", + "tls handshake", + "i/o timeout", + "operation timed out", + "unexpected disconnect", + ] + .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)), + ( + "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), + ), + // These close lasting refusals too (a missing key, a gone + // repository, a pack too large): they reach a person. + ( + "git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.", + 128, + 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)", + 1, + None, + ), + ("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/judgment.rs b/hide-factory/src/judgment.rs new file mode 100644 index 0000000000..75ed29a1f9 --- /dev/null +++ b/hide-factory/src/judgment.rs @@ -0,0 +1,527 @@ +//! 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, + /// 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, + 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, + 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, + 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, + /// 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 { + 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, + fits_scope: value["fits_scope"].as_bool(), + }) +} + +/// 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", "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, + "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. 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."; + +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."; + +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..c85e6be56f --- /dev/null +++ b/hide-factory/src/lib.rs @@ -0,0 +1,29 @@ +//! 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 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}; +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..674c314ee9 --- /dev/null +++ b/hide-factory/src/model.rs @@ -0,0 +1,1020 @@ +//! 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, + /// `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, + /// 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, + /// 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 { + "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")] +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, + /// A recovery (finding or reverting the failing merge) is running. + #[serde(default)] + pub recovering: bool, +} + +#[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, + 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, + /// 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 { + fn default() -> Self { + Self { + verification: Verification::None, + merge_mode: MergeMode::Manual, + merge_method: MergeMethod::Merge, + quick_check: None, + 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, + worker_args: std::collections::BTreeMap::new(), + } + } +} + +#[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 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. + 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 ③). 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). + 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, + /// 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, + MergeRefused, +} + +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 => "직접 확인 표시", + Self::ApprovedScopeChange => "승인된 범위 변경", + Self::BreakingChange => "보고된 breaking change 또는 공개 계약 변경", + Self::NoVerification => "검증 없음", + Self::RiskPath => "위험 경로 변경", + Self::ManualMode => "manual 머지", + Self::OpenQuestion => "열린 질문", + Self::CheckFailed => "점검을 하지 못함", + Self::AutonomyDiff => "자율 처리 diff 상한 초과", + Self::DirtyMain => "main checkout에 커밋 안 된 변경", + Self::MergeRefused => "머지가 거절됨", + } + } +} + +/// 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, + WorkerStart, + PublishRefused, +} + +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 => "보고 없이 멈춤", + Self::Stalled => "정체", + Self::VerifyFailed => "검증 3회 실패", + Self::NewTaskCap => "새 Task 상한", + Self::EnvironmentRepeated => "같은 환경 실패 반복", + Self::WorkerStart => "worker 시작 실패", + Self::PublishRefused => "push 거절됨", + } + } +} + +/// 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 { + /// 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, + 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, + /// 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, + /// Worker starts refused or abandoned 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, + 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, + /// The same hold as a code. + #[serde(default)] + pub held_code: 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 { + /// 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, + stop_detail: None, + spawn_refusals: 0, + 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, + held_code: None, + label_path: false, + source_body_hash: None, + } + } + + 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/project.rs b/hide-factory/src/project.rs new file mode 100644 index 0000000000..5000fd1d53 --- /dev/null +++ b/hide-factory/src/project.rs @@ -0,0 +1,1610 @@ +//! 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, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use crate::adapters::*; +use crate::engine::{MERGE_COMMIT_AGAIN_MS, task_marker}; +use crate::exec::{Runner, checked, classify}; +use crate::model::*; +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>, + /// 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, + /// 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. +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>); + +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(), + ci_pending: BTreeMap::new(), + ci_poll_every: CI_POLL_EVERY, + held_cursor: BTreeMap::new(), + }))) + } + + /// 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()) + } +} + +/// 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() + .map(|worker| PathBuf::from(&worker.worktree)) + .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)) +} + +/// 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 + .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) + } + + /// 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) + .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), + output_limit: crate::verify::RUN_OUTPUT_LIMIT, + }) + } + + 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), 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])?; + let required = match &factory.config.verification { + 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 + .iter() + .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(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), + runtimes: installed_runtimes(), + ..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); + // 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(); + } + for (key, method) in [ + ("mergeCommitAllowed", MergeMethod::Merge), + ("squashMergeAllowed", MergeMethod::Squash), + ("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 prepare(&mut self, factory: &Factory) -> Result<(), Failure> { + if factory.source != SourceKind::Github { + return Ok(()); + } + let repo = write_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 = write_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 = write_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,isCrossRepository,closingIssuesReferences", + ], + )?; + let held: BTreeMap = tasks + .iter() + .filter_map(|task| match task.issue { + Some(IssueRef::Github { number }) => Some((number, task)), + _ => None, + }) + .collect(); + let mut labelled: BTreeMap = issues + .as_array() + .into_iter() + .flatten() + .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: 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", + "view", + &number.to_string(), + "--repo", + &repo, + "--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() + .flatten() + .any(|label| label["name"].as_str() == Some(LABEL)); + if still { + 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(); + let hash = crate::store::body_hash(body); + 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}]})); + // 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 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 }, + 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_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_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_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(); + 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..2c7139ed62 --- /dev/null +++ b/hide-factory/tests/local_git.rs @@ -0,0 +1,437 @@ +//! 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"]); + // 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", "."]); + 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 { + factory: String::new(), + agent: None, + 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 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(), + 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); + 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", "."]); + 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:?}"); + // 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()); + assert!( + fx.project.join("c.txt").exists(), + "only that merge is undone" + ); +} + +#[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(); + let factory = factory(&fx.project, &[]); + 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!( + fx.projects.premerge(&factory, &t).unwrap(), + PreMerge::Conflict { + 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()); +} + +#[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" + ); +} + +/// 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()); + 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); + 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 new file mode 100644 index 0000000000..3de63e727a --- /dev/null +++ b/hide-factory/tests/support/mod.rs @@ -0,0 +1,750 @@ +//! 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, BTreeSet, 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, + /// 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, + 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>, + 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, + /// 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, + /// 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, + /// 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`. + pub main_check_script: 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, + /// 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, + /// 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, + /// 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, + /// 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. + pub judgment_failure: Option, + /// 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, + 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()), + account: github.then(|| self.world().account.clone()).flatten(), + 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(), + runtimes: self.world().runtimes.clone(), + }) + } + 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, + commit: 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.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)); + } + 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 { + 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 { + self.world().premerge_calls += 1; + 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.merge_attempts += 1; + 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 { + 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)); + 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 let Some(failure) = world.merged_read_failure.take() { + return Err(failure); + } + 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() + .main_check_script + .get_mut(sha) + .and_then(VecDeque::pop_front) + { + return Ok(next); + } + 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(); + world.spawn_asks.push(request.clone()); + if let Some(failure) = world.spawn_failure.clone() { + return Err(failure); + } + world.spawned.push(request.clone()); + world.worker_status.remove(&request.task); + Ok(WorkerRef { + factory: String::new(), + agent: Some(format!("agent-{}", request.task)), + 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 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)); + Ok(()) + } + 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(()) + } + fn usage_limited(&mut self, runtime: Runtime) -> Option { + self.world().usage_limits.get(&runtime).copied() + } +} + +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 { + 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( + || json!({"questions": [], "dependencies": [], "flags": [], "split": [], "fits_scope": true}), + ) + } + 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 { .. } => world + .watch + .pop_front() + .unwrap_or_else(|| json!({"warnings": []})), + JudgmentInput::EnvDiagnosis { .. } => world + .env_diagnosis + .clone() + .unwrap_or_else(|| 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_reads += 1; + 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, _factory: &str, 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, + account: Some("octo".into()), + 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().join("factory.sqlite3"), + &dir.path().join("factory-files"), + 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().join("factory.sqlite3"), + &dir.path().join("factory-files"), + 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() + } +} 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..191ef0d803 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,20 @@ 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)) + // 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(( "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())? })?;