diff --git a/docs/desktop-app.md b/docs/desktop-app.md index a86dd17..1540878 100644 --- a/docs/desktop-app.md +++ b/docs/desktop-app.md @@ -67,7 +67,7 @@ folder and the skills version before anything else shows; a later launch skips s A **launch card** then asks which agent, model and effort (Claude and Codex only) to start on. The picker lists Claude Code, Devin and Codex, then any custom agents you added in the web console's -**User Preferences → Agents** (saved in `~/.plan2code/agents.json`, shared with the `plan2code` +**User Preferences → Agents & models** (saved in `~/.plan2code/agents.json`, shared with the `plan2code` command), and starts on one that is actually installed, so a machine with only Devin or Codex is ready to go. Permission checks off is its own tick, on by default (see below; New Session keeps whatever you picked, and reuses the same agent); a CLI the app cannot find is named, with how to install it, @@ -89,7 +89,7 @@ needs attention and bounces once; on Linux a count badge appears where the deskt is no dot while the agent is busy or once a finished step has nothing left to press (a finished screen that still offers a button, such as back to the dashboard, keeps the green dot), and it clears when the agent ends or the page reloads. Turn it off with **Show on the taskbar when Plan2Code needs -me** under **User Preferences → Desktop app** (shown only inside the app). The per-system details are in +me** under **User Preferences → System → Desktop app** (shown only inside the app). The per-system details are in [plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar). A slim top bar reads, left to right: the project folder's name, a menu holding its full path and @@ -121,6 +121,113 @@ involved. A slash command still offered to continue a step (such as `/plan2code- exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real agent CLI. +## Implementation Loop + +The Implementation Loop builds every remaining phase of a documented spec for you, one after another, +while you do something else. It is in the app only: the dashboard shows an **Implementation Loop** +card there, and nowhere else. Pick a spec, answer a short setup, press **Start the loop**, and the app +confirms it once in its own window before anything runs. + +**How it runs.** Each phase gets a fresh agent session, so a long spec never grows one tired +conversation. The app, not the agent, decides when a phase counts: it reads the spec's marks, runs the +quick check, marks the phase done and commits it. With commits on, it commits to the branch you are on and never +pushes. With commits on, Start needs a clean working tree (the setup offers the Git board when it is +not), so your own edits never end up inside a phase's commit. + +**The setup.** The fields and their defaults: + +- **Review each phase** (on): a fresh agent reviews the phase before it counts. +- **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the + ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the + Critical, Warning and Suggestion findings you tick (all three start ticked). +- **When a phase asks something**: **Take the agent's best guess** (the default), which records the + assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**. +- **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**. +- **Quick check**: a command run after each phase, pre-filled from the project (for example + `npm run build`). Clearing it still lets you start; the setup warns that nothing is checked. +- **If a phase crashes or goes quiet**: **Retry it once** (on), and how many minutes with no file changes, in the project or the agent's + session, count the agent as stuck (20). Waiting on your answer does not count. +- **Send a notification** (no address, so off): a message from the loop when it waits on your answer or + ends. Send it to a Discord, Slack, Microsoft Teams or Google Chat webhook, or to any `http` or `https` + address with the message in its query string or a JSON body. +- **Commit each phase** (on): one local commit per phase, with the subject and `AI Assisted`. + +The last setup is remembered per project in `~/.plan2code/console/loop-setup.json`, so the next loop +starts from it. The quick check is typed text the page never runs: the app reads it from that file +itself and names it in its own window before the loop begins. The notification gets the same treatment, +and Resume asks again if either one changed. + +**The notification.** The loop says a question is waiting, that it is complete, or why it stopped. Nothing +is sent when you stopped it yourself, and with **Take the agent's best guess** no question ever waits on +you. What the app sends depends on the **Send to** choice: + +| Send to | Request | Where the message goes | +| --- | --- | --- | +| A web address, query string | GET | A parameter you name (`message` by default), added to the address's own | +| Discord webhook | POST JSON | `content`, with mentions turned off | +| Slack webhook | POST JSON | `text` | +| Microsoft Teams webhook | POST JSON | An Adaptive Card, for a Workflows "when a webhook request is received" trigger | +| Google Chat webhook | POST JSON | `text` | +| A web address, JSON body | POST JSON | A field you name (`message` by default) | + +**Send a test** saves the setup and sends a test message right away, after the app names the address in its +own window, so a wrong address shows up before a long run. A name can use letters, digits and `- _ . ~`. Pasting a Discord, Slack, Teams or Google Chat address picks +its choice for you, since a plain GET to a Discord webhook answers 200 and posts nothing. The call has 10 +seconds and any 2xx answer counts. One that fails never changes what the loop does: the finish line or the +stop screen's evidence says so, without repeating the address, which is stored in `loop-setup.json` and +usually holds a token. + +**It uses the app's agent.** The loop starts every phase on the agent and model you launched the app +with, and it needs permission checks off. With them on, an agent would wait on a prompt that nobody +sees, so **Start the loop** stays grayed out until you turn them off (see +[Permission checks are off by default](#permission-checks-are-off-by-default-same-as-the-terminal)). + +**What is locked while it drives.** Answers, sign-offs, launches, Workspace, Helpers, **Back** and +**New Session** are read-only, and Ask is off, except for a question the loop is waiting on. Activities, Notebook, Help, Preferences, the documents +and the code review stay usable, so you can watch, play, or read along. + +**You can always see it's running.** From the moment you confirm Start until the loop ends, a banner runs +across the top of the window, outside the console page, so it stays put as each phase's session comes and +goes. It says what the loop is doing right now (starting, building, between phases, stopping), with the +phase, its name and step, a pip per phase, the time so far and any retries. It turns amber when a question +needs your answer. The window title says the same, for the taskbar. While the loop works, the page's Send +button and "Nothing to send" line go away, and they come back when a question waits. + +**Stopping it.** Two buttons on the banner: **Stop after this phase** lets the phase finish its +review, mark and commit, then ends the loop; **Stop now** ends the agent at once, after you confirm, and never commits, retries or finishes the build (a commit already begun finishes first). Stop after can be canceled by pressing it again. After a window reload the banner and both buttons come back, and Change project and Change agent are blocked while the loop runs. +Quitting the app ends the loop too, and the quit check says which phases are already committed. + +**A question holds the loop.** When a phase needs an answer (with **Pause and wait for me**), the loop +waits with no time limit and nothing is lost. The app calls you back with the taskbar dot, a flash +of the window and the question sound, and carries on once you answer. + +**When it stops by itself.** The loop ends on a stop screen, saying what failed and showing the +evidence, when: + +- the phase's named tests or the quick check fail; +- Critical or Warning findings are left after the re-check, at a level the setup said to fix (a leftover Suggestion does not stop it); +- a task is blocked or the spec conflicts with itself; +- a commit is refused, for example by a pre-commit hook (the app puts the phase file back as it was, so the spec and git agree, and stops with the hook's first line; if the undo fails too, it says so and remembers it across a restart); +- a staged file looks like a secret (`.env` and the like; `.example`, `.sample` and `.template` are fine) or is oversized (nothing stays staged, and the stop line names the file); +- the project is on a detached HEAD (the loop will not start); +- the agent's report is missing task data or says its tests failed (the phase is refused); +- the watcher cannot read the session or hits an internal error (it ends on a stop screen, never a hang); +- the Smart pick skipped a Critical finding. + +A crashed or silent agent gets exactly one retry per phase when the retry tick is on, and none when it is off. +It never retries a real failure. On a stop screen, **Resume the loop** carries on from the stopped +phase and **Fix it by hand** opens an ordinary Implement session on it. + +**The report.** One report follows the whole build, across stops and Resume. For every phase it says what +was built and committed, the tests, the findings fixed, the findings it chose not to fix and why, the +findings left open, each assumption with its note, and any other decisions the agent reported, plus every +retry and stop, in order. The agent writes most of this, so it holds what the agent noticed; the task marks, +the quick check and the commits are the app's own. The finish screen counts each kind per phase, and **Read +the full report** opens it, saved as `specs//LOOP-SUMMARY-.md` (`-2` and so on for another +the same day). After a stop, **Read why, and the report so far** shows it on the stop screen. While a build +is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Resume needs a +clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, which the loop card links to as "How the loop works". + ## Keep it up to date `plan2code update` brings the skills, the `plan2code` command and the app up together. If the app diff --git a/plan2code-app/Cargo.lock b/plan2code-app/Cargo.lock index cc37e7f..dbdae79 100644 --- a/plan2code-app/Cargo.lock +++ b/plan2code-app/Cargo.lock @@ -381,7 +381,7 @@ dependencies = [ "bitflags 2.13.2", "core-foundation", "core-graphics-types", - "foreign-types", + "foreign-types 0.5.0", "libc", ] @@ -759,6 +759,7 @@ dependencies = [ name = "fake-agent" version = "3.0.0" dependencies = [ + "serde_json", "terminal_size", ] @@ -827,6 +828,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared 0.1.1", +] + [[package]] name = "foreign-types" version = "0.5.0" @@ -834,7 +844,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" dependencies = [ "foreign-types-macros", - "foreign-types-shared", + "foreign-types-shared 0.3.1", ] [[package]] @@ -848,6 +858,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "foreign-types-shared" version = "0.3.1" @@ -870,6 +886,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -1312,6 +1329,22 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.21" @@ -1863,6 +1896,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "ndk" version = "0.9.0" @@ -2151,6 +2201,49 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "foreign-types 0.3.2", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -2283,6 +2376,7 @@ dependencies = [ "chrono", "libc", "portable-pty", + "reqwest", "serde", "serde_json", "tauri", @@ -2561,21 +2655,26 @@ checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ "base64 0.23.1", "bytes", + "futures-channel", "futures-core", "futures-util", "http", "http-body", "http-body-util", "hyper", + "hyper-tls", "hyper-util", "js-sys", "log", + "native-tls", "percent-encoding", "pin-project-lite", + "rustls-pki-types", "serde", "serde_json", "sync_wrapper", "tokio", + "tokio-native-tls", "tokio-util", "tower", "tower-http", @@ -2639,6 +2738,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2654,6 +2762,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.8.22" @@ -2711,6 +2828,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" version = "0.38.0" @@ -3473,6 +3613,19 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys 0.60.2", +] + [[package]] name = "tendril" version = "0.5.1" @@ -3592,6 +3745,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -3860,6 +4023,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version-compare" version = "0.2.1" @@ -4578,6 +4747,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/plan2code-app/README.md b/plan2code-app/README.md index 205dfc1..0769f5d 100644 --- a/plan2code-app/README.md +++ b/plan2code-app/README.md @@ -6,7 +6,7 @@ The app is optional. The Node web console and the skills never depend on it, so ## Agents and the taskbar -**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. Custom agents offer their own models, and `/plan2code` only does something in an agent that loads the installed Plan2Code skills. +**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents & models, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. Custom agents offer their own models, and `/plan2code` only does something in an agent that loads the installed Plan2Code skills. **No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app. @@ -18,7 +18,7 @@ The app is optional. The Node web console and the skills never depend on it, so | macOS | no badge (the system badge cannot be green), one bounce when not focused | red `!` dock badge, and one bounce when not focused | | Linux | the urgency hint when not focused | a count badge of 1 where the desktop supports it, and the urgency hint | -There is no dot while busy or once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`. +There is no dot while busy or once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → System → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`. ## Layout diff --git a/plan2code-app/RELEASE-CHECKLIST.md b/plan2code-app/RELEASE-CHECKLIST.md index 8c15cdf..f6e1b0c 100644 --- a/plan2code-app/RELEASE-CHECKLIST.md +++ b/plan2code-app/RELEASE-CHECKLIST.md @@ -112,7 +112,7 @@ Do each of Claude Code, Devin and Codex for a few minutes: ## Agents and the taskbar (each system) -- [ ] A custom agent added in the console's User Preferences → Agents (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments +- [ ] A custom agent added in the console's User Preferences → Agents & models (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments - [ ] With no agent CLI on `PATH` and no custom agent, the first-run checklist and the launch card show the explainer with each install command and an **Install page** link, and Start is off - [ ] Each **Install page** link opens the right page in the default browser (Claude Code, Devin, Codex) - [ ] Install an agent (or add a custom one), press **Check again**: it appears and Start turns on without restarting the app @@ -122,7 +122,7 @@ Do each of Claude Code, Devin and Codex for a few minutes: - [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background - [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused - [ ] Reloading the window, or ending the agent, clears the dot -- [ ] User Preferences → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app +- [ ] User Preferences → System → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app ## Standalone path diff --git a/plan2code-app/fake-agent/Cargo.toml b/plan2code-app/fake-agent/Cargo.toml index 3a0c31c..b67e050 100644 --- a/plan2code-app/fake-agent/Cargo.toml +++ b/plan2code-app/fake-agent/Cargo.toml @@ -7,3 +7,4 @@ publish = false [dependencies] terminal_size = "0.4" +serde_json = "1" diff --git a/plan2code-app/fake-agent/src/main.rs b/plan2code-app/fake-agent/src/main.rs index 63f4a19..8086875 100644 --- a/plan2code-app/fake-agent/src/main.rs +++ b/plan2code-app/fake-agent/src/main.rs @@ -7,6 +7,10 @@ //! EXIT exit with code c //! SIZE print the terminal size once //! PID print the agent's process id as `PID ` +//! REPORT write as `loopOutcome` into the session's state.json +//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say +//! `REPORT written` (`REPORT unavailable` when either is missing) +//! HANG say `HANGING`, then go silent for good (no more lines read) //! echoed back as `echo: ` //! //! A change in terminal size is reported on its own as `SIZE x`. @@ -36,9 +40,47 @@ pub enum Command { Pid, /// `ENV NAME`: print the variable's value, for tests of what an agent is given. Env(String), + /// `REPORT `: the phase report the loop waits for, as the JSON text. + Report(String), + /// `HANG`: go silent, to model an agent that stops answering. + Hang, Echo(String), } +/// Write `json` as the `loopOutcome` of the session named by the environment. +/// Returns false when the session cannot be named. +fn write_report(json: &str) -> bool { + let (Ok(home), Ok(sid)) = ( + std::env::var("PLAN2CODE_CONSOLE_HOME"), + std::env::var("PLAN2CODE_CONSOLE_SID"), + ) else { + return false; + }; + write_report_to(std::path::Path::new(&home), &sid, json) +} + +/// `write_report` with the session named: `/sessions//state.json`. +fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool { + let Ok(outcome) = serde_json::from_str::(json) else { + return false; + }; + let dir = home.join("sessions").join(sid); + let file = dir.join("state.json"); + let mut state = std::fs::read_to_string(&file) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .filter(|value| value.is_object()) + // The console's own file always carries its schema number; a new one does too. + .unwrap_or_else(|| serde_json::json!({ "schema": 1 })); + state["loopOutcome"] = outcome; + let _ = std::fs::create_dir_all(&dir); + let temp = dir.join("state.json.tmp"); + let Ok(text) = serde_json::to_string(&state) else { + return false; + }; + std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok() +} + pub fn parse(line: &str) -> Command { let line = line.trim(); if let Some(rest) = line.strip_prefix("STEP ") { @@ -60,6 +102,15 @@ pub fn parse(line: &str) -> Command { if let Some(name) = line.strip_prefix("ENV ") { return Command::Env(name.trim().to_string()); } + if let Some(rest) = line.strip_prefix("REPORT ") { + let json = rest.trim(); + if serde_json::from_str::(json).is_ok() { + return Command::Report(json.to_string()); + } + } + if line == "HANG" { + return Command::Hang; + } Command::Echo(line.to_string()) } @@ -106,6 +157,19 @@ fn main() { "ENV {name}={}", std::env::var(&name).unwrap_or_default() )), + Command::Report(json) => { + if write_report(&json) { + say("REPORT written") + } else { + say("REPORT unavailable") + } + } + Command::Hang => { + say("HANGING"); + loop { + thread::sleep(Duration::from_secs(3600)); + } + } Command::Echo(text) => say(&format!("echo: {text}")), } } @@ -128,6 +192,47 @@ mod tests { assert_eq!(parse("hello there"), Command::Echo("hello there".into())); } + #[test] + fn parses_report_and_hang() { + assert_eq!( + parse("REPORT {\"phase\":2}"), + Command::Report("{\"phase\":2}".into()) + ); + assert_eq!(parse("HANG\r\n"), Command::Hang); + } + + #[test] + fn a_report_lands_in_the_session_file_beside_what_was_there() { + let home = std::env::temp_dir().join(format!("fake-agent-report-{}", std::process::id())); + let dir = home.join("sessions").join("s9"); + std::fs::create_dir_all(&dir).unwrap(); + // No file yet: a new one with the schema number. + assert!(write_report_to(&home, "s9", "{\"phase\":2}")); + let read = || -> serde_json::Value { + serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap() + }; + assert_eq!(read()["loopOutcome"]["phase"], 2); + assert_eq!(read()["schema"], 1); + // An existing object keeps its keys. + std::fs::write(dir.join("state.json"), "{\"schema\":1,\"title\":\"t\"}").unwrap(); + assert!(write_report_to(&home, "s9", "{\"phase\":3}")); + assert_eq!(read()["title"], "t"); + assert_eq!(read()["loopOutcome"]["phase"], 3); + // A garbage file is replaced, not trusted. + std::fs::write(dir.join("state.json"), "not json").unwrap(); + assert!(write_report_to(&home, "s9", "{\"phase\":4}")); + assert_eq!(read()["loopOutcome"]["phase"], 4); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn a_report_with_bad_json_is_an_echo() { + assert_eq!( + parse("REPORT {not json"), + Command::Echo("REPORT {not json".into()) + ); + } + #[test] fn a_bad_number_is_just_an_echo() { assert_eq!(parse("STEP x"), Command::Echo("STEP x".into())); diff --git a/plan2code-app/src-tauri/Cargo.toml b/plan2code-app/src-tauri/Cargo.toml index 529e40b..ca9afa1 100644 --- a/plan2code-app/src-tauri/Cargo.toml +++ b/plan2code-app/src-tauri/Cargo.toml @@ -19,6 +19,9 @@ portable-pty = "0.9.0" serde = { version = "1", features = ["derive"] } serde_json = "1" chrono = "0.4" +# The loop's call to a web address. The operating system's TLS, so a company's +# own root certificates work and no second TLS stack is built. +reqwest = { version = "0.13", default-features = false, features = ["blocking", "native-tls"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/plan2code-app/src-tauri/capabilities/default.json b/plan2code-app/src-tauri/capabilities/default.json index b32e750..39da663 100644 --- a/plan2code-app/src-tauri/capabilities/default.json +++ b/plan2code-app/src-tauri/capabilities/default.json @@ -1,7 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name", + "description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name and putting it in and out of full screen for an Activities game", "windows": ["main"], - "permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title"] + "permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title", "core:window:allow-is-fullscreen", "core:window:allow-set-fullscreen"] } diff --git a/plan2code-app/src-tauri/src/agent_manager.rs b/plan2code-app/src-tauri/src/agent_manager.rs index bd403b8..318257c 100644 --- a/plan2code-app/src-tauri/src/agent_manager.rs +++ b/plan2code-app/src-tauri/src/agent_manager.rs @@ -29,6 +29,12 @@ pub enum AgentState { /// manager: it runs with the manager's state locked. pub type BeforeFresh = Arc Option + Send + Sync>; +/// Runs when the Implementation Loop starts a phase's fresh agent: the app +/// forgets the console session it was showing, so the new agent's `open` +/// makes a session of its own. Like `BeforeFresh`, it must not call back into +/// the manager. +pub type ForgetSession = Arc; + /// What the page needs to draw the bar. `generation` counts the agents started /// so far: a new number means a fresh agent, so the terminal clears. #[derive(Clone, Debug, Serialize)] @@ -101,6 +107,7 @@ struct Shared { folder: PathBuf, sink: Sink, before_fresh: Mutex>, + forget_session: Mutex>, /// Environment every agent this manager starts gets, on top of its own: /// the in-app signal that sends the agent's console pages to this window. extra_env: Mutex>, @@ -128,6 +135,7 @@ impl AgentManager { folder, sink, before_fresh: Mutex::new(None), + forget_session: Mutex::new(None), extra_env: Mutex::new(Vec::new()), generation: AtomicU64::new(0), inner: Mutex::new(Inner { @@ -153,6 +161,20 @@ impl AgentManager { } } + /// Run `hook` whenever the loop starts a phase's fresh agent (`start_fresh` + /// and `forget_session`). + pub fn set_forget_session(&self, hook: ForgetSession) { + if let Ok(mut slot) = self.shared.forget_session.lock() { + *slot = Some(hook); + } + } + + /// Make the app forget the console session it follows, so the next agent's + /// `open` starts a new one. + pub fn forget_session(&self) { + self.shared.forget(); + } + /// Give every agent started from now on these variables (replacing any set before). pub fn set_env(&self, env: Vec<(String, String)>) { if let Ok(mut slot) = self.shared.extra_env.lock() { @@ -197,6 +219,54 @@ impl AgentManager { } } + /// Start a fresh agent on the stored launch choice with `prompt` as its + /// only first prompt: the Implementation Loop's way to begin a phase. A + /// running agent is killed first (the same path as Restart), but without + /// Restart's brief note; the app still forgets the console session, so + /// the new agent's `open` makes a new one. An agent that ended, or never + /// ran, starts directly. Needs a launch choice from an earlier start. + pub fn start_fresh(&self, prompt: String) -> Result<(), String> { + let mut inner = lock(&self.shared.inner); + let (choice, _) = inner + .last_start + .clone() + .ok_or("no agent has been started")?; + inner.brief_note = None; + inner.last_start = Some((choice, Some(prompt))); + self.shared.forget(); + if inner.state == AgentState::Running { + self.shared.generation.fetch_add(1, Ordering::SeqCst); + if let Some(old) = inner.running.take() { + let _ = old.host.kill(); + } + } + match self.shared.spawn(&mut inner) { + Ok(()) => Ok(()), + Err(e) => { + inner.state = AgentState::Ended { + reason: format!("could not start the agent: {e}"), + }; + self.shared.emit(&inner); + Err(e) + } + } + } + + /// The stored launch choice: agent, model, effort and permission mode. + pub fn launch_choice(&self) -> Option<(Agent, Option, Option, PermissionMode)> { + lock(&self.shared.inner) + .last_start + .as_ref() + .map(|(choice, _)| { + ( + choice.kind.clone(), + choice.model.clone(), + choice.effort.clone(), + choice.mode, + ) + }) + } + pub fn snapshot(&self) -> AgentSnapshot { self.shared.snapshot(&lock(&self.shared.inner)) } @@ -296,6 +366,17 @@ impl Shared { } } + fn forget(&self) { + let hook = self + .forget_session + .lock() + .ok() + .and_then(|slot| slot.clone()); + if let Some(run) = hook { + run(); + } + } + fn emit(&self, inner: &Inner) { (self.sink)(AgentEvent::State(self.snapshot(inner))); } diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs index 5e40c99..19af9df 100644 --- a/plan2code-app/src-tauri/src/console_supervisor.rs +++ b/plan2code-app/src-tauri/src/console_supervisor.rs @@ -243,7 +243,7 @@ impl ConsoleSupervisor { if !session.embed { // Do not leave an old console running that the frame cannot show. let _ = node_command(console_dir) - .args(["stop", "--session", &session.sid]) + .args(stop_args(&session.sid)) .current_dir(project_dir) .output(); return Err(OLD_CONSOLE.to_string()); @@ -327,13 +327,15 @@ impl ConsoleSupervisor { Ok(true) } - /// `console.mjs stop --session `: the console's own orderly shutdown. + /// `console.mjs stop --session --force`: the console's own orderly + /// shutdown. `--force` because the app's shutdown is not the agent's ending: + /// the session may be unfinished, and `stop` refuses a session with no finish. pub fn stop(&mut self) -> Result<(), String> { if self.stopped { return Ok(()); } let output = node_command(&self.console_dir) - .args(["stop", "--session", &self.session.sid]) + .args(stop_args(&self.session.sid)) .current_dir(&self.project_dir) .output() .map_err(err)?; @@ -382,10 +384,25 @@ impl Drop for ConsoleSupervisor { } } +/// The arguments of the app's own `stop`: always `--force`, since the app's +/// shutdown is not the agent's ending and `stop` refuses a session with no finish. +fn stop_args(sid: &str) -> [&str; 4] { + ["stop", "--session", sid, "--force"] +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn the_apps_stop_calls_pass_force() { + let args = stop_args("20261101-120000-abcdef"); + assert_eq!( + args, + ["stop", "--session", "20261101-120000-abcdef", "--force"] + ); + } + #[test] fn splits_the_session_url() { let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap(); diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs index 67e6893..2ceb887 100644 --- a/plan2code-app/src-tauri/src/lib.rs +++ b/plan2code-app/src-tauri/src/lib.rs @@ -7,6 +7,11 @@ pub mod attention; pub mod brief; pub mod console_supervisor; pub mod handoff; +pub mod loop_commit; +pub mod loop_driver; +pub mod loop_notify; +pub mod loop_report; +pub mod loop_tools; pub mod node_check; pub mod project; pub mod pty_host; diff --git a/plan2code-app/src-tauri/src/loop_commit.rs b/plan2code-app/src-tauri/src/loop_commit.rs new file mode 100644 index 0000000..20c157e --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_commit.rs @@ -0,0 +1,861 @@ +//! The commit step of the Implementation Loop: its order, and nothing else. +//! +//! A passed phase goes through five calls, in this order: `prepare` (everything +//! that can fail, before any file is touched), `stage_and_check` (stage, then +//! refuse a secret or an oversized file), `mark` (save the files, mark the +//! phase done, write the approval line), `commit` (stage the marked files and +//! commit) and, when the commit fails, `undo` (put the saved text back). The +//! driver decides what to say and where to stop; this module only does the work +//! and names the failure. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::Value; + +use crate::loop_driver::{with_approval_line, write_atomic}; +use crate::loop_report::LoopReport; +use crate::loop_tools; + +/// What `prepare` settled before any file was touched. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Prepared { + pub message: String, + pub phase_file: PathBuf, +} + +/// The phase file named by a row of `specs.mjs status`, as a path under +/// `//`. Refuses a name that is missing, empty, climbs out of +/// the folder (`..`, a separator, a drive letter) or does not exist. +pub fn phase_file(project: &Path, spec: &str, entry: &Value) -> Result { + let file = entry["file"].as_str().unwrap_or("").trim(); + if file.is_empty() { + return Err("the spec names no phase file for this phase".to_string()); + } + let unsafe_name = file.contains("..") + || file.contains('/') + || file.contains('\\') + || file.contains('\0') + || file.chars().nth(1) == Some(':'); + if unsafe_name { + return Err(format!( + "the phase file name {file} is not a plain file name" + )); + } + let path = project.join(spec).join(file); + if !path.is_file() { + return Err(format!("the phase file {file} does not exist in {spec}")); + } + Ok(path) +} + +/// Everything that can fail before a file changes: the commit message and the +/// phase file. Nothing is written. +pub fn prepare( + project: &Path, + spec: &str, + entry: &Value, + subject: &str, +) -> Result { + let phase_file = phase_file(project, spec, entry)?; + let message = loop_tools::commit_message(project, subject) + .map_err(|e| format!("the commit message was refused: {e}"))?; + Ok(Prepared { + message, + phase_file, + }) +} + +/// The text of the two files `specs.mjs mark` changes, before and after the +/// loop wrote them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Marked { + /// The phase file before the mark, and as the loop left it. + pub saved: String, + pub written: String, + /// The same for `overview.md`, whose checkbox the mark flips. + pub overview: PathBuf, + pub overview_saved: String, + pub overview_written: String, +} + +fn read(file: &Path) -> Result { + std::fs::read_to_string(file).map_err(|e| format!("{} could not be read ({e})", file.display())) +} + +/// Why `mark` failed, and whether the files could be put back. When they could +/// not, the phase may be left marked done and the driver must say so. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MarkFailure { + pub message: String, + pub put_back_failed: bool, +} + +/// Mark the phase done and write the approval line, keeping the text of both +/// files so `undo` can take it back. On any failure both files are put back +/// before the error is returned. +pub fn mark( + prepared: &Prepared, + project: &Path, + spec: &str, + phase: u32, + approval: &str, +) -> Result { + let plain = |message: String| MarkFailure { + message, + put_back_failed: false, + }; + let overview = project.join(spec).join("overview.md"); + let saved = read(&prepared.phase_file).map_err(plain)?; + let overview_saved = read(&overview).map_err(plain)?; + let fail = |message: String| { + let phase_back = write_atomic(&prepared.phase_file, &saved); + let overview_back = write_atomic(&overview, &overview_saved); + MarkFailure { + put_back_failed: phase_back.is_err() || overview_back.is_err(), + message, + } + }; + let run = loop_tools::specs_mark_done(project, spec, phase); + if !run.ok { + return Err(fail(run.output.trim().to_string())); + } + let written = read(&prepared.phase_file) + .map(|text| with_approval_line(&text, approval)) + .and_then(|text| { + write_atomic(&prepared.phase_file, &text) + .map(|()| text) + .map_err(|e| format!("the approval line could not be written ({e})")) + }) + .map_err(&fail)?; + let overview_written = read(&overview).map_err(&fail)?; + Ok(Marked { + saved, + written, + overview, + overview_saved, + overview_written, + }) +} + +/// Take the mark back: both files get their saved text again, but only while +/// both still hold what the loop wrote, so an edit the person made in between +/// is never overwritten. Nothing is written unless both can be restored, so the +/// mark is either fully off or fully on; the error names each file that could +/// not be. +pub fn undo(prepared: &Prepared, marked: &Marked) -> Result<(), String> { + let files = [ + (&prepared.phase_file, &marked.saved, &marked.written), + ( + &marked.overview, + &marked.overview_saved, + &marked.overview_written, + ), + ]; + let name = |file: &Path| { + file.file_name() + .map_or_else(String::new, |n| n.to_string_lossy().into_owned()) + }; + let changed: Vec = files + .iter() + .filter(|(file, _, written)| std::fs::read_to_string(file).ok().as_ref() != Some(*written)) + .map(|(file, _, _)| name(file)) + .collect(); + if !changed.is_empty() { + return Err(format!( + "{} changed since the loop wrote it, so it was not restored", + changed.join(" and ") + )); + } + for (file, saved, _) in files { + write_atomic(file, saved) + .map_err(|e| format!("{} could not be restored ({e})", name(file)))?; + } + Ok(()) +} + +/// Which call failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + Add, + Commit, +} + +/// A failed `git add` or `git commit`, with what it printed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommitFailure { + pub stage: Stage, + pub first_line: String, + pub output: String, +} + +/// The first non-empty line of `output`, trimmed, at most 160 characters. +pub fn first_line(output: &str) -> String { + let line = output + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or(""); + if line.chars().count() > 160 { + let cut: String = line.chars().take(157).collect(); + format!("{cut}...") + } else { + line.to_string() + } +} + +/// The largest file the loop will commit. +pub const MAX_STAGED_BYTES: u64 = 5 * 1024 * 1024; + +/// File-name suffixes of a key or certificate. +const SECRET_SUFFIXES: [&str; 5] = [".pem", ".key", ".p12", ".pfx", ".keystore"]; +/// Names an `.env` file may carry and still be committed: a template. +const ENV_TEMPLATES: [&str; 3] = [".example", ".sample", ".template"]; +/// Private-key files with no suffix. +const KEY_NAMES: [&str; 2] = ["id_rsa", "id_ed25519"]; + +/// Why a staged file must not be committed, or `None`. Only the file name is +/// read (the part after the last separator, any case), so a folder named `.env` +/// does not match and `environment.md` or `monkey.txt` does not either. +pub fn denied(path: &str) -> Option<&'static str> { + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let name = name.to_lowercase(); + if name == ".env" + || (name.starts_with(".env.") && !ENV_TEMPLATES.iter().any(|suffix| name.ends_with(suffix))) + { + return Some("an environment file"); + } + if SECRET_SUFFIXES.iter().any(|suffix| name.ends_with(suffix)) { + return Some("a key or certificate"); + } + if KEY_NAMES.contains(&name.as_str()) { + return Some("a private key"); + } + if name == "credentials.json" || name.starts_with("secrets.") { + return Some("a credentials file"); + } + if name.ends_with(".loop-tmp") { + return Some("a temporary file of the loop"); + } + None +} + +/// A staged file and its size on disk. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StagedFile { + pub path: String, + pub bytes: u64, +} + +/// Whether the file is over `MAX_STAGED_BYTES`. +pub fn too_big(file: &StagedFile) -> bool { + file.bytes > MAX_STAGED_BYTES +} + +/// Staged files the loop refuses to commit, by their names. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StagedProblem { + pub files: Vec, + pub why: &'static str, + /// Set when the files could not be taken out of the index again: git's + /// first line. They are still staged. + pub left_staged: Option, +} + +/// Why `stage_and_check` stopped: `git add` itself failed, or the staged list +/// holds something that must not be committed (and was unstaged again). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StageError { + Add(CommitFailure), + Problem(StagedProblem), +} + +/// Stage everything and look at the list before anything is marked. Any +/// secret-looking or oversized file takes everything out of the index again and +/// returns every offending path. +pub fn stage_and_check(project: &Path) -> Result<(), StageError> { + let added = loop_tools::git_add_all(project); + if !added.ok { + return Err(StageError::Add(CommitFailure { + stage: Stage::Add, + first_line: first_line(&added.output), + output: added.output, + })); + } + let staged = loop_tools::git_staged(project).map_err(|output| { + StageError::Add(CommitFailure { + stage: Stage::Add, + first_line: first_line(&output), + output, + }) + })?; + // Staged names are relative to the repository's top folder. + let top = loop_tools::git_toplevel(project).unwrap_or_else(|| project.to_path_buf()); + let mut secrets = false; + let mut big = false; + let mut files = Vec::new(); + for path in staged { + // A deleted file is gone from the tree: it counts as 0 bytes. + let bytes = std::fs::symlink_metadata(top.join(&path)).map_or(0, |m| m.len()); + let file = StagedFile { path, bytes }; + let is_secret = denied(&file.path).is_some(); + let is_big = too_big(&file); + if is_secret || is_big { + secrets |= is_secret; + big |= is_big; + files.push(file.path); + } + } + if files.is_empty() { + return Ok(()); + } + let unstaged = loop_tools::git_unstage_all(project); + let left_staged = (!unstaged.ok).then(|| first_line(&unstaged.output)); + let why = match (secrets, big) { + (true, true) => "look like secrets or are over 5 MB", + (true, false) => "look like secrets", + _ => "are over 5 MB", + }; + Err(StageError::Problem(StagedProblem { + files, + why, + left_staged, + })) +} + +/// Commit what `stage_and_check` staged, plus the two files the mark changed +/// since: the phase file and `overview.md`. The short hash of the new commit. +/// `limit` is the commit's own time limit, for a slow hook. +pub fn commit( + project: &Path, + prepared: &Prepared, + marked: &Marked, + limit: Duration, +) -> Result, CommitFailure> { + let added = loop_tools::git_add_paths(project, &[&prepared.phase_file, &marked.overview]); + if !added.ok { + return Err(CommitFailure { + stage: Stage::Add, + first_line: first_line(&added.output), + output: added.output, + }); + } + let done = loop_tools::git_commit_with(project, &prepared.message, limit); + if !done.ok { + // A cut-off commit says so on its last line, after whatever a hook + // printed first; lead with that. + let cut_off = done + .output + .lines() + .last() + .filter(|line| line.starts_with("(stopped after")) + .map(|line| { + format!( + "the commit was {} (a hook ran too long)", + line.trim_matches(|c| c == '(' || c == ')') + ) + }); + return Err(CommitFailure { + stage: Stage::Commit, + first_line: cut_off.unwrap_or_else(|| first_line(&done.output)), + output: done.output, + }); + } + Ok(loop_tools::git_head_short(project)) +} + +/// Take what a failed commit left staged out of the index, so a commit the +/// person makes by hand does not carry a mark the loop took back. +pub fn unstage(project: &Path) { + let _ = loop_tools::git_unstage_all(project); +} + +/// The phases the spec shows done (`done`) that the commit log does not hold: +/// one the loop built whose recorded commit is gone from the history, and the +/// phase a failed undo left marked. A phase the loop never recorded is trusted +/// (the person built it). +pub fn marks_without_commits( + project: &Path, + _spec: &str, + done: &[u32], + report: &LoopReport, +) -> Vec { + let mut missing: Vec = report + .passed() + .iter() + .filter(|entry| done.contains(&entry.phase)) + .filter(|entry| { + entry + .commit + .as_deref() + .is_some_and(|hash| !loop_tools::git_commit_exists(project, hash)) + }) + .map(|entry| entry.phase) + .collect(); + if let Some(left) = &report.marked_not_committed { + if done.contains(&left.phase) && !missing.contains(&left.phase) { + missing.push(left.phase); + } + } + missing.sort_unstable(); + missing +} + +/// With commit on, the phases `status` shows done that have no commit behind +/// them (see `marks_without_commits`). With commit off a mark is trusted. +/// Reads only: nothing is written until the person has confirmed the Start. +pub fn unbacked_marks( + project: &Path, + spec: &str, + status: &Value, + report: &LoopReport, + commit: bool, +) -> Vec { + if !commit { + return Vec::new(); + } + let done: Vec = status["phases"] + .as_array() + .map(|all| { + all.iter() + .filter(|p| p["marker"].as_str() == Some("x")) + .filter_map(|p| u32::try_from(p["number"].as_u64()?).ok()) + .collect() + }) + .unwrap_or_default(); + marks_without_commits(project, spec, &done, report) +} + +/// Open each of `phases` again through `specs.mjs`: `open` first, which also +/// sets a Complete phase file back to In Progress, then `in-progress`. +pub fn reopen(project: &Path, spec: &str, phases: &[u32]) -> Result<(), String> { + for &n in phases { + for to in ["open", "in-progress"] { + let run = loop_tools::specs_mark(project, spec, n, to); + if !run.ok { + return Err(format!( + "Phase {n} is marked done with no commit, and could not be opened again: {}", + first_line(&run.output) + )); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn temp_spec(name: &str) -> (PathBuf, PathBuf) { + let base = std::env::temp_dir().join(format!( + "plan2code-loop-commit-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&base); + let spec = base.join("specs/lunch"); + std::fs::create_dir_all(&spec).unwrap(); + (base, spec) + } + + #[test] + fn the_first_line_skips_blanks_and_is_cut_at_160_characters() { + assert_eq!(first_line("\n \n lint says no \nsecond"), "lint says no"); + assert_eq!(first_line(""), ""); + let long = "x".repeat(300); + let line = first_line(&long); + assert_eq!(line.chars().count(), 160); + assert!(line.ends_with("...")); + assert_eq!(first_line(&"y".repeat(160)).chars().count(), 160); + } + + #[test] + fn a_phase_file_must_be_a_plain_name_that_exists() { + let (base, spec) = temp_spec("names"); + std::fs::write(spec.join("phase-2.md"), "x").unwrap(); + std::fs::write(base.join("secret.md"), "x").unwrap(); + let ok = phase_file(&base, "specs/lunch", &json!({ "file": "phase-2.md" })); + assert_eq!(ok.unwrap(), spec.join("phase-2.md")); + for (entry, word) in [ + (json!({}), "no phase file"), + (json!({ "file": "" }), "no phase file"), + (json!({ "file": " " }), "no phase file"), + (json!({ "file": "../../secret.md" }), "plain file name"), + (json!({ "file": "sub/phase-2.md" }), "plain file name"), + (json!({ "file": "sub\\phase-2.md" }), "plain file name"), + (json!({ "file": "C:phase-2.md" }), "plain file name"), + (json!({ "file": "phase-9.md" }), "does not exist"), + ] { + let err = phase_file(&base, "specs/lunch", &entry).unwrap_err(); + assert!(err.contains(word), "{entry}: {err}"); + } + } + + const OVERVIEW: &str = + "# Lunch - Overview\n\n## Phase Checklist\n\n- [/] [Phase 2: P2](./phase-2.md)\n"; + const PHASE: &str = "# Phase 2: P2\n\n**Status:** In Progress\n\n## Tasks\n\n- [x] **Task 2.1:** First\n\n## Phase Completion Summary\n\nBuilt it.\n"; + + fn marked_spec(name: &str) -> (PathBuf, Prepared) { + let (base, spec) = temp_spec(name); + std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap(); + std::fs::write(spec.join("phase-2.md"), PHASE).unwrap(); + let prepared = Prepared { + message: "Add it\n\nAI Assisted".to_string(), + phase_file: spec.join("phase-2.md"), + }; + (base, prepared) + } + + fn node_ready() -> bool { + loop_tools::skill_script("specs.mjs").is_some() + && std::process::Command::new("node") + .arg("--version") + .output() + .is_ok_and(|out| out.status.success()) + } + + #[test] + fn mark_writes_the_approval_line_and_undo_puts_both_files_back() { + if !node_ready() { + assert!(std::env::var_os("CI").is_none(), "node is not on PATH"); + return; + } + let (base, prepared) = marked_spec("undo"); + let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved by the loop.").unwrap(); + let overview = std::fs::read_to_string(&marked.overview).unwrap(); + assert!(overview.contains("[x] [Phase 2"), "{overview}"); + let phase = std::fs::read_to_string(&prepared.phase_file).unwrap(); + assert!(phase.contains("Approved by the loop."), "{phase}"); + assert_eq!(phase, marked.written); + undo(&prepared, &marked).unwrap(); + assert_eq!( + std::fs::read_to_string(&prepared.phase_file).unwrap(), + PHASE + ); + assert_eq!(std::fs::read_to_string(&marked.overview).unwrap(), OVERVIEW); + } + + #[test] + fn undo_will_not_overwrite_an_edit_made_since_and_names_the_file() { + if !node_ready() { + assert!(std::env::var_os("CI").is_none(), "node is not on PATH"); + return; + } + let (base, prepared) = marked_spec("edited"); + let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap(); + let mut edited = marked.written.clone(); + edited.push_str("\nMy own note.\n"); + std::fs::write(&prepared.phase_file, &edited).unwrap(); + let err = undo(&prepared, &marked).unwrap_err(); + assert!(err.contains("phase-2.md"), "{err}"); + assert!(!err.contains("overview.md"), "{err}"); + assert_eq!( + std::fs::read_to_string(&prepared.phase_file).unwrap(), + edited, + "the edit stays" + ); + assert_eq!( + std::fs::read_to_string(&marked.overview).unwrap(), + marked.overview_written, + "nothing is restored unless both files can be" + ); + } + + #[test] + fn prepare_refuses_an_unsafe_phase_file_before_anything_is_touched() { + let (base, prepared) = marked_spec("prepare"); + for file in ["../../secret.md", "", "phase-9.md"] { + let err = + prepare(&base, "specs/lunch", &json!({ "file": file }), "Add it").unwrap_err(); + assert!(!err.is_empty()); + } + assert_eq!( + std::fs::read_to_string(&prepared.phase_file).unwrap(), + PHASE + ); + let overview = base.join("specs/lunch/overview.md"); + assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW); + } + + #[test] + fn marks_are_found_with_commit_on_and_reopened_only_when_asked() { + if !node_ready() { + assert!(std::env::var_os("CI").is_none(), "node is not on PATH"); + return; + } + let (base, prepared) = marked_spec("reopen"); + mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap(); + let status = loop_tools::specs_status(&base, "specs/lunch").unwrap(); + assert_eq!(status["phases"][0]["marker"], "x"); + let mut report = LoopReport::new("specs/lunch", "now"); + report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted { + phase: 2, + file: "phase-2.md".into(), + }); + // Commit off: a mark is trusted. + assert!(unbacked_marks(&base, "specs/lunch", &status, &report, false).is_empty()); + // Commit on: the saved fact names the phase, and finding it writes nothing. + let found = unbacked_marks(&base, "specs/lunch", &status, &report, true); + assert_eq!(found, vec![2]); + let still = loop_tools::specs_status(&base, "specs/lunch").unwrap(); + assert_eq!(still["phases"][0]["marker"], "x"); + // Reopening sets the overview and the phase file's Status back. + reopen(&base, "specs/lunch", &found).unwrap(); + let after = loop_tools::specs_status(&base, "specs/lunch").unwrap(); + assert_eq!(after["phases"][0]["marker"], "/"); + let phase = std::fs::read_to_string(&prepared.phase_file).unwrap(); + assert!(phase.contains("**Status:** In Progress"), "{phase}"); + } + + #[test] + fn a_failed_mark_leaves_both_files_as_they_were() { + if !node_ready() { + assert!(std::env::var_os("CI").is_none(), "node is not on PATH"); + return; + } + let (base, prepared) = marked_spec("failed-mark"); + // Phase 9 is not in the overview, so the script refuses. + let err = mark(&prepared, &base, "specs/lunch", 9, "Approved.").unwrap_err(); + assert!(!err.message.is_empty()); + assert!(!err.put_back_failed); + assert_eq!( + std::fs::read_to_string(&prepared.phase_file).unwrap(), + PHASE + ); + let overview = base.join("specs/lunch/overview.md"); + assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW); + } + + #[test] + fn a_report_that_names_a_marked_phase_is_rebuilt_only_when_the_spec_shows_it_done() { + let (base, _) = temp_spec("marks"); + let mut report = LoopReport::new("specs/lunch", "now"); + report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted { + phase: 3, + file: "phase-3.md".into(), + }); + assert_eq!( + marks_without_commits(&base, "specs/lunch", &[1, 3], &report), + vec![3] + ); + assert!(marks_without_commits(&base, "specs/lunch", &[1], &report).is_empty()); + } + + fn git_in(repo: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .args(args) + .current_dir(repo) + .output() + .expect("run git"); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + fn git_ready() -> bool { + let found = std::process::Command::new("git") + .arg("--version") + .output() + .is_ok_and(|out| out.status.success()); + if !found { + assert!(std::env::var_os("CI").is_none(), "git is not on PATH"); + } + found + } + + #[test] + fn secret_looking_names_are_denied_and_templates_are_not() { + for name in [ + ".env", + ".env.local", + ".env.production", + ".ENV", + "a/b/.env", + "server.pem", + "tls.KEY", + "cert.p12", + "cert.pfx", + "release.keystore", + "id_rsa", + "home/.ssh/id_ed25519", + "credentials.json", + "config\\credentials.json", + "secrets.yml", + "Secrets.json", + "x/y.loop-tmp", + ] { + assert!(denied(name).is_some(), "{name} should be denied"); + } + for name in [ + ".env.example", + ".env.production.example", + ".env.local.sample", + ".env.sample", + ".env.template", + "app/.env.EXAMPLE", + "environment.md", + "monkey.txt", + "keyboard.rs", + "id_rsa.pub", + "my-credentials.json.md", + "secretsauce.md", + "src/.env/readme.md", + "tmp.loop-tmp.md", + ] { + assert_eq!(denied(name), None, "{name} should be allowed"); + } + } + + #[test] + fn a_file_is_too_big_only_over_five_megabytes() { + let file = |bytes| StagedFile { + path: "a.bin".into(), + bytes, + }; + assert!(!too_big(&file(0))); + assert!(!too_big(&file(MAX_STAGED_BYTES))); + assert!(too_big(&file(MAX_STAGED_BYTES + 1))); + } + + fn init_repo(name: &str) -> PathBuf { + let (base, _) = temp_spec(name); + git_in(&base, &["init", "-q"]); + for (key, value) in [ + ("user.name", "Loop Test"), + ("user.email", "loop@example.com"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git_in(&base, &["config", key, value]); + } + base + } + + #[test] + fn staging_stops_on_every_secret_and_oversized_file_and_unstages_all() { + if !git_ready() { + return; + } + let repo = init_repo("stage-problem"); + std::fs::write(repo.join("ok.txt"), "fine").unwrap(); + std::fs::write(repo.join(".env"), "KEY=1").unwrap(); + std::fs::write(repo.join(".env.example"), "KEY=").unwrap(); + std::fs::create_dir_all(repo.join("sub")).unwrap(); + std::fs::write(repo.join("sub/server.pem"), "x").unwrap(); + let big = std::fs::File::create(repo.join("big.bin")).unwrap(); + big.set_len(MAX_STAGED_BYTES + 1).unwrap(); + // No commit yet: unstaging must work without a HEAD. + let Err(StageError::Problem(problem)) = stage_and_check(&repo) else { + panic!("expected a problem"); + }; + let mut files = problem.files.clone(); + files.sort(); + assert_eq!(files, vec![".env", "big.bin", "sub/server.pem"]); + assert_eq!(problem.why, "look like secrets or are over 5 MB"); + assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), ""); + + // Once the offenders are gone, the same call stages the rest. + std::fs::remove_file(repo.join(".env")).unwrap(); + std::fs::remove_file(repo.join("big.bin")).unwrap(); + std::fs::remove_file(repo.join("sub/server.pem")).unwrap(); + stage_and_check(&repo).expect("a clean list passes"); + let staged = git_in(&repo, &["diff", "--cached", "--name-only"]); + assert!(staged.contains("ok.txt") && staged.contains(".env.example")); + } + + #[test] + fn a_deleted_ordinary_file_passes_and_a_big_one_alone_says_so() { + if !git_ready() { + return; + } + let repo = init_repo("stage-deleted"); + std::fs::write(repo.join("a.txt"), "a").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "First"]); + std::fs::remove_file(repo.join("a.txt")).unwrap(); + stage_and_check(&repo).expect("a deletion of an ordinary file passes"); + git_in(&repo, &["reset", "-q"]); + let big = std::fs::File::create(repo.join("huge.dat")).unwrap(); + big.set_len(MAX_STAGED_BYTES + 1).unwrap(); + let Err(StageError::Problem(problem)) = stage_and_check(&repo) else { + panic!("expected a problem"); + }; + assert_eq!(problem.files, vec!["huge.dat"]); + assert_eq!(problem.why, "are over 5 MB"); + assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), ""); + } + + #[test] + fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() { + if !git_ready() || !node_ready() { + return; + } + let repo = init_repo("commit-ignored"); + std::fs::write(repo.join(".gitignore"), "specs/\n").unwrap(); + std::fs::write(repo.join("a.txt"), "a").unwrap(); + let spec = repo.join("specs/lunch"); + std::fs::create_dir_all(&spec).unwrap(); + std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap(); + std::fs::write(spec.join("phase-2.md"), PHASE).unwrap(); + let prepared = Prepared { + message: "Add it\n\nAI Assisted".to_string(), + phase_file: spec.join("phase-2.md"), + }; + stage_and_check(&repo).unwrap(); + let marked = mark(&prepared, &repo, "specs/lunch", 2, "Approved.").unwrap(); + let head = commit(&repo, &prepared, &marked, Duration::from_secs(30)).unwrap(); + assert!(head.is_some()); + let shown = git_in(&repo, &["show", "--name-only", "--format=%s", "HEAD"]); + assert!(shown.contains("a.txt"), "{shown}"); + assert!(!shown.contains("specs/"), "{shown}"); + } + + #[test] + fn a_recorded_commit_hash_is_checked_against_the_history() { + if !git_ready() { + return; + } + let (base, _) = temp_spec("hashes"); + git_in(&base, &["init", "-q"]); + for (key, value) in [ + ("user.name", "Loop Test"), + ("user.email", "loop@example.com"), + ("commit.gpgsign", "false"), + ] { + git_in(&base, &["config", key, value]); + } + std::fs::write(base.join("a.txt"), "a").unwrap(); + git_in(&base, &["add", "-A"]); + git_in(&base, &["commit", "-q", "-m", "First"]); + let real = git_in(&base, &["rev-parse", "--short", "HEAD"]); + assert!(loop_tools::git_commit_exists(&base, &real)); + assert!(!loop_tools::git_commit_exists(&base, "deadbee")); + assert!(!loop_tools::git_commit_exists(&base, "")); + assert!(!loop_tools::git_commit_exists(&base, "--all")); + assert!(!loop_tools::git_commit_exists(&base, "HEAD")); + + let entry = |phase: u32, commit: Option<&str>| crate::loop_report::ReportEntry { + phase, + commit: commit.map(str::to_string), + ..crate::loop_report::ReportEntry::default() + }; + let mut report = LoopReport::new("specs/lunch", "now"); + report.entries.push(entry(2, Some(real.as_str()))); + report.entries.push(entry(3, Some("deadbee"))); + // Built with commit off: no hash, so nothing to check. + report.entries.push(entry(4, None)); + // Never recorded by the loop (built by hand): trusted. + let done = [1, 2, 3, 4]; + assert_eq!( + marks_without_commits(&base, "specs/lunch", &done, &report), + vec![3] + ); + // A phase the spec no longer shows done is not listed. + assert!(marks_without_commits(&base, "specs/lunch", &[2], &report).is_empty()); + } +} diff --git a/plan2code-app/src-tauri/src/loop_driver.rs b/plan2code-app/src-tauri/src/loop_driver.rs new file mode 100644 index 0000000..af32114 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_driver.rs @@ -0,0 +1,5750 @@ +//! The Implementation Loop's driver: one fresh agent per phase, the app judging +//! what each one reports. The agent builds and reports (`loopOutcome`); only +//! this module marks a phase done and commits it (NFR-3). The running record +//! lives in memory alone, so an app restart ends the loop and a new Start picks +//! up from the spec's marks (NFR-5). +//! +//! The judgment is in pure functions (`phase_prompt`, `judge_outcome`, +//! `silence_expired`, `should_retry`, `step_for_stage`, `open_question`, +//! `stop_line`, `evidence_markdown`, `with_approval_line`, `summary_markdown`) +//! so they test without an agent. A crashed or silent agent gets one fresh +//! retry; every other failure stops at once through `stop_loop`, the one place +//! a stop goes, with its evidence on the page. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::agent_manager::{AgentManager, AgentState}; +use crate::agents::{Agent, PermissionMode}; +use crate::console_supervisor::find_console_dir; +use crate::loop_commit; +use crate::loop_notify::{self, NotifyKind}; +use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry}; +use crate::loop_tools; +use crate::session_reader::{self, ReadError}; + +// ---------------------------------------------------------------- the setup + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum FixMode { + #[default] + Levels, + Smart, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FixLevel { + Critical, + Warning, + Suggestion, +} + +impl FixLevel { + pub fn word(self) -> &'static str { + match self { + FixLevel::Critical => "critical", + FixLevel::Warning => "warning", + FixLevel::Suggestion => "suggestion", + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum OnQuestion { + Pause, + Stop, + #[default] + Guess, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum AfterLast { + #[default] + OfferFinalize, + RunFinalize, +} + +/// One project's entry in `loop-setup.json`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct LoopSetup { + pub review: bool, + // An entry saved before this field existed fixed by level, so it keeps + // doing that (FixMode's own default) rather than taking the new setup's. + #[serde(default)] + pub fix_mode: FixMode, + pub fix: Vec, + pub commit: bool, + pub on_question: OnQuestion, + pub after_last: AfterLast, + pub quick_check: String, + pub retry_once: bool, + pub silence_minutes: u32, + /// How the notification is sent, when the loop needs the person or ends. + pub notify_kind: NotifyKind, + /// The web address it goes to; empty for none. + pub notify_url: String, + /// The query parameter or JSON field that carries the message, for the + /// kinds that let the person name it. + pub notify_param: String, +} + +impl Default for LoopSetup { + fn default() -> Self { + LoopSetup { + review: true, + fix_mode: FixMode::Smart, + fix: vec![FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion], + commit: true, + on_question: OnQuestion::Guess, + after_last: AfterLast::OfferFinalize, + quick_check: String::new(), + retry_once: true, + silence_minutes: 20, + notify_kind: NotifyKind::Query, + notify_url: String::new(), + notify_param: loop_notify::DEFAULT_PARAM.to_string(), + } + } +} + +impl LoopSetup { + /// The levels whose leftovers matter: every level in Smart pick. + fn chosen_levels(&self) -> Vec { + if !self.review { + return Vec::new(); + } + match self.fix_mode { + FixMode::Smart => vec![FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion], + FixMode::Levels => self.fix.clone(), + } + } +} + +// -------------------------------------------------------------- the outcome + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Finding { + pub level: FixLevel, + #[serde(default)] + pub title: String, + #[serde(default)] + pub file: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct Triage { + pub ran: bool, + pub skipped: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct Left { + pub critical: u32, + pub warning: u32, + pub suggestion: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct ReviewPart { + pub ran: bool, + pub recheck: bool, + pub triage: Option, + pub left: Left, + pub unfixed: Vec, + pub fixed: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct TasksPart { + pub blocked: Vec, + pub assumed: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct TestsPart { + pub ran: bool, + pub passed: bool, + pub summary: String, +} + +/// What a phase's skill reported (`loopOutcome`, overview API). +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct Outcome { + pub phase: u32, + pub result: String, + pub reason: Option, + pub summary: String, + pub tests: Option, + pub review: Option, + pub tasks: TasksPart, + pub conflicts: Vec, + pub decisions: Vec, + pub subject: String, +} + +// -------------------------------------------------------------- the record + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Step { + Starting, + Build, + Review, + Fixes, + Recheck, + WaitingOnYou, + Checking, + Commit, +} + +impl Step { + pub fn label(&self) -> &'static str { + match self { + Step::Starting => "Starting", + Step::Build => "Build", + Step::Review => "Review", + Step::Fixes => "Fixes", + Step::Recheck => "Re-check", + Step::WaitingOnYou => "Waiting on you", + Step::Checking => "Checking", + Step::Commit => "Commit", + } + } +} + +/// The step a console headline stage names; any other word is Build. +pub fn step_for_stage(stage: &str) -> Step { + let stage = stage.to_lowercase(); + if stage.contains("re-check") || stage.contains("recheck") { + Step::Recheck + } else if stage.contains("fix") { + Step::Fixes + } else if stage.contains("review") { + Step::Review + } else { + Step::Build + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PhaseStatus { + Pending, + Running, + Done, + Stopped, +} + +#[derive(Clone, Debug)] +pub struct PhaseRecord { + pub n: u32, + pub name: String, + pub status: PhaseStatus, + pub commit: Option, + pub subject: Option, + pub retries: u32, +} + +#[derive(Clone, Debug)] +pub struct RunningRecord { + /// Tells a watch thread whether the record is still its own loop's. + pub run_id: u64, + pub project: PathBuf, + pub spec: String, + pub setup: LoopSetup, + pub phases: Vec, + pub current: usize, + pub step: Step, + pub sid: Option, + /// The latest phase session seen, kept across phases so a stop that comes + /// before the next session opens can still be told to the page. + pub last_sid: Option, + pub started_at: Instant, + /// The same moment as epoch milliseconds, for the strip's elapsed clock. + pub started_at_ms: u64, + pub phase_started_at: Instant, + /// The last sign of work (session files, the tree), for silence. + pub last_activity: SystemTime, + /// When the session files and the tree were last looked at. + pub activity_checked: Instant, + pub retries_used: u32, + pub stop_after_phase: bool, + /// Set by Stop now; the watch thread ends the loop on its next look. + pub stop_now: bool, + /// A question holds the loop (step Waiting on you). + pub waiting: bool, + /// The current phase's agent generation, to tell its end from an older one's. + pub generation: u64, + /// The phase's report and its entry from `specs.mjs status`, kept for the + /// evidence document. + pub last_outcome: Option, + pub last_entry: Option, + /// Output of the call that stopped the loop (a refused commit's hook), kept + /// for the evidence document. + pub failure_output: Option, + /// Why the call to the web address failed while a question held the loop. + pub notify_failure: Option, + /// Everything this build has done, across stops and resumes. + pub report: LoopReport, + /// Why the report could not be saved, the last time it could not. + pub report_failure: Option, + /// Phases Start found marked done with no commit behind them and opened again. + pub rebuilt: Vec, + /// A Resume on a dirty tree: how many uncommitted files the resumed phase's + /// commit will take. + pub resumed_files: Option, + /// The branch the loop started on (None: not known, or commit off outside + /// a repository). A detached HEAD never starts a loop. + pub branch: Option, + /// `HEAD` when the loop started, kept for later use (nothing shows it yet). + pub start_head: Option, + /// Files that were already changed when the loop started: the person's own + /// work, left out of the stop screen's list of the agent's. + pub own_dirty: Vec, + /// How many looks in a row could not read the phase's session; reset by + /// the next good read. While it is above zero a silence stop says why. + pub read_failures: u32, +} + +fn report_time() -> String { + chrono::Local::now().format("%Y-%m-%d %H:%M").to_string() +} + +fn epoch_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| u64::try_from(d.as_millis()).unwrap_or(0)) + .unwrap_or(0) +} + +impl RunningRecord { + pub fn new( + project: PathBuf, + spec: String, + setup: LoopSetup, + phases: Vec, + ) -> RunningRecord { + let now = Instant::now(); + let report = LoopReport::new(&spec, &report_time()); + RunningRecord { + run_id: NEXT_RUN.fetch_add(1, Ordering::SeqCst), + project, + spec, + setup, + phases, + current: 0, + step: Step::Starting, + sid: None, + last_sid: None, + started_at: now, + started_at_ms: epoch_ms(), + phase_started_at: now, + last_activity: SystemTime::now(), + activity_checked: now, + retries_used: 0, + stop_after_phase: false, + stop_now: false, + waiting: false, + generation: 0, + last_outcome: None, + last_entry: None, + failure_output: None, + notify_failure: None, + report, + report_failure: None, + rebuilt: Vec::new(), + resumed_files: None, + branch: None, + start_head: None, + own_dirty: Vec::new(), + read_failures: 0, + } + } +} + +/// What the strip in the app's top bar shows (`loop-state` event). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LoopStateEvent { + pub running: bool, + pub spec_name: String, + /// The current phase's number in the spec, and the run's last phase number. + pub phase: u32, + pub phases: u32, + pub phase_name: String, + /// The phase this run built just before the current one, while the next starts. + pub previous_phase: Option, + pub previous_committed: bool, + /// The current phase has used its retry. + pub phase_retried: bool, + pub step: String, + pub started_at_ms: u64, + pub retries_used: u32, + pub stop_after_phase: bool, + /// Stop now was pressed: the agent is ending and nothing more is committed. + pub stopping: bool, + /// Stop after this phase can be turned on (false on the run's last phase). + pub can_stop_after: bool, +} + +impl LoopStateEvent { + /// The last event of a loop: the strip goes away. + pub fn ended() -> LoopStateEvent { + LoopStateEvent { + running: false, + spec_name: String::new(), + phase: 0, + phases: 0, + phase_name: String::new(), + previous_phase: None, + previous_committed: false, + phase_retried: false, + step: String::new(), + started_at_ms: 0, + retries_used: 0, + stop_after_phase: false, + stopping: false, + can_stop_after: false, + } + } +} + +pub fn state_event(rec: &RunningRecord) -> LoopStateEvent { + let current = rec.phases.get(rec.current); + let previous = rec + .current + .checked_sub(1) + .and_then(|at| rec.phases.get(at)) + .filter(|p| p.status == PhaseStatus::Done); + LoopStateEvent { + running: true, + spec_name: rec + .spec + .strip_prefix("specs/") + .unwrap_or(&rec.spec) + .to_string(), + phase: rec.phases.get(rec.current).map_or(0, |p| p.n), + phases: rec.phases.last().map_or(0, |p| p.n), + phase_name: current.map_or_else(String::new, |p| p.name.clone()), + previous_phase: previous.map(|p| p.n), + previous_committed: previous.is_some_and(|p| p.commit.is_some()), + phase_retried: current.is_some_and(|p| p.retries > 0), + step: rec.step.label().to_string(), + started_at_ms: rec.started_at_ms, + retries_used: rec.retries_used, + stop_after_phase: rec.stop_after_phase, + stopping: rec.stop_now, + can_stop_after: rec.current + 1 < rec.phases.len(), + } +} + +/// The running loop's strip state, or `None` when no loop runs. +pub fn current_event(slot: &LoopSlot) -> Option { + lock(slot).as_ref().map(state_event) +} + +/// What Resume, Fix it by hand and Finalize need after the running record is +/// gone. Memory only (NFR-5). +#[derive(Clone)] +pub struct LastLoop { + pub project: PathBuf, + pub spec: String, + pub launch: Launch, + /// The quick check the person last confirmed in the Start dialog. + pub confirmed_check: String, + /// The notification the person last confirmed there. + pub confirmed_notify: String, +} + +pub type LoopSlot = Arc>>; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Verdict { + /// The phase holds. `warnings` are things to show on the report that do + /// not stop the loop (leftover Suggestions). + Approve { + warnings: Vec, + }, + Refuse(String), +} + +/// A poisoned mutex is still taken: the watcher catches its own panics (see +/// `watch_with`), and a panic inside a lock poisons it, so the stop that +/// follows must still be able to clear the slot. +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +// ---------------------------------------------------------- pure judgment + +/// The first prompt of a phase's fresh agent. +pub fn phase_prompt(spec: &str, setup: &LoopSetup) -> String { + let skill = if setup.review { + "plan2code-3-implement-review" + } else { + "plan2code-3-implement" + }; + let mut prompt = format!("/{skill} {spec}/overview.md --web --loop"); + if setup.review { + if setup.fix_mode == FixMode::Smart { + prompt.push_str(" --fix smart"); + } else if !setup.fix.is_empty() { + let levels: Vec<&str> = [FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion] + .into_iter() + .filter(|level| setup.fix.contains(level)) + .map(FixLevel::word) + .collect(); + prompt.push_str(&format!(" --fix {}", levels.join(","))); + } + } + if setup.on_question == OnQuestion::Guess { + prompt.push_str(" --guess"); + } + prompt +} + +fn count(tasks: &Value, key: &str) -> u64 { + counted(tasks, key).unwrap_or(0) +} + +/// A task count the spec's status gave, or `None` when the key is missing, so a +/// missing count is never read as zero. +fn counted(tasks: &Value, key: &str) -> Option { + tasks.get(key).and_then(Value::as_u64) +} + +/// How many findings of `level` the phase left: the report's counter or the +/// length of its unfixed list, whichever is larger. An agent can miscount, so +/// neither is trusted alone. +fn leftover(review: &ReviewPart, level: FixLevel) -> u32 { + let counter = match level { + FixLevel::Critical => review.left.critical, + FixLevel::Warning => review.left.warning, + FixLevel::Suggestion => review.left.suggestion, + }; + let listed = review.unfixed.iter().filter(|f| f.level == level).count(); + counter.max(u32::try_from(listed).unwrap_or(u32::MAX)) +} + +/// Why a phase says it failed, for the stop line and the notification: what the +/// agent wrote, which a person can read, else the contract's reason in words. +fn failed_words(outcome: &Outcome) -> String { + let summary = outcome.summary.trim(); + if !summary.is_empty() { + return summary.to_string(); + } + match outcome.reason.as_deref() { + Some("tests") => "its tests failed", + Some("findings") => "the review left findings it had to fix", + Some("blocked") => "a task is blocked", + Some("conflict") => "the spec conflicts with the code", + _ => "it reported a failure", + } + .to_string() +} + +/// The report's note about Suggestions the phase left unfixed, if any. They +/// never refuse a phase, but the person should see them. +fn suggestion_warning(review: &ReviewPart) -> Option { + let n = leftover(review, FixLevel::Suggestion); + (n > 0).then(|| { + format!( + "{n} Suggestion{} left unfixed", + if n == 1 { "" } else { "s" } + ) + }) +} + +/// Whether to take the skill's report at its word, cross-checked against the +/// spec's own marks (`phase_status` is the phase's entry from `specs.mjs +/// status`). The quick check runs after an Approve, not here. +pub fn judge_outcome(outcome: &Outcome, phase_status: &Value, setup: &LoopSetup) -> Verdict { + let refuse = |why: String| Verdict::Refuse(why); + if outcome.result == "failed" { + return refuse(failed_words(outcome)); + } + if outcome.result != "passed" { + return refuse(format!("the report said \"{}\"", outcome.result)); + } + // Missing data is never success: a phase the spec does not show, or shows + // without counts, cannot be taken at the report's word. + let n = outcome.phase; + if phase_status.is_null() { + return refuse(format!("the spec has no status for Phase {n}")); + } + let tasks = &phase_status["tasks"]; + if !tasks.is_object() { + return refuse(format!("the spec shows no task counts for Phase {n}")); + } + let Some(total) = counted(tasks, "total") else { + return refuse(format!("the spec shows no task total for Phase {n}")); + }; + if total == 0 { + return refuse(format!("the spec shows no tasks in Phase {n}")); + } + // A failed test run is a refusal even when every task is ticked. Blocked + // tasks and listed conflicts are not: the checks below cover blocked tasks + // through the spec's own marks, and a conflict the agent worked around is + // reported to the person, not refused (FR-7). + if let Some(tests) = &outcome.tests { + if tests.ran && !tests.passed { + let summary = one_line(&tests.summary); + return refuse(if summary.is_empty() { + "its tests ran and failed".to_string() + } else { + format!("its tests ran and failed: {summary}") + }); + } + } + let blocked = count(tasks, "blocked"); + // `open` already holds pending, in-progress, blocked and unknown tasks. + let open = count(tasks, "open"); + if blocked > 0 || open > 0 { + return refuse(format!( + "the spec disagrees: {blocked} blocked, {open} still open" + )); + } + let assumed = count(tasks, "assumed"); + if assumed > 0 && setup.on_question != OnQuestion::Guess { + return refuse("assumed tasks without best guess".to_string()); + } + let done = count(tasks, "complete") + assumed; + if done != total { + return refuse(format!("the spec shows {done} of {total} tasks done")); + } + let mut warnings = Vec::new(); + if setup.review { + let review = outcome.review.clone().unwrap_or_default(); + if !review.ran { + return refuse("review did not run".to_string()); + } + if setup.fix_mode == FixMode::Smart { + match &review.triage { + Some(triage) if triage.ran => { + let critical = triage + .skipped + .iter() + .filter(|f| f.level == FixLevel::Critical) + .count(); + if critical > 0 { + return refuse(format!("{critical} Critical skipped by the triage")); + } + } + _ => return refuse("the triage did not run".to_string()), + } + } + let chosen = setup.chosen_levels(); + if !chosen.is_empty() && !review.recheck { + return refuse("the re-check did not run".to_string()); + } + let mut left = Vec::new(); + let critical = leftover(&review, FixLevel::Critical); + if chosen.contains(&FixLevel::Critical) && critical > 0 { + left.push(format!("{critical} Critical")); + } + let warning = leftover(&review, FixLevel::Warning); + if chosen.contains(&FixLevel::Warning) && warning > 0 { + left.push(format!("{warning} Warning")); + } + if !left.is_empty() { + return refuse(format!("{} left after the re-check", left.join(" / "))); + } + warnings.extend(suggestion_warning(&review)); + } + Verdict::Approve { warnings } +} + +/// Whether the agent has been quiet too long. A waiting question never counts +/// (the person may take all night). The limit is the setup's silence minutes +/// or the skill's own `quietMinutes`, whichever is longer, at most 60. +pub fn silence_expired( + now: SystemTime, + last_activity: SystemTime, + setup: &LoopSetup, + quiet_minutes: Option, + waiting: bool, +) -> bool { + if waiting { + return false; + } + let minutes = setup + .silence_minutes + .max(quiet_minutes.unwrap_or(0)) + .min(60); + let limit = Duration::from_secs(u64::from(minutes) * 60); + now.duration_since(last_activity) + .is_ok_and(|quiet| quiet > limit) +} + +/// Why a loop ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StopCause { + Crash, + Silence, + Refused(String), + QuickCheck, + Commit, + /// The commit failed and the mark could not be taken back: the phase file + /// (named here) says done while its work is not committed. + MarkedNotCommitted(String), + /// The staged files hold something that looks like a secret or is over 5 MB + /// (every offending path). Nothing was marked or committed. + UnsafeFiles(Vec), + Question, + StoppedByPerson, + NoSession, + /// The watcher thread panicked (the panic's text, on one line). Never + /// retried: the loop's own code failed, not the agent. + WatcherFailed(String), +} + +/// One fresh retry for a crash, silence or an announce notice that never came +/// (a crash), when the setup allows it and the phase has not used it yet. A +/// failed watcher is never retried. +pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phase: u32) -> bool { + matches!( + cause, + StopCause::Crash | StopCause::Silence | StopCause::NoSession + ) && setup.retry_once + && retries_used_this_phase == 0 +} + +/// Whether the session state holds a question for the person: an item still +/// open or reopened, required, not handled by the loop and not just a notice. +pub fn open_question(state: &Value) -> bool { + state["items"].as_array().is_some_and(|items| { + items.iter().any(|item| { + matches!(item["status"].as_str(), Some("open" | "reopened")) + && item["required"].as_bool() != Some(false) + && item["kind"].as_str() != Some("notice") + && item.get("handledBy").is_none_or(Value::is_null) + }) + }) +} + +/// The line the stop screen leads with. `detail` is the exit reason for a +/// crash, the minutes for silence and the whole clause for a refused commit. +pub fn stop_line(cause: &StopCause, phase: u32, detail: &str, retried: bool) -> String { + let after = if retried { " after one retry" } else { "" }; + match cause { + StopCause::Crash => format!("Phase {phase} stopped: the agent crashed ({detail}){after}"), + StopCause::Silence => { + format!("Phase {phase} stopped: the agent went silent for {detail} minutes{after}") + } + StopCause::NoSession => { + format!("Phase {phase} stopped: the agent never opened the console{after}") + } + StopCause::Refused(why) => format!("Phase {phase} stopped: {why}"), + StopCause::QuickCheck => format!("Phase {phase} stopped: the quick check failed"), + StopCause::Commit => { + let why: String = one_line(detail).chars().take(100).collect(); + let why = if why.is_empty() { + "git gave no reason".to_string() + } else { + why + }; + format!( + "Phase {phase} was not committed: {why}. The work is uncommitted; Resume tries the commit again" + ) + } + StopCause::MarkedNotCommitted(file) => { + format!("Phase {phase} is marked done in {file} but its work is not committed") + } + StopCause::UnsafeFiles(files) => { + let shown: Vec<&str> = files.iter().take(5).map(String::as_str).collect(); + let more = match files.len().saturating_sub(5) { + 0 => String::new(), + m => format!(" and {m} more"), + }; + format!( + "Phase {phase} was not committed: {}{more} look like secrets or are over 5 MB. Nothing was marked or committed", + shown.join(", ") + ) + } + StopCause::Question => format!("Phase {phase} stopped: it asked a question"), + StopCause::StoppedByPerson => { + format!("Stopped during Phase {phase}. This phase's changes stay uncommitted.") + } + StopCause::WatcherFailed(text) => { + let text: String = one_line(text).chars().take(100).collect(); + format!( + "The loop's watcher failed: {text}. Nothing more was committed; Resume starts again" + ) + } + } +} + +// ---------------------------------------------------------- the setup file + +/// The key `loop-setup.json` keeps a project under: the console's `foldKey` +/// (resolved path, lowercased on Windows and macOS). +pub fn fold_key(project: &Path) -> String { + let mut text = project.to_string_lossy().into_owned(); + if let Some(rest) = text.strip_prefix(r"\\?\") { + text = rest.to_string(); + } + if cfg!(windows) { + text = text.replace('/', "\\"); + } + let sep: &[char] = if cfg!(windows) { &['\\'] } else { &['/'] }; + let trimmed = text.trim_end_matches(sep); + // A bare root ("C:\" or "/") keeps its separator. + let mut text = if trimmed.is_empty() || trimmed.ends_with(':') { + text + } else { + trimmed.to_string() + }; + if cfg!(windows) || cfg!(target_os = "macos") { + text = text.to_lowercase(); + } + text +} + +/// This project's saved setup. The app never takes setup values from a page +/// message: the quick check reaches it only from this file. +pub fn read_setup(project: &Path) -> Result { + let home = session_reader::console_home().ok_or("no home folder found")?; + read_setup_from(&home.join("loop-setup.json"), project) +} + +fn read_setup_from(file: &Path, project: &Path) -> Result { + const NONE: &str = "No loop setup saved for this project"; + let text = std::fs::read_to_string(file).map_err(|_| NONE.to_string())?; + let store: Value = serde_json::from_str(&text).map_err(|_| NONE.to_string())?; + if store["schema"].as_u64() != Some(1) { + return Err(NONE.to_string()); + } + let entry = store["projects"] + .get(fold_key(project)) + .ok_or_else(|| NONE.to_string())?; + serde_json::from_value(entry.clone()) + .map_err(|e| format!("The saved loop setup could not be read: {e}")) +} + +// ------------------------------------------------------------ the facts + +/// What the setup screen shows about the agent a loop would use. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LoopFacts { + pub agent: Option, + pub agent_label: Option, + pub model: Option, + pub effort: Option, + pub permission_mode: Option, + pub prompt_support: bool, + pub running: bool, +} + +/// Whether the agent's launch can carry a first prompt. Built-in agents take +/// one, and a custom agent's template gets it appended when no argument holds +/// `{prompt}` (`build_custom_args`); a future kind can answer false. +pub fn prompt_support(agent: &Agent) -> bool { + match agent { + Agent::Builtin(_) | Agent::Custom(_) => true, + } +} + +// -------------------------------------------------------- starting a loop + +/// `specs/`: one folder directly under `specs/`, not a link. +pub fn validate_spec(project: &Path, spec: &str) -> Result<(), String> { + let bad = || format!("not a spec folder: {spec}"); + let name = spec.strip_prefix("specs/").ok_or_else(bad)?; + if name.is_empty() + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return Err(bad()); + } + let meta = std::fs::symlink_metadata(project.join("specs").join(name)).map_err(|_| bad())?; + if !meta.is_dir() || meta.file_type().is_symlink() { + return Err(bad()); + } + Ok(()) +} + +static NEXT_RUN: AtomicU64 = AtomicU64::new(1); + +/// Everything Start checks before the confirm: the spec, the saved setup, the +/// phases left to build and the gates (FR-5). Starts nothing. +pub fn prepare( + project: &Path, + spec: &str, + mode: PermissionMode, + prompt_ok: bool, + resuming: bool, +) -> Result { + validate_spec(project, spec)?; + let setup = read_setup(project)?; + let report = session_reader::console_home() + .and_then(|home| loop_report::load(&home, project, spec)) + .unwrap_or_default(); + prepare_with(project, spec, setup, &report, mode, prompt_ok, resuming) +} + +/// `prepare` with the saved setup and report given. Reads only: a phase marked +/// done with no commit behind it stays in the list (`rebuilt`) and is opened +/// again by `reopen_rebuilt`, after the person has confirmed. +pub fn prepare_with( + project: &Path, + spec: &str, + setup: LoopSetup, + report: &LoopReport, + mode: PermissionMode, + prompt_ok: bool, + resuming: bool, +) -> Result { + if !setup.notify_url.is_empty() + && !loop_notify::valid_setup(setup.notify_kind, &setup.notify_url, &setup.notify_param) + { + return Err("The saved notification address is not valid".to_string()); + } + let status = loop_tools::specs_status(project, spec)?; + // With commit on, a "done" mark must have a commit behind it. + let rebuilt = loop_commit::unbacked_marks(project, spec, &status, report, setup.commit); + let phases: Vec = status["phases"] + .as_array() + .map(|all| { + all.iter() + .filter_map(|p| { + let n = u32::try_from(p["number"].as_u64()?).ok()?; + if p["marker"].as_str() == Some("x") && !rebuilt.contains(&n) { + return None; + } + Some(PhaseRecord { + n, + name: p["name"].as_str().unwrap_or("").to_string(), + status: PhaseStatus::Pending, + commit: None, + subject: None, + retries: 0, + }) + }) + .collect() + }) + .unwrap_or_default(); + if phases.is_empty() { + return Err("Nothing left to build".to_string()); + } + // A detached HEAD would leave every phase's commit on no branch at all. + // Outside a repository a loop with commit off may still run. + let branch = match loop_tools::git_branch(project) { + Ok(None) => { + return Err("HEAD is detached. Switch to a branch before starting the loop".to_string()) + } + Ok(branch) => branch, + Err(e) if setup.commit => return Err(e), + Err(_) => None, + }; + let own_dirty = loop_tools::git_status_porcelain(project).unwrap_or_default(); + let mut resumed_files = None; + if setup.commit { + let dirty = loop_tools::git_status_porcelain(project)?; + if !dirty.is_empty() { + // A Resume after this app stopped the spec carries the stopped + // phase's uncommitted work by design; a fresh Start needs a clean tree. + if !resuming { + return Err(format!( + "Commit each phase needs a clean tree: {} uncommitted changes", + dirty.len() + )); + } + resumed_files = Some(dirty.len()); + } + } + if mode == PermissionMode::Checked { + return Err( + "The loop needs permission checks off. Start a New Session with checks off first." + .to_string(), + ); + } + if !prompt_ok { + return Err( + "This agent cannot be started with a prompt, so it cannot run the loop.".to_string(), + ); + } + let mut rec = RunningRecord::new(project.to_path_buf(), spec.to_string(), setup, phases); + rec.rebuilt = rebuilt; + rec.resumed_files = resumed_files; + rec.branch = branch; + rec.start_head = loop_tools::git_head_full(project); + // On a resumed run this holds the stopped phase's work too, by design: it + // is listed as the person's own, the known limit of a baseline. + rec.own_dirty = own_dirty; + Ok(rec) +} + +/// Open again the phases `prepare` found marked done with no commit behind +/// them. Writes to the spec, so Start calls it only after the confirm. +pub fn reopen_rebuilt(rec: &RunningRecord) -> Result<(), String> { + loop_commit::reopen(&rec.project, &rec.spec, &rec.rebuilt) +} + +/// Whether `branch` is the repository's trunk, where a loop's commits land +/// straight on the shared line. +pub fn is_trunk(branch: &str) -> bool { + matches!(branch, "main" | "master") +} + +/// The stop screen's list: the agent's uncommitted files, at most 200. +fn uncommitted_files(project: &Path, own_dirty: &[String]) -> Vec { + let now = loop_tools::git_status_porcelain(project).unwrap_or_default(); + let mut files = agent_work(now, own_dirty); + files.truncate(200); + files +} + +/// Whether this loop will commit straight to `main` or `master`. A Resume never +/// skips its confirm then. +pub fn commits_to_trunk(rec: &RunningRecord) -> bool { + rec.setup.commit && rec.branch.as_deref().is_some_and(is_trunk) +} + +/// The files the agent changed: what `git status` lists now, less the files +/// that were already changed when the loop started. A file both the person and +/// the agent changed is hidden from the list, a known limit. +pub fn agent_work(now: Vec, own: &[String]) -> Vec { + now.into_iter().filter(|file| !own.contains(file)).collect() +} + +/// The app's own Start confirm. +pub fn confirm_text(rec: &RunningRecord) -> String { + let name = rec.spec.strip_prefix("specs/").unwrap_or(&rec.spec); + let n = rec.phases.len(); + let phases = if n == 1 { + "1 phase".to_string() + } else { + format!("{n} phases") + }; + let check = rec.setup.quick_check.trim(); + let mut text = if check.is_empty() { + format!("Build {phases} of {name}? No quick check is set.") + } else { + format!("Build {phases} of {name}? After each phase the app runs: {check}") + }; + if !rec.rebuilt.is_empty() { + let list: Vec = rec.rebuilt.iter().map(|n| format!("Phase {n}")).collect(); + text.push_str(&format!( + " {} is marked done but has no commit in the log, so it is built again.", + list.join(" and ") + )); + } + if let Some(files) = rec.resumed_files { + let files = if files == 1 { + "1 uncommitted file".to_string() + } else { + format!("{files} uncommitted files") + }; + text.push_str(&format!( + " The resumed phase's commit will take {files} already in the tree." + )); + } + if commits_to_trunk(rec) { + let branch = rec.branch.as_deref().unwrap_or_default(); + text.push_str(&format!( + " You are on `{branch}`: every phase will commit straight to it. Start only if that is what you want." + )); + } + if !rec.setup.notify_url.is_empty() { + text.push_str(&format!( + " When the loop needs you or ends, {}.", + loop_notify::describe( + rec.setup.notify_kind, + &rec.setup.notify_url, + &rec.setup.notify_param + ) + )); + } + text +} + +/// What the Start confirm promised about the notification, to tell a change on +/// Resume; empty when no address is set. +pub fn confirmed_notify(setup: &LoopSetup) -> String { + if setup.notify_url.is_empty() { + String::new() + } else { + format!( + "{:?} {} {}", + setup.notify_kind, setup.notify_url, setup.notify_param + ) + } +} + +/// The app's own confirm for Send a test: the saved setup's notification, or why +/// there is nothing to test. +pub fn notify_test_confirm(setup: &LoopSetup) -> Result { + if setup.notify_url.is_empty() { + return Err("Fill in the address first".to_string()); + } + if !loop_notify::valid_setup(setup.notify_kind, &setup.notify_url, &setup.notify_param) { + return Err("The saved notification address is not valid".to_string()); + } + Ok(format!( + "Send a test notification? To do that, {}.", + loop_notify::describe(setup.notify_kind, &setup.notify_url, &setup.notify_param) + )) +} + +/// Send a test: the saved notification with a message that says what it is. Must +/// not run on an async runtime's own thread (the HTTP client blocks). +pub fn send_notify_test(setup: &LoopSetup) -> Result<(), String> { + const MESSAGE: &str = + "Plan2Code test: the Implementation Loop's notifications will arrive here."; + match notify(setup, MESSAGE) { + Some(reason) => Err(format!("The test was not sent: {reason}")), + None => Ok(()), + } +} + +/// The message for a question holding the loop, or ending it (On question: Stop). +pub fn question_message(spec: &str, phase: u32, ended: bool) -> String { + let name = spec.strip_prefix("specs/").unwrap_or(spec); + if ended { + format!("Plan2Code loop stopped on {name}: Phase {phase} has a question for you to answer.") + } else { + format!( + "Plan2Code loop is waiting on {name}: Phase {phase} has a question for you to answer." + ) + } +} + +/// The message for a loop that built everything. +pub fn finished_message(spec: &str, phases: usize) -> String { + let name = spec.strip_prefix("specs/").unwrap_or(spec); + let built = if phases == 1 { + "1 phase".to_string() + } else { + format!("all {phases} phases") + }; + format!("Plan2Code loop complete on {name}: {built} built.") +} + +/// The message for a stop, or none when the person stopped it themselves. +pub fn stop_message(cause: &StopCause, spec: &str, phase: u32, line: &str) -> Option { + let name = spec.strip_prefix("specs/").unwrap_or(spec); + match cause { + StopCause::StoppedByPerson => None, + StopCause::Question => Some(question_message(spec, phase, true)), + _ => Some(format!("Plan2Code loop stopped on {name}: {line}")), + } +} + +/// Send the setup's notification, when it has one; the reason it failed, if it did. +fn notify(setup: &LoopSetup, message: &str) -> Option { + if setup.notify_url.is_empty() { + return None; + } + loop_notify::send( + setup.notify_kind, + &setup.notify_url, + &setup.notify_param, + message, + ) + .err() +} + +/// The clause the end of a loop says about a failed call. +fn notify_failed(reason: &str) -> String { + format!("the notification could not be sent ({reason})") +} + +/// An agent's launch choice: agent, model, effort and permission mode. +pub type Launch = (Agent, Option, Option, PermissionMode); + +/// What the app does as the loop moves. Both run on the watch thread (or the +/// command that asked) and must not call back into the driver. +pub struct Hooks { + /// Told on every change of phase, step, retries or running (the strip). + pub emit: Box, + /// A question now holds the loop: set the app's own taskbar attention, so + /// the dot and flash do not depend on the locked page sending one. + pub attention: Box, +} + +/// What the watch thread needs, shared by every step of one loop. +#[derive(Clone)] +struct Ctx { + slot: LoopSlot, + agent: Arc, + console_dir: PathBuf, + home: PathBuf, + launch: Launch, + run_id: u64, + hooks: Arc, + limits: Limits, +} + +/// A notice that waits for the new agent's console: how long before the phase +/// counts as crashed. +const NOTICE_WAIT: Duration = Duration::from_secs(180); +const WATCH_EVERY: Duration = Duration::from_secs(2); +/// How often silence looks at the session's files and the tree. +const ACTIVITY_EVERY: Duration = Duration::from_secs(30); +/// How long a phase's commit may run: a slow pre-commit hook is allowed this +/// much, where the quick calls keep their one minute. +const COMMIT_LIMIT: Duration = Duration::from_secs(10 * 60); + +/// The watcher's timing, settable so a test can run a loop in milliseconds. +/// The default is the three constants above. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// How often the watcher looks at the running phase. + pub watch_every: Duration, + /// How long a new phase may wait for its agent's console. + pub notice_wait: Duration, + /// How often silence looks at the session's files and the tree. + pub activity_every: Duration, + /// How long a phase's commit may run, hooks included. + pub commit_limit: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + watch_every: WATCH_EVERY, + notice_wait: NOTICE_WAIT, + activity_every: ACTIVITY_EVERY, + commit_limit: COMMIT_LIMIT, + } + } +} + +/// Store the record and start its first phase; a watch thread follows it. +pub fn begin( + slot: &LoopSlot, + agent: Arc, + rec: RunningRecord, + launch: Launch, + hooks: Hooks, +) -> Result<(), String> { + begin_with_limits(slot, agent, rec, launch, hooks, Limits::default()) +} + +/// `begin` with the watcher's timing given; a test starts a real loop with +/// millisecond limits through it. +pub fn begin_with_limits( + slot: &LoopSlot, + agent: Arc, + rec: RunningRecord, + launch: Launch, + hooks: Hooks, + limits: Limits, +) -> Result<(), String> { + let console_dir = find_console_dir()?; + let home = session_reader::console_home().ok_or("no home folder found")?; + // A build that stopped earlier carries on in the same report. + let mut rec = rec; + if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) { + rec.report = report; + } + let ctx = Ctx { + slot: Arc::clone(slot), + agent, + console_dir, + home, + launch, + run_id: rec.run_id, + hooks: Arc::new(hooks), + limits, + }; + { + let mut guard = lock(slot); + if guard.is_some() { + return Err("A loop is already running".to_string()); + } + *guard = Some(rec); + } + if let Err(e) = start_phase(&ctx, 0) { + *lock(slot) = None; + // start_phase already told the strip "Starting": take it away again. + (ctx.hooks.emit)(LoopStateEvent::ended()); + return Err(e); + } + thread::spawn(move || watch(ctx)); + Ok(()) +} + +/// A page the app took: while a loop waits for its phase's session, an +/// Implement or Implement + Review page is that session. +pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str) { + if !matches!(workflow, "implement" | "implement-review") { + return; + } + if let Some(rec) = lock(slot).as_mut() { + if rec.sid.is_none() { + rec.sid = Some(sid.to_string()); + rec.last_sid = Some(sid.to_string()); + rec.last_activity = SystemTime::now(); + } + } +} + +/// Start a fresh agent on `prompt`: on the agent's stored launch choice when it +/// has one, else on `launch` (an agent the loop stopped has forgotten it). +pub fn start_with(agent: &AgentManager, launch: &Launch, prompt: String) -> Result<(), String> { + if agent.launch_choice().is_some() { + agent.start_fresh(prompt) + } else { + agent.forget_session(); + let (kind, model, effort, mode) = launch.clone(); + agent.start(kind, model, effort, mode, Some(prompt)) + } +} + +/// The prompt behind Fix it by hand: an ordinary Implement session. +pub fn fix_prompt(spec: &str) -> String { + format!("/plan2code-3-implement {spec}/overview.md --web") +} + +pub fn finalize_prompt(spec: &str) -> String { + format!("/plan2code-4-finalize {spec}/overview.md --web") +} + +fn emit(ctx: &Ctx) { + let event = { + let guard = lock(&ctx.slot); + guard + .as_ref() + .filter(|r| r.run_id == ctx.run_id) + .map(state_event) + }; + if let Some(event) = event { + (ctx.hooks.emit)(event); + } +} + +fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> { + let prompt = { + let mut guard = lock(&ctx.slot); + let rec = guard.as_mut().ok_or("the loop ended")?; + rec.current = index; + rec.phases[index].status = PhaseStatus::Running; + rec.step = Step::Starting; + rec.sid = None; + rec.waiting = false; + rec.last_outcome = None; + rec.last_entry = None; + rec.phase_started_at = Instant::now(); + rec.activity_checked = Instant::now(); + rec.last_activity = SystemTime::now(); + phase_prompt(&rec.spec, &rec.setup) + }; + // Said before the agent starts: the banner is up from the moment of Start, + // and says what is happening between phases. + emit(ctx); + start_with(&ctx.agent, &ctx.launch, prompt)?; + let generation = ctx.agent.snapshot().generation; + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + rec.generation = generation; + } + emit(ctx); + Ok(()) +} + +// ---------------------------------------------------------- the watch loop + +fn watch(ctx: Ctx) { + watch_with(ctx, tick); +} + +/// The watcher: look every `watch_every` until `step` says the loop is over. +/// A panic in `step` ends the loop with the "watcher failed" stop, so the slot +/// is cleared, the agent ended and the page told, never a loop left running +/// with nothing watching it. +fn watch_with(ctx: Ctx, mut step: impl FnMut(&Ctx) -> bool) { + loop { + thread::sleep(ctx.limits.watch_every); + let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step(&ctx))); + match seen { + Ok(true) => {} + Ok(false) => return, + Err(payload) => { + let text = payload + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "an unknown error".to_string()); + let text: String = one_line(&text).chars().take(200).collect(); + let cause = StopCause::WatcherFailed(text); + let line = stop_line(&cause, 0, "", false); + stop_loop(&ctx, cause, line, &["resume", "fix"]); + return; + } + } + } +} + +/// What one pass over the running loop needs, copied out so no lock is held +/// while a tool runs. +struct Snapshot { + project: PathBuf, + spec: String, + setup: LoopSetup, + current: usize, + phase_n: u32, + sid: Option, + waited: Duration, + generation: u64, + stop_now: bool, + phase_retries: u32, + last_activity: SystemTime, + activity_due: bool, +} + +/// The running loop as one look sees it, or `None` when this loop is over. +fn take_snapshot(ctx: &Ctx) -> Option { + let guard = lock(&ctx.slot); + match guard.as_ref() { + Some(rec) if rec.run_id == ctx.run_id => Some(Snapshot { + project: rec.project.clone(), + spec: rec.spec.clone(), + setup: rec.setup.clone(), + current: rec.current, + phase_n: rec.phases[rec.current].n, + sid: rec.sid.clone(), + waited: rec.phase_started_at.elapsed(), + generation: rec.generation, + stop_now: rec.stop_now, + phase_retries: rec.phases[rec.current].retries, + last_activity: rec.last_activity, + activity_due: rec.activity_checked.elapsed() >= ctx.limits.activity_every, + }), + _ => None, + } +} + +/// One look at the running phase. Returns false when the loop is over. +fn tick(ctx: &Ctx) -> bool { + let Some(snap) = take_snapshot(ctx) else { + return false; + }; + if snap.stop_now { + stop_by_person(ctx, &snap); + return false; + } + let Some(sid) = snap.sid.clone() else { + if let Some(reason) = crashed(ctx, &snap) { + return fail(ctx, &snap, StopCause::Crash, reason); + } + if snap.waited > ctx.limits.notice_wait { + return fail(ctx, &snap, StopCause::NoSession, String::new()); + } + return true; + }; + let session = match session_reader::load(&ctx.home, &sid) { + Ok(session) => session, + // Busy is the console mid-write, or a file that stays locked: look + // again, but an ended agent is still judged and a state that never + // frees counts as silence, or a locked file would hang the loop. It + // is not counted as a failed read, which names a state that cannot be + // understood. + Err(ReadError::Busy) => { + if let Some(go) = crash_or_outcome(ctx, &snap, &sid) { + return go; + } + if silence_expired( + SystemTime::now(), + snap.last_activity, + &snap.setup, + None, + false, + ) { + let minutes = snap.setup.silence_minutes.min(60); + return fail(ctx, &snap, StopCause::Silence, minutes.to_string()); + } + return true; + } + // Any other error reads as "no outcome yet": the ended-agent check + // runs, and a session that stays unreadable counts as silence. + Err(_) => { + if let Some(go) = crash_or_outcome(ctx, &snap, &sid) { + return go; + } + note_read_failure(ctx, true); + let now = SystemTime::now(); + if silence_expired(now, snap.last_activity, &snap.setup, None, false) { + let minutes = snap.setup.silence_minutes.min(60); + return fail(ctx, &snap, StopCause::Silence, minutes.to_string()); + } + return true; + } + }; + note_read_failure(ctx, false); + let state = &session.state; + if state["loopOutcome"].is_object() { + return handle_outcome(ctx, &snap, &state["loopOutcome"]); + } + if let Some(go) = crash_or_outcome(ctx, &snap, &sid) { + return go; + } + let asked = snap.setup.on_question != OnQuestion::Guess && open_question(state); + if asked && snap.setup.on_question == OnQuestion::Stop { + let cause = StopCause::Question; + let line = stop_line(&cause, snap.phase_n, "", false); + stop_loop(ctx, cause, line, &["resume", "fix"]); + return false; + } + observe(ctx, state["headline"]["stage"].as_str(), asked); + + let quiet = state["agent"]["quietMinutes"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()); + let mut last = snap.last_activity; + if snap.activity_due { + last = refresh_activity(ctx, &snap, &session.dir); + } + if silence_expired(SystemTime::now(), last, &snap.setup, quiet, asked) { + let minutes = snap.setup.silence_minutes.max(quiet.unwrap_or(0)).min(60); + return fail(ctx, &snap, StopCause::Silence, minutes.to_string()); + } + true +} + +/// The agent has ended by itself: read the session once more before calling +/// it a crash, because an agent that writes its report and exits between two +/// looks must be judged, not retried. `Some(goes_on)` when it had ended (the +/// report was handled, or the crash stop or retry ran); `None` when it has not. +fn crash_or_outcome(ctx: &Ctx, snap: &Snapshot, sid: &str) -> Option { + let reason = crashed(ctx, snap)?; + if let Ok(session) = session_reader::load(&ctx.home, sid) { + if session.state["loopOutcome"].is_object() { + return Some(handle_outcome(ctx, snap, &session.state["loopOutcome"])); + } + } + Some(fail(ctx, snap, StopCause::Crash, reason)) +} + +/// Count (or clear) the looks that could not read the session. +fn note_read_failure(ctx: &Ctx, failed: bool) { + let mut guard = lock(&ctx.slot); + if let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) { + if failed { + rec.read_failures += 1; + } else if rec.read_failures > 0 { + rec.read_failures = 0; + } + } +} + +/// The reason the current phase's agent ended by itself, if it did. +fn crashed(ctx: &Ctx, snap: &Snapshot) -> Option { + let seen = ctx.agent.snapshot(); + match seen.state { + AgentState::Ended { reason } if seen.generation == snap.generation => Some(reason), + _ => None, + } +} + +/// Take the step from the page's headline, or Waiting on you while a question +/// holds the loop; the first moment of a hold sets the app's own attention. +fn observe(ctx: &Ctx, stage: Option<&str>, asked: bool) { + let (changed, hold) = { + let mut guard = lock(&ctx.slot); + let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else { + return; + }; + let before = (rec.step, rec.waiting); + let newly_waiting = asked && !rec.waiting; + rec.waiting = asked; + if asked { + // A held question is not silence, and the clock starts afresh the + // moment it is answered. + rec.last_activity = SystemTime::now(); + rec.activity_checked = Instant::now(); + rec.step = Step::WaitingOnYou; + } else if matches!(rec.step, Step::Checking | Step::Commit) { + // The app's own steps: the page's headline does not name them. + } else if let Some(stage) = stage { + rec.step = step_for_stage(stage); + } else if rec.step == Step::WaitingOnYou { + rec.step = Step::Build; + } + let hold = newly_waiting.then(|| { + ( + rec.setup.clone(), + rec.spec.clone(), + rec.phases[rec.current].n, + ) + }); + ((rec.step, rec.waiting) != before, hold) + }; + if let Some((setup, spec, phase)) = hold { + (ctx.hooks.attention)(); + // On its own thread: a slow address must not delay the watch. + let (slot, run_id) = (Arc::clone(&ctx.slot), ctx.run_id); + thread::spawn(move || { + if let Some(reason) = notify(&setup, &question_message(&spec, phase, false)) { + if let Some(rec) = lock(&slot).as_mut().filter(|r| r.run_id == run_id) { + rec.notify_failure = Some(reason); + } + } + }); + } + if changed { + emit(ctx); + } +} + +/// A file time is never later than now: a file dated in the future (a clock +/// that was wrong, a copied file) must not hold the last sign of work ahead of +/// the clock, or silence would never fire. +fn clamp_to_now(time: SystemTime) -> SystemTime { + time.min(SystemTime::now()) +} + +fn modified(path: &Path) -> Option { + std::fs::metadata(path) + .ok()? + .modified() + .ok() + .map(clamp_to_now) +} + +/// The newest sign of work: the session's own files, or a file `git status` +/// lists (ignored folders never appear, so they never count). +fn newest_work(session_dir: &Path, project: &Path) -> Option { + let mut newest = ["state.json", "events.ndjson"] + .iter() + .filter_map(|name| modified(&session_dir.join(name))) + .max(); + if let Ok(files) = loop_tools::git_status_porcelain(project) { + let tree = files + .iter() + .take(2000) + .filter_map(|file| modified(&project.join(file.trim_end_matches('/')))) + .max(); + newest = newest.max(tree); + } + newest +} + +fn refresh_activity(ctx: &Ctx, snap: &Snapshot, session_dir: &Path) -> SystemTime { + let newest = newest_work(session_dir, &snap.project); + let mut guard = lock(&ctx.slot); + let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else { + return snap.last_activity; + }; + rec.activity_checked = Instant::now(); + if let Some(time) = newest.map(clamp_to_now) { + if time > rec.last_activity { + rec.last_activity = time; + } + } + rec.last_activity +} + +/// A crash, silence or a console that never opened: one fresh retry when the +/// setup allows it, else the loop stops. Returns whether the loop goes on. +fn fail(ctx: &Ctx, snap: &Snapshot, cause: StopCause, detail: String) -> bool { + // Stop now was pressed since this look began: the ended agent is not a + // crash and nothing is retried. + if stop_requested(ctx) { + stop_by_person(ctx, snap); + return false; + } + if should_retry(&cause, &snap.setup, snap.phase_retries) { + let why = stop_line(&cause, snap.phase_n, &detail, false); + let name = phase_name(ctx); + add_entry( + ctx, + ReportEntry { + at: report_time(), + phase: snap.phase_n, + name, + result: EntryResult::Retried, + line: why, + retries: 1, + assumed: phase_assumptions(&snap.project, &snap.spec, snap.phase_n, None), + ..ReportEntry::default() + }, + ); + { + let mut guard = lock(&ctx.slot); + let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else { + return false; + }; + rec.phases[snap.current].retries += 1; + rec.retries_used += 1; + } + // Stop now may have come while the entry was written: no new agent. + if stop_requested(ctx) { + stop_by_person(ctx, snap); + return false; + } + // Nothing is undone: the skill picks up at the phase's first open task. + return match start_phase(ctx, snap.current) { + Ok(()) => true, + Err(e) => { + let why = format!("the retry could not start ({})", one_line(&e)); + let cause = StopCause::Refused(why); + let line = stop_line(&cause, snap.phase_n, "", true); + stop_loop(ctx, cause, line, &["resume", "fix"]); + false + } + }; + } + let line = stop_line(&cause, snap.phase_n, &detail, snap.phase_retries > 0); + stop_loop(ctx, cause, line, &["resume", "fix"]); + false +} + +fn stop_by_person(ctx: &Ctx, snap: &Snapshot) { + let cause = StopCause::StoppedByPerson; + let line = stop_line(&cause, snap.phase_n, "", false); + stop_loop(ctx, cause, line, &["resume", "fix"]); +} + +/// Stop now came before the commit began: nothing is committed. `staged` is +/// whether the loop put files in the index, which are taken out again. +fn stop_before_mark(ctx: &Ctx, snap: &Snapshot, staged: bool) -> bool { + if staged { + loop_commit::unstage(&snap.project); + } + stop_by_person(ctx, snap); + false +} + +fn stop_requested(ctx: &Ctx) -> bool { + lock(&ctx.slot) + .as_ref() + .is_some_and(|r| r.run_id == ctx.run_id && r.stop_now) +} + +/// Judge a phase's report and, when it holds, record it: quick check, mark, +/// approval line, commit, stop the agent, then the next phase, a stop the +/// person asked for, or the finish. Returns whether the loop goes on. +fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool { + let n = snap.phase_n; + let stop = |cause: StopCause, line: String| { + stop_loop(ctx, cause, line, &["resume", "fix"]); + false + }; + let refused = |why: String| { + let cause = StopCause::Refused(why); + let line = stop_line(&cause, n, "", false); + stop(cause, line) + }; + let outcome: Outcome = match serde_json::from_value(raw.clone()) { + Ok(outcome) => outcome, + Err(e) => return refused(format!("the phase report could not be read ({e})")), + }; + if outcome.phase != n { + return refused(format!("the report names Phase {}", outcome.phase)); + } + let status = match loop_tools::specs_status(&snap.project, &snap.spec) { + Ok(status) => status, + Err(e) => return refused(format!("the spec could not be read ({})", one_line(&e))), + }; + let entry = status["phases"] + .as_array() + .and_then(|all| { + all.iter() + .find(|p| p["number"].as_u64() == Some(u64::from(n))) + }) + .cloned() + .unwrap_or(Value::Null); + keep_report(ctx, &outcome, &entry); + let warnings = match judge_outcome(&outcome, &entry, &snap.setup) { + Verdict::Refuse(why) => return refused(why), + Verdict::Approve { warnings } => warnings, + }; + + // Everything that can fail before a file changes comes first. + let prepared = if snap.setup.commit { + loop_commit::prepare(&snap.project, &snap.spec, &entry, &outcome.subject) + } else { + loop_commit::phase_file(&snap.project, &snap.spec, &entry).map(|phase_file| { + loop_commit::Prepared { + message: String::new(), + phase_file, + } + }) + }; + let prepared = match prepared { + Ok(prepared) => prepared, + Err(e) => return refused(one_line(&e)), + }; + + set_step(ctx, Step::Checking); + let check = snap.setup.quick_check.trim(); + if !check.is_empty() { + let run = loop_tools::quick_check(&snap.project, check, loop_tools::CHECK_LIMIT); + if !run.ok { + keep_output(ctx, &run.output); + let cause = StopCause::QuickCheck; + let line = stop_line(&cause, n, "", false); + return stop(cause, line); + } + } + // Stop now came while the check ran: nothing is staged or marked yet. + if stop_requested(ctx) { + return stop_before_mark(ctx, snap, false); + } + // With commit on, stage and look at the list before any file is marked: + // a secret or an oversized file stops the phase with nothing to undo. + if snap.setup.commit { + set_step(ctx, Step::Commit); + match loop_commit::stage_and_check(&snap.project) { + Ok(()) => {} + Err(loop_commit::StageError::Add(failure)) => { + keep_output(ctx, &failure.output); + loop_commit::unstage(&snap.project); + let cause = StopCause::Commit; + let detail = format!("git add failed: {}", failure.first_line); + let line = stop_line(&cause, n, &detail, false); + return stop(cause, line); + } + Err(loop_commit::StageError::Problem(problem)) => { + let mut kept = problem.files.join("\n"); + if let Some(why) = &problem.left_staged { + kept.push_str(&format!("\n\nThey could not be unstaged: {why}")); + } + keep_output(ctx, &kept); + let cause = StopCause::UnsafeFiles(problem.files); + let mut line = stop_line(&cause, n, "", false); + if let Some(why) = &problem.left_staged { + line = format!( + "{line}. They are still staged ({why}): run git reset before committing by hand" + ); + } + return stop(cause, line); + } + } + } + if stop_requested(ctx) { + return stop_before_mark(ctx, snap, snap.setup.commit); + } + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + let approval = approval_line(&date, &snap.setup); + let marked = match loop_commit::mark(&prepared, &snap.project, &snap.spec, n, &approval) { + Ok(marked) => marked, + Err(failure) if failure.put_back_failed => { + // Both files could not be put back: the spec may say done with + // nothing committed, so say so and keep the fact like a failed undo. + keep_output(ctx, &failure.message); + return marked_not_committed(ctx, &prepared, n); + } + Err(failure) => { + keep_output(ctx, &failure.message); + if snap.setup.commit { + loop_commit::unstage(&snap.project); + } + return refused(format!( + "the phase could not be marked done ({})", + one_line(&failure.message) + )); + } + }; + + let mut commit = None; + if snap.setup.commit { + // Stop now came during the mark: take the mark back, commit nothing. + // Once the commit below begins, it is finished (and nothing follows). + if stop_requested(ctx) { + return match loop_commit::undo(&prepared, &marked) { + Ok(()) => stop_before_mark(ctx, snap, true), + Err(why) => { + keep_output(ctx, &why); + marked_not_committed(ctx, &prepared, n) + } + }; + } + match loop_commit::commit(&snap.project, &prepared, &marked, ctx.limits.commit_limit) { + Ok(head) => { + commit = head; + set_marked(ctx, None); + } + Err(failure) => return commit_failed(ctx, snap, &prepared, &marked, &failure), + } + } + ctx.agent.stop(); + + let passed = ReportEntry { + at: report_time(), + phase: n, + name: phase_name(ctx), + result: EntryResult::Passed, + commit: commit.clone(), + retries: snap.phase_retries, + assumed: phase_assumptions(&snap.project, &snap.spec, n, Some(&entry)), + warnings, + ..ReportEntry::default() + } + .with_outcome(&outcome); + add_entry(ctx, passed); + let (next, stop_after, stop_now) = { + let mut guard = lock(&ctx.slot); + let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else { + return false; + }; + let phase = &mut rec.phases[snap.current]; + phase.status = PhaseStatus::Done; + phase.commit = commit; + phase.subject = Some(outcome.subject.clone()); + ( + (snap.current + 1 < rec.phases.len()).then_some(snap.current + 1), + rec.stop_after_phase, + rec.stop_now, + ) + }; + // Stop now, even on the last phase: the phase is recorded as it stands, + // and no next phase or Finalize follows. + if stop_now { + let how = if snap.setup.commit { + "committed" + } else { + "marked done" + }; + let can: &[&str] = if next.is_some() { + &["resume"] + } else { + &["finalize"] + }; + stop_loop( + ctx, + StopCause::StoppedByPerson, + format!("Stopped after Phase {n} was {how}, as asked"), + can, + ); + return false; + } + match next { + Some(_) if stop_after => { + stop_loop( + ctx, + StopCause::StoppedByPerson, + format!("Stopped after Phase {n}, as asked"), + &["resume"], + ); + false + } + Some(index) => match start_phase(ctx, index) { + Ok(()) => true, + Err(e) => { + let cause = StopCause::Refused(format!( + "the next phase could not start ({})", + one_line(&e) + )); + let line = format!("The next phase could not start: {}", one_line(&e)); + stop_loop(ctx, cause, line, &["resume", "fix"]); + false + } + }, + None => { + finish(ctx); + false + } + } +} + +/// A commit that failed: take the mark back and stop with the work uncommitted +/// and the spec showing the phase open. When the mark cannot be taken back, +/// stop at once and save the fact, so it survives an app restart. +fn commit_failed( + ctx: &Ctx, + snap: &Snapshot, + prepared: &loop_commit::Prepared, + marked: &loop_commit::Marked, + failure: &loop_commit::CommitFailure, +) -> bool { + let n = snap.phase_n; + keep_output(ctx, &failure.output); + let (cause, line) = match loop_commit::undo(prepared, marked) { + Ok(()) => { + loop_commit::unstage(&snap.project); + let cause = StopCause::Commit; + let detail = match failure.stage { + loop_commit::Stage::Add => format!("git add failed: {}", failure.first_line), + loop_commit::Stage::Commit => failure.first_line.clone(), + }; + let line = stop_line(&cause, n, &detail, false); + (cause, line) + } + Err(why) => { + keep_output(ctx, &format!("{why}\n\n{}", failure.output)); + return marked_not_committed(ctx, prepared, n); + } + }; + stop_loop(ctx, cause, line, &["resume", "fix"]); + false +} + +/// Stop at once: the phase file says done and its work is not committed. The +/// fact is saved with the report, so it survives an app restart. +fn marked_not_committed(ctx: &Ctx, prepared: &loop_commit::Prepared, n: u32) -> bool { + let file = prepared + .phase_file + .file_name() + .map_or_else(String::new, |f| f.to_string_lossy().into_owned()); + set_marked(ctx, Some((n, file.clone()))); + let cause = StopCause::MarkedNotCommitted(file); + let line = stop_line(&cause, n, "", false); + stop_loop(ctx, cause, line, &["resume", "fix"]); + false +} + +/// Remember (or forget) that a phase is marked done with no commit behind it. +/// `stop_loop` and `add_entry` save the report, so the fact reaches the disk. +fn set_marked(ctx: &Ctx, marked: Option<(u32, String)>) { + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + match marked { + Some((phase, file)) => rec.report.set_marked(phase, &file), + None => rec.report.clear_marked(), + } + } +} + +/// The current phase's name, for a report entry. +fn phase_name(ctx: &Ctx) -> String { + lock(&ctx.slot) + .as_ref() + .filter(|r| r.run_id == ctx.run_id) + .map(|r| r.phases[r.current].name.clone()) + .unwrap_or_default() +} + +/// The assumptions the phase file holds now. `entry` is the phase's row from +/// `specs.mjs status` when one is at hand; it names the file. +fn phase_assumptions( + project: &Path, + spec: &str, + phase: u32, + entry: Option<&Value>, +) -> Vec { + let file = entry + .and_then(|e| e["file"].as_str()) + .map_or_else(|| format!("phase-{phase}.md"), str::to_string); + std::fs::read_to_string(project.join(spec).join(file)) + .map(|text| loop_report::assumptions_in(&text)) + .unwrap_or_default() +} + +/// Add to the report and save it straight away, so a crash loses nothing. A save +/// that fails never stops the loop; the report stays in memory and the end says so. +fn add_entry(ctx: &Ctx, entry: ReportEntry) { + let saved = { + let mut guard = lock(&ctx.slot); + let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else { + return; + }; + rec.report.entries.push(entry); + (rec.project.clone(), rec.report.clone()) + }; + let result = loop_report::save(&ctx.home, &saved.0, &saved.1); + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + rec.report_failure = result.err(); + } +} + +fn set_step(ctx: &Ctx, step: Step) { + let changed = { + let mut guard = lock(&ctx.slot); + match guard.as_mut().filter(|r| r.run_id == ctx.run_id) { + Some(rec) => { + let changed = rec.step != step; + rec.step = step; + changed + } + None => false, + } + }; + if changed { + emit(ctx); + } +} + +fn keep_output(ctx: &Ctx, output: &str) { + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + rec.failure_output = Some(output.to_string()); + } +} + +fn keep_report(ctx: &Ctx, outcome: &Outcome, entry: &Value) { + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + rec.last_outcome = Some(outcome.clone()); + rec.last_entry = Some(entry.clone()); + } +} + +fn one_line(text: &str) -> String { + let line = text.split_whitespace().collect::>().join(" "); + if line.chars().count() > 160 { + let cut: String = line.chars().take(157).collect(); + format!("{cut}...") + } else { + line + } +} + +// ------------------------------------------------------ requests from the app + +/// Stop after this phase: the phase finishes (review, mark, commit), then the +/// loop stops instead of starting the next. Returns the strip's new state. +pub fn request_stop_after(slot: &LoopSlot, on: bool) -> Result { + let mut guard = lock(slot); + let rec = guard.as_mut().ok_or("No loop is running")?; + if on && rec.current + 1 >= rec.phases.len() { + return Err("This is the last phase".to_string()); + } + rec.stop_after_phase = on; + Ok(state_event(rec)) +} + +/// Stop now: the flag is set first, so the ended agent is never taken for a +/// crash and no branch of the loop starts more work, then the agent (when one +/// is running) is ended; the watch thread tells the page. The strip's new state +/// ("Stopping") goes to `emit` while the slot is still held, so the watcher's +/// own "ended" event can never come before it; ending the agent can take a +/// while, and runs after. +pub fn request_stop_now( + slot: &LoopSlot, + agent: Option<&AgentManager>, + emit: impl FnOnce(&LoopStateEvent), +) -> Result { + let event = { + let mut guard = lock(slot); + let rec = guard.as_mut().ok_or("No loop is running")?; + rec.stop_now = true; + let event = state_event(rec); + emit(&event); + event + }; + if let Some(agent) = agent { + agent.stop(); + } + Ok(event) +} + +/// Forget the running loop without a word to the page: the app is quitting. +pub fn abandon(slot: &LoopSlot) { + *lock(slot) = None; +} + +pub fn is_running(slot: &LoopSlot) -> bool { + lock(slot).is_some() +} + +/// What the quit check says: the current phase's number, the run's last phase +/// number and the phases committed so far. `None` when no loop runs. +pub fn quit_facts(slot: &LoopSlot) -> Option<(u32, u32, Vec)> { + lock(slot).as_ref().map(|rec| { + let committed = rec + .phases + .iter() + .filter(|p| p.status == PhaseStatus::Done && p.commit.is_some()) + .map(|p| p.n) + .collect(); + ( + rec.phases.get(rec.current).map_or(0, |p| p.n), + rec.phases.last().map_or(0, |p| p.n), + committed, + ) + }) +} + +// ------------------------------------------------------------ the ending + +/// Every phase this build has touched, by number: what the report says for one +/// that passed, even in an earlier run before a Resume, else this run's record. +fn phase_rows(rec: &RunningRecord) -> Value { + let passed = rec.report.passed(); + let mut rows: Vec<(u32, Value)> = passed + .iter() + .map(|e| { + ( + e.phase, + json!({ + "n": e.phase, + "name": e.name, + "commit": e.commit, + "unfixed": e.skipped.len() + e.left_open.len(), + "retries": e.retries, + "fixed": e.fixed.len(), + "skipped": e.skipped.len(), + "left": e.left_open.len(), + "assumed": e.assumed.len(), + "decisions": e.decisions.len(), + }), + ) + }) + .collect(); + for p in &rec.phases { + if !rows.iter().any(|(n, _)| *n == p.n) { + rows.push(( + p.n, + json!({ + "n": p.n, + "name": p.name, + "commit": p.commit, + "unfixed": 0, + "retries": p.retries, + "fixed": 0, + "skipped": 0, + "left": 0, + "assumed": 0, + "decisions": 0, + }), + )); + } + } + rows.sort_by_key(|(n, _)| *n); + Value::Array(rows.into_iter().map(|(_, row)| row).collect()) +} + +/// The stop's evidence with the report so far under it, within the size limit. +fn evidence_with_report(evidence: &str, rec: &RunningRecord) -> String { + let mut md = format!( + "{evidence}\n# Everything the loop has done so far\n\n{}", + loop_report::body_markdown(&rec.report) + ); + if let Some(why) = &rec.report_failure { + md.push_str(&format!( + "\nThe report could not be saved along the way ({}), so a crash of the app would lose it.\n", + one_line(why) + )); + } + if md.len() > EVIDENCE_LIMIT { + let mut cut = EVIDENCE_LIMIT; + while !md.is_char_boundary(cut) { + cut -= 1; + } + md.truncate(cut); + md.push_str( + "\n\n(cut here: the rest is kept, and is in the report when the build finishes)\n", + ); + } + md +} + +const EVIDENCE_LIMIT: usize = 100 * 1024; +const OUTPUT_KEEP: usize = 40 * 1024; + +/// The last `max` bytes of `text`, cut on a character boundary. +fn tail(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_string(); + } + let mut start = text.len() - max; + while !text.is_char_boundary(start) { + start += 1; + } + format!("(earlier output left out)\n{}", &text[start..]) +} + +fn fenced(text: &str) -> String { + let body = tail(text.trim_end(), OUTPUT_KEEP).replace("```", "'''"); + format!("```\n{body}\n```\n") +} + +/// Task ids from a `specs.mjs status` list (`blockedTasks`, `assumedTasks`): +/// plain ids or objects that name one. +fn task_ids(entry: &Value, key: &str) -> Vec { + entry[key] + .as_array() + .map(|all| { + all.iter() + .map(|t| match t { + Value::String(id) => id.clone(), + Value::Object(_) => t["id"] + .as_str() + .or_else(|| t["task"].as_str()) + .map_or_else(|| t.to_string(), str::to_string), + other => other.to_string(), + }) + .collect() + }) + .unwrap_or_default() +} + +fn ids_text(ids: Vec) -> String { + if ids.is_empty() { + "none".to_string() + } else { + ids.join(", ") + } +} + +fn report_section(outcome: &Outcome, entry: Option<&Value>) -> String { + let mut md = String::from("\n## What the phase reported\n\n"); + md.push_str(&format!("- Summary: {}\n", one_line(&outcome.summary))); + let tests = match &outcome.tests { + Some(t) if !t.summary.is_empty() => one_line(&t.summary), + Some(t) if t.passed => "passed".to_string(), + Some(t) if t.ran => "failed".to_string(), + _ => "not reported".to_string(), + }; + md.push_str(&format!("- Tests: {tests}\n")); + if let Some(review) = &outcome.review { + md.push_str(&format!( + "- Left after the review: {} Critical, {} Warning, {} Suggestion\n", + review.left.critical, review.left.warning, review.left.suggestion + )); + } + if let Some(note) = outcome.review.as_ref().and_then(suggestion_warning) { + md.push_str(&format!("- Warnings: {note}\n")); + } + if let Some(entry) = entry { + md.push_str(&format!( + "- Blocked tasks: {}\n", + ids_text(task_ids(entry, "blockedTasks")) + )); + md.push_str(&format!( + "- Assumed tasks: {}\n", + ids_text(task_ids(entry, "assumedTasks")) + )); + } + if let Some(review) = &outcome.review { + if !review.unfixed.is_empty() { + md.push_str("\n### Findings left unfixed\n\n"); + for f in &review.unfixed { + md.push_str(&format!( + "- {}: {} ({})\n", + f.level.word(), + one_line(&f.title), + one_line(&f.file) + )); + } + } + } + md +} + +/// The markdown behind "Why the loop stopped": what failed and the proof, by +/// cause. Kept under 100 KB (output is trimmed to its tail). +pub fn evidence_markdown(cause: &StopCause, line: &str, rec: &RunningRecord) -> String { + let mut md = format!("## What happened\n\n{line}\n"); + let phase_report = matches!( + cause, + StopCause::Refused(_) + | StopCause::QuickCheck + | StopCause::Commit + | StopCause::MarkedNotCommitted(_) + | StopCause::UnsafeFiles(_) + ); + if phase_report { + if let Some(outcome) = &rec.last_outcome { + md.push_str(&report_section(outcome, rec.last_entry.as_ref())); + } + } + match cause { + StopCause::QuickCheck => { + md.push_str("\n## The quick check\n\n"); + md.push_str(&format!("Command: `{}`\n\n", rec.setup.quick_check.trim())); + md.push_str(&fenced( + rec.failure_output.as_deref().unwrap_or("(no output)"), + )); + } + StopCause::Commit => { + md.push_str("\n## What git said\n\n"); + md.push_str(&fenced( + rec.failure_output.as_deref().unwrap_or("(no output)"), + )); + md.push_str( + "\nThe phase was approved, but its changes are not committed. The mark was taken back, so the spec still shows the phase open. Fix what git says, then press Resume to try the commit again.\n", + ); + } + StopCause::MarkedNotCommitted(file) => { + md.push_str("\n## What git said\n\n"); + md.push_str(&fenced( + rec.failure_output.as_deref().unwrap_or("(no output)"), + )); + md.push_str(&format!( + "\nThe phase is marked done in `{file}` (and in overview.md), but its changes are not committed, and the mark could not be taken back. Set the phase back to in progress by hand, or press Resume: it checks every done mark against the commit log and builds this phase again.\n" + )); + } + StopCause::UnsafeFiles(files) => { + md.push_str("\n## The files\n\n"); + for file in files { + let reason = loop_commit::denied(file).unwrap_or("over 5 MB"); + md.push_str(&format!("- `{file}` ({reason})\n")); + } + md.push_str( + "\nThe phase was approved, but these files were staged and the loop does not commit secrets or files over 5 MB. Nothing was marked done or committed, and everything was taken out of the index again (unless the stop line says otherwise). Remove the files, or add them to `.gitignore`, then press Resume.\n", + ); + } + StopCause::Refused(_) => { + if let Some(output) = &rec.failure_output { + md.push_str("\n## Output\n\n"); + md.push_str(&fenced(output)); + } + } + StopCause::Crash | StopCause::NoSession => { + md.push_str("\nThe agent's terminal, beside this page, shows where it ended.\n"); + } + StopCause::Silence => { + md.push_str("\nNothing changed in the session or the project for that long, so the loop ended the agent.\n"); + if rec.read_failures > 0 { + md.push_str( + "\nThe session could not be read during that time, so it counted as silence.\n", + ); + } + } + StopCause::WatcherFailed(_) => { + md.push_str( + "\nThe loop's own watcher stopped working, so the agent was ended. Whatever was committed stays committed; nothing more was. Press Resume to carry on from the spec.\n", + ); + } + StopCause::Question => { + md.push_str("\nThe setup says to stop when a phase asks something.\n"); + } + StopCause::StoppedByPerson => { + md.push_str("\nNothing was undone: the project stays as the agent left it.\n"); + } + } + if !rec.own_dirty.is_empty() { + md.push_str( + "\n## Your own files\n\nThese files were already changed when the loop started, so the list of uncommitted files leaves them out. A file you and the agent both changed is hidden from that list too.\n\n", + ); + for file in rec.own_dirty.iter().take(50) { + md.push_str(&format!("- `{file}`\n")); + } + if rec.own_dirty.len() > 50 { + md.push_str(&format!("- and {} more\n", rec.own_dirty.len() - 50)); + } + } + if md.len() > EVIDENCE_LIMIT { + let mut cut = EVIDENCE_LIMIT; + while !md.is_char_boundary(cut) { + cut -= 1; + } + md.truncate(cut); + md.push_str("\n\n(cut here)\n"); + } + md +} + +/// Tell the page how the loop ended. A session the console no longer holds is +/// opened again once; a post the console refuses is repeated with the line +/// alone, so the page always hears the end. +fn post_end(ctx: &Ctx, rec: &RunningRecord, patch: &Value) { + // A post writes the session's files, so it works with no server running, + // and on Windows the agent's server has just ended with the agent. The + // window brings the server back when it hears the loop ended. + let Some(sid) = rec.sid.clone().or_else(|| rec.last_sid.clone()) else { + return; + }; + if loop_tools::console_post(&ctx.console_dir, &sid, patch).ok { + return; + } + let workflow = if rec.setup.review { + "implement-review" + } else { + "implement" + }; + if loop_tools::console_resume(&ctx.console_dir, &sid, workflow).ok + && loop_tools::console_post(&ctx.console_dir, &sid, patch).ok + { + return; + } + let mut plain = patch.clone(); + if let Some(object) = plain.as_object_mut() { + object.remove("docs"); + } + if let Some(end) = plain.get_mut("loopEnd").and_then(Value::as_object_mut) { + end.remove("evidence"); + } + let _ = loop_tools::console_post(&ctx.console_dir, &sid, &plain); +} + +/// End the loop, the one place every stop goes through: stop the agent, mark +/// the phase stopped, write the evidence and the end to the page, clear the +/// record and tell the strip. `can` names the buttons the stop screen offers. +fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) { + // The record first: a stale caller (an older loop's watcher) finds a newer + // record, or none, and returns without ever ending the newer loop's agent. + let rec = { + let mut guard = lock(&ctx.slot); + match guard.take() { + Some(rec) if rec.run_id == ctx.run_id => rec, + other => { + *guard = other; + return; + } + } + }; + ctx.agent.stop(); + // The strip goes at once, so a new Start in the gap while this stop is + // written is not hidden by this loop's late event. + (ctx.hooks.emit)(LoopStateEvent::ended()); + let mut rec = rec; + let at = rec.current; + // A phase already built and recorded (Stop after this phase) adds only the + // stop; any other carries what its agent reported, if it got that far. + let built = rec.phases[at].status == PhaseStatus::Done; + if rec.phases[at].status == PhaseStatus::Running { + rec.phases[at].status = PhaseStatus::Stopped; + } + // Only the agent's work: files that were already changed when the loop + // started are the person's own. A file both of them changed is hidden here, + // a known limit of comparing names. + let uncommitted = uncommitted_files(&rec.project, &rec.own_dirty); + let line: String = one_line(&line).chars().take(200).collect(); + let mut entry = ReportEntry { + at: report_time(), + phase: rec.phases[at].n, + name: rec.phases[at].name.clone(), + result: EntryResult::Stopped, + line: line.clone(), + retries: rec.phases[at].retries, + ..ReportEntry::default() + }; + if !built { + entry.assumed = phase_assumptions( + &rec.project, + &rec.spec, + entry.phase, + rec.last_entry.as_ref(), + ); + if let Some(outcome) = &rec.last_outcome { + entry = entry.with_outcome(outcome); + } + } + rec.report.entries.push(entry); + rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err(); + let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec); + let sent = stop_message(&cause, &rec.spec, rec.phases[at].n, &line) + .and_then(|message| notify(&rec.setup, &message)); + if let Some(reason) = sent.or_else(|| rec.notify_failure.clone()) { + let said = notify_failed(&reason); + evidence.push_str(&format!("\n\nAlso, {said}.\n")); + } + let patch = json!({ + "docs": [{ + "id": "evidence", + "title": "Why the loop stopped, and the report so far", + "blocks": [{ "id": "body", "state": "settled", "md": evidence }], + }], + "loopEnd": { + "kind": "stopped", + "line": line, + "evidence": "evidence", + "phases": phase_rows(&rec), + "uncommitted": uncommitted, + "can": can, + }, + }); + post_end(ctx, &rec, &patch); +} + +fn finish(ctx: &Ctx) { + let rec = { + let guard = lock(&ctx.slot); + match guard.as_ref() { + Some(rec) if rec.run_id == ctx.run_id => rec.clone(), + _ => return, + } + }; + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + let spec_dir = rec.project.join(&rec.spec); + let file = unused_summary_name(&date, |name| spec_dir.join(name).exists()); + let relative = format!("{}/{file}", rec.spec); + let built = phase_rows(&rec).as_array().map_or(0, Vec::len); + let line = if built == 1 { + "The 1 phase is built".to_string() + } else { + format!("All {built} phases built") + }; + let markdown = summary_markdown(&rec, &date); + let written = write_atomic(&spec_dir.join(&file), &markdown); + if written.is_ok() { + // The project holds the report now. A failure here only means the next + // loop on this spec starts from this report, so it is not worth a stop. + let _ = loop_report::remove(&ctx.home, &rec.project, &rec.spec); + } + // Stop now pressed while the summary was written: no Finalize agent starts. + let skip_finalize = stop_requested(ctx); + let finalize_error = if rec.setup.after_last == AfterLast::RunFinalize && !skip_finalize { + start_with(&ctx.agent, &ctx.launch, finalize_prompt(&rec.spec)).err() + } else { + None + }; + // The page always hears the end; a summary that could not be written or a + // Finalize that could not start is said in the line. + let mut said = line.clone(); + let mut patch = json!({}); + let mut evidence = None; + match &written { + Ok(()) => { + evidence = Some("loop-summary"); + patch["docs"] = json!([{ + "id": "loop-summary", + "title": "Loop summary", + "blocks": [{ "id": "body", "file": relative }], + }]); + } + Err(e) => said = format!("{said}; the summary file could not be written ({e})"), + } + if let Some(e) = finalize_error { + said = format!("{said}; Finalize could not start ({e})"); + } + if skip_finalize && rec.setup.after_last == AfterLast::RunFinalize { + said = format!("{said}; Finalize was not started, as you asked to stop"); + } + let message = finished_message(&rec.spec, built); + if let Some(reason) = notify(&rec.setup, &message).or_else(|| rec.notify_failure.clone()) { + said = format!("{said}; {}", notify_failed(&reason)); + } + let mut end = json!({ + "kind": "finished", + "line": one_line(&said), + "phases": phase_rows(&rec), + "uncommitted": [], + "can": ["finalize"], + }); + if let Some(id) = evidence { + end["evidence"] = json!(id); + } + patch["loopEnd"] = end; + post_end(ctx, &rec, &patch); + { + let mut guard = lock(&ctx.slot); + if guard.as_ref().is_some_and(|r| r.run_id == ctx.run_id) { + *guard = None; + } + } + (ctx.hooks.emit)(LoopStateEvent::ended()); +} + +// ----------------------------------------------------- the files it writes + +/// `LOOP-SUMMARY-.md`, or `-2`, `-3` and so on when a report of that name +/// is already there: a second build the same day must not replace the first's. +pub fn unused_summary_name(date: &str, taken: impl Fn(&str) -> bool) -> String { + let first = format!("LOOP-SUMMARY-{date}.md"); + if !taken(&first) { + return first; + } + (2..) + .map(|n| format!("LOOP-SUMMARY-{date}-{n}.md")) + .find(|name| !taken(name)) + .unwrap_or(first) +} + +fn levels_text(setup: &LoopSetup) -> String { + if setup.fix_mode == FixMode::Smart { + return "smart pick".to_string(); + } + if setup.fix.is_empty() { + return "no fix levels".to_string(); + } + [FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion] + .into_iter() + .filter(|level| setup.fix.contains(level)) + .map(FixLevel::word) + .collect::>() + .join(", ") +} + +/// The line the app leaves under a phase's completion summary. +pub fn approval_line(date: &str, setup: &LoopSetup) -> String { + let check = setup.quick_check.trim(); + let check = if check.is_empty() { + "no quick check".to_string() + } else { + format!("quick check passed ({check})") + }; + let review = if setup.review { + format!("review at {}", levels_text(setup)) + } else { + "review off".to_string() + }; + format!("Approved by the Implementation Loop on {date}: tests passed, {check}, {review}.") +} + +const SUMMARY_HEADING: &str = "## Phase Completion Summary"; + +/// `text` with `line` as the first line under the completion summary heading; +/// the heading and the line are appended when the file has none. The file's +/// own line endings are kept (LF when it has no CRLF). +pub fn with_approval_line(text: &str, line: &str) -> String { + let eol = if text.contains("\r\n") { "\r\n" } else { "\n" }; + let lines: Vec<&str> = text.lines().collect(); + let heading = lines + .iter() + .position(|l| l.trim_end().eq_ignore_ascii_case(SUMMARY_HEADING)); + let mut out: Vec = Vec::new(); + match heading { + Some(at) => { + out.extend(lines[..=at].iter().map(|l| l.to_string())); + out.push(String::new()); + out.push(line.to_string()); + let mut rest = &lines[at + 1..]; + if rest.first().is_some_and(|l| l.trim().is_empty()) { + rest = &rest[1..]; + } + if !rest.is_empty() { + out.push(String::new()); + out.extend(rest.iter().map(|l| l.to_string())); + } + } + None => { + out.extend(lines.iter().map(|l| l.to_string())); + if out.last().is_some_and(|l| !l.is_empty()) { + out.push(String::new()); + } + out.push(SUMMARY_HEADING.to_string()); + out.push(String::new()); + out.push(line.to_string()); + } + } + let mut joined = out.join(eol); + joined.push_str(eol); + joined +} + +/// A temp file beside the target, then a rename. +pub(crate) fn write_atomic(file: &Path, text: &str) -> Result<(), String> { + let name = file + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let temp = file.with_file_name(format!("{name}.loop-tmp")); + std::fs::write(&temp, text).map_err(|e| e.to_string())?; + std::fs::rename(&temp, file).map_err(|e| { + let _ = std::fs::remove_file(&temp); + e.to_string() + }) +} + +/// `LOOP-SUMMARY-.md`: the setup used, each phase, the end state and the +/// Finalize offer. +pub fn summary_markdown(rec: &RunningRecord, date: &str) -> String { + let setup = &rec.setup; + let name = rec.spec.strip_prefix("specs/").unwrap_or(&rec.spec); + let yes = |on: bool| if on { "on" } else { "off" }; + let mut md = format!( + "# Loop report: {name}\n\nBuilt by the Implementation Loop, started {} and finished {date}.\n\n", + rec.report.started + ); + md.push_str("## Setup of the last run\n\n"); + md.push_str(&format!("- Review: {}\n", yes(setup.review))); + if setup.review { + md.push_str(&format!("- Fixes: {}\n", levels_text(setup))); + } + md.push_str(&format!("- Commit each phase: {}\n", yes(setup.commit))); + let on_question = match setup.on_question { + OnQuestion::Pause => "pause and wait for you", + OnQuestion::Stop => "stop the loop", + OnQuestion::Guess => "best guess", + }; + md.push_str(&format!("- When a phase asks something: {on_question}\n")); + let check = setup.quick_check.trim(); + md.push_str(&format!( + "- Quick check: {}\n", + if check.is_empty() { + "none".to_string() + } else { + format!("`{check}`") + } + )); + md.push_str(&format!( + "- Retry once after a crash or silence: {}\n", + yes(setup.retry_once) + )); + // Only whether: this file is committed, and an address may hold a token. + md.push_str(&format!( + "- Send a notification when it stops: {}\n\n", + yes(!setup.notify_url.is_empty()) + )); + md.push_str(&loop_report::body_markdown(&rec.report)); + md.push_str(&format!( + "\n## End state\n\nPhases built by this loop: {}.\n\n", + phase_rows(rec).as_array().map_or(0, Vec::len) + )); + if setup.after_last == AfterLast::RunFinalize { + md.push_str(&format!( + "Finalize was started in a fresh session: `/plan2code-4-finalize {}/overview.md`.\n", + rec.spec + )); + } else { + md.push_str(&format!( + "Next: run Finalize with `/plan2code-4-finalize {}/overview.md`.\n", + rec.spec + )); + } + md +} + +#[cfg(test)] +mod tests { + use super::*; + + fn setup() -> LoopSetup { + LoopSetup { + fix_mode: FixMode::Levels, + on_question: OnQuestion::Pause, + ..LoopSetup::default() + } + } + + #[test] + fn the_messages_say_what_the_person_needs_to_know() { + assert_eq!( + question_message("specs/lunch", 2, false), + "Plan2Code loop is waiting on lunch: Phase 2 has a question for you to answer." + ); + assert_eq!( + stop_message(&StopCause::Question, "specs/lunch", 2, "ignored").unwrap(), + "Plan2Code loop stopped on lunch: Phase 2 has a question for you to answer." + ); + assert_eq!( + finished_message("specs/lunch", 3), + "Plan2Code loop complete on lunch: all 3 phases built." + ); + assert_eq!( + finished_message("specs/lunch", 1), + "Plan2Code loop complete on lunch: 1 phase built." + ); + assert_eq!( + stop_message( + &StopCause::QuickCheck, + "specs/lunch", + 2, + "Phase 2 stopped: tests" + ) + .unwrap(), + "Plan2Code loop stopped on lunch: Phase 2 stopped: tests" + ); + assert_eq!( + stop_message(&StopCause::StoppedByPerson, "specs/lunch", 2, "x"), + None, + "the person is already there" + ); + } + + #[test] + fn no_web_address_means_no_call_and_an_older_entry_reads_with_none() { + assert_eq!(notify(&setup(), "x"), None); + let s: LoopSetup = serde_json::from_value(json!({ "review": true })).unwrap(); + assert_eq!(s.notify_url, ""); + assert_eq!(s.notify_param, "message"); + assert_eq!(confirmed_notify(&s), ""); + } + + #[test] + fn the_confirm_names_the_web_address_and_a_changed_one_is_told_apart() { + let mut s = setup(); + let bare = RunningRecord::new("p".into(), "specs/x".into(), s.clone(), vec![phase(1)]); + assert!(!confirm_text(&bare).contains("calls")); + s.notify_url = "https://e.com/hook".into(); + let first = confirmed_notify(&s); + let rec = RunningRecord::new("p".into(), "specs/x".into(), s.clone(), vec![phase(1)]); + assert!(confirm_text(&rec) + .contains("the app calls: https://e.com/hook with a message in message.")); + s.notify_param = "msg".into(); + let second = confirmed_notify(&s); + assert_ne!(second, first); + s.notify_kind = NotifyKind::Discord; + assert_ne!( + confirmed_notify(&s), + second, + "a changed kind is asked again" + ); + let rec = RunningRecord::new("p".into(), "specs/x".into(), s.clone(), vec![phase(1)]); + assert!(confirm_text(&rec).contains("the app posts to Discord at: https://e.com/hook.")); + } + + #[test] + fn the_summary_never_holds_the_web_address() { + let mut rec = record("specs/x", vec![phase(1)]); + rec.setup.notify_url = "https://e.com/hook?token=secret".into(); + let md = summary_markdown(&rec, "2026-11-01"); + assert!(md.contains("Send a notification when it stops: on")); + assert!(!md.contains("secret")); + } + + #[test] + fn a_new_setup_starts_on_smart_pick_and_best_guess() { + assert_eq!(LoopSetup::default().fix_mode, FixMode::Smart); + assert_eq!(LoopSetup::default().on_question, OnQuestion::Guess); + } + + fn phase(n: u32) -> PhaseRecord { + PhaseRecord { + n, + name: format!("P{n}"), + status: PhaseStatus::Pending, + commit: None, + subject: None, + retries: 0, + } + } + + fn record(spec: &str, phases: Vec) -> RunningRecord { + RunningRecord::new(PathBuf::from("."), spec.into(), setup(), phases) + } + + /// An approval with nothing to warn about. + fn approved() -> Verdict { + Verdict::Approve { warnings: vec![] } + } + + fn status(complete: u64, blocked: u64, open: u64, assumed: u64) -> Value { + json!({ "tasks": { "total": complete + blocked + open + assumed, "complete": complete, "blocked": blocked, "open": open, "pending": 0, "in-progress": 0, "assumed": assumed } }) + } + + fn passed() -> Outcome { + Outcome { + phase: 3, + result: "passed".into(), + subject: "Add the driver".into(), + review: Some(ReviewPart { + ran: true, + recheck: true, + ..ReviewPart::default() + }), + ..Outcome::default() + } + } + + fn finding(level: FixLevel) -> Finding { + Finding { + level, + title: "t".into(), + file: "f".into(), + reason: None, + } + } + + fn refused(v: Verdict) -> String { + match v { + Verdict::Refuse(why) => why, + Verdict::Approve { .. } => panic!("expected a refusal"), + } + } + + #[test] + fn the_prompt_follows_review_fix_and_guess() { + let mut s = setup(); + assert_eq!( + phase_prompt("specs/x", &s), + "/plan2code-3-implement-review specs/x/overview.md --web --loop --fix critical,warning,suggestion" + ); + s.fix = vec![FixLevel::Warning]; + s.on_question = OnQuestion::Guess; + assert_eq!( + phase_prompt("specs/x", &s), + "/plan2code-3-implement-review specs/x/overview.md --web --loop --fix warning --guess" + ); + s.fix_mode = FixMode::Smart; + assert!(phase_prompt("specs/x", &s).contains(" --fix smart --guess")); + s.fix.clear(); + s.fix_mode = FixMode::Levels; + s.on_question = OnQuestion::Pause; + assert!(!phase_prompt("specs/x", &s).contains("--fix")); + s.review = false; + s.fix = vec![FixLevel::Critical]; + assert_eq!( + phase_prompt("specs/x", &s), + "/plan2code-3-implement specs/x/overview.md --web --loop" + ); + } + + #[test] + fn a_clean_report_that_the_spec_agrees_with_is_approved() { + assert_eq!( + judge_outcome(&passed(), &status(14, 0, 0, 0), &setup()), + approved() + ); + } + + #[test] + fn a_failed_report_is_refused_with_its_reason() { + let mut o = passed(); + o.result = "failed".into(); + o.reason = Some("tests".into()); + o.summary = "Opus misses the 40% target".into(); + assert_eq!( + refused(judge_outcome(&o, &status(14, 0, 0, 0), &setup())), + "Opus misses the 40% target", + "the person is told what the agent found, not a contract word" + ); + o.summary = " ".into(); + assert_eq!( + refused(judge_outcome(&o, &status(14, 0, 0, 0), &setup())), + "its tests failed" + ); + o.reason = None; + assert_eq!( + refused(judge_outcome(&o, &status(14, 0, 0, 0), &setup())), + "it reported a failure" + ); + } + + #[test] + fn marks_that_disagree_with_the_report_are_refused() { + assert!( + refused(judge_outcome(&passed(), &status(12, 1, 0, 0), &setup())) + .starts_with("the spec disagrees") + ); + assert!( + refused(judge_outcome(&passed(), &status(12, 0, 2, 0), &setup())) + .starts_with("the spec disagrees") + ); + } + + #[test] + fn assumed_tasks_need_best_guess() { + let st = status(14, 0, 0, 1); + assert_eq!( + refused(judge_outcome(&passed(), &st, &setup())), + "assumed tasks without best guess" + ); + let mut s = setup(); + s.on_question = OnQuestion::Guess; + assert_eq!(judge_outcome(&passed(), &st, &s), approved()); + } + + #[test] + fn review_and_recheck_must_have_run() { + let st = status(14, 0, 0, 0); + let mut o = passed(); + o.review = None; + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "review did not run" + ); + o.review = Some(ReviewPart { + ran: true, + recheck: false, + ..ReviewPart::default() + }); + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "the re-check did not run" + ); + let mut s = setup(); + s.fix.clear(); + assert_eq!(judge_outcome(&o, &st, &s), approved()); + s.review = false; + o.review = None; + assert_eq!(judge_outcome(&o, &st, &s), approved()); + } + + #[test] + fn critical_and_warning_left_at_a_chosen_level_refuse_but_suggestions_never_do() { + let st = status(14, 0, 0, 0); + let mut o = passed(); + o.review.as_mut().unwrap().left = Left { + critical: 1, + warning: 2, + suggestion: 5, + }; + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "1 Critical / 2 Warning left after the re-check" + ); + let mut s = setup(); + s.fix = vec![FixLevel::Critical]; + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "1 Critical left after the re-check" + ); + o.review.as_mut().unwrap().left = Left { + critical: 0, + warning: 0, + suggestion: 5, + }; + assert_eq!( + judge_outcome(&o, &st, &setup()), + Verdict::Approve { + warnings: vec!["5 Suggestions left unfixed".into()] + }, + "leftover Suggestions approve, with a warning" + ); + } + + #[test] + fn smart_pick_needs_the_triage_and_refuses_a_skipped_critical() { + let st = status(14, 0, 0, 0); + let mut s = setup(); + s.fix_mode = FixMode::Smart; + s.fix.clear(); + let mut o = passed(); + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "the triage did not run" + ); + o.review.as_mut().unwrap().triage = Some(Triage { + ran: false, + skipped: vec![], + }); + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "the triage did not run" + ); + o.review.as_mut().unwrap().triage = Some(Triage { + ran: true, + skipped: vec![finding(FixLevel::Warning), finding(FixLevel::Suggestion)], + }); + assert_eq!(judge_outcome(&o, &st, &s), approved()); + o.review + .as_mut() + .unwrap() + .triage + .as_mut() + .unwrap() + .skipped + .push(finding(FixLevel::Critical)); + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "1 Critical skipped by the triage" + ); + // Smart pick counts every level as chosen for what is left. + o.review + .as_mut() + .unwrap() + .triage + .as_mut() + .unwrap() + .skipped + .clear(); + o.review.as_mut().unwrap().left.warning = 1; + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "1 Warning left after the re-check" + ); + } + + #[test] + fn an_unticked_level_never_stops_the_loop_by_level() { + let st = status(14, 0, 0, 0); + let mut s = setup(); + s.fix = vec![FixLevel::Critical]; + let mut o = passed(); + o.review.as_mut().unwrap().left = Left { + critical: 0, + warning: 3, + suggestion: 9, + }; + assert_eq!( + judge_outcome(&o, &st, &s), + Verdict::Approve { + warnings: vec!["9 Suggestions left unfixed".into()] + } + ); + // Smart pick counts every level as chosen, so the same leftover stops it. + s.fix_mode = FixMode::Smart; + o.review.as_mut().unwrap().triage = Some(Triage { + ran: true, + skipped: vec![], + }); + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "3 Warning left after the re-check" + ); + o.review.as_mut().unwrap().left = Left { + critical: 1, + warning: 0, + suggestion: 0, + }; + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "1 Critical left after the re-check" + ); + o.review.as_mut().unwrap().left = Left::default(); + o.review.as_mut().unwrap().recheck = false; + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "the re-check did not run" + ); + } + + #[test] + fn missing_or_empty_status_data_never_reads_as_success() { + let setup = setup(); + let why = |status: Value| refused(judge_outcome(&passed(), &status, &setup)); + assert_eq!( + why(Value::Null), + "the spec has no status for Phase 3", + "a phase the spec does not show" + ); + assert_eq!(why(json!({})), "the spec shows no task counts for Phase 3"); + assert_eq!( + why(json!({ "tasks": { "complete": 14, "open": 0 } })), + "the spec shows no task total for Phase 3" + ); + assert_eq!( + why(json!({ "tasks": { "total": 0, "complete": 0, "open": 0 } })), + "the spec shows no tasks in Phase 3" + ); + assert_eq!( + why(json!({ "tasks": { "total": 14, "complete": 13, "open": 0 } })), + "the spec shows 13 of 14 tasks done", + "a count that does not add up, even with nothing open or blocked" + ); + } + + #[test] + fn a_report_whose_tests_ran_and_failed_is_refused() { + let st = status(14, 0, 0, 0); + let mut o = passed(); + o.tests = Some(TestsPart { + ran: true, + passed: false, + summary: "3 failed +second line" + .into(), + }); + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "its tests ran and failed: 3 failed second line" + ); + o.tests.as_mut().unwrap().summary.clear(); + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "its tests ran and failed" + ); + o.tests = Some(TestsPart { + ran: false, + passed: false, + summary: String::new(), + }); + assert_eq!(judge_outcome(&o, &st, &setup()), approved()); + o.tests = None; + assert_eq!(judge_outcome(&o, &st, &setup()), approved()); + } + + #[test] + fn blocked_tasks_and_conflicts_in_the_report_alone_do_not_refuse() { + let mut o = passed(); + o.tasks.blocked = vec!["3.2".into()]; + o.conflicts = vec!["the spec and the code disagree".into()]; + assert_eq!( + judge_outcome(&o, &status(14, 0, 0, 0), &setup()), + approved(), + "only the spec's own marks decide" + ); + } + + #[test] + fn the_larger_of_the_counter_and_the_unfixed_list_decides_each_level() { + let st = status(14, 0, 0, 0); + // The counter says none, the list holds one Critical. + let mut o = passed(); + o.review.as_mut().unwrap().unfixed = vec![finding(FixLevel::Critical)]; + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "1 Critical left after the re-check" + ); + // The counter says one, the list is empty. + let mut o = passed(); + o.review.as_mut().unwrap().left.critical = 1; + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "1 Critical left after the re-check" + ); + // A leftover Warning refuses, from either source. + let mut o = passed(); + o.review.as_mut().unwrap().unfixed = vec![finding(FixLevel::Warning); 2]; + assert_eq!( + refused(judge_outcome(&o, &st, &setup())), + "2 Warning left after the re-check" + ); + // A leftover Suggestion approves with a warning, singular for one. + let mut o = passed(); + o.review.as_mut().unwrap().unfixed = vec![finding(FixLevel::Suggestion)]; + assert_eq!( + judge_outcome(&o, &st, &setup()), + Verdict::Approve { + warnings: vec!["1 Suggestion left unfixed".into()] + } + ); + // Levels mode: an unfixed finding of a chosen level refuses, of an + // unchosen level does not. + let mut s = setup(); + s.fix = vec![FixLevel::Warning]; + let mut o = passed(); + o.review.as_mut().unwrap().unfixed = vec![finding(FixLevel::Warning)]; + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "1 Warning left after the re-check" + ); + o.review.as_mut().unwrap().unfixed = vec![finding(FixLevel::Critical)]; + assert_eq!(judge_outcome(&o, &st, &s), approved()); + // Smart pick: every level counts as chosen. + let mut s = setup(); + s.fix_mode = FixMode::Smart; + s.fix.clear(); + let mut o = passed(); + o.review.as_mut().unwrap().triage = Some(Triage { + ran: true, + skipped: vec![], + }); + o.review.as_mut().unwrap().unfixed = vec![finding(FixLevel::Warning)]; + assert_eq!( + refused(judge_outcome(&o, &st, &s)), + "1 Warning left after the re-check" + ); + // All zero and an empty list still approve with nothing to say. + let o = passed(); + assert_eq!(judge_outcome(&o, &st, &setup()), approved()); + } + + #[test] + fn the_prompt_orders_levels_fixed_and_drops_fix_without_review() { + let mut s = setup(); + s.fix = vec![FixLevel::Suggestion, FixLevel::Critical]; + assert!(phase_prompt("specs/x", &s).ends_with(" --fix critical,suggestion")); + s.fix_mode = FixMode::Smart; + assert!(phase_prompt("specs/x", &s).ends_with("--web --loop --fix smart")); + assert!(!phase_prompt("specs/x", &s).contains("critical")); + s.review = false; + assert_eq!( + phase_prompt("specs/x", &s), + "/plan2code-3-implement specs/x/overview.md --web --loop" + ); + s.fix_mode = FixMode::Levels; + s.on_question = OnQuestion::Guess; + assert_eq!( + phase_prompt("specs/x", &s), + "/plan2code-3-implement specs/x/overview.md --web --loop --guess" + ); + } + + #[test] + fn an_unknown_result_is_not_approved() { + let mut o = passed(); + o.result = String::new(); + assert!(refused(judge_outcome(&o, &status(14, 0, 0, 0), &setup())) + .starts_with("the report said")); + } + + #[test] + fn the_first_phase_page_wins_and_other_workflows_are_ignored() { + let rec = record("specs/x", vec![]); + let slot: LoopSlot = Arc::new(Mutex::new(Some(rec))); + note_page(&slot, "dashboard", "s0"); + assert!(lock(&slot).as_ref().unwrap().sid.is_none()); + note_page(&slot, "implement-review", "s1"); + note_page(&slot, "implement", "s2"); + let guard = lock(&slot); + assert_eq!(guard.as_ref().unwrap().sid.as_deref(), Some("s1")); + assert_eq!(guard.as_ref().unwrap().last_sid.as_deref(), Some("s1")); + } + + #[test] + fn the_headline_stage_picks_the_step() { + assert_eq!(step_for_stage("Phase 3: Review"), Step::Review); + assert_eq!(step_for_stage("Fixes"), Step::Fixes); + assert_eq!(step_for_stage("Re-check"), Step::Recheck); + assert_eq!(step_for_stage("Phase 3: Driver core"), Step::Build); + assert_eq!(Step::Recheck.label(), "Re-check"); + assert_eq!(Step::WaitingOnYou.label(), "Waiting on you"); + } + + #[test] + fn the_setup_file_entry_reads_with_kebab_values_and_a_missing_fix_mode() { + let entry = json!({ + "review": true, "fix": ["critical", "warning"], "commit": false, + "onQuestion": "guess", "afterLast": "run-finalize", + "quickCheck": "npm run build", "retryOnce": false, "silenceMinutes": 30, + "saved": "2026-11-01T00:00:00Z" + }); + let s: LoopSetup = serde_json::from_value(entry).unwrap(); + assert_eq!(s.fix_mode, FixMode::Levels); + assert_eq!(s.fix, vec![FixLevel::Critical, FixLevel::Warning]); + assert_eq!(s.on_question, OnQuestion::Guess); + assert_eq!(s.after_last, AfterLast::RunFinalize); + assert_eq!(s.silence_minutes, 30); + } + + #[test] + fn the_setup_is_found_under_the_consoles_folded_key() { + let dir = std::env::temp_dir().join(format!("plan2code-loop-setup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let project = dir.join("My Project"); + let file = dir.join("loop-setup.json"); + let store = json!({ "schema": 1, "projects": { fold_key(&project): { "quickCheck": "make", "commit": true } } }); + std::fs::write(&file, store.to_string()).unwrap(); + assert_eq!( + read_setup_from(&file, &project).unwrap().quick_check, + "make" + ); + let other = read_setup_from(&file, &dir.join("elsewhere")).unwrap_err(); + assert_eq!(other, "No loop setup saved for this project"); + std::fs::write(&file, r#"{"schema":2,"projects":{}}"#).unwrap(); + assert!(read_setup_from(&file, &project).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(windows)] + #[test] + fn the_key_is_lowercase_with_backslashes_and_no_trailing_separator() { + assert_eq!( + fold_key(Path::new("C:/Git/Plan2Code/")), + r"c:\git\plan2code" + ); + assert_eq!(fold_key(Path::new(r"\\?\C:\Git\X")), r"c:\git\x"); + } + + #[test] + fn the_approval_line_names_the_check_and_the_review() { + let mut s = setup(); + s.quick_check = "npm run build".into(); + assert_eq!( + approval_line("2026-11-01", &s), + "Approved by the Implementation Loop on 2026-11-01: tests passed, quick check passed (npm run build), review at critical, warning, suggestion." + ); + s.quick_check.clear(); + s.review = false; + assert!( + approval_line("2026-11-01", &s).ends_with("tests passed, no quick check, review off.") + ); + s.review = true; + s.fix_mode = FixMode::Smart; + assert!(approval_line("2026-11-01", &s).ends_with("review at smart pick.")); + } + + #[test] + fn the_approval_line_goes_first_under_the_heading_and_the_rest_stays() { + let text = "# Phase 3\n\n## Phase Completion Summary\n\n_Filled in after implementation._\n\n## Notes\n\nx\n"; + let out = with_approval_line(text, "Approved."); + assert_eq!( + out, + "# Phase 3\n\n## Phase Completion Summary\n\nApproved.\n\n_Filled in after implementation._\n\n## Notes\n\nx\n" + ); + // A heading with nothing after it; CRLF in, CRLF out. + assert_eq!( + with_approval_line("a\r\n## Phase Completion Summary\r\n", "Approved."), + "a\r\n## Phase Completion Summary\r\n\r\nApproved.\r\n" + ); + } + + #[test] + fn a_file_without_the_heading_gets_it_at_the_end() { + assert_eq!( + with_approval_line("# Phase 3\n\nbody\n", "Approved."), + "# Phase 3\n\nbody\n\n## Phase Completion Summary\n\nApproved.\n" + ); + } + + #[test] + fn only_a_spec_folder_directly_under_specs_is_valid() { + let dir = std::env::temp_dir().join(format!("plan2code-loop-spec-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("specs").join("lunch-vote")).unwrap(); + std::fs::write(dir.join("specs").join("a-file"), "x").unwrap(); + assert!(validate_spec(&dir, "specs/lunch-vote").is_ok()); + for bad in [ + "specs/missing", + "specs/a-file", + "specs/../x", + "specs/a/b", + "lunch-vote", + "specs/", + "specs/a b", + ] { + assert!(validate_spec(&dir, bad).is_err(), "{bad}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_confirm_names_the_phase_count_and_the_quick_check() { + let mut rec = record( + "specs/lunch-vote", + vec![phase(3), phase(4), phase(5), phase(6)], + ); + assert_eq!( + confirm_text(&rec), + "Build 4 phases of lunch-vote? No quick check is set." + ); + rec.setup.quick_check = "npm run build".into(); + assert_eq!( + confirm_text(&rec), + "Build 4 phases of lunch-vote? After each phase the app runs: npm run build" + ); + } + + #[test] + fn the_summary_lists_every_phase_its_commit_and_the_unfixed_findings() { + let mut done = phase(3); + done.name = "Driver | core".into(); + done.status = PhaseStatus::Done; + done.commit = Some("a1b2c3d".into()); + done.subject = Some("Add the driver".into()); + let mut rec = record("specs/x", vec![done]); + rec.report.entries.push(ReportEntry { + at: "2026-11-01 10:00".into(), + phase: 3, + name: "Driver | core".into(), + commit: Some("a1b2c3d".into()), + subject: "Add the driver".into(), + reported: true, + review_ran: true, + skipped: vec![Finding { + level: FixLevel::Warning, + title: "Rename".into(), + file: "src/y.js".into(), + reason: Some("Outside this phase".into()), + }], + ..ReportEntry::default() + }); + rec.step = Step::Commit; + let md = summary_markdown(&rec, "2026-11-01"); + assert!(md.contains( + "| Phase 3: Driver \\| core | a1b2c3d | Add the driver | 0 | 1 | 0 | 0 | 0 | 0 |" + )); + assert!(md.contains("- warning: Rename (`src/y.js`): Outside this phase")); + assert!(md.contains("Next: run Finalize with `/plan2code-4-finalize specs/x/overview.md`.")); + assert!(!md.contains('\u{2014}')); + } + + // ----------------------------------------------- failures, stops, the strip + + fn at(minutes: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(minutes * 60) + } + + #[test] + fn silence_waits_past_the_limit_and_never_while_a_question_waits() { + let s = setup(); // 20 minutes + assert!(!silence_expired(at(120), at(100), &s, None, false)); + assert!(silence_expired(at(121), at(100), &s, None, false)); + // A waiting question has no time limit. + assert!(!silence_expired(at(1000), at(0), &s, None, true)); + // The skill's own quiet minutes stretch the limit, never shrink it. + assert!(!silence_expired(at(140), at(100), &s, Some(45), false)); + assert!(silence_expired(at(146), at(100), &s, Some(45), false)); + assert!(silence_expired(at(121), at(100), &s, Some(5), false)); + // Capped at 60 minutes whatever either side asks for. + assert!(silence_expired(at(161), at(100), &s, Some(500), false)); + let mut long = setup(); + long.silence_minutes = 60; + assert!(!silence_expired(at(160), at(100), &long, Some(90), false)); + assert!(silence_expired(at(161), at(100), &long, Some(90), false)); + // A clock that went backwards is not silence. + assert!(!silence_expired(at(100), at(200), &s, None, false)); + } + + #[test] + fn only_a_crash_silence_or_a_missing_console_retries_and_only_once() { + let s = setup(); + for cause in [StopCause::Crash, StopCause::Silence, StopCause::NoSession] { + assert!(should_retry(&cause, &s, 0), "{cause:?}"); + assert!(!should_retry(&cause, &s, 1), "{cause:?} twice"); + } + for cause in [ + StopCause::Refused("x".into()), + StopCause::QuickCheck, + StopCause::Commit, + StopCause::Question, + StopCause::StoppedByPerson, + ] { + assert!(!should_retry(&cause, &s, 0), "{cause:?}"); + } + let mut off = setup(); + off.retry_once = false; + assert!(!should_retry(&StopCause::Crash, &off, 0)); + assert!(!should_retry(&StopCause::Silence, &off, 0)); + } + + #[test] + fn a_question_is_an_open_required_item_the_loop_does_not_handle() { + let item = |status: &str, extra: Value| { + let mut v = json!({ "id": "q1", "kind": "choice", "status": status }); + if let (Some(o), Some(e)) = (v.as_object_mut(), extra.as_object()) { + for (k, val) in e { + o.insert(k.clone(), val.clone()); + } + } + json!({ "items": [v] }) + }; + assert!(open_question(&item("open", json!({})))); + assert!(open_question(&item( + "reopened", + json!({ "required": true }) + ))); + assert!(!open_question(&item("answered", json!({})))); + assert!(!open_question(&item("skipped", json!({})))); + assert!(!open_question(&item("open", json!({ "required": false })))); + assert!(!open_question(&item("open", json!({ "kind": "notice" })))); + assert!(!open_question(&item( + "open", + json!({ "handledBy": "loop" }) + ))); + assert!(open_question(&item("open", json!({ "handledBy": null })))); + assert!(!open_question(&json!({}))); + assert!(!open_question(&json!({ "items": [] }))); + } + + #[test] + fn each_stop_has_its_line() { + assert_eq!( + stop_line(&StopCause::Crash, 3, "exit code 1", false), + "Phase 3 stopped: the agent crashed (exit code 1)" + ); + assert_eq!( + stop_line(&StopCause::Crash, 3, "exit code 1", true), + "Phase 3 stopped: the agent crashed (exit code 1) after one retry" + ); + assert_eq!( + stop_line(&StopCause::Silence, 2, "20", true), + "Phase 2 stopped: the agent went silent for 20 minutes after one retry" + ); + assert_eq!( + stop_line(&StopCause::NoSession, 2, "", false), + "Phase 2 stopped: the agent never opened the console" + ); + assert_eq!( + stop_line(&StopCause::Question, 4, "", false), + "Phase 4 stopped: it asked a question" + ); + assert_eq!( + stop_line(&StopCause::QuickCheck, 4, "", false), + "Phase 4 stopped: the quick check failed" + ); + assert_eq!( + stop_line(&StopCause::Commit, 4, "lint says no", false), + "Phase 4 was not committed: lint says no. The work is uncommitted; Resume tries the commit again" + ); + assert_eq!( + stop_line( + &StopCause::MarkedNotCommitted("phase-4.md".into()), + 4, + "", + false + ), + "Phase 4 is marked done in phase-4.md but its work is not committed" + ); + assert_eq!( + stop_line( + &StopCause::Refused("1 Warning left after the re-check".into()), + 2, + "", + false + ), + "Phase 2 stopped: 1 Warning left after the re-check" + ); + assert_eq!( + stop_line(&StopCause::StoppedByPerson, 5, "", false), + "Stopped during Phase 5. This phase's changes stay uncommitted." + ); + } + + #[test] + fn the_evidence_for_a_refusal_lists_the_report_and_the_blocked_tasks() { + let mut rec = record("specs/x", vec![phase(2)]); + let mut outcome = passed(); + outcome.summary = "Built the screen".into(); + outcome.tests = Some(TestsPart { + ran: true, + passed: false, + summary: "2 failed".into(), + }); + let review = outcome.review.as_mut().unwrap(); + review.left = Left { + critical: 0, + warning: 1, + suggestion: 2, + }; + review.unfixed.push(Finding { + level: FixLevel::Warning, + title: "Name the timer".into(), + file: "src/x.js".into(), + reason: None, + }); + rec.last_outcome = Some(outcome); + rec.last_entry = Some(json!({ + "blockedTasks": ["2.3", { "id": "2.4" }], + "assumedTasks": [] + })); + let cause = StopCause::Refused("1 Warning left after the re-check".into()); + let md = evidence_markdown( + &cause, + "Phase 2 stopped: 1 Warning left after the re-check", + &rec, + ); + assert!(md.starts_with("## What happened")); + assert!(md.contains("- Summary: Built the screen")); + assert!(md.contains("- Tests: 2 failed")); + assert!(md.contains("0 Critical, 1 Warning, 2 Suggestion")); + assert!(md.contains("- Blocked tasks: 2.3, 2.4")); + assert!(md.contains("- Assumed tasks: none")); + assert!(md.contains("warning: Name the timer (src/x.js)")); + } + + #[test] + fn the_evidence_of_an_approved_phase_that_stopped_later_shows_the_suggestion_warning() { + let mut rec = record("specs/x", vec![phase(2)]); + let mut outcome = passed(); + outcome + .review + .as_mut() + .unwrap() + .unfixed + .push(finding(FixLevel::Suggestion)); + rec.last_outcome = Some(outcome); + let md = evidence_markdown(&StopCause::QuickCheck, "l", &rec); + assert!(md.contains("- Warnings: 1 Suggestion left unfixed"), "{md}"); + rec.last_outcome = Some(passed()); + let md = evidence_markdown(&StopCause::QuickCheck, "l", &rec); + assert!(!md.contains("Warnings"), "{md}"); + } + + #[test] + fn the_evidence_keeps_a_failed_checks_command_and_the_tail_of_its_output() { + let mut rec = record("specs/x", vec![phase(2)]); + rec.setup.quick_check = "npm run build".into(); + rec.failure_output = Some(format!("{}\nerror TS2304: nope", "x".repeat(60_000))); + let md = evidence_markdown(&StopCause::QuickCheck, "line", &rec); + assert!(md.contains("Command: `npm run build`")); + assert!(md.contains("error TS2304: nope")); + assert!(md.contains("(earlier output left out)")); + assert!(md.len() < EVIDENCE_LIMIT); + // A refused commit keeps the hook's words. + rec.failure_output = Some("pre-commit hook failed".into()); + let md = evidence_markdown(&StopCause::Commit, "line", &rec); + assert!(md.contains("pre-commit hook failed")); + assert!(md.contains("not committed")); + // Output that holds a code fence cannot close ours early. + rec.failure_output = Some("a ``` b".into()); + let md = evidence_markdown(&StopCause::Commit, "line", &rec); + assert!(md.contains("a ''' b")); + } + + #[test] + fn a_crash_and_silence_name_nothing_the_agent_did_not_leave() { + let rec = record("specs/x", vec![phase(2)]); + let md = evidence_markdown( + &StopCause::Crash, + "Phase 2 stopped: the agent crashed (x)", + &rec, + ); + assert!(md.contains("terminal")); + assert!(!md.contains("What the phase reported")); + let md = evidence_markdown(&StopCause::Silence, "l", &rec); + assert!(md.contains("Nothing changed")); + assert!(!md.contains('\u{2014}')); + } + + #[test] + fn the_tail_cuts_on_a_character_boundary() { + let text = "ab\u{e9}\u{e9}\u{e9}cd"; + let cut = tail(text, 5); + assert!(cut.ends_with("cd")); + assert_eq!(tail("short", 100), "short"); + } + + #[test] + fn the_strip_shows_the_spec_phase_and_step() { + let mut rec = record("specs/lunch-vote", vec![phase(4), phase(5), phase(7)]); + rec.current = 1; + rec.step = Step::Review; + rec.retries_used = 1; + rec.stop_after_phase = true; + let event = state_event(&rec); + assert!(event.running); + assert_eq!(event.spec_name, "lunch-vote"); + assert_eq!(event.phase, 5); + assert_eq!(event.phases, 7); + assert_eq!(event.step, "Review"); + assert_eq!(event.phase_name, "P5"); + assert_eq!(event.previous_phase, None, "Phase 4 is not done"); + assert!(!event.phase_retried); + assert_eq!(event.retries_used, 1); + assert!(event.stop_after_phase); + assert!(event.started_at_ms > 0); + let json = serde_json::to_value(&event).unwrap(); + assert_eq!(json["specName"], "lunch-vote"); + assert_eq!(json["stopAfterPhase"], true); + assert!(json["startedAtMs"].is_u64()); + let ended = LoopStateEvent::ended(); + assert!(!ended.running); + } + + #[test] + fn the_banner_hears_what_just_finished_and_whether_this_is_a_retry() { + let mut rec = record("specs/x", vec![phase(1), phase(2)]); + assert_eq!(state_event(&rec).previous_phase, None); + rec.phases[0].status = PhaseStatus::Done; + rec.phases[0].commit = Some("abc1234".into()); + rec.current = 1; + let event = state_event(&rec); + assert_eq!(event.previous_phase, Some(1)); + assert!(event.previous_committed); + rec.phases[0].commit = None; + assert!(!state_event(&rec).previous_committed); + rec.phases[1].retries = 1; + assert!(state_event(&rec).phase_retried); + let json = serde_json::to_value(state_event(&rec)).unwrap(); + assert_eq!(json["phaseName"], "P2"); + assert_eq!(json["previousPhase"], 1); + assert_eq!(json["phaseRetried"], true); + } + + /// A local web address that hands over the first line of each call it gets. + fn listening_address() -> (String, std::sync::mpsc::Receiver) { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let (tx, rx) = std::sync::mpsc::channel(); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + let mut buf = [0u8; 4096]; + let n = stream.read(&mut buf).unwrap_or(0); + let text = String::from_utf8_lossy(&buf[..n]).to_string(); + let _ = stream.write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ); + let first = text.lines().next().unwrap_or("").to_string(); + if tx.send(first).is_err() { + return; + } + } + }); + (format!("http://127.0.0.1:{port}/hook"), rx) + } + + /// A running loop on a temp project, with no session, so nothing reaches a console. + fn notifying_loop(name: &str) -> (Ctx, std::sync::mpsc::Receiver) { + let dir = std::env::temp_dir().join(format!( + "plan2code-loop-notify-{name}-{}", + std::process::id() + )); + std::fs::create_dir_all(dir.join("specs/lunch")).unwrap(); + let report_home = dir.join("console-home"); + std::fs::create_dir_all(&report_home).unwrap(); + let _ = std::fs::remove_file(report_home.join(loop_report::REPORTS_FILE)); + let (url, calls) = listening_address(); + let mut s = setup(); + s.notify_url = url; + s.notify_param = "msg".into(); + let rec = RunningRecord::new(dir, "specs/lunch".into(), s, vec![phase(2), phase(3)]); + let run_id = rec.run_id; + let slot: LoopSlot = Arc::new(Mutex::new(Some(rec))); + let ctx = Ctx { + slot, + agent: Arc::new(AgentManager::new(PathBuf::from("."), Arc::new(|_| {}))), + console_dir: PathBuf::from("."), + home: report_home, + launch: ( + Agent::Builtin(crate::agents::AgentKind::Claude), + None, + None, + PermissionMode::Bypass, + ), + run_id, + hooks: Arc::new(Hooks { + emit: Box::new(|_| {}), + attention: Box::new(|| {}), + }), + limits: Limits::default(), + }; + (ctx, calls) + } + + // ------------------------------------------------ the loop test harness + // + // A real throwaway git repository, the fake agent in a pseudo-terminal and + // millisecond limits, so the loop's glue code runs end to end without a + // mock of git. + + /// Whether `program` runs; a test that needs it says so and skips when not. + /// On CI (`CI` is set) a missing program fails the test instead, so a + /// runner without git or node cannot turn the tests into silent passes. + fn program_ready(test: &str, program: &str) -> bool { + let found = std::process::Command::new(program) + .arg("--version") + .output() + .is_ok_and(|out| out.status.success()); + if !found { + assert!( + std::env::var_os("CI").is_none(), + "{test}: {program} is not on PATH" + ); + eprintln!("SKIPPED {test}: {program} is not on PATH"); + } + found + } + + fn git_ready(test: &str) -> bool { + program_ready(test, "git") + } + + /// Git, node and the skill scripts (`specs.mjs`, `commit-msg.mjs`) the tick + /// runs. The scripts are the repository's own (see `loop_tools::skill_script`). + fn harness_ready(test: &str) -> bool { + let scripts = loop_tools::skill_script("specs.mjs").is_some() + && loop_tools::skill_script("commit-msg.mjs").is_some(); + assert!( + scripts, + "{test}: the skill scripts are missing from src/skill-scripts" + ); + git_ready(test) && program_ready(test, "node") + } + + fn git_in(repo: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .args(args) + .current_dir(repo) + .output() + .expect("run git"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + /// A new git repository in a unique temp folder, with `specs/lunch` (Phases + /// 2 and 3, two open tasks each) and one commit. The console home sits + /// beside it, in `console-home`. + fn throwaway_repo(name: &str) -> PathBuf { + let base = + std::env::temp_dir().join(format!("plan2code-loop-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let repo = base.join("repo"); + let spec = repo.join("specs/lunch"); + std::fs::create_dir_all(&spec).unwrap(); + git_in(&repo, &["init", "-q"]); + for (key, value) in [ + ("user.name", "Loop Test"), + ("user.email", "loop@example.com"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + // A global hooks folder must not run in a test. + ("core.hooksPath", ".git/hooks"), + ] { + git_in(&repo, &["config", key, value]); + } + std::fs::write( + spec.join("overview.md"), + "# Lunch - Overview\n\n## Phase Checklist\n\n- [/] [Phase 2: P2](./phase-2.md)\n- [ ] [Phase 3: P3](./phase-3.md)\n", + ) + .unwrap(); + for n in [2, 3] { + std::fs::write( + spec.join(format!("phase-{n}.md")), + format!( + "# Phase {n}: P{n}\n\n**Status:** In Progress\n\n## Tasks\n\n- [ ] **Task {n}.1:** First\n- [ ] **Task {n}.2:** Second\n" + ), + ) + .unwrap(); + } + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "Start the lunch spec"]); + repo + } + + /// Make `.git/hooks/pre-commit` refuse every commit, printing `first_line` + /// and a second line to stderr. + fn add_failing_hook(repo: &Path, first_line: &str) { + let hook = repo.join(".git/hooks/pre-commit"); + std::fs::create_dir_all(hook.parent().unwrap()).unwrap(); + std::fs::write( + &hook, + format!("#!/bin/sh\necho \"{first_line}\" >&2\necho \"second line\" >&2\nexit 1\n"), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + /// What `specs.mjs status` says about the throwaway spec. + fn spec_status(repo: &Path) -> Value { + loop_tools::specs_status(repo, "specs/lunch").expect("specs.mjs status") + } + + /// Tick every task of Phase `n` off, as a finished build leaves it. + fn finish_phase_tasks(repo: &Path, n: u32) { + let file = repo.join(format!("specs/lunch/phase-{n}.md")); + let text = std::fs::read_to_string(&file).unwrap(); + std::fs::write(&file, text.replace("- [ ]", "- [x]")).unwrap(); + } + + /// Where `cargo build -p fake-agent` leaves the fake agent, built on first use. + fn fake_agent_path() -> PathBuf { + static BUILD: std::sync::Once = std::sync::Once::new(); + BUILD.call_once(|| { + let status = std::process::Command::new(env!("CARGO")) + .args(["build", "-p", "fake-agent"]) + .status() + .expect("run cargo"); + assert!(status.success(), "could not build the fake agent"); + }); + // The test binary is in target//deps; the fake agent is one up. + let exe = std::env::current_exe().unwrap(); + let path = exe + .parent() + .and_then(|deps| deps.parent()) + .unwrap() + .join(format!("fake-agent{}", std::env::consts::EXE_SUFFIX)); + assert!(path.exists(), "{} is missing", path.display()); + path + } + + /// The fake agent as a custom agent. The loop's tests start it this way, not + /// through `PLAN2CODE_APP_AGENT_BIN`: that variable is process-wide, and + /// other tests in this process read it. + fn fake_agent_launch() -> Launch { + let agent = crate::agents::CustomAgent { + id: "fake".into(), + name: "Fake agent".into(), + command: fake_agent_path().to_string_lossy().into_owned(), + args: Vec::new(), + prompt: String::new(), + bypass_args: Vec::new(), + model_args: Vec::new(), + models: Vec::new(), + }; + (Agent::Custom(agent), None, None, PermissionMode::Bypass) + } + + /// An agent manager for the fake agent, and everything the agents printed. The pump answers the pseudo-terminal's cursor question, + /// as a terminal does, or Windows holds the output back. + fn fake_agent_manager(folder: &Path) -> (Arc, Arc>) { + use crate::agent_manager::AgentEvent; + let (tx, rx) = std::sync::mpsc::channel(); + let tx = Mutex::new(tx); + let sink: crate::agent_manager::Sink = Arc::new(move |event| { + let _ = lock(&tx).send(event); + }); + let manager = Arc::new(AgentManager::new(folder.to_path_buf(), sink)); + let seen = Arc::new(Mutex::new(String::new())); + let (weak, log) = (Arc::downgrade(&manager), Arc::clone(&seen)); + thread::spawn(move || { + for event in rx { + if let AgentEvent::Output(bytes) = event { + let text = String::from_utf8_lossy(&bytes).into_owned(); + if text.contains("[6n") { + if let Some(manager) = weak.upgrade() { + let _ = manager.input(b"\x1b[1;1R"); + } + } + lock(&log).push_str(&text); + } + } + }); + (manager, seen) + } + + /// Poll until `ready`; the wait ends on state, not on a fixed sleep. + fn wait_until(what: &str, mut ready: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(30); + while Instant::now() < deadline { + if ready() { + return; + } + thread::sleep(Duration::from_millis(20)); + } + panic!("never saw {what}"); + } + + /// `running_loop` with the fake agent's output as well. + fn running_loop_seen(repo: &Path, limits: Limits) -> (Ctx, PathBuf, Arc>) { + let home = repo.parent().unwrap().join("console-home"); + std::fs::create_dir_all(home.join("sessions/s1")).unwrap(); + std::fs::write(home.join("sessions/s1/state.json"), "{\"schema\":1}").unwrap(); + let (agent, seen) = fake_agent_manager(repo); + let mut rec = RunningRecord::new( + repo.to_path_buf(), + "specs/lunch".into(), + setup(), + vec![phase(2), phase(3)], + ); + rec.sid = Some("s1".into()); + rec.last_sid = Some("s1".into()); + let run_id = rec.run_id; + let ctx = Ctx { + slot: Arc::new(Mutex::new(Some(rec))), + agent, + console_dir: PathBuf::from("."), + home: home.clone(), + launch: fake_agent_launch(), + run_id, + hooks: Arc::new(Hooks { + emit: Box::new(|_| {}), + attention: Box::new(|| {}), + }), + limits, + }; + (ctx, home, seen) + } + + /// A loop on the throwaway repo, session `s1` open, the given limits and + /// the fake agent: what `notifying_loop` is, with real git behind it. + fn running_loop(repo: &Path, limits: Limits) -> (Ctx, PathBuf) { + let (ctx, home, _) = running_loop_seen(repo, limits); + (ctx, home) + } + + /// Replace session `s1`'s `state.json`, whole, as the console does + /// (with the schema number the reader insists on). + fn write_session(home: &Path, mut state: Value) { + state["schema"] = json!(crate::session_reader::SCHEMA); + let dir = home.join("sessions/s1"); + std::fs::write(dir.join("state.json.tmp"), state.to_string()).unwrap(); + std::fs::rename(dir.join("state.json.tmp"), dir.join("state.json")).unwrap(); + } + + /// A phase report that passes every check. + fn good_report(phase: u32) -> Value { + json!({ + "phase": phase, + "result": "passed", + "summary": "Built it", + "subject": "Add the driver", + "tests": { "ran": true, "passed": true, "summary": "ok" }, + "review": { "ran": true, "recheck": true }, + "tasks": { "blocked": [], "assumed": [] }, + }) + } + + fn end_the_test(ctx: &Ctx) { + ctx.agent.stop(); + *lock(&ctx.slot) = None; + } + + /// The last entry of the loop's saved report, once the loop has ended. + fn last_entry_saved(home: &Path, repo: &Path) -> ReportEntry { + loop_report::load(home, repo, "specs/lunch") + .expect("a saved report") + .entries + .last() + .cloned() + .expect("an entry") + } + + #[test] + fn the_default_limits_are_the_watchers_own_constants() { + let limits = Limits::default(); + assert_eq!(limits.watch_every, Duration::from_secs(2)); + assert_eq!(limits.notice_wait, Duration::from_secs(180)); + assert_eq!(limits.activity_every, Duration::from_secs(30)); + } + + #[test] + fn a_throwaway_repo_has_the_spec_and_a_failing_hook_stops_a_commit() { + if !harness_ready("throwaway repo") { + return; + } + let repo = throwaway_repo("harness"); + let status = spec_status(&repo); + assert_eq!(status["phases"].as_array().unwrap().len(), 2); + assert_eq!(status["phases"][0]["tasks"]["open"], 2); + add_failing_hook(&repo, "hook says no"); + std::fs::write(repo.join("new.txt"), "x").unwrap(); + let added = loop_tools::git_add_all(&repo); + assert!(added.ok); + let done = loop_tools::git_commit(&repo, "Add new\n\nAI Assisted"); + assert!(!done.ok); + assert!(done.output.starts_with("hook says no"), "{}", done.output); + } + + #[test] + fn a_good_report_passes_marks_the_phase_done_and_commits_it() { + if !harness_ready("good report") { + return; + } + let repo = throwaway_repo("good-report"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx), "the loop goes on to Phase 3"); + { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + assert_eq!(rec.current, 1); + assert_eq!(rec.phases[0].status, PhaseStatus::Done); + let head = git_in(&repo, &["rev-parse", "--short", "HEAD"]); + assert_eq!(rec.phases[0].commit.as_deref(), Some(head.as_str())); + assert_eq!(rec.phases[0].subject.as_deref(), Some("Add the driver")); + } + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "x"); + end_the_test(&ctx); + } + + #[test] + fn a_phase_that_never_opens_its_console_stops_with_that_cause() { + if !git_ready("no session") { + return; + } + let repo = throwaway_repo("no-session"); + let limits = Limits { + notice_wait: Duration::ZERO, + ..Limits::default() + }; + let (ctx, home) = running_loop(&repo, limits); + { + let mut guard = lock(&ctx.slot); + let rec = guard.as_mut().unwrap(); + rec.sid = None; + rec.setup.retry_once = false; + } + assert!(!tick(&ctx), "the loop is over"); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert_eq!( + entry.line, + "Phase 2 stopped: the agent never opened the console" + ); + } + + #[test] + fn a_crashed_agent_gets_one_retry_and_then_the_loop_stops() { + if !git_ready("crash") { + return; + } + let repo = throwaway_repo("crash"); + let (ctx, home, seen) = running_loop_seen(&repo, Limits::default()); + let ready = |count: usize| { + wait_until("the fake agent ready", || { + lock(&seen).matches("FAKE-AGENT ready").count() >= count + }) + }; + let crash = || { + ctx.agent.input(b"EXIT 3\r").unwrap(); + wait_until("the agent ended", || { + matches!(ctx.agent.snapshot().state, AgentState::Ended { .. }) + }); + }; + start_phase(&ctx, 0).expect("start the fake agent"); + ready(1); + crash(); + assert!(tick(&ctx), "the first crash is retried"); + { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + assert_eq!(rec.phases[0].retries, 1); + assert_eq!(rec.retries_used, 1); + assert_eq!(rec.phases[0].status, PhaseStatus::Running); + } + ready(2); + crash(); + assert!(!tick(&ctx), "the second crash stops the loop"); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert!(entry.line.contains("the agent crashed"), "{}", entry.line); + assert!(entry.line.ends_with("after one retry"), "{}", entry.line); + } + + #[test] + fn a_refused_commit_stops_the_loop() { + if !harness_ready("refused commit") { + return; + } + let repo = throwaway_repo("refused-commit"); + add_failing_hook(&repo, "lint says no"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + let before = std::fs::read_to_string(repo.join("specs/lunch/phase-2.md")).unwrap(); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(!tick(&ctx)); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert_eq!( + entry.line, + "Phase 2 was not committed: lint says no. The work is uncommitted; Resume tries the commit again" + ); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Start the lunch spec", + "nothing was committed" + ); + // The mark was taken back: the phase is open and its file is as the + // agent left it. + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/"); + assert_eq!( + std::fs::read_to_string(repo.join("specs/lunch/phase-2.md")).unwrap(), + before + ); + let status = git_in(&repo, &["status", "--porcelain"]); + assert!(status.contains("specs/lunch/phase-2.md"), "{status}"); + assert_eq!( + git_in(&repo, &["diff", "--cached", "--name-only"]), + "", + "nothing stays staged" + ); + let saved = loop_report::load(&home, &repo, "specs/lunch").unwrap(); + assert_eq!(saved.marked_not_committed, None); + + // Resume with the hook fixed commits the same phase. + std::fs::remove_file(repo.join(".git/hooks/pre-commit")).unwrap(); + let (again, home) = running_loop(&repo, Limits::default()); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&again), "the loop goes on to Phase 3"); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "x"); + end_the_test(&again); + } + + #[test] + fn a_passing_report_with_failed_tests_is_refused_and_nothing_changes() { + if !harness_ready("failed tests") { + return; + } + let repo = throwaway_repo("failed-tests"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + let before = std::fs::read_to_string(repo.join("specs/lunch/phase-2.md")).unwrap(); + let head = git_in(&repo, &["rev-parse", "HEAD"]); + let mut report = good_report(2); + report["tests"] = json!({ "ran": true, "passed": false, "summary": "2 failed" }); + write_session(&home, json!({ "loopOutcome": report })); + assert!(!tick(&ctx)); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert_eq!( + entry.line, + "Phase 2 stopped: its tests ran and failed: 2 failed" + ); + assert_eq!(git_in(&repo, &["rev-parse", "HEAD"]), head, "no commit"); + assert_eq!( + git_in(&repo, &["diff", "--cached", "--name-only"]), + "", + "nothing staged" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/"); + assert_eq!( + std::fs::read_to_string(repo.join("specs/lunch/phase-2.md")).unwrap(), + before, + "the spec is untouched" + ); + } + + #[test] + fn a_phase_with_a_task_left_open_is_refused_with_the_specs_counts() { + if !harness_ready("open task") { + return; + } + let repo = throwaway_repo("open-task"); + let (ctx, home) = running_loop(&repo, Limits::default()); + // The agent ticked one task and reported success all the same. + let file = repo.join("specs/lunch/phase-2.md"); + let text = std::fs::read_to_string(&file).unwrap(); + std::fs::write(&file, text.replacen("- [ ]", "- [x]", 1)).unwrap(); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(!tick(&ctx)); + let entry = last_entry_saved(&home, &repo); + assert_eq!( + entry.line, + "Phase 2 stopped: the spec disagrees: 0 blocked, 1 still open" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/"); + } + + #[test] + fn a_leftover_suggestion_commits_the_phase_and_is_recorded_as_a_warning() { + if !harness_ready("leftover suggestion") { + return; + } + let repo = throwaway_repo("leftover-suggestion"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + let mut report = good_report(2); + report["review"] = json!({ + "ran": true, + "recheck": true, + "left": { "critical": 0, "warning": 0, "suggestion": 1 }, + "unfixed": [ + { "level": "suggestion", "title": "Name the timer", "file": "src/x.js" }, + { "level": "suggestion", "title": "Trim the log", "file": "src/y.js" } + ] + }); + write_session(&home, json!({ "loopOutcome": report })); + assert!(tick(&ctx), "the loop goes on to Phase 3"); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + let saved = loop_report::load(&home, &repo, "specs/lunch").unwrap(); + let entry = saved.entries.last().unwrap(); + assert_eq!(entry.result, EntryResult::Passed); + assert_eq!( + entry.warnings, + vec!["2 Suggestions left unfixed".to_string()], + "the larger of the counter (1) and the list (2)" + ); + end_the_test(&ctx); + } + + #[test] + fn the_approval_line_is_inside_the_phases_commit() { + if !harness_ready("approval in commit") { + return; + } + let repo = throwaway_repo("approval-commit"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx)); + let shown = git_in(&repo, &["show", "HEAD"]); + assert!( + shown.contains("Approved by the Implementation Loop on"), + "{shown}" + ); + assert!(shown.contains("specs/lunch/overview.md"), "{shown}"); + assert_eq!(git_in(&repo, &["status", "--porcelain"]), ""); + end_the_test(&ctx); + } + + #[test] + fn a_failed_undo_stops_with_the_exact_message_and_the_fact_outlives_the_run() { + if !harness_ready("failed undo") { + return; + } + let repo = throwaway_repo("failed-undo"); + // The hook edits the phase file while the commit runs, so the loop + // cannot tell its own text from the person's and must not restore it. + let hook = repo.join(".git/hooks/pre-commit"); + std::fs::create_dir_all(hook.parent().unwrap()).unwrap(); + std::fs::write( + &hook, + "#!/bin/sh\necho \"edited\" >> specs/lunch/phase-2.md\necho \"hook says no\" >&2\nexit 1\n", + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(!tick(&ctx)); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!( + entry.line, + "Phase 2 is marked done in phase-2.md but its work is not committed" + ); + // A re-load of the store, as after an app restart. + let saved = loop_report::load(&home, &repo, "specs/lunch").unwrap(); + assert_eq!( + saved.marked_not_committed, + Some(loop_report::MarkedNotCommitted { + phase: 2, + file: "phase-2.md".into() + }) + ); + // Resume finds the mark has no commit and opens the phase again. + let status = spec_status(&repo); + assert_eq!(status["phases"][0]["marker"], "x"); + let reopened = loop_commit::unbacked_marks(&repo, "specs/lunch", &status, &saved, true); + assert_eq!(reopened, vec![2]); + loop_commit::reopen(&repo, "specs/lunch", &reopened).unwrap(); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/"); + } + + /// What a stopped phase leaves behind when the agent left `file` in the + /// tree: the line, the spec and git as the person would find them. + fn assert_unsafe_stop(repo: &Path, home: &Path, ctx: &Ctx, file: &str) { + assert!(!tick(ctx), "the loop is over"); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(home, repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert_eq!( + entry.line, + format!( + "Phase 2 was not committed: {file} look like secrets or are over 5 MB. Nothing was marked or committed" + ) + ); + assert_eq!( + git_in(repo, &["log", "-1", "--format=%s"]), + "Start the lunch spec", + "nothing was committed" + ); + assert_eq!( + git_in(repo, &["diff", "--cached", "--name-only"]), + "", + "nothing stays staged" + ); + assert_eq!(spec_status(repo)["phases"][0]["marker"], "/"); + let phase = std::fs::read_to_string(repo.join("specs/lunch/phase-2.md")).unwrap(); + assert!(!phase.contains("Approved by the Implementation Loop")); + let saved = loop_report::load(home, repo, "specs/lunch").unwrap(); + assert_eq!(saved.marked_not_committed, None); + } + + #[test] + fn an_agent_that_leaves_an_env_file_stops_the_phase_before_any_mark() { + if !harness_ready("env file") { + return; + } + let repo = throwaway_repo("env-file"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + std::fs::write(repo.join(".env"), "TOKEN=abc").unwrap(); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert_unsafe_stop(&repo, &home, &ctx, ".env"); + } + + #[test] + fn an_agent_that_leaves_a_six_megabyte_file_stops_the_phase() { + if !harness_ready("big file") { + return; + } + let repo = throwaway_repo("big-file"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + let big = std::fs::File::create(repo.join("dump.bin")).unwrap(); + big.set_len(6 * 1024 * 1024).unwrap(); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert_unsafe_stop(&repo, &home, &ctx, "dump.bin"); + } + + #[test] + fn many_offending_files_are_named_five_at_a_time_and_all_in_the_evidence() { + let files: Vec = (1..=7).map(|n| format!("k{n}.pem")).collect(); + let cause = StopCause::UnsafeFiles(files.clone()); + assert_eq!( + stop_line(&cause, 4, "", false), + "Phase 4 was not committed: k1.pem, k2.pem, k3.pem, k4.pem, k5.pem and 2 more look like secrets or are over 5 MB. Nothing was marked or committed" + ); + let mut rec = record("specs/lunch", vec![phase(4)]); + rec.own_dirty = vec!["mine.txt".into()]; + let md = evidence_markdown(&cause, "line", &rec); + for file in &files { + assert!(md.contains(&format!("`{file}`")), "{file} missing: {md}"); + } + assert!(md.contains("(a key or certificate)"), "{md}"); + assert!(md.contains("## Your own files") && md.contains("`mine.txt`")); + let big = evidence_markdown(&StopCause::UnsafeFiles(vec!["dump.bin".into()]), "l", &rec); + assert!(big.contains("`dump.bin` (over 5 MB)"), "{big}"); + // The line is never sent as a notification for a stop by the person. + assert!(stop_message(&cause, "specs/lunch", 4, "x").is_some()); + } + + #[test] + fn an_env_example_is_committed_like_any_other_file() { + if !harness_ready("env example") { + return; + } + let repo = throwaway_repo("env-example"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + std::fs::write(repo.join(".env.example"), "TOKEN=").unwrap(); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx), "the loop goes on to Phase 3"); + let shown = git_in(&repo, &["show", "--name-only", "--format=%s", "HEAD"]); + assert!(shown.contains(".env.example"), "{shown}"); + end_the_test(&ctx); + } + + fn add_slow_hook(repo: &Path, seconds: u32) { + let hook = repo.join(".git/hooks/pre-commit"); + std::fs::create_dir_all(hook.parent().unwrap()).unwrap(); + std::fs::write(&hook, format!("#!/bin/sh\nsleep {seconds}\nexit 0\n")).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + #[test] + fn a_slow_hook_commits_within_the_commit_limit_and_is_cut_off_past_it() { + if !harness_ready("commit limit") { + return; + } + // Within the limit: the hook's two seconds do not matter. + let repo = throwaway_repo("slow-hook"); + add_slow_hook(&repo, 1); + let limits = Limits { + commit_limit: Duration::from_secs(30), + ..Limits::default() + }; + let (ctx, home) = running_loop(&repo, limits); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx), "a slow hook still commits"); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + end_the_test(&ctx); + + // Past the limit: the commit is stopped, the mark is taken back. + let repo = throwaway_repo("slow-hook-cut"); + add_slow_hook(&repo, 20); + let limits = Limits { + commit_limit: Duration::from_millis(300), + ..Limits::default() + }; + let (ctx, home) = running_loop(&repo, limits); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(!tick(&ctx)); + let entry = last_entry_saved(&home, &repo); + assert!(entry.line.contains("stopped after"), "{}", entry.line); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/"); + } + + #[test] + fn start_refuses_a_detached_head_with_commit_on_or_off() { + if !harness_ready("detached") { + return; + } + let repo = throwaway_repo("detached"); + git_in(&repo, &["checkout", "-q", "--detach"]); + for commit in [true, false] { + let err = prepare_with( + &repo, + "specs/lunch", + LoopSetup { + commit, + ..prepare_setup() + }, + &LoopReport::new("specs/lunch", "now"), + PermissionMode::Bypass, + true, + false, + ) + .expect_err("a detached HEAD is refused"); + assert_eq!( + err, + "HEAD is detached. Switch to a branch before starting the loop" + ); + } + assert_eq!(loop_tools::git_branch(&repo), Ok(None)); + } + + #[test] + fn the_confirm_names_main_and_resume_never_skips_it_there() { + if !harness_ready("trunk") { + return; + } + let repo = throwaway_repo("trunk"); + let report = LoopReport::new("specs/lunch", "now"); + let go = || { + prepare_with( + &repo, + "specs/lunch", + prepare_setup(), + &report, + PermissionMode::Bypass, + true, + true, + ) + .expect("prepare") + }; + for trunk in ["main", "master"] { + git_in(&repo, &["checkout", "-q", "-B", trunk]); + let rec = go(); + assert_eq!(rec.branch.as_deref(), Some(trunk)); + assert!(commits_to_trunk(&rec)); + assert!( + confirm_text(&rec).contains(&format!( + "You are on `{trunk}`: every phase will commit straight to it. Start only if that is what you want." + )), + "{}", + confirm_text(&rec) + ); + } + git_in(&repo, &["checkout", "-q", "-b", "feature/lunch"]); + let rec = go(); + assert!(!commits_to_trunk(&rec)); + assert!(!confirm_text(&rec).contains("You are on")); + } + + #[test] + fn the_stop_screen_leaves_out_what_was_dirty_at_start() { + if !harness_ready("own dirty") { + return; + } + let repo = throwaway_repo("own-dirty"); + std::fs::write(repo.join("mine.txt"), "mine").unwrap(); + let rec = prepare_with( + &repo, + "specs/lunch", + prepare_setup(), + &LoopReport::new("specs/lunch", "now"), + PermissionMode::Bypass, + true, + true, + ) + .expect("a resume takes the dirty tree"); + assert_eq!(rec.own_dirty, vec!["mine.txt"]); + assert_eq!( + rec.start_head.as_deref(), + Some(git_in(&repo, &["rev-parse", "HEAD"]).as_str()) + ); + std::fs::write(repo.join("agent work.txt"), "x").unwrap(); + assert_eq!( + uncommitted_files(&repo, &rec.own_dirty), + vec!["agent work.txt"] + ); + } + + #[test] + fn the_agents_work_is_what_is_dirty_now_less_what_was_dirty_then() { + let own = vec!["a.txt".to_string()]; + let now = vec!["a.txt".to_string(), "b.txt".to_string()]; + assert_eq!(agent_work(now, &own), vec!["b.txt"]); + assert_eq!(agent_work(vec!["c".into()], &[]), vec!["c"]); + assert!(agent_work(Vec::new(), &own).is_empty()); + assert!(is_trunk("main") && is_trunk("master")); + assert!(!is_trunk("mainline") && !is_trunk("feature/main")); + } + + /// The setup the prepare tests use: commit on, notification off. + fn prepare_setup() -> LoopSetup { + LoopSetup { + commit: true, + ..setup() + } + } + + #[test] + fn start_needs_a_clean_tree_and_resume_takes_the_dirty_one_it_left() { + if !harness_ready("prepare") { + return; + } + let repo = throwaway_repo("prepare-dirty"); + let report = LoopReport::new("specs/lunch", "now"); + let go = |resuming: bool| { + prepare_with( + &repo, + "specs/lunch", + prepare_setup(), + &report, + PermissionMode::Bypass, + true, + resuming, + ) + }; + let rec = go(false).expect("a clean tree starts"); + assert_eq!(rec.resumed_files, None); + std::fs::write(repo.join("agent-work.txt"), "x").unwrap(); + let err = go(false).expect_err("a dirty tree refuses a fresh Start"); + assert!(err.contains("clean tree: 1 uncommitted"), "{err}"); + let rec = go(true).expect("Resume takes the dirty tree"); + assert_eq!(rec.resumed_files, Some(1)); + assert!(confirm_text(&rec).contains("1 uncommitted file already in the tree")); + } + + #[test] + fn a_phase_with_no_commit_behind_its_mark_is_listed_but_not_written_until_confirmed() { + if !harness_ready("prepare rebuilt") { + return; + } + let repo = throwaway_repo("prepare-rebuilt"); + // Phase 2 is marked done by the loop, and its commit is gone. + assert!(loop_tools::specs_mark_done(&repo, "specs/lunch", 2).ok); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "Mark Phase 2 by hand"]); + let mut report = LoopReport::new("specs/lunch", "now"); + report.entries.push(ReportEntry { + phase: 2, + commit: Some("deadbee".into()), + ..ReportEntry::default() + }); + let go = |commit: bool| { + prepare_with( + &repo, + "specs/lunch", + LoopSetup { + commit, + ..prepare_setup() + }, + &report, + PermissionMode::Bypass, + true, + false, + ) + .expect("prepare") + }; + let rec = go(true); + assert_eq!(rec.rebuilt, vec![2]); + assert_eq!(rec.phases.iter().map(|p| p.n).collect::>(), [2, 3]); + assert_eq!( + spec_status(&repo)["phases"][0]["marker"], + "x", + "nothing written yet" + ); + assert_eq!(git_in(&repo, &["status", "--porcelain"]), ""); + assert!(confirm_text(&rec).contains("Phase 2 is marked done but has no commit")); + reopen_rebuilt(&rec).unwrap(); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/"); + // With commit off the mark is trusted: only Phase 3 is left. + assert!(loop_tools::specs_mark_done(&repo, "specs/lunch", 2).ok); + let rec = go(false); + assert!(rec.rebuilt.is_empty()); + assert_eq!(rec.phases.iter().map(|p| p.n).collect::>(), [3]); + } + + #[test] + fn a_commit_that_gives_no_reason_still_reads_as_a_sentence() { + assert_eq!( + stop_line(&StopCause::Commit, 2, "", false), + "Phase 2 was not committed: git gave no reason. The work is uncommitted; Resume tries the commit again" + ); + } + + #[test] + fn with_commit_off_the_phase_is_marked_and_nothing_is_committed() { + if !harness_ready("commit off") { + return; + } + let repo = throwaway_repo("commit-off"); + add_failing_hook(&repo, "never reached"); + let (ctx, home) = running_loop(&repo, Limits::default()); + lock(&ctx.slot).as_mut().unwrap().setup.commit = false; + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx)); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Start the lunch spec" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "x"); + let text = std::fs::read_to_string(repo.join("specs/lunch/phase-2.md")).unwrap(); + assert!( + text.contains("Approved by the Implementation Loop on"), + "{text}" + ); + end_the_test(&ctx); + } + + #[test] + fn finish_writes_the_summary_and_empties_the_slot() { + if !git_ready("finish") { + return; + } + let repo = throwaway_repo("finish"); + let (ctx, _home) = running_loop(&repo, Limits::default()); + { + let mut guard = lock(&ctx.slot); + let rec = guard.as_mut().unwrap(); + for p in &mut rec.phases { + p.status = PhaseStatus::Done; + p.commit = Some("abc1234".into()); + } + rec.current = 1; + } + finish(&ctx); + assert!(lock(&ctx.slot).is_none()); + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + let md = std::fs::read_to_string(repo.join(format!("specs/lunch/LOOP-SUMMARY-{date}.md"))) + .expect("the summary file"); + assert!(md.contains("Phases built by this loop: 2.")); + } + + #[test] + fn stop_after_ends_the_loop_once_the_phase_is_built() { + if !harness_ready("stop after") { + return; + } + let repo = throwaway_repo("stop-after"); + let (ctx, home) = running_loop(&repo, Limits::default()); + request_stop_after(&ctx.slot, true).unwrap(); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(!tick(&ctx)); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert_eq!(entry.line, "Stopped after Phase 2, as asked"); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + } + + #[test] + fn stop_now_with_no_agent_running_leaves_the_slot_taken_until_the_next_look() { + if !git_ready("stop now") { + return; + } + let repo = throwaway_repo("stop-now"); + let (ctx, home) = running_loop(&repo, Limits::default()); + request_stop_now(&ctx.slot, Some(&ctx.agent), |_| {}).unwrap(); + // Only the watcher's next look ends the loop (the flag is read first), + // so the slot stays taken until then. + assert!(is_running(&ctx.slot)); + assert!(lock(&ctx.slot).as_ref().unwrap().stop_now); + assert!(!tick(&ctx)); + assert!(lock(&ctx.slot).is_none()); + let entry = last_entry_saved(&home, &repo); + assert_eq!( + entry.line, + "Stopped during Phase 2. This phase's changes stay uncommitted." + ); + } + + #[test] + fn the_watcher_thread_runs_on_its_limits_and_ends_the_loop_when_stopped() { + if !git_ready("watcher") { + return; + } + let repo = throwaway_repo("watcher"); + let limits = Limits { + watch_every: Duration::from_millis(10), + ..Limits::default() + }; + let (ctx, _home) = running_loop(&repo, limits); + request_stop_now(&ctx.slot, Some(&ctx.agent), |_| {}).unwrap(); + let watcher = ctx.clone(); + thread::spawn(move || watch(watcher)); + wait_until("the watcher to end the loop", || !is_running(&ctx.slot)); + } + + // ------------------------------------ the watcher and the stop promises + + /// Wait until the fake agent has printed its ready line `count` times. + fn fake_agent_ready(seen: &Arc>, count: usize) { + wait_until("the fake agent ready", || { + lock(seen).matches("FAKE-AGENT ready").count() >= count + }); + } + + /// Wait until the loop's report holds an entry (the stop was written). + fn wait_for_entry(home: &Path, repo: &Path) { + wait_until("the stop to be reported", || { + loop_report::load(home, repo, "specs/lunch").is_some_and(|r| !r.entries.is_empty()) + }); + } + + #[test] + fn a_panic_in_the_watcher_stops_the_loop_and_the_agent_and_a_new_loop_can_start() { + if !harness_ready("watcher panic") { + return; + } + let repo = throwaway_repo("watcher-panic"); + let limits = Limits { + watch_every: Duration::from_millis(10), + ..Limits::default() + }; + let (ctx, home, seen) = running_loop_seen(&repo, limits); + start_phase(&ctx, 0).expect("start the fake agent"); + fake_agent_ready(&seen, 1); + let watcher = ctx.clone(); + thread::spawn(move || { + watch_with(watcher, |c| { + // A panic inside the lock poisons it, the worst case for the stop. + let _held = c.slot.lock().unwrap(); + panic!("boom inside the lock"); + }) + }); + wait_for_entry(&home, &repo); + assert!(!is_running(&ctx.slot), "the slot is cleared"); + assert!(ctx.slot.is_poisoned(), "the lock really was poisoned"); + wait_until("the agent to end", || { + matches!(ctx.agent.snapshot().state, AgentState::Idle) + }); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert_eq!( + entry.line, + "The loop's watcher failed: boom inside the lock. Nothing more was committed; Resume starts again" + ); + // A new loop can take the slot. + *lock(&ctx.slot) = Some(record("specs/lunch", vec![phase(2), phase(3)])); + assert!(is_running(&ctx.slot)); + abandon(&ctx.slot); + } + + #[test] + fn a_watcher_that_returns_false_just_ends() { + if !git_ready("watcher ends") { + return; + } + let repo = throwaway_repo("watcher-ends"); + let limits = Limits { + watch_every: Duration::from_millis(5), + ..Limits::default() + }; + let (ctx, _home) = running_loop(&repo, limits); + let mut looks = 0; + watch_with(ctx.clone(), |_| { + looks += 1; + looks < 3 + }); + assert_eq!(looks, 3); + assert!(is_running(&ctx.slot), "no stop: the step ended the watch"); + end_the_test(&ctx); + } + + #[test] + fn an_unreadable_session_counts_as_silence_and_a_good_read_clears_the_count() { + if !harness_ready("unreadable session") { + return; + } + let repo = throwaway_repo("unreadable"); + let (ctx, home) = running_loop(&repo, Limits::default()); + lock(&ctx.slot).as_mut().unwrap().setup.retry_once = false; + std::fs::write(home.join("sessions/s1/state.json"), "not json at all").unwrap(); + assert!(tick(&ctx), "recent activity: still waiting"); + assert!(tick(&ctx)); + assert_eq!(lock(&ctx.slot).as_ref().unwrap().read_failures, 2); + // A good read puts the count back to zero. + write_session(&home, json!({})); + assert!(tick(&ctx)); + assert_eq!(lock(&ctx.slot).as_ref().unwrap().read_failures, 0); + // Unreadable again, and quiet for two hours: the loop ends as silent. + std::fs::write(home.join("sessions/s1/state.json"), "{").unwrap(); + lock(&ctx.slot).as_mut().unwrap().last_activity = + SystemTime::now() - Duration::from_secs(2 * 60 * 60); + assert!(!tick(&ctx), "silence ends the loop"); + assert!(!is_running(&ctx.slot)); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert!( + entry + .line + .starts_with("Phase 2 stopped: the agent went silent for"), + "{}", + entry.line + ); + } + + #[test] + fn a_state_file_that_stays_locked_or_a_directory_still_ends_in_a_silence_stop() { + if !harness_ready("locked session") { + return; + } + let repo = throwaway_repo("locked-session"); + let (ctx, home) = running_loop(&repo, Limits::default()); + lock(&ctx.slot).as_mut().unwrap().setup.retry_once = false; + // A directory where the file belongs: Windows reads that as a locked + // file (Busy), other systems as unreadable; both must end the same way. + let state = home.join("sessions/s1/state.json"); + std::fs::remove_file(&state).unwrap(); + std::fs::create_dir(&state).unwrap(); + assert!(tick(&ctx), "recent activity: still waiting"); + lock(&ctx.slot).as_mut().unwrap().last_activity = + SystemTime::now() - Duration::from_secs(2 * 60 * 60); + assert!(!tick(&ctx), "silence ends the loop"); + assert!(!is_running(&ctx.slot)); + let entry = last_entry_saved(&home, &repo); + assert!(entry.line.contains("went silent for"), "{}", entry.line); + } + + #[test] + fn stop_now_tells_the_strip_while_the_slot_is_held() { + let slot: LoopSlot = Arc::new(Mutex::new(Some(record( + "specs/x", + vec![phase(2), phase(3)], + )))); + let mut told = Vec::new(); + let event = request_stop_now(&slot, None, |event| { + assert!( + slot.try_lock().is_err(), + "the slot is held while it is told" + ); + told.push(event.clone()); + }) + .unwrap(); + assert_eq!(told, vec![event]); + assert!(told[0].stopping); + let none: LoopSlot = Arc::new(Mutex::new(None)); + let mut called = false; + assert!(request_stop_now(&none, None, |_| called = true).is_err()); + assert!(!called, "no loop, nothing to tell"); + } + + #[test] + fn the_silence_evidence_says_when_the_session_could_not_be_read() { + let mut rec = record("specs/x", vec![phase(2)]); + let line = stop_line(&StopCause::Silence, 2, "20", false); + let plain = evidence_markdown(&StopCause::Silence, &line, &rec); + assert!(!plain.contains("could not be read")); + rec.read_failures = 3; + let md = evidence_markdown(&StopCause::Silence, &line, &rec); + assert!(md.contains("The session could not be read during that time")); + } + + #[test] + fn a_report_written_just_before_the_agent_exits_is_handled_not_retried() { + if !harness_ready("report before exit") { + return; + } + let repo = throwaway_repo("report-before-exit"); + let (ctx, home, seen) = running_loop_seen(&repo, Limits::default()); + start_phase(&ctx, 0).expect("start the fake agent"); + fake_agent_ready(&seen, 1); + // The look found no report; then the agent wrote it and exited. + let snap = take_snapshot(&ctx).unwrap(); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + ctx.agent.input(b"EXIT 0\r").unwrap(); + wait_until("the agent ended", || { + matches!(ctx.agent.snapshot().state, AgentState::Ended { .. }) + }); + assert_eq!(crash_or_outcome(&ctx, &snap, "s1"), Some(true)); + { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + assert_eq!(rec.phases[0].status, PhaseStatus::Done); + assert_eq!(rec.phases[0].retries, 0, "not retried"); + assert_eq!(rec.retries_used, 0); + assert_eq!(rec.current, 1, "the next phase began"); + } + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + end_the_test(&ctx); + } + + #[test] + fn an_ended_agent_with_no_report_is_a_crash_and_one_that_has_not_ended_is_no_crash() { + if !harness_ready("crash or outcome") { + return; + } + let repo = throwaway_repo("crash-or-outcome"); + let (ctx, home, seen) = running_loop_seen(&repo, Limits::default()); + lock(&ctx.slot).as_mut().unwrap().setup.retry_once = false; + start_phase(&ctx, 0).expect("start the fake agent"); + fake_agent_ready(&seen, 1); + let snap = take_snapshot(&ctx).unwrap(); + assert_eq!(crash_or_outcome(&ctx, &snap, "s1"), None, "still running"); + ctx.agent.input(b"EXIT 3\r").unwrap(); + wait_until("the agent ended", || { + matches!(ctx.agent.snapshot().state, AgentState::Ended { .. }) + }); + assert_eq!(crash_or_outcome(&ctx, &snap, "s1"), Some(false)); + assert!(!is_running(&ctx.slot)); + assert!(last_entry_saved(&home, &repo).line.contains("crashed")); + } + + #[test] + fn a_file_dated_in_the_future_never_holds_the_last_sign_of_work_ahead_of_the_clock() { + let dir = std::env::temp_dir().join(format!("plan2code-clamp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("future.txt"); + std::fs::write(&file, "x").unwrap(); + let future = SystemTime::now() + Duration::from_secs(24 * 60 * 60); + std::fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(future) + .unwrap(); + let seen = modified(&file).expect("a time"); + assert!(seen <= SystemTime::now(), "clamped to now"); + assert!(clamp_to_now(future) <= SystemTime::now()); + let past = SystemTime::now() - Duration::from_secs(60); + assert_eq!(clamp_to_now(past), past, "an older time is left alone"); + // Silence fires on a clamped time once the limit has passed. + let setup = setup(); + let quiet = SystemTime::now() - Duration::from_secs(61 * 60); + assert!(silence_expired( + SystemTime::now(), + quiet, + &setup, + None, + false + )); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn stop_now_sets_the_flag_with_or_without_an_agent_and_tells_the_strip() { + let slot: LoopSlot = Arc::new(Mutex::new(Some(record( + "specs/x", + vec![phase(2), phase(3)], + )))); + let before = current_event(&slot).unwrap(); + assert!(!before.stopping); + assert!(before.can_stop_after, "not the last phase"); + let event = request_stop_now(&slot, None, |_| {}).expect("no agent is not an error"); + assert!(event.stopping); + assert!(lock(&slot).as_ref().unwrap().stop_now); + let ended = LoopStateEvent::ended(); + assert!(!ended.stopping && !ended.can_stop_after); + } + + #[test] + fn stop_after_toggles_and_is_refused_on_the_last_phase() { + let slot: LoopSlot = Arc::new(Mutex::new(Some(record( + "specs/x", + vec![phase(2), phase(3)], + )))); + assert!(request_stop_after(&slot, true).unwrap().stop_after_phase); + assert!(!request_stop_after(&slot, false).unwrap().stop_after_phase); + assert!(!lock(&slot).as_ref().unwrap().stop_after_phase); + lock(&slot).as_mut().unwrap().current = 1; + let event = current_event(&slot).unwrap(); + assert!( + !event.can_stop_after, + "the last phase has nothing to stop after" + ); + assert_eq!( + request_stop_after(&slot, true), + Err("This is the last phase".to_string()) + ); + assert!(!lock(&slot).as_ref().unwrap().stop_after_phase); + assert!( + request_stop_after(&slot, false).is_ok(), + "off is always allowed" + ); + } + + #[test] + fn stop_after_on_then_off_carries_on_to_the_next_phase() { + if !harness_ready("stop after toggle") { + return; + } + let repo = throwaway_repo("stop-after-toggle"); + let (ctx, home) = running_loop(&repo, Limits::default()); + request_stop_after(&ctx.slot, true).unwrap(); + request_stop_after(&ctx.slot, false).unwrap(); + finish_phase_tasks(&repo, 2); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx), "the loop goes on to Phase 3"); + { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + assert_eq!(rec.current, 1); + assert_eq!(rec.phases[0].status, PhaseStatus::Done); + } + end_the_test(&ctx); + } + + #[test] + fn stop_now_before_the_commit_commits_nothing_retries_nothing_and_marks_nothing() { + if !harness_ready("stop now before commit") { + return; + } + let repo = throwaway_repo("stop-now-before"); + let (ctx, home) = running_loop(&repo, Limits::default()); + finish_phase_tasks(&repo, 2); + // The look began before Stop now was pressed. + let snap = take_snapshot(&ctx).unwrap(); + request_stop_now(&ctx.slot, Some(&ctx.agent), |_| {}).unwrap(); + assert!(!handle_outcome(&ctx, &snap, &good_report(2))); + assert!(!is_running(&ctx.slot)); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Start the lunch spec", + "nothing was committed" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "/", "not marked"); + assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), ""); + let entry = last_entry_saved(&home, &repo); + assert_eq!( + entry.line, + "Stopped during Phase 2. This phase's changes stay uncommitted." + ); + } + + #[test] + fn stop_now_after_the_agent_ended_is_not_a_crash_and_starts_no_retry() { + if !harness_ready("stop now not a crash") { + return; + } + let repo = throwaway_repo("stop-now-crash"); + let (ctx, home, seen) = running_loop_seen(&repo, Limits::default()); + { + let mut guard = lock(&ctx.slot); + guard.as_mut().unwrap().setup.retry_once = true; + } + start_phase(&ctx, 0).expect("start the fake agent"); + fake_agent_ready(&seen, 1); + let snap = take_snapshot(&ctx).unwrap(); + request_stop_now(&ctx.slot, Some(&ctx.agent), |_| {}).unwrap(); + // The look that began earlier meets the ended agent. + assert!(!fail(&ctx, &snap, StopCause::Crash, "exit code 1".into())); + assert!(!is_running(&ctx.slot)); + assert!( + matches!(ctx.agent.snapshot().state, AgentState::Idle), + "the agent is ended and no retry started another" + ); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert!( + entry.line.starts_with("Stopped during Phase 2"), + "{}", + entry.line + ); + assert_eq!(entry.retries, 0); + } + + /// A pre-commit hook that says it has begun, then takes `seconds`. + fn add_marking_slow_hook(repo: &Path, seconds: u32) { + let hook = repo.join(".git/hooks/pre-commit"); + std::fs::create_dir_all(hook.parent().unwrap()).unwrap(); + std::fs::write( + &hook, + format!("#!/bin/sh\necho begun > .git/hook-begun\nsleep {seconds}\nexit 0\n"), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + /// Press Stop now once the commit's hook has begun, and return how the + /// phase's look went (whether the loop would go on). + fn stop_now_during_the_commit(repo: &Path, ctx: &Ctx, phase: u32) -> bool { + add_marking_slow_hook(repo, 2); + finish_phase_tasks(repo, phase); + let snap = take_snapshot(ctx).unwrap(); + let (worker, report) = (ctx.clone(), good_report(phase)); + let handle = thread::spawn(move || handle_outcome(&worker, &snap, &report)); + wait_until("the commit's hook to begin", || { + repo.join(".git/hook-begun").exists() + }); + request_stop_now(&ctx.slot, Some(&ctx.agent), |_| {}).unwrap(); + handle.join().expect("the look did not panic") + } + + #[test] + fn stop_now_while_a_slow_hook_runs_finishes_the_commit_and_nothing_follows() { + if !harness_ready("stop now during commit") { + return; + } + let repo = throwaway_repo("stop-now-during"); + let limits = Limits { + commit_limit: Duration::from_secs(60), + ..Limits::default() + }; + let (ctx, home) = running_loop(&repo, limits); + assert!(!stop_now_during_the_commit(&repo, &ctx, 2)); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver", + "the begun commit finished" + ); + assert_eq!(spec_status(&repo)["phases"][0]["marker"], "x"); + assert!(!is_running(&ctx.slot)); + assert!( + matches!(ctx.agent.snapshot().state, AgentState::Idle), + "no next phase's agent" + ); + let report = loop_report::load(&home, &repo, "specs/lunch").unwrap(); + let passed = report + .entries + .iter() + .find(|e| e.result == EntryResult::Passed); + assert!( + passed.is_some_and(|e| e.commit.is_some()), + "recorded as done" + ); + assert_eq!( + last_entry_saved(&home, &repo).line, + "Stopped after Phase 2 was committed, as asked" + ); + } + + #[test] + fn stop_now_on_the_last_phase_never_finishes_the_loop_or_runs_finalize() { + if !harness_ready("stop now last phase") { + return; + } + let repo = throwaway_repo("stop-now-last"); + let limits = Limits { + commit_limit: Duration::from_secs(60), + ..Limits::default() + }; + let (ctx, home) = running_loop(&repo, limits); + { + let mut guard = lock(&ctx.slot); + let rec = guard.as_mut().unwrap(); + rec.setup.after_last = AfterLast::RunFinalize; + rec.phases[0].status = PhaseStatus::Done; + rec.phases[0].commit = Some("abc1234".into()); + rec.current = 1; + rec.phases[1].status = PhaseStatus::Running; + } + assert!(!stop_now_during_the_commit(&repo, &ctx, 3)); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + assert!( + !repo + .join(format!("specs/lunch/LOOP-SUMMARY-{date}.md")) + .exists(), + "finish never ran" + ); + assert!( + matches!(ctx.agent.snapshot().state, AgentState::Idle), + "no Finalize agent" + ); + assert_eq!( + last_entry_saved(&home, &repo).line, + "Stopped after Phase 3 was committed, as asked" + ); + } + + #[test] + fn finish_skips_finalize_when_stop_now_was_pressed() { + if !harness_ready("finish skips finalize") { + return; + } + let repo = throwaway_repo("finish-skips"); + let (ctx, _home) = running_loop(&repo, Limits::default()); + { + let mut guard = lock(&ctx.slot); + let rec = guard.as_mut().unwrap(); + rec.setup.after_last = AfterLast::RunFinalize; + for p in &mut rec.phases { + p.status = PhaseStatus::Done; + p.commit = Some("abc1234".into()); + } + rec.current = 1; + rec.stop_now = true; + } + finish(&ctx); + assert!(!is_running(&ctx.slot)); + assert!( + matches!(ctx.agent.snapshot().state, AgentState::Idle), + "Finalize was not started" + ); + } + + #[test] + fn a_stale_stop_never_ends_a_newer_loops_agent() { + if !harness_ready("stale stop") { + return; + } + let repo = throwaway_repo("stale-stop"); + let (ctx, _home, seen) = running_loop_seen(&repo, Limits::default()); + start_phase(&ctx, 0).expect("start the fake agent"); + fake_agent_ready(&seen, 1); + // Another loop took the slot; this one's watcher is stale. + let newer = record("specs/lunch", vec![phase(2), phase(3)]); + let newer_id = newer.run_id; + *lock(&ctx.slot) = Some(newer); + stop_loop(&ctx, StopCause::Crash, "stale".into(), &["resume", "fix"]); + assert!( + matches!(ctx.agent.snapshot().state, AgentState::Running), + "the agent was left alone" + ); + assert_eq!(lock(&ctx.slot).as_ref().unwrap().run_id, newer_id); + end_the_test(&ctx); + } + + #[test] + fn the_watcher_failed_stop_has_its_line_and_is_never_retried() { + let cause = StopCause::WatcherFailed("index out of bounds".into()); + assert_eq!( + stop_line(&cause, 3, "", false), + "The loop's watcher failed: index out of bounds. Nothing more was committed; Resume starts again" + ); + assert!(!should_retry(&cause, &setup(), 0)); + let line = stop_line(&cause, 3, "", false); + assert!(stop_message(&cause, "specs/lunch", 3, &line) + .unwrap() + .contains("watcher failed")); + let rec = record("specs/x", vec![phase(3)]); + assert!(evidence_markdown(&cause, &line, &rec).contains("watcher stopped working")); + let long = StopCause::WatcherFailed("x".repeat(500)); + assert!( + stop_line(&long, 1, "", false).len() < 200, + "trimmed to a line" + ); + } + + const QUIET: Duration = Duration::from_millis(300); + const CALL_WAIT: Duration = Duration::from_secs(10); + + #[test] + fn a_report_outlasts_a_stop_and_a_resume_and_lands_in_the_project_when_built() { + let (ctx, _calls) = notifying_loop("report"); + let (home, project) = { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + (ctx.home.clone(), rec.project.clone()) + }; + std::fs::write( + project.join("specs/lunch/phase-2.md"), + "- [?] **Task 2.1:** Pick\n - Assumed: SQLite\n", + ) + .unwrap(); + for old in std::fs::read_dir(project.join("specs/lunch")).unwrap() { + let old = old.unwrap(); + if old + .file_name() + .to_string_lossy() + .starts_with("LOOP-SUMMARY") + { + std::fs::remove_file(old.path()).unwrap(); + } + } + // The first run: the phase reports a skip, then the quick check stops it. + { + let mut guard = lock(&ctx.slot); + let rec = guard.as_mut().unwrap(); + let mut outcome = passed(); + outcome.review.as_mut().unwrap().triage = Some(Triage { + ran: true, + skipped: vec![Finding { + level: FixLevel::Warning, + title: "Rename the helper".into(), + file: "src/y.js".into(), + reason: Some("Outside this phase".into()), + }], + }); + outcome.decisions = vec!["Kept the old route".into()]; + rec.last_outcome = Some(outcome); + } + stop_loop( + &ctx, + StopCause::QuickCheck, + "Phase 2 stopped: the quick check failed".into(), + &["resume"], + ); + assert!(lock(&ctx.slot).is_none()); + let saved = loop_report::load(&home, &project, "specs/lunch").unwrap(); + assert_eq!(saved.entries.len(), 1); + assert_eq!(saved.entries[0].result, EntryResult::Stopped); + assert_eq!(saved.entries[0].skipped[0].title, "Rename the helper"); + assert_eq!(saved.entries[0].assumed[0].note, "SQLite"); + assert_eq!(saved.entries[0].decisions, vec!["Kept the old route"]); + + // Resume: a new run holding only what is left, on the same report. + let mut rec = RunningRecord::new( + project.clone(), + "specs/lunch".into(), + setup(), + vec![phase(3)], + ); + rec.report = saved; + rec.report.entries.push(ReportEntry { + at: "t".into(), + phase: 2, + name: "P2".into(), + commit: Some("abc1234".into()), + fixed: vec![finding(FixLevel::Critical)], + reported: true, + review_ran: true, + ..ReportEntry::default() + }); + rec.report.entries.push(ReportEntry { + at: "t".into(), + phase: 3, + name: "P3".into(), + commit: Some("def5678".into()), + reported: true, + ..ReportEntry::default() + }); + let run_id = rec.run_id; + let rows = phase_rows(&rec); + assert_eq!( + rows.as_array().unwrap().len(), + 2, + "the phase from before the Resume stays" + ); + assert_eq!(rows[0]["commit"], "abc1234"); + assert_eq!(rows[0]["fixed"], 1); + loop_report::save(&home, &project, &rec.report).unwrap(); + let resumed = Ctx { + slot: Arc::new(Mutex::new(Some(rec))), + agent: Arc::clone(&ctx.agent), + console_dir: PathBuf::from("."), + home: home.clone(), + launch: ctx.launch.clone(), + run_id, + hooks: Arc::clone(&ctx.hooks), + limits: ctx.limits, + }; + finish(&resumed); + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + let md = + std::fs::read_to_string(project.join(format!("specs/lunch/LOOP-SUMMARY-{date}.md"))) + .unwrap(); + assert!(md.contains("Rename the helper"), "from before the Resume"); + assert!(md.contains("Outside this phase")); + assert!(md.contains("Phases built by this loop: 2.")); + assert_eq!( + loop_report::load(&home, &project, "specs/lunch"), + None, + "the project holds it now" + ); + } + + #[test] + fn a_second_report_the_same_day_gets_its_own_name() { + let taken = |name: &str| { + name == "LOOP-SUMMARY-2026-11-01.md" || name == "LOOP-SUMMARY-2026-11-01-2.md" + }; + assert_eq!( + unused_summary_name("2026-11-02", taken), + "LOOP-SUMMARY-2026-11-02.md" + ); + assert_eq!( + unused_summary_name("2026-11-01", taken), + "LOOP-SUMMARY-2026-11-01-3.md" + ); + } + + #[test] + fn send_a_test_confirms_the_saved_address_and_says_how_it_went() { + let mut s = setup(); + assert_eq!( + notify_test_confirm(&s).unwrap_err(), + "Fill in the address first" + ); + s.notify_url = "not an address".into(); + assert!(notify_test_confirm(&s).unwrap_err().contains("not valid")); + + let (url, calls) = listening_address(); + s.notify_url = url.clone(); + s.notify_param = "msg".into(); + assert!(notify_test_confirm(&s).unwrap().contains(&url)); + send_notify_test(&s).unwrap(); + let call = calls.recv_timeout(CALL_WAIT).unwrap(); + assert!(call.contains("Plan2Code%20test"), "{call}"); + + // A port nothing listens on: the reason, and never the address. + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + s.notify_url = format!("http://127.0.0.1:{port}/secret"); + let err = send_notify_test(&s).unwrap_err(); + assert!(err.starts_with("The test was not sent: "), "{err}"); + assert!(!err.contains("secret"), "{err}"); + } + + #[test] + fn a_finished_loop_calls_the_web_address_with_the_message() { + let (ctx, calls) = notifying_loop("finish"); + finish(&ctx); + assert_eq!( + calls.recv_timeout(CALL_WAIT).unwrap(), + "GET /hook?msg=Plan2Code%20loop%20complete%20on%20lunch%3A%20all%202%20phases%20built. HTTP/1.1" + ); + } + + #[test] + fn a_stopped_loop_calls_with_its_reason_unless_the_person_stopped_it() { + let (ctx, calls) = notifying_loop("stop"); + stop_loop( + &ctx, + StopCause::QuickCheck, + "Phase 2 stopped: the quick check failed".into(), + &["resume"], + ); + let call = calls.recv_timeout(CALL_WAIT).unwrap(); + assert!(call.contains("loop%20stopped%20on%20lunch"), "{call}"); + assert!(call.contains("the%20quick%20check%20failed"), "{call}"); + + let (ctx, calls) = notifying_loop("question"); + stop_loop(&ctx, StopCause::Question, "x".into(), &["resume"]); + let call = calls.recv_timeout(CALL_WAIT).unwrap(); + assert!(call.contains("has%20a%20question%20for%20you"), "{call}"); + + let (ctx, calls) = notifying_loop("person"); + stop_loop(&ctx, StopCause::StoppedByPerson, "x".into(), &["resume"]); + assert!(calls.recv_timeout(QUIET).is_err(), "the person is there"); + } + + #[test] + fn a_question_holding_the_loop_calls_once_per_hold() { + let (ctx, calls) = notifying_loop("hold"); + observe(&ctx, None, true); + let call = calls.recv_timeout(CALL_WAIT).unwrap(); + assert!(call.contains("is%20waiting%20on%20lunch"), "{call}"); + assert!(call.contains("Phase%202"), "{call}"); + // Still the same question: no second call. Answered, then a new one: another. + observe(&ctx, None, true); + assert!(calls.recv_timeout(QUIET).is_err()); + observe(&ctx, None, false); + observe(&ctx, None, true); + assert!(calls.recv_timeout(CALL_WAIT).is_ok()); + } + + #[test] + fn a_call_that_fails_keeps_the_loop_going_and_is_remembered() { + let (ctx, _calls) = notifying_loop("fail"); + // A port nothing listens on. + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + lock(&ctx.slot).as_mut().unwrap().setup.notify_url = + format!("http://127.0.0.1:{port}/secret"); + observe(&ctx, None, true); + let start = Instant::now(); + let failure = loop { + let seen = lock(&ctx.slot).as_ref().unwrap().notify_failure.clone(); + if let Some(failure) = seen { + break failure; + } + assert!(start.elapsed() < CALL_WAIT, "the failure never came back"); + thread::sleep(Duration::from_millis(20)); + }; + assert!(!failure.contains("secret"), "{failure}"); + assert!(lock(&ctx.slot).as_ref().unwrap().waiting); + } + + #[test] + fn stop_after_this_phase_is_remembered_and_stop_now_ends_the_agent() { + let slot: LoopSlot = Arc::new(Mutex::new(None)); + assert!(request_stop_after(&slot, true).is_err()); + let agent = AgentManager::new(PathBuf::from("."), Arc::new(|_| {})); + assert!(request_stop_now(&slot, Some(&agent), |_| {}).is_err()); + *lock(&slot) = Some(record("specs/x", vec![phase(2), phase(3)])); + let event = request_stop_after(&slot, true).unwrap(); + assert!(event.stop_after_phase); + assert!(lock(&slot).as_ref().unwrap().stop_after_phase); + request_stop_now(&slot, Some(&agent), |_| {}).unwrap(); + assert!(lock(&slot).as_ref().unwrap().stop_now); + assert!(is_running(&slot)); + abandon(&slot); + assert!(!is_running(&slot)); + assert!(current_event(&slot).is_none()); + } + + #[test] + fn the_quit_check_lists_only_committed_phases() { + let slot: LoopSlot = Arc::new(Mutex::new(None)); + assert!(quit_facts(&slot).is_none()); + let mut done = phase(1); + done.status = PhaseStatus::Done; + done.commit = Some("abc1234".into()); + let mut uncommitted = phase(2); + uncommitted.status = PhaseStatus::Done; + let mut rec = record("specs/x", vec![done, uncommitted, phase(3), phase(4)]); + rec.current = 2; + *lock(&slot) = Some(rec); + assert_eq!(quit_facts(&slot), Some((3, 4, vec![1]))); + } + + #[test] + fn fix_and_finalize_start_ordinary_sessions() { + assert_eq!( + fix_prompt("specs/x"), + "/plan2code-3-implement specs/x/overview.md --web" + ); + assert!(!fix_prompt("specs/x").contains("--loop")); + assert_eq!( + finalize_prompt("specs/x"), + "/plan2code-4-finalize specs/x/overview.md --web" + ); + } +} diff --git a/plan2code-app/src-tauri/src/loop_notify.rs b/plan2code-app/src-tauri/src/loop_notify.rs new file mode 100644 index 0000000..d24f1cd --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_notify.rs @@ -0,0 +1,416 @@ +//! The Implementation Loop's notification to a web address the person chose, +//! when it needs them or ends: a plain GET with the message in the query +//! string, or a POST in the shape a chat service's webhook wants. The kind, the +//! address and the name come from `loop-setup.json` and the app names them in +//! its own Start confirm; the message is written by the loop. A failed call +//! never changes what the loop does, and its reason never repeats the address, +//! which may hold a token. + +use reqwest::{blocking::Client, header::CONTENT_TYPE, redirect::Policy, Url}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::time::Duration; + +/// How the message reaches the address. To add a service: a variant here, its +/// body in `request_for`, its words in `describe`, and its row in the setup +/// screen's `NOTIFY_KINDS` and `loop-setup.mjs`'s list. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum NotifyKind { + /// A GET with the message in a query string parameter the person names. + #[default] + Query, + /// A POST of a JSON object with the message in a field the person names. + Json, + Discord, + Slack, + Teams, + GoogleChat, +} + +impl NotifyKind { + /// Whether the person names the parameter or field that holds the message. + pub fn uses_param(self) -> bool { + matches!(self, NotifyKind::Query | NotifyKind::Json) + } +} + +pub const DEFAULT_PARAM: &str = "message"; +const MAX_URL: usize = 2000; +const MAX_PARAM: usize = 64; +const CALL_LIMIT: Duration = Duration::from_secs(10); + +/// Whether `url` is an http or https address the app may call: printable ASCII +/// (anything else percent-encoded), a host, and no user name or password. +pub fn valid_url(url: &str) -> bool { + if url.len() > MAX_URL || !url.chars().all(|c| ('!'..='~').contains(&c)) { + return false; + } + let lower = url.to_ascii_lowercase(); + let Some(rest) = lower + .strip_prefix("http://") + .or_else(|| lower.strip_prefix("https://")) + else { + return false; + }; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + !authority.is_empty() + && !authority.contains('@') + && Url::parse(url).is_ok_and(|u| u.host_str().is_some()) +} + +/// Whether `name` can stand as a query parameter's name without being encoded. +pub fn valid_param(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_PARAM + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~')) +} + +fn encode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +/// `url` with `param=message` in its query. The address's other parameters and +/// fragment stay; a parameter of the same name is replaced. +pub fn target_url(url: &str, param: &str, message: &str) -> String { + let (rest, fragment) = match url.split_once('#') { + Some((rest, fragment)) => (rest, Some(fragment)), + None => (url, None), + }; + let (base, query) = rest.split_once('?').unwrap_or((rest, "")); + let mut pairs: Vec = query + .split('&') + .filter(|pair| !pair.is_empty() && pair.split('=').next() != Some(param)) + .map(str::to_string) + .collect(); + pairs.push(format!("{param}={}", encode(message))); + let mut out = format!("{base}?{}", pairs.join("&")); + if let Some(fragment) = fragment { + out.push('#'); + out.push_str(fragment); + } + out +} + +/// Whether the setup's notification fields can be used, for an address that is set. +pub fn valid_setup(kind: NotifyKind, url: &str, param: &str) -> bool { + valid_url(url) && (!kind.uses_param() || valid_param(param)) +} + +/// Slack treats these three as its own markup in message text. +fn slack_escaped(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +/// The address to call and, for a POST, the JSON body. +pub fn request_for( + kind: NotifyKind, + url: &str, + param: &str, + message: &str, +) -> (String, Option) { + let body = match kind { + NotifyKind::Query => return (target_url(url, param, message), None), + NotifyKind::Json => json!({ param: message }), + // No mentions, whatever a spec is called: this must never ping a channel. + NotifyKind::Discord => json!({ "content": message, "allowed_mentions": { "parse": [] } }), + NotifyKind::Slack => json!({ "text": slack_escaped(message) }), + NotifyKind::GoogleChat => json!({ "text": message }), + // A Teams workflow's "when a webhook request is received" trigger. + NotifyKind::Teams => json!({ + "type": "message", + "attachments": [{ + "contentType": "application/vnd.microsoft.card.adaptive", + "contentUrl": null, + "content": { + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "type": "AdaptiveCard", + "version": "1.4", + "body": [{ "type": "TextBlock", "text": message, "wrap": true }], + }, + }], + }), + }; + (url.to_string(), Some(body)) +} + +/// The Start confirm's words for what the app will do. +pub fn describe(kind: NotifyKind, url: &str, param: &str) -> String { + match kind { + NotifyKind::Query => format!("the app calls: {url} with a message in {param}"), + NotifyKind::Json => format!("the app posts to: {url} with a message in {param}"), + NotifyKind::Discord => format!("the app posts to Discord at: {url}"), + NotifyKind::Slack => format!("the app posts to Slack at: {url}"), + NotifyKind::Teams => format!("the app posts to Microsoft Teams at: {url}"), + NotifyKind::GoogleChat => format!("the app posts to Google Chat at: {url}"), + } +} + +/// Send the message, within ten seconds. Any 2xx answer counts as sent. The +/// error is safe to show: it never holds the address. +pub fn send(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> { + let client = Client::builder() + .timeout(CALL_LIMIT) + .redirect(Policy::limited(5)) + .build() + .map_err(|_| "the app could not prepare the call".to_string())?; + let (address, body) = request_for(kind, url, param, message); + let request = match body { + None => client.get(address), + Some(body) => client + .post(address) + .header(CONTENT_TYPE, "application/json") + .body(body.to_string()), + }; + let response = request.send().map_err(|e| { + if e.is_timeout() { + "it did not answer within 10 seconds".to_string() + } else if e.is_connect() { + "the app could not connect to it".to_string() + } else { + "the call failed".to_string() + } + })?; + let status = response.status(); + if status.is_success() { + Ok(()) + } else { + Err(format!("it answered {}", status.as_u16())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::thread; + + /// Answer one request with `status` on a local port; gives back the whole request. + fn one_call(status: &'static str) -> (String, thread::JoinHandle) { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let handle = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = String::new(); + let mut buf = [0u8; 4096]; + loop { + let n = stream.read(&mut buf).unwrap(); + request.push_str(&String::from_utf8_lossy(&buf[..n])); + let Some((head, body)) = request.split_once("\r\n\r\n") else { + continue; + }; + let length = head + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length: ") + .map(str::to_string) + }) + .and_then(|l| l.parse::().ok()) + .unwrap_or(0); + if n == 0 || body.len() >= length { + break; + } + } + let answer = + format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + stream.write_all(answer.as_bytes()).unwrap(); + request + }); + (format!("http://127.0.0.1:{port}/hook?team=a"), handle) + } + + #[test] + fn only_http_and_https_addresses_with_a_host_are_valid() { + for good in [ + "http://example.com", + "https://example.com/hook?x=1#top", + "HTTPS://EXAMPLE.COM/a%20b", + "http://127.0.0.1:8080/", + ] { + assert!(valid_url(good), "{good}"); + } + for bad in [ + "", + "example.com", + "ftp://example.com", + "file:///c:/x", + "javascript:alert(1)", + "https:/example.com", + "https://", + "https://?x=1", + "https://exa mple.com", + "https://example.com/é", + "https://me:secret@example.com/", + "https://example.com/\nx", + ] { + assert!(!valid_url(bad), "{bad}"); + } + assert!(!valid_url(&format!( + "https://e.com/{}", + "x".repeat(MAX_URL) + ))); + } + + #[test] + fn a_parameter_name_needs_no_encoding() { + for good in ["message", "msg_1", "a-b.c~d", "M"] { + assert!(valid_param(good), "{good}"); + } + for bad in ["", "a b", "a=b", "a&b", "a?b", "a#b", "a%20b", "é", "[x]"] { + assert!(!valid_param(bad), "{bad}"); + } + assert!(!valid_param(&"x".repeat(MAX_PARAM + 1))); + } + + #[test] + fn the_message_lands_encoded_in_the_query_beside_what_is_there() { + assert_eq!( + target_url("https://e.com/hook", "message", "a b&c=d/é"), + "https://e.com/hook?message=a%20b%26c%3Dd%2F%C3%A9" + ); + assert_eq!( + target_url("https://e.com/hook?t=1&x=2#top", "msg", "hi"), + "https://e.com/hook?t=1&x=2&msg=hi#top" + ); + assert_eq!( + target_url("https://e.com/?msg=old&t=1", "msg", "new"), + "https://e.com/?t=1&msg=new", + "a parameter of the same name is replaced" + ); + } + + #[test] + fn the_call_is_a_get_with_the_message_in_the_query() { + let (url, server) = one_call("200 OK"); + assert_eq!(send(NotifyKind::Query, &url, "message", "all done"), Ok(())); + assert_eq!( + server.join().unwrap().lines().next().unwrap(), + "GET /hook?team=a&message=all%20done HTTP/1.1" + ); + } + + #[test] + fn a_webhook_gets_a_post_of_json_at_the_address_as_given() { + let (url, server) = one_call("204 No Content"); + assert_eq!( + send(NotifyKind::Discord, &url, "ignored", "all done"), + Ok(()) + ); + let request = server.join().unwrap(); + assert_eq!( + request.lines().next().unwrap(), + "POST /hook?team=a HTTP/1.1" + ); + assert!(request + .to_ascii_lowercase() + .contains("content-type: application/json")); + let (_, body) = request.split_once("\r\n\r\n").unwrap(); + let body: Value = serde_json::from_str(body).unwrap(); + assert_eq!(body["content"], "all done"); + } + + #[test] + fn each_service_gets_the_shape_it_wants() { + let body = |kind, message| { + request_for(kind, "https://e.com/x", "note", message) + .1 + .unwrap() + }; + assert_eq!(body(NotifyKind::Json, "hi"), json!({ "note": "hi" })); + assert_eq!( + body(NotifyKind::Discord, "@everyone hi"), + json!({ "content": "@everyone hi", "allowed_mentions": { "parse": [] } }), + "a mention in a spec's name pings nobody" + ); + assert_eq!( + body(NotifyKind::Slack, "a & c"), + json!({ "text": "a <b> & c" }) + ); + assert_eq!(body(NotifyKind::GoogleChat, "hi"), json!({ "text": "hi" })); + let teams = body(NotifyKind::Teams, "hi"); + assert_eq!(teams["type"], "message"); + let attachment = &teams["attachments"][0]; + assert_eq!( + attachment["contentType"], + "application/vnd.microsoft.card.adaptive" + ); + assert_eq!(attachment["content"]["type"], "AdaptiveCard"); + assert_eq!(attachment["content"]["body"][0]["text"], "hi"); + assert_eq!( + request_for(NotifyKind::Slack, "https://e.com/x", "n", "m").0, + "https://e.com/x" + ); + assert_eq!( + request_for(NotifyKind::Query, "https://e.com/x", "n", "m"), + ("https://e.com/x?n=m".to_string(), None) + ); + } + + #[test] + fn a_kind_reads_by_its_saved_name_and_only_some_need_a_name() { + for (name, kind) in [ + ("query", NotifyKind::Query), + ("json", NotifyKind::Json), + ("discord", NotifyKind::Discord), + ("slack", NotifyKind::Slack), + ("teams", NotifyKind::Teams), + ("google-chat", NotifyKind::GoogleChat), + ] { + assert_eq!( + serde_json::from_value::(json!(name)).unwrap(), + kind + ); + } + assert!(valid_setup(NotifyKind::Slack, "https://e.com/", "a b")); + assert!(!valid_setup(NotifyKind::Query, "https://e.com/", "a b")); + assert!(!valid_setup(NotifyKind::Json, "https://e.com/", "")); + assert!(!valid_setup(NotifyKind::Slack, "e.com", "message")); + } + + // Needs the internet, so only by hand: `cargo test live_https -- --ignored`. + #[test] + #[ignore] + fn live_https_reaches_a_real_certificate() { + assert_eq!( + send(NotifyKind::Query, "https://example.com/", "message", "test"), + Ok(()) + ); + } + + #[test] + fn a_failed_call_says_why_without_the_address() { + let (url, server) = one_call("503 Service Unavailable"); + assert_eq!( + send(NotifyKind::Query, &url, "message", "x"), + Err("it answered 503".to_string()) + ); + server.join().unwrap(); + + // A port nothing listens on. + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let err = send( + NotifyKind::Slack, + &format!("http://127.0.0.1:{port}/secret-token"), + "message", + "x", + ) + .unwrap_err(); + assert!(!err.contains("secret-token"), "{err}"); + } +} diff --git a/plan2code-app/src-tauri/src/loop_report.rs b/plan2code-app/src-tauri/src/loop_report.rs new file mode 100644 index 0000000..804deb7 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_report.rs @@ -0,0 +1,568 @@ +//! The Implementation Loop's report: everything the loop did on the person's +//! behalf, across stops and resumes, until every phase is built. +//! +//! While a build is under way the report lives in `loop-reports.json` in the +//! console's folder, saved after every phase, retry and stop. It cannot live in +//! the project yet: a file there would dirty the tree, and Resume needs a clean +//! one to commit each phase. When the last phase is built it is written to +//! `specs//LOOP-SUMMARY-.md` and its entry here goes away. + +use std::path::Path; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::loop_driver::{fold_key, write_atomic, Finding, Outcome}; + +pub const REPORTS_FILE: &str = "loop-reports.json"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum EntryResult { + #[default] + Passed, + Stopped, + Retried, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Assumption { + pub task: String, + pub note: String, +} + +/// One thing that happened to a phase, in the order it happened. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ReportEntry { + pub at: String, + pub phase: u32, + pub name: String, + pub result: EntryResult, + /// Why it stopped or was retried; empty for a phase that passed. + pub line: String, + pub commit: Option, + pub subject: String, + pub summary: String, + pub tests: String, + /// Whether the phase got as far as reporting; false for a crash or a stop mid-build. + pub reported: bool, + pub review_ran: bool, + pub fixed: Vec, + pub skipped: Vec, + pub left_open: Vec, + pub assumed: Vec, + pub blocked: Vec, + pub conflicts: Vec, + pub decisions: Vec, + /// Things the app noticed that did not stop the phase (leftover Suggestions). + pub warnings: Vec, + pub retries: u32, +} + +impl ReportEntry { + /// An entry's review, tasks and decisions, from the phase's report. + pub fn with_outcome(mut self, outcome: &Outcome) -> ReportEntry { + self.reported = true; + self.subject.clone_from(&outcome.subject); + self.summary.clone_from(&outcome.summary); + self.tests = match &outcome.tests { + Some(t) if !t.summary.is_empty() => t.summary.clone(), + Some(t) if t.passed => "passed".to_string(), + Some(t) if t.ran => "failed".to_string(), + _ => "not reported".to_string(), + }; + if let Some(review) = &outcome.review { + self.review_ran = review.ran; + self.fixed.clone_from(&review.fixed); + self.left_open.clone_from(&review.unfixed); + if let Some(triage) = &review.triage { + self.skipped.clone_from(&triage.skipped); + } + } + self.blocked.clone_from(&outcome.tasks.blocked); + self.conflicts.clone_from(&outcome.conflicts); + self.decisions.clone_from(&outcome.decisions); + for task in &outcome.tasks.assumed { + if !self.assumed.iter().any(|a| &a.task == task) { + self.assumed.push(Assumption { + task: task.clone(), + note: String::new(), + }); + } + } + self + } +} + +/// A phase the loop marked done whose commit failed and whose mark could not be +/// taken back: it survives an app restart, so Resume can rebuild the phase. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct MarkedNotCommitted { + pub phase: u32, + pub file: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct LoopReport { + pub spec: String, + pub started: String, + pub entries: Vec, + pub marked_not_committed: Option, +} + +impl LoopReport { + pub fn new(spec: &str, started: &str) -> LoopReport { + LoopReport { + spec: spec.to_string(), + started: started.to_string(), + entries: Vec::new(), + marked_not_committed: None, + } + } + + pub fn set_marked(&mut self, phase: u32, file: &str) { + self.marked_not_committed = Some(MarkedNotCommitted { + phase, + file: file.to_string(), + }); + } + + pub fn clear_marked(&mut self) { + self.marked_not_committed = None; + } + + /// Each phase's latest pass, by phase number. + pub fn passed(&self) -> Vec<&ReportEntry> { + let mut seen: Vec<&ReportEntry> = Vec::new(); + for entry in self + .entries + .iter() + .filter(|e| e.result == EntryResult::Passed) + { + seen.retain(|e| e.phase != entry.phase); + seen.push(entry); + } + seen.sort_by_key(|e| e.phase); + seen + } +} + +// ------------------------------------------------------------- the store + +fn key(project: &Path, spec: &str) -> String { + format!("{}|{spec}", fold_key(project)) +} + +fn read_store(home: &Path) -> Value { + std::fs::read_to_string(home.join(REPORTS_FILE)) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .filter(|store| store["schema"].as_u64() == Some(1) && store["reports"].is_object()) + .unwrap_or_else(|| json!({ "schema": 1, "reports": {} })) +} + +/// The report under way for this spec, if a build of it has not finished. +pub fn load(home: &Path, project: &Path, spec: &str) -> Option { + let store = read_store(home); + serde_json::from_value(store["reports"].get(key(project, spec))?.clone()).ok() +} + +pub fn save(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> { + let mut store = read_store(home); + store["reports"][key(project, &report.spec)] = json!(report); + write_atomic(&home.join(REPORTS_FILE), &store.to_string()) +} + +pub fn remove(home: &Path, project: &Path, spec: &str) -> Result<(), String> { + let mut store = read_store(home); + let gone = store["reports"] + .as_object_mut() + .and_then(|all| all.remove(&key(project, spec))); + if gone.is_none() { + return Ok(()); + } + write_atomic(&home.join(REPORTS_FILE), &store.to_string()) +} + +// ------------------------------------------------------ the phase file + +/// The `[?]` tasks in a phase file and their `Assumed:` notes: on the task's own +/// line or on an indented line under it. +pub fn assumptions_in(phase_text: &str) -> Vec { + let mut found: Vec = Vec::new(); + let mut open = false; + for line in phase_text.lines() { + let trimmed = line.trim_start(); + let indented = trimmed.len() < line.len(); + if let Some(rest) = trimmed.strip_prefix("- [?]") { + found.push(Assumption { + task: task_id(rest), + note: note_in(rest).unwrap_or_default(), + }); + open = true; + } else if !indented { + open = false; + } else if open { + if let (Some(last), Some(note)) = (found.last_mut(), note_in(trimmed)) { + if last.note.is_empty() { + last.note = note; + } + } + } + } + found +} + +fn note_in(text: &str) -> Option { + let (_, note) = text.split_once("Assumed:")?; + let note = note.trim().trim_end_matches("**").trim(); + (!note.is_empty()).then(|| note.to_string()) +} + +/// `2.4` from ` **Task 2.4:** Do it`; the line itself when it names no task. +fn task_id(rest: &str) -> String { + let id = rest.split_once("Task ").and_then(|(_, after)| { + let id: String = after + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + (!id.is_empty()).then(|| id.trim_end_matches('.').to_string()) + }); + id.unwrap_or_else(|| rest.trim().to_string()) +} + +// ----------------------------------------------------------- the markdown + +fn cell(text: &str) -> String { + text.replace('|', "\\|").replace(['\r', '\n'], " ") +} + +fn finding_line(f: &Finding) -> String { + let file = if f.file.is_empty() { + String::new() + } else { + format!(" (`{}`)", cell(&f.file)) + }; + format!("- {}: {}{file}", f.level.word(), cell(&f.title)) +} + +fn section(md: &mut String, title: &str, lines: &[String], none: &str) { + md.push_str(&format!("\n**{title}**\n\n")); + if lines.is_empty() { + md.push_str(none); + md.push('\n'); + } else { + md.push_str(&lines.join("\n")); + md.push('\n'); + } +} + +fn entry_markdown(md: &mut String, e: &ReportEntry) { + let word = match e.result { + EntryResult::Passed => "built", + EntryResult::Stopped => "stopped", + EntryResult::Retried => "retried", + }; + md.push_str(&format!( + "\n### Phase {}: {} ({word}, {})\n\n", + e.phase, + cell(&e.name), + e.at + )); + if !e.line.is_empty() { + md.push_str(&format!("{}\n\n", cell(&e.line))); + } + if let Some(commit) = &e.commit { + md.push_str(&format!("- Commit: `{commit}` {}\n", cell(&e.subject))); + } else if e.result == EntryResult::Passed { + md.push_str("- Commit: not committed\n"); + } + if e.retries > 0 { + md.push_str(&format!("- Retries: {}\n", e.retries)); + } + if !e.warnings.is_empty() { + let notes: Vec = e.warnings.iter().map(|w| cell(w)).collect(); + md.push_str(&format!("- Warnings: {}\n", notes.join("; "))); + } + if !e.reported { + md.push_str( + "- The agent ended before reporting, so its review and decisions are unknown.\n", + ); + } else { + md.push_str(&format!("- Summary: {}\n", cell(&e.summary))); + md.push_str(&format!("- Tests: {}\n", cell(&e.tests))); + } + if !e.blocked.is_empty() { + md.push_str(&format!("- Blocked tasks: {}\n", e.blocked.join(", "))); + } + for conflict in &e.conflicts { + md.push_str(&format!("- Spec conflict: {}\n", cell(conflict))); + } + let assumed: Vec = e + .assumed + .iter() + .map(|a| { + let note = if a.note.is_empty() { + "(no note in the phase file)" + } else { + &a.note + }; + format!("- Task {}: {}", cell(&a.task), cell(note)) + }) + .collect(); + if e.reported || !assumed.is_empty() { + section(md, "Assumptions it made", &assumed, "None."); + } + if !e.reported { + return; + } + let decisions: Vec = e + .decisions + .iter() + .map(|d| format!("- {}", cell(d))) + .collect(); + section( + md, + "Other decisions it reported", + &decisions, + "None reported.", + ); + if !e.review_ran { + md.push_str("\n**Review:** did not run.\n"); + return; + } + let fixed: Vec = e.fixed.iter().map(finding_line).collect(); + section(md, "Findings it fixed", &fixed, "None."); + let skipped: Vec = e + .skipped + .iter() + .map(|f| { + format!( + "{}: {}", + finding_line(f), + cell(f.reason.as_deref().unwrap_or("(no reason given)")) + ) + }) + .collect(); + section(md, "Findings it chose not to fix", &skipped, "None."); + let left: Vec = e.left_open.iter().map(finding_line).collect(); + section(md, "Findings left open", &left, "None."); +} + +/// The report's body: the table of phases and every entry, oldest first. +pub fn body_markdown(report: &LoopReport) -> String { + let mut md = String::from( + "Everything below comes from each phase's report, as its agent wrote it, except the \ + task marks, the quick check and the commits, which the app checked or made itself. \ + An agent can only report the decisions it noticed making.\n", + ); + let passed = report.passed(); + if !passed.is_empty() { + md.push_str( + "\n## Phases\n\n| Phase | Commit | Subject | Fixed | Not fixed | Left open | Assumed | Other decisions | Retries |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n", + ); + for e in &passed { + md.push_str(&format!( + "| Phase {}: {} | {} | {} | {} | {} | {} | {} | {} | {} |\n", + e.phase, + cell(&e.name), + e.commit.as_deref().unwrap_or("not committed"), + cell(&e.subject), + e.fixed.len(), + e.skipped.len(), + e.left_open.len(), + e.assumed.len(), + e.decisions.len(), + e.retries, + )); + } + } + md.push_str("\n## What happened, in order\n"); + if report.entries.is_empty() { + md.push_str("\nNo phase has finished or stopped yet.\n"); + } + for entry in &report.entries { + entry_markdown(&mut md, entry); + } + md +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::FixLevel; + + fn finding(title: &str, reason: Option<&str>) -> Finding { + Finding { + level: FixLevel::Warning, + title: title.into(), + file: "src/y.js".into(), + reason: reason.map(str::to_string), + } + } + + fn entry(phase: u32, result: EntryResult) -> ReportEntry { + ReportEntry { + at: "2026-11-01 10:00".into(), + phase, + name: format!("P{phase}"), + result, + ..ReportEntry::default() + } + } + + #[test] + fn the_store_keeps_a_report_per_project_and_spec_until_it_is_removed() { + let home = std::env::temp_dir().join(format!("plan2code-report-{}", std::process::id())); + std::fs::create_dir_all(&home).unwrap(); + let (a, b) = (Path::new("C:/one"), Path::new("C:/two")); + assert_eq!(load(&home, a, "specs/x"), None); + let mut report = LoopReport::new("specs/x", "2026-11-01 10:00"); + report.entries.push(entry(1, EntryResult::Passed)); + save(&home, a, &report).unwrap(); + save(&home, b, &LoopReport::new("specs/x", "later")).unwrap(); + assert_eq!(load(&home, a, "specs/x").unwrap(), report); + assert_eq!(load(&home, a, "specs/other"), None); + remove(&home, a, "specs/x").unwrap(); + assert_eq!(load(&home, a, "specs/x"), None); + assert_eq!(load(&home, b, "specs/x").unwrap().started, "later"); + remove(&home, a, "specs/x").unwrap(); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn a_broken_store_reads_as_empty_and_is_replaced() { + let home = + std::env::temp_dir().join(format!("plan2code-report-bad-{}", std::process::id())); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write(home.join(REPORTS_FILE), "not json").unwrap(); + assert_eq!(load(&home, Path::new("C:/one"), "specs/x"), None); + let report = LoopReport::new("specs/x", "now"); + save(&home, Path::new("C:/one"), &report).unwrap(); + assert_eq!(load(&home, Path::new("C:/one"), "specs/x").unwrap(), report); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn assumptions_come_from_the_task_line_or_the_line_under_it() { + let text = "# Phase 2\n\n- [x] **Task 2.1:** Done\n - Assumed: not this one\n- [?] **Task 2.2:** Pick a store\n - Test: through the route\n - Assumed: SQLite, since the spec names no store\n- [?] **Task 2.3:** Pick a port. Assumed: 8080\n- [?] **Task 2.4:** No note\n\n## Notes\n\nAssumed: not under a task\n"; + assert_eq!( + assumptions_in(text), + vec![ + Assumption { + task: "2.2".into(), + note: "SQLite, since the spec names no store".into() + }, + Assumption { + task: "2.3".into(), + note: "8080".into() + }, + Assumption { + task: "2.4".into(), + note: String::new() + }, + ] + ); + } + + #[test] + fn the_report_lists_every_kind_of_decision_with_its_reason() { + let mut report = LoopReport::new("specs/x", "2026-11-01 10:00"); + let mut built = entry(2, EntryResult::Passed); + built.reported = true; + built.review_ran = true; + built.commit = Some("a1b2c3d".into()); + built.subject = "Add | the driver".into(); + built.summary = "Built it".into(); + built.tests = "14 pass".into(); + built.fixed.push(finding("Null check", None)); + built + .skipped + .push(finding("Rename", Some("Outside this phase"))); + built.left_open.push(finding("Name the timer", None)); + built.assumed.push(Assumption { + task: "2.2".into(), + note: "SQLite".into(), + }); + built.assumed.push(Assumption { + task: "2.3".into(), + note: String::new(), + }); + built + .decisions + .push("Kept the old route for callers".into()); + built.retries = 1; + report.entries.push(built); + let md = body_markdown(&report); + assert!( + md.contains("| Phase 2: P2 | a1b2c3d | Add \\| the driver | 1 | 1 | 1 | 2 | 1 | 1 |") + ); + assert!(md.contains("- warning: Null check (`src/y.js`)")); + assert!(md.contains("- warning: Rename (`src/y.js`): Outside this phase")); + assert!(md.contains("- warning: Name the timer (`src/y.js`)")); + assert!(md.contains("- Task 2.2: SQLite")); + assert!(md.contains("- Task 2.3: (no note in the phase file)")); + assert!(md.contains("- Kept the old route for callers")); + assert!(md.contains("- Tests: 14 pass")); + assert!(md.contains("- Retries: 1")); + assert!(!md.contains('\u{2014}')); + } + + #[test] + fn a_phase_that_never_reported_says_so_and_keeps_what_the_file_shows() { + let mut report = LoopReport::new("specs/x", "2026-11-01 10:00"); + let mut stopped = entry(3, EntryResult::Stopped); + stopped.line = "Phase 3 stopped: the agent crashed".into(); + stopped.assumed.push(Assumption { + task: "3.1".into(), + note: "Port 8080".into(), + }); + report.entries.push(stopped); + let md = body_markdown(&report); + assert!(md.contains("Phase 3 stopped: the agent crashed")); + assert!(md.contains("its review and decisions are unknown")); + assert!(md.contains("- Task 3.1: Port 8080")); + assert!(!md.contains("Findings it fixed")); + } + + #[test] + fn a_later_pass_is_the_phases_row_and_earlier_attempts_stay_in_the_story() { + let mut report = LoopReport::new("specs/x", "2026-11-01 10:00"); + report.entries.push(entry(1, EntryResult::Stopped)); + let mut first = entry(1, EntryResult::Passed); + first.subject = "first".into(); + report.entries.push(first); + report.entries.push(entry(2, EntryResult::Passed)); + let mut again = entry(1, EntryResult::Passed); + again.subject = "again".into(); + report.entries.push(again); + let passed = report.passed(); + assert_eq!(passed.len(), 2); + assert_eq!(passed[0].phase, 1); + assert_eq!(passed[0].subject, "again"); + assert_eq!(passed[1].phase, 2); + assert_eq!(body_markdown(&report).matches("### Phase 1").count(), 3); + } + + #[test] + fn warnings_show_under_the_phase_and_an_old_store_loads_without_them() { + let mut e = entry(2, EntryResult::Passed); + e.warnings = vec!["2 Suggestions left unfixed".into(), "a | b".into()]; + let mut report = LoopReport::new("specs/x", "2026-11-01 10:00"); + report.entries.push(e); + let md = body_markdown(&report); + assert!( + md.contains("- Warnings: 2 Suggestions left unfixed; a \\| b"), + "{md}" + ); + let mut report = LoopReport::new("specs/x", "2026-11-01 10:00"); + report.entries.push(entry(3, EntryResult::Passed)); + assert!(!body_markdown(&report).contains("Warnings")); + let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap(); + assert!(old.warnings.is_empty()); + } +} diff --git a/plan2code-app/src-tauri/src/loop_tools.rs b/plan2code-app/src-tauri/src/loop_tools.rs new file mode 100644 index 0000000..9c2c33e --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_tools.rs @@ -0,0 +1,673 @@ +//! The commands the Implementation Loop runs on its own: the spec scripts, git, +//! the console's `post` and the person's quick check. Each call has a time +//! limit and keeps its output. No shell runs here except the quick check, whose +//! text comes only from `loop-setup.json` (never from a page message). + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +use crate::console_supervisor::find_console_dir; + +/// What a finished (or stopped) call left behind. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ToolRun { + pub ok: bool, + pub code: Option, + pub output: String, +} + +/// Output kept per call: the tail, which is where a failure says why. +const OUTPUT_LIMIT: usize = 200 * 1024; + +/// The limit for node and git calls. +pub const QUICK_LIMIT: Duration = Duration::from_secs(60); +/// The limit for the person's quick check. +pub const CHECK_LIMIT: Duration = Duration::from_secs(15 * 60); + +const POLL: Duration = Duration::from_millis(25); + +/// Appends `bytes`, dropping from the front when over `limit`. +fn append_tail(buf: &mut Vec, bytes: &[u8], limit: usize) { + buf.extend_from_slice(bytes); + if buf.len() > limit { + let excess = buf.len() - limit; + buf.drain(..excess); + } +} + +fn pump( + mut source: R, + sink: Arc>>, +) -> thread::JoinHandle<()> { + thread::spawn(move || { + let mut chunk = [0u8; 8192]; + loop { + match source.read(&mut chunk) { + Ok(0) | Err(_) => break, + Ok(n) => { + if let Ok(mut buf) = sink.lock() { + append_tail(&mut buf, &chunk[..n], OUTPUT_LIMIT); + } + } + } + } + }) +} + +/// Run `cmd` to its end or `limit`, with `stdin` written when given. Stdout and +/// stderr share one kept `output`. The child is killed when the limit passes. +fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun { + run_limited_with(cmd, stdin, limit, true) +} + +/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read +/// from stdout must not be mixed with a warning git printed beside it. +fn run_limited_with( + mut cmd: Command, + stdin: Option<&str>, + limit: Duration, + keep_stderr: bool, +) -> ToolRun { + cmd.env("PATH", crate::node_check::resolved_path()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW + } + cmd.stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(if keep_stderr { + Stdio::piped() + } else { + Stdio::null() + }); + let mut child = match cmd.spawn() { + Ok(child) => child, + Err(e) => { + return ToolRun { + ok: false, + code: None, + output: format!("could not start: {e}"), + } + } + }; + let sink = Arc::new(Mutex::new(Vec::new())); + let readers = [ + child.stdout.take().map(|s| pump(s, Arc::clone(&sink))), + child.stderr.take().map(|s| pump(s, Arc::clone(&sink))), + ]; + if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) { + // A child that exits before reading closes the pipe: not an error here. + let _ = pipe.write_all(text.as_bytes()); + } + let pid = child.id(); + let started = Instant::now(); + let mut timed_out = false; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) => { + if started.elapsed() >= limit { + timed_out = true; + kill_tree(pid); + let _ = child.kill(); + let _ = child.wait(); + break None; + } + thread::sleep(POLL); + } + Err(_) => break None, + } + }; + // A descendant that outlives the child can keep the pipes open: wait a + // short grace for the readers, then leave them behind. + let grace = Instant::now() + Duration::from_secs(3); + for reader in readers.into_iter().flatten() { + while !reader.is_finished() && Instant::now() < grace { + thread::sleep(POLL); + } + if reader.is_finished() { + let _ = reader.join(); + } + } + let mut output = sink + .lock() + .map(|buf| String::from_utf8_lossy(&buf).into_owned()) + .unwrap_or_default(); + if timed_out { + if !output.is_empty() && !output.ends_with('\n') { + output.push('\n'); + } + output.push_str(&format!("(stopped after {})", describe_limit(limit))); + } + ToolRun { + ok: status.is_some_and(|s| s.success()), + code: status.and_then(|s| s.code()), + output, + } +} + +/// "1 minute", "15 minutes", "2 seconds". +fn describe_limit(limit: Duration) -> String { + let secs = limit.as_secs(); + let (n, unit) = if secs >= 60 { + (secs / 60, "minute") + } else { + (secs.max(1), "second") + }; + format!("{n} {unit}{}", if n == 1 { "" } else { "s" }) +} + +/// End a call's whole process tree, not just the program it started. +fn kill_tree(pid: u32) { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + let _ = Command::new("taskkill") + .args(["/PID", &pid.to_string(), "/T", "/F"]) + .creation_flags(0x08000000) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + #[cfg(not(windows))] + { + let _ = Command::new("pkill") + .args(["-KILL", "-P", &pid.to_string()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } +} + +fn node_script(script: &Path, project: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new("node"); + cmd.arg(script).args(args).current_dir(project); + cmd +} + +fn git(project: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(project); + cmd +} + +/// A skill script (`specs.mjs`, `commit-msg.mjs`): beside the console's skill +/// first (`/../../scripts/`), then the Implement skills' own. +pub fn skill_script(name: &str) -> Option { + let mut candidates = Vec::new(); + // Tests run the repository's own scripts, so they need no installed skill + // (CI has none) and cannot drift from the source. + #[cfg(test)] + candidates.push( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../src/skill-scripts") + .join(name), + ); + if let Ok(console) = find_console_dir() { + if let Some(skill) = console.parent().and_then(Path::parent) { + candidates.push(skill.join("scripts").join(name)); + } + } + if let Some(home) = std::env::home_dir() { + let skills = home.join(".agents").join("skills"); + for skill in ["plan2code-3-implement", "plan2code-3-implement-review"] { + candidates.push(skills.join(skill).join("scripts").join(name)); + } + } + candidates.into_iter().find(|path| path.is_file()) +} + +fn script_or_err(name: &str) -> Result { + skill_script(name).ok_or_else(|| format!("the Plan2Code skill script {name} is not installed")) +} + +/// `specs.mjs status `, parsed. +pub fn specs_status(project: &Path, spec: &str) -> Result { + let script = script_or_err("specs.mjs")?; + let run = run_limited( + node_script(&script, project, &["status", spec]), + None, + QUICK_LIMIT, + ); + parse_json_object(&run) +} + +/// `specs.mjs mark --phase N --to done`. +pub fn specs_mark_done(project: &Path, spec: &str, phase: u32) -> ToolRun { + specs_mark(project, spec, phase, "done") +} + +/// `specs.mjs mark --phase N --to ` (`in-progress` reopens a phase). +pub fn specs_mark(project: &Path, spec: &str, phase: u32, to: &str) -> ToolRun { + let script = match script_or_err("specs.mjs") { + Ok(script) => script, + Err(output) => { + return ToolRun { + ok: false, + code: None, + output, + } + } + }; + let phase = phase.to_string(); + run_limited( + node_script( + &script, + project, + &["mark", spec, "--phase", &phase, "--to", to], + ), + None, + QUICK_LIMIT, + ) +} + +/// `commit-msg.mjs --subject --add-all`: the checked message. The +/// script's own subject checks are the only ones. +pub fn commit_message(project: &Path, subject: &str) -> Result { + let script = script_or_err("commit-msg.mjs")?; + let run = run_limited( + node_script(&script, project, &["--subject", subject, "--add-all"]), + None, + QUICK_LIMIT, + ); + parse_commit_msg(&run.output) +} + +/// What `commit-msg.mjs` printed, read without a shell: its `message` when +/// `ok`, otherwise its error, otherwise whatever it printed. +fn parse_commit_msg(stdout: &str) -> Result { + let run = ToolRun { + ok: true, + code: Some(0), + output: stdout.to_string(), + }; + let value = parse_json_object(&run).map_err(|_| stdout.trim().to_string())?; + if value["ok"].as_bool() == Some(true) { + if let Some(message) = value["message"].as_str() { + return Ok(message.to_string()); + } + } + // `error` is a machine code; `message` is the human text. + Err(value["message"] + .as_str() + .or_else(|| value["error"].as_str()) + .map(str::to_string) + .unwrap_or_else(|| stdout.trim().to_string())) +} + +pub fn git_add_all(project: &Path) -> ToolRun { + run_limited(git(project, &["add", "-A"]), None, QUICK_LIMIT) +} + +/// `git commit -F -` with the message on stdin: no shell, nothing quoted. +pub fn git_commit(project: &Path, message: &str) -> ToolRun { + git_commit_with(project, message, QUICK_LIMIT) +} + +/// `git_commit` with its own time limit: a slow hook is not killed at the +/// limit of the quick calls. +pub fn git_commit_with(project: &Path, message: &str, limit: Duration) -> ToolRun { + run_limited(git(project, &["commit", "-F", "-"]), Some(message), limit) +} + +/// `git add -- `: stage exactly these files. A path git ignores (a +/// `specs/` folder in `.gitignore`) is left out, as `git add -A` leaves it out, +/// not refused. +pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun { + let wanted: Vec<&Path> = paths + .iter() + .copied() + .filter(|path| { + let mut cmd = git(project, &["check-ignore", "-q", "--"]); + cmd.arg(path); + !run_limited(cmd, None, QUICK_LIMIT).ok + }) + .collect(); + if wanted.is_empty() { + return ToolRun { + ok: true, + code: Some(0), + output: String::new(), + }; + } + let mut cmd = git(project, &["add", "--"]); + cmd.args(wanted); + run_limited(cmd, None, QUICK_LIMIT) +} + +/// The names of the staged files, as `git diff --cached --name-only -z` prints +/// them: NUL-separated, so no path is quoted. +pub fn git_staged(project: &Path) -> Result, String> { + let run = run_limited_with( + git(project, &["diff", "--cached", "--name-only", "-z"]), + None, + QUICK_LIMIT, + false, + ); + if !run.ok { + return Err(run.output.trim().to_string()); + } + Ok(split_nul(&run.output)) +} + +fn split_nul(text: &str) -> Vec { + text.split('\0') + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect() +} + +/// The repository's top folder: staged names are relative to it, not to +/// `project`, which may be a subfolder. +pub fn git_toplevel(project: &Path) -> Option { + let run = run_limited_with( + git(project, &["rev-parse", "--show-toplevel"]), + None, + QUICK_LIMIT, + false, + ); + let top = run.output.trim(); + (run.ok && !top.is_empty()).then(|| PathBuf::from(top)) +} + +/// Whether `HEAD` names a commit (false in a repository with no commit yet). +fn git_has_head(project: &Path) -> bool { + run_limited( + git(project, &["rev-parse", "--verify", "-q", "HEAD"]), + None, + QUICK_LIMIT, + ) + .ok +} + +/// Take everything out of the index again; the files keep their contents. +pub fn git_unstage_all(project: &Path) -> ToolRun { + if git_has_head(project) { + run_limited(git(project, &["reset", "-q"]), None, QUICK_LIMIT) + } else { + // Before a first commit there is no HEAD to reset to. + run_limited( + git(project, &["rm", "-r", "--cached", "-q", ":/"]), + None, + QUICK_LIMIT, + ) + } +} + +/// The branch `HEAD` is on: `Ok(None)` for a detached HEAD, an error when +/// `project` is not a git repository. +pub fn git_branch(project: &Path) -> Result, String> { + let run = run_limited( + git(project, &["symbolic-ref", "--short", "-q", "HEAD"]), + None, + QUICK_LIMIT, + ); + let name = run.output.trim(); + if run.ok && !name.is_empty() { + return Ok(Some(name.to_string())); + } + // `symbolic-ref -q` exits 1 and prints nothing for a detached HEAD; any + // other failure (not a repository, git missing) prints something. + if run.code == Some(1) && name.is_empty() { + return Ok(None); + } + Err(name.to_string()) +} + +/// Whether `hash` names a commit in this repository. +pub fn git_commit_exists(project: &Path, hash: &str) -> bool { + if hash.is_empty() || !hash.chars().all(|c| c.is_ascii_hexdigit()) { + return false; + } + let target = format!("{hash}^{{commit}}"); + run_limited( + git(project, &["cat-file", "-e", &target]), + None, + QUICK_LIMIT, + ) + .ok +} + +pub fn git_head_short(project: &Path) -> Option { + let run = run_limited( + git(project, &["rev-parse", "--short", "HEAD"]), + None, + QUICK_LIMIT, + ); + let hash = run.output.trim(); + (run.ok && !hash.is_empty()).then(|| hash.to_string()) +} + +/// The full hash of `HEAD`, when there is a commit. +pub fn git_head_full(project: &Path) -> Option { + let run = run_limited(git(project, &["rev-parse", "HEAD"]), None, QUICK_LIMIT); + let hash = run.output.trim(); + (run.ok && !hash.is_empty()).then(|| hash.to_string()) +} + +/// The paths `git status --porcelain=v1 -z` lists (renames name the new path). +pub fn git_status_porcelain(project: &Path) -> Result, String> { + let run = run_limited_with( + git(project, &["status", "--porcelain=v1", "-z"]), + None, + QUICK_LIMIT, + false, + ); + if !run.ok { + return Err(run.output.trim().to_string()); + } + Ok(parse_porcelain(&run.output)) +} + +/// Read `git status --porcelain=v1 -z`: NUL-separated records of `XY path`, no +/// quoting. A rename or copy record is followed by one more field, the old +/// path, which is skipped (the new path is the one listed). +pub fn parse_porcelain(text: &str) -> Vec { + let mut paths = Vec::new(); + let mut fields = text.split('\0'); + while let Some(record) = fields.next() { + let mut chars = record.chars(); + let (Some(x), Some(y), Some(' ')) = (chars.next(), chars.next(), chars.next()) else { + continue; + }; + let Some(path) = record.get(x.len_utf8() + y.len_utf8() + 1..) else { + continue; + }; + if path.is_empty() { + continue; + } + if matches!(x, 'R' | 'C') || matches!(y, 'R' | 'C') { + fields.next(); + } + paths.push(path.to_string()); + } + paths +} + +/// `node console.mjs post --session --file -` with `patch` on stdin. +pub fn console_post(console_dir: &Path, sid: &str, patch: &serde_json::Value) -> ToolRun { + let mut cmd = Command::new("node"); + cmd.arg(console_dir.join("console.mjs")) + .args(["post", "--session", sid, "--file", "-"]); + run_limited(cmd, Some(&patch.to_string()), QUICK_LIMIT) +} + +/// `node console.mjs open --resume --no-open --workflow `: the +/// console holding a session again after it went away, without a browser. +pub fn console_resume(console_dir: &Path, sid: &str, workflow: &str) -> ToolRun { + let mut cmd = Command::new("node"); + cmd.arg(console_dir.join("console.mjs")).args([ + "open", + "--resume", + sid, + "--no-open", + "--workflow", + workflow, + ]); + run_limited(cmd, None, QUICK_LIMIT) +} + +/// The person's quick check through the platform shell, in `project`. +pub fn quick_check(project: &Path, command: &str, limit: Duration) -> ToolRun { + let mut cmd; + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd = Command::new("cmd"); + // Raw, so a quoted argument reaches cmd.exe as typed (the usual + // argument quoting would turn each quote into a backslash-quote). + cmd.arg("/C").raw_arg(command); + } + #[cfg(not(windows))] + { + cmd = Command::new("sh"); + cmd.args(["-c", command]); + } + cmd.current_dir(project); + run_limited(cmd, None, limit) +} + +fn parse_json_object(run: &ToolRun) -> Result { + let text = run.output.trim(); + // Stderr shares the output: take the first line that starts the object. + let start = text.find('{').unwrap_or(0); + // Only the first value counts: stderr lines may trail the object. + let first = serde_json::Deserializer::from_str(&text[start..]) + .into_iter::() + .next(); + match first { + Some(Ok(value)) if value.is_object() => Ok(value), + _ => Err(if text.is_empty() { + "the tool printed nothing".to_string() + } else { + text.to_string() + }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() { + let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#; + assert_eq!(parse_commit_msg(ok).unwrap(), "Add it\n\nAI Assisted"); + // Stderr noise before the object does not matter. + let noisy = format!("warning: something\n{ok}\n"); + assert_eq!(parse_commit_msg(&noisy).unwrap(), "Add it\n\nAI Assisted"); + assert_eq!( + parse_commit_msg(r#"{"ok":false,"error":"subject too long"}"#).unwrap_err(), + "subject too long" + ); + assert_eq!( + parse_commit_msg(r#"{"ok":false,"message":"no subject"}"#).unwrap_err(), + "no subject" + ); + assert_eq!( + parse_commit_msg("not json at all\n").unwrap_err(), + "not json at all" + ); + assert!(parse_commit_msg("").is_err()); + } + + #[test] + fn a_refusal_as_the_script_really_prints_it_reads_as_its_message() { + let real = "{\n \"ok\": false,\n \"error\": \"unsafe-subject\",\n \"message\": \"The subject has a double quote.\",\n \"next\": \"Rephrase.\"\n}\nerror: The subject has a double quote.\nnext: Rephrase.\n"; + assert_eq!( + parse_commit_msg(real).unwrap_err(), + "The subject has a double quote." + ); + // ok without a message is still an error, never an empty commit. + assert!(parse_commit_msg(r#"{"ok":true}"#).is_err()); + } + + #[test] + fn the_kept_output_is_the_tail() { + let mut buf = Vec::new(); + append_tail(&mut buf, b"0123456789", 6); + append_tail(&mut buf, b"AB", 6); + assert_eq!(buf, b"6789AB"); + } + + #[test] + fn porcelain_lists_paths_and_the_new_name_of_a_rename() { + let text = " M src/a.rs\0?? new file.txt\0R new.rs\0old.rs\0A \"quoted\".txt\0"; + assert_eq!( + parse_porcelain(text), + vec!["src/a.rs", "new file.txt", "new.rs", "\"quoted\".txt"] + ); + assert!(parse_porcelain("").is_empty()); + } + + #[test] + fn a_renames_old_path_is_never_read_as_a_record() { + // The old path could look like a record; it is skipped by position. + let text = "R new.rs\0 M fake.rs\0 M real.rs\0"; + assert_eq!(parse_porcelain(text), vec!["new.rs", "real.rs"]); + // A work-tree rename (intent-to-add) carries the old path too. + assert_eq!(parse_porcelain(" R new.rs\0 M fake.rs\0"), vec!["new.rs"]); + } + + #[test] + fn staged_names_are_split_on_nul() { + assert_eq!( + split_nul("a b.txt\0dir/c.rs\0"), + vec!["a b.txt", "dir/c.rs"] + ); + assert!(split_nul("").is_empty()); + } + + #[test] + fn a_call_that_outlives_its_limit_is_stopped_and_says_so() { + #[cfg(windows)] + let cmd = { + let mut c = Command::new("ping"); + c.args(["-n", "30", "127.0.0.1"]); + c + }; + #[cfg(not(windows))] + let cmd = { + let mut c = Command::new("sleep"); + c.arg("30"); + c + }; + let run = run_limited(cmd, None, Duration::from_millis(300)); + assert!(!run.ok); + assert!(run.output.ends_with("(stopped after 1 second)")); + } + + #[test] + fn stdin_reaches_the_child_and_its_output_is_kept() { + #[cfg(windows)] + let cmd = { + let mut c = Command::new("findstr"); + c.arg("x*"); + c + }; + #[cfg(not(windows))] + let cmd = Command::new("cat"); + let run = run_limited(cmd, Some("hello loop\n"), Duration::from_secs(10)); + assert!(run.ok, "{}", run.output); + assert!(run.output.contains("hello loop")); + } + + #[test] + fn the_first_json_object_in_mixed_output_is_parsed() { + let run = ToolRun { + ok: true, + code: Some(0), + output: "warning: noise\n{\"ok\":true,\"n\":1}\n".to_string(), + }; + assert_eq!(parse_json_object(&run).unwrap()["n"], 1); + } +} diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index b207006..817ba94 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -11,9 +11,10 @@ use plan2code_app_lib::attention::{self, Badge, Signal}; use plan2code_app_lib::console_supervisor::{ app_origin, origin_of, session_on_disk, ConsoleSupervisor, }; +use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot}; use plan2code_app_lib::node_check; use plan2code_app_lib::project::{self, ProjectDir}; -use plan2code_app_lib::quit_prompt::{quit_prompt, QuitCase}; +use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase}; use plan2code_app_lib::restart_brief; use plan2code_app_lib::settings; #[cfg(windows)] @@ -49,6 +50,13 @@ struct AppState { // The app itself, once it is set up: the agent's sink clears the taskbar // through it when the agent ends. app: Arc>, + // The Implementation Loop running now, if any: in memory only, so an app + // restart ends it (NFR-5). + loop_run: LoopSlot, + // The last loop's project, spec, launch choice and confirmed quick check, + // kept after the running record is gone so Resume, Fix it by hand and + // Finalize still work. Memory only. + last_loop: Mutex>, } // The console page's last state as the taskbar shows it (attention.rs), and @@ -225,6 +233,7 @@ fn agent_for_project(state: &AppState) -> Result, String> { let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app)); let agent = Arc::new(AgentManager::new(dir, sink)); agent.set_before_fresh(before_fresh_hook(state)); + agent.set_forget_session(forget_session_hook(state)); *guard = Some(Arc::clone(&agent)); Ok(agent) } @@ -253,6 +262,19 @@ fn before_fresh_hook(state: &AppState) -> BeforeFresh { }) } +// What the loop does before a phase's fresh agent starts: forget the console +// session the window follows, so the new agent's `open` starts its own. +fn forget_session_hook(state: &AppState) -> plan2code_app_lib::agent_manager::ForgetSession { + let announce = Arc::clone(&state.announce); + Arc::new(move || { + if let Ok(guard) = announce.lock() { + if let Some(server) = guard.as_ref() { + server.forget_current(); + } + } + }) +} + fn current_agent(state: &AppState) -> Option> { state.agent.lock().ok().and_then(|guard| guard.clone()) } @@ -332,6 +354,20 @@ fn sync_agent_env(app: &tauri::AppHandle) { // the same frontend id; dropping one (as happened here when it replaced the // reattach registration) sends the frontend an "end" message that // unregisters that id for good, breaking all future sends through it. +// The window's own commands that would end or replace the loop's agent refuse +// while a loop runs, between phases too (the slot holds a record then). The +// loop's own agent starts go through `loop_driver::start_with`, not these +// commands, and `agent_input` stays open so a trust or login prompt can be +// answered. +fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> { + if loop_driver::is_running(&state.loop_run) { + return Err(format!( + "A loop is running. Stop it before you change the {what}." + )); + } + Ok(()) +} + #[tauri::command] #[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke fn agent_start( @@ -344,6 +380,7 @@ fn agent_start( cols: u16, rows: u16, ) -> Result<(), String> { + refuse_while_looping(&state, "agent")?; let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?; let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?; @@ -376,6 +413,7 @@ fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(), #[tauri::command] fn agent_restart(state: State<'_, AppState>) -> Result<(), String> { + refuse_while_looping(&state, "agent")?; current_agent(&state) .ok_or("no agent has been started")? .restart() @@ -434,7 +472,11 @@ fn confirm_quit(app: &tauri::AppHandle) { .lock() .ok() .and_then(|guard| guard.last); - let prompt = quit_prompt(last); + // A running loop has its own words, naming what is committed. + let prompt = match loop_driver::quit_facts(&app.state::().loop_run) { + Some((phase, phases, committed)) => loop_quit_prompt(phase, phases, &committed), + None => quit_prompt(last), + }; #[cfg(windows)] { if let Some(parent) = app @@ -462,12 +504,12 @@ fn confirm_quit(app: &tauri::AppHandle) { // reads Esc as "not the first button". let app = app.clone(); app.dialog() - .message(prompt.message) - .title(prompt.heading) + .message(prompt.message.clone()) + .title(prompt.heading.clone()) .kind(kind) .buttons(MessageDialogButtons::OkCancelCustom( - prompt.quit.to_string(), - prompt.stay.to_string(), + prompt.quit.clone(), + prompt.stay.clone(), )) .show({ let app = app.clone(); @@ -480,13 +522,19 @@ fn confirm_quit(app: &tauri::AppHandle) { }); } +// A running loop counts even between two phases, when no agent runs for a moment. fn agent_is_active(app: &tauri::AppHandle) -> bool { - current_agent(&app.state::()).is_some_and(|agent| agent.is_active()) + let state = app.state::(); + loop_driver::is_running(&state.loop_run) + || current_agent(&state).is_some_and(|agent| agent.is_active()) } -// Stops the agent, then the console, then exits. +// Stops the loop, the agent, then the console, then exits. The loop goes first: +// its record is dropped without a word to the page, so its watch thread never +// takes the ended agent for a crash. fn quit_app(app: &tauri::AppHandle) { let state = app.state::(); + loop_driver::abandon(&state.loop_run); if let Some(agent) = current_agent(&state) { agent.stop(); } @@ -503,10 +551,17 @@ fn quit_app(app: &tauri::AppHandle) { // person's move or needs attention while the window is not focused. An // unknown word does nothing. #[tauri::command] -fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) { - let Some(next) = Signal::from_id(&signal) else { - return; - }; +fn set_attention(app: tauri::AppHandle, signal: String) { + if let Some(next) = Signal::from_id(&signal) { + apply_signal(&app, next); + } +} + +// The dot and the flash for a state. The page's `attention` message comes here, +// and so does the loop when a question starts holding it: the dot and flash +// then do not depend on the page, which is locked while the loop drives. +fn apply_signal(app: &tauri::AppHandle, next: Signal) { + let state = app.state::(); let Some(window) = app.get_webview_window("main") else { return; }; @@ -733,6 +788,7 @@ fn pick_project_folder( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result, String> { + refuse_while_looping(&state, "project")?; let picked = app .dialog() .file() @@ -781,6 +837,7 @@ fn change_project( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result, String> { + refuse_while_looping(&state, "project")?; let picked = app .dialog() .file() @@ -844,6 +901,290 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> { Ok(()) } +// What the setup screen shows about the agent a loop would use: the running +// agent's launch choice, else what the launcher chose. +#[tauri::command] +fn loop_facts(state: State<'_, AppState>) -> LoopFacts { + let running = state + .loop_run + .lock() + .map(|guard| guard.is_some()) + .unwrap_or(false); + if let Some((agent, model, effort, mode)) = + current_agent(&state).and_then(|a| a.launch_choice()) + { + return LoopFacts { + agent: Some(agent.id().to_string()), + agent_label: Some(agent.label().to_string()), + model, + effort, + permission_mode: Some(mode.id().to_string()), + prompt_support: loop_driver::prompt_support(&agent), + running, + }; + } + let agent = state.launch.agent.as_deref().and_then(agents::find_agent); + LoopFacts { + agent: agent.as_ref().map(|a| a.id().to_string()), + agent_label: agent.as_ref().map(|a| a.label().to_string()), + model: state.launch.model.clone(), + effort: None, + permission_mode: None, + prompt_support: agent.as_ref().is_none_or(loop_driver::prompt_support), + running, + } +} + +// What the loop tells the window and the taskbar: the strip's state on every +// change, and the app's own attention when a question holds it. +fn loop_hooks(app: &tauri::AppHandle) -> Hooks { + let for_strip = app.clone(); + let for_attention = app.clone(); + Hooks { + emit: Box::new(move |event| { + let _ = for_strip.emit("loop-state", &event); + }), + attention: Box::new(move || apply_signal(&for_attention, Signal::Attention)), + } +} + +// Starts a loop on `spec`: checks, the app's own confirm, then the first phase. +// Async so the confirm's blocking dialog never waits on the main thread. The +// setup comes from `loop-setup.json`, never from the page's message. With +// `skip_confirm_if_same`, the confirm is skipped when the quick check and the +// web address are the ones the person last confirmed (Resume): a changed one is +// asked again. +async fn start_loop( + app: &tauri::AppHandle, + state: &AppState, + spec: String, + skip_confirm_if_same: bool, +) -> Result { + if loop_driver::is_running(&state.loop_run) { + return Err("A loop is already running".to_string()); + } + let project = state + .project + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .map(|p| p.dir.clone()) + .ok_or("no project folder chosen")?; + let agent = current_agent(state) + .filter(|a| a.folder() == &project) + .ok_or("Start an agent first, with permission checks off.")?; + // A stopped agent has forgotten its launch choice; the last loop kept it. + let launch = agent + .launch_choice() + .or_else(|| { + state + .last_loop + .lock() + .ok() + .and_then(|last| last.as_ref().map(|l| l.launch.clone())) + }) + .ok_or("Start an agent first, with permission checks off.")?; + // Resume (the only caller that skips the confirm) on a spec this app + // stopped: the stopped phase's uncommitted work is expected in the tree. + let resuming = skip_confirm_if_same + && state.last_loop.lock().ok().is_some_and(|last| { + last.as_ref() + .is_some_and(|l| l.project == project && l.spec == spec) + }); + let record = loop_driver::prepare( + &project, + &spec, + launch.3, + loop_driver::prompt_support(&launch.0), + resuming, + )?; + let check = record.setup.quick_check.clone(); + let notify = loop_driver::confirmed_notify(&record.setup); + // A Resume that rebuilds a phase or takes uncommitted files into its commit + // is asked again: the confirm is where the person is told. + let unchanged = skip_confirm_if_same + && record.rebuilt.is_empty() + && record.resumed_files.is_none() + && !loop_driver::commits_to_trunk(&record) + && state + .last_loop + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .is_some_and(|last| { + last.project == project + && last.spec == spec + && last.confirmed_check == check + && last.confirmed_notify == notify + }); + if !unchanged { + let go = app + .dialog() + .message(loop_driver::confirm_text(&record)) + .title("Implementation Loop") + .kind(MessageDialogKind::Info) + .buttons(MessageDialogButtons::OkCancelCustom( + "Start".to_string(), + "Cancel".to_string(), + )) + .blocking_show(); + if !go { + return Ok(false); + } + } + loop_driver::reopen_rebuilt(&record)?; + loop_driver::begin( + &state.loop_run, + agent, + record, + launch.clone(), + loop_hooks(app), + )?; + if let Ok(mut last) = state.last_loop.lock() { + *last = Some(LastLoop { + project, + spec, + launch, + confirmed_check: check, + confirmed_notify: notify, + }); + } + Ok(true) +} + +#[tauri::command] +async fn loop_start( + app: tauri::AppHandle, + state: State<'_, AppState>, + spec: String, +) -> Result { + start_loop(&app, &state, spec, false).await +} + +// Send a test: the setup screen saved first, and the address comes from +// `loop-setup.json`, never from the page's message. The app names it in its own +// confirm. Answers whether a test was sent: false when the person said no. +#[tauri::command] +async fn loop_notify_test( + app: tauri::AppHandle, + state: State<'_, AppState>, +) -> Result { + let project = state + .project + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .map(|p| p.dir.clone()) + .ok_or("no project folder chosen")?; + let setup = loop_driver::read_setup(&project)?; + let text = loop_driver::notify_test_confirm(&setup)?; + let go = app + .dialog() + .message(text) + .title("Implementation Loop") + .kind(MessageDialogKind::Info) + .buttons(MessageDialogButtons::OkCancelCustom( + "Send".to_string(), + "Cancel".to_string(), + )) + .blocking_show(); + if !go { + return Ok(false); + } + // The HTTP client blocks, and panics on an async runtime's own thread. + tauri::async_runtime::spawn_blocking(move || loop_driver::send_notify_test(&setup)) + .await + .map_err(|e| e.to_string())??; + Ok(true) +} + +// Stop after this phase: it finishes its review, mark and commit, then the +// loop stops instead of starting the next. +#[tauri::command] +fn loop_stop_after_phase( + app: tauri::AppHandle, + state: State<'_, AppState>, + on: bool, +) -> Result<(), String> { + let event = loop_driver::request_stop_after(&state.loop_run, on)?; + let _ = app.emit("loop-state", &event); + Ok(()) +} + +// Stop now: the flag is set first, then the agent (if one is running) ends at +// once. The page asked the person first ("End the agent now? This phase's +// changes stay uncommitted."); the strip says Stopping, and the driver tells +// the stop screen on its next look. +#[tauri::command] +fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { + let agent = current_agent(&state); + // The event goes out before the agent is ended (which can take a while), so + // the strip's "ended" can never be followed by an older "Stopping". + loop_driver::request_stop_now(&state.loop_run, agent.as_deref(), |event| { + let _ = app.emit("loop-state", event); + })?; + Ok(()) +} + +// What the loop is doing, for a window that just loaded or just started +// listening: the strip event, or nothing when no loop runs. +#[tauri::command] +fn loop_state(state: State<'_, AppState>) -> Option { + loop_driver::current_event(&state.loop_run) +} + +// The last loop, for the stop and finish screens' buttons. +fn last_loop(state: &AppState) -> Result { + if loop_driver::is_running(&state.loop_run) { + return Err("A loop is running".to_string()); + } + let last = state + .last_loop + .lock() + .map_err(|e| e.to_string())? + .clone() + .ok_or("No loop has run in this session")?; + let here = state + .project + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .map(|p| p.dir.clone()); + if here.as_ref() != Some(&last.project) { + return Err("The project changed since that loop".to_string()); + } + Ok(last) +} + +// Resume: start again on the same spec. The app reads the setup and the +// spec's marks afresh; the Start dialog is skipped only while the quick check +// is the one the person last confirmed. +#[tauri::command] +async fn loop_resume(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { + let last = last_loop(&state)?; + start_loop(&app, &state, last.spec, true).await.map(|_| ()) +} + +// Fix it by hand: an ordinary Implement session on the stopped phase, with no +// `--loop`, so the person talks to the agent as usual. +#[tauri::command] +fn loop_fix(state: State<'_, AppState>) -> Result<(), String> { + let last = last_loop(&state)?; + let agent = current_agent(&state).ok_or("No agent is available")?; + loop_driver::start_with(&agent, &last.launch, loop_driver::fix_prompt(&last.spec)) +} + +#[tauri::command] +fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> { + let last = last_loop(&state)?; + let agent = current_agent(&state).ok_or("No agent is available")?; + loop_driver::start_with( + &agent, + &last.launch, + loop_driver::finalize_prompt(&last.spec), + ) +} + fn main() { // Without Node 18+ the console and skills cannot run: say so and stop (FR-13). let status = node_check::check_node(); @@ -890,6 +1231,15 @@ fn main() { console_start, console_status, console_stop, + loop_start, + loop_notify_test, + loop_facts, + loop_stop_after_phase, + loop_stop_now, + loop_state, + loop_resume, + loop_fix, + loop_finalize, set_attention, clear_attention_cmd, set_taskbar_signal @@ -918,6 +1268,8 @@ fn main() { let taken = take_announced(&state, ¬ice, window_origin(&handle), session_on_disk); if taken { + // A running loop follows its phase's session from here. + loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid); let _ = handle.emit("console-page", ¬ice); } else { eprintln!( @@ -1204,6 +1556,46 @@ mod tests { ) } + fn state_with_loop(running: bool) -> AppState { + let state = state_for("project-a"); + if running { + *state.loop_run.lock().unwrap() = Some(loop_driver::RunningRecord::new( + PathBuf::from("project-a"), + "specs/x".into(), + loop_driver::LoopSetup::default(), + vec![], + )); + } + state + } + + #[test] + fn the_window_refuses_to_change_project_or_agent_while_a_loop_runs() { + let state = state_with_loop(true); + let project = refuse_while_looping(&state, "project").expect_err("a loop is running"); + assert!(project.contains("A loop is running"), "{project:?}"); + assert!(project.contains("project"), "{project:?}"); + let agent = refuse_while_looping(&state, "agent").expect_err("a loop is running"); + assert!(agent.contains("change the agent."), "{agent:?}"); + } + + #[test] + fn the_window_changes_project_and_agent_freely_with_no_loop() { + let state = state_with_loop(false); + assert!(refuse_while_looping(&state, "project").is_ok()); + assert!(refuse_while_looping(&state, "agent").is_ok()); + } + + #[test] + fn loop_state_data_is_none_with_no_loop_and_the_strip_event_with_one() { + let idle = state_with_loop(false); + assert!(loop_driver::current_event(&idle.loop_run).is_none()); + let busy = state_with_loop(true); + let event = loop_driver::current_event(&busy.loop_run).expect("a loop runs"); + assert!(event.running); + assert_eq!(event.spec_name, "x"); + } + #[test] fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() { let Some(sup) = real_console() else { return }; diff --git a/plan2code-app/src-tauri/src/quit_prompt.rs b/plan2code-app/src-tauri/src/quit_prompt.rs index e360e08..63a2ffe 100644 --- a/plan2code-app/src-tauri/src/quit_prompt.rs +++ b/plan2code-app/src-tauri/src/quit_prompt.rs @@ -2,7 +2,9 @@ //! agent is not mid-step at all but waiting on the person's answer in the web //! console, so the check reads the page's last taskbar signal (attention.rs) //! and says which case it is. Anything it cannot be sure of is the working -//! case, the safer warning. Knows nothing about Tauri; main.rs shows it. +//! case, the safer warning. While the Implementation Loop builds a phase the +//! words are the loop's own (`loop_quit_prompt`). Knows nothing about Tauri; +//! main.rs shows it. use crate::attention::Signal; @@ -16,38 +18,73 @@ pub enum QuitCase { } /// Everything the box says. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct QuitPrompt { pub case: QuitCase, - pub title: &'static str, - pub heading: &'static str, - pub message: &'static str, - pub quit: &'static str, - pub stay: &'static str, + pub title: String, + pub heading: String, + pub message: String, + pub quit: String, + pub stay: String, +} + +fn words(case: QuitCase, heading: &str, message: &str, quit: &str) -> QuitPrompt { + QuitPrompt { + case, + title: "Plan2Code".to_string(), + heading: heading.to_string(), + message: message.to_string(), + quit: quit.to_string(), + stay: "Stay".to_string(), + } } /// The prompt for the page's last signal (`None` before the page has sent one). pub fn quit_prompt(last: Option) -> QuitPrompt { match last { - Some(Signal::Ready | Signal::Plain) => QuitPrompt { - case: QuitCase::Waiting, - title: "Plan2Code", - heading: "Done for now?", - message: "Your agent is just waiting on your next answer. Quit and this session ends.", - quit: "Quit", - stay: "Stay", - }, - Some(Signal::Busy | Signal::Attention) | None => QuitPrompt { - case: QuitCase::Working, - title: "Plan2Code", - heading: "Leave while your agent is busy?", - message: "If you quit now, the agent stops mid-step. Everything it has saved so far stays put.", - quit: "Quit and stop it", - stay: "Stay", - }, + Some(Signal::Ready | Signal::Plain) => words( + QuitCase::Waiting, + "Done for now?", + "Your agent is just waiting on your next answer. Quit and this session ends.", + "Quit", + ), + Some(Signal::Busy | Signal::Attention) | None => words( + QuitCase::Working, + "Leave while your agent is busy?", + "If you quit now, the agent stops mid-step. Everything it has saved so far stays put.", + "Quit and stop it", + ), } } +/// "Phase 1", "Phases 1 and 2", "Phases 1, 2 and 3". +fn phase_list(committed: &[u32]) -> String { + let numbers: Vec = committed.iter().map(u32::to_string).collect(); + match numbers.as_slice() { + [] => String::new(), + [one] => format!("Phase {one}"), + [init @ .., last] => format!("Phases {} and {last}", init.join(", ")), + } +} + +/// The words for quitting while the Implementation Loop builds a phase. +/// `committed` lists the phase numbers already committed. +pub fn loop_quit_prompt(phase: u32, phases: u32, committed: &[u32]) -> QuitPrompt { + let done = match committed.len() { + 0 => "No phase is committed yet".to_string(), + 1 => format!("{} is committed", phase_list(committed)), + _ => format!("{} are committed", phase_list(committed)), + }; + words( + QuitCase::Working, + "Stop the loop and quit?", + &format!( + "Phase {phase} of {phases} is mid-build. {done}; this phase's changes stay uncommitted." + ), + "Quit and stop the loop", + ) +} + #[cfg(test)] mod tests { use super::*; @@ -92,11 +129,38 @@ mod tests { #[test] fn no_text_carries_an_em_dash() { - for last in [None, Some(Signal::Busy), Some(Signal::Ready)] { - let p = quit_prompt(last); - for text in [p.title, p.heading, p.message, p.quit, p.stay] { + let mut all = vec![loop_quit_prompt(2, 4, &[1]), loop_quit_prompt(1, 4, &[])]; + all.extend([None, Some(Signal::Busy), Some(Signal::Ready)].map(quit_prompt)); + for p in all { + for text in [&p.title, &p.heading, &p.message, &p.quit, &p.stay] { assert!(!text.contains('\u{2014}'), "{text}"); } } } + + #[test] + fn the_loop_wording_names_what_is_committed() { + let none = loop_quit_prompt(1, 4, &[]); + assert_eq!(none.heading, "Stop the loop and quit?"); + assert_eq!(none.title, "Plan2Code"); + assert_eq!(none.quit, "Quit and stop the loop"); + assert_eq!(none.stay, "Stay"); + assert_eq!(none.case, QuitCase::Working); + assert_eq!( + none.message, + "Phase 1 of 4 is mid-build. No phase is committed yet; this phase's changes stay uncommitted." + ); + assert_eq!( + loop_quit_prompt(2, 4, &[1]).message, + "Phase 2 of 4 is mid-build. Phase 1 is committed; this phase's changes stay uncommitted." + ); + assert_eq!( + loop_quit_prompt(3, 4, &[1, 2]).message, + "Phase 3 of 4 is mid-build. Phases 1 and 2 are committed; this phase's changes stay uncommitted." + ); + assert_eq!( + loop_quit_prompt(4, 4, &[1, 2, 3]).message, + "Phase 4 of 4 is mid-build. Phases 1, 2 and 3 are committed; this phase's changes stay uncommitted." + ); + } } diff --git a/plan2code-app/src-tauri/src/task_dialog.rs b/plan2code-app/src-tauri/src/task_dialog.rs index 7f8d8b7..0c4ed9b 100644 --- a/plan2code-app/src-tauri/src/task_dialog.rs +++ b/plan2code-app/src-tauri/src/task_dialog.rs @@ -53,11 +53,11 @@ unsafe extern "system" fn on_event( /// Quit was pressed; anything else (Stay, Esc, the close button, a failure to /// show the box) keeps the app open. pub fn ask(parent: HWND, prompt: &QuitPrompt) -> bool { - let title = wide(prompt.title); - let heading = wide(prompt.heading); - let message = wide(prompt.message); - let quit = wide(prompt.quit); - let stay = wide(prompt.stay); + let title = wide(&prompt.title); + let heading = wide(&prompt.heading); + let message = wide(&prompt.message); + let quit = wide(&prompt.quit); + let stay = wide(&prompt.stay); let buttons = [ TASKDIALOG_BUTTON { nButtonID: ID_QUIT, diff --git a/plan2code-app/src-tauri/tauri.conf.json b/plan2code-app/src-tauri/tauri.conf.json index 5be1c39..974e46b 100644 --- a/plan2code-app/src-tauri/tauri.conf.json +++ b/plan2code-app/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "Plan2Code", "version": "3.0.0", - "identifier": "com.plan2code.app", + "identifier": "com.plan2code.desktop", "build": { "frontendDist": "../ui", "beforeDevCommand": "node scripts/vendor.mjs", diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js index c86e503..5faa270 100644 --- a/plan2code-app/ui/app.js +++ b/plan2code-app/ui/app.js @@ -2,7 +2,7 @@ // agent's terminal panel docked at the bottom with a drag handle. import { mountTerminal } from './terminal.js'; -import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor } from './meter.js'; +import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle } from './meter.js'; const { invoke, Channel } = window.__TAURI__.core; @@ -20,6 +20,27 @@ const agentBypassEl = document.getElementById('agent-bypass'); const agentNoneEl = document.getElementById('agent-none'); const agentStatusEl = document.getElementById('agent-status'); const restartBtn = document.getElementById('agent-restart'); +const loopBannerEl = document.getElementById('loop-banner'); +const loopTitleEl = document.getElementById('loop-title'); +const loopDetailEl = document.getElementById('loop-detail'); +const loopPipsEl = document.getElementById('loop-pips'); +const loopHintEl = document.getElementById('loop-hint'); +const loopSpecEl = document.getElementById('loop-spec'); +const loopElapsedEl = document.getElementById('loop-elapsed'); +const loopRetriesEl = document.getElementById('loop-retries'); +const loopStopAfterBtn = document.getElementById('loop-stop-after'); +const loopStopNowBtn = document.getElementById('loop-stop-now'); +const loopErrorEl = document.getElementById('loop-error'); +const loopRetryBtn = document.getElementById('loop-retry'); +// Whether Stop after this phase is on, as the last state said; a press asks for the opposite. +let loopStopAfterOn = false; +// True while an Implementation Loop runs: New Session stays hidden meanwhile. +let loopRunning = false; +let loopStep = ''; +// Whether this loop's one-time typing note was shown; a new loop resets it. +let loopTypingNoted = false; +const LOOP_TYPING_NOTE = 'A loop is running. Typing here can derail the phase it is working on.'; +const LOOP_TYPING_NOTE_MS = 8000; const changeAgentBtn = document.getElementById('change-agent'); const changeProjectBtn = document.getElementById('change-project'); const barRowEl = document.getElementById('bar-row'); @@ -82,7 +103,10 @@ const agentActive = () => agent.state === 'running'; const terminal = await mountTerminal(document.getElementById('term'), { onInput: (data) => { - if (agentActive()) invoke('agent_input', { data }); + if (agentActive()) { + noteTypingDuringLoop(); + invoke('agent_input', { data }); + } }, onResize: (cols, rows) => { if (agentActive()) invoke('agent_resize', { cols, rows }); @@ -129,7 +153,7 @@ function applyAgentState(next, { skipReset } = {}) { // ended (New Session keeps the previous agent, model, effort and mode); // Change agent, in that menu, only once ended, when there is a real choice // to make again. - restartBtn.hidden = !(active || ended); + restartBtn.hidden = loopRunning || !(active || ended); changeAgentBtn.hidden = !ended; // Checked mode needs no marker; bypass always gets the "checks off" badge // on the agent, for exactly as long as that agent runs. @@ -171,6 +195,17 @@ function setAgentStatus(text, { error = false } = {}) { agentStatusEl.classList.toggle('is-error', error && Boolean(text)); } +// The first key typed in the terminal while a loop runs: a note beside the agent, +// once per loop, gone after a few seconds. The key itself is always delivered. +function noteTypingDuringLoop() { + if (!loopRunning || loopTypingNoted) return; + loopTypingNoted = true; + setAgentStatus(LOOP_TYPING_NOTE); + setTimeout(() => { + if (agentStatusEl.textContent === LOOP_TYPING_NOTE) setAgentStatus(''); + }, LOOP_TYPING_NOTE_MS); +} + // The agent menu's first lines: what the agent is doing and, while it runs, // which permission mode it started with. function renderAgentMenuHead(label, { active, ended, bypassActive }) { @@ -638,6 +673,8 @@ function loadFrame(url) { frameReady = false; // The page going away takes its taskbar dot with it; the new one tells its own. clearAttention(); + // And a game it had in full screen. + setGameFull(false); clearTimeout(helloTimer); helloTimer = setTimeout(onNoHello, HELLO_WAIT_MS); frame.src = url; @@ -668,6 +705,9 @@ window.addEventListener('message', (event) => { if (on === null) return; if (appState) appState.taskbarSignal = on; invoke('set_taskbar_signal', { on }).catch(() => {}); + } else if (kind === 'activities-full') { + const on = taskbarSwitch(event.data); + if (on !== null) setGameFull(on); } else if (kind === 'agent-continue') { typeContinue(); } else if (kind === 'new-session') { @@ -675,9 +715,66 @@ window.addEventListener('message', (event) => { if (!restartBtn.hidden) restartBtn.click(); } else if (kind === 'looks') { applyAccent(event.data.accent, { save: true }); + } else if (kind === 'loop-facts') { + // The setup screen asks what agent a loop would use. The answer is facts + // only; the page never sends the app any setup value. + const source = event.source; + invoke('loop_facts') + .then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*')) + .catch(() => {}); + } else if (kind === 'loop-resume' || kind === 'loop-fix' || kind === 'loop-finalize') { + // Fixed requests, no free text: the page answers with ok or the error. + const source = event.source; + const command = { 'loop-resume': 'loop_resume', 'loop-fix': 'loop_fix', 'loop-finalize': 'loop_finalize' }[kind]; + invoke(command) + .then(() => source.postMessage({ plan2code: `${kind}-result`, ok: true, error: null }, '*')) + .catch((error) => source.postMessage({ plan2code: `${kind}-result`, ok: false, error: String(error) }, '*')); + } else if (kind === 'loop-notify-test') { + // Send a test: no values at all. The app reads the saved setup itself and + // asks the person to confirm in its own dialog. + const source = event.source; + invoke('loop_notify_test') + .then((sent) => source.postMessage({ plan2code: 'loop-notify-test-result', ok: true, sent, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'loop-notify-test-result', ok: false, sent: false, error: String(error) }, '*') + ); + } else if (kind === 'loop-start') { + // Start: a spec folder name only. The app validates it, reads the saved + // setup itself and asks the person to confirm in its own dialog. + const source = event.source; + const spec = typeof event.data.spec === 'string' ? event.data.spec : ''; + invoke('loop_start', { spec }) + .then((started) => source.postMessage({ plan2code: 'loop-start-result', ok: true, started, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'loop-start-result', ok: false, error: String(error) }, '*') + ); } }); +// An Activities game in full screen: the console's frame is laid over the +// bar and the terminal (over, not instead of, so the terminal keeps its size +// and the agent sees no resize), and the window goes full screen. Off, both +// go back; the window leaves full screen only if this put it there. +let fullByGame = false; + +function setGameFull(on) { + document.body.classList.toggle('console-full', on); + const win = window.__TAURI__.window.getCurrentWindow(); + if (on) { + win + .isFullscreen() + .then((already) => { + if (already) return; + fullByGame = true; + return win.setFullscreen(true); + }) + .catch(() => {}); + } else if (fullByGame) { + fullByGame = false; + win.setFullscreen(false).catch(() => {}); + } +} + // Its "Not running... type continue" line, pressed: the keystrokes // continueKeys names, each on its own a moment after the last, so an agent // that treats one burst of input as a paste still reads the Enter as a submit. @@ -727,6 +824,8 @@ async function onNoHello() { if (frameReady || !consoleKnown || restarting) return; // A page that does not answer cannot say it is done needing the person. clearAttention(); + // The next phase's console is on its way; the poll says so instead. + if (loopRunning && loopStep === 'Starting') return; let status = null; try { status = await invoke('console_status'); @@ -794,12 +893,19 @@ async function pollConsole() { markConsoleAlive(); return; } + const action = deadConsoleAction({ loopRunning, loopStep, frameReady, reconnects, limit: RECONNECT_LIMIT }); + if (action === 'wait-for-phase') { + // Covers the old phase's page and its "Lost contact" until the new one + // says hello. Never over a question the box is already asking. + if (stateCancelEl.hidden) showState(loopDetailEl.textContent); + return; + } markConsoleDead(); - if (frameReady && reconnects < RECONNECT_LIMIT) { + if (action === 'reconnect') { reconnects += 1; showState('The console stopped. Reconnecting'); await reconnectConsole(); - } else if (!frameReady) { + } else if (action === 'no-hello') { onNoHello(); } } catch { @@ -856,6 +962,8 @@ async function restartConsole() { // not repeated here. function showAnnounced(notice) { restarting = false; + // A new page is a new start: the budget is per run of trouble, not per launch. + reconnects = 0; if (!consoleKnown) { consoleKnown = true; if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS); @@ -869,6 +977,164 @@ function showAnnounced(notice) { window.__TAURI__.event.listen('console-page', (event) => showAnnounced(event.payload)); +// "45s", "12m", "1h 12m": whole units, the largest two at most. +function formatElapsed(ms) { + const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000)); + if (total < 60) return `${total}s`; + const minutes = Math.floor(total / 60); + if (minutes < 60) return `${minutes}m`; + return `${Math.floor(minutes / 60)}h ${minutes % 60}m`; +} + +// The Implementation Loop's banner across the window, drawn from the app's +// loop-state. It lives here and not in the console page because a loop runs +// across many sessions: the page changes under it, and this does not. +let loopTimer = null; +let loopStartedAt = 0; + +function tickLoopElapsed() { + loopElapsedEl.textContent = formatElapsed(Date.now() - loopStartedAt); +} + +function setLoopTitle(title) { + window.__TAURI__.window.getCurrentWindow().setTitle(title).catch(() => {}); +} + +// The app ending the loop's last agent ended that agent's console too, so the +// page holding the stop or finish card has to be brought back, at once and +// whatever the budget says: it is the one thing the person came back to read. +async function showLoopEnd() { + reconnects = 0; + try { + const status = await invoke('console_status'); + if (status.state === 'dead') await reconnectConsole(); + } catch { + // The poll looks again on its next tick. + } +} + +// Change project and Change agent are off while a loop runs, with the reason on +// them; the app refuses them too. +function applyLoopLocks(state) { + const { locked, reason } = loopLocks(state); + for (const button of [changeProjectBtn, changeAgentBtn]) { + button.disabled = locked; + button.title = locked ? reason : ''; + } +} + +// Asks the app what the loop is doing: a reloaded window has missed every +// loop-state event so far, and one sent between the first ask and the listener +// is caught by asking again once it listens. +async function syncLoopState() { + // The reply and the loop-state event travel apart: an event that landed while + // the question was out is newer than the answer, which then is dropped. + const seen = loopEventSeq; + try { + const state = await invoke('loop_state'); + if (seen !== loopEventSeq) return; + // No loop and none drawn: nothing to redraw. One drawn that is gone: it ended. + if (state) applyLoopState(state); + else if (loopRunning) applyLoopState({ running: false }); + } catch { + // The next loop-state event tells it. + } +} + +function applyLoopState(state) { + if (!state || !state.running) { + const wasRunning = loopRunning; + loopRunning = false; + loopStep = ''; + if (wasRunning) showLoopEnd(); + clearInterval(loopTimer); + loopTimer = null; + loopBannerEl.hidden = true; + applyLoopLocks({ running: false }); + setLoopTitle(windowTitleFor(projectPathEl.textContent)); + // New Session's visibility is applyAgentState's rule alone. + applyAgentState(agent, { skipReset: true }); + return; + } + if (!loopRunning) loopTypingNoted = false; + loopRunning = true; + loopStep = state.step || ''; + restartBtn.hidden = true; + applyLoopLocks(state); + const banner = loopBanner(state); + loopBannerEl.hidden = false; + loopBannerEl.dataset.tone = banner.tone; + // Only a change of words: this is a live region, and screen readers read it out. + if (loopTitleEl.textContent !== banner.title) loopTitleEl.textContent = banner.title; + if (loopDetailEl.textContent !== banner.detail) loopDetailEl.textContent = banner.detail; + loopHintEl.textContent = banner.hint; + loopSpecEl.textContent = state.specName || ''; + loopPipsEl.replaceChildren( + ...banner.pips.map((kind, i) => { + const pip = document.createElement('span'); + pip.className = `loop-pip ${kind}`; + pip.title = `Phase ${i + 1}`; + return pip; + }) + ); + setLoopTitle(loopWindowTitle(projectPathEl.textContent, state)); + const stopLabels = loopStopLabels(state); + loopStopAfterOn = !!state.stopAfterPhase; + loopStopAfterBtn.disabled = stopLabels.afterDisabled; + loopStopAfterBtn.textContent = stopLabels.afterText; + loopStopNowBtn.disabled = stopLabels.nowDisabled; + // A good state means the last press went through. + hideLoopError(); + const retries = Number(state.retriesUsed) || 0; + loopRetriesEl.hidden = retries <= 0; + loopRetriesEl.textContent = retries === 1 ? '1 retry' : `${retries} retries`; + loopStartedAt = Number(state.startedAtMs) || Date.now(); + tickLoopElapsed(); + if (!loopTimer) loopTimer = setInterval(tickLoopElapsed, 1000); +} + +let loopEventSeq = 0; +window.__TAURI__.event + .listen('loop-state', (event) => { + loopEventSeq += 1; + applyLoopState(event.payload); + }) + .then(syncLoopState, () => {}); + +// A press that fails shows why next to the buttons, with a Retry for the same press. +let loopRetryAction = null; +function hideLoopError() { + loopErrorEl.hidden = true; + loopErrorEl.textContent = ''; + loopRetryBtn.hidden = true; + loopRetryAction = null; +} +function pressLoop(command, args) { + const press = () => + invoke(command, args).then(hideLoopError, (e) => { + loopErrorEl.textContent = `Could not do that: ${String(e && e.message ? e.message : e)}`; + loopErrorEl.hidden = false; + loopRetryBtn.hidden = false; + loopRetryAction = press; + }); + return press(); +} +loopRetryBtn.onclick = () => { + if (loopRetryAction) loopRetryAction(); +}; +loopStopAfterBtn.onclick = () => pressLoop('loop_stop_after_phase', { on: !loopStopAfterOn }); +loopStopNowBtn.onclick = () => + showState( + "End the agent now? This phase's changes stay uncommitted.", + 'Stop now', + () => { + frameReady ? hideState() : showState('No dashboard has loaded yet.'); + pressLoop('loop_stop_now'); + }, + () => (frameReady ? hideState() : showState('No dashboard has loaded yet.')), + { tired: true } + ); + // The right end of the bar: whether the console stopped answering and where // the skills stand against this app, drawn as one next step (meter.js // barNextSteps decides which, and its button), with the rest as "+N more". @@ -1081,6 +1347,8 @@ async function main() { } catch { // Nothing to reattach to is not fatal: carry on as a plain first paint. } + // A reloaded window learns of a running loop before it draws the agent. + await syncLoopState(); if (reattach && reattach.state !== 'idle') { if (state.projectDir) setProjectDir(state.projectDir); await recoverAfterReload(reattach); diff --git a/plan2code-app/ui/index.html b/plan2code-app/ui/index.html index 090f4ff..6ef1dba 100644 --- a/plan2code-app/ui/index.html +++ b/plan2code-app/ui/index.html @@ -50,6 +50,46 @@ #agent-none { color: var(--ink-3); } #agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; } #agent-status.is-error { color: #f48771; } + /* The Implementation Loop, for as long as one runs: the loudest thing in the + window on purpose. The accent says it is working; amber says it needs you. */ + #loop-banner { + --banner-color: var(--accent); --banner-bg: var(--accent-soft); --banner-line: var(--accent-line); + flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 20px; + padding: 10px 14px 10px 16px; font-size: 13px; color: var(--ink); + background: var(--banner-bg); border-bottom: 1px solid var(--banner-line); box-shadow: inset 4px 0 0 var(--banner-color); + } + #loop-banner[hidden] { display: none; } + #loop-banner[data-tone="waiting"] { --banner-color: #e5a93c; --banner-bg: #3a2b10; --banner-line: #7a5a1e; } + #loop-now { flex: 1 1 320px; min-width: 0; display: grid; gap: 3px; } + #loop-headline { display: flex; align-items: center; gap: 9px; } + #loop-dot { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--banner-color); animation: loop-pulse 1.8s ease-in-out infinite; } + #loop-banner[data-tone="waiting"] #loop-dot { animation-duration: 0.9s; } + @keyframes loop-pulse { 0%, 100% { box-shadow: 0 0 0 0 transparent; opacity: 1; } 50% { box-shadow: 0 0 0 5px color-mix(in srgb, var(--banner-color) 30%, transparent); opacity: 0.75; } } + #loop-title { margin: 0; font-size: 15px; font-weight: 700; line-height: 1.25; } + #loop-detail { margin: 0; color: var(--ink-2); overflow-wrap: anywhere; } + #loop-progress { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; margin-top: 3px; color: var(--ink-3); font-size: 12px; } + #loop-pips { display: flex; flex-wrap: wrap; gap: 3px; } + .loop-pip { width: 16px; height: 5px; border-radius: 3px; background: var(--rule-2); } + .loop-pip.done { background: var(--banner-color); } + .loop-pip.current { background: var(--banner-color); animation: loop-pip 1.8s ease-in-out infinite; } + @keyframes loop-pip { 50% { opacity: 0.4; } } + #loop-spec { color: var(--ink-2); font-weight: 600; } + #loop-elapsed { font-variant-numeric: tabular-nums; } + #loop-retries { color: #f48771; } + #loop-actions { flex: none; display: flex; flex-wrap: wrap; gap: 8px; } + #loop-actions button { + appearance: none; font: inherit; font-size: 12.5px; font-weight: 600; line-height: 1.2; + padding: 6px 12px; border-radius: 8px; cursor: pointer; + border: 1px solid var(--banner-line); background: var(--panel); color: var(--ink); + } + #loop-actions button:hover:not(:disabled) { border-color: var(--banner-color); background: var(--panel-2); } + #loop-actions button:disabled { cursor: default; opacity: 0.65; } + #loop-actions button:focus-visible { outline: 2px solid var(--banner-color); outline-offset: 2px; } + #loop-actions #loop-error { align-self: center; max-width: 320px; color: #f48771; font-size: 12.5px; overflow-wrap: anywhere; } + #loop-actions [hidden] { display: none; } + #loop-actions #loop-stop-now { color: #f48771; } + #loop-actions #loop-stop-now:hover:not(:disabled) { border-color: #f48771; } + @media (prefers-reduced-motion: reduce) { #loop-dot, .loop-pip.current { animation: none; } } #bar-grow { flex: 1; min-width: 0; } /* The one next step for the console or the skills, at the right end. */ #next-step { display: flex; align-items: center; gap: 8px; flex: none; } @@ -84,6 +124,9 @@ #workspace.dock-right { flex-direction: row; } #dashboard { flex: 1; min-height: 0; min-width: 0; position: relative; } + /* An Activities game in full screen: the console's frame over the whole + window, the bar and the terminal left as they are underneath. */ + body.console-full #console-frame { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 1000; } #console-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #1e1e1e; } #dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: #1e1e1e; text-align: center; padding: 16px; box-sizing: border-box; } #dashboard-state[hidden] { display: none; } @@ -253,6 +296,28 @@ + +
diff --git a/plan2code-app/ui/meter.js b/plan2code-app/ui/meter.js index 6d348a4..f2a9a0f 100644 --- a/plan2code-app/ui/meter.js +++ b/plan2code-app/ui/meter.js @@ -128,6 +128,83 @@ export function windowTitleFor(dir) { return name ? `Plan2Code - ${name}` : "Plan2Code"; } +/** + * The window title while a loop runs, so its state shows in the taskbar too. + */ +export function loopWindowTitle(dir, state) { + const name = lastSegment(dir); + const what = state.step === "Waiting on you" ? `Loop needs you: Phase ${state.phase}` : `Loop: Phase ${state.phase} of ${state.phases}`; + return name ? `${what} - ${name}` : what; +} + +/** + * What the loop banner says, from the app's `loop-state`: the one clear word on + * what the loop is doing right now. `tone` is "running" or "waiting", `hint` the + * line beside the phase pips and `pips` one "done", "current" or "todo" per phase + * of the spec up to the last this run builds. + */ +export function loopBanner(state) { + const { phase, phases, phaseName, step } = state; + const named = phaseName ? `Phase ${phase} of ${phases}: ${phaseName}` : `Phase ${phase} of ${phases}`; + const pips = Array.from({ length: Math.max(phases, 0) }, (_, i) => (i + 1 < phase ? "done" : i + 1 === phase ? "current" : "todo")); + const base = { tone: "running", pips, hint: "Working on its own. You can walk away." }; + if (state.stopping) { + return { ...base, title: "Stopping", detail: "The agent is ending. Nothing more will be committed.", hint: "The stop screen follows in a moment." }; + } + if (step === "Waiting on you") { + return { ...base, tone: "waiting", title: "The loop needs your answer", detail: `${named} is waiting on the question below.`, hint: "Nothing is lost while it waits." }; + } + if (state.stopAfterPhase) { + return { ...base, title: "Stopping after this phase", detail: `${named} finishes its checks and commit, then the loop stops.`, hint: "Stop now ends the agent at once." }; + } + if (step === "Starting") { + if (state.phaseRetried) return { ...base, title: `Retrying Phase ${phase}`, detail: `The agent crashed or went quiet, so a fresh one is picking up ${named}.` }; + if (state.previousPhase) { + const how = state.previousCommitted ? "done and committed" : "done"; + return { ...base, title: `Phase ${state.previousPhase} ${how}`, detail: `Opening a fresh agent for ${named}.` }; + } + return { ...base, title: "Starting the loop", detail: `Opening a fresh agent for ${named}.` }; + } + return { ...base, title: "Implementation loop running", detail: step ? `${named} \u00b7 ${step}` : named }; +} + +/** + * The two stop buttons from the app's `loop-state`: "Stop after this phase" is + * a toggle (its label says what a press does), off on the last phase, and both + * buttons are off once Stop now was pressed. + */ +export function loopStopLabels(state) { + const stopping = Boolean(state.stopping); + const on = Boolean(state.stopAfterPhase); + return { + afterText: on ? "Cancel stop after this phase" : "Stop after this phase", + afterDisabled: stopping || (!on && state.canStopAfter === false), + nowDisabled: stopping, + }; +} + +/** + * The bar's Change project and Change agent controls while a loop runs: off, + * with one short reason on them. The app refuses both commands too. + */ +export function loopLocks(state) { + const locked = Boolean(state && state.running); + return { locked, reason: locked ? "A loop is running. Stop it before you change the project or agent." : "" }; +} + +/** + * What the window does about a console that stopped answering. On Windows the + * agent's console dies with the agent (the app ends the agent's whole Job + * Object), so between a loop's phases a dead console is expected: the next + * phase opens its own, and the loop itself stops if it never does. The budget + * guards against a console that keeps dying, not against a long session. + */ +export function deadConsoleAction({ loopRunning, loopStep, frameReady, reconnects, limit }) { + if (loopRunning && loopStep === "Starting") return "wait-for-phase"; + if (!frameReady) return "no-hello"; + return reconnects < limit ? "reconnect" : "offer-button"; +} + /** * A project folder's own name, for the bar's project menu: the same last * segment the window title uses, or the whole path when there is none (a @@ -150,7 +227,9 @@ function lastSegment(dir) { * The console page's taskbar messages, checked here before anything reaches * the app (attention.rs decides what they mean). `attention` carries one of * the four states the page's favicon has; `taskbar` carries the Desktop app - * switch as a boolean. Anything else is null, and nothing is forwarded. + * switch as a boolean, and `activities-full` an Activities game going in or + * out of full screen the same way (taskbarSwitch checks both). Anything else + * is null, and nothing is forwarded. */ export const ATTENTION_STATES = Object.freeze(['busy', 'ready', 'attention', 'plain']); diff --git a/scripts/test-app-meter.mjs b/scripts/test-app-meter.mjs index 4539dc5..abecdd3 100644 --- a/scripts/test-app-meter.mjs +++ b/scripts/test-app-meter.mjs @@ -11,7 +11,7 @@ import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js"; +import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js"; import { findBrowser, launchBrowser } from "./browser.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -298,3 +298,159 @@ test("app.js forwards attention and taskbar through those checks, and clears the assert.match(APP_JS, /async function onNoHello\(\) \{\s+if \(frameReady \|\| !consoleKnown \|\| restarting\) return;[\s\S]{0,120}clearAttention\(\);/); assert.match(APP_JS, /plan2code: 'taskbar-state', on/, "the page hears the saved switch on its hello"); }); + +test("the loop banner says what the loop is doing at every moment", () => { + const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, phaseRetried: false, previousPhase: null, previousCommitted: false }; + const said = (extra) => loopBanner({ ...base, ...extra }); + + const running = said({}); + assert.equal(running.tone, "running"); + assert.equal(running.title, "Implementation loop running"); + assert.equal(running.detail, "Phase 2 of 4: API \u00b7 Build"); + assert.deepEqual(running.pips, ["done", "current", "todo", "todo"]); + + assert.equal(said({ phase: 1, step: "Starting" }).title, "Starting the loop"); + assert.equal(said({ phase: 1, step: "Starting" }).detail, "Opening a fresh agent for Phase 1 of 4: API."); + assert.equal(said({ step: "Starting", previousPhase: 1, previousCommitted: true }).title, "Phase 1 done and committed"); + assert.equal(said({ step: "Starting", previousPhase: 1 }).title, "Phase 1 done", "commits off: claims none"); + assert.equal(said({ step: "Starting", previousPhase: 1, phaseRetried: true }).title, "Retrying Phase 2", "a retry is not a new phase"); + + const waiting = said({ step: "Waiting on you" }); + assert.equal(waiting.tone, "waiting"); + assert.equal(waiting.title, "The loop needs your answer"); + assert.equal(said({ step: "Waiting on you", stopAfterPhase: true }).tone, "waiting", "a waiting question outranks a stop on its way"); + + const stopping = said({ stopAfterPhase: true }); + assert.equal(stopping.title, "Stopping after this phase"); + assert.equal(stopping.tone, "running"); + + assert.equal(said({ phaseName: "" }).detail, "Phase 2 of 4 \u00b7 Build"); + assert.deepEqual(said({ phase: 0, phases: 0 }).pips, []); +}); + +test("Stop now turns the banner to Stopping, ahead of a question or a stop on its way", () => { + const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: true }; + for (const extra of [{}, { step: "Waiting on you" }, { stopAfterPhase: true }, { step: "Starting" }]) { + const banner = loopBanner({ ...base, ...extra }); + assert.equal(banner.title, "Stopping"); + assert.equal(banner.detail, "The agent is ending. Nothing more will be committed."); + assert.equal(banner.tone, "running"); + assert.ok(banner.hint, "it has a hint"); + } + assert.equal(loopBanner({ ...base, stopping: false }).title, "Implementation loop running"); +}); + +test("the stop buttons: Stop after is a toggle, off on the last phase, and both are off while stopping", () => { + const base = { stopAfterPhase: false, stopping: false, canStopAfter: true }; + assert.deepEqual(loopStopLabels(base), { afterText: "Stop after this phase", afterDisabled: false, nowDisabled: false }); + assert.deepEqual(loopStopLabels({ ...base, stopAfterPhase: true }), { afterText: "Cancel stop after this phase", afterDisabled: false, nowDisabled: false }, "it can be turned off again"); + assert.equal(loopStopLabels({ ...base, canStopAfter: false }).afterDisabled, true, "the last phase has nothing to stop after"); + assert.equal(loopStopLabels({ ...base, canStopAfter: false }).nowDisabled, false, "Stop now stays on the last phase"); + assert.equal(loopStopLabels({ stopAfterPhase: false }).afterDisabled, false, "a state without the field leaves it on"); + assert.deepEqual(loopStopLabels({ ...base, stopping: true }), { afterText: "Stop after this phase", afterDisabled: true, nowDisabled: true }); + assert.equal(loopStopLabels({ ...base, stopAfterPhase: true, stopping: true }).afterDisabled, true); +}); + +test("app.js sends the toggle's wish and shows a failed press with a Retry", () => { + const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8"); + assert.match(app, /invoke\(command, args\)\.then\(hideLoopError/, "a good press clears the error"); + assert.match(app, /pressLoop\('loop_stop_after_phase', \{ on: !loopStopAfterOn \}\)/); + assert.match(app, /pressLoop\('loop_stop_now'\)/); + assert.match(app, /loopRetryBtn\.hidden = false/, "a failed press offers Retry"); + const html = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "index.html"), "utf8"); + assert.match(html, /id="loop-error"[^>]*hidden/); + assert.match(html, /id="loop-retry"[^>]*hidden/); +}); + +test("a console dead between a loop's phases waits for the next phase; any other gets the budget", () => { + const base = { loopRunning: false, loopStep: "", frameReady: true, reconnects: 0, limit: 3 }; + assert.equal(deadConsoleAction({ ...base, loopRunning: true, loopStep: "Starting" }), "wait-for-phase"); + assert.equal(deadConsoleAction({ ...base, loopRunning: true, loopStep: "Starting", reconnects: 3 }), "wait-for-phase", "never counts against the budget"); + assert.equal(deadConsoleAction({ ...base, loopRunning: true, loopStep: "Build" }), "reconnect", "mid-phase the agent still needs its page"); + assert.equal(deadConsoleAction(base), "reconnect"); + assert.equal(deadConsoleAction({ ...base, reconnects: 3 }), "offer-button"); + assert.equal(deadConsoleAction({ ...base, frameReady: false }), "no-hello"); +}); + +test("app.js refills the reconnect budget on a new page and brings the page back when a loop ends", () => { + const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8"); + const announced = app.slice(app.indexOf("function showAnnounced"), app.indexOf("window.__TAURI__.event.listen('console-page'")); + assert.match(announced, /reconnects = 0/, "a budget never refilled ran out by a loop's Phase 3 and the stop card was never seen"); + const applied = app.slice(app.indexOf("function applyLoopState"), app.indexOf("loopRunning = true;")); + assert.match(applied, /if \(wasRunning\) showLoopEnd\(\)/); + assert.match(app.slice(app.indexOf("async function showLoopEnd"), app.indexOf("function applyLoopState")), /reconnectConsole\(\)/); +}); + +test("the window title says a loop is running, and when it needs the person", () => { + assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Build" }), "Loop: Phase 2 of 7 - lunch"); + assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Waiting on you" }), "Loop needs you: Phase 2 - lunch"); + assert.equal(loopWindowTitle("", { phase: 1, phases: 2, step: "Build" }), "Loop: Phase 1 of 2"); +}); + +test("the loop banner and its stop buttons sit outside the bar, so nothing else competes with them", () => { + const banner = INDEX_HTML.indexOf('id="loop-banner"'); + const barEnd = INDEX_HTML.indexOf(""); + const workspace = INDEX_HTML.indexOf('
'); + assert.ok(barEnd < banner && banner < workspace, "between the bar and the workspace"); + assert.ok(INDEX_HTML.indexOf('id="loop-stop-now"') > banner, "the stop buttons moved with it"); + assert.ok(!INDEX_HTML.includes('id="loop-strip"')); + assert.match(INDEX_HTML, /id="loop-banner"[^>]*\bhidden\b/, "hidden until a loop runs"); + assert.match(INDEX_HTML, /role="status" aria-live="polite"/); + assert.match(INDEX_HTML, /prefers-reduced-motion: reduce\) \{ #loop-dot/); + assert.match(APP_JS, /listen\('loop-state'/); +}); + +test("loopLocks turns Change project and Change agent off, with one reason, only while a loop runs", () => { + const on = loopLocks({ running: true, phase: 2, phases: 4 }); + assert.equal(on.locked, true); + assert.equal(on.reason, "A loop is running. Stop it before you change the project or agent."); + for (const state of [{ running: false }, {}, null, undefined]) { + assert.deepEqual(loopLocks(state), { locked: false, reason: "" }); + } +}); + +test("the banner and stop buttons agree for a state carrying stopping, stopAfterPhase or the last phase", () => { + const base = { running: true, phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: false, canStopAfter: true }; + const stopping = { ...base, stopping: true }; + assert.equal(loopBanner(stopping).title, "Stopping"); + assert.deepEqual(loopStopLabels(stopping), { afterText: "Stop after this phase", afterDisabled: true, nowDisabled: true }); + const after = { ...base, stopAfterPhase: true }; + assert.equal(loopBanner(after).title, "Stopping after this phase"); + assert.deepEqual(loopStopLabels(after), { afterText: "Cancel stop after this phase", afterDisabled: false, nowDisabled: false }); + const last = { ...base, canStopAfter: false }; + assert.equal(loopBanner(last).title, "Implementation loop running"); + assert.equal(loopStopLabels(last).afterDisabled, true); +}); + +test("app.js asks loop_state after attach and again once it listens, without calling a reload a loop's end", () => { + assert.match(APP_JS, /async function syncLoopState\(\)[\s\S]*?invoke\('loop_state'\)/); + assert.match(APP_JS, /\.listen\('loop-state'[\s\S]*?\.then\(syncLoopState/, "asked again once the listener is up"); + const attach = APP_JS.indexOf("invoke('agent_reattach'"); + const sync = APP_JS.indexOf("await syncLoopState()", attach); + assert.ok(attach > 0 && sync > attach, "asked right after the reattach"); + assert.match(APP_JS, /const seen = loopEventSeq;[\s\S]*?if \(seen !== loopEventSeq\) return;/, "an event that landed while loop_state was out wins over its answer"); + assert.match(APP_JS, /else if \(loopRunning\) applyLoopState\(\{ running: false \}\)/, "no loop and none drawn redraws nothing"); + assert.match(APP_JS, /const wasRunning = loopRunning;[\s\S]*?if \(wasRunning\) showLoopEnd\(\)/, "only a drawn loop ends with the finish redraw"); +}); + +test("app.js locks the change buttons through loopLocks and shows the typing note once per loop", () => { + assert.match(APP_JS, /const \{ locked, reason \} = loopLocks\(state\);[\s\S]*?button\.disabled = locked/); + assert.match(APP_JS, /applyLoopLocks\(\{ running: false \}\)/, "the ended branch gives them back"); + assert.match(APP_JS, /if \(!loopRunning\) loopTypingNoted = false/, "a new loop shows the note again"); + assert.ok(APP_JS.includes("noteTypingDuringLoop();\n invoke('agent_input'"), "the note comes before, and never replaces, the delivery of the key"); + assert.ok(APP_JS.includes("A loop is running. Typing here can derail the phase it is working on.")); +}); + +test("main.rs guards the window's agent and project commands, and registers loop_state", () => { + const rust = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "src-tauri", "src", "main.rs"), "utf8"); + const body = (name) => { + const at = rust.indexOf(`fn ${name}(`); + assert.ok(at > 0, `${name} exists`); + return rust.slice(at, rust.indexOf("\n}\n", at)); + }; + for (const [name, what] of [["agent_start", "agent"], ["agent_restart", "agent"], ["change_project", "project"], ["pick_project_folder", "project"]]) { + assert.ok(body(name).includes(`refuse_while_looping(&state, "${what}")?;`), `${name} refuses while a loop runs`); + } + assert.ok(!body("agent_input").includes("refuse_while_looping"), "typing stays open for a trust or login prompt"); + assert.match(rust, /generate_handler!\[[\s\S]*?loop_stop_now,\s*loop_state,/); +});