From 57567d7a0b99494bae494ba7a235d19e783f9e36 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Sat, 28 Nov 2026 21:09:02 -0800 Subject: [PATCH] Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases AI Assisted --- .../AGENTS-architecture-console-page.md | 5 +- .agents-docs/AGENTS-architecture-console.md | 1 + .agents-docs/AGENTS-architecture-install.md | 8 +- .agents-docs/AGENTS-development-commands.md | 2 +- .agents-docs/AGENTS-test-map.md | 1 + .readme/web-console.md | 9 + AGENTS.md | 2 +- CHANGELOG.md | 11 +- docs/desktop-app.md | 52 + package.json | 2 +- plan2code-app/fake-agent/src/main.rs | 182 +- plan2code-app/src-tauri/src/agents.rs | 29 +- plan2code-app/src-tauri/src/lib.rs | 6 + plan2code-app/src-tauri/src/loop_driver.rs | 662 ++- plan2code-app/src-tauri/src/loop_report.rs | 49 + .../src-tauri/src/loop_shared/mod.rs | 16 + .../src-tauri/src/loop_shared/report_list.rs | 16 + .../src-tauri/src/loop_shared/retry.rs | 28 + .../src-tauri/src/loop_shared/rounds.rs | 110 + .../src-tauri/src/loop_shared/session.rs | 62 + .../src-tauri/src/loop_shared/watch.rs | 129 + plan2code-app/src-tauri/src/loop_tools.rs | 42 +- plan2code-app/src-tauri/src/main.rs | 215 +- plan2code-app/src-tauri/src/phase_rounds.rs | 631 +++ plan2code-app/src-tauri/src/review_loop.rs | 4868 +++++++++++++++++ plan2code-app/src-tauri/src/review_report.rs | 522 ++ plan2code-app/src-tauri/src/round_boundary.rs | 400 ++ plan2code-app/src-tauri/src/round_logic.rs | 675 +++ plan2code-app/ui/app.js | 104 +- plan2code-app/ui/meter.js | 46 +- scripts/test-agent-lookup.mjs | 7 + scripts/test-app-meter.mjs | 92 +- scripts/test-console-wire-budgets.mjs | 3 +- scripts/test-lanes.json | 2 + scripts/test-web-console-loop.mjs | 336 +- scripts/test-web-console-page-loop.mjs | 34 + scripts/test-web-console-page-review-loop.mjs | 421 ++ scripts/test-web-console-review-loop.mjs | 199 + scripts/test-web-console-server.mjs | 4 +- scripts/test-web-console-shape.mjs | 2 +- scripts/test-web-console-skills.mjs | 45 +- scripts/test-web-console-state.mjs | 4 + src/launcher/agents.json | 8 + src/plan2code-review.md | 2 +- src/shared-references/lessons.md | 2 +- src/web-console/agent-lookup.mjs | 7 +- src/web-console/cmd-open.mjs | 54 +- src/web-console/console.mjs | 2 +- src/web-console/loop-setup.mjs | 4 + src/web-console/notes/review-loop.md | 55 + src/web-console/notes/review.md | 2 + src/web-console/patches.mjs | 168 +- src/web-console/public/answers.js | 9 +- src/web-console/public/app-bridge.js | 28 +- src/web-console/public/app.js | 4 +- src/web-console/public/index.html | 3 + src/web-console/public/loop-parts.js | 262 + src/web-console/public/review-loop-end.js | 201 + src/web-console/public/screens/core.js | 14 +- src/web-console/public/screens/dashboard.js | 32 +- src/web-console/public/screens/ending.js | 2 + src/web-console/public/screens/help-dialog.js | 2 + src/web-console/public/screens/loop-setup.js | 260 +- .../public/screens/review-loop-setup.js | 433 ++ src/web-console/public/skills.js | 31 +- src/web-console/public/state.js | 8 + src/web-console/public/styles/dashboard.css | 9 + src/web-console/review-loop-setup.mjs | 96 + src/web-console/routes.mjs | 38 + src/web-console/sessions.mjs | 1 + src/web-console/static.mjs | 3 + 71 files changed, 11331 insertions(+), 443 deletions(-) create mode 100644 plan2code-app/src-tauri/src/loop_shared/mod.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/report_list.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/retry.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/rounds.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/session.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/watch.rs create mode 100644 plan2code-app/src-tauri/src/phase_rounds.rs create mode 100644 plan2code-app/src-tauri/src/review_loop.rs create mode 100644 plan2code-app/src-tauri/src/review_report.rs create mode 100644 plan2code-app/src-tauri/src/round_boundary.rs create mode 100644 plan2code-app/src-tauri/src/round_logic.rs create mode 100644 scripts/test-web-console-page-review-loop.mjs create mode 100644 scripts/test-web-console-review-loop.mjs create mode 100644 src/web-console/notes/review-loop.md create mode 100644 src/web-console/public/loop-parts.js create mode 100644 src/web-console/public/review-loop-end.js create mode 100644 src/web-console/public/screens/review-loop-setup.js create mode 100644 src/web-console/review-loop-setup.mjs diff --git a/.agents-docs/AGENTS-architecture-console-page.md b/.agents-docs/AGENTS-architecture-console-page.md index 1622e9a..e394ec7 100644 --- a/.agents-docs/AGENTS-architecture-console-page.md +++ b/.agents-docs/AGENTS-architecture-console-page.md @@ -13,6 +13,7 @@ One row per file under `src/web-console/public/` (the games and their sound are | `public/diff-parse.js` | the Changes tab's parser: the unified diff `changes.mjs diff` writes, read into files, hunks and numbered lines; never throws | | `public/diff-view.js` | the Changes tab: a `diff` doc block drawn as a file list and one unified diff, with its empty, loading and error states (Check again and Reload send `__changes`) | | `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` | +| `public/loop-parts.js` | what the two loop setup screens share so neither imports the other (the shape test forbids it): the field builders (`field`, `toggle`, `radios`, `select`), the strength words, the notification fields with their checks (`notifyFields`, `notifyProblem`, `kindForUrl`) and the silence input. | | `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches | | `public/mention-box.js` | the @name suggestions popover under a text box | | `public/net.js` | the page talking to its own server | @@ -32,7 +33,9 @@ One row per file under `src/web-console/public/` (the games and their sound are | `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it | | `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, the first-open wake-up, and Learning's waiting banner (`learningBanner()`: the line from `learningBannerText()` and a **Review** button sending `__learning` `review`, last of the banners), which places Learning's row through `hooks.renderLearningRow` | | `public/screens/learning-row.js` | Learning's row on the dashboard (`renderLearningRow(scan, position)`): four states in two places (under the picker while not set up, off or paused; after the last card group while on), Pause for me posting `/learning/pause` with no agent, More, Open the lessons and the Remove confirm, plus `renderLessonsDialog()`, the Lessons to review dialog that draws an open `lessons` card over the menu; the agent-run controls send `__learning` through `hooks.sendLearning` and gray out under `learningBlocked()` | -| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The **Strength per phase** field (`strengthField`) is a grid: four headed columns (Match my session, Thrifty, Balanced, Best; level 0 to 3) and one `radiogroup` row per phase left, one radio per column (`#loop-strength--`, `match` for Match my session; an unmapped word's radio is disabled and its header says "(not mapped)"), the cell's dot (`strengthBars`) over the hidden radio, and the model the pick becomes at the row's end. **Set all to** stays a select (`#loop-strength-all`, blank again after use). **Suggest for me** (`#loop-strength-suggest`, right of it) sends a no-hop `__loopSuggest` (`id`, `spec`, `phases`, the mapped `strengths`) to the dashboard agent and grays the field under `.loop-suggest-overlay` (`.is-suggesting`, `aria-busy`); the agent posts `loopSuggest` (`{ id, spec, picks: [{ n, strength, why }] }`, checked by `loopSuggestProblems` in `patches.mjs`), and the page applies only the answer whose `id` and `spec` match its own request, mapped words only, with each `why` as a `.loop-strength-why` line that a hand change or Set all to clears; `SUGGEST_WAIT_MS` (two minutes) gives the field back with a note when nobody answers. The dashboard skill answers it under "A strength suggestion arrives". `drawStrengthLine(grid)` draws the grid's SVG from the checked nodes' measured positions, never from state: a very light dashed `line.col` per column and a thick square-step `path.step` from each row's node to the next (one path fewer than rows, none under two rows or with the toggle off). It redraws on the window's resize, a `ResizeObserver` on the grid (Preferences' page width), fonts loading and every redraw of the section, and stops once the grid is gone. The colors are the `--lvl-0` to `--lvl-3` tokens (`--lvl-0` is the neutral gray of Match my session); tests wait for the drawn state before reading the line. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session | +| `public/screens/review-loop-setup.js` | the Review Loop's setup screen on the dashboard (app only): scope, round cap, commit and the pre-run commit tick, Suggestions, strength, silence, notify (the lifted `notifyFields` and `silenceField` of `loop-setup.js`), the hands-off and reviewer lines, the Start checks, and the `review-loop-start` request to the app. | +| `public/review-loop-end.js` | how a Review Loop run ends (`renderLoopEnd` hands a `loopEnd` with `kind: "review"` to `renderReviewLoopEnd`): a heading by `reason` (Clean, Stopped at the round cap, Stopped by you, Failed) with `line`, the `report` doc behind Read the full report, after Stop now (`partial`) the partial diff drawn by `diff-view.js` with Keep and Discard (`review-loop-partial`), Continue ("Run one more round" at the cap) only when `canContinue` and no `partial` (`review-loop-continue`), the Suggestions pick (nothing ticked) and the squash switch (only when `canSquash`, off) kept in module state per ending, and Sign off (`review-loop-sign-off` with `picks` and `squash`, always on offer); once `signedOff`, the finished screen: PR Prep and Fix what's left by hand (hidden when `open` is empty) send `review-loop-next` (`pr-prep` or `quick-task`), Back to the dashboard sends `loop-dashboard`. The app's answers land in `page.reviewAction` (`wireLoopMessages`) and show under the card; a pressed button stays disabled until the ending changes or an answer carries an error | +| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The **Strength per phase** field (`strengthField`) is a grid: four headed columns (Match my session, Thrifty, Balanced, Best; level 0 to 3) and one `radiogroup` row per phase left, one radio per column (`#loop-strength--`, `match` for Match my session; an unmapped word's radio is disabled and its header says "(not mapped)"), the cell's dot (`strengthBars`) over the hidden radio, and the model the pick becomes at the row's end. **Set all to** stays a select (`#loop-strength-all`, blank again after use). **Suggest for me** (`#loop-strength-suggest`, right of it) sends a no-hop `__loopSuggest` (`id`, `spec`, `phases`, the mapped `strengths`) to the dashboard agent and grays the field under `.loop-suggest-overlay` (`.is-suggesting`, `aria-busy`); the agent posts `loopSuggest` (`{ id, spec, picks: [{ n, strength, why }] }`, checked by `loopSuggestProblems` in `patches.mjs`), and the page applies only the answer whose `id` and `spec` match its own request, mapped words only, with each `why` as a `.loop-strength-why` line that a hand change or Set all to clears; `SUGGEST_WAIT_MS` (two minutes) gives the field back with a note when nobody answers. The dashboard skill answers it under "A strength suggestion arrives". `drawStrengthLine(grid)` draws the grid's SVG from the checked nodes' measured positions, never from state: a very light dashed `line.col` per column and a thick square-step `path.step` from each row's node to the next (one path fewer than rows, none under two rows or with the toggle off). It redraws on the window's resize, a `ResizeObserver` on the grid (Preferences' page width), fonts loading and every redraw of the section, and stops once the grid is gone. The colors are the `--lvl-0` to `--lvl-3` tokens (`--lvl-0` is the neutral gray of Match my session); tests wait for the drawn state before reading the line. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd` takes a third `kind`, `"review"` (the Review Loop's end, `reviewLoopEndProblems` in `patches.mjs`: `reason`, `report`, `canContinue`, `canSquash`, optional `partial`, `suggestions`, `open`, `signedOff`, `note`; `report` and `partial.diff` name docs on the page, no `phases` or `uncommitted` needed); `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session | | `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button | | `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home; a Diagnose finish whose `doc` is saved shows that file whole as a Bug report box with Copy report (the raw Markdown), above Next step | | `public/screens/git-host.js` | hosts the git board: the tools fold-out (`board.tools`, saved with the board), tabs, panels and what each click sends | diff --git a/.agents-docs/AGENTS-architecture-console.md b/.agents-docs/AGENTS-architecture-console.md index 39c44ae..2e24192 100644 --- a/.agents-docs/AGENTS-architecture-console.md +++ b/.agents-docs/AGENTS-architecture-console.md @@ -16,6 +16,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page | | `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` | | `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser | +| `review-loop-setup.mjs` | the Review Loop's setup, remembered per project in `~/.plan2code/console/review-loop-setup.json` (one entry per folded project folder, schema 1; a protected file Cleanup never offers): defaults, validation and the read and write the `/review-loop-setup` route uses. Its notify address and kind come from the loop setup, never from here | | `loop-setup.mjs` | the Implementation Loop's setup, remembered per project in `~/.plan2code/console/loop-setup.json` (one entry per folded project folder, schema 1): defaults, validation and the read and write the `/loop-setup` route uses. The app reads the same file itself for the quick check, so the page never carries that command | | `spec-carry.mjs` | the spec a desktop app's New Session carries to the fresh dashboard: one short-lived `~/.plan2code/console/spec-carry.json` (`{project, spec, at}`), written by `restart_brief::leave_spec` in the app from the old session's `specDir` (or, from a dashboard, its picker's `specSel` in the draft), taken once by `POST /spec-carry` (`takeSpecCarry`: same folded project, under ten minutes old, one folder under `specs/`) and used by `loadSpecCarry()` in `selectors.js` only when the new picker lists that spec | | `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent. `sessionActions()` hands the send's `__` actions to the agent whole: `__delete`, a `__launch` with its `fromBanner` (sent from a dashboard showing lessons waiting), and `__learning` with every field (`{ "i": "__learning", "do": ... }`, `do` one of `LEARNING_ACTIONS` in `public/answers.js`: `review`, `switch-on`, `switch-off`, `move-log`, `remove` or `tidy`). `__learning` is not a hop: the dashboard agent runs `lessons.mjs`, resumes as the dashboard and posts the menu again, and `pointers.mjs` names `console-launches.md` for it. Pause for me never reaches the agent (`POST /learning/pause`) | diff --git a/.agents-docs/AGENTS-architecture-install.md b/.agents-docs/AGENTS-architecture-install.md index 6a41f50..af67391 100644 --- a/.agents-docs/AGENTS-architecture-install.md +++ b/.agents-docs/AGENTS-architecture-install.md @@ -119,6 +119,12 @@ plan2code/ | `plan2code-app/src-tauri/src/loop_notify.rs` | The loop's notification: `NotifyKind` (query string, JSON body, Discord, Slack, Teams, Google Chat; its comment lists what a new service needs), `valid_url()`, `valid_param()` (mirrored in `loop-setup.mjs` and `screens/loop-setup.js`), `request_for()` (each kind's address and body) and `send()`, with a 10 second limit and errors that never hold the address. The driver writes the message and calls it from `observe()`, `stop_loop()` and `finish()`. | | `plan2code-app/src-tauri/src/loop_report.rs` | The loop's report on everything done for the person: one `LoopReport` per build, entries in order (passed, stopped, retried) with findings fixed, skipped and left open, assumptions read from the phase file, and reported decisions. Saved in the console's `loop-reports.json` after every entry, because a project file would dirty the tree Resume needs clean; `finish()` writes it to `LOOP-SUMMARY-.md` and removes the entry. | | `plan2code-app/src-tauri/src/loop_tools.rs` | What the loop runs on its own, each call with a time limit and its output kept: the spec scripts (`specs.mjs status`, `mark --to done`), `commit-msg.mjs`, git (`add`, `commit`, `status`, the short head), the console's `post` and `open --resume`, and the person's quick check. No shell runs here except the quick check, whose text comes only from `loop-setup.json`, never from a page message | +| `plan2code-app/src-tauri/src/loop_shared/` | What both loop drivers share, moved out of `loop_driver.rs` with its behavior unchanged: `session.rs` (`start_session` with the launch strength, `read_session_state`), `watch.rs` (`watch_loop`, the 2 s tick under `catch_unwind`, and `silence_expired`), `retry.rs` (`should_retry`, `next_strength_word`), `report_list.rs` (`load_reports`, `save_report` over `loop_report`), `rounds.rs` (finding a round's `roundOutcome` on its page, `proofs_for`, report text, the fixer's `reviewer_brief`) and `notify` in `mod.rs` | +| `plan2code-app/src-tauri/src/round_logic.rs` | The Review Loop's pure rules, with their tests: `RoundOutcome` (the console's `roundOutcome`), `judge_round` (clean needs the report doc, targeted tests that ran and passed, and no Critical or Warning; a fixer is judged with at least its reviewer's counts through `hold_reviewer_counts`), `next_step` (round, retry, Suggestions batch, final check or stop), `round_detail` and the round commit subject | +| `plan2code-app/src-tauri/src/round_boundary.rs` | Where a round starts and ends: a full commit id in commit mode, a temp-index `write-tree` snapshot otherwise, the diff between two boundaries into `round-N.diff`, and the `cat-file -e` check that fails a round loudly when a snapshot is gone | +| `plan2code-app/src-tauri/src/review_loop.rs` | The Review Loop's driver: the pre-run commit, one session per round (or a reviewer then a fixer for an agent without `helpers`), retry a strength up, commit or snapshot per round, Stop after this round, Stop now with Keep or Discard, Continue (one round at a time past the cap, never above 6), the Suggestions batch and final check, the `loop-state` banner (`kind: "rounds"`, `afterRounds` after the rounds), the end post, sign-off and squash (never the pre-run commit; refused when anything else landed on top). `open_findings()` carries every round's unfixed findings until a later round fixes them | +| `plan2code-app/src-tauri/src/review_report.rs` | The Review Loop's report markdown: setup, stop reason and evidence, one section per round and batch, Still open (from `open_findings()`), Suggestions and the sign-off; written to the report list and, for a spec scope, `REVIEW-LOOP-.md` | +| `plan2code-app/src-tauri/src/phase_rounds.rs` | Extra review rounds inside an Implementation Loop phase (`reviewRounds` in the loop setup): after a phase agent reports Critical or Warning left, fresh rounds review the phase diff (the first fixer briefed with the phase's unfixed findings) before the phase is judged and committed once. It keeps its own watch and retry (a recorded deviation) | | `plan2code-app/src-tauri/src/agents.rs` | Agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the shipped `agents.json` read at run time with the baked copy as fallback; `find_on_path`, the Rust twin of `agent-lookup.mjs`'s `findAgent` (PATH, PATHEXT, the saved PATH from `node_check::resolved_path()`, npm's global folder, the install folders), held to `scripts/fixtures/agent-lookup-cases.json`. The console side is `src/web-console/agents.mjs` | | Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app---[.exe]` and `plan2code-app--SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` | @@ -130,7 +136,7 @@ Install and update follow release tags, never `main`. `release-app.yml`'s `publi `~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents & models, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first. -`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to. +`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. Each entry may carry `helpers` beside `bypassArgs`: the agent can start a subagent from inside a session (`true` for Claude Code, `false` for every other built-in and template); missing means it cannot. `loadAgentList()` and the app's `AgentEntry` both read it as a boolean, so a custom agent without it reads `false`. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to. - **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves. - **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument. diff --git a/.agents-docs/AGENTS-development-commands.md b/.agents-docs/AGENTS-development-commands.md index 6b14c98..f32d699 100644 --- a/.agents-docs/AGENTS-development-commands.md +++ b/.agents-docs/AGENTS-development-commands.md @@ -92,7 +92,7 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md), | An Activities game (`public/activities/*`), `public/tones.js` or `public/music.js` | `node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs`, plus the game's own `scripts/test-web-console-activities-*.mjs` when it has one; add `test-web-console-page-activities.mjs` when the Activities window or its switches changed | | Page styles (`public/styles/*.css`) or `public/index.html` | `npm run test:page -- scripts/test-web-console-page-layout.mjs`, plus the page file of a screen whose own look changed (`test:page` unsets the app variables, takes `--test-name-pattern`, and is the way to run any page file) | | A music prototype (`prototypes/music//`) | `node prototypes/music/check.cjs ` (nothing in `npm test` reads `prototypes/`) | -| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-.mjs` (the loop's is `test-web-console-loop.mjs`), and its `test-web-console-page-.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` | +| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-.mjs` (the loop's is `test-web-console-loop.mjs`, the Review Loop's `test-web-console-review-loop.mjs` with `test-web-console-page-review-loop.mjs`), and its `test-web-console-page-.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` | | The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` | | A skill's script | `npm run build:skills`, then `node --test scripts/test-script-.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) | | Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` | diff --git a/.agents-docs/AGENTS-test-map.md b/.agents-docs/AGENTS-test-map.md index fe72691..eaaed8a 100644 --- a/.agents-docs/AGENTS-test-map.md +++ b/.agents-docs/AGENTS-test-map.md @@ -14,6 +14,7 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch | Lessons script | `src/skill-scripts/lessons.mjs`, `src/web-console/learning.mjs` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-lessons.mjs` | no | | Changes tab and script | `src/skill-scripts/changes.mjs`, `src/web-console/public/diff-parse.js`, `src/web-console/public/diff-view.js`, `src/web-console/public/styles/diff.css` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-changes.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-page-changes.mjs` | no | | Learning on the console | `src/web-console/learning.mjs`, `src/web-console/public/screens/learning-row.js`, `src/web-console/public/styles/learning.css` | `node scripts/node-test.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-page-learning.mjs` | no | +| Review Loop on the console | `src/web-console/review-loop-setup.mjs`, `src/web-console/notes/review-loop.md`, `src/web-console/public/screens/review-loop-setup.js`, `src/web-console/public/loop-parts.js`, `src/web-console/public/review-loop-end.js` | `node scripts/node-test.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-loop.mjs && npm run test:page -- scripts/test-web-console-page-review-loop.mjs` | no | | Workflow prompts | `src/plan2code-*.md` | `node scripts/validate-char-count.js && node scripts/check-skill-table.mjs` | no | | Desktop app | `plan2code-app/**` | `cd plan2code-app && cargo test` | no | | Metrics | `plan2code-metrics/**` | `cd plan2code-metrics && npm test` | no | diff --git a/.readme/web-console.md b/.readme/web-console.md index 1af8874..d00fa03 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -479,6 +479,15 @@ stopped, its actions sit beside a **Back to the dashboard** button that opens a fresh dashboard in the frame, no agent needed, and its status line marks it as your move rather than leaving a stale "starting" line behind. +Review rounds per phase (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers run up to this many more rounds before the phase is committed. + +The **Review Loop** card, also app only, sits beside the Implementation Loop's: it reviews and fixes a +finished change in rounds while you are away (round 1 the whole change, each later round only the last +round's fixes, a fresh reviewer every time), stops on a clean round, the round cap, your stop or a failure, +and ends on its own screen with the report, **Continue**, the Suggestions pick, an optional squash, **PR +Prep**, **Fix what's left by hand** and **Back to the dashboard**. The desktop app's guide covers it under +"Review Loop". + A stopped loop also offers **Ask a question**, first in the row. The app ended its agent when the loop stopped, so the Ask tab says no agent is available; the button wakes an ordinary agent on the same page, without starting the loop diff --git a/AGENTS.md b/AGENTS.md index 3b5e7b6..8ed33da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md) ## Web Console -Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review, and in Implement, Implement + Review and Quick task a **Changes** tab: a `diff` doc block fed by the `changes.mjs` skill script, parsed by `public/diff-parse.js` and drawn by `public/diff-view.js`), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (a Save, Share, Review, Tidy path, one task card for the step you are on, and the Changes, Branches and Sync tabs folded into **All branches and tools**; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (and the time each game was last picked in `activityPlayed`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in every skill that starts helpers); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). +Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review, and in Implement, Implement + Review and Quick task a **Changes** tab: a `diff` doc block fed by the `changes.mjs` skill script, parsed by `public/diff-parse.js` and drawn by `public/diff-view.js`), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (a Save, Share, Review, Tidy path, one task card for the step you are on, and the Changes, Branches and Sync tabs folded into **All branches and tools**; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (and the time each game was last picked in `activityPlayed`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), the app-only **Review Loop** (a card beside it, `screens/review-loop-setup.js`, the setup remembered in `~/.plan2code/console/review-loop-setup.json` owned by `review-loop-setup.mjs`; the app's `review_loop.rs` drives review-and-fix rounds, each a Review session opened with `--loop --round N --role` that reports a `roundOutcome` per `notes/review-loop.md`; its end screen is `public/review-loop-end.js`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in every skill that starts helpers); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 307d67c..4db3c30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,16 @@ All notable changes to Plan2Code will be documented in this file. ### Highlights -- Every waiting lesson is graded by a separate check (true, worth keeping, overlap, clear) before the lessons card asks you to approve it. -- Tidy up proposes merging, rewording, retiring or moving saved lessons when a file grows crowded. +- The desktop app gains a Review Loop: unattended review-and-fix rounds on a finished change, a fresh reviewer every round, until a clean round, the round cap or your stop; Implementation Loop phases can run the same extra rounds. +- Every waiting lesson is graded by a separate check (true, worth keeping, overlap, clear) before the lessons card asks you to approve it, and Tidy up proposes merging, rewording, retiring or moving saved lessons when a file grows crowded. - The lessons reader shows how often each lesson was followed, and every skill can now remember what you ask it to. ### ✨ Added +- **Desktop app**: a Review Loop card (app only) and setup: review the branch, uncommitted changes or a spec's work, with a round cap (3, up to 6), a commit per round (and an optional commit of your own work first), Suggestions on their own, strength, silence and notifications. +- **Desktop app**: round 1 reviews the whole change and each later round only the last round's fixes; the app counts a round clean only with the reviewer's report, tests that ran and passed, and no Critical or Warning, and an agent that cannot start its own reviewer gets a separate reviewer and fixer session. +- **Desktop app**: the Review Loop's banner shows a dot per round with its counts, the Suggestions batch and final check by name, Stop after this round, and Stop now with Keep or Discard for the unfinished round. +- **Desktop app**: the Review Loop ends on one report (also saved as `REVIEW-LOOP-.md` for a spec's work) listing every finding still open, with Continue one round at a time up to 6, the Suggestions pick, an optional squash of the round commits, PR Prep and Fix what's left by hand. - **Learning**: before the lessons card asks for approval, a fresh read-only helper (or the same agent in a separate step) grades every waiting lesson on four tests; each row shows its Fails and Doubts with reasons, the card says who checked and how long it took, and a suggested wording can be taken with Use this wording. - **Learning**: a Tidy up action (in the banner when lessons near their limit, and in the dashboard's menu) proposes merging, rewording, retiring or moving saved lessons, each graded by the same check before you decide. - **Learning**: the lessons reader shows under each lesson how often it was followed and when last (recorded on this machine only). @@ -21,7 +25,10 @@ All notable changes to Plan2Code will be documented in this file. ### 🔧 Changed +- **Implementation Loop**: a new Review rounds per phase setting (default 2): when a phase's own review leaves a Critical or a Warning, fresh reviewers run up to that many more rounds on the phase's diff before it is judged, so existing loops now run these rounds unless it is set to 0. +- **Agents**: the agent list marks which agents can start their own subagents (`helpers`), which picks the Review Loop's round shape. - **Learning**: every skill that reads lessons now notes what you ask it to remember (asking why when you gave no reason); the read-only skills' lessons wait for the next lessons card or the dashboard's Review. +- **For contributors**: the loop machinery both drivers use moved into `loop_shared/`, with new round, boundary and Review Loop driver tests and console and page suites. - **For contributors**: new lessons script and page tests cover the check, tidy-ups, follow counts and the near-limit nudge. ## v3.1.5 (2026-11-23) diff --git a/docs/desktop-app.md b/docs/desktop-app.md index c02ccd8..633ed7d 100644 --- a/docs/desktop-app.md +++ b/docs/desktop-app.md @@ -165,6 +165,7 @@ 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. +- **Review rounds per phase** (2, from 0 to 6, only with Review on): when a phase's own review leaves a Critical or a Warning, fresh reviewers run up to this many more rounds on the phase's diff before it is judged. The phase is still committed once. - **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). @@ -268,6 +269,57 @@ the same day). After a stop, **Read why, and the report so far** shows it on the is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Continue building 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". +## Review Loop + +The Review Loop reviews and fixes a finished change for you, round after round, while you do something +else. Like the Implementation Loop it is in the app only: the dashboard shows a **Review Loop** card beside +the Implementation Loop's, grayed out while either loop runs (one loop per window). + +**How rounds work.** Round 1 reviews everything you chose. Every later round reviews only what the round +before it changed, so the work shrinks as it goes. Each round's reviewer is a fresh one that never saw the +code being written. An agent that can start its own reviewer runs the round in one session; any other agent +gets two, a reviewer and then a separate fixer. Each round fixes Critical and Warning findings, runs the +tests for what it touched, and is committed (or, with commits off, snapshotted) before the next begins. The +app, not the agent, decides whether a round was clean: it needs the reviewer's report, tests that ran and +passed, and no Critical or Warning left. + +**The setup.** The fields and their defaults: + +- **What to review**: **Branch against main, with uncommitted changes** (everything the branch changed), + **Uncommitted changes only**, or **A spec's work** (the files the chosen spec's phases built). +- **Round cap** (3, from 1 to 6): the run stops after this many rounds. +- **Commit each round to the current branch** (on). With uncommitted changes in the tree, tick **Commit my + current changes first as Work before Review Loop** so your own work stays out of round 1's commit. It + never pushes. +- **Suggestions**: **Apply Suggestions on their own** (off) lists them in the report for you to pick; on, they + are applied in one last pass after the rounds, followed by a final check. +- **Strength for every round**, as in the Implementation Loop. A retried round goes one step up for that + round only. +- **If a round goes quiet** (20 minutes): a stuck round is retried once. +- **Send a notification**: the same address as the Implementation Loop's, plus **Also tell me when each + round finishes** (off). + +The setup is remembered per project in `~/.plan2code/console/review-loop-setup.json`. Please do not edit the +project's files while rounds run: anything changed goes into the round. + +**Watching and stopping.** The banner across the top shows a dot per round, with each finished round's +counts on hover, the current step, the time so far and any retries; the Suggestions batch and the final check +are named as such. **Stop after this round** lets the round finish, be judged and committed; **Stop now** +ends the agent at once and then asks whether to **Keep** or **Discard** what the unfinished round changed. + +**When it ends.** The run stops on a clean round, at the round cap, when you stop it, or on a failure it +cannot repair (a second crash, failing tests, a refused commit). The end screen says which, and **Read the +full report** shows every round: what it found, fixed and left, its tests and its commit, plus any +findings still open, including ones an earlier round could not fix. From there: + +- **Continue** runs one more round from where it stopped, one at a time past the cap, never above 6 in all. +- Pick the Suggestions you want applied, and, when every round was committed and nothing else landed on top, + turn on **Squash the round commits into one** (off; your pre-run commit is never touched). +- **Sign off** finishes the run, with or without picks. For a spec's work the report is also saved as + `specs//REVIEW-LOOP-.md`. +- Then **PR Prep**, or **Fix what's left by hand** (a Quick task with the open findings), or back to the + dashboard. + ## Keep it up to date `plan2code update` brings the skills, the `plan2code` command and the app up together. diff --git a/package.json b/package.json index fd31e60..7eabd37 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "pretest": "node scripts/fix-line-endings.mjs", "test:fast": "node scripts/test-fast.mjs", "test:page": "node scripts/run-page-tests.mjs", - "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-card-rows.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-ui-prototype-page.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" + "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-card-rows.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-ui-prototype-page.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" }, "devDependencies": { "gpt-tokenizer": "2.9.0", diff --git a/plan2code-app/fake-agent/src/main.rs b/plan2code-app/fake-agent/src/main.rs index 46ab410..de35895 100644 --- a/plan2code-app/fake-agent/src/main.rs +++ b/plan2code-app/fake-agent/src/main.rs @@ -10,6 +10,13 @@ //! 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) +//! ROUND write as `roundOutcome` the same way; when it names a +//! `report` id, first add that doc (`kind: report`) to `docs`. +//! Says `ROUND written` (`ROUND unavailable` when it cannot) +//! FILE write to under the working directory (`\n` +//! in the text is a line break), for a round's "fixes". Says +//! `FILE written ` (`FILE refused ` for a path that +//! leaves the folder) //! ENV print the variable as `ENV =` //! HANG say `HANGING`, then go silent for good (no more lines read) //! echoed back as `echo: ` @@ -43,6 +50,10 @@ pub enum Command { Env(String), /// `REPORT `: the phase report the loop waits for, as the JSON text. Report(String), + /// `ROUND `: a Review Loop round's report, as the JSON text. + Round(String), + /// `FILE `: a file the agent "fixed", relative to its folder. + File(String, String), /// `HANG`: go silent, to model an agent that stops answering. Hang, Echo(String), @@ -65,6 +76,47 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool { let Ok(outcome) = serde_json::from_str::(json) else { return false; }; + update_state(home, sid, |state| state["loopOutcome"] = outcome) +} + +/// Write the JSON as the `roundOutcome` of the session named by the environment. +fn write_round(json: &str) -> bool { + let (Ok(home), Ok(sid)) = ( + std::env::var("PLAN2CODE_CONSOLE_HOME"), + std::env::var("PLAN2CODE_CONSOLE_SID"), + ) else { + return false; + }; + write_round_to(std::path::Path::new(&home), &sid, json) +} + +/// `write_round` with the session named. A named `report` is added to `docs` +/// first, as the console would hold it, so the app finds the doc it checks for. +fn write_round_to(home: &std::path::Path, sid: &str, json: &str) -> bool { + let Ok(outcome) = serde_json::from_str::(json) else { + return false; + }; + update_state(home, sid, |state| { + if let Some(report) = outcome.get("report").and_then(|value| value.as_str()) { + let doc = + serde_json::json!({ "id": report, "kind": "report", "title": "Review round" }); + match state.get_mut("docs").and_then(|docs| docs.as_array_mut()) { + Some(docs) => docs.push(doc), + None => state["docs"] = serde_json::json!([doc]), + } + } + state["roundOutcome"] = outcome; + }) +} + +/// Read `/sessions//state.json` (a new object when it is missing or +/// not one), let `change` edit it, and write it back through a temp file and a +/// rename, so a reader never sees half a file. +fn update_state( + home: &std::path::Path, + sid: &str, + change: impl FnOnce(&mut serde_json::Value), +) -> bool { let dir = home.join("sessions").join(sid); let file = dir.join("state.json"); let mut state = std::fs::read_to_string(&file) @@ -73,7 +125,7 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool { .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; + change(&mut state); let _ = std::fs::create_dir_all(&dir); let temp = dir.join("state.json.tmp"); let Ok(text) = serde_json::to_string(&state) else { @@ -109,12 +161,45 @@ pub fn parse(line: &str) -> Command { return Command::Report(json.to_string()); } } + if let Some(rest) = line.strip_prefix("ROUND ") { + let json = rest.trim(); + if serde_json::from_str::(json).is_ok() { + return Command::Round(json.to_string()); + } + } + if let Some(rest) = line.strip_prefix("FILE ") { + let rest = rest.trim_start(); + if let Some((path, text)) = rest.split_once(char::is_whitespace) { + return Command::File(path.to_string(), text.trim_start().to_string()); + } + } if line == "HANG" { return Command::Hang; } Command::Echo(line.to_string()) } +/// Write `text` to `relative` under the working directory. Refuses a path that +/// is absolute or climbs out of it. `\n` in `text` becomes a line break. +fn write_file(relative: &str, text: &str) -> bool { + use std::path::{Component, Path}; + let path = Path::new(relative); + let inside = !relative.is_empty() + && path + .components() + .all(|part| matches!(part, Component::Normal(_) | Component::CurDir)); + if !inside { + return false; + } + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write(path, text.replace("\\n", "\n")).is_ok() +} + fn main() { say("FAKE-AGENT ready"); // What the app launched it with: the launch prompt is one of these, so a @@ -169,6 +254,20 @@ fn main() { say("REPORT unavailable") } } + Command::Round(json) => { + if write_round(&json) { + say("ROUND written") + } else { + say("ROUND unavailable") + } + } + Command::File(path, text) => { + if write_file(&path, &text) { + say(&format!("FILE written {path}")) + } else { + say(&format!("FILE refused {path}")) + } + } Command::Hang => { say("HANGING"); loop { @@ -230,6 +329,87 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn parses_round_and_file() { + assert_eq!( + parse("ROUND {\"round\":1}"), + Command::Round("{\"round\":1}".into()) + ); + assert_eq!(parse("ROUND {nope"), Command::Echo("ROUND {nope".into())); + assert_eq!( + parse("FILE src/a.rs fixed it\\nline two"), + Command::File("src/a.rs".into(), "fixed it\\nline two".into()) + ); + assert_eq!( + parse("FILE onlypath"), + Command::Echo("FILE onlypath".into()) + ); + } + + #[test] + fn a_round_lands_with_its_report_doc_beside_what_was_there() { + let home = std::env::temp_dir().join(format!("fake-agent-round-{}", std::process::id())); + let dir = home.join("sessions").join("s5"); + std::fs::create_dir_all(&dir).unwrap(); + let read = || -> serde_json::Value { + serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap() + }; + // A report id adds the doc to a state that had none. + assert!(write_round_to( + &home, + "s5", + "{\"round\":1,\"role\":\"both\",\"report\":\"rep\"}" + )); + let state = read(); + assert_eq!(state["roundOutcome"]["round"], 1); + assert_eq!(state["docs"][0]["id"], "rep"); + assert_eq!(state["docs"][0]["kind"], "report"); + assert_eq!(state["docs"][0]["title"], "Review round"); + assert_eq!(state["schema"], 1); + // Existing docs stay, and the new one is appended. + std::fs::write( + dir.join("state.json"), + "{\"schema\":1,\"docs\":[{\"id\":\"phasefile\"}]}", + ) + .unwrap(); + assert!(write_round_to( + &home, + "s5", + "{\"round\":2,\"report\":\"r2\"}" + )); + let state = read(); + assert_eq!(state["docs"][0]["id"], "phasefile"); + assert_eq!(state["docs"][1]["id"], "r2"); + // No report id, no doc; a fixer's outcome adds none. + std::fs::write(dir.join("state.json"), "{\"schema\":1}").unwrap(); + assert!(write_round_to( + &home, + "s5", + "{\"round\":3,\"role\":\"fixer\"}" + )); + let state = read(); + assert!(state.get("docs").is_none()); + assert_eq!(state["roundOutcome"]["role"], "fixer"); + // The loop's own report key is untouched by a round. + assert!(state.get("loopOutcome").is_none()); + assert!(!write_round_to(&home, "s5", "not json")); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn a_file_command_writes_under_the_working_folder_only() { + let base = format!("fake-agent-file-{}", std::process::id()); + assert!(write_file(&format!("{base}/sub/a.txt"), "one\\ntwo")); + assert_eq!( + std::fs::read_to_string(format!("{base}/sub/a.txt")).unwrap(), + "one\ntwo" + ); + let _ = std::fs::remove_dir_all(&base); + assert!(!write_file("../escape.txt", "x")); + assert!(!write_file("/abs.txt", "x")); + assert!(!write_file("", "x")); + } + #[test] fn a_report_with_bad_json_is_an_echo() { assert_eq!( diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs index 060d3f1..052689b 100644 --- a/plan2code-app/src-tauri/src/agents.rs +++ b/plan2code-app/src-tauri/src/agents.rs @@ -78,6 +78,10 @@ pub struct AgentEntry { pub args: Vec, #[serde(default)] pub bypass_args: Vec, + /// The agent can start a subagent from inside a session. Missing means it + /// cannot, so a custom agent without the key reads `false`. + #[serde(default)] + pub helpers: bool, #[serde(default)] pub model_args: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1678,6 +1682,21 @@ mod tests { .all(|e| !e.command.is_empty() && !e.args.is_empty())); } + #[test] + fn helpers_is_true_for_claude_and_false_for_everything_else() { + // The Review Loop picks its round shape from this flag: one session + // with a reviewer subagent, or a reviewer session then a fixer one. + let list = parse_agent_list(BAKED_AGENTS).expect("the baked list parses"); + for e in list.builtins.iter().chain(list.templates.iter()) { + assert_eq!(e.helpers, e.id == "claude", "helpers for {}", e.id); + } + // An entry without the key reads false. + let text = + r#"{"schema":1,"agents":[{"id":"x","name":"X","kind":"template","command":"x"}]}"#; + let list = parse_agent_list(text).expect("parses"); + assert!(!list.templates[0].helpers); + } + #[test] fn the_list_loader_rejects_a_bad_file_and_reads_the_installed_path() { // Not JSON, not an object, or the wrong schema is an error: the @@ -1809,6 +1828,7 @@ mod tests { prompt: String::new(), args: vec![], bypass_args: vec![], + helpers: false, model_args: vec![], install_url: None, install: PerOs::default(), @@ -1985,10 +2005,11 @@ mod tests { let dir = temp_dir("find"); let file = dir.join("agents.json"); std::fs::write(&file, GOOSE).unwrap(); - assert_eq!( - find_agent_in("claude", Some(&file)), - Some(Agent::Builtin(entry("claude"))) - ); + // A built-in wins over the file. Only its identity is compared: the list the + // lookup reads is the installed one, which a machine may still hold from before + // a field was added, so a whole-entry comparison depended on that machine. + let found = find_agent_in("claude", Some(&file)); + assert!(matches!(&found, Some(Agent::Builtin(e)) if e.id == entry("claude").id)); let goose = find_agent_in("goose", Some(&file)).unwrap(); assert_eq!( ( diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs index fb18fea..adf28ca 100644 --- a/plan2code-app/src-tauri/src/lib.rs +++ b/plan2code-app/src-tauri/src/lib.rs @@ -11,13 +11,19 @@ pub mod loop_commit; pub mod loop_driver; pub mod loop_notify; pub mod loop_report; +pub mod loop_shared; pub mod loop_tools; pub mod models; pub mod node_check; +pub mod phase_rounds; pub mod project; pub mod pty_host; pub mod quit_prompt; pub mod restart_brief; +pub mod review_loop; +pub mod review_report; +pub mod round_boundary; +pub mod round_logic; pub mod session_reader; pub mod settings; #[cfg(windows)] diff --git a/plan2code-app/src-tauri/src/loop_driver.rs b/plan2code-app/src-tauri/src/loop_driver.rs index 3f91184..fcafa7f 100644 --- a/plan2code-app/src-tauri/src/loop_driver.rs +++ b/plan2code-app/src-tauri/src/loop_driver.rs @@ -27,8 +27,18 @@ 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_shared::notify as notify_call; +use crate::loop_shared::report_list::{load_reports, save_report}; +use crate::loop_shared::retry::{next_strength_word, should_retry}; +use crate::loop_shared::session::{read_session_state, start_session, Ctx}; +use crate::loop_shared::watch::{ + silence_expired, watch_loop, WatchStep, ACTIVITY_EVERY, WATCH_EVERY, +}; use crate::loop_tools; use crate::models::{self, StrengthRow}; +use crate::phase_rounds; +use crate::round_boundary::{self, Boundary}; +use crate::round_logic::Role; use crate::session_reader::{self, ReadError}; // ---------------------------------------------------------------- the setup @@ -132,6 +142,9 @@ pub struct PhasePick { #[serde(rename_all = "camelCase", default)] pub struct LoopSetup { pub review: bool, + /// Extra fresh review rounds a phase gets while its own review leaves a + /// Critical or Warning (0 turns them off). Read through `extra_rounds()`. + pub review_rounds: u32, // 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)] @@ -163,6 +176,7 @@ impl Default for LoopSetup { fn default() -> Self { LoopSetup { review: true, + review_rounds: MAX_REVIEW_ROUNDS_DEFAULT, fix_mode: FixMode::Smart, fix: vec![FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion], commit: true, @@ -181,7 +195,21 @@ impl Default for LoopSetup { } } +/// The Review rounds per phase a setup without the field takes. +const MAX_REVIEW_ROUNDS_DEFAULT: u32 = 2; +/// The most Review rounds per phase the setup allows. +const MAX_REVIEW_ROUNDS: u32 = 6; + impl LoopSetup { + /// The extra review rounds a phase may run: none with Review off, at most 6. + pub fn extra_rounds(&self) -> u32 { + if self.review { + self.review_rounds.min(MAX_REVIEW_ROUNDS) + } else { + 0 + } + } + /// The levels whose leftovers matter: every level in Smart pick. fn chosen_levels(&self) -> Vec { if !self.review { @@ -412,6 +440,28 @@ pub struct RunningRecord { /// not yet locked by the agent's `open --loop`: adopted on a later look /// once its state shows the lock (`note_page`). pub page_candidate: Option, + /// The banner's step while a phase's extra review rounds run ("Review round + /// 1 of 2"); it replaces the step's own label and is cleared by `set_step`. + pub step_text: Option, + /// The extra round session the phase is waiting on, so `note_page` can hand + /// it the page that session announces. + pub round_wait: Option, + /// The working tree as the phase began (a snapshot), kept only when the + /// setup allows extra review rounds: the first round reviews the diff from it. + pub phase_start: Option, + /// The extra review rounds the current phase has run, for its report entry. + pub phase_rounds: Vec, +} + +/// An extra review round session a phase is waiting on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RoundWait { + pub round: u32, + pub role: Role, + /// The adopted page's session id. + pub sid: Option, + /// A page announced before it showed the agent's lock, adopted once it does. + pub candidate: Option, } /// What one phase runs on, for its start, the strip and the report. @@ -496,6 +546,10 @@ impl RunningRecord { launch_effort: None, phase_baseline: None, page_candidate: None, + step_text: None, + round_wait: None, + phase_start: None, + phase_rounds: Vec::new(), } } @@ -531,7 +585,7 @@ impl RunningRecord { return; }; let Some(word) = phase.strength else { return }; - if let Some(next) = models::next_strength(&self.strength_rows, word.word()) + if let Some(next) = next_strength_word(&self.strength_rows, word.word()) .and_then(|w| Strength::from_word(&w)) { phase.strength = Some(next); @@ -567,6 +621,25 @@ pub struct LoopStateEvent { /// The model and effort the phase runs on, when known. pub model: Option, pub effort: Option, + /// `"phases"` for the Implementation Loop, `"rounds"` for the Review Loop. + pub kind: &'static str, + /// A Review Loop's current round and its cap (0 for the phases kind). + pub round: u32, + pub rounds: u32, + /// Critical and Warning per finished round (empty for the phases kind). + pub round_counts: Vec, + /// Stop after this round is on (a Review Loop). + pub stop_after_round: bool, + /// What a Review Loop runs after its rounds ("Suggestions batch" or + /// "Final check"), empty while a round runs and for the phases kind. + pub after_rounds: &'static str, +} + +/// What one finished Review Loop round found, for the banner's dots. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct RoundCount { + pub critical: u32, + pub warning: u32, } impl LoopStateEvent { @@ -590,6 +663,12 @@ impl LoopStateEvent { strength: None, model: None, effort: None, + kind: "phases", + round: 0, + rounds: 0, + round_counts: Vec::new(), + stop_after_round: false, + after_rounds: "", } } } @@ -615,7 +694,10 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent { 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(), + step: rec + .step_text + .clone() + .unwrap_or_else(|| rec.step.label().to_string()), started_at_ms: rec.started_at_ms, retries_used: rec.retries_used, stop_after_phase: rec.stop_after_phase, @@ -627,6 +709,12 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent { .map(|w| w.word().to_string()), model: run.as_ref().and_then(|r| r.model.clone()), effort: run.as_ref().and_then(|r| r.effort.clone()), + kind: "phases", + round: 0, + rounds: 0, + round_counts: Vec::new(), + stop_after_round: false, + after_rounds: "", } } @@ -663,7 +751,7 @@ pub enum Verdict { /// 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> { +pub(crate) fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -909,28 +997,6 @@ pub fn judge_outcome(outcome: &Outcome, phase_status: &Value, setup: &LoopSetup) 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 { @@ -953,17 +1019,6 @@ pub enum StopCause { 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 { @@ -1172,7 +1227,7 @@ pub fn prepare( validate_spec(project, spec)?; let setup = read_setup(project)?; let report = session_reader::console_home() - .and_then(|home| loop_report::load(&home, project, spec)) + .and_then(|home| load_reports(&home, project, spec)) .unwrap_or_default(); prepare_with(project, spec, setup, &report, mode, prompt_ok, resuming) } @@ -1266,7 +1321,7 @@ pub fn prepare_with( rec.rebuilt = rebuilt; rec.resumed_files = resumed_files; rec.branch = branch; - rec.start_head = loop_tools::git_head_full(project); + rec.start_head = loop_tools::git_head_full(project).ok(); // 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; @@ -1289,7 +1344,7 @@ fn phase_pick(setup: &LoopSetup, spec: &str, n: u32, name: &str) -> Option BTreeMap { +pub fn strength_rows_for(agent: &Agent) -> BTreeMap { let models: Vec = match agent { Agent::Builtin(entry) => models::models_for_builtin(&entry.id), Agent::Custom(custom) => custom.models.clone(), @@ -1670,7 +1725,7 @@ fn notify(setup: &LoopSetup, message: &str) -> Option { if setup.notify_url.is_empty() { return None; } - loop_notify::send( + notify_call( setup.notify_kind, &setup.notify_url, &setup.notify_param, @@ -1697,25 +1752,9 @@ pub struct Hooks { 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); @@ -1775,7 +1814,7 @@ pub fn begin_with_limits( } rec.launch_model.clone_from(&launch.1); rec.launch_effort.clone_from(&launch.2); - if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) { + if let Some(report) = load_reports(&home, &rec.project, &rec.spec) { rec.report = report; } let ctx = Ctx { @@ -1811,6 +1850,11 @@ pub fn begin_with_limits( /// (`page_is_this_phase`). One without the lock is kept as a candidate the /// watch adopts once the lock shows; one with a report is ignored. pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) { + // An extra review round's session, while a phase waits for one. + if workflow == "review" { + note_round_page(slot, sid, state); + return; + } if !matches!(workflow, "implement" | "implement-review") { return; } @@ -1827,6 +1871,27 @@ pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) { } } +/// Hand a Review page to the extra round a phase is waiting on: the page the +/// agent locked with `open --loop` for that round and role is its session; one +/// without the lock yet is kept as a candidate the round adopts once it shows. +fn note_round_page(slot: &LoopSlot, sid: &str, state: &Value) { + let mut guard = lock(slot); + let Some(rec) = guard.as_mut() else { return }; + let Some(wait) = rec.round_wait.as_mut() else { + return; + }; + if wait.sid.is_some() { + return; + } + if crate::loop_shared::rounds::page_is_this_round(state, wait.round, wait.role) { + wait.sid = Some(sid.to_string()); + wait.candidate = None; + rec.last_activity = SystemTime::now(); + } else if state.is_object() && state.get("roundOutcome").is_none_or(Value::is_null) { + wait.candidate = Some(sid.to_string()); + } +} + /// Follow `sid` as the phase's session from here. fn adopt_page(rec: &mut RunningRecord, sid: &str) { rec.sid = Some(sid.to_string()); @@ -1839,8 +1904,8 @@ fn adopt_page(rec: &mut RunningRecord, sid: &str) { /// agent's lock; the session to follow, or `None` while there is none yet. fn adopt_candidate(ctx: &Ctx, candidate: Option<&str>) -> Option { let sid = candidate?; - let session = session_reader::load(&ctx.home, sid).ok()?; - if !page_is_this_phase(&session.state) { + let state = read_session_state(ctx, sid)?; + if !page_is_this_phase(&state) { return None; } let mut guard = lock(&ctx.slot); @@ -1938,7 +2003,7 @@ pub fn finalize_prompt(spec: &str) -> String { format!("/plan2code-4-finalize {spec}/overview.md --web") } -fn emit(ctx: &Ctx) { +pub(crate) fn emit(ctx: &Ctx) { let event = { let guard = lock(&ctx.slot); guard @@ -1964,16 +2029,25 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> { } else { Vec::new() }; - (rec.project.clone(), carried) + (rec.project.clone(), carried, rec.setup.extra_rounds() > 0) }) } - .map(|(project, carried)| phase_baseline(&project, &carried)); + .map(|(project, carried, rounds)| { + // The tree as the phase begins, for its extra review rounds; a phase + // that allows none never pays for the snapshot. + let start = rounds.then(|| round_boundary::snapshot(&project).ok()); + (phase_baseline(&project, &carried), start) + }); let prompt = { let mut guard = lock(&ctx.slot); let rec = guard.as_mut().ok_or("the loop ended")?; - if let Some(baseline) = baseline { + if let Some((baseline, start)) = baseline { rec.phase_baseline = baseline; + rec.phase_start = start.flatten(); + rec.phase_rounds.clear(); } + rec.round_wait = None; + rec.step_text = None; rec.page_candidate = None; rec.current = index; rec.phases[index].status = PhaseStatus::Running; @@ -1996,11 +2070,8 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> { // Said before the agent starts: the banner is up from the moment of Start, // and says what is happening between phases. emit(ctx); - match on { - Some((word, row)) => start_phase_with(&ctx.agent, &ctx.launch, prompt, &row, word)?, - None => start_with(&ctx.agent, &ctx.launch, prompt)?, - } - let generation = ctx.agent.snapshot().generation; + let started = start_session(ctx, &prompt, on.as_ref().map(|(word, row)| (*word, row)))?; + let generation = started.generation; if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { rec.generation = generation; } @@ -2019,25 +2090,18 @@ fn watch(ctx: Ctx) { /// 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; - } + let panicked = watch_loop(ctx.limits.watch_every, || { + if step(&ctx) { + WatchStep::Continue + } else { + WatchStep::Stop } + }); + if let Some(text) = panicked { + 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"]); } } @@ -2289,7 +2353,7 @@ fn observe(ctx: &Ctx, stage: Option<&str>, asked: bool) { /// 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 { +pub(crate) fn clamp_to_now(time: SystemTime) -> SystemTime { time.min(SystemTime::now()) } @@ -2303,7 +2367,7 @@ fn modified(path: &Path) -> Option { /// 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 { +pub(crate) 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))) @@ -2409,12 +2473,91 @@ fn stop_before_mark(ctx: &Ctx, snap: &Snapshot, staged: bool) -> bool { false } -fn stop_requested(ctx: &Ctx) -> bool { +pub(crate) fn stop_requested(ctx: &Ctx) -> bool { lock(&ctx.slot) .as_ref() .is_some_and(|r| r.run_id == ctx.run_id && r.stop_now) } +/// The extra review rounds a phase's own review calls for (FR-28): with Review +/// on, `review_rounds` above zero and a Critical or Warning left in a report +/// that otherwise could pass, fresh round sessions review the phase's diff +/// before it is judged. Returns the report to judge (the phase agent's own when +/// no round ran, else with the last round's counts in its place), or `None` +/// when the loop was stopped here and the stop is already recorded. +fn extra_rounds(ctx: &Ctx, snap: &Snapshot, outcome: Outcome) -> Option { + let review = outcome.review.clone().unwrap_or_default(); + let left = leftover(&review, FixLevel::Critical) + leftover(&review, FixLevel::Warning); + // A phase that reports failed only for its findings has no other failure: + // its tests, tasks and conflicts are still checked by the judge afterwards. + let findings_only = outcome.result == "failed" + && outcome.reason.as_deref() == Some("findings") + && outcome.conflicts.is_empty(); + let tests_hold = outcome + .tests + .as_ref() + .is_none_or(|t| !t.ran || t.passed || excused_failures(t)); + if snap.setup.extra_rounds() == 0 + || !review.ran + || left == 0 + || !(outcome.result == "passed" || findings_only) + || !tests_hold + { + return Some(outcome); + } + let n = snap.phase_n; + let stop_with = |cause: StopCause, line: String| { + stop_loop(ctx, cause, line, &["resume", "fix"]); + None + }; + let start = { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?; + rec.phase_start.clone() + }; + let Some(start) = start else { + keep_output( + ctx, + "The extra review rounds were skipped: the tree as the phase began could not be recorded.", + ); + return Some(outcome); + }; + let input = phase_rounds::RoundsInput { + project: snap.project.clone(), + phase: n, + setup: snap.setup.clone(), + cap: snap.setup.extra_rounds(), + helpers: phase_rounds::helpers_for(ctx), + start, + unfixed: review.unfixed.clone(), + dir: ctx + .home + .join("loop-phase-rounds") + .join(format!("{}-phase-{n}", ctx.run_id)), + }; + let end = phase_rounds::run_rounds(ctx, &input); + match end { + phase_rounds::RoundsEnd::Done(done) => { + keep_rounds(ctx, &done.rounds); + Some(phase_rounds::judged_after(outcome, &done)) + } + phase_rounds::RoundsEnd::Person { rounds } => { + keep_rounds(ctx, &rounds); + stop_by_person(ctx, snap); + None + } + phase_rounds::RoundsEnd::Failed { reason, rounds } => { + keep_rounds(ctx, &rounds); + let cause = StopCause::Refused(format!( + "an extra review round failed ({})", + one_line(&reason) + )); + let line = stop_line(&cause, n, "", false); + stop_with(cause, line) + } + } +} + /// 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. @@ -2436,6 +2579,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool { if outcome.phase != n { return refused(format!("the report names Phase {}", outcome.phase)); } + // A phase whose own review left a Critical or a Warning gets fresh review + // rounds before it is judged (the hook; nothing else about the phase changes). + let Some(outcome) = extra_rounds(ctx, snap, outcome) else { + return false; + }; 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))), @@ -2595,6 +2743,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool { retries: snap.phase_retries, assumed: phase_assumptions(&snap.project, &snap.spec, n, Some(&entry)), warnings, + rounds: lock(&ctx.slot) + .as_ref() + .filter(|r| r.run_id == ctx.run_id) + .map(|r| r.phase_rounds.clone()) + .unwrap_or_default(), ..ReportEntry::default() } .with_outcome(&outcome); @@ -2798,7 +2951,7 @@ fn add_entry(ctx: &Ctx, entry: ReportEntry) { rec.report.entries.push(entry); (rec.project.clone(), rec.report.clone()) }; - let result = loop_report::save(&ctx.home, &saved.0, &saved.1); + let result = save_report(&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(); } @@ -2809,8 +2962,9 @@ fn set_step(ctx: &Ctx, step: Step) { 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; + let changed = rec.step != step || rec.step_text.is_some(); rec.step = step; + rec.step_text = None; changed } None => false, @@ -2827,6 +2981,13 @@ fn keep_output(ctx: &Ctx, output: &str) { } } +/// Keep the extra rounds the phase has run, for its report entry. +pub(crate) fn keep_rounds(ctx: &Ctx, rounds: &[loop_report::RoundEntry]) { + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + rec.phase_rounds = rounds.to_vec(); + } +} + 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()); @@ -3297,6 +3458,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) { if let Some(outcome) = &rec.last_outcome { entry = entry.with_outcome(outcome); } + entry.rounds.clone_from(&rec.phase_rounds); } // What the phase ran on, as `add_entry` does for every other entry. if let Some(run) = rec.phase_run(at) { @@ -3304,7 +3466,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) { entry.model = run.model_text(); } rec.report.entries.push(entry); - rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err(); + rec.report_failure = save_report(&ctx.home, &rec.project, &rec.report).err(); let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec); let sent = stop_message(&cause, &Where::of(&rec, at), &line) .and_then(|message| notify(&rec.setup, &message)); @@ -3681,6 +3843,12 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote if setup.review { md.push_str(&format!("- Fixes: {}\n", levels_text(setup))); } + if setup.review { + md.push_str(&format!( + "- Review rounds per phase: {}\n", + setup.extra_rounds() + )); + } 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", @@ -3726,7 +3894,7 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; fn setup() -> LoopSetup { @@ -4837,31 +5005,6 @@ second line" // ----------------------------------------------- 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(); @@ -5268,7 +5411,7 @@ second line" /// 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 { + pub(crate) fn program_ready(test: &str, program: &str) -> bool { let found = std::process::Command::new(program) .arg("--version") .output() @@ -5283,13 +5426,13 @@ second line" found } - fn git_ready(test: &str) -> bool { + pub(crate) 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 { + pub(crate) 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!( @@ -5299,7 +5442,7 @@ second line" git_ready(test) && program_ready(test, "node") } - fn git_in(repo: &Path, args: &[&str]) -> String { + pub(crate) fn git_in(repo: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") .args(args) .current_dir(repo) @@ -5383,7 +5526,7 @@ second line" } /// Where `cargo build -p fake-agent` leaves the fake agent, built on first use. - fn fake_agent_path() -> PathBuf { + pub(crate) 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")) @@ -5406,7 +5549,7 @@ second line" /// 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 { + pub(crate) fn fake_agent_launch() -> Launch { let agent = crate::agents::CustomAgent { id: "fake".into(), name: "Fake agent".into(), @@ -5422,7 +5565,7 @@ second line" /// 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>) { + pub(crate) 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); @@ -5449,7 +5592,7 @@ second line" } /// Poll until `ready`; the wait ends on state, not on a fixed sleep. - fn wait_until(what: &str, mut ready: impl FnMut() -> bool) { + pub(crate) fn wait_until(what: &str, mut ready: impl FnMut() -> bool) { let deadline = Instant::now() + Duration::from_secs(30); while Instant::now() < deadline { if ready() { @@ -7858,4 +8001,271 @@ second line" ); agent.stop(); } + + // ------------------------------------------------ extra review rounds in a phase + + fn quick_limits() -> Limits { + Limits { + watch_every: Duration::from_millis(20), + notice_wait: Duration::from_secs(20), + ..Limits::default() + } + } + + /// A `roundOutcome` the way a round agent posts it; the reviewer lists the + /// Warning it found as unfixed, the fixer says what its round left. + fn round_json(round: u32, role: &str, critical: u32, warning: u32) -> Value { + let mut value = json!({ + "round": round, "role": role, "result": "passed", "reason": null, + "summary": "Round done", + "review": { "critical": critical, "warning": warning, "suggestion": 0, + "fixed": [], "unfixed": [], "suggestions": [] }, + "tests": { "ran": true, "passed": true, "summary": "ok" }, + }); + if role != "fixer" { + value["report"] = json!("report"); + } + if role == "reviewer" { + value.as_object_mut().unwrap().remove("tests"); + if warning > 0 { + value["review"]["unfixed"] = + json!([{ "title": "Close the handle", "file": "work.txt" }]); + } + } + value + } + + /// What the player saw of a round session before it answered. + struct Seen { + scope: String, + banner: String, + } + + /// Answer the phase's extra round sessions in order: wait for each one the + /// driver starts, read its scope file and the banner, hand the driver its + /// page (as the app's notice does) and post its `roundOutcome`. + fn play_rounds( + ctx: &Ctx, + script: Vec<(u32, &'static str, Value)>, + ) -> thread::JoinHandle> { + let ctx = ctx.clone(); + thread::spawn(move || { + let mut seen = Vec::new(); + for (round, role, outcome) in script { + let want = match role { + "reviewer" => Role::Reviewer, + "fixer" => Role::Fixer, + _ => Role::Both, + }; + wait_until("a round session to wait for", || { + lock(&ctx.slot) + .as_ref() + .and_then(|rec| rec.round_wait.as_ref()) + .is_some_and(|w| w.round == round && w.role == want && w.sid.is_none()) + }); + let (phase, banner) = { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + (rec.phases[rec.current].n, state_event(rec).step) + }; + let dir = ctx + .home + .join("loop-phase-rounds") + .join(format!("{}-phase-{phase}", ctx.run_id)) + .join(format!("round-{round}-{role}-t0")); + let scope = std::fs::read_to_string(dir.join("scope.md")).expect("a scope file"); + let sid = format!("r{round}{role}"); + let folder = ctx.home.join("sessions").join(&sid); + std::fs::create_dir_all(&folder).unwrap(); + let post = |state: &Value| { + let mut state = state.clone(); + state["schema"] = json!(crate::session_reader::SCHEMA); + std::fs::write(folder.join("state.json.tmp"), state.to_string()).unwrap(); + std::fs::rename(folder.join("state.json.tmp"), folder.join("state.json")) + .unwrap(); + state + }; + let locked = + post(&json!({ "loop": { "driving": true, "round": round, "role": role } })); + note_page(&ctx.slot, "review", &sid, &locked); + let mut done = locked.clone(); + done["roundOutcome"] = outcome; + done["docs"] = json!([{ "id": "report", "kind": "report", "title": "Review round", + "blocks": [{ "id": "r", "md": "Found things to fix." }] }]); + post(&done); + seen.push(Seen { scope, banner }); + } + seen + }) + } + + /// A phase report whose own review left one Warning, the way a phase agent + /// that could not fix it reports it. + fn findings_report(phase: u32) -> Value { + let mut report = good_report(phase); + report["result"] = json!("failed"); + report["reason"] = json!("findings"); + report["review"] = json!({ + "ran": true, "recheck": true, + "left": { "critical": 0, "warning": 1, "suggestion": 0 }, + "unfixed": [{ "level": "warning", "title": "Close the handle", "file": "work.txt" }], + }); + report + } + + /// A running loop on a throwaway repo whose Phase 2 is built (tasks ticked, + /// one file written) after the start snapshot the rounds measure from. + fn built_phase(name: &str) -> (Ctx, PathBuf, PathBuf) { + let repo = throwaway_repo(name); + let (ctx, home) = running_loop(&repo, quick_limits()); + lock(&ctx.slot).as_mut().unwrap().phase_start = + Some(round_boundary::snapshot(&repo).unwrap()); + finish_phase_tasks(&repo, 2); + std::fs::write(repo.join("work.txt"), "phase work\n").unwrap(); + (ctx, repo, home) + } + + #[test] + fn a_phase_with_a_warning_left_runs_fresh_rounds_then_commits_once() { + if !harness_ready("extra rounds") { + return; + } + let (ctx, repo, home) = built_phase("extra-rounds"); + let before = git_in(&repo, &["rev-list", "--count", "HEAD"]); + write_session(&home, json!({ "loopOutcome": findings_report(2) })); + let player = play_rounds( + &ctx, + vec![ + (1, "reviewer", round_json(1, "reviewer", 0, 1)), + (1, "fixer", round_json(1, "fixer", 0, 1)), + (2, "reviewer", round_json(2, "reviewer", 0, 0)), + ], + ); + assert!(tick(&ctx), "the clean round 2 lets the phase pass"); + let seen = player.join().unwrap(); + assert_eq!(seen[0].banner, "Review round 1 of 2"); + assert_eq!(seen[2].banner, "Review round 2 of 2"); + assert!( + seen[0].scope.contains("everything the phase changed"), + "{}", + seen[0].scope + ); + let diff = seen[0] + .scope + .lines() + .find_map(|l| l.strip_prefix("- ")) + .unwrap(); + let diff = std::fs::read_to_string(diff).unwrap(); + assert!(diff.contains("work.txt"), "the whole phase diff: {diff}"); + assert!( + seen[1].scope.contains("Close the handle") + && seen[1].scope.contains("reviewer-report.md"), + "the fixer is briefed with the unfixed list: {}", + seen[1].scope + ); + assert!( + !seen[0].scope.contains("Close the handle"), + "the reviewer sees no brief" + ); + assert!( + seen[2].scope.contains("previous round's changes"), + "{}", + seen[2].scope + ); + let after = git_in(&repo, &["rev-list", "--count", "HEAD"]); + assert_eq!( + after.parse::().unwrap(), + before.parse::().unwrap() + 1, + "one commit for the phase" + ); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + assert!(git_in(&repo, &["show", "--name-only", "--format=", "HEAD"]).contains("work.txt")); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Passed); + assert_eq!(entry.rounds.len(), 2); + assert_eq!((entry.rounds[0].warning, entry.rounds[1].warning), (1, 0)); + let md = loop_report::body_markdown(&lock(&ctx.slot).as_ref().unwrap().report); + assert!( + md.contains("Extra review rounds: 2 (left after: 0 Critical, 0 Warning)"), + "{md}" + ); + end_the_test(&ctx); + } + + #[test] + fn findings_left_after_the_rounds_judge_the_phase_with_those_counts() { + if !harness_ready("extra rounds cap") { + return; + } + let (ctx, repo, home) = built_phase("extra-rounds-cap"); + lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 1; + // The phase agent leaves two Warnings; the one round leaves one, so only + // the last round's count can make the stop line say "1 Warning". + let mut report = findings_report(2); + report["review"]["left"]["warning"] = json!(2); + report["review"]["unfixed"] + .as_array_mut() + .unwrap() + .push(json!({ "level": "warning", "title": "Name the timer", "file": "work.txt" })); + write_session(&home, json!({ "loopOutcome": report })); + let player = play_rounds( + &ctx, + vec![ + (1, "reviewer", round_json(1, "reviewer", 0, 1)), + (1, "fixer", round_json(1, "fixer", 0, 1)), + ], + ); + assert!( + !tick(&ctx), + "a Warning left after the only round stops the phase" + ); + player.join().unwrap(); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert!( + entry.line.contains("1 Warning left after the re-check"), + "{}", + entry.line + ); + assert_eq!(entry.rounds.len(), 1); + assert_eq!( + git_in(&repo, &["rev-list", "--count", "HEAD"]), + "1", + "nothing was committed" + ); + end_the_test(&ctx); + } + + #[test] + fn no_rounds_run_when_nothing_is_left_when_they_are_zero_or_when_review_is_off() { + if !harness_ready("extra rounds skipped") { + return; + } + // Nothing left: the phase commits as before and no round folder appears. + let (ctx, repo, home) = built_phase("extra-none"); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx)); + assert!(last_entry_saved(&home, &repo).rounds.is_empty()); + assert!(!home.join("loop-phase-rounds").exists()); + end_the_test(&ctx); + // Zero rounds: the Warning stops the phase as it always did. + let (ctx, repo, home) = built_phase("extra-zero"); + lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 0; + write_session(&home, json!({ "loopOutcome": findings_report(2) })); + assert!(!tick(&ctx)); + assert!(last_entry_saved(&home, &repo).rounds.is_empty()); + assert!(!home.join("loop-phase-rounds").exists()); + end_the_test(&ctx); + // Review off: the setting means nothing, and the report judges as before. + let (ctx, repo, home) = built_phase("extra-off"); + lock(&ctx.slot).as_mut().unwrap().setup.review = false; + write_session(&home, json!({ "loopOutcome": findings_report(2) })); + let _ = tick(&ctx); + assert!(last_entry_saved(&home, &repo).rounds.is_empty()); + assert!(!home.join("loop-phase-rounds").exists()); + end_the_test(&ctx); + } } diff --git a/plan2code-app/src-tauri/src/loop_report.rs b/plan2code-app/src-tauri/src/loop_report.rs index 3ff46a3..5cce10d 100644 --- a/plan2code-app/src-tauri/src/loop_report.rs +++ b/plan2code-app/src-tauri/src/loop_report.rs @@ -32,10 +32,42 @@ pub struct Assumption { pub note: String, } +/// Which loop wrote an entry. Entries saved before the Review Loop existed +/// carry no kind and read as `Implementation`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum EntryKind { + #[default] + Implementation, + Review, +} + +/// One round of a Review Loop, as its entry keeps it. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct RoundEntry { + pub n: u32, + pub critical: u32, + pub warning: u32, + pub suggestion: u32, + pub fixed: Vec, + pub left_open: Vec, + pub commit: Option, + pub tests: String, + pub started: String, + pub ended: String, + /// "Balanced" and so on, or empty for an agent run as launched. + pub strength: String, + pub retried: bool, +} + /// 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 kind: EntryKind, + /// A Review Loop's rounds, in order; empty for an Implementation Loop phase. + pub rounds: Vec, pub at: String, pub phase: u32, pub name: String, @@ -298,6 +330,23 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) { if e.retries > 0 { md.push_str(&format!("- Retries: {}\n", e.retries)); } + if let Some(last) = e.rounds.last() { + md.push_str(&format!( + "- Extra review rounds: {} (left after: {} Critical, {} Warning)\n", + e.rounds.len(), + last.critical, + last.warning + )); + for round in &e.rounds { + md.push_str(&format!( + " - Round {}: {} Critical, {} Warning found, {} fixed\n", + round.n, + round.critical, + round.warning, + round.fixed.len() + )); + } + } if !e.warnings.is_empty() { let notes: Vec = e.warnings.iter().map(|w| cell(w)).collect(); md.push_str(&format!("- Warnings: {}\n", notes.join("; "))); diff --git a/plan2code-app/src-tauri/src/loop_shared/mod.rs b/plan2code-app/src-tauri/src/loop_shared/mod.rs new file mode 100644 index 0000000..6d4af15 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/mod.rs @@ -0,0 +1,16 @@ +//! Loop machinery both the Implementation Loop (`loop_driver`) and the Review +//! Loop call: starting an agent session, the watcher, the retry rule, the +//! saved report list and the notification. + +pub mod report_list; +pub mod retry; +pub mod rounds; +pub mod session; +pub mod watch; + +use crate::loop_notify::{self, NotifyKind}; + +/// Send a notification of `kind` to `url`; the reason it failed, if it did. +pub fn notify(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> { + loop_notify::send(kind, url, param, message) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/report_list.rs b/plan2code-app/src-tauri/src/loop_shared/report_list.rs new file mode 100644 index 0000000..f00c550 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/report_list.rs @@ -0,0 +1,16 @@ +//! The saved report list (`loop-reports.json`): one entry point for both the +//! Implementation Loop and the Review Loop. + +use std::path::Path; + +use crate::loop_report::{self, LoopReport}; + +/// The saved report for `spec` in `project`, when there is one. +pub fn load_reports(home: &Path, project: &Path, spec: &str) -> Option { + loop_report::load(home, project, spec) +} + +/// Save `report` for `project`. +pub fn save_report(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> { + loop_report::save(home, project, report) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/retry.rs b/plan2code-app/src-tauri/src/loop_shared/retry.rs new file mode 100644 index 0000000..1489478 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/retry.rs @@ -0,0 +1,28 @@ +//! The retry rule and the strength step-up, called by both the Implementation +//! Loop and the Review Loop. + +use std::collections::BTreeMap; + +use crate::loop_driver::{LoopSetup, StopCause}; +use crate::models::{self, StrengthRow}; + +/// 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 +} + +/// The strength word one step above `current`, or `None` when there is none +/// (Best stays, an unmapped word stays). A thin wrapper over +/// `models::next_strength`, so a caller without a `RunningRecord` can step up. +pub fn next_strength_word( + resolved: &BTreeMap, + current: &str, +) -> Option { + models::next_strength(resolved, current) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/rounds.rs b/plan2code-app/src-tauri/src/loop_shared/rounds.rs new file mode 100644 index 0000000..d4dc25b --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/rounds.rs @@ -0,0 +1,110 @@ +//! The pieces of a review round both loops read the same way: whether an +//! announced page is a round's session, the round's `roundOutcome` in a session +//! state, the report text it names, the proofs the app checks for itself, and +//! the reviewer's findings as the fixer's brief. The Review Loop and the +//! Implementation Loop's extra review rounds (a phase's hook) both call them. + +use serde_json::Value; + +use crate::round_logic::{Finding, Role, RoundOutcome, RoundProofs}; + +/// The word a role goes by in a console state and a prompt. +pub fn role_word(role: Role) -> &'static str { + match role { + Role::Both => "both", + Role::Reviewer => "reviewer", + Role::Fixer => "fixer", + } +} + +/// Whether an announced page is this round's session: the agent locked it with +/// `open --loop` for this round and role, and it holds no report yet. +pub fn page_is_this_round(state: &Value, round: u32, role: Role) -> bool { + state["loop"]["driving"].as_bool().unwrap_or(false) + && state["loop"]["round"].as_u64() == Some(u64::from(round)) + && state["loop"]["role"].as_str() == Some(role_word(role)) + && state.get("roundOutcome").is_none_or(Value::is_null) +} + +/// The round's outcome in `state`, when it is this round's and this role's. +pub fn round_outcome_in( + state: &Value, + round: u32, + role: Role, +) -> Option> { + let raw = state + .get("roundOutcome") + .filter(|value| value.is_object())?; + match serde_json::from_value::(raw.clone()) { + Ok(outcome) => (outcome.round == round && outcome.role == role).then_some(Ok(outcome)), + Err(err) => Some(Err(format!("the round's report could not be read ({err})"))), + } +} + +/// The text of the report doc the outcome names, from the session's `docs`. +pub fn report_text(state: &Value, id: &str) -> Option { + let doc = state["docs"] + .as_array()? + .iter() + .find(|doc| doc["id"].as_str() == Some(id))?; + let mut text = String::new(); + if let Some(blocks) = doc["blocks"].as_array() { + for block in blocks { + if let Some(md) = block["md"].as_str() { + text.push_str(md); + text.push_str("\n\n"); + } + } + } + Some(text) +} + +pub fn proofs_for(state: &Value, outcome: &RoundOutcome, role: Role) -> RoundProofs { + let report_doc_present = match role { + Role::Fixer => true, + _ => outcome + .report + .as_deref() + .is_some_and(|id| report_text(state, id).is_some()), + }; + let (tests_ran, tests_passed) = match role { + // A reviewer changes nothing and is not asked for tests. + Role::Reviewer => (true, true), + _ => outcome + .tests + .as_ref() + .map_or((false, false), |t| (t.ran, t.passed)), + }; + RoundProofs { + report_doc_present, + tests_ran, + tests_passed, + } +} + +pub fn finding_line(finding: &Finding) -> String { + match finding.line { + Some(line) => format!("- {} ({}:{line})", finding.title, finding.file), + None => format!("- {} ({})", finding.title, finding.file), + } +} + +/// The reviewer's findings, as the fixer's brief: the report's text and the +/// Critical and Warning findings the reviewer left unfixed. +pub fn reviewer_brief(text: &str, outcome: &RoundOutcome) -> String { + let mut brief = format!( + "# Reviewer report\n\n{}\n\nFound: {} Critical, {} Warning, {} Suggestion.\n\n", + text.trim(), + outcome.review.critical, + outcome.review.warning, + outcome.review.suggestion + ); + if !outcome.review.unfixed.is_empty() { + brief.push_str("## Fix these\n\n"); + for finding in &outcome.review.unfixed { + brief.push_str(&finding_line(finding)); + brief.push('\n'); + } + } + brief +} diff --git a/plan2code-app/src-tauri/src/loop_shared/session.rs b/plan2code-app/src-tauri/src/loop_shared/session.rs new file mode 100644 index 0000000..614af98 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/session.rs @@ -0,0 +1,62 @@ +//! What a loop needs to start an agent session and read its console state: the +//! shared context, `start_session` and `read_session_state`. Both the +//! Implementation Loop and the Review Loop call it. + +use std::path::PathBuf; +use std::sync::Arc; + +use crate::agent_manager::AgentManager; +use crate::loop_driver::{self, Hooks, Launch, Limits, LoopSlot, Strength}; +use crate::models::StrengthRow; +use crate::session_reader; + +/// What the watch thread needs, shared by every step of one loop. +#[derive(Clone)] +pub struct Ctx { + pub slot: LoopSlot, + pub agent: Arc, + pub console_dir: PathBuf, + pub home: PathBuf, + pub launch: Launch, + pub run_id: u64, + pub hooks: Arc, + pub limits: Limits, +} + +/// What a started session reports: the agent's generation and the model and +/// effort it started on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SessionStart { + pub generation: u64, + pub model: Option, + pub effort: Option, +} + +/// Start a fresh agent on `prompt`. With `strength` (the word and its row) the +/// agent starts on that row's model and effort with `PLAN2CODE_LOOP_STRENGTH` +/// set; without it, on the agent's launch choice. +pub fn start_session( + ctx: &Ctx, + prompt: &str, + strength: Option<(Strength, &StrengthRow)>, +) -> Result { + match strength { + Some((word, row)) => { + loop_driver::start_phase_with(&ctx.agent, &ctx.launch, prompt.to_string(), row, word)? + } + None => loop_driver::start_with(&ctx.agent, &ctx.launch, prompt.to_string())?, + } + let snapshot = ctx.agent.snapshot(); + Ok(SessionStart { + generation: snapshot.generation, + model: snapshot.model, + effort: snapshot.effort, + }) +} + +/// The console state of session `sid`, or `None` when it cannot be read now. +pub fn read_session_state(ctx: &Ctx, sid: &str) -> Option { + session_reader::load(&ctx.home, sid) + .ok() + .map(|session| session.state) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/watch.rs b/plan2code-app/src-tauri/src/loop_shared/watch.rs new file mode 100644 index 0000000..580b1d9 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/watch.rs @@ -0,0 +1,129 @@ +//! The watcher's timing, the silence rule and the generic watch loop, called by +//! both the Implementation Loop and the Review Loop. + +use std::time::{Duration, SystemTime}; + +use crate::loop_driver::LoopSetup; + +/// How often the watcher looks at the running loop. +pub const WATCH_EVERY: Duration = Duration::from_secs(2); +/// How often silence looks at the session's files and the tree. +pub const ACTIVITY_EVERY: Duration = Duration::from_secs(30); + +/// What a step of the watch loop says to do next. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WatchStep { + Continue, + Stop, +} + +/// Look every `every` until `step` says `Stop`. A panic in `step` ends the +/// watch and comes back as its text (`Some`), so the caller can end its loop +/// with the "watcher failed" stop instead of leaving a loop running with +/// nothing watching it; a normal stop returns `None`. +pub fn watch_loop WatchStep>(every: Duration, mut step: F) -> Option { + loop { + std::thread::sleep(every); + let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut step)); + match seen { + Ok(WatchStep::Continue) => {} + Ok(WatchStep::Stop) => return None, + Err(payload) => { + return Some( + payload + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "an unknown error".to_string()), + ); + } + } + } +} + +/// 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) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::{FixMode, OnQuestion}; + use std::time::UNIX_EPOCH; + + fn setup() -> LoopSetup { + LoopSetup { + fix_mode: FixMode::Levels, + on_question: OnQuestion::Pause, + ..LoopSetup::default() + } + } + + fn at(minutes: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(minutes * 60) + } + + #[test] + fn the_watch_loop_stops_on_stop_and_returns_the_text_of_a_panic() { + let none = Duration::ZERO; + let mut calls = 0; + let stopped = watch_loop(none, || { + calls += 1; + if calls < 3 { + WatchStep::Continue + } else { + WatchStep::Stop + } + }); + assert_eq!((stopped, calls), (None, 3)); + let quiet = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let literal = watch_loop(none, || panic!("literal")); + let text = "formatted".to_string(); + let owned = watch_loop(none, || panic!("{text}")); + let other = watch_loop(none, || std::panic::panic_any(1_u8)); + std::panic::set_hook(quiet); + assert_eq!(literal.as_deref(), Some("literal")); + assert_eq!(owned.as_deref(), Some("formatted")); + assert_eq!(other.as_deref(), Some("an unknown error")); + } + + #[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)); + } +} diff --git a/plan2code-app/src-tauri/src/loop_tools.rs b/plan2code-app/src-tauri/src/loop_tools.rs index 3938a61..55f5887 100644 --- a/plan2code-app/src-tauri/src/loop_tools.rs +++ b/plan2code-app/src-tauri/src/loop_tools.rs @@ -600,11 +600,17 @@ pub fn git_head_short(project: &Path) -> Option { (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 { +/// The full hash of `HEAD` (40 or 64 hex characters), or why there is none. +pub fn git_head_full(project: &Path) -> Result { 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()) + if !run.ok { + return Err("git could not read the current commit".to_string()); + } + if !matches!(hash.len(), 40 | 64) || !hash.chars().all(|c| c.is_ascii_hexdigit()) { + return Err("git did not return a full commit id".to_string()); + } + Ok(hash.to_string()) } /// The paths `git status --porcelain=v1 -z` lists (renames name the new path). @@ -799,6 +805,36 @@ mod tests { let _ = std::fs::remove_dir_all(&repo); } + #[test] + fn the_full_head_hash_starts_with_the_short_one() { + if Command::new("git").arg("--version").output().is_err() { + assert!(std::env::var_os("CI").is_none(), "git is not on PATH"); + return; + } + let repo = std::env::temp_dir().join(format!("plan2code-head-full-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&repo); + std::fs::create_dir_all(&repo).unwrap(); + let git_in = |args: &[&str]| { + let status = Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@example.com"]) + .args(args) + .current_dir(&repo) + .status() + .unwrap(); + assert!(status.success(), "git {args:?}"); + }; + git_in(&["init", "-q"]); + assert!(git_head_full(&repo).is_err(), "no commit yet"); + std::fs::write(repo.join("a.txt"), "x").unwrap(); + git_in(&["add", "-A"]); + git_in(&["commit", "-q", "--no-gpg-sign", "-m", "first"]); + let full = git_head_full(&repo).unwrap(); + let short = git_head_short(&repo).unwrap(); + assert!(full.starts_with(&short), "{full} / {short}"); + assert!(matches!(full.len(), 40 | 64)); + let _ = std::fs::remove_dir_all(&repo); + } + #[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"}"#; diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 8a1dac4..ace96fe 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -18,6 +18,7 @@ use plan2code_app_lib::node_check; use plan2code_app_lib::project::{self, ProjectDir}; use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase}; use plan2code_app_lib::restart_brief; +use plan2code_app_lib::review_loop::{self, ReviewSlot}; use plan2code_app_lib::session_reader; use plan2code_app_lib::settings; #[cfg(windows)] @@ -54,6 +55,9 @@ struct AppState { // The Implementation Loop running now, if any: in memory only, so an app // restart ends it (NFR-5). loop_run: LoopSlot, + // The Review Loop running now, or the one that stopped and waits for + // Continue or its report: in memory only, so an app restart ends it. + review_run: ReviewSlot, // The last loop's project, spec, launch choice and confirmed quick check, // kept after the running record is gone so Resume, Fix together with an agent and // Finalize still work. Memory only. @@ -450,7 +454,7 @@ fn sync_agent_env(app: &tauri::AppHandle) { // 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) { + if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err(format!( "A loop is running. Stop it before you change the {what}." )); @@ -729,6 +733,7 @@ fn confirm_quit(app: &tauri::AppHandle) { fn agent_is_active(app: &tauri::AppHandle) -> bool { let state = app.state::(); loop_driver::is_running(&state.loop_run) + || review_loop::is_running(&state.review_run) || current_agent(&state).is_some_and(|agent| agent.is_active()) } @@ -739,6 +744,7 @@ fn quit_app(app: &tauri::AppHandle) { let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take()); let state = app.state::(); loop_driver::abandon(&state.loop_run); + review_loop::abandon(&state.review_run); if let Some(agent) = current_agent(&state) { agent.stop(); } @@ -1410,8 +1416,8 @@ async fn start_loop( 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()); + if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { + return Err("A loop is already running in this window.".to_string()); } let project = state .project @@ -1601,11 +1607,203 @@ fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<() #[tauri::command] fn loop_state(state: State<'_, AppState>) -> Option { loop_driver::current_event(&state.loop_run) + .or_else(|| review_loop::current_event(&state.review_run)) +} + +// The project folder and the agent a Review Loop would use, or why there is none. +fn review_target( + state: &AppState, +) -> Result<(std::path::PathBuf, Arc, loop_driver::Launch), 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 run kept its own. + let launch = agent + .launch_choice() + .or_else(|| { + state + .review_run + .lock() + .ok() + .and_then(|run| run.as_ref().map(|r| r.launch.clone())) + }) + .ok_or("Start an agent first, with permission checks off.")?; + Ok((project, agent, launch)) +} + +// What the Review Loop's setup screen shows about the agent a run would use, +// and the notification settings the Implementation Loop's setup holds. +#[tauri::command] +fn review_loop_facts(state: State<'_, AppState>) -> review_loop::ReviewFacts { + let running = + loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run); + let project = state + .project + .lock() + .ok() + .and_then(|guard| guard.as_ref().map(|p| p.dir.clone())); + let setup = project + .as_deref() + .and_then(|dir| loop_driver::read_setup(dir).ok()) + .unwrap_or_default(); + let agent = current_agent(&state) + .and_then(|a| a.launch_choice()) + .map(|choice| choice.0) + .or_else(|| state.launch.agent.as_deref().and_then(agents::find_agent)); + review_loop::facts(agent.as_ref(), running, &setup) +} + +// Starts a Review Loop. Async and off the main thread: the pre-run commit and +// the start boundary run git. The notification comes from the Implementation +// Loop's setup file, never from the page's message. +#[tauri::command] +async fn review_loop_start( + app: tauri::AppHandle, + state: State<'_, AppState>, + setup: review_loop::ReviewRequest, +) -> Result { + let (project, agent, launch) = review_target(&state)?; + let loop_setup = loop_driver::read_setup(&project).unwrap_or_default(); + let setup = setup.into_setup(&loop_setup); + let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); + let hooks = loop_hooks(&app); + tauri::async_runtime::spawn_blocking(move || { + review_loop::start_review_loop(&slot, &phases, agent, launch, project, setup, hooks) + }) + .await + .map_err(|e| e.to_string())??; + Ok(true) +} + +// Stop after this round: it finishes, is judged and committed, then the run stops. +#[tauri::command] +fn review_loop_stop_after( + app: tauri::AppHandle, + state: State<'_, AppState>, + on: bool, +) -> Result<(), String> { + let event = review_loop::request_stop_after(&state.review_run, on)?; + let _ = app.emit("loop-state", &event); + Ok(()) +} + +// Stop now: the flag first, then the agent ends at once. Nothing more is +// committed; the stop screen offers Keep or Discard for the partial changes. +#[tauri::command] +fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { + let agent = current_agent(&state); + review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| { + let _ = app.emit("loop-state", event); + })?; + Ok(()) +} + +// Keep the partial changes of a Stop now, or put the tree back to the last +// finished round. +#[tauri::command] +async fn review_loop_partial(state: State<'_, AppState>, keep: bool) -> Result<(), String> { + let home = session_reader::console_home().ok_or("no home folder found")?; + let slot = state.review_run.clone(); + // The end screen is posted through node, so this is not main-thread work. + tauri::async_runtime::spawn_blocking(move || review_loop::settle_partial(&slot, keep, &home)) + .await + .map_err(|e| e.to_string())? +} + +// Sign off a finished Review Loop: fix the Suggestions the person ticked (one +// fixer session and its fresh check), squash the round commits when asked, and +// show the finished screen. Async and off the main thread: it runs git. +#[tauri::command] +async fn review_loop_sign_off( + app: tauri::AppHandle, + state: State<'_, AppState>, + picks: Vec, + squash: bool, +) -> Result<(), String> { + let (project, agent, _) = review_target(&state)?; + let same_project = state + .review_run + .lock() + .ok() + .and_then(|run| run.as_ref().map(|r| r.project == project)); + if same_project != Some(true) { + return Err("The project changed since that Review Loop.".to_string()); + } + let home = session_reader::console_home().ok_or("no home folder found")?; + let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); + let hooks = loop_hooks(&app); + tauri::async_runtime::spawn_blocking(move || { + review_loop::sign_off( + &slot, + &phases, + agent, + hooks, + loop_driver::Limits::default(), + home, + &picks, + squash, + true, + ) + }) + .await + .map_err(|e| e.to_string())? +} + +// The finished screen's PR Prep and Fix what's left by hand: an ordinary +// session on the skill, with no `--loop`, so the person talks to the agent. +#[tauri::command] +fn review_loop_next(state: State<'_, AppState>, next: String) -> Result<(), String> { + let prompt = review_loop::next_prompt(&state.review_run, &next)?; + let (_, agent, launch) = review_target(&state)?; + loop_driver::start_with(&agent, &launch, prompt) +} + +// Continue a stopped Review Loop: the next round from the last boundary; past +// the cap one round at a time, never above six in all. +#[tauri::command] +async fn review_loop_continue( + app: tauri::AppHandle, + state: State<'_, AppState>, +) -> Result<(), String> { + let (project, agent, _) = review_target(&state)?; + // A stopped run stays after a change of project: its git work would run + // in the old folder while the agent works in the new one. + let same_project = state + .review_run + .lock() + .ok() + .and_then(|run| run.as_ref().map(|r| r.project == project)); + if same_project != Some(true) { + return Err("The project changed since that Review Loop.".to_string()); + } + let home = session_reader::console_home().ok_or("no home folder found")?; + let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); + let hooks = loop_hooks(&app); + tauri::async_runtime::spawn_blocking(move || { + review_loop::continue_run( + &slot, + &phases, + agent, + hooks, + loop_driver::Limits::default(), + home, + true, + ) + }) + .await + .map_err(|e| e.to_string())? } // The last loop, for the stop and finish screens' buttons. fn last_loop(state: &AppState) -> Result { - if loop_driver::is_running(&state.loop_run) { + if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err("A loop is running".to_string()); } let last = state @@ -1808,6 +2006,14 @@ fn main() { loop_stop_after_phase, loop_stop_now, loop_state, + review_loop_facts, + review_loop_start, + review_loop_stop_after, + review_loop_stop_now, + review_loop_partial, + review_loop_sign_off, + review_loop_next, + review_loop_continue, loop_resume, loop_fix, loop_ask, @@ -1848,6 +2054,7 @@ fn main() { .map(|session| session.state) .unwrap_or(serde_json::Value::Null); loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid, &page); + review_loop::note_page(&state.review_run, ¬ice.workflow, ¬ice.sid, &page); let _ = handle.emit("console-page", ¬ice); } else { eprintln!( diff --git a/plan2code-app/src-tauri/src/phase_rounds.rs b/plan2code-app/src-tauri/src/phase_rounds.rs new file mode 100644 index 0000000..89bc22a --- /dev/null +++ b/plan2code-app/src-tauri/src/phase_rounds.rs @@ -0,0 +1,631 @@ +//! Extra review rounds inside an Implementation Loop phase (FR-28). +//! +//! When a phase's own review leaves a Critical or a Warning, fresh round +//! sessions review (and fix) the phase before it is judged and committed: the +//! first round looks at the whole phase diff and briefs the fixer with the +//! phase agent's unfixed findings, each later round looks only at what the +//! round before it changed. The rounds run here, one at a time, inside the +//! phase's report handling; the rules are `round_logic`'s, the session pieces +//! are `loop_shared`'s and the scope and prompt are the Review Loop's. A phase +//! never commits per round: its own commit at the end carries everything +//! (NFR-1). + +use std::path::{Path, PathBuf}; +use std::time::{Instant, SystemTime}; + +use serde_json::Value; + +use crate::agent_manager::AgentState; +use crate::loop_driver::{ + self, Finding as PhaseFinding, FixLevel, Left, LoopSetup, RoundWait, StopCause, Strength, +}; +use crate::loop_report::RoundEntry; +use crate::loop_shared::retry::should_retry; +use crate::loop_shared::rounds::{ + finding_line, page_is_this_round, proofs_for, report_text, reviewer_brief, role_word, + round_outcome_in, +}; +use crate::loop_shared::session::{read_session_state, start_session, Ctx}; +use crate::loop_shared::watch::silence_expired; +use crate::models::StrengthRow; +use crate::review_loop::round_prompt; +use crate::round_boundary::{self, Boundary}; +use crate::round_logic::{ + self, Finding, Next, Role, RoundOutcome, RoundReview, RunView, StopReason, Verdict, MAX_ROUNDS, +}; +use crate::session_reader; + +/// What the rounds need, copied out of the loop's record. +pub struct RoundsInput { + pub project: PathBuf, + pub phase: u32, + pub setup: LoopSetup, + /// The most rounds to run (the setup's Review rounds per phase). + pub cap: u32, + /// One session per round (the agent starts its own helper) or two. + pub helpers: bool, + /// The working tree as the phase began. + pub start: Boundary, + /// The phase agent's findings it left unfixed: the first fixer's brief. + pub unfixed: Vec, + /// Where each round's scope file and diff are written. + pub dir: PathBuf, +} + +/// How the rounds ended. +#[derive(Debug)] +pub enum RoundsEnd { + /// A clean round, or the cap: the last round's counts judge the phase. + Done(Done), + /// Stop now was pressed. + Person { rounds: Vec }, + /// A round failed after its retry. + Failed { + reason: String, + rounds: Vec, + }, +} + +#[derive(Debug, Default)] +pub struct Done { + pub rounds: Vec, + pub critical: u32, + pub warning: u32, + pub suggestion: u32, + pub unfixed: Vec, +} + +/// How one session of a round ended. +enum SessionEnd { + Outcome(Box, Value), + /// Why it failed, and the cause the retry rule reads (never the words). + Failed(StopCause, String), + Person, +} + +/// What a finished round gives the next step. +struct Played { + outcome: RoundOutcome, + verdict: Verdict, + retried: bool, + started: String, + strength: String, +} + +fn clock() -> String { + chrono::Local::now().format("%Y-%m-%d %H:%M").to_string() +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Whether the loop's agent can start a helper from inside a session. +pub fn helpers_for(ctx: &Ctx) -> bool { + crate::review_loop::agent_helpers(&ctx.launch.0) +} + +/// The banner's step, "Review round 1 of 2". +fn banner(ctx: &Ctx, round: u32, cap: u32) { + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + rec.step_text = Some(format!("Review round {round} of {cap}")); + } + loop_driver::emit(ctx); +} + +fn clear_wait(ctx: &Ctx) { + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + rec.round_wait = None; + } +} + +/// The strength the phase runs on now (a retry steps it up first), as +/// `start_phase` reads it. +fn strength_now(ctx: &Ctx) -> Option<(Strength, StrengthRow)> { + let guard = loop_driver::lock(&ctx.slot); + let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?; + let word = rec.phase_run(rec.current)?.strength?; + Some((word, rec.strength_rows.get(word.word())?.clone())) +} + +fn step_strength_up(ctx: &Ctx) { + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + let at = rec.current; + rec.step_strength_up(at); + } +} + +/// The text of a round's scope file: the diff to review, the reviewer's report +/// for a fixer and, in the first round, what the phase agent left unfixed. +fn scope_text( + round: u32, + role: Role, + diff: &Path, + report: Option<&Path>, + brief: &[PhaseFinding], +) -> String { + let mut text = format!( + "# Phase review round {round} scope\n\nRole: {}\n", + role_word(role) + ); + if round == 1 { + text.push_str(&format!( + "\nReview exactly this diff, everything the phase changed, and nothing else:\n\n- {}\n", + diff.display() + )); + } else { + text.push_str(&format!( + "\nReview exactly this diff, the previous round's changes, and nothing else:\n\n- {}\n", + diff.display() + )); + } + if !brief.is_empty() && role != Role::Reviewer { + text.push_str("\nThe phase's own review left these findings unfixed (fix them):\n\n"); + for finding in brief { + text.push_str(&finding_line(&Finding { + title: finding.title.clone(), + file: finding.file.clone(), + line: None, + })); + text.push('\n'); + } + } + if let Some(report) = report { + text.push_str(&format!( + "\nThe reviewer's report (fix its Critical and Warning findings):\n\n- {}\n", + report.display() + )); + } + text +} + +fn start_one( + ctx: &Ctx, + input: &RoundsInput, + round: u32, + role: Role, + scope: &str, + attempt: u32, +) -> Result { + let dir = input + .dir + .join(format!("round-{round}-{}-t{attempt}", role_word(role))); + std::fs::create_dir_all(&dir) + .map_err(|err| format!("could not make {}: {err}", dir.display()))?; + let scope_file = dir.join("scope.md"); + std::fs::write(&scope_file, scope) + .map_err(|err| format!("could not write {}: {err}", scope_file.display()))?; + let prompt = round_prompt(round, role, &scope_file); + // A running session (the phase's own, a silent one being retried) ends first. + ctx.agent.stop(); + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + rec.round_wait = Some(RoundWait { + round, + role, + sid: None, + candidate: None, + }); + rec.last_activity = SystemTime::now(); + rec.activity_checked = Instant::now(); + } + let on = strength_now(ctx); + let started = start_session(ctx, &prompt, on.as_ref().map(|(word, row)| (*word, row)))?; + Ok(started.generation) +} + +/// The round's session id: the page `note_page` handed over, or a candidate +/// whose state now shows the agent's lock. +fn session_id(ctx: &Ctx, round: u32, role: Role) -> Option { + let candidate = { + let guard = loop_driver::lock(&ctx.slot); + let wait = guard + .as_ref() + .filter(|r| r.run_id == ctx.run_id)? + .round_wait + .as_ref()?; + if let Some(sid) = &wait.sid { + return Some(sid.clone()); + } + wait.candidate.clone()? + }; + let state = read_session_state(ctx, &candidate)?; + if !page_is_this_round(&state, round, role) { + return None; + } + let mut guard = loop_driver::lock(&ctx.slot); + let wait = guard + .as_mut() + .filter(|r| r.run_id == ctx.run_id)? + .round_wait + .as_mut()?; + wait.sid.get_or_insert(candidate); + wait.sid.clone() +} + +fn crashed(ctx: &Ctx, generation: u64) -> Option { + let seen = ctx.agent.snapshot(); + match seen.state { + AgentState::Ended { reason } if seen.generation == generation => Some(reason), + _ => None, + } +} + +/// Watch one round session until it reports, fails or is stopped. The same +/// rules as a phase's watch: a crash, silence or a console that never opens +/// fail it, and so does a question (a round cannot be answered). +fn watch_session( + ctx: &Ctx, + setup: &LoopSetup, + round: u32, + role: Role, + generation: u64, +) -> SessionEnd { + let began = Instant::now(); + let mut last_activity = SystemTime::now(); + let mut checked = Instant::now(); + loop { + std::thread::sleep(ctx.limits.watch_every); + { + let guard = loop_driver::lock(&ctx.slot); + match guard.as_ref().filter(|r| r.run_id == ctx.run_id) { + // The loop ended under us (a stop, a restart): nothing to judge. + None => return SessionEnd::Person, + Some(rec) if rec.stop_now => { + drop(guard); + ctx.agent.stop(); + return SessionEnd::Person; + } + Some(_) => {} + } + } + let Some(sid) = session_id(ctx, round, role) else { + if let Some(reason) = crashed(ctx, generation) { + return SessionEnd::Failed( + StopCause::Crash, + format!("the agent crashed ({reason})"), + ); + } + if began.elapsed() > ctx.limits.notice_wait { + return SessionEnd::Failed( + StopCause::NoSession, + "the round's console never opened".to_string(), + ); + } + continue; + }; + let state = session_reader::load(&ctx.home, &sid) + .ok() + .map(|session| (session.state, session.dir)); + if let Some((state, _)) = &state { + if let Some(found) = round_outcome_in(state, round, role) { + ctx.agent.stop(); + return match found { + Ok(outcome) => SessionEnd::Outcome(Box::new(outcome), state.clone()), + Err(reason) => SessionEnd::Failed(StopCause::Refused(reason.clone()), reason), + }; + } + } + // An agent that writes its report and exits between two looks is + // judged, not called a crash. + if let Some(reason) = crashed(ctx, generation) { + let again = read_session_state(ctx, &sid); + if let Some(Ok(outcome)) = again + .as_ref() + .and_then(|state| round_outcome_in(state, round, role)) + { + return SessionEnd::Outcome(Box::new(outcome), again.unwrap_or(Value::Null)); + } + return SessionEnd::Failed(StopCause::Crash, format!("the agent crashed ({reason})")); + } + let mut quiet = None; + if let Some((state, dir)) = &state { + if let Some(question) = loop_driver::first_open_question(state) { + ctx.agent.stop(); + let reason = format!("the agent asked a question: {}", one_line(&question)); + return SessionEnd::Failed(StopCause::Question, reason); + } + quiet = state["agent"]["quietMinutes"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()); + if checked.elapsed() >= ctx.limits.activity_every { + checked = Instant::now(); + if let Some(time) = loop_driver::newest_work(dir, &input_project(ctx)) { + let time = loop_driver::clamp_to_now(time); + if time > last_activity { + last_activity = time; + } + } + } + } + if silence_expired(SystemTime::now(), last_activity, setup, quiet, false) { + let minutes = setup.silence_minutes.max(quiet.unwrap_or(0)).min(60); + return SessionEnd::Failed( + StopCause::Silence, + format!("the agent went silent for {minutes} minutes"), + ); + } + } +} + +/// The project the loop builds in, for the silence rule's look at the tree. +fn input_project(ctx: &Ctx) -> PathBuf { + loop_driver::lock(&ctx.slot) + .as_ref() + .filter(|r| r.run_id == ctx.run_id) + .map(|r| r.project.clone()) + .unwrap_or_default() +} + +/// One session with its one retry (a step up in strength): `Ok` with the +/// session's outcome, `Err(None)` when stop now ended it, `Err(Some)` with the +/// reason when the retry failed too. `retried` says the retry was used. +fn session_with_retry( + ctx: &Ctx, + input: &RoundsInput, + round: u32, + role: Role, + scope: &str, + retried: &mut bool, +) -> Result<(RoundOutcome, Value), Option> { + let mut attempt = 0; + loop { + let begun = start_one(ctx, input, round, role, scope, attempt).map_err(Some); + let end = match begun { + Ok(generation) => watch_session(ctx, &input.setup, round, role, generation), + Err(Some(reason)) => SessionEnd::Failed( + StopCause::Refused(reason.clone()), + format!("the round could not start ({reason})"), + ), + Err(None) => SessionEnd::Person, + }; + clear_wait(ctx); + match end { + SessionEnd::Person => return Err(None), + SessionEnd::Outcome(outcome, state) => return Ok((*outcome, state)), + SessionEnd::Failed(cause, reason) => { + // A crash, silence or a console that never opened gets one + // fresh try a strength up, as a phase does; `should_retry` + // reads the typed cause, so any other failure (a question, an + // unreadable report) fails the round. + if !*retried && should_retry(&cause, &input.setup, 0) { + *retried = true; + attempt += 1; + step_strength_up(ctx); + continue; + } + return Err(Some(reason)); + } + } + } +} + +/// Play one round: one session, or a reviewer then a fixer that never saw the +/// review. A failed session after its retry comes back as the round's failure. +fn play_round( + ctx: &Ctx, + input: &RoundsInput, + round: u32, + from: &Boundary, + to: &Boundary, +) -> Result> { + let dir = input.dir.join(format!("round-{round}")); + std::fs::create_dir_all(&dir) + .map_err(|err| Some(format!("could not make {}: {err}", dir.display())))?; + let diff = dir.join(format!("round-{round}.diff")); + round_boundary::diff(&input.project, from, to, &diff).map_err(Some)?; + let brief: &[PhaseFinding] = if round == 1 { &input.unfixed } else { &[] }; + let started = clock(); + let strength = strength_now(ctx).map_or_else(String::new, |(word, _)| word.label().to_string()); + let mut retried = false; + let (outcome, state) = if input.helpers { + let scope = scope_text(round, Role::Both, &diff, None, brief); + session_with_retry(ctx, input, round, Role::Both, &scope, &mut retried)? + } else { + let scope = scope_text(round, Role::Reviewer, &diff, None, &[]); + let (reviewed, state) = + session_with_retry(ctx, input, round, Role::Reviewer, &scope, &mut retried)?; + let proofs = proofs_for(&state, &reviewed, Role::Reviewer); + match round_logic::judge_round(&reviewed, &proofs) { + Verdict::Failed(reason) => return Err(Some(reason)), + Verdict::Clean => (reviewed, state), + Verdict::Findings { .. } => { + let text = reviewed + .report + .as_deref() + .and_then(|id| report_text(&state, id)) + .unwrap_or_default(); + let report = dir.join("reviewer-report.md"); + std::fs::write(&report, reviewer_brief(&text, &reviewed)) + .map_err(|err| Some(format!("could not write {}: {err}", report.display())))?; + let scope = scope_text(round, Role::Fixer, &diff, Some(&report), brief); + let (mut fixed, state) = + session_with_retry(ctx, input, round, Role::Fixer, &scope, &mut retried)?; + round_logic::hold_reviewer_counts( + &mut fixed.review, + reviewed.review.critical, + reviewed.review.warning, + ); + (fixed, state) + } + } + }; + let role = outcome.role; + let proofs = proofs_for(&state, &outcome, role); + let verdict = round_logic::judge_round(&outcome, &proofs); + if let Verdict::Failed(reason) = &verdict { + return Err(Some(reason.clone())); + } + Ok(Played { + outcome, + verdict, + retried, + started, + strength, + }) +} + +fn titles(findings: &[Finding]) -> Vec { + findings.iter().map(|f| f.title.clone()).collect() +} + +fn entry_of(round: u32, played: &Played) -> RoundEntry { + let review: &RoundReview = &played.outcome.review; + RoundEntry { + n: round, + critical: review.critical, + warning: review.warning, + suggestion: review.suggestion, + fixed: titles(&review.fixed), + left_open: titles(&review.unfixed), + commit: None, + tests: played + .outcome + .tests + .as_ref() + .map_or_else(String::new, |t| t.summary.clone()), + started: played.started.clone(), + ended: clock(), + strength: played.strength.clone(), + retried: played.retried, + } +} + +fn snapshot(input: &RoundsInput) -> Result { + round_boundary::snapshot(&input.project) +} + +/// Run the phase's extra rounds. Never commits and never marks anything. +pub fn run_rounds(ctx: &Ctx, input: &RoundsInput) -> RoundsEnd { + let cap = input.cap.clamp(1, MAX_ROUNDS); + let mut entries: Vec = Vec::new(); + // Where the phase's own work ended: round 1 reviews start to here. + let mut round_before = match snapshot(input) { + Ok(boundary) => boundary, + Err(reason) => { + return RoundsEnd::Failed { + reason: format!("the phase's work could not be recorded ({reason})"), + rounds: entries, + } + } + }; + let mut from = input.start.clone(); + let mut to = round_before.clone(); + let mut round = 1; + loop { + banner(ctx, round, cap); + let played = match play_round(ctx, input, round, &from, &to) { + Ok(played) => played, + Err(None) => return RoundsEnd::Person { rounds: entries }, + Err(Some(reason)) => { + return RoundsEnd::Failed { + reason, + rounds: entries, + } + } + }; + entries.push(entry_of(round, &played)); + loop_driver::keep_rounds(ctx, &entries); + let stop_now = loop_driver::stop_requested(ctx); + let view = RunView { + round, + cap, + rounds_run: round, + suggestions_on: false, + suggestions_pending: false, + batch_done: false, + // The round's one retry is spent inside `session_with_retry`. + retried_this_round: true, + stop_after_round: false, + stop_now, + }; + match round_logic::next_step(&view, &played.verdict) { + Next::StartRound(next) => { + let after = match snapshot(input) { + Ok(boundary) => boundary, + Err(reason) => { + return RoundsEnd::Failed { + reason: format!("the round's work could not be recorded ({reason})"), + rounds: entries, + } + } + }; + // The next round reviews what this one changed. + from = round_before; + to = after.clone(); + round_before = after; + round = next; + } + Next::Stop(StopReason::Person) => return RoundsEnd::Person { rounds: entries }, + Next::Stop(StopReason::Failed(reason)) => { + return RoundsEnd::Failed { + reason, + rounds: entries, + } + } + // A clean round or the cap; the suggestions batch and the final + // check do not exist inside a phase. + Next::Stop(_) | Next::Retry | Next::SuggestionsBatch | Next::FinalCheck => { + let review = &played.outcome.review; + return RoundsEnd::Done(Done { + rounds: entries, + critical: review.critical, + warning: review.warning, + suggestion: review.suggestion, + unfixed: review.unfixed.clone(), + }); + } + } + } +} + +/// The phase agent's report with the last round's counts in place of its own +/// `review.left`, so `judge_outcome` decides on what is left after the rounds. +/// A phase that reported `failed` only for its findings reads as passed once +/// they are gone; the judge still checks the spec, the tests and the rest. +pub fn judged_after(mut outcome: loop_driver::Outcome, done: &Done) -> loop_driver::Outcome { + let mut review = outcome.review.take().unwrap_or_default(); + review.ran = true; + review.recheck = true; + review.left = Left { + critical: done.critical, + warning: done.warning, + suggestion: done.suggestion, + }; + // The agent's own Critical and Warning entries are replaced by the last + // round's; Suggestions it left stay. The round's list has no levels: its + // first `critical` entries read as Critical, the rest as Warning. + review.unfixed.retain(|f| f.level == FixLevel::Suggestion); + let mut critical_left = done.critical; + for finding in &done.unfixed { + let level = if critical_left > 0 { + critical_left -= 1; + FixLevel::Critical + } else { + FixLevel::Warning + }; + review.unfixed.push(PhaseFinding { + level, + title: finding.title.clone(), + file: finding.file.clone(), + reason: None, + }); + } + outcome.review = Some(review); + if outcome.result == "failed" && outcome.reason.as_deref() == Some("findings") { + outcome.result = "passed".to_string(); + outcome.reason = None; + } + outcome +} diff --git a/plan2code-app/src-tauri/src/review_loop.rs b/plan2code-app/src-tauri/src/review_loop.rs new file mode 100644 index 0000000..ba3f82e --- /dev/null +++ b/plan2code-app/src-tauri/src/review_loop.rs @@ -0,0 +1,4868 @@ +//! The Review Loop's driver: rounds of review and fix, each in a fresh agent +//! session, the app judging what every round reports. The agent reviews and +//! fixes and reports (`roundOutcome`); only this module stages, commits and +//! records boundaries, so the agent never runs git (NFR-3). The run record +//! lives in memory alone: an app restart ends the run (NFR-5). +//! +//! The rules are in `round_logic` (judging, the next step, the commit subject) +//! and the boundaries in `round_boundary`; this module is the part with an +//! agent, git, files and a clock in it. A round runs in one session (`both`, +//! for an agent that can start a helper) or in two (a `reviewer` session, then +//! a `fixer` one that never saw the review: FR-17). A crashed, silent or failed +//! session gets one fresh retry one strength up; the second failure stops the +//! run with the rounds that finished kept (FR-3). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +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::Value; + +use crate::agent_manager::{AgentManager, AgentState}; +use crate::agents::Agent; +#[cfg(not(test))] +use crate::console_supervisor::find_console_dir; +use crate::loop_commit; +use crate::loop_driver::{ + self, Hooks, Launch, Limits, LoopSlot, LoopStateEvent, RoundCount, StopCause, Strength, +}; +use crate::loop_notify::NotifyKind; +use crate::loop_report::{EntryKind, EntryResult, LoopReport, ReportEntry, RoundEntry}; +use crate::loop_shared::report_list; +use crate::loop_shared::retry::next_strength_word; +use crate::loop_shared::rounds::{ + finding_line, page_is_this_round, proofs_for, report_text, reviewer_brief, + round_outcome_in as outcome_for_round, +}; +use crate::loop_shared::session::{read_session_state, start_session, Ctx}; +use crate::loop_shared::watch::{silence_expired, watch_loop, WatchStep}; +use crate::loop_tools; +use crate::models::StrengthRow; +use crate::review_report::review_report_markdown; +use crate::round_boundary::{self, Boundary}; +use crate::round_logic::{ + self, Finding, Next, Role, RoundOutcome, RoundReview, RoundTests, RunView, StopReason, Verdict, + MAX_ROUNDS, +}; +use crate::session_reader; + +// ---------------------------------------------------------------- the setup + +/// What the person asked a run to review. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ReviewScope { + Branch, + Uncommitted, + Spec, +} + +impl ReviewScope { + pub fn word(self) -> &'static str { + match self { + ReviewScope::Branch => "branch", + ReviewScope::Uncommitted => "uncommitted", + ReviewScope::Spec => "spec", + } + } +} + +/// Whether the run commits each round or only measures it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Commit, + Snapshot, +} + +/// How a round runs: one session with a helper reviewing, or two sessions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Shape { + OneSession, + TwoSession, +} + +/// The Start screen's picks, plus the notification the Implementation Loop's +/// setup holds (read by the app, never taken from the page). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReviewSetup { + pub scope: ReviewScope, + /// The spec folder (`specs/`) for the `spec` scope. + pub spec: Option, + /// Rounds before the run stops at its cap, 1 to 6. + pub cap: u32, + /// Commit each round (off: snapshot mode). + pub commit: bool, + /// The person agreed to commit their uncommitted work first. + pub pre_run_commit_agreed: bool, + /// Fix the collected Suggestions in one batch after the run. + pub suggestions: bool, + /// The strength every round runs on; `None` runs on the launch choice. + pub strength: Option, + pub silence_minutes: u32, + pub notify_rounds: bool, + pub notify_kind: NotifyKind, + pub notify_url: String, + pub notify_param: String, +} + +impl Default for ReviewSetup { + fn default() -> Self { + ReviewSetup { + scope: ReviewScope::Branch, + spec: None, + cap: 3, + commit: true, + pre_run_commit_agreed: false, + suggestions: false, + strength: None, + silence_minutes: 20, + notify_rounds: false, + notify_kind: NotifyKind::default(), + notify_url: String::new(), + notify_param: String::new(), + } + } +} + +// -------------------------------------------------------------- the record + +/// What the banner says a round is doing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReviewStep { + Starting, + Reviewing, + Fixing, + Testing, + Committing, +} + +impl ReviewStep { + pub fn label(self) -> &'static str { + match self { + ReviewStep::Starting => "Starting", + ReviewStep::Reviewing => "Reviewing", + ReviewStep::Fixing => "Fixing", + ReviewStep::Testing => "Testing", + ReviewStep::Committing => "Committing", + } + } +} + +/// Which session of the run is going on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + /// A one-session round. + Both, + /// A two-session round's reviewer. + Reviewer, + /// A two-session round's fixer. + Fixer, + /// The Suggestions batch: a fixer on the collected Suggestions. + Batch, + /// The final check: one fresh reviewer on the batch's diff. + Final, +} + +impl Stage { + pub fn role(self) -> Role { + match self { + Stage::Both => Role::Both, + Stage::Reviewer | Stage::Final => Role::Reviewer, + Stage::Fixer | Stage::Batch => Role::Fixer, + } + } + + fn word(self) -> &'static str { + match self { + Stage::Both => "both", + Stage::Reviewer => "reviewer", + Stage::Fixer => "fixer", + Stage::Batch => "batch", + Stage::Final => "final", + } + } +} + +/// One finished round, for the report and the banner. +#[derive(Clone, Debug, Default)] +pub struct RoundRecord { + pub n: u32, + /// Where the round ended: the next round's diff starts here. + pub boundary: Option, + pub strength: Option, + pub model: Option, + pub effort: Option, + pub started_at: String, + pub ended_at: String, + pub retried: bool, + /// The retry could not go a strength up (already Best, or not mapped). + pub could_not_step_up: bool, + pub verdict: Option, + pub critical: u32, + pub warning: u32, + pub suggestion: u32, + pub fixed: Vec, + pub unfixed: Vec, + pub suggestions: Vec, + pub tests: Option, + pub commit: Option, + pub summary: String, +} + +/// The Suggestions batch and its final check, kept apart from the rounds. +#[derive(Clone, Debug, Default)] +pub struct BatchRecord { + /// How many rounds had finished when the batch began: orders it among them. + pub after_rounds: usize, + /// The Suggestions the fixer was briefed with. + pub briefed: Vec, + /// Where the run stood before the batch: the final check's diff starts here. + pub before: Option, + pub boundary: Option, + pub verdict: Option, + pub commit: Option, + pub summary: String, + pub final_check: Option, + pub final_critical: u32, + pub final_warning: u32, +} + +/// What Stop now left behind: the partial changes of the stopped round. +#[derive(Clone, Debug, Default)] +pub struct Partial { + /// The diff from the last finished boundary to a snapshot taken at the stop. + pub diff: PathBuf, + pub files: u32, + pub added: u32, + pub removed: u32, + /// Files that did not exist at the boundary: what Discard may delete. + pub new_files: Vec, + /// Still to be kept or discarded. + pub pending: bool, +} + +static NEXT_RUN: AtomicU64 = AtomicU64::new(1); + +/// One Review Loop run, with the overview's run-record fields and the live +/// fields the watcher needs. +#[derive(Clone, Debug)] +pub struct ReviewRun { + /// Tells a watch thread whether the record is still its own run's. + pub run_id: u64, + pub id: String, + pub project: PathBuf, + pub setup: ReviewSetup, + pub scope: ReviewScope, + pub cap: u32, + pub mode: Mode, + pub shape: Shape, + pub launch: Launch, + /// Full id of the "Work before Review Loop" commit, when one was made. + pub pre_run_commit: Option, + pub start: Boundary, + pub rounds: Vec, + pub suggestions_batch: Option, + /// Batches from before a Continue, kept for the report. + pub earlier_batches: Vec, + pub stop_reason: Option, + pub stop_evidence: Option, + /// The round the run stopped in; `round` moves on with a sign-off's fix. + pub stop_round: u32, + // ---- live + /// The run's folder under the console home: scope files, diffs, reports. + pub run_dir: PathBuf, + /// False once the run has stopped (it is kept for Continue and the report). + pub running: bool, + pub round: u32, + pub stage: Stage, + pub step: ReviewStep, + pub sid: Option, + pub last_sid: Option, + pub generation: u64, + pub started_at: Instant, + pub started_at_ms: u64, + /// When the current session started, for the "console never opened" wait. + pub session_started_at: Instant, + pub last_activity: SystemTime, + pub activity_checked: Instant, + pub stop_after_round: bool, + pub stop_now: bool, + /// The current round's one retry is used. + pub retried: bool, + pub retries_used: u32, + /// The round in progress. + pub cur: RoundRecord, + pub strength_rows: BTreeMap, + pub cur_strength: Option, + /// Suggestions collected across rounds (FR-19). + pub collected: Vec, + pub reviewer_report: Option, + /// The files the current round's reviewer was shown. + pub reviewed_files: Vec, + /// The files the person's scope named when the run began. + pub scope_files: Vec, + pub scope_base: Option, + /// What the run was going to stop for when the Suggestions batch began. + pub pending_stop: Option, + pub batch_done: bool, + pub partial: Option, + pub notify_failure: Option, + /// A page announced for the session that holds no lock yet. + pub page_candidate: Option, + /// What the person picked at sign-off, and how the squash went. + pub signoff: Option, + /// A sign-off's Suggestions fix is running: its end finishes the sign-off. + pub signing: bool, + pub signed_off: bool, + /// The report written into the spec folder, kept so sign-off rewrites it. + pub report_file: Option, +} + +/// How the sign-off's squash of the round commits went. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Squash { + /// Not asked for. + Off, + /// Done: the one commit that replaced this many commits of the run. + Done { commit: String, commits: usize }, + /// Refused or failed, with the words the person reads. + Refused(String), +} + +/// What the sign-off did, for the report and the finished screen. +#[derive(Clone, Debug)] +pub struct SignOff { + /// The Suggestions the person ticked. + pub picked: Vec, + /// The Suggestions they left. + pub left: Vec, + pub squash_asked: bool, + pub squash: Squash, + /// Why the picked Suggestions were not all fixed, when they were not. + pub problem: Option, +} + +pub type ReviewSlot = Arc>>; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn epoch_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| u64::try_from(d.as_millis()).unwrap_or(0)) + .unwrap_or(0) +} + +fn clock() -> String { + chrono::Local::now().format("%Y-%m-%d %H:%M").to_string() +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Whether the loop's agent can start a helper from inside a session. +pub(crate) fn agent_helpers(agent: &Agent) -> bool { + matches!(agent, Agent::Builtin(entry) if entry.helpers) +} + +/// A session that never opened its console counts as crashed after this long. +const NOTICE_WAIT: Duration = Duration::from_secs(180); + +impl ReviewRun { + #[allow(clippy::too_many_arguments)] + pub fn new( + project: PathBuf, + setup: ReviewSetup, + launch: Launch, + mode: Mode, + shape: Shape, + start: Boundary, + run_dir: PathBuf, + strength_rows: BTreeMap, + ) -> ReviewRun { + let now = Instant::now(); + let run_id = NEXT_RUN.fetch_add(1, Ordering::SeqCst); + ReviewRun { + run_id, + id: format!("review-{}-{run_id}", epoch_ms()), + project, + scope: setup.scope, + cap: setup.cap.clamp(1, MAX_ROUNDS), + cur_strength: setup.strength, + setup, + mode, + shape, + launch, + pre_run_commit: None, + start, + rounds: Vec::new(), + suggestions_batch: None, + earlier_batches: Vec::new(), + stop_reason: None, + stop_evidence: None, + stop_round: 0, + run_dir, + running: true, + round: 1, + stage: Stage::Both, + step: ReviewStep::Starting, + sid: None, + last_sid: None, + generation: 0, + started_at: now, + started_at_ms: epoch_ms(), + session_started_at: now, + last_activity: SystemTime::now(), + activity_checked: now, + stop_after_round: false, + stop_now: false, + retried: false, + retries_used: 0, + cur: RoundRecord::default(), + strength_rows, + collected: Vec::new(), + reviewer_report: None, + reviewed_files: Vec::new(), + scope_files: Vec::new(), + scope_base: None, + pending_stop: None, + batch_done: false, + partial: None, + notify_failure: None, + page_candidate: None, + signoff: None, + signing: false, + signed_off: false, + report_file: None, + } + } + + /// The boundary before round `n` began: the run's start, or where the + /// round before it ended. + fn boundary_before(&self, n: u32) -> Boundary { + n.checked_sub(2) + .and_then(|at| self.rounds.get(at as usize)) + .and_then(|round| round.boundary.clone()) + .unwrap_or_else(|| self.start.clone()) + } + + /// The Critical and Warning findings still open: every round's unfixed + /// ones that no later round fixed. A later round reviews only the fix + /// diff, so a clean one never clears what an earlier round left. + pub fn open_findings(&self) -> Vec { + let same = |a: &Finding, b: &Finding| a.title == b.title && a.file == b.file; + let mut open: Vec = Vec::new(); + for round in &self.rounds { + open.retain(|left| !round.fixed.iter().any(|fixed| same(left, fixed))); + for finding in &round.unfixed { + if !open.iter().any(|left| same(left, finding)) { + open.push(finding.clone()); + } + } + } + open + } + + /// Where the last finished round ended (or the start). + pub fn last_boundary(&self) -> Boundary { + // The newest committed work: a Suggestions batch counts after the + // rounds that had finished when it ran, and before any later round + // (a Continue starts a round after a finished batch). + let round = self + .rounds + .iter() + .enumerate() + .rev() + .find_map(|(i, round)| round.boundary.clone().map(|b| (i, b))); + let batch = self + .suggestions_batch + .iter() + .chain(self.earlier_batches.iter().rev()) + .find_map(|batch| batch.boundary.clone().map(|b| (batch.after_rounds, b))); + match (round, batch) { + (Some((i, round)), Some((after, batch))) => { + if after > i { + batch + } else { + round + } + } + (Some((_, round)), None) => round, + (None, Some((_, batch))) => batch, + (None, None) => self.start.clone(), + } + } + + fn view(&self, round: u32) -> RunView { + RunView { + round, + cap: self.cap, + rounds_run: u32::try_from(self.rounds.len()).unwrap_or(u32::MAX), + suggestions_on: self.setup.suggestions, + suggestions_pending: !self.collected.is_empty(), + batch_done: self.batch_done, + retried_this_round: self.retried, + stop_after_round: self.stop_after_round, + stop_now: self.stop_now, + } + } +} + +// ----------------------------------------------------------------- events + +/// The banner's state for a Review Loop (`kind: "rounds"`). +pub fn review_state_event(run: &ReviewRun) -> LoopStateEvent { + let (critical, warning) = run + .rounds + .last() + .map_or((0, 0), |round| (round.critical, round.warning)); + let strength = run.cur_strength.map(|word| word.word().to_string()); + let row = run + .cur_strength + .and_then(|word| run.strength_rows.get(word.word())); + // The Suggestions batch and the final check come after the rounds: they + // are named for what they are, and never read as a round past the cap. + let after_rounds = match run.stage { + Stage::Batch => "Suggestions batch", + Stage::Final => "Final check", + _ => "", + }; + let (shown, detail) = if after_rounds.is_empty() { + ( + run.round, + round_logic::round_detail(run.round, run.cap, run.step.label(), critical, warning), + ) + } else { + ( + run.round.min(run.cap), + format!("{after_rounds}: {}", run.step.label()), + ) + }; + LoopStateEvent { + running: run.running, + spec_name: run + .setup + .spec + .as_deref() + .map_or_else(|| run.scope.word().to_string(), |spec| spec.to_string()), + phase: shown, + phases: run.cap, + phase_name: detail, + previous_phase: None, + previous_committed: false, + phase_retried: run.retried, + step: run.step.label().to_string(), + started_at_ms: run.started_at_ms, + retries_used: run.retries_used, + stop_after_phase: run.stop_after_round, + stopping: run.stop_now, + can_stop_after: run.running && run.round < run.cap, + strength, + model: row.map(|r| r.model.clone()), + effort: row.and_then(|r| r.effort.clone()), + kind: "rounds", + round: shown, + rounds: run.cap, + round_counts: run + .rounds + .iter() + .map(|round| RoundCount { + critical: round.critical, + warning: round.warning, + }) + .collect(), + stop_after_round: run.stop_after_round, + after_rounds, + } +} + +/// The running Review Loop's banner state, or `None` when none runs. +pub fn current_event(slot: &ReviewSlot) -> Option { + lock(slot) + .as_ref() + .filter(|run| run.running) + .map(review_state_event) +} + +/// Whether a Review Loop is running (a stopped run waiting for Continue or +/// the report is not). +pub fn is_running(slot: &ReviewSlot) -> bool { + lock(slot).as_ref().is_some_and(|run| run.running) +} + +/// Forget the run without a word to the page: the app is quitting. +pub fn abandon(slot: &ReviewSlot) { + *lock(slot) = None; +} + +// ------------------------------------------------------------- the context + +/// What the watch thread needs: the run's slot and the shared session context. +#[derive(Clone)] +pub struct RoundCtx { + pub slot: ReviewSlot, + pub ctx: Ctx, +} + +fn with_run(rc: &RoundCtx, f: impl FnOnce(&mut ReviewRun) -> R) -> Option { + let mut guard = lock(&rc.slot); + guard + .as_mut() + .filter(|run| run.run_id == rc.ctx.run_id) + .map(f) +} + +fn emit(rc: &RoundCtx) { + let event = with_run(rc, |run| review_state_event(run)); + if let Some(event) = event { + (rc.ctx.hooks.emit)(event); + } +} + +/// The console the end screen is posted to. A test never reaches the real +/// one (it would post to, and resume sessions in, the person's console). +fn console_dir() -> PathBuf { + #[cfg(test)] + { + PathBuf::from(".") + } + #[cfg(not(test))] + { + find_console_dir().unwrap_or_else(|_| PathBuf::from(".")) + } +} + +fn new_ctx( + run: &ReviewRun, + agent: Arc, + home: PathBuf, + hooks: Hooks, + limits: Limits, +) -> Ctx { + Ctx { + // The Review Loop keeps its own slot; this one only fills the field + // the shared session code carries for the Implementation Loop. + slot: Arc::new(Mutex::new(None)), + agent, + console_dir: console_dir(), + home, + launch: run.launch.clone(), + run_id: run.run_id, + hooks: Arc::new(hooks), + limits, + } +} + +// ------------------------------------------------------------ git helpers + +fn git_cmd(project: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(project); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + cmd +} + +/// What `git ` printed, or the first line of why it failed. +fn git_text(project: &Path, args: &[&str]) -> Result { + let out = git_cmd(project, args) + .output() + .map_err(|err| format!("git could not run: {err}"))?; + if !out.status.success() { + let why = String::from_utf8_lossy(&out.stderr) + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or("no reason given") + .to_string(); + return Err(format!("git {} failed: {why}", args.first().unwrap_or(&""))); + } + Ok(String::from_utf8_lossy(&out.stdout).to_string()) +} + +fn lines_of(text: &str) -> Vec { + text.lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(str::to_string) + .collect() +} + +/// Names from `git ... -z` output: NUL-separated, never quoted. +fn nul_lines(text: &str) -> Vec { + text.split('\0') + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect() +} + +/// The branch the work is measured against: the first of `main`, +/// `origin/main`, `master`, `origin/master` that exists. +fn base_branch(project: &Path) -> Option { + ["main", "origin/main", "master", "origin/master"] + .into_iter() + .find(|name| { + git_text( + project, + &["rev-parse", "--verify", "-q", &format!("{name}^{{commit}}")], + ) + .is_ok() + }) + .map(str::to_string) +} + +/// The files a scope names, and the base branch it measured against: for +/// `branch`, the diff against the base plus staged, unstaged and untracked +/// files; for `uncommitted`, those changed files; for `spec`, the spec folder's +/// files plus the branch diff. +pub fn scope_files( + project: &Path, + scope: ReviewScope, + spec: Option<&str>, +) -> Result<(Option, Vec), String> { + let mut files: Vec = Vec::new(); + let mut base = None; + let uncommitted = |files: &mut Vec| -> Result<(), String> { + files.extend(loop_tools::git_status_porcelain(project)?); + Ok(()) + }; + let against_base = |files: &mut Vec, base: &mut Option| -> Result<(), String> { + // Counting only untracked files would hide every commit on the + // branch, so no trunk is an error, as `review-scope.mjs` says. A + // repository with no commits yet has nothing committed to miss. + let has_head = git_text(project, &["rev-parse", "--verify", "-q", "HEAD"]).is_ok(); + match base_branch(project) { + Some(name) => { + let found = git_text(project, &["merge-base", "HEAD", &name]) + .map_err(|e| format!("The branch could not be compared with {name}: {e}"))?; + let point = found.trim().to_string(); + if !point.is_empty() { + files.extend(nul_lines(&git_text( + project, + &["diff", "--name-only", "-z", "--no-renames", &point], + )?)); + *base = Some(name); + } + } + None if has_head => { + return Err( + "There is no main or master branch (local or origin) to compare this branch with." + .to_string(), + ); + } + None => {} + } + files.extend(lines_of(&git_text( + project, + &["ls-files", "--others", "--exclude-standard"], + )?)); + Ok(()) + }; + match scope { + ReviewScope::Uncommitted => uncommitted(&mut files)?, + ReviewScope::Branch => against_base(&mut files, &mut base)?, + ReviewScope::Spec => { + let spec = spec.ok_or("A spec scope needs a spec folder.")?; + let folder = project.join(spec); + if !folder.is_dir() { + return Err(format!("{spec} is not a folder in this project.")); + } + against_base(&mut files, &mut base)?; + if let Ok(entries) = std::fs::read_dir(&folder) { + for entry in entries.flatten() { + if entry.path().is_file() { + files.push(format!( + "{}/{}", + spec.trim_end_matches('/'), + entry.file_name().to_string_lossy() + )); + } + } + } + } + } + files.sort(); + files.dedup(); + Ok((base, files)) +} + +// ------------------------------------------------------- the scope and prompt + +/// Everything a round's scope file says. +struct ScopeInput<'a> { + round: u32, + stage: Stage, + scope: ReviewScope, + spec: Option<&'a str>, + base: Option<&'a str>, + files: &'a [String], + diff: Option<&'a Path>, + report: Option<&'a Path>, + brief: &'a [Finding], +} + +/// The text of a round's scope file. +fn scope_text(input: &ScopeInput) -> String { + let mut text = format!( + "# Review Loop round {} scope\n\nRole: {}\n", + input.round, + input.stage.role_word() + ); + if let Some(diff) = input.diff { + text.push_str(&format!( + "\nReview exactly this diff, the previous round's changes, and nothing else:\n\n- {}\n", + diff.display() + )); + } else if input.stage == Stage::Batch { + text.push_str("\nFix these Suggestions and nothing else:\n\n"); + for finding in input.brief { + text.push_str(&finding_line(finding)); + text.push('\n'); + } + } else { + text.push_str(&format!("\nScope: {}\n", input.scope.word())); + if let Some(spec) = input.spec { + text.push_str(&format!("Spec folder: {spec}\n")); + } + if let Some(base) = input.base { + text.push_str(&format!("Base branch: {base}\n")); + } + text.push_str("\nFiles:\n\n"); + for file in input.files { + text.push_str(&format!("- {file}\n")); + } + } + if let Some(report) = input.report { + text.push_str(&format!( + "\nThe reviewer's report (fix its Critical and Warning findings):\n\n- {}\n", + report.display() + )); + } + text +} + +impl Stage { + fn role_word(self) -> &'static str { + match self.role() { + Role::Both => "both", + Role::Reviewer => "reviewer", + Role::Fixer => "fixer", + } + } +} + +/// A path as the agent's prompt carries it: quoted when it holds a space. +fn quoted(path: &Path) -> String { + let text = path.display().to_string(); + if text.contains(char::is_whitespace) { + format!("\"{text}\"") + } else { + text + } +} + +/// The prompt a round's session starts on. +pub fn round_prompt(round: u32, role: Role, scope_file: &Path) -> String { + let role = match role { + Role::Both => "both", + Role::Reviewer => "reviewer", + Role::Fixer => "fixer", + }; + format!( + "/plan2code-review --web --loop --round {round} --role {role} --scope-file {}", + quoted(scope_file) + ) +} + +/// Suggestions kept across rounds (FR-19): the new round's are added, a repeat +/// (same file and title) is dropped, one whose file and line a round fixed is +/// dropped, and an earlier one about a file the latest reviewer was shown but +/// did not report again is dropped. +pub fn merge_suggestions( + collected: &[Finding], + new: &[Finding], + fixed: &[Finding], + reviewed_files: &[String], +) -> Vec { + let was_fixed = |finding: &Finding| { + fixed + .iter() + .any(|f| f.file == finding.file && f.line.is_some() && f.line == finding.line) + }; + let same = |a: &Finding, b: &Finding| a.file == b.file && a.title == b.title; + let mut kept: Vec = collected + .iter() + .filter(|old| { + !was_fixed(old) + && (new.iter().any(|n| same(n, old)) + || !reviewed_files.iter().any(|file| file == &old.file)) + }) + .cloned() + .collect(); + for finding in new { + if !was_fixed(finding) && !kept.iter().any(|k| same(k, finding)) { + kept.push(finding.clone()); + } + } + kept +} + +/// The files a unified diff touches, from its `+++ b/` lines. +fn diff_files(diff: &Path) -> Vec { + let Ok(text) = std::fs::read_to_string(diff) else { + return Vec::new(); + }; + let mut files: Vec = text + .lines() + .filter_map(|line| line.strip_prefix("+++ b/")) + .map(str::to_string) + .collect(); + files.sort(); + files.dedup(); + files +} + +// ------------------------------------------------------------ starting a run + +fn is_dirty(project: &Path) -> Result { + Ok(!loop_tools::git_status_porcelain(project)?.is_empty()) +} + +/// Stage by name and commit what changed since `before` (everything, with an +/// empty list), through the same checks a phase's commit takes. `Ok(None)` +/// when nothing changed; otherwise the new commit's full id. +fn commit_all( + project: &Path, + subject: &str, + limit: Duration, +) -> Result, (String, String)> { + match loop_commit::stage_and_check(project, Some(&[])) { + Ok(()) => {} + Err(loop_commit::StageError::Add(failure)) => { + return Err((failure.first_line, failure.output)); + } + Err(loop_commit::StageError::Problem(problem)) => { + let files = problem.files.join(", "); + let line = format!("{} {}", files, problem.why); + return Err((line.clone(), line)); + } + } + let staged = loop_tools::git_staged(project).map_err(|e| (e.clone(), e))?; + if staged.is_empty() { + return Ok(None); + } + let message = match loop_tools::commit_message(project, subject) { + Ok(message) => message, + Err(e) => { + // Nothing is committed: the files this run staged come out again. + loop_commit::unstage(project); + return Err((e.clone(), e)); + } + }; + let done = loop_tools::git_commit_with(project, &message, limit); + if !done.ok { + loop_commit::unstage(project); + return Err((loop_commit::first_line(&done.output), done.output)); + } + loop_tools::git_head_full(project) + .map(Some) + .map_err(|e| (e.clone(), e)) +} + +/// Check the setup, make the pre-run commit when agreed, and take the start +/// boundary: everything a run needs before round 1. +pub fn prepare_run( + project: &Path, + launch: &Launch, + setup: ReviewSetup, + home: &Path, +) -> Result { + if !(1..=MAX_ROUNDS).contains(&setup.cap) { + return Err(format!("The round cap is 1 to {MAX_ROUNDS}.")); + } + if setup.scope == ReviewScope::Spec { + let spec = setup + .spec + .as_deref() + .ok_or("A spec scope needs a spec folder.")?; + loop_driver::validate_spec(project, spec)?; + } + let (base, files) = scope_files(project, setup.scope, setup.spec.as_deref())?; + let mode = if setup.commit { + Mode::Commit + } else { + Mode::Snapshot + }; + let shape = if agent_helpers(&launch.0) { + Shape::OneSession + } else { + Shape::TwoSession + }; + let mut pre_run_commit = None; + if mode == Mode::Commit && is_dirty(project)? { + if !setup.pre_run_commit_agreed { + return Err( + "Your project has uncommitted changes. Agree to commit them first, or turn commits off." + .to_string(), + ); + } + match commit_all( + project, + "Work before Review Loop", + Duration::from_secs(10 * 60), + ) { + Ok(id) => pre_run_commit = id, + Err((line, _)) => { + return Err(format!("The work before the run was not committed: {line}")) + } + } + } + let start = match mode { + Mode::Commit => round_boundary::head(project)?, + Mode::Snapshot => round_boundary::snapshot(project)?, + }; + let rows = if setup.strength.is_some() { + loop_driver::strength_rows_for(&launch.0) + } else { + BTreeMap::new() + }; + let mut run = ReviewRun::new( + project.to_path_buf(), + setup, + launch.clone(), + mode, + shape, + start, + PathBuf::new(), + rows, + ); + run.run_dir = home.join("review-loop").join(&run.id); + run.pre_run_commit = pre_run_commit; + run.scope_files = files; + run.scope_base = base; + Ok(run) +} + +/// Start a Review Loop: refuse while any loop runs, prepare the run, store it +/// and start round 1; a watch thread follows it. +pub fn start_review_loop( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + launch: Launch, + project: PathBuf, + setup: ReviewSetup, + hooks: Hooks, +) -> Result<(), String> { + let home = session_reader::console_home().ok_or("no home folder found")?; + start_review_loop_with( + slot, + phases, + agent, + launch, + project, + setup, + hooks, + Limits::default(), + home, + true, + ) +} + +/// `start_review_loop` with the console home and the watcher's timing given, +/// and the watch thread optional: a test starts a run and plays the watcher +/// itself. +#[allow(clippy::too_many_arguments)] +pub fn start_review_loop_with( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + launch: Launch, + project: PathBuf, + setup: ReviewSetup, + hooks: Hooks, + limits: Limits, + home: PathBuf, + watch: bool, +) -> Result<(), String> { + if loop_driver::is_running(phases) || is_running(slot) { + return Err("A loop is already running in this window.".to_string()); + } + let run = prepare_run(&project, &launch, setup, &home)?; + if run.scope_files.is_empty() { + return Err("There is nothing to review in that scope.".to_string()); + } + let rc = RoundCtx { + slot: Arc::clone(slot), + ctx: new_ctx(&run, agent, home, hooks, limits), + }; + { + let mut guard = lock(slot); + if guard.as_ref().is_some_and(|held| held.running) { + return Err("A loop is already running in this window.".to_string()); + } + *guard = Some(run); + } + let first = with_run(&rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both); + if let Err(e) = start_stage(&rc, first, 1) { + *lock(slot) = None; + (rc.ctx.hooks.emit)(LoopStateEvent::ended()); + return Err(e); + } + if watch { + thread::spawn(move || watcher(rc)); + } + Ok(()) +} + +fn first_stage(shape: Shape) -> Stage { + match shape { + Shape::OneSession => Stage::Both, + Shape::TwoSession => Stage::Reviewer, + } +} + +// ------------------------------------------------------ starting a session + +/// What a session's scope file needs, copied out so git runs outside the lock. +struct Plan { + project: PathBuf, + scope: ReviewScope, + spec: Option, + base: Option, + files: Vec, + diff: Option<(Boundary, Boundary)>, + reviewer_report: Option, + brief: Vec, + dir: PathBuf, + prompt_round: u32, + strength: Option<(Strength, StrengthRow)>, +} + +fn plan_for(run: &ReviewRun, stage: Stage, round: u32) -> Plan { + let diff = match stage { + Stage::Both | Stage::Reviewer | Stage::Fixer if round >= 2 => { + // The round being started ends where the last finished work did, so + // a Suggestions batch committed before a Continue is in its diff. + let to = if usize::try_from(round).ok() == Some(run.rounds.len() + 1) { + run.last_boundary() + } else { + run.boundary_before(round) + }; + Some((run.boundary_before(round - 1), to)) + } + Stage::Final => run + .suggestions_batch + .as_ref() + .and_then(|batch| Some((batch.before.clone()?, batch.boundary.clone()?))), + _ => None, + }; + let brief = if stage == Stage::Batch { + run.collected.clone() + } else { + Vec::new() + }; + let name = format!("round-{round}-{}-t{}", stage.word(), run.retries_used); + Plan { + project: run.project.clone(), + scope: run.scope, + spec: run.setup.spec.clone(), + base: run.scope_base.clone(), + files: run.scope_files.clone(), + diff, + reviewer_report: (stage == Stage::Fixer) + .then(|| run.reviewer_report.clone()) + .flatten(), + brief, + dir: run.run_dir.join(name), + prompt_round: round, + strength: run.cur_strength.and_then(|word| { + run.strength_rows + .get(word.word()) + .map(|row| (word, row.clone())) + }), + } +} + +/// Write the scope file (and the diff and reviewer report it names) and start +/// the stage's session. The prompt names the round, the role and the file. +fn start_stage(rc: &RoundCtx, stage: Stage, round: u32) -> Result<(), String> { + let plan = + with_run(rc, |run| plan_for(run, stage, round)).ok_or("The Review Loop has ended.")?; + std::fs::create_dir_all(&plan.dir) + .map_err(|err| format!("could not make {}: {err}", plan.dir.display()))?; + let mut diff_path = None; + let mut touched = Vec::new(); + if let Some((from, to)) = &plan.diff { + let name = if stage == Stage::Final { + "batch.diff".to_string() + } else { + format!("round-{}.diff", round - 1) + }; + let path = plan.dir.join(name); + round_boundary::diff(&plan.project, from, to, &path)?; + touched = diff_files(&path); + diff_path = Some(path); + } + let report_path = match &plan.reviewer_report { + Some(text) => { + let path = plan.dir.join("reviewer-report.md"); + std::fs::write(&path, text) + .map_err(|err| format!("could not write {}: {err}", path.display()))?; + Some(path) + } + None => None, + }; + let text = scope_text(&ScopeInput { + round, + stage, + scope: plan.scope, + spec: plan.spec.as_deref(), + base: plan.base.as_deref(), + files: &plan.files, + diff: diff_path.as_deref(), + report: report_path.as_deref(), + brief: &plan.brief, + }); + let scope_file = plan.dir.join("scope.md"); + std::fs::write(&scope_file, text) + .map_err(|err| format!("could not write {}: {err}", scope_file.display()))?; + let prompt = round_prompt(plan.prompt_round, stage.role(), &scope_file); + // A running session (a silent one being retried) is ended first. + rc.ctx.agent.stop(); + let started = start_session( + &rc.ctx, + &prompt, + plan.strength.as_ref().map(|(word, row)| (*word, row)), + )?; + let worked = with_run(rc, |run| { + run.round = round; + run.stage = stage; + run.sid = None; + run.page_candidate = None; + run.generation = started.generation; + run.session_started_at = Instant::now(); + run.last_activity = SystemTime::now(); + run.activity_checked = Instant::now(); + run.step = match stage.role() { + Role::Fixer => ReviewStep::Fixing, + _ => ReviewStep::Reviewing, + }; + if !run.retried && matches!(stage, Stage::Both | Stage::Reviewer) { + run.cur = RoundRecord { + n: round, + started_at: clock(), + ..RoundRecord::default() + }; + run.reviewed_files = if touched.is_empty() && round == 1 { + run.scope_files.clone() + } else { + touched.clone() + }; + } + run.cur.strength = run.cur_strength.map(|word| word.word().to_string()); + run.cur.model = started.model.clone(); + run.cur.effort = started.effort.clone(); + run.cur.retried = run.retried; + }); + if worked.is_none() { + rc.ctx.agent.stop(); + return Err("The Review Loop has ended.".to_string()); + } + emit(rc); + Ok(()) +} + +// -------------------------------------------------------------- the watcher + +fn watcher(rc: RoundCtx) { + let panicked = watch_loop(rc.ctx.limits.watch_every, || { + if tick(&rc) { + WatchStep::Continue + } else { + WatchStep::Stop + } + }); + if let Some(text) = panicked { + let text: String = one_line(&text).chars().take(200).collect(); + finish_run( + &rc, + StopReason::Failed(format!("the Review Loop's watcher failed: {text}")), + None, + ); + } +} + +/// What one look needs, copied out so no lock is held while a tool runs. +struct Look { + project: PathBuf, + round: u32, + stage: Stage, + sid: Option, + generation: u64, + stop_now: bool, + running: bool, + last_activity: SystemTime, + activity_due: bool, + waited: Duration, + silence_minutes: u32, + candidate: Option, +} + +fn take_look(rc: &RoundCtx) -> Option { + with_run(rc, |run| Look { + project: run.project.clone(), + round: run.round, + stage: run.stage, + sid: run.sid.clone(), + generation: run.generation, + stop_now: run.stop_now, + running: run.running, + last_activity: run.last_activity, + activity_due: run.activity_checked.elapsed() >= rc.ctx.limits.activity_every, + waited: run.session_started_at.elapsed(), + silence_minutes: run.setup.silence_minutes, + candidate: run.page_candidate.clone(), + }) +} + +/// A page the app took: while a run waits for its round's session, a Review +/// page locked for that round and role is the session. One without the lock +/// yet is kept as a candidate the watch adopts once it shows. +pub fn note_page(slot: &ReviewSlot, workflow: &str, sid: &str, state: &Value) { + if workflow != "review" { + return; + } + if let Some(run) = lock(slot).as_mut().filter(|run| run.running) { + if run.sid.is_some() { + return; + } + if page_is_this_round(state, run.round, run.stage.role()) { + run.sid = Some(sid.to_string()); + run.last_sid = Some(sid.to_string()); + run.last_activity = SystemTime::now(); + run.page_candidate = None; + } else if state.is_object() && state.get("roundOutcome").is_none_or(Value::is_null) { + run.page_candidate = Some(sid.to_string()); + } + } +} + +fn adopt_candidate(rc: &RoundCtx, look: &Look) -> Option { + let candidate = look.candidate.as_deref()?; + let state = read_session_state(&rc.ctx, candidate)?; + if !page_is_this_round(&state, look.round, look.stage.role()) { + return None; + } + with_run(rc, |run| { + if run.sid.is_none() && run.page_candidate.as_deref() == Some(candidate) { + run.sid = Some(candidate.to_string()); + run.last_sid = Some(candidate.to_string()); + run.page_candidate = None; + } + run.sid.clone() + }) + .flatten() +} + +/// The reason the current session's agent ended by itself, if it did. +fn crashed(rc: &RoundCtx, look: &Look) -> Option { + let seen = rc.ctx.agent.snapshot(); + match seen.state { + AgentState::Ended { reason } if seen.generation == look.generation => Some(reason), + _ => None, + } +} + +/// The silence rule's setup: the shared check wants a `LoopSetup`. +fn silence_setup(minutes: u32) -> loop_driver::LoopSetup { + loop_driver::LoopSetup { + silence_minutes: minutes, + ..loop_driver::LoopSetup::default() + } +} + +/// The round's outcome in `state`, when it is this look's round and role. +fn round_outcome_in(state: &Value, look: &Look) -> Option> { + outcome_for_round(state, look.round, look.stage.role()) +} + +/// One look at the running round. Returns false when the run is over. +pub fn tick(rc: &RoundCtx) -> bool { + let Some(look) = take_look(rc) else { + return false; + }; + if !look.running { + return false; + } + if look.stop_now { + stop_now_finish(rc); + return false; + } + let Some(sid) = look.sid.clone().or_else(|| adopt_candidate(rc, &look)) else { + if let Some(reason) = crashed(rc, &look) { + return fail(rc, &look, &StopCause::Crash, &reason); + } + if look.waited > NOTICE_WAIT.max(rc.ctx.limits.notice_wait) { + return fail(rc, &look, &StopCause::NoSession, ""); + } + return true; + }; + let session = match session_reader::load(&rc.ctx.home, &sid) { + Ok(session) => session, + Err(_) => { + if let Some(go) = crash_or_outcome(rc, &look, &sid) { + return go; + } + return silence_check(rc, &look, look.last_activity, None, false); + } + }; + if let Some(found) = round_outcome_in(&session.state, &look) { + return take_outcome(rc, &look, &session.state, found); + } + if let Some(go) = crash_or_outcome(rc, &look, &sid) { + return go; + } + // A round that asks the person a question cannot be answered: it fails. + if let Some(question) = loop_driver::first_open_question(&session.state) { + let reason = format!("the agent asked a question: {}", one_line(&question)); + return settle_failure(rc, &look, reason); + } + observe(rc, session.state["headline"]["stage"].as_str()); + let quiet = session.state["agent"]["quietMinutes"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()); + let mut last = look.last_activity; + if look.activity_due { + last = refresh_activity(rc, &look, &session.dir); + } + silence_check(rc, &look, last, quiet, false) +} + +fn silence_check( + rc: &RoundCtx, + look: &Look, + last: SystemTime, + quiet: Option, + waiting: bool, +) -> bool { + let setup = silence_setup(look.silence_minutes); + if silence_expired(SystemTime::now(), last, &setup, quiet, waiting) { + let minutes = look.silence_minutes.max(quiet.unwrap_or(0)).min(60); + return fail(rc, look, &StopCause::Silence, &minutes.to_string()); + } + true +} + +/// The agent ended by itself: read the session once more before calling it a +/// crash, since an agent that writes its report and exits between two looks +/// must be judged, not retried. +fn crash_or_outcome(rc: &RoundCtx, look: &Look, sid: &str) -> Option { + let reason = crashed(rc, look)?; + if let Ok(session) = session_reader::load(&rc.ctx.home, sid) { + if let Some(found) = round_outcome_in(&session.state, look) { + return Some(take_outcome(rc, look, &session.state, found)); + } + } + Some(fail(rc, look, &StopCause::Crash, &reason)) +} + +fn refresh_activity(rc: &RoundCtx, look: &Look, session_dir: &Path) -> SystemTime { + let newest = loop_driver::newest_work(session_dir, &look.project); + with_run(rc, |run| { + run.activity_checked = Instant::now(); + if let Some(time) = newest.map(loop_driver::clamp_to_now) { + if time > run.last_activity { + run.last_activity = time; + } + } + run.last_activity + }) + .unwrap_or(look.last_activity) +} + +/// Take the banner's step from the page's headline stage. +fn observe(rc: &RoundCtx, stage: Option<&str>) { + let changed = with_run(rc, |run| { + let before = run.step; + if let Some(stage) = stage { + let lower = stage.to_lowercase(); + if lower.contains("test") { + run.step = ReviewStep::Testing; + } else if lower.contains("fix") { + run.step = ReviewStep::Fixing; + } else if lower.contains("review") { + run.step = ReviewStep::Reviewing; + } + } + run.step != before + }); + if changed == Some(true) { + emit(rc); + } +} + +fn cause_text(cause: &StopCause, detail: &str) -> String { + match cause { + StopCause::Crash => format!("the agent crashed ({detail})"), + StopCause::Silence => format!("the agent went silent for {detail} minutes"), + StopCause::NoSession => "the round's console never opened".to_string(), + _ => "the round failed".to_string(), + } +} + +/// A crash, silence or a console that never opened. +fn fail(rc: &RoundCtx, look: &Look, cause: &StopCause, detail: &str) -> bool { + settle_failure(rc, look, cause_text(cause, detail)) +} + +/// A failed round try: one fresh retry a strength up, else the run stops. +fn settle_failure(rc: &RoundCtx, look: &Look, reason: String) -> bool { + // Stop now was pressed since this look began: the ended agent is not a + // crash and nothing is retried. + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + // The final check that fails twice never changes why the run ended: its + // own result is kept apart, and the run stops for the reason it already + // had (FR-19). + if look.stage == Stage::Final { + let original = with_run(rc, |run| { + if !run.retried { + return None; + } + if let Some(batch) = run.suggestions_batch.as_mut() { + batch.final_check = Some(Verdict::Failed(reason.clone())); + } + Some(run.pending_stop.clone().unwrap_or(StopReason::Clean)) + }) + .flatten(); + if let Some(original) = original { + let note = format!("the final check did not finish ({reason})"); + return act( + rc, + Stage::Final, + round_logic::after_final_check(original), + Some(¬e), + ); + } + } + let next = with_run(rc, |run| { + round_logic::next_step(&run.view(look.round), &Verdict::Failed(reason.clone())) + }); + match next { + Some(next) => act(rc, look.stage, next, Some(&reason)), + None => false, + } +} + +// ------------------------------------------------------ handling an outcome + +fn take_outcome( + rc: &RoundCtx, + look: &Look, + state: &Value, + found: Result, +) -> bool { + // Stop now came since this look began: nothing is judged or committed. + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let mut outcome = match found { + Ok(outcome) => outcome, + Err(reason) => { + rc.ctx.agent.stop(); + return settle_failure(rc, look, reason); + } + }; + if look.stage == Stage::Fixer { + let (critical, warning) = + with_run(rc, |run| (run.cur.critical, run.cur.warning)).unwrap_or((0, 0)); + round_logic::hold_reviewer_counts(&mut outcome.review, critical, warning); + } + let role = look.stage.role(); + let proofs = proofs_for(state, &outcome, role); + let verdict = round_logic::judge_round(&outcome, &proofs); + let report = outcome + .report + .as_deref() + .and_then(|id| report_text(state, id)) + .unwrap_or_default(); + // This session's work is read: its agent ends before anything else starts. + rc.ctx.agent.stop(); + match look.stage { + Stage::Both | Stage::Fixer => finish_round(rc, look, &outcome, verdict), + Stage::Reviewer => match verdict { + Verdict::Failed(reason) => settle_failure(rc, look, reason), + Verdict::Clean => finish_round(rc, look, &outcome, verdict), + Verdict::Findings { .. } => { + let brief = reviewer_brief(&report, &outcome); + with_run(rc, |run| { + run.reviewer_report = Some(brief); + // The round has one retry in all: the fixer gets none when + // the reviewer's session used it. + run.cur.critical = outcome.review.critical; + run.cur.warning = outcome.review.warning; + }); + match start_stage(rc, Stage::Fixer, look.round) { + Ok(()) => true, + Err(e) => { + finish_run( + rc, + StopReason::Failed(format!( + "the fixer could not start ({})", + one_line(&e) + )), + Some(e), + ); + false + } + } + } + }, + Stage::Batch => finish_batch(rc, look, &outcome, verdict), + Stage::Final => finish_final(rc, look, &outcome, verdict), + } +} + +/// Commit what a round changed (commit mode) or take a snapshot (snapshot +/// mode), and say where the round ended. A refused or failed commit stops the +/// run as `Failed` with what git or the staged-file check said. +fn close_round( + rc: &RoundCtx, + project: &Path, + mode: Mode, + subject: &str, +) -> Result<(Option, Boundary), (String, String)> { + with_run(rc, |run| run.step = ReviewStep::Committing); + emit(rc); + match mode { + Mode::Snapshot => round_boundary::snapshot(project) + .map(|boundary| (None, boundary)) + .map_err(|e| (e.clone(), e)), + Mode::Commit => { + let commit = commit_all(project, subject, rc.ctx.limits.commit_limit)?; + let boundary = round_boundary::head(project).map_err(|e| (e.clone(), e))?; + Ok((commit, boundary)) + } + } +} + +/// A title as a commit subject takes it: `commit-msg.mjs` refuses a double +/// quote (straight or curly), a backtick, `$`, `!` and a backslash, since shells +/// read them differently inside double quotes, and review titles carry them +/// often (a backticked name). Quotes become `'`, the rest are dropped. +fn safe_title(title: &str) -> String { + title + .chars() + .filter(|c| !matches!(c, '`' | '$' | '!' | '\\')) + .map(|c| { + if c == '"' || ('\u{201C}'..='\u{201F}').contains(&c) { + '\'' + } else { + c + } + }) + .collect::() + .trim() + .to_string() +} + +fn fix_titles(review: &RoundReview, subject: Option<&str>) -> Vec { + let mut titles: Vec = review.fixed.iter().map(|f| safe_title(&f.title)).collect(); + if titles.is_empty() { + titles.extend(subject.map(safe_title)); + } + titles +} + +/// The Suggestions batch's commit subject, fitted to 72 characters with its +/// own prefix (a longer one than a round's). +fn batch_subject(titles: &[String]) -> String { + let subject = + round_logic::round_commit_message(0, titles).replacen("round 0", "Suggestions batch", 1); + if subject.chars().count() <= 72 { + return subject; + } + let cut: String = subject.chars().take(69).collect(); + format!("{}...", cut.trim_end()) +} + +/// A judged round: record it, commit or snapshot it, then take the next step. +fn finish_round(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool { + if let Verdict::Failed(reason) = &verdict { + return settle_failure(rc, look, reason.clone()); + } + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let (mode, round) = with_run(rc, |run| (run.mode, run.round)).unwrap_or((Mode::Snapshot, 0)); + let subject = round_logic::round_commit_message( + round, + &fix_titles(&outcome.review, outcome.subject.as_deref()), + ); + let (commit, boundary) = match close_round(rc, &look.project, mode, &subject) { + Ok(saved) => saved, + Err((line, evidence)) => { + finish_run( + rc, + StopReason::Failed(format!("the round could not be saved ({line})")), + Some(evidence), + ); + return false; + } + }; + let next = with_run(rc, |run| { + let mut done = std::mem::take(&mut run.cur); + done.n = look.round; + done.boundary = Some(boundary); + done.verdict = Some(verdict.clone()); + done.ended_at = clock(); + done.critical = outcome.review.critical; + done.warning = outcome.review.warning; + done.suggestion = outcome.review.suggestion; + done.fixed = outcome.review.fixed.clone(); + done.unfixed = outcome.review.unfixed.clone(); + done.suggestions = outcome.review.suggestions.clone(); + done.tests = outcome.tests.clone(); + done.commit = commit; + done.retried = run.retried; + done.summary = outcome.summary.clone(); + run.collected = merge_suggestions( + &run.collected, + &outcome.review.suggestions, + &outcome.review.fixed, + &run.reviewed_files, + ); + run.rounds.push(done); + run.step = ReviewStep::Starting; + let next = round_logic::next_step(&run.view(look.round), &verdict); + if next == Next::SuggestionsBatch { + run.pending_stop = Some(if verdict == Verdict::Clean { + StopReason::Clean + } else { + StopReason::Cap + }); + } + next + }); + let Some(next) = next else { return false }; + notify_round(rc, look.round, outcome, &verdict); + emit(rc); + act(rc, look.stage, next, None) +} + +/// Act on the step `next_step` chose. Returns whether the run goes on. +fn act(rc: &RoundCtx, stage: Stage, next: Next, why: Option<&str>) -> bool { + match next { + Next::StartRound(n) => { + with_run(rc, |run| { + run.retried = false; + run.reviewer_report = None; + // A retry's step up applies to that round only. + run.cur_strength = run.setup.strength; + }); + let first = with_run(rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both); + go(rc, start_stage(rc, first, n)) + } + Next::Retry => { + let round = with_run(rc, |run| run.round).unwrap_or(1); + with_run(rc, |run| { + run.retried = true; + run.retries_used += 1; + let stepped = run + .cur_strength + .and_then(|word| next_strength_word(&run.strength_rows, word.word())) + .and_then(|word| Strength::from_word(&word)); + match stepped { + Some(word) => run.cur_strength = Some(word), + None => run.cur.could_not_step_up = true, + } + run.cur.retried = true; + }); + emit(rc); + go(rc, start_stage(rc, stage, round)) + } + Next::SuggestionsBatch => { + let round = with_run(rc, |run| { + let n = u32::try_from(run.rounds.len()).unwrap_or(0) + 1; + run.retried = false; + // A retried round's step up was for that round only. + run.cur_strength = run.setup.strength; + run.suggestions_batch = Some(BatchRecord { + briefed: run.collected.clone(), + before: Some(run.last_boundary()), + after_rounds: run.rounds.len(), + ..BatchRecord::default() + }); + n + }) + .unwrap_or(1); + go(rc, start_stage(rc, Stage::Batch, round)) + } + Next::FinalCheck => { + let round = with_run(rc, |run| { + run.retried = false; + run.cur_strength = run.setup.strength; + u32::try_from(run.rounds.len()).unwrap_or(0) + 2 + }) + .unwrap_or(2); + go(rc, start_stage(rc, Stage::Final, round)) + } + Next::Stop(reason) => { + let evidence = why.map(str::to_string); + finish_run(rc, reason, evidence); + false + } + } +} + +/// A session start that failed stops the run as `Failed`. +fn go(rc: &RoundCtx, started: Result<(), String>) -> bool { + match started { + Ok(()) => true, + Err(e) => { + finish_run( + rc, + StopReason::Failed(format!("a session could not start ({})", one_line(&e))), + Some(e), + ); + false + } + } +} + +/// The Suggestions batch's fixer reported: commit it on its own, then check it. +fn finish_batch(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool { + if let Verdict::Failed(reason) = &verdict { + return settle_failure(rc, look, reason.clone()); + } + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let mode = with_run(rc, |run| run.mode).unwrap_or(Mode::Snapshot); + let subject = batch_subject(&fix_titles(&outcome.review, outcome.subject.as_deref())); + let (commit, boundary) = match close_round(rc, &look.project, mode, &subject) { + Ok(saved) => saved, + Err((line, evidence)) => { + finish_run( + rc, + StopReason::Failed(format!("the Suggestions batch could not be saved ({line})")), + Some(evidence), + ); + return false; + } + }; + let next = with_run(rc, |run| { + if let Some(batch) = run.suggestions_batch.as_mut() { + batch.boundary = Some(boundary); + batch.commit = commit; + batch.verdict = Some(verdict.clone()); + batch.summary = outcome.summary.clone(); + } + // Fixed and committed: a later round never briefs them again. + run.collected.clear(); + run.batch_done = true; + run.step = ReviewStep::Starting; + round_logic::next_step(&run.view(look.round), &verdict) + }); + let Some(next) = next else { return false }; + emit(rc); + act(rc, look.stage, next, None) +} + +/// The final check reported: its verdict is kept apart, and the run ends for +/// the reason it was already ending for (FR-19). +fn finish_final(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool { + if let Verdict::Failed(reason) = &verdict { + let retried = with_run(rc, |run| run.retried).unwrap_or(true); + if !retried { + return settle_failure(rc, look, reason.clone()); + } + } + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let original = with_run(rc, |run| { + if let Some(batch) = run.suggestions_batch.as_mut() { + batch.final_check = Some(verdict.clone()); + batch.final_critical = outcome.review.critical; + batch.final_warning = outcome.review.warning; + } + run.pending_stop.clone().unwrap_or(StopReason::Clean) + }); + let Some(original) = original else { + return false; + }; + let next = round_logic::after_final_check(original); + let note = match &verdict { + Verdict::Failed(reason) => Some(format!("the final check did not finish ({reason})")), + _ => None, + }; + act(rc, look.stage, next, note.as_deref()) +} + +// -------------------------------------------------------- ending a run + +/// End the run: record why, end the agent, tell the banner, then show the end +/// screen. The run is kept for Continue and sign-off. A sign-off's own +/// Suggestions fix ends here too: it keeps the reason the run already ended +/// for and finishes the sign-off. +pub fn finish_run(rc: &RoundCtx, reason: StopReason, evidence: Option) { + rc.ctx.agent.stop(); + let notice = with_run(rc, |run| { + let signing = run.signing; + if signing { + match &reason { + StopReason::Person => { + // Stop now during sign-off: not signed off, the person + // settles the partial changes and signs off again. + run.signing = false; + if let Some(signoff) = run.signoff.as_mut() { + signoff.problem = + Some("Stop now was pressed while the Suggestions were fixed".into()); + } + } + StopReason::Failed(why) => { + if let Some(signoff) = run.signoff.as_mut() { + signoff.problem = Some(one_line(why)); + } + } + _ => {} + } + } else { + run.stop_reason = Some(reason.clone()); + run.stop_evidence = evidence; + run.stop_round = run.round; + } + run.running = false; + run.step = ReviewStep::Starting; + ( + signing, + run.setup.notify_kind, + run.setup.notify_url.clone(), + run.setup.notify_param.clone(), + run.round, + run.open_findings().len(), + ) + }); + (rc.ctx.hooks.emit)(LoopStateEvent::ended()); + let Some((signing, kind, url, param, round, open)) = notice else { + return; + }; + if with_run(rc, |run| run.signing) == Some(true) { + complete_sign_off(rc); + } + show_end(rc); + if !signing { + if let Some(words) = stop_words(&reason, round, open).filter(|_| !url.trim().is_empty()) { + send_notice(rc, kind, url, param, format!("Review Loop {words}")); + } + } +} + +// ----------------------------------------------------- the end screen + +/// The doc ids the end post uses. +const REPORT_DOC: &str = "review-report"; +const PARTIAL_DOC: &str = "review-partial"; + +/// The most Suggestions and open findings the end screen lists. +const LIST_LIMIT: usize = 50; + +fn text_line(text: &str, max: usize) -> String { + one_line(text).chars().take(max).collect() +} + +fn count_words(n: usize, one: &str, many: &str) -> String { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {many}") + } +} + +fn reason_key(reason: Option<&StopReason>) -> &'static str { + match reason { + Some(StopReason::Clean) => "clean", + Some(StopReason::Cap) => "cap", + Some(StopReason::Person) => "person", + Some(StopReason::Failed(_)) | None => "failed", + } +} + +/// The one line the end screen leads with, never over 200 characters. +pub fn end_line(run: &ReviewRun) -> String { + let rounds = run.rounds.len(); + let ran = count_words(rounds, "round", "rounds"); + let open = run.open_findings().len(); + let line = match &run.stop_reason { + Some(StopReason::Clean) if open > 0 => format!( + "Clean after {ran}, but {} still open.", + count_words( + open, + "finding an earlier round left unfixed is", + "findings earlier rounds left unfixed are" + ) + ), + Some(StopReason::Clean) => { + format!("Clean after {ran}: no Critical or Warning findings are left.") + } + Some(StopReason::Cap) => format!( + "Stopped at the round cap after {ran}: {} still open.", + count_words(open, "finding is", "findings are") + ), + Some(StopReason::Person) if rounds == 0 => { + "Stopped by you before a round finished.".to_string() + } + Some(StopReason::Person) => format!("Stopped by you after {ran} finished."), + Some(StopReason::Failed(why)) => { + let round = if run.stop_round > 0 { + run.stop_round + } else { + run.round + }; + format!("Failed in round {round}: {why}.") + } + None => "The Review Loop has not finished.".to_string(), + }; + text_line(&line, 200) +} + +/// Whether the end screen offers Continue: not after a clean run or a +/// sign-off, not while partial changes wait, and never past six rounds. +pub fn can_continue(run: &ReviewRun) -> bool { + if run.running || run.signing || run.signed_off { + return false; + } + if run.partial.as_ref().is_some_and(|partial| partial.pending) { + return false; + } + let rounds = u32::try_from(run.rounds.len()).unwrap_or(u32::MAX); + match run.stop_reason { + Some(StopReason::Cap) => round_logic::continue_cap(run.cap, rounds).is_some(), + Some(StopReason::Person) | Some(StopReason::Failed(_)) => rounds < MAX_ROUNDS, + Some(StopReason::Clean) | None => false, + } +} + +/// The squash switch shows only in commit mode with two round commits. +pub fn can_squash(run: &ReviewRun) -> bool { + run.mode == Mode::Commit + && !run.signed_off + && run + .rounds + .iter() + .filter(|round| round.commit.is_some()) + .count() + >= 2 +} + +fn finding_json(finding: &Finding) -> Value { + let mut value = serde_json::json!({ + "title": text_line(&finding.title, 200), + "file": finding.file.trim(), + }); + if let Some(line) = finding.line.filter(|line| *line > 0) { + value["line"] = serde_json::json!(line); + } + value +} + +/// What sign-off did, in one line for the finished screen. +fn sign_off_note(run: &ReviewRun) -> Option { + let signoff = run.signoff.as_ref().filter(|_| run.signed_off)?; + let mut parts: Vec = Vec::new(); + match &signoff.squash { + Squash::Done { commits, .. } => parts.push(format!( + "Squashed {} into one.", + count_words(*commits, "commit", "commits") + )), + Squash::Refused(why) => parts.push(why.clone()), + Squash::Off => {} + } + if !signoff.picked.is_empty() && signoff.problem.is_none() { + parts.push(format!( + "Fixed {}.", + count_words(signoff.picked.len(), "Suggestion", "Suggestions") + )); + } + if let Some(problem) = &signoff.problem { + parts.push(format!("The Suggestions were not all fixed: {problem}.")); + } + (!parts.is_empty()).then(|| text_line(&parts.join(" "), 200)) +} + +/// The page's `loopEnd` for the run as it stands. `partial_doc` says the +/// partial diff was put on the page. +pub fn end_patch_for(run: &ReviewRun, partial_doc: bool, report_md: &str) -> Value { + use serde_json::json; + let mut docs = vec![json!({ + "id": REPORT_DOC, + "title": "Review Loop report", + "blocks": [{ "id": "body", "state": "settled", "md": report_md }], + })]; + let mut end = json!({ + "kind": "review", + "line": end_line(run), + "reason": reason_key(run.stop_reason.as_ref()), + "report": REPORT_DOC, + "canContinue": can_continue(run), + "canSquash": can_squash(run), + "can": [], + }); + if let Some(partial) = run.partial.as_ref().filter(|p| p.pending && partial_doc) { + docs.push(json!({ + "id": PARTIAL_DOC, + "title": "Partial changes", + "blocks": [{ "id": "diff", "diff": "partial.diff" }], + })); + end["partial"] = json!({ + "files": partial.files, + "added": partial.added, + "removed": partial.removed, + "diff": PARTIAL_DOC, + }); + } + if !run.signed_off && !run.collected.is_empty() { + let list: Vec = run + .collected + .iter() + .take(LIST_LIMIT) + .enumerate() + .map(|(i, finding)| { + let mut value = finding_json(finding); + value["id"] = json!(format!("s{}", i + 1)); + value + }) + .collect(); + end["suggestions"] = json!(list); + } + let open: Vec = run + .open_findings() + .iter() + .take(LIST_LIMIT) + .map(finding_json) + .collect(); + if !open.is_empty() { + end["open"] = json!(open); + } + if run.signed_off { + end["signedOff"] = json!(true); + if let Some(note) = sign_off_note(run) { + end["note"] = json!(note); + } + } + json!({ "docs": docs, "loopEnd": end }) +} + +/// Put the partial diff in the session's own folder, where a diff block must +/// live. False when the file could not be copied. +fn publish_partial(home: &Path, sid: &str, partial: &Partial) -> bool { + let folder = crate::session_reader::session_dir(home, sid); + std::fs::create_dir_all(&folder).is_ok() + && std::fs::copy(&partial.diff, folder.join("partial.diff")).is_ok() +} + +/// Tell the page how the run ended. A session the console no longer holds is +/// opened again once; a post it refuses is repeated without the partial diff. +fn post_review_end(console_dir: &Path, run: &ReviewRun, patch: &Value) { + let Some(sid) = run.sid.clone().or_else(|| run.last_sid.clone()) else { + return; + }; + // No console to post to (a test, or the console not found): nothing to do. + if !console_dir.join("console.mjs").is_file() { + return; + } + if loop_tools::console_post(console_dir, &sid, patch).ok { + return; + } + if loop_tools::console_resume(console_dir, &sid, "review").ok + && loop_tools::console_post(console_dir, &sid, patch).ok + { + return; + } + let mut plain = patch.clone(); + if let Some(docs) = plain.get_mut("docs").and_then(Value::as_array_mut) { + docs.retain(|doc| doc["id"].as_str() != Some(PARTIAL_DOC)); + } + if let Some(end) = plain.get_mut("loopEnd").and_then(Value::as_object_mut) { + end.remove("partial"); + } + let _ = loop_tools::console_post(console_dir, &sid, &plain); +} + +/// `REVIEW-LOOP-.md`, or `-2`, `-3` and so on when that name is taken. +pub fn unused_report_name(date: &str, taken: impl Fn(&str) -> bool) -> String { + let first = format!("REVIEW-LOOP-{date}.md"); + if !taken(&first) { + return first; + } + (2..) + .map(|n| format!("REVIEW-LOOP-{date}-{n}.md")) + .find(|name| !taken(name)) + .unwrap_or(first) +} + +/// Take the report file out of the spec folder before more work that commits +/// starts (a Suggestions fix, a Continue): the commit would otherwise sweep a +/// stale report into it. The next end writes a fresh one. +fn drop_spec_report(run: &mut ReviewRun) { + if let Some(file) = run.report_file.take() { + let _ = std::fs::remove_file(file); + } +} + +/// Write the report into the spec folder, for a run launched on a spec and +/// only then. A later write (the sign-off's) replaces the first one. +pub fn write_spec_report(run: &ReviewRun, md: &str) -> Option { + if run.scope != ReviewScope::Spec { + return None; + } + let spec = run.setup.spec.as_deref()?; + loop_driver::validate_spec(&run.project, spec).ok()?; + let folder = run.project.join(spec); + let file = match &run.report_file { + Some(file) => file.clone(), + None => { + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + folder.join(unused_report_name(&date, |name| folder.join(name).exists())) + } + }; + loop_driver::write_atomic(&file, md).ok().map(|()| file) +} + +/// This run's entry for the report list: its rounds and how it ended. +pub fn review_entry(run: &ReviewRun) -> ReportEntry { + let rounds = run + .rounds + .iter() + .map(|round| RoundEntry { + n: round.n, + critical: round.critical, + warning: round.warning, + suggestion: round.suggestion, + fixed: round + .fixed + .iter() + .map(|f| text_line(&f.title, 200)) + .collect(), + left_open: round + .unfixed + .iter() + .map(|f| text_line(&f.title, 200)) + .collect(), + commit: round.commit.clone(), + tests: match &round.tests { + None => "not reported".to_string(), + Some(t) if !t.summary.is_empty() => text_line(&t.summary, 200), + Some(t) if t.passed => "passed".to_string(), + Some(_) => "failed".to_string(), + }, + started: round.started_at.clone(), + ended: round.ended_at.clone(), + strength: round.strength.clone().unwrap_or_default(), + retried: round.retried, + }) + .collect(); + ReportEntry { + kind: EntryKind::Review, + rounds, + at: clock(), + name: run + .setup + .spec + .clone() + .unwrap_or_else(|| run.scope.word().to_string()), + result: if run.stop_reason == Some(StopReason::Clean) { + EntryResult::Passed + } else { + EntryResult::Stopped + }, + line: end_line(run), + summary: end_line(run), + reported: true, + ..ReportEntry::default() + } +} + +/// Save the run's entry in the report list. It has a key of its own, so it +/// never meets an Implementation Loop report for the same spec. +fn save_review_entry(home: &Path, run: &ReviewRun) -> Result<(), String> { + let mut report = LoopReport::new(&format!("review-loop:{}", run.id), &clock()); + report.entries.push(review_entry(run)); + report_list::save_report(home, &run.project, &report) +} + +/// Write the report where it goes (the report list, and the spec folder for a +/// spec launch) and post the end to the page. Returns the spec file written. +fn publish_end(console_dir: &Path, home: &Path, run: &ReviewRun) -> Option { + let md = review_report_markdown(run); + let file = write_spec_report(run, &md); + let _ = save_review_entry(home, run); + let sid = run.sid.clone().or_else(|| run.last_sid.clone()); + let partial_doc = match (&sid, run.partial.as_ref().filter(|p| p.pending)) { + (Some(sid), Some(partial)) => publish_partial(home, sid, partial), + _ => false, + }; + post_review_end(console_dir, run, &end_patch_for(run, partial_doc, &md)); + file +} + +/// Show the end screen for the run as it stands. +fn show_end(rc: &RoundCtx) { + let Some(run) = with_run(rc, |run| run.clone()) else { + return; + }; + if let Some(file) = publish_end(&rc.ctx.console_dir, &rc.ctx.home, &run) { + with_run(rc, |run| run.report_file = Some(file)); + } +} + +// ------------------------------------------------------------- sign-off + +/// The Suggestion a pick id (`s1`, `s2`...) names, as an index. +fn pick_index(id: &str, count: usize) -> Option { + let n: usize = id.strip_prefix('s')?.parse().ok()?; + (1..=count.min(LIST_LIMIT)).contains(&n).then(|| n - 1) +} + +const FOREIGN_COMMIT: &str = + "Something else was committed during the run, so the rounds were not squashed."; + +/// The squash commit's subject: the rounds it covers and what they fixed. +fn squash_subject(first: u32, last: u32, titles: &[String]) -> String { + let subject = round_logic::round_commit_message(0, titles).replacen( + "round 0", + &format!("rounds {first} to {last}"), + 1, + ); + if subject.chars().count() <= 72 { + return subject; + } + let cut: String = subject.chars().take(69).collect(); + format!("{}...", cut.trim_end()) +} + +/// Squash the run's commits (the round commits and the Suggestions commit) +/// into one on top of the start boundary, which holds the pre-run commit and +/// everything before it. Refuses, and changes nothing, when any commit +/// between the start and HEAD was not made by this run or something is +/// staged. +fn squash_rounds(project: &Path, start: &Boundary, mine: &[String], subject: &str) -> Squash { + let Boundary::Commit(start_id) = start else { + return Squash::Refused("There are no round commits to squash.".to_string()); + }; + let Ok(list) = git_text( + project, + &["rev-list", "--reverse", &format!("{start_id}..HEAD")], + ) else { + return Squash::Refused(FOREIGN_COMMIT.to_string()); + }; + let ids = lines_of(&list); + if ids.len() < 2 { + return Squash::Refused("There are not two commits of the run to squash.".to_string()); + } + if ids.len() != mine.len() || ids.iter().any(|id| !mine.contains(id)) { + return Squash::Refused(FOREIGN_COMMIT.to_string()); + } + if git_text(project, &["diff", "--cached", "--quiet"]).is_err() { + return Squash::Refused("Something is staged, so the rounds were not squashed.".into()); + } + let Ok(head) = loop_tools::git_head_full(project) else { + return Squash::Refused("git could not read the current commit.".to_string()); + }; + let message = match loop_tools::commit_message(project, subject) { + Ok(message) => message, + Err(why) => return Squash::Refused(format!("The squash commit was refused: {why}")), + }; + if let Err(why) = git_text(project, &["reset", "--soft", start_id]) { + return Squash::Refused(format!("The rounds were not squashed: {why}")); + } + let done = loop_tools::git_commit(project, &message); + if !done.ok { + // Put every round commit back where it was. + let _ = git_text(project, &["reset", "--soft", &head]); + return Squash::Refused(format!( + "The squash commit failed, so the round commits are as they were ({}).", + loop_commit::first_line(&done.output) + )); + } + match loop_tools::git_head_full(project) { + Ok(commit) => Squash::Done { + commit, + commits: ids.len(), + }, + Err(why) => Squash::Refused(format!("The squash ran, but {why}.")), + } +} + +/// The commits this run made, from its records. +fn run_commits(run: &ReviewRun) -> Vec { + run.rounds + .iter() + .filter_map(|round| round.commit.clone()) + .chain( + run.earlier_batches + .iter() + .chain(run.suggestions_batch.iter()) + .filter_map(|batch| batch.commit.clone()), + ) + .collect() +} + +/// Run the squash the person asked for (if they did) and mark the run signed +/// off. Called once the Suggestions fix, if there was one, has ended. +fn complete_sign_off(rc: &RoundCtx) { + let plan = with_run(rc, |run| { + let asked = run.signoff.as_ref().is_some_and(|s| s.squash_asked); + let first = run.rounds.first().map_or(1, |r| r.n); + let last = run.rounds.last().map_or(1, |r| r.n); + let titles: Vec = run + .rounds + .iter() + .flat_map(|r| r.fixed.iter().map(|f| safe_title(&f.title))) + .collect(); + ( + asked, + run.mode, + run.project.clone(), + run.start.clone(), + run_commits(run), + squash_subject(first, last, &titles), + ) + }); + let Some((asked, mode, project, start, mine, subject)) = plan else { + return; + }; + let squash = match (asked, mode) { + (false, _) => Squash::Off, + (true, Mode::Commit) => squash_rounds(&project, &start, &mine, &subject), + (true, Mode::Snapshot) => Squash::Refused("A squash needs commit mode.".to_string()), + }; + with_run(rc, |run| { + if let Some(signoff) = run.signoff.as_mut() { + signoff.squash = squash; + } + run.signing = false; + run.signed_off = true; + }); +} + +/// Sign off a finished run: fix the Suggestions the person ticked (one fixer +/// session, its fresh check and its own commit, the same path as the auto +/// batch), then squash the round commits when asked, then show the finished +/// screen. With no Suggestions ticked nothing runs but the squash. +#[allow(clippy::too_many_arguments)] +pub fn sign_off( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + hooks: Hooks, + limits: Limits, + home: PathBuf, + picks: &[String], + squash: bool, + watch: bool, +) -> Result<(), String> { + if loop_driver::is_running(phases) || is_running(slot) { + return Err("A loop is already running in this window.".to_string()); + } + let (rc, any_picked) = { + let mut guard = lock(slot); + let run = guard + .as_mut() + .ok_or("There is no Review Loop to sign off.")?; + if run.running || run.signing { + return Err("A loop is already running in this window.".to_string()); + } + if run.signed_off { + return Err("This Review Loop was already signed off.".to_string()); + } + if run.stop_reason.is_none() { + return Err("The Review Loop has not finished.".to_string()); + } + if run.partial.as_ref().is_some_and(|partial| partial.pending) { + return Err("Keep or discard the partial changes first.".to_string()); + } + let mut chosen: Vec = Vec::new(); + for id in picks { + let at = + pick_index(id, run.collected.len()).ok_or("That Suggestion is not on the list.")?; + if chosen.contains(&at) { + return Err("A Suggestion was picked twice.".to_string()); + } + chosen.push(at); + } + chosen.sort_unstable(); + let picked: Vec = chosen.iter().map(|at| run.collected[*at].clone()).collect(); + let left: Vec = run + .collected + .iter() + .enumerate() + .filter(|(at, _)| !chosen.contains(at)) + .map(|(_, finding)| finding.clone()) + .collect(); + run.signoff = Some(SignOff { + picked: picked.clone(), + left, + squash_asked: squash, + squash: Squash::Off, + problem: None, + }); + if !picked.is_empty() { + run.signing = true; + run.running = true; + // A neutral sentinel: the check then ends the fix with Clean, so a + // Person or Failed reason can only come from this fix itself. + run.pending_stop = Some(StopReason::Clean); + run.collected = picked; + run.batch_done = false; + run.retried = false; + run.stop_now = false; + run.stop_after_round = false; + run.cur_strength = run.setup.strength; + drop_spec_report(run); + if let Some(batch) = run.suggestions_batch.take() { + run.earlier_batches.push(batch); + } + } + let any = run.signing; + let rc = RoundCtx { + slot: Arc::clone(slot), + ctx: new_ctx(run, agent, home, hooks, limits), + }; + (rc, any) + }; + if !any_picked { + complete_sign_off(&rc); + show_end(&rc); + return Ok(()); + } + emit(&rc); + // A start that fails ends the sign-off through `finish_run`, which says so. + let started = act(&rc, Stage::Batch, Next::SuggestionsBatch, None); + if started && watch { + thread::spawn(move || watcher(rc)); + } + Ok(()) +} + +/// The prompt behind a finished screen's button: PR Prep, or a Quick task on +/// what the run left open. +pub fn next_prompt(slot: &ReviewSlot, which: &str) -> Result { + let guard = lock(slot); + let run = guard.as_ref().ok_or("There is no Review Loop run.")?; + if run.running { + return Err("The Review Loop is still running.".to_string()); + } + match which { + "pr-prep" => Ok("/plan2code-pr-prep --web".to_string()), + "quick-task" => { + let open: Vec = run + .open_findings() + .iter() + .enumerate() + .map(|(i, finding)| { + let at = match (finding.file.is_empty(), finding.line) { + (true, _) => String::new(), + (false, None) => format!(" ({})", finding.file), + (false, Some(line)) => format!(" ({}:{line})", finding.file), + }; + format!("{}. {}{at}", i + 1, text_line(&finding.title, 200)) + }) + .collect(); + if open.is_empty() { + return Err("Nothing is left open.".to_string()); + } + Ok(format!( + "/plan2code-quick-task --web Fix by hand what the Review Loop left open: {}", + open.join("; ") + )) + } + _ => Err("That is not a next step.".to_string()), + } +} + +/// Keep or discard what Stop now left, then show the end screen again +/// without it (Continue is offered once the partial changes are settled). +pub fn settle_partial(slot: &ReviewSlot, keep: bool, home: &Path) -> Result<(), String> { + partial(slot, keep)?; + let run = lock(slot).clone(); + if let Some(run) = run { + if let Some(file) = publish_end(&console_dir(), home, &run) { + if let Some(held) = lock(slot).as_mut().filter(|r| r.run_id == run.run_id) { + held.report_file = Some(file); + } + } + } + Ok(()) +} + +/// What the ending notice says, always naming the round it ended in, or none +/// when the person stopped the run themselves (as the Implementation Loop does). +fn stop_words(reason: &StopReason, round: u32, open: usize) -> Option { + match reason { + StopReason::Clean if open > 0 => Some(format!( + "finished after round {round}, but {} still open.", + count_words( + open, + "finding an earlier round left unfixed is", + "findings earlier rounds left unfixed are" + ) + )), + StopReason::Clean => Some(format!( + "finished after round {round}: no Critical or Warning findings are left." + )), + StopReason::Cap => Some(format!("stopped at the round cap after round {round}.")), + StopReason::Person => None, + StopReason::Failed(why) => Some(format!("failed in round {round}: {why}.")), + } +} + +/// Tell the address on its own thread: a slow one must not delay the watch. +fn send_notice(rc: &RoundCtx, kind: NotifyKind, url: String, param: String, message: String) { + let (slot, run_id) = (Arc::clone(&rc.slot), rc.ctx.run_id); + thread::spawn(move || { + if let Err(reason) = crate::loop_shared::notify(kind, &url, ¶m, &message) { + if let Some(run) = lock(&slot).as_mut().filter(|run| run.run_id == run_id) { + run.notify_failure = Some(reason); + } + } + }); +} + +fn notify_round(rc: &RoundCtx, round: u32, outcome: &RoundOutcome, verdict: &Verdict) { + let target = with_run(rc, |run| { + (run.setup.notify_rounds && !run.setup.notify_url.trim().is_empty()).then(|| { + ( + run.setup.notify_kind, + run.setup.notify_url.clone(), + run.setup.notify_param.clone(), + ) + }) + }) + .flatten(); + if let Some((kind, url, param)) = target { + let how = match verdict { + Verdict::Clean => "clean".to_string(), + Verdict::Findings { critical, warning } => { + format!("{critical} Critical, {warning} Warning") + } + Verdict::Failed(reason) => format!("failed ({reason})"), + }; + let message = format!("Review Loop round {round}: {how}. {}", outcome.summary); + send_notice(rc, kind, url, param, message); + } +} + +// ------------------------------------------------------- the stop buttons + +/// Stop after this round: it finishes, is judged and committed, then the run +/// stops instead of starting the next. Returns the banner's new state. +pub fn request_stop_after(slot: &ReviewSlot, on: bool) -> Result { + let mut guard = lock(slot); + let run = guard + .as_mut() + .filter(|run| run.running) + .ok_or("No Review Loop is running")?; + run.stop_after_round = on; + Ok(review_state_event(run)) +} + +/// Stop now: the flag is set first, so the ended agent is never taken for a +/// crash and nothing more is committed, then the agent ends. The banner's new +/// state goes to `emit` while the slot is held. +pub fn request_stop_now( + slot: &ReviewSlot, + agent: Option<&AgentManager>, + emit: impl FnOnce(&LoopStateEvent), +) -> Result { + let event = { + let mut guard = lock(slot); + let run = guard + .as_mut() + .filter(|run| run.running) + .ok_or("No Review Loop is running")?; + run.stop_now = true; + let event = review_state_event(run); + emit(&event); + event + }; + if let Some(agent) = agent { + agent.stop(); + } + Ok(event) +} + +/// Stop now was pressed: end the run as stopped by the person, commit +/// nothing, and leave the partial changes (a diff from the last finished +/// boundary to a fresh snapshot) for the stop screen. +fn stop_now_finish(rc: &RoundCtx) { + rc.ctx.agent.stop(); + let plan = with_run(rc, |run| { + ( + run.project.clone(), + run.last_boundary(), + run.run_dir.join("partial.diff"), + ) + }); + let Some((project, from, out)) = plan else { + return; + }; + let mut partial = Partial { + diff: out.clone(), + pending: true, + ..Partial::default() + }; + let _ = std::fs::create_dir_all(out.parent().unwrap_or(Path::new("."))); + let mut evidence = None; + match round_boundary::snapshot(&project) { + Ok(now) => match round_boundary::diff(&project, &from, &now, &out) { + Ok(stats) => { + partial.files = stats.files; + partial.added = stats.added; + partial.removed = stats.removed; + partial.new_files = git_text( + &project, + &[ + "diff", + "--name-only", + "-z", + "--no-renames", + "--diff-filter=A", + from.id(), + now.id(), + ], + ) + .map(|text| nul_lines(&text)) + .unwrap_or_default(); + } + Err(e) => evidence = Some(format!("the partial changes could not be listed ({e})")), + }, + Err(e) => evidence = Some(format!("the partial changes could not be listed ({e})")), + } + with_run(rc, |run| run.partial = Some(partial)); + finish_run(rc, StopReason::Person, evidence); +} + +/// Keep or discard what Stop now left. Keep leaves the partial changes +/// uncommitted. Discard puts tracked files back to the last finished +/// boundary and removes only the untracked files that appeared during the +/// stopped round, never others. +pub fn partial(slot: &ReviewSlot, keep: bool) -> Result<(), String> { + let (project, boundary, new_files) = { + let guard = lock(slot); + let run = guard.as_ref().ok_or("No Review Loop to settle")?; + if run.running { + return Err("The Review Loop is still running.".to_string()); + } + let partial = run + .partial + .as_ref() + .filter(|partial| partial.pending) + .ok_or("There are no partial changes waiting.")?; + ( + run.project.clone(), + run.last_boundary(), + partial.new_files.clone(), + ) + }; + if !keep { + // Git names files from the repository's top folder, and the project + // may be a folder inside it: put back and remove from the top. + let top = loop_tools::git_toplevel(&project).unwrap_or_else(|| project.clone()); + match &boundary { + Boundary::Commit(id) => { + git_text(&top, &["checkout", id, "--", "."])?; + } + Boundary::Tree(id) => restore_tree(&top, id)?, + } + for file in &new_files { + let path = top.join(file); + if path.is_file() { + let _ = std::fs::remove_file(&path); + } + } + } + if let Some(run) = lock(slot).as_mut() { + if let Some(partial) = run.partial.as_mut() { + partial.pending = false; + } + } + Ok(()) +} + +/// Put the working tree's files back to a tree id, through a temp index so the +/// real one is never touched. +fn restore_tree(project: &Path, tree: &str) -> Result<(), String> { + let temp = std::env::temp_dir().join(format!( + "plan2code-round-restore-{}-{}", + std::process::id(), + NEXT_RUN.fetch_add(1, Ordering::SeqCst) + )); + let run = |args: &[&str]| -> Result<(), String> { + let out = git_cmd(project, args) + .env("GIT_INDEX_FILE", &temp) + .output() + .map_err(|err| format!("git could not run: {err}"))?; + if out.status.success() { + Ok(()) + } else { + Err(format!( + "git {} failed: {}", + args.first().unwrap_or(&""), + String::from_utf8_lossy(&out.stderr) + .lines() + .next() + .unwrap_or("") + )) + } + }; + let result = run(&["read-tree", tree]).and_then(|()| run(&["checkout-index", "-a", "-f"])); + let _ = std::fs::remove_file(&temp); + result +} + +// ----------------------------------------------------------------- Continue + +/// Continue after a stop by the person, a failure or the cap: start the next +/// round from the run's last boundary. At the cap the cap goes up by one, and +/// never above six rounds in all. +pub fn continue_run( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + hooks: Hooks, + limits: Limits, + home: PathBuf, + watch: bool, +) -> Result<(), String> { + if loop_driver::is_running(phases) || is_running(slot) { + return Err("A loop is already running in this window.".to_string()); + } + let (round, rc) = { + let mut guard = lock(slot); + let run = guard + .as_mut() + .ok_or("There is no Review Loop to continue.")?; + if run.running || run.signing { + return Err("A loop is already running in this window.".to_string()); + } + if run.signed_off { + return Err("This Review Loop was signed off.".to_string()); + } + if run.partial.as_ref().is_some_and(|partial| partial.pending) { + return Err("Keep or discard the partial changes first.".to_string()); + } + let rounds_run = u32::try_from(run.rounds.len()).unwrap_or(u32::MAX); + match run.stop_reason { + Some(StopReason::Clean) | None => { + return Err( + "This Review Loop finished clean: there is nothing to continue.".into(), + ); + } + Some(StopReason::Cap) => { + let cap = round_logic::continue_cap(run.cap, rounds_run) + .ok_or("A Review Loop runs at most 6 rounds.")?; + run.cap = cap; + } + Some(StopReason::Person) | Some(StopReason::Failed(_)) => { + if rounds_run >= MAX_ROUNDS { + return Err("A Review Loop runs at most 6 rounds.".to_string()); + } + if rounds_run >= run.cap { + run.cap = rounds_run + 1; + } + } + } + run.running = true; + run.stop_reason = None; + run.stop_evidence = None; + run.stop_now = false; + run.stop_after_round = false; + run.retried = false; + run.reviewer_report = None; + run.cur_strength = run.setup.strength; + run.pending_stop = None; + run.partial = None; + run.batch_done = false; + drop_spec_report(run); + // A finished batch stays in the record; the next one is a new batch. + if let Some(batch) = run.suggestions_batch.take() { + run.earlier_batches.push(batch); + } + let rc = RoundCtx { + slot: Arc::clone(slot), + ctx: new_ctx(run, agent, home, hooks, limits), + }; + (rounds_run + 1, rc) + }; + let first = with_run(&rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both); + if let Err(e) = start_stage(&rc, first, round) { + with_run(&rc, |run| { + run.running = false; + run.stop_round = round; + run.stop_reason = Some(StopReason::Failed(format!( + "a session could not start ({})", + one_line(&e) + ))); + }); + // The report was dropped above: write it again and re-post the end. + show_end(&rc); + (rc.ctx.hooks.emit)(LoopStateEvent::ended()); + return Err(e); + } + if watch { + thread::spawn(move || watcher(rc)); + } + Ok(()) +} + +// ------------------------------------------------------------- the facts + +/// What the setup screen shows about the agent a Review Loop would use. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReviewFacts { + pub agent: Option, + pub agent_label: Option, + pub helpers: bool, + pub strengths_mapped: bool, + pub running: bool, + pub prompt_support: bool, + pub notify_kind: NotifyKind, + pub notify_url: String, + pub notify_param: String, +} + +/// The facts for `agent` (or none), a loop running, and the Implementation +/// Loop's notification settings (`loop_setup`). +pub fn facts( + agent: Option<&Agent>, + running: bool, + loop_setup: &loop_driver::LoopSetup, +) -> ReviewFacts { + ReviewFacts { + agent: agent.map(|a| a.id().to_string()), + agent_label: agent.map(|a| a.label().to_string()), + helpers: agent.is_some_and(agent_helpers), + strengths_mapped: agent.is_some_and(|a| !loop_driver::strength_rows_for(a).is_empty()), + running, + prompt_support: agent.is_none_or(loop_driver::prompt_support), + notify_kind: loop_setup.notify_kind, + notify_url: loop_setup.notify_url.clone(), + notify_param: loop_setup.notify_param.clone(), + } +} + +/// The Start screen's request, as the page sends it. The notification comes +/// from the Implementation Loop's setup, never from this message. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReviewRequest { + pub scope: ReviewScope, + #[serde(default)] + pub spec: Option, + #[serde(default = "default_cap")] + pub cap: u32, + #[serde(default = "default_true")] + pub commit: bool, + #[serde(default)] + pub pre_run_commit_agreed: bool, + #[serde(default)] + pub suggestions: bool, + #[serde(default)] + pub strength: String, + #[serde(default = "default_silence")] + pub silence_minutes: u32, + #[serde(default)] + pub notify_rounds: bool, +} + +fn default_cap() -> u32 { + 3 +} + +fn default_true() -> bool { + true +} + +fn default_silence() -> u32 { + 20 +} + +impl ReviewRequest { + pub fn into_setup(self, loop_setup: &loop_driver::LoopSetup) -> ReviewSetup { + ReviewSetup { + scope: self.scope, + spec: self.spec.filter(|spec| !spec.trim().is_empty()), + cap: self.cap, + commit: self.commit, + pre_run_commit_agreed: self.pre_run_commit_agreed, + suggestions: self.suggestions, + strength: Strength::from_word(&self.strength), + silence_minutes: self.silence_minutes.clamp(1, 60), + notify_rounds: self.notify_rounds, + notify_kind: loop_setup.notify_kind, + notify_url: loop_setup.notify_url.clone(), + notify_param: loop_setup.notify_param.clone(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::tests::{ + fake_agent_launch, fake_agent_manager, git_in, harness_ready, wait_until, + }; + use serde_json::json; + + #[test] + fn every_ending_notice_names_the_round_and_a_stop_by_the_person_sends_none() { + assert_eq!( + stop_words(&StopReason::Cap, 3, 0).as_deref(), + Some("stopped at the round cap after round 3.") + ); + assert!(stop_words(&StopReason::Clean, 2, 0) + .unwrap() + .contains("after round 2")); + assert!(stop_words(&StopReason::Clean, 2, 1) + .unwrap() + .ends_with("1 finding an earlier round left unfixed is still open.")); + assert!(stop_words(&StopReason::Failed("tests failed".into()), 2, 0) + .unwrap() + .starts_with("failed in round 2: tests failed")); + assert_eq!(stop_words(&StopReason::Person, 1, 0), None); + } + + /// A new repository on `main` in a unique temp folder, with a committed + /// `a.txt` and a `.gitignore` for `ignored.log`, its config scrubbed of + /// anything global. + fn scratch_repo(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!( + "plan2code-review-loop-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&base); + let repo = base.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git_in(&repo, &["init", "-q"]); + git_in(&repo, &["symbolic-ref", "HEAD", "refs/heads/main"]); + for (key, value) in [ + ("user.name", "Review Test"), + ("user.email", "review@example.com"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git_in(&repo, &["config", key, value]); + } + std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap(); + std::fs::write(repo.join(".gitignore"), "ignored.log\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "first"]); + repo + } + + struct Rig { + rc: RoundCtx, + repo: PathBuf, + home: PathBuf, + phases: LoopSlot, + events: Arc>>, + } + + fn hooks_into(events: &Arc>>) -> Hooks { + let sink = Arc::clone(events); + Hooks { + emit: Box::new(move |event| lock(&sink).push(event)), + attention: Box::new(|| {}), + } + } + + /// A run on a scratch repo with the fake agent, round 1 started, and no + /// watch thread: a test plays the watcher by calling `tick`. + fn rig(name: &str, setup: ReviewSetup, shape: Shape) -> Rig { + rig_on(scratch_repo(name), setup, shape) + } + + fn rig_on(repo: PathBuf, setup: ReviewSetup, shape: Shape) -> Rig { + let home = repo.parent().unwrap().join("console-home"); + std::fs::create_dir_all(home.join("sessions")).unwrap(); + let launch = fake_agent_launch(); + let mut run = prepare_run(&repo, &launch, setup, &home).expect("the run prepares"); + run.shape = shape; + let (agent, _seen) = fake_agent_manager(&repo); + let events = Arc::new(Mutex::new(Vec::new())); + let ctx = new_ctx( + &run, + agent, + home.clone(), + hooks_into(&events), + Limits::default(), + ); + let rc = RoundCtx { + slot: Arc::new(Mutex::new(Some(run))), + ctx, + }; + start_stage(&rc, first_stage(shape), 1).expect("round 1 starts"); + Rig { + rc, + repo, + home, + phases: Arc::new(Mutex::new(None)), + events, + } + } + + fn snap(rig: &Rig) -> ReviewRun { + lock(&rig.rc.slot).clone().expect("a run") + } + + fn done(rig: &Rig) { + rig.rc.ctx.agent.stop(); + let _ = std::fs::remove_dir_all(rig.repo.parent().unwrap()); + } + + fn subjects(repo: &Path) -> Vec { + git_in(repo, &["log", "--format=%s"]) + .lines() + .map(str::to_string) + .collect() + } + + /// A `roundOutcome` the way a round agent posts it. + fn outcome(round: u32, role: &str, critical: u32, warning: u32, fixed: &[&str]) -> Value { + let list: Vec = fixed + .iter() + .map(|title| json!({ "title": title, "file": "a.txt" })) + .collect(); + let mut value = json!({ + "round": round, "role": role, "result": "passed", "reason": null, + "summary": "Round done", + "review": { "critical": critical, "warning": warning, "suggestion": 0, + "fixed": list, "unfixed": [], "suggestions": [] }, + "tests": { "ran": true, "passed": true, "summary": "ok" }, + }); + if role != "fixer" { + value["report"] = json!("report"); + } + if role == "reviewer" { + value.as_object_mut().unwrap().remove("tests"); + value["review"]["unfixed"] = json!(fixed + .iter() + .map(|title| json!({ "title": title, "file": "a.txt" })) + .collect::>()); + value["review"]["fixed"] = json!([]); + } + value + } + + /// Put `outcome` in session `sid` (with the report doc it names, as the + /// console holds it), make `sid` the round's session, and take one look. + fn answer(rig: &Rig, sid: &str, outcome: Value) -> bool { + let mut state = json!({ "schema": session_reader::SCHEMA, "roundOutcome": outcome }); + if let Some(id) = state["roundOutcome"]["report"].as_str() { + state["docs"] = json!([{ "id": id, "kind": "report", "title": "Review round", + "blocks": [{ "id": "r", "md": "Found things to fix." }] }]); + } + let dir = rig.home.join("sessions").join(sid); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("state.json"), state.to_string()).unwrap(); + with_run(&rig.rc, |run| run.sid = Some(sid.to_string())); + tick(&rig.rc) + } + + fn edit(rig: &Rig, file: &str, text: &str) { + std::fs::write(rig.repo.join(file), text).unwrap(); + } + + fn one_session(name: &str, setup: ReviewSetup) -> Option { + harness_ready(name).then(|| rig(name, setup, Shape::OneSession)) + } + + fn go_on(rig: &Rig) -> Result<(), String> { + continue_run( + &rig.rc.slot, + &rig.phases, + Arc::clone(&rig.rc.ctx.agent), + hooks_into(&rig.events), + Limits::default(), + rig.home.clone(), + false, + ) + } + + fn rows() -> BTreeMap { + ["thrifty", "balanced", "best"] + .into_iter() + .map(|word| { + ( + word.to_string(), + StrengthRow { + model: format!("{word}-model"), + effort: None, + }, + ) + }) + .collect() + } + + // ------------------------------------------------------------ pure parts + + fn finding(title: &str, file: &str, line: Option) -> Finding { + Finding { + title: title.into(), + file: file.into(), + line, + } + } + + #[test] + fn suggestions_drop_repeats_fixed_ones_and_ones_the_latest_reviewer_dropped() { + let timer = finding("Name the timer", "x.js", Some(4)); + let handle = finding("Close the handle", "z.js", Some(9)); + let first = merge_suggestions(&[], std::slice::from_ref(&timer), &[], &["x.js".into()]); + assert_eq!(first, vec![timer.clone()]); + let again = merge_suggestions(&first, std::slice::from_ref(&timer), &[], &["x.js".into()]); + assert_eq!(again.len(), 1, "a repeat is kept once"); + let fixed = merge_suggestions(&first, &[], std::slice::from_ref(&timer), &["x.js".into()]); + assert!(fixed.is_empty(), "a later round fixed that file and line"); + let seen = ["x.js".to_string(), "z.js".to_string()]; + let dropped = merge_suggestions(&first, std::slice::from_ref(&handle), &[], &seen); + assert_eq!( + dropped, + vec![handle.clone()], + "the latest reviewer saw x.js and left it out" + ); + let kept = merge_suggestions( + &first, + std::slice::from_ref(&handle), + &[], + &["z.js".to_string()], + ); + assert_eq!( + kept, + vec![timer, handle], + "a file the reviewer never saw stays" + ); + } + + #[test] + fn the_round_prompt_names_the_round_the_role_and_the_scope_file() { + let prompt = round_prompt(2, Role::Fixer, Path::new("C:/runs/scope.md")); + assert_eq!( + prompt, + "/plan2code-review --web --loop --round 2 --role fixer --scope-file C:/runs/scope.md" + ); + let spaced = round_prompt(1, Role::Both, Path::new("C:/Jane Doe/scope.md")); + assert!( + spaced.ends_with("--scope-file \"C:/Jane Doe/scope.md\""), + "{spaced}" + ); + } + + #[test] + fn the_banner_event_is_a_rounds_event_and_the_phases_one_is_unchanged() { + let run = ReviewRun::new( + PathBuf::from("."), + ReviewSetup::default(), + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit("a".repeat(40)), + PathBuf::from("runs"), + BTreeMap::new(), + ); + let event = review_state_event(&run); + assert_eq!((event.kind, event.round, event.rounds), ("rounds", 1, 3)); + assert!(event.running && event.round_counts.is_empty()); + assert_eq!(event.phase_name, "Round 1 of 3: Starting"); + let ended = LoopStateEvent::ended(); + assert_eq!((ended.kind, ended.round, ended.rounds), ("phases", 0, 0)); + assert!(ended.round_counts.is_empty() && !ended.stop_after_round); + } + + #[test] + fn a_request_takes_its_notification_from_the_loop_setup_only() { + let request: ReviewRequest = serde_json::from_value(json!({ + "scope": "spec", "spec": "specs/x", "cap": 4, "suggestions": true, + "strength": "best", "silenceMinutes": 99, "notifyRounds": true, + "notifyUrl": "http://evil.example/", "notifyParam": "x" + })) + .unwrap(); + let loop_setup = loop_driver::LoopSetup { + notify_url: "http://mine.example/".into(), + notify_param: "msg".into(), + ..loop_driver::LoopSetup::default() + }; + let setup = request.into_setup(&loop_setup); + assert_eq!(setup.notify_url, "http://mine.example/"); + assert_eq!(setup.notify_param, "msg"); + assert_eq!(setup.silence_minutes, 60, "clamped to an hour"); + assert_eq!(setup.strength, Some(Strength::Best)); + assert!( + setup.commit, + "commits are on unless the page turns them off" + ); + } + + // ---------------------------------------------------- the four stop reasons + + #[test] + fn a_clean_first_round_stops_clean_with_nothing_to_commit() { + let Some(rig) = one_session("clean", ReviewSetup::default()) else { + return; + }; + let head = git_in(&rig.repo, &["rev-parse", "HEAD"]); + assert!( + !answer(&rig, "s1", outcome(1, "both", 0, 0, &[])), + "the run is over" + ); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert!(!run.running); + assert_eq!(run.rounds.len(), 1); + assert_eq!(run.rounds[0].verdict, Some(Verdict::Clean)); + assert_eq!(run.rounds[0].commit, None); + assert_eq!(git_in(&rig.repo, &["rev-parse", "HEAD"]), head); + assert!(!is_running(&rig.rc.slot)); + assert!(lock(&rig.events).last().is_some_and(|e| !e.running)); + done(&rig); + } + + #[test] + fn findings_then_clean_commits_each_round_by_number_and_scopes_round_two_to_round_ones_diff() { + let Some(rig) = one_session("two-rounds", ReviewSetup::default()) else { + return; + }; + edit(&rig, "b.txt", "fixed b\n"); + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + let run = snap(&rig); + assert_eq!( + (run.round, run.stage, run.rounds.len()), + (2, Stage::Both, 1) + ); + // The agent never ran git: the app committed the round. + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b"); + // Round 2 reviews exactly round 1's diff. + let dir = run.run_dir.join("round-2-both-t0"); + let diff = std::fs::read_to_string(dir.join("round-1.diff")).unwrap(); + assert!( + diff.contains("+++ b/b.txt") && !diff.contains("a.txt"), + "{diff}" + ); + let scope = std::fs::read_to_string(dir.join("scope.md")).unwrap(); + assert!(scope.contains("round-1.diff"), "{scope}"); + edit(&rig, "c.txt", "tidy c\n"); + assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &["Tidy c"]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + let log = subjects(&rig.repo); + assert_eq!(log[0], "Review Loop round 2: Tidy c"); + assert_eq!(log[1], "Review Loop round 1: Fix b"); + assert_eq!(run.rounds.len(), 2); + assert_eq!(run.rounds[1].commit.as_deref().map(str::len), Some(40)); + done(&rig); + } + + #[test] + fn findings_every_round_stop_at_the_cap_after_three_commits() { + let Some(rig) = one_session("cap", ReviewSetup::default()) else { + return; + }; + for n in 1..=3 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let more = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + assert_eq!(more, n < 3, "round {n}"); + } + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Cap)); + assert_eq!(run.rounds.len(), 3); + assert_eq!( + subjects(&rig.repo).len(), + 4, + "three rounds and the first commit" + ); + done(&rig); + } + + #[test] + fn stop_after_this_round_commits_the_round_then_stops() { + let Some(rig) = one_session("stop-after", ReviewSetup::default()) else { + return; + }; + let event = request_stop_after(&rig.rc.slot, true).unwrap(); + assert!(event.stop_after_round); + edit(&rig, "b.txt", "x\n"); + assert!(!answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b"); + assert_eq!(run.rounds.len(), 1); + done(&rig); + } + + #[test] + fn stop_now_commits_nothing_and_keep_leaves_the_partial_changes() { + let Some(rig) = one_session("stop-now-keep", ReviewSetup::default()) else { + return; + }; + let before = git_in(&rig.repo, &["rev-parse", "HEAD"]); + edit(&rig, "a.txt", "changed\n"); + edit(&rig, "p.txt", "new\n"); + request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap(); + assert!(!tick(&rig.rc), "the next look ends the run"); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert_eq!( + git_in(&rig.repo, &["rev-parse", "HEAD"]), + before, + "nothing committed" + ); + let info = run.partial.clone().expect("partial data"); + assert!(info.pending && info.files == 2, "{info:?}"); + let diff = std::fs::read_to_string(&info.diff).unwrap(); + assert!(diff.contains("+++ b/p.txt") && diff.contains("+++ b/a.txt")); + // Continue is held until the partial changes are settled. + assert!(go_on(&rig).unwrap_err().contains("partial changes")); + partial(&rig.rc.slot, true).unwrap(); + assert_eq!( + std::fs::read_to_string(rig.repo.join("a.txt")).unwrap(), + "changed\n" + ); + assert!(rig.repo.join("p.txt").exists()); + assert!(snap(&rig).partial.is_some_and(|p| !p.pending)); + done(&rig); + } + + #[test] + fn stop_now_then_discard_puts_back_tracked_files_and_removes_only_the_rounds_new_ones() { + for (commit, name) in [(true, "discard-commit"), (false, "discard-snapshot")] { + let setup = ReviewSetup { + commit, + ..ReviewSetup::default() + }; + let Some(rig) = one_session(name, setup) else { + return; + }; + // An ignored file that was there before the round: never touched. + std::fs::write(rig.repo.join("ignored.log"), "mine\n").unwrap(); + edit(&rig, "a.txt", "changed\n"); + edit(&rig, "p.txt", "new\n"); + request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap(); + assert!(!tick(&rig.rc)); + partial(&rig.rc.slot, false).unwrap(); + assert_eq!( + std::fs::read_to_string(rig.repo.join("a.txt")).unwrap(), + "one\ntwo\n", + "{name}: the tracked file is back" + ); + assert!( + !rig.repo.join("p.txt").exists(), + "{name}: the round's new file is gone" + ); + assert!( + rig.repo.join("ignored.log").exists(), + "{name}: ignored files are never touched" + ); + assert!(snap(&rig).partial.is_some_and(|p| !p.pending)); + // Settled once: a second answer has nothing to act on. + assert!(partial(&rig.rc.slot, false).is_err()); + done(&rig); + } + } + + #[test] + fn continue_past_the_cap_runs_one_round_at_a_time_and_refuses_a_seventh() { + let Some(rig) = one_session("continue", ReviewSetup::default()) else { + return; + }; + for n in 1..=3 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap)); + // Each Continue past the cap adds exactly one round. + for n in 4..=6 { + go_on(&rig).unwrap_or_else(|e| panic!("continue for round {n}: {e}")); + let run = snap(&rig); + assert_eq!((run.round, run.cap, run.running), (n, n, true)); + edit(&rig, &format!("f{n}.txt"), "x\n"); + assert!(!answer( + &rig, + &format!("s{n}"), + outcome(n, "both", 0, 1, &["Fix"]) + )); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap)); + } + assert_eq!( + go_on(&rig).unwrap_err(), + "A Review Loop runs at most 6 rounds." + ); + assert_eq!(snap(&rig).rounds.len(), 6); + // A run that finished clean has nothing to continue. + with_run(&rig.rc, |run| run.stop_reason = Some(StopReason::Clean)); + assert!(go_on(&rig).unwrap_err().contains("nothing to continue")); + done(&rig); + } + + // ----------------------------------------- shapes, proofs, retries, modes + + #[test] + fn the_two_session_shape_runs_a_reviewer_then_a_fixer_that_gets_the_reviewers_report() { + if !harness_ready("two-session") { + return; + } + let rig = rig("two-session", ReviewSetup::default(), Shape::TwoSession); + assert_eq!(snap(&rig).stage, Stage::Reviewer); + let reviewer_generation = snap(&rig).generation; + assert!(answer(&rig, "r1", outcome(1, "reviewer", 0, 1, &["Fix x"]))); + let run = snap(&rig); + assert_eq!( + run.stage, + Stage::Fixer, + "the fixer starts in its own session" + ); + assert_ne!( + run.generation, reviewer_generation, + "a fresh agent, not the reviewer's" + ); + let fixer = run.run_dir.join("round-1-fixer-t0"); + let report = std::fs::read_to_string(fixer.join("reviewer-report.md")).unwrap(); + assert!( + report.contains("Found things to fix.") && report.contains("Fix x"), + "{report}" + ); + let scope = std::fs::read_to_string(fixer.join("scope.md")).unwrap(); + assert!(scope.contains("reviewer-report.md"), "{scope}"); + assert_eq!( + subjects(&rig.repo).len(), + 1, + "a report alone commits nothing" + ); + edit(&rig, "x.txt", "fixed\n"); + assert!(answer(&rig, "f1", outcome(1, "fixer", 0, 1, &["Fix x"]))); + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix x"); + let run = snap(&rig); + assert_eq!((run.round, run.stage), (2, Stage::Reviewer)); + assert!(!answer(&rig, "r2", outcome(2, "reviewer", 0, 0, &[]))); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Clean)); + done(&rig); + } + + #[test] + fn a_fixer_that_reports_zero_counts_cannot_end_the_run_clean() { + if !harness_ready("fixer-zero") { + return; + } + let rig = rig("fixer-zero", ReviewSetup::default(), Shape::TwoSession); + assert!(answer(&rig, "r1", outcome(1, "reviewer", 0, 1, &["Fix x"]))); + edit(&rig, "x.txt", "fixed\n"); + assert!( + answer(&rig, "f1", outcome(1, "fixer", 0, 0, &["Fix x"])), + "the run goes on: the reviewer found a Warning" + ); + let run = snap(&rig); + assert_eq!((run.round, run.stage), (2, Stage::Reviewer)); + assert_eq!(run.stop_reason, None); + assert_eq!( + run.rounds[0].warning, 1, + "recorded with the reviewer's count" + ); + assert!(!answer(&rig, "r2", outcome(2, "reviewer", 0, 0, &[]))); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Clean)); + done(&rig); + } + + #[test] + fn a_finding_a_round_left_unfixed_stays_open_after_a_clean_fix_diff_round() { + if !harness_ready("carry-open") { + return; + } + let rig = rig("carry-open", ReviewSetup::default(), Shape::OneSession); + let mut first = outcome(1, "both", 0, 2, &["Fix a"]); + first["review"]["unfixed"] = json!([{ "title": "Hard one", "file": "b.txt" }]); + edit(&rig, "a.txt", "fixed\n"); + assert!(answer(&rig, "s1", first)); + assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &[]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + let open = run.open_findings(); + assert_eq!(open.len(), 1); + assert_eq!(open[0].title, "Hard one"); + let line = end_line(&run); + assert!( + line.contains("1 finding an earlier round left unfixed is still open"), + "{line}" + ); + done(&rig); + } + + #[test] + fn a_report_that_ran_no_tests_fails_the_round_and_the_retry_runs_one_strength_up() { + if !harness_ready("no-tests") { + return; + } + let setup = ReviewSetup { + strength: Some(Strength::Thrifty), + ..ReviewSetup::default() + }; + let rig = rig("no-tests", setup, Shape::OneSession); + with_run(&rig.rc, |run| run.strength_rows = rows()); + let mut bad = outcome(1, "both", 0, 0, &[]); + bad["tests"] = json!({ "ran": false, "passed": false, "summary": "" }); + assert!( + answer(&rig, "s1", bad.clone()), + "a first failure is retried" + ); + let run = snap(&rig); + assert!(run.retried && run.running); + assert_eq!(run.cur_strength, Some(Strength::Balanced)); + assert!(run.cur.retried && !run.cur.could_not_step_up); + assert!(!answer(&rig, "s2", bad), "the second failure stops the run"); + let run = snap(&rig); + assert_eq!( + run.stop_reason, + Some(StopReason::Failed("targeted tests did not run".into())) + ); + assert!(run.rounds.is_empty()); + done(&rig); + } + + #[test] + fn a_second_failure_keeps_the_rounds_that_finished_and_best_cannot_step_up() { + if !harness_ready("keep-finished") { + return; + } + let setup = ReviewSetup { + strength: Some(Strength::Best), + ..ReviewSetup::default() + }; + let rig = rig("keep-finished", setup, Shape::OneSession); + with_run(&rig.rc, |run| run.strength_rows = rows()); + edit(&rig, "b.txt", "x\n"); + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + let mut failed = outcome(2, "both", 0, 0, &[]); + failed["result"] = json!("failed"); + failed["reason"] = json!("tests"); + assert!(answer(&rig, "s2", failed.clone())); + let run = snap(&rig); + assert_eq!(run.cur_strength, Some(Strength::Best)); + assert!( + run.cur.could_not_step_up, + "Best stays Best, and the report says so" + ); + assert!(!answer(&rig, "s3", failed)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Failed("tests".into()))); + assert_eq!(run.rounds.len(), 1, "round 1 is kept"); + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b"); + done(&rig); + } + + #[test] + fn a_crashed_agent_gets_one_retry_then_stops_the_run() { + let Some(rig) = one_session("crash", ReviewSetup::default()) else { + return; + }; + let dir = rig.home.join("sessions/s1"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("state.json"), json!({ "schema": 1 }).to_string()).unwrap(); + for attempt in ["first", "second"] { + with_run(&rig.rc, |run| run.sid = Some("s1".into())); + wait_until("the fake agent to be up", || { + rig.rc.ctx.agent.snapshot().state == AgentState::Running + }); + rig.rc.ctx.agent.input(b"EXIT 3\r").unwrap(); + wait_until("the agent to end", || { + matches!(rig.rc.ctx.agent.snapshot().state, AgentState::Ended { .. }) + }); + let goes_on = tick(&rig.rc); + assert_eq!(goes_on, attempt == "first", "{attempt} crash"); + } + let run = snap(&rig); + assert!( + matches!(run.stop_reason, Some(StopReason::Failed(ref why)) if why.contains("crashed")), + "{:?}", + run.stop_reason + ); + done(&rig); + } + + #[test] + fn snapshot_mode_diffs_between_snapshots_and_makes_no_commit() { + let setup = ReviewSetup { + commit: false, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("snapshot", setup) else { + return; + }; + assert!(matches!(snap(&rig).start, Boundary::Tree(_))); + edit(&rig, "b.txt", "fixed b\n"); + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + assert_eq!( + subjects(&rig.repo), + vec!["first"], + "no commit in snapshot mode" + ); + let run = snap(&rig); + assert!(matches!(run.rounds[0].boundary, Some(Boundary::Tree(_)))); + assert_eq!(run.rounds[0].commit, None); + let diff = + std::fs::read_to_string(run.run_dir.join("round-2-both-t0/round-1.diff")).unwrap(); + assert!(diff.contains("+++ b/b.txt"), "{diff}"); + assert_eq!( + git_in(&rig.repo, &["status", "--porcelain"]).trim(), + "?? b.txt", + "the work stays in the tree, uncommitted" + ); + done(&rig); + } + + #[test] + fn the_pre_run_commit_is_made_only_when_agreed() { + if !harness_ready("pre-run") { + return; + } + let repo = scratch_repo("pre-run"); + let home = repo.parent().unwrap().join("console-home"); + std::fs::write(repo.join("d.txt"), "mine\n").unwrap(); + let launch = fake_agent_launch(); + let refused = prepare_run(&repo, &launch, ReviewSetup::default(), &home).unwrap_err(); + assert!(refused.contains("uncommitted changes"), "{refused}"); + assert_eq!(subjects(&repo), vec!["first"], "nothing was committed"); + let setup = ReviewSetup { + pre_run_commit_agreed: true, + ..ReviewSetup::default() + }; + let run = prepare_run(&repo, &launch, setup, &home).expect("agreed"); + assert_eq!(subjects(&repo)[0], "Work before Review Loop"); + let head = git_in(&repo, &["rev-parse", "HEAD"]); + assert_eq!(run.pre_run_commit.as_deref(), Some(head.as_str())); + assert_eq!(run.start, Boundary::Commit(head)); + assert!(git_in(&repo, &["status", "--porcelain"]).trim().is_empty()); + // Commits off needs no agreement: the tree is only measured. + std::fs::write(repo.join("e.txt"), "more\n").unwrap(); + let snapshot_only = ReviewSetup { + commit: false, + ..ReviewSetup::default() + }; + let run = prepare_run(&repo, &launch, snapshot_only, &home).expect("snapshot mode"); + assert!(run.pre_run_commit.is_none() && matches!(run.start, Boundary::Tree(_))); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn a_loop_already_running_refuses_a_second_start_and_a_bad_cap() { + if !harness_ready("refuse") { + return; + } + let rig = rig("refuse", ReviewSetup::default(), Shape::OneSession); + let start = |rig: &Rig| { + let (agent, _) = fake_agent_manager(&rig.repo); + start_review_loop_with( + &rig.rc.slot, + &rig.phases, + agent, + fake_agent_launch(), + rig.repo.clone(), + ReviewSetup::default(), + hooks_into(&rig.events), + Limits::default(), + rig.home.clone(), + false, + ) + }; + assert_eq!( + start(&rig).unwrap_err(), + "A loop is already running in this window." + ); + let high = ReviewSetup { + cap: 7, + ..ReviewSetup::default() + }; + let launch = fake_agent_launch(); + assert!(prepare_run(&rig.repo, &launch, high, &rig.home) + .unwrap_err() + .contains("1 to 6")); + // An Implementation Loop running blocks it too. + abandon(&rig.rc.slot); + *lock(&rig.phases) = Some(loop_driver::RunningRecord::new( + rig.repo.clone(), + "specs/x".into(), + loop_driver::LoopSetup::default(), + vec![], + )); + assert_eq!( + start(&rig).unwrap_err(), + "A loop is already running in this window." + ); + done(&rig); + } + + // ---------------------------------------------- the Suggestions batch + + fn with_suggestions(round: u32, role: &str) -> Value { + let mut value = outcome(round, role, 0, 0, &[]); + value["review"]["suggestion"] = json!(1); + value["review"]["suggestions"] = json!([{ "title": "Name the timer", "file": "a.txt" }]); + value + } + + #[test] + fn with_the_switch_on_a_clean_stop_runs_the_batch_and_the_final_check_outside_the_cap() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("batch-on", setup) else { + return; + }; + assert!(answer(&rig, "s1", with_suggestions(1, "both"))); + let run = snap(&rig); + assert_eq!((run.stage, run.round), (Stage::Batch, 2)); + assert_eq!(run.pending_stop, Some(StopReason::Clean)); + assert_eq!(run.suggestions_batch.as_ref().unwrap().briefed.len(), 1); + let scope = std::fs::read_to_string(run.run_dir.join("round-2-batch-t0/scope.md")).unwrap(); + assert!(scope.contains("Name the timer"), "{scope}"); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert_eq!( + subjects(&rig.repo)[0], + "Review Loop Suggestions batch: Name the timer", + "the batch is committed on its own" + ); + let run = snap(&rig); + assert_eq!((run.stage, run.round), (Stage::Final, 3)); + let diff = + std::fs::read_to_string(run.run_dir.join("round-3-final-t0/batch.diff")).unwrap(); + assert!(diff.contains("+++ b/t.txt"), "{diff}"); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert_eq!( + run.rounds.len(), + 1, + "the batch and the check are outside the rounds" + ); + let batch = run.suggestions_batch.unwrap(); + assert_eq!(batch.final_check, Some(Verdict::Clean)); + assert!(batch.commit.is_some()); + done(&rig); + } + + #[test] + fn with_the_switch_off_no_batch_runs() { + let Some(rig) = one_session("batch-off", ReviewSetup::default()) else { + return; + }; + assert!(!answer(&rig, "s1", with_suggestions(1, "both"))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert!(run.suggestions_batch.is_none()); + assert_eq!( + run.collected.len(), + 1, + "collected for the report, not fixed" + ); + done(&rig); + } + + #[test] + fn after_a_person_stop_or_a_failure_no_batch_runs_even_when_on() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("batch-person", setup.clone()) else { + return; + }; + request_stop_after(&rig.rc.slot, true).unwrap(); + edit(&rig, "b.txt", "x\n"); + let mut found = with_suggestions(1, "both"); + found["review"]["warning"] = json!(1); + found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]); + assert!(!answer(&rig, "s1", found)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert!(run.suggestions_batch.is_none()); + done(&rig); + let Some(rig) = one_session("batch-failed", setup) else { + return; + }; + let mut failed = with_suggestions(1, "both"); + failed["result"] = json!("failed"); + failed["reason"] = json!("other"); + assert!(answer(&rig, "s1", failed.clone())); + assert!(!answer(&rig, "s2", failed)); + let run = snap(&rig); + assert!(matches!(run.stop_reason, Some(StopReason::Failed(_)))); + assert!(run.suggestions_batch.is_none()); + done(&rig); + } + + #[test] + fn a_batch_at_the_cap_keeps_the_cap_as_the_stop_reason() { + let setup = ReviewSetup { + suggestions: true, + cap: 1, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("batch-cap", setup) else { + return; + }; + edit(&rig, "b.txt", "x\n"); + let mut found = with_suggestions(1, "both"); + found["review"]["warning"] = json!(1); + found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]); + assert!(answer(&rig, "s1", found)); + assert_eq!(snap(&rig).pending_stop, Some(StopReason::Cap)); + edit(&rig, "t.txt", "x\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 1, &["Late"]))); + assert_eq!( + snap(&rig).stop_reason, + Some(StopReason::Cap), + "the final check's own verdict never changes why the run ended" + ); + done(&rig); + } + + #[test] + fn a_page_announced_for_this_round_and_role_becomes_its_session() { + let Some(rig) = one_session("note-page", ReviewSetup::default()) else { + return; + }; + let unlocked = json!({ "schema": 1 }); + note_page(&rig.rc.slot, "review", "other", &unlocked); + assert_eq!(snap(&rig).sid, None); + assert_eq!(snap(&rig).page_candidate.as_deref(), Some("other")); + let wrong_round = json!({ "loop": { "driving": true, "round": 2, "role": "both" } }); + note_page(&rig.rc.slot, "review", "later", &wrong_round); + assert_eq!(snap(&rig).sid, None); + let right = json!({ "loop": { "driving": true, "round": 1, "role": "both" } }); + note_page(&rig.rc.slot, "implement", "x", &right); + assert_eq!(snap(&rig).sid, None, "only a Review page counts"); + note_page(&rig.rc.slot, "review", "mine", &right); + assert_eq!(snap(&rig).sid.as_deref(), Some("mine")); + done(&rig); + } + + // ------------------------------------------------- the review's fixes + + #[test] + fn a_title_with_shell_characters_is_cleaned_and_the_round_still_commits() { + assert_eq!( + safe_title("Guard `None` in \u{201C}parse\u{201D} $x! \\n"), + "Guard None in 'parse' x n" + ); + let Some(rig) = one_session("shell-title", ReviewSetup::default()) else { + return; + }; + edit(&rig, "b.txt", "x\n"); + let title = "Guard `None` in \"parse\" $x!"; + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &[title]))); + assert_eq!( + subjects(&rig.repo)[0], + "Review Loop round 1: Guard None in 'parse' x" + ); + assert!(git_in(&rig.repo, &["status", "--porcelain"]) + .trim() + .is_empty()); + done(&rig); + } + + #[test] + fn a_refused_subject_takes_the_staged_files_out_again() { + if !harness_ready("refused-subject") { + return; + } + let repo = scratch_repo("refused-subject"); + std::fs::write(repo.join("b.txt"), "x\n").unwrap(); + let long = "x".repeat(150); + let refused = commit_all(&repo, &long, Duration::from_secs(60)); + assert!(refused.is_err(), "a 150 character subject is refused"); + assert!( + git_in(&repo, &["diff", "--cached", "--name-only"]) + .trim() + .is_empty(), + "nothing is left staged" + ); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn the_batch_subject_fits_72_characters_with_its_own_prefix() { + let titles: Vec = [ + "Name the timer correctly everywhere", + "Close the file handle", + ] + .iter() + .map(|t| t.to_string()) + .collect(); + let subject = batch_subject(&titles); + assert!( + subject.starts_with("Review Loop Suggestions batch"), + "{subject}" + ); + assert!(subject.chars().count() <= 72, "{subject}"); + let long = vec!["y".repeat(120)]; + let cut = batch_subject(&long); + assert!(cut.chars().count() <= 72 && cut.ends_with("..."), "{cut}"); + assert_eq!(batch_subject(&[]), "Review Loop Suggestions batch"); + } + + #[test] + fn stop_now_in_the_final_check_then_discard_keeps_the_committed_batch() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("final-discard", setup) else { + return; + }; + assert!(answer(&rig, "s1", with_suggestions(1, "both"))); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert_eq!(snap(&rig).stage, Stage::Final); + // The final check is running; the person stops it and a stray file lands. + edit(&rig, "q.txt", "partial\n"); + request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap(); + assert!(!tick(&rig.rc)); + let info = snap(&rig).partial.expect("partial data"); + assert_eq!( + info.new_files, + vec!["q.txt".to_string()], + "only the stray file" + ); + partial(&rig.rc.slot, false).unwrap(); + assert!(rig.repo.join("t.txt").exists(), "the committed batch stays"); + assert!(!rig.repo.join("q.txt").exists()); + done(&rig); + } + + #[test] + fn the_branch_scope_needs_a_trunk_and_says_so() { + if !harness_ready("no-trunk") { + return; + } + let repo = scratch_repo("no-trunk"); + git_in(&repo, &["branch", "-m", "main", "feature"]); + let err = scope_files(&repo, ReviewScope::Branch, None).unwrap_err(); + assert!(err.contains("no main or master branch"), "{err}"); + let spec_err = scope_files(&repo, ReviewScope::Spec, Some(".")).unwrap_err(); + assert!(spec_err.contains("no main or master branch"), "{spec_err}"); + assert!(scope_files(&repo, ReviewScope::Uncommitted, None).is_ok()); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn a_final_check_that_fails_twice_keeps_the_reason_the_run_was_ending_for() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("final-fails", setup) else { + return; + }; + assert!(answer(&rig, "s1", with_suggestions(1, "both"))); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + let mut failed = outcome(3, "reviewer", 0, 0, &[]); + failed["result"] = json!("failed"); + failed["reason"] = json!("other"); + assert!( + answer(&rig, "c1", failed.clone()), + "the first failure is retried" + ); + assert!(!answer(&rig, "c2", failed)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean), "not Failed"); + assert!(matches!( + run.suggestions_batch + .as_ref() + .and_then(|b| b.final_check.clone()), + Some(Verdict::Failed(_)) + )); + assert!(run.stop_evidence.is_some_and(|e| e.contains("final check"))); + done(&rig); + } + + #[test] + fn last_boundary_orders_a_kept_batch_among_the_rounds() { + let Some(rig) = one_session("last-boundary", ReviewSetup::default()) else { + return; + }; + let mut run = snap(&rig); + let c = |id: &str| Boundary::Commit(id.to_string()); + let round = |n: u32, id: &str| RoundRecord { + n, + boundary: Some(c(id)), + ..RoundRecord::default() + }; + let batch = |after: usize, id: &str| BatchRecord { + after_rounds: after, + boundary: Some(c(id)), + ..BatchRecord::default() + }; + run.rounds = vec![round(1, "r1"), round(2, "r2")]; + run.earlier_batches = vec![batch(2, "b1")]; + assert_eq!(run.last_boundary(), c("b1"), "the batch came after round 2"); + run.rounds.push(round(3, "r3")); + assert_eq!(run.last_boundary(), c("r3"), "a round after the batch wins"); + run.suggestions_batch = Some(batch(3, "b2")); + assert_eq!(run.last_boundary(), c("b2"), "the current batch is newest"); + done(&rig); + } + + #[test] + fn the_round_after_a_continue_is_scoped_from_the_batch_committed_before_it() { + let Some(rig) = one_session("diff-after-batch", ReviewSetup::default()) else { + return; + }; + let mut run = snap(&rig); + let c = |id: &str| Boundary::Commit(id.to_string()); + let round = |n: u32, id: &str| RoundRecord { + n, + boundary: Some(c(id)), + ..RoundRecord::default() + }; + run.rounds = vec![round(1, "r1"), round(2, "r2")]; + run.earlier_batches = vec![BatchRecord { + after_rounds: 2, + boundary: Some(c("b1")), + ..BatchRecord::default() + }]; + let (from, to) = plan_for(&run, Stage::Both, 3) + .diff + .expect("round 3 has a diff"); + assert_eq!((from, to), (c("r1"), c("b1")), "round 3 sees the batch"); + let (from, to) = plan_for(&run, Stage::Both, 2) + .diff + .expect("round 2 has a diff"); + assert_eq!( + (from, to), + (run.start.clone(), c("r1")), + "an earlier round is unchanged" + ); + done(&rig); + } + + #[test] + fn nul_separated_names_are_never_quoted_or_split_on_spaces() { + assert_eq!( + nul_lines("a b.txt\0caf\u{e9}.txt\0"), + vec!["a b.txt".to_string(), "caf\u{e9}.txt".to_string()] + ); + } + + #[test] + fn continue_after_a_capped_batch_keeps_the_batch_and_never_briefs_it_again() { + let setup = ReviewSetup { + suggestions: true, + cap: 1, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("continue-batch", setup) else { + return; + }; + edit(&rig, "b.txt", "x\n"); + let mut found = with_suggestions(1, "both"); + found["review"]["warning"] = json!(1); + found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]); + assert!(answer(&rig, "s1", found)); + edit(&rig, "t.txt", "x\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap)); + assert!(snap(&rig).collected.is_empty(), "the batch fixed them"); + go_on(&rig).unwrap(); + let run = snap(&rig); + assert_eq!((run.round, run.cap), (2, 2)); + assert_eq!(run.earlier_batches.len(), 1, "the first batch is kept"); + assert!(run.earlier_batches[0].commit.is_some()); + assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &[]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert!(run.suggestions_batch.is_none(), "no second batch"); + done(&rig); + } + + #[test] + fn discard_works_from_the_repositorys_top_when_the_project_is_a_folder_inside_it() { + if !harness_ready("subfolder") { + return; + } + let repo = scratch_repo("subfolder"); + std::fs::create_dir_all(repo.join("sub")).unwrap(); + std::fs::write(repo.join("sub/y.txt"), "y\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "add sub"]); + let head = git_in(&repo, &["rev-parse", "HEAD"]); + let mut run = ReviewRun::new( + repo.join("sub"), + ReviewSetup::default(), + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit(head), + repo.parent().unwrap().join("runs"), + BTreeMap::new(), + ); + run.running = false; + run.stop_reason = Some(StopReason::Person); + run.partial = Some(Partial { + pending: true, + new_files: vec!["sub/new.txt".to_string()], + ..Partial::default() + }); + let slot: ReviewSlot = Arc::new(Mutex::new(Some(run))); + std::fs::write(repo.join("sub/y.txt"), "changed\n").unwrap(); + std::fs::write(repo.join("a.txt"), "changed\n").unwrap(); + std::fs::write(repo.join("sub/new.txt"), "new\n").unwrap(); + partial(&slot, false).unwrap(); + assert_eq!( + std::fs::read_to_string(repo.join("sub/y.txt")).unwrap(), + "y\n" + ); + assert_eq!( + std::fs::read_to_string(repo.join("a.txt")).unwrap(), + "one\ntwo\n", + "a tracked file outside the project folder is put back too" + ); + assert!(!repo.join("sub/new.txt").exists()); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + // ------------------------------------------------------ Phase 6: the end + + /// A run's finished state with `rounds` committed rounds on a scratch repo, + /// stopped at the cap: the state sign-off starts from. + fn capped(name: &str, setup: ReviewSetup, rounds: u32) -> Option { + let rig = one_session(name, setup)?; + for n in 1..=rounds { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + Some(rig) + } + + fn sign(rig: &Rig, picks: &[&str], squash: bool) -> Result<(), String> { + let picks: Vec = picks.iter().map(|p| p.to_string()).collect(); + sign_off( + &rig.rc.slot, + &rig.phases, + Arc::clone(&rig.rc.ctx.agent), + hooks_into(&rig.events), + Limits::default(), + rig.home.clone(), + &picks, + squash, + false, + ) + } + + #[test] + fn squashing_three_round_commits_makes_one_commit_and_keeps_the_commit_before_the_run() { + let Some(rig) = capped("squash-three", ReviewSetup::default(), 3) else { + return; + }; + let before = subjects(&rig.repo); + assert_eq!(before.len(), 4, "three rounds and the first commit"); + assert!(can_squash(&snap(&rig))); + sign(&rig, &[], true).expect("sign-off with no picks runs no agent"); + let run = snap(&rig); + assert!(run.signed_off); + match &run.signoff.as_ref().unwrap().squash { + Squash::Done { commits, commit } => { + assert_eq!(*commits, 3); + assert_eq!(commit.as_str(), git_in(&rig.repo, &["rev-parse", "HEAD"])); + } + other => panic!("expected a squash, got {other:?}"), + } + let after = subjects(&rig.repo); + assert_eq!( + after.len(), + 2, + "one squash commit on top of the first: {after:?}" + ); + assert!( + after[0].starts_with("Review Loop rounds 1 to 3"), + "{after:?}" + ); + assert_eq!(after[1], "first", "the commit before the run is untouched"); + for n in 1..=3 { + assert!(rig.repo.join(format!("f{n}.txt")).exists(), "f{n}.txt"); + } + assert_eq!( + git_in(&rig.repo, &["status", "--porcelain"]), + "", + "the tree is clean after the squash" + ); + done(&rig); + } + + #[test] + fn the_squash_never_includes_the_pre_run_commit() { + if !harness_ready("squash-pre") { + return; + } + let repo = scratch_repo("squash-pre"); + std::fs::write(repo.join("mine.txt"), "mine\n").unwrap(); + let setup = ReviewSetup { + pre_run_commit_agreed: true, + cap: 2, + ..ReviewSetup::default() + }; + let rig = rig_on(repo, setup, Shape::OneSession); + for n in 1..=2 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + assert_eq!(subjects(&rig.repo)[2], "Work before Review Loop"); + sign(&rig, &[], true).unwrap(); + let after = subjects(&rig.repo); + assert_eq!(after.len(), 3, "{after:?}"); + assert!( + after[0].starts_with("Review Loop rounds 1 to 2"), + "{after:?}" + ); + assert_eq!(after[1], "Work before Review Loop"); + done(&rig); + } + + #[test] + fn the_squash_refuses_when_a_commit_that_is_not_the_runs_sits_on_top() { + let Some(rig) = capped("squash-foreign", ReviewSetup::default(), 3) else { + return; + }; + std::fs::write(rig.repo.join("other.txt"), "other\n").unwrap(); + git_in(&rig.repo, &["add", "-A"]); + git_in(&rig.repo, &["commit", "-q", "-m", "somebody else"]); + let before = subjects(&rig.repo); + sign(&rig, &[], true).unwrap(); + let run = snap(&rig); + assert!(run.signed_off, "the sign-off still finishes"); + assert_eq!( + run.signoff.unwrap().squash, + Squash::Refused(FOREIGN_COMMIT.to_string()) + ); + assert_eq!(subjects(&rig.repo), before, "nothing was rewritten"); + done(&rig); + } + + #[test] + fn the_squash_switch_needs_commit_mode_and_two_round_commits() { + let Some(rig) = capped("squash-switch", ReviewSetup::default(), 1) else { + return; + }; + assert!(!can_squash(&snap(&rig)), "one round commit"); + done(&rig); + let snapshots = ReviewSetup { + commit: false, + ..ReviewSetup::default() + }; + let Some(rig) = capped("squash-snap", snapshots, 2) else { + return; + }; + assert!(!can_squash(&snap(&rig)), "snapshot mode makes no commits"); + done(&rig); + } + + #[test] + fn picked_suggestions_run_as_one_fixer_session_with_its_own_commit_and_a_fresh_check() { + let Some(rig) = one_session("sign-picks", ReviewSetup::default()) else { + return; + }; + assert!(!answer(&rig, "s1", with_suggestions(1, "both"))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert_eq!(run.collected.len(), 1); + let patch = end_patch_for(&run, false, "report"); + assert_eq!(patch["loopEnd"]["suggestions"][0]["id"], "s1"); + assert_eq!( + patch["loopEnd"]["suggestions"][0]["title"], + "Name the timer" + ); + assert!( + sign(&rig, &["s9"], false).is_err(), + "an unknown pick is refused" + ); + sign(&rig, &["s1"], false).expect("sign-off starts the fix"); + let run = snap(&rig); + assert!(run.signing && run.running); + assert_eq!((run.stage, run.round), (Stage::Batch, 2)); + assert_eq!(run.suggestions_batch.as_ref().unwrap().briefed.len(), 1); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert_eq!( + subjects(&rig.repo)[0], + "Review Loop Suggestions batch: Name the timer" + ); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert!(run.signed_off && !run.signing && !run.running); + assert_eq!( + run.stop_reason, + Some(StopReason::Clean), + "the reason is kept" + ); + let signoff = run.signoff.clone().unwrap(); + assert_eq!(signoff.picked.len(), 1); + assert!(signoff.left.is_empty()); + assert_eq!( + run.suggestions_batch.unwrap().final_check, + Some(Verdict::Clean) + ); + assert!( + sign(&rig, &[], false).is_err(), + "a second sign-off is refused" + ); + done(&rig); + } + + #[test] + fn a_signed_off_run_cannot_continue() { + let Some(rig) = capped("signed-continue", ReviewSetup::default(), 3) else { + return; + }; + sign(&rig, &[], false).unwrap(); + let err = go_on(&rig).unwrap_err(); + assert!(err.contains("signed off"), "{err}"); + done(&rig); + } + + fn spec_run(project: &Path, scope: ReviewScope, spec: Option<&str>) -> ReviewRun { + let setup = ReviewSetup { + scope, + spec: spec.map(str::to_string), + ..ReviewSetup::default() + }; + let mut run = ReviewRun::new( + project.to_path_buf(), + setup, + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit("0".repeat(40)), + PathBuf::new(), + BTreeMap::new(), + ); + run.stop_reason = Some(StopReason::Clean); + run.running = false; + run + } + + #[test] + fn the_report_goes_into_the_spec_folder_only_for_a_spec_launch() { + let base = + std::env::temp_dir().join(format!("plan2code-review-report-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("specs/demo")).unwrap(); + let spec = spec_run(&base, ReviewScope::Spec, Some("specs/demo")); + let first = write_spec_report(&spec, "# one").expect("a spec launch writes it"); + assert!(first.starts_with(base.join("specs/demo"))); + assert!(first + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("REVIEW-LOOP-")); + // A rerun after sign-off replaces the same file. + let mut again = spec.clone(); + again.report_file = Some(first.clone()); + assert_eq!(write_spec_report(&again, "# two"), Some(first.clone())); + assert_eq!(std::fs::read_to_string(&first).unwrap(), "# two"); + // Another run the same day takes a new name. + let second = write_spec_report(&spec, "# three").unwrap(); + assert_ne!(second, first); + assert!(second.to_string_lossy().ends_with("-2.md")); + for scope in [ReviewScope::Branch, ReviewScope::Uncommitted] { + let run = spec_run(&base, scope, Some("specs/demo")); + assert_eq!(write_spec_report(&run, "# no"), None, "{scope:?}"); + } + let escaping = spec_run(&base, ReviewScope::Spec, Some("../elsewhere")); + assert_eq!(write_spec_report(&escaping, "# no"), None); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn the_report_list_gains_a_review_entry_and_old_entries_still_load() { + let base = + std::env::temp_dir().join(format!("plan2code-review-list-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let project = base.join("project"); + std::fs::create_dir_all(&project).unwrap(); + let mut old = crate::loop_report::LoopReport::new("specs/old", "2026-11-01 09:00"); + old.entries.push(ReportEntry { + phase: 4, + name: "P4".into(), + ..ReportEntry::default() + }); + report_list::save_report(&base, &project, &old).unwrap(); + // A report written before the kind existed reads as an Implementation one. + let file = base.join(crate::loop_report::REPORTS_FILE); + let mut store: Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + for report in store["reports"].as_object_mut().unwrap().values_mut() { + for entry in report["entries"].as_array_mut().unwrap() { + entry.as_object_mut().unwrap().remove("kind"); + entry.as_object_mut().unwrap().remove("rounds"); + } + } + std::fs::write(&file, store.to_string()).unwrap(); + let mut run = spec_run(&project, ReviewScope::Branch, None); + run.rounds.push(RoundRecord { + n: 1, + critical: 1, + commit: Some("a".repeat(40)), + ..RoundRecord::default() + }); + save_review_entry(&base, &run).unwrap(); + let loaded = report_list::load_reports(&base, &project, "specs/old").unwrap(); + assert_eq!(loaded.entries[0].kind, EntryKind::Implementation); + assert_eq!(loaded.entries[0].name, "P4"); + let mine = report_list::load_reports(&base, &project, &format!("review-loop:{}", run.id)) + .expect("the review run has its own key"); + assert_eq!(mine.entries[0].kind, EntryKind::Review); + assert_eq!(mine.entries[0].rounds.len(), 1); + assert_eq!(mine.entries[0].rounds[0].critical, 1); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn the_end_post_names_the_reason_the_report_continue_and_what_is_open() { + let base = + std::env::temp_dir().join(format!("plan2code-review-end-{}", std::process::id())); + let mut run = spec_run(&base, ReviewScope::Branch, None); + for (n, id) in [(1, "a"), (2, "b")] { + run.rounds.push(RoundRecord { + n, + commit: Some(id.repeat(40)), + unfixed: vec![finding("Missing check", "src/b.rs", Some(40))], + ..RoundRecord::default() + }); + } + run.cap = 2; + for (reason, key, can) in [ + (StopReason::Clean, "clean", false), + (StopReason::Cap, "cap", true), + (StopReason::Person, "person", true), + (StopReason::Failed("tests failed".into()), "failed", true), + ] { + run.stop_reason = Some(reason); + let patch = end_patch_for(&run, false, "# Report"); + let end = &patch["loopEnd"]; + assert_eq!(end["kind"], "review"); + assert_eq!(end["reason"], key); + assert_eq!(end["report"], REPORT_DOC); + assert_eq!(end["canContinue"], can, "{key}"); + assert_eq!(end["canSquash"], true); + assert_eq!(end["open"][0]["file"], "src/b.rs"); + assert_eq!(end["open"][0]["line"], 40); + assert!(end["line"].as_str().unwrap().chars().count() <= 200); + assert!(end.get("signedOff").is_none()); + assert_eq!(patch["docs"][0]["id"], REPORT_DOC); + } + run.rounds.clear(); + run.cap = 6; + run.stop_reason = Some(StopReason::Cap); + for n in 1..=6 { + run.rounds.push(RoundRecord { + n, + ..RoundRecord::default() + }); + } + assert!(!can_continue(&run), "never past six rounds"); + run.signed_off = true; + run.stop_reason = Some(StopReason::Person); + let patch = end_patch_for(&run, false, "# Report"); + assert_eq!(patch["loopEnd"]["signedOff"], true); + assert_eq!(patch["loopEnd"]["canContinue"], false); + } + + #[test] + fn partial_changes_ride_the_end_post_and_hide_continue() { + let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None); + run.stop_reason = Some(StopReason::Person); + run.partial = Some(Partial { + pending: true, + files: 2, + added: 5, + removed: 1, + ..Partial::default() + }); + let patch = end_patch_for(&run, true, "# Report"); + assert_eq!(patch["loopEnd"]["partial"]["files"], 2); + assert_eq!(patch["loopEnd"]["partial"]["diff"], PARTIAL_DOC); + assert_eq!(patch["docs"][1]["blocks"][0]["diff"], "partial.diff"); + assert_eq!(patch["loopEnd"]["canContinue"], false); + let without = end_patch_for(&run, false, "# Report"); + assert!(without["loopEnd"].get("partial").is_none()); + run.partial.as_mut().unwrap().pending = false; + assert!(end_patch_for(&run, true, "# Report")["loopEnd"] + .get("partial") + .is_none()); + assert!(can_continue(&run), "settled partial changes allow Continue"); + } + + #[test] + fn the_finished_screens_next_steps_build_their_prompts_from_the_open_findings() { + let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None); + run.rounds.push(RoundRecord { + n: 1, + unfixed: vec![ + finding("Missing check", "src/b.rs", Some(40)), + finding("Wrong default", "src/c.rs", None), + ], + ..RoundRecord::default() + }); + let slot: ReviewSlot = Arc::new(Mutex::new(Some(run))); + assert_eq!( + next_prompt(&slot, "pr-prep").unwrap(), + "/plan2code-pr-prep --web" + ); + let brief = next_prompt(&slot, "quick-task").unwrap(); + assert!(brief.starts_with("/plan2code-quick-task --web "), "{brief}"); + assert!(brief.contains("1. Missing check (src/b.rs:40)"), "{brief}"); + assert!(brief.contains("2. Wrong default (src/c.rs)"), "{brief}"); + assert!(next_prompt(&slot, "other").is_err()); + lock(&slot).as_mut().unwrap().rounds[0].unfixed.clear(); + assert_eq!( + next_prompt(&slot, "quick-task").unwrap_err(), + "Nothing is left open." + ); + } + + #[test] + fn the_spec_report_needs_a_real_specs_folder_never_the_git_folder_or_src() { + let base = + std::env::temp_dir().join(format!("plan2code-review-spec-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for folder in [".git", "src", "specs/nested/deep"] { + std::fs::create_dir_all(base.join(folder)).unwrap(); + } + for spec in [ + ".git", + "src", + "specs/nested/deep", + "specs/.hidden", + "specs/missing", + ] { + let run = spec_run(&base, ReviewScope::Spec, Some(spec)); + assert_eq!(write_spec_report(&run, "# no"), None, "{spec}"); + } + assert!( + !base.join(".git").join("REVIEW-LOOP.md").exists() + && std::fs::read_dir(base.join("src")) + .unwrap() + .next() + .is_none() + ); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn a_spec_scope_run_refuses_a_folder_that_is_not_a_spec() { + let repo = scratch_repo("not-a-spec"); + let launch = fake_agent_launch(); + let setup = ReviewSetup { + scope: ReviewScope::Spec, + spec: Some("src".to_string()), + ..ReviewSetup::default() + }; + let err = prepare_run(&repo, &launch, setup, &repo.join("home")) + .map(|_| ()) + .unwrap_err(); + assert!(err.contains("not a spec folder"), "{err}"); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + /// A finished spec-scope run on a scratch repo whose spec folder is + /// committed, so only the report is new in it. + fn spec_capped(name: &str) -> Option { + if !harness_ready(name) { + return None; + } + let repo = scratch_repo(name); + std::fs::create_dir_all(repo.join("specs/demo")).unwrap(); + std::fs::write(repo.join("specs/demo/overview.md"), "# demo\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "spec"]); + let setup = ReviewSetup { + scope: ReviewScope::Spec, + spec: Some("specs/demo".to_string()), + cap: 2, + ..ReviewSetup::default() + }; + let rig = rig_on(repo, setup, Shape::OneSession); + with_run(&rig.rc, |run| run.last_sid = Some("sx".to_string())); + for n in 1..=2 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + Some(rig) + } + + fn spec_reports(rig: &Rig) -> Vec { + std::fs::read_dir(rig.repo.join("specs/demo")) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .unwrap() + .to_string_lossy() + .starts_with("REVIEW-LOOP-") + }) + .collect() + } + + #[test] + fn the_end_saves_a_report_entry_and_the_spec_file_and_sign_off_rewrites_both() { + let Some(rig) = spec_capped("end-files") else { + return; + }; + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Cap)); + let kept = + report_list::load_reports(&rig.home, &run.project, &format!("review-loop:{}", run.id)) + .expect("the end saved a review entry"); + assert_eq!(kept.entries[0].kind, EntryKind::Review); + assert_eq!(kept.entries[0].rounds.len(), 2); + let files = spec_reports(&rig); + assert_eq!(files.len(), 1, "{files:?}"); + let first = std::fs::read_to_string(&files[0]).unwrap(); + assert!( + first.starts_with("# Review Loop: Stopped at the round cap"), + "{first}" + ); + assert!(!first.contains("## Sign-off"), "{first}"); + sign(&rig, &[], false).unwrap(); + let files = spec_reports(&rig); + assert_eq!(files.len(), 1, "sign-off rewrites the same file: {files:?}"); + let after = std::fs::read_to_string(&files[0]).unwrap(); + assert!(after.contains("## Sign-off"), "{after}"); + assert!(after.contains("not asked for"), "{after}"); + done(&rig); + } + + #[test] + fn a_picked_fix_never_commits_the_stale_spec_report() { + let Some(rig) = spec_capped("stale-report") else { + return; + }; + with_run(&rig.rc, |run| { + run.collected = vec![finding("Name the timer", "a.txt", None)]; + }); + assert_eq!(spec_reports(&rig).len(), 1); + sign(&rig, &["s1"], false).expect("sign-off starts the fix"); + assert!( + spec_reports(&rig).is_empty(), + "the stale report is out of the way before the fixer commits" + ); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(3, "fixer", 0, 0, &["Name the timer"]) + )); + let committed = git_in(&rig.repo, &["show", "--name-only", "--format=", "HEAD"]); + assert!(!committed.contains("REVIEW-LOOP"), "{committed}"); + assert!(!answer(&rig, "c1", outcome(4, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert!(run.signed_off); + assert_eq!( + spec_reports(&rig).len(), + 1, + "a fresh report is written after sign-off" + ); + done(&rig); + } + + #[test] + fn sign_off_after_a_stop_by_the_person_still_completes_and_keeps_that_reason() { + let Some(rig) = one_session("sign-person", ReviewSetup::default()) else { + return; + }; + request_stop_after(&rig.rc.slot, true).unwrap(); + let mut found = outcome(1, "both", 0, 1, &["Fix"]); + found["review"]["suggestion"] = json!(1); + found["review"]["suggestions"] = json!([{ "title": "Name the timer", "file": "a.txt" }]); + edit(&rig, "b.txt", "x\n"); + assert!(!answer(&rig, "s1", found)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert_eq!(run.collected.len(), 1); + sign(&rig, &["s1"], false).expect("sign-off starts the fix"); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert!(run.signed_off, "the sign-off finished"); + assert_eq!( + run.stop_reason, + Some(StopReason::Person), + "the reason is kept" + ); + assert_eq!(run.signoff.unwrap().problem, None); + done(&rig); + } + + #[test] + fn a_failed_round_is_named_even_after_a_sign_off_moves_the_round_on() { + let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None); + run.stop_reason = Some(StopReason::Failed("tests failed".to_string())); + run.stop_round = 2; + run.round = 5; + assert_eq!(end_line(&run), "Failed in round 2: tests failed."); + } +} diff --git a/plan2code-app/src-tauri/src/review_report.rs b/plan2code-app/src-tauri/src/review_report.rs new file mode 100644 index 0000000..b7e38e2 --- /dev/null +++ b/plan2code-app/src-tauri/src/review_report.rs @@ -0,0 +1,522 @@ +//! The Review Loop's end report: one markdown page that says why the run +//! stopped and what every round found, fixed, committed and tested. Pure, like +//! `loop_driver::summary_markdown()`: the driver hands it the run record and +//! writes the text where it goes (the page, the report list and, for a spec +//! launch, the spec folder). + +use crate::review_loop::{BatchRecord, Mode, ReviewRun, ReviewScope, RoundRecord, Shape, Squash}; +use crate::round_logic::{Finding, StopReason, Verdict}; + +/// The stop reason in the words the report and the end screen lead with. +pub fn reason_words(reason: Option<&StopReason>) -> &'static str { + match reason { + Some(StopReason::Clean) => "Clean", + Some(StopReason::Cap) => "Stopped at the round cap", + Some(StopReason::Person) => "Stopped by you", + Some(StopReason::Failed(_)) => "Failed", + None => "Not finished", + } +} + +/// A commit id as people read it: the first seven characters. +pub fn short_id(id: &str) -> &str { + id.get(..7).unwrap_or(id) +} + +/// `title (file:line)`, leaving out what a finding does not name. +pub fn finding_text(finding: &Finding) -> String { + let title = one_line(&finding.title); + match (finding.file.is_empty(), finding.line) { + (true, _) => title, + (false, None) => format!("{title} (`{}`)", finding.file), + (false, Some(line)) => format!("{title} (`{}:{line}`)", finding.file), + } +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +fn plural(n: usize, one: &str, many: &str) -> String { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {many}") + } +} + +fn scope_words(run: &ReviewRun) -> String { + match (run.scope, run.setup.spec.as_deref()) { + (ReviewScope::Spec, Some(spec)) => format!("the spec {spec}"), + (ReviewScope::Spec, None) => "a spec".to_string(), + (ReviewScope::Branch, _) => "the branch against its base".to_string(), + (ReviewScope::Uncommitted, _) => "the uncommitted changes".to_string(), + } +} + +fn verdict_words(verdict: Option<&Verdict>, critical: u32, warning: u32) -> String { + match verdict { + Some(Verdict::Clean) => "clean".to_string(), + Some(Verdict::Findings { .. }) => format!("{critical} Critical, {warning} Warning"), + Some(Verdict::Failed(reason)) => format!("did not finish ({})", one_line(reason)), + None => "not checked".to_string(), + } +} + +fn strength_words(round: &RoundRecord) -> String { + let word = match round.strength.as_deref() { + Some(word) if !word.is_empty() => word.to_string(), + _ => "as launched".to_string(), + }; + let model = match (round.model.as_deref(), round.effort.as_deref()) { + (Some(model), Some(effort)) => Some(format!("{model}, {effort}")), + (Some(model), None) => Some(model.to_string()), + _ => None, + }; + match model { + Some(model) => format!("{word} ({model})"), + None => word, + } +} + +fn tests_words(round: &RoundRecord) -> String { + match &round.tests { + None => "not reported".to_string(), + Some(t) => { + let result = if !t.ran { + "did not run" + } else if t.passed { + "passed" + } else { + "failed" + }; + let summary = one_line(&t.summary); + if summary.is_empty() { + result.to_string() + } else { + format!("{summary} ({result})") + } + } + } +} + +fn commit_words(round_commit: Option<&str>, mode: Mode) -> String { + match (round_commit, mode) { + (Some(id), _) => format!("`{}`", short_id(id)), + (None, Mode::Snapshot) => "not committed (snapshot mode)".to_string(), + (None, Mode::Commit) => "not committed (nothing changed)".to_string(), + } +} + +fn round_section(md: &mut String, round: &RoundRecord, mode: Mode) { + md.push_str(&format!("\n## Round {}\n\n", round.n)); + md.push_str(&format!( + "- Found: {} Critical, {} Warning, {} Suggestion ({})\n", + round.critical, + round.warning, + round.suggestion, + verdict_words(round.verdict.as_ref(), round.critical, round.warning) + )); + if round.fixed.is_empty() { + md.push_str("- Fixed: nothing\n"); + } else { + let fixed: Vec = round.fixed.iter().map(finding_text).collect(); + md.push_str(&format!("- Fixed: {}\n", fixed.join("; "))); + } + if !round.unfixed.is_empty() { + let open: Vec = round.unfixed.iter().map(finding_text).collect(); + md.push_str(&format!("- Left open: {}\n", open.join("; "))); + } + md.push_str(&format!( + "- Commit: {}\n", + commit_words(round.commit.as_deref(), mode) + )); + md.push_str(&format!("- Targeted tests: {}\n", tests_words(round))); + let time = match (round.started_at.is_empty(), round.ended_at.is_empty()) { + (false, false) => format!("{} to {}", round.started_at, round.ended_at), + (false, true) => format!("started {}", round.started_at), + _ => "not recorded".to_string(), + }; + md.push_str(&format!("- Time: {time}\n")); + md.push_str(&format!("- Strength: {}\n", strength_words(round))); + if round.retried { + if round.could_not_step_up { + md.push_str( + "- Retry: one fresh session after a failure; it could not step up, so it ran at the same level\n", + ); + } else { + md.push_str("- Retry: one fresh session after a failure, one strength up\n"); + } + } + if !round.summary.trim().is_empty() { + md.push_str(&format!("- Summary: {}\n", one_line(&round.summary))); + } +} + +fn batch_section(md: &mut String, batch: &BatchRecord, mode: Mode, title: &str) { + md.push_str(&format!("\n## {title}\n\n")); + md.push_str(&format!( + "- Briefed with {}\n", + plural(batch.briefed.len(), "Suggestion", "Suggestions") + )); + md.push_str(&format!( + "- Commit: {}\n", + commit_words(batch.commit.as_deref(), mode) + )); + match &batch.final_check { + Some(verdict) => md.push_str(&format!( + "- Final check by a fresh reviewer: {}\n", + verdict_words(Some(verdict), batch.final_critical, batch.final_warning) + )), + None => md.push_str("- Final check by a fresh reviewer: not run\n"), + } + if !batch.summary.trim().is_empty() { + md.push_str(&format!("- Summary: {}\n", one_line(&batch.summary))); + } +} + +/// The whole report for `run`, as it stands: after a stop, and again after +/// sign-off with what was picked and whether the squash ran. +pub fn review_report_markdown(run: &ReviewRun) -> String { + let reason = run.stop_reason.as_ref(); + let mut md = format!("# Review Loop: {}\n\n", reason_words(reason)); + if let Some(StopReason::Failed(why)) = reason { + md.push_str(&format!("Why it failed: {}\n\n", one_line(why))); + } + let rounds_run = run.rounds.len(); + md.push_str(&format!( + "- Rounds run: {} of at most {}\n", + rounds_run, run.cap + )); + md.push_str(&format!("- Reviewed: {}\n", scope_words(run))); + md.push_str(&format!( + "- Mode: {}\n", + match run.mode { + Mode::Commit => "each round committed", + Mode::Snapshot => "snapshots only, nothing committed", + } + )); + md.push_str(&format!( + "- Shape: {}\n", + match run.shape { + Shape::OneSession => "one session per round, with a helper reviewing", + Shape::TwoSession => "two sessions per round, a reviewer and then a fixer", + } + )); + if let Some(id) = &run.pre_run_commit { + md.push_str(&format!( + "- Work before the run was committed first: `{}`\n", + short_id(id) + )); + } + if let Some(evidence) = run + .stop_evidence + .as_deref() + .filter(|e| !e.trim().is_empty()) + { + md.push_str(&format!("- Evidence: {}\n", one_line(evidence))); + } + + for round in &run.rounds { + round_section(&mut md, round, run.mode); + } + for batch in run + .earlier_batches + .iter() + .chain(run.suggestions_batch.iter()) + { + batch_section(&mut md, batch, run.mode, "Suggestions batch"); + } + + md.push_str("\n## Still open\n\n"); + let open = run.open_findings(); + if open.is_empty() { + md.push_str("No Critical or Warning findings are open.\n"); + } else { + md.push_str("Critical or Warning findings no round fixed:\n\n"); + for finding in &open { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + + md.push_str("\n## Suggestions\n\n"); + match &run.signoff { + Some(signoff) => { + if signoff.picked.is_empty() { + md.push_str("Nothing was picked at sign-off.\n"); + } else { + md.push_str("Picked at sign-off:\n\n"); + for finding in &signoff.picked { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + if let Some(problem) = &signoff.problem { + md.push_str(&format!("\nNot all were fixed: {}\n", one_line(problem))); + } + if !signoff.left.is_empty() { + md.push_str("\nLeft alone:\n\n"); + for finding in &signoff.left { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + } + None => { + let applied = run + .earlier_batches + .iter() + .chain(run.suggestions_batch.iter()); + let applied_count: usize = applied.map(|batch| batch.briefed.len()).sum(); + if applied_count > 0 { + md.push_str(&format!( + "{} fixed in the batch above, with its final check.\n", + plural(applied_count, "Suggestion was", "Suggestions were") + )); + } + if run.collected.is_empty() { + if applied_count == 0 { + md.push_str("No Suggestions were collected.\n"); + } + } else { + md.push_str("Waiting for you to pick at sign-off:\n\n"); + for finding in &run.collected { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + } + } + + if let Some(signoff) = &run.signoff { + md.push_str("\n## Sign-off\n\n"); + let squash = match (&signoff.squash, signoff.squash_asked) { + (Squash::Done { commit, commits }, _) => format!( + "squashed {} into `{}`", + plural(*commits, "commit", "commits"), + short_id(commit) + ), + (Squash::Refused(why), _) => format!("not squashed: {}", one_line(why)), + (Squash::Off, _) => "not asked for".to_string(), + }; + md.push_str(&format!("- Squash of the round commits: {squash}\n")); + } + + if let Some(partial) = run.partial.as_ref().filter(|p| p.pending) { + md.push_str(&format!( + "\n## Partial changes\n\nStop now left {} changed (+{} -{}) that are not committed, waiting for Keep or Discard.\n", + plural(partial.files as usize, "file", "files"), + partial.added, + partial.removed + )); + } + md +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::tests::fake_agent_launch; + use crate::review_loop::{ReviewSetup, SignOff}; + use crate::round_boundary::Boundary; + use crate::round_logic::RoundTests; + use std::collections::BTreeMap; + use std::path::PathBuf; + + fn run_with(reason: Option) -> ReviewRun { + let mut run = ReviewRun::new( + PathBuf::from("."), + ReviewSetup::default(), + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit("0000000000000000000000000000000000000000".to_string()), + PathBuf::new(), + BTreeMap::new(), + ); + run.stop_reason = reason; + run.running = false; + run + } + + fn finding(title: &str, file: &str, line: Option) -> Finding { + Finding { + title: title.to_string(), + file: file.to_string(), + line, + } + } + + fn round(n: u32, critical: u32, warning: u32) -> RoundRecord { + RoundRecord { + n, + critical, + warning, + suggestion: 1, + verdict: Some(if critical + warning == 0 { + Verdict::Clean + } else { + Verdict::Findings { critical, warning } + }), + commit: Some("1234567890abcdef".to_string()), + started_at: "2026-11-28 10:00".to_string(), + ended_at: "2026-11-28 10:09".to_string(), + tests: Some(RoundTests { + ran: true, + passed: true, + summary: "14 pass".to_string(), + }), + ..RoundRecord::default() + } + } + + #[test] + fn every_stop_reason_leads_the_report_in_words() { + let cases = [ + (Some(StopReason::Clean), "# Review Loop: Clean"), + ( + Some(StopReason::Cap), + "# Review Loop: Stopped at the round cap", + ), + (Some(StopReason::Person), "# Review Loop: Stopped by you"), + ( + Some(StopReason::Failed("tests failed".to_string())), + "# Review Loop: Failed", + ), + ]; + for (reason, heading) in cases { + let md = review_report_markdown(&run_with(reason)); + assert!(md.starts_with(heading), "{md}"); + } + let failed = review_report_markdown(&run_with(Some(StopReason::Failed( + "tests failed".to_string(), + )))); + assert!(failed.contains("Why it failed: tests failed"), "{failed}"); + let clean = review_report_markdown(&run_with(Some(StopReason::Clean))); + assert!(clean.contains("Rounds run: 0 of at most 3"), "{clean}"); + } + + #[test] + fn a_round_says_its_findings_fixes_commit_tests_time_and_strength() { + let mut run = run_with(Some(StopReason::Cap)); + let mut first = round(1, 2, 1); + first.fixed = vec![finding("Close the handle", "src/a.rs", Some(12))]; + first.strength = Some("Balanced".to_string()); + first.model = Some("sonnet".to_string()); + first.effort = Some("low".to_string()); + run.rounds.push(first); + let md = review_report_markdown(&run); + assert!(md.contains("## Round 1"), "{md}"); + assert!( + md.contains("Found: 2 Critical, 1 Warning, 1 Suggestion"), + "{md}" + ); + assert!( + md.contains("Fixed: Close the handle (`src/a.rs:12`)"), + "{md}" + ); + assert!(md.contains("Commit: `1234567`"), "{md}"); + assert!(md.contains("Targeted tests: 14 pass (passed)"), "{md}"); + assert!( + md.contains("Time: 2026-11-28 10:00 to 2026-11-28 10:09"), + "{md}" + ); + assert!(md.contains("Strength: Balanced (sonnet, low)"), "{md}"); + } + + #[test] + fn an_agent_without_strengths_reads_as_launched_and_a_same_level_retry_says_so() { + let mut run = run_with(Some(StopReason::Cap)); + let mut r = round(1, 1, 0); + r.retried = true; + r.could_not_step_up = true; + run.rounds.push(r); + let md = review_report_markdown(&run); + assert!(md.contains("Strength: as launched"), "{md}"); + assert!( + md.contains("it could not step up, so it ran at the same level"), + "{md}" + ); + let mut stepped = run_with(Some(StopReason::Cap)); + let mut r = round(1, 1, 0); + r.retried = true; + r.strength = Some("Best".to_string()); + stepped.rounds.push(r); + let md = review_report_markdown(&stepped); + assert!(md.contains("one strength up"), "{md}"); + assert!(!md.contains("could not step up"), "{md}"); + } + + #[test] + fn open_findings_show_their_file_and_line_and_a_clean_run_has_none() { + let mut run = run_with(Some(StopReason::Cap)); + let mut last = round(2, 1, 1); + last.unfixed = vec![ + finding("Missing check", "src/b.rs", Some(40)), + finding("Wrong default", "src/c.rs", None), + ]; + run.rounds.push(last); + let md = review_report_markdown(&run); + assert!(md.contains("- Missing check (`src/b.rs:40`)"), "{md}"); + assert!(md.contains("- Wrong default (`src/c.rs`)"), "{md}"); + let mut clean = run_with(Some(StopReason::Clean)); + clean.rounds.push(round(1, 0, 0)); + let md = review_report_markdown(&clean); + assert!( + md.contains("No Critical or Warning findings are open."), + "{md}" + ); + } + + #[test] + fn suggestions_are_listed_to_pick_or_reported_as_applied_with_the_final_check() { + let mut waiting = run_with(Some(StopReason::Clean)); + waiting.collected = vec![finding("Name the timer", "src/d.rs", Some(3))]; + let md = review_report_markdown(&waiting); + assert!(md.contains("Waiting for you to pick at sign-off"), "{md}"); + assert!(md.contains("- Name the timer (`src/d.rs:3`)"), "{md}"); + + let mut applied = run_with(Some(StopReason::Clean)); + applied.suggestions_batch = Some(BatchRecord { + briefed: vec![finding("Name the timer", "src/d.rs", None)], + commit: Some("abcdef0123456789".to_string()), + final_check: Some(Verdict::Clean), + ..BatchRecord::default() + }); + let md = review_report_markdown(&applied); + assert!( + md.contains("1 Suggestion was fixed in the batch above"), + "{md}" + ); + assert!( + md.contains("Final check by a fresh reviewer: clean"), + "{md}" + ); + assert!(md.contains("Commit: `abcdef0`"), "{md}"); + } + + #[test] + fn the_sign_off_records_the_picks_and_whether_the_squash_ran_or_was_refused() { + let mut run = run_with(Some(StopReason::Cap)); + run.signoff = Some(SignOff { + picked: vec![finding("Name the timer", "src/d.rs", None)], + left: vec![finding("Tidy import", "src/e.rs", None)], + squash_asked: true, + squash: Squash::Done { + commit: "fedcba9876543210".to_string(), + commits: 3, + }, + problem: None, + }); + let md = review_report_markdown(&run); + assert!(md.contains("Picked at sign-off"), "{md}"); + assert!(md.contains("Left alone"), "{md}"); + assert!(md.contains("squashed 3 commits into `fedcba9`"), "{md}"); + run.signoff.as_mut().unwrap().squash = Squash::Refused( + "Something else was committed during the run, so the rounds were not squashed." + .to_string(), + ); + let md = review_report_markdown(&run); + assert!( + md.contains("not squashed: Something else was committed"), + "{md}" + ); + } +} diff --git a/plan2code-app/src-tauri/src/round_boundary.rs b/plan2code-app/src-tauri/src/round_boundary.rs new file mode 100644 index 0000000..14c24df --- /dev/null +++ b/plan2code-app/src-tauri/src/round_boundary.rs @@ -0,0 +1,400 @@ +//! Where a Review Loop round starts and ends: a full commit id (commit mode) or +//! a tree id from a snapshot of the working tree (snapshot mode), and the diff +//! between any two of them. A snapshot never touches the real index, `HEAD` or +//! the working tree: it adds everything to a copy of the index and writes a tree +//! from that copy, the same technique as `snapshotTree` in `changes.mjs`. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::loop_tools; + +/// A point in the project's history a round can be measured from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Boundary { + /// A full commit id. + Commit(String), + /// A tree id written from a snapshot of the working tree. + Tree(String), +} + +impl Boundary { + /// The object id, whichever kind it is. + pub fn id(&self) -> &str { + match self { + Boundary::Commit(id) | Boundary::Tree(id) => id, + } + } + + fn peel(&self) -> String { + match self { + Boundary::Commit(id) => format!("{id}^{{commit}}"), + Boundary::Tree(id) => format!("{id}^{{tree}}"), + } + } +} + +/// What a diff between two boundaries changed. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DiffStats { + pub files: u32, + pub added: u32, + pub removed: u32, +} + +fn git(project: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(project); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + cmd +} + +/// The first line git said on stderr, or `fallback`. +fn why(stderr: &[u8], fallback: &str) -> String { + String::from_utf8_lossy(stderr) + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| fallback.to_string()) +} + +/// A hex object id (git's full ids are 40 or 64 characters). +fn is_object_id(id: &str) -> bool { + matches!(id.len(), 40 | 64) && id.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// The boundary at `HEAD`, as a full commit id. +pub fn head(project: &Path) -> Result { + loop_tools::git_head_full(project).map(Boundary::Commit) +} + +/// Deletes the copied index on every path out of `snapshot`. +struct TempIndex(PathBuf); + +impl Drop for TempIndex { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +static SNAPSHOTS: AtomicU64 = AtomicU64::new(0); + +/// Snapshot the working tree (tracked, changed and untracked, ignored files +/// left out) as a tree id, without touching the real index, `HEAD` or any file. +pub fn snapshot(project: &Path) -> Result { + let located = git(project, &["rev-parse", "--git-path", "index"]) + .output() + .map_err(|err| format!("git could not run: {err}"))?; + if !located.status.success() { + return Err(format!( + "git could not find the index: {}", + why(&located.stderr, "not a git repository") + )); + } + let real = String::from_utf8_lossy(&located.stdout).trim().to_string(); + let temp = TempIndex(std::env::temp_dir().join(format!( + "plan2code-round-index-{}-{}", + std::process::id(), + SNAPSHOTS.fetch_add(1, Ordering::Relaxed) + ))); + if !real.is_empty() { + let source = project.join(&real); + if source.is_file() { + std::fs::copy(&source, &temp.0) + .map_err(|err| format!("could not copy the index: {err}"))?; + } + } + let run = |args: &[&str]| { + git(project, args) + .env("GIT_INDEX_FILE", &temp.0) + .output() + .map_err(|err| format!("git could not run: {err}")) + }; + let added = run(&["add", "-A"])?; + if !added.status.success() { + return Err(format!( + "git could not snapshot the working tree: {}", + why(&added.stderr, "git add failed") + )); + } + let written = run(&["write-tree"])?; + let tree = String::from_utf8_lossy(&written.stdout).trim().to_string(); + if !written.status.success() || !is_object_id(&tree) { + return Err(format!( + "git could not write the snapshot: {}", + why(&written.stderr, "git write-tree failed") + )); + } + Ok(Boundary::Tree(tree)) +} + +/// Whether the boundary's object is still in the repository (git may collect +/// an unreferenced snapshot tree). +pub fn exists(project: &Path, b: &Boundary) -> bool { + if !is_object_id(b.id()) { + return false; + } + git(project, &["cat-file", "-e", &b.peel()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|status| status.success()) + .unwrap_or(false) +} + +/// Write the plain unified diff from `from` to `to` into `out`, and say how big +/// it is. A boundary gone from the repository is refused by name. +pub fn diff( + project: &Path, + from: &Boundary, + to: &Boundary, + out: &Path, +) -> Result { + for side in [from, to] { + if !exists(project, side) { + return Err(format!("round boundary missing: {}", side.id())); + } + } + // Fixed prefixes and no external driver: a user's diff settings must not + // change what the round agent reads. + let base = [ + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + ]; + let file = std::fs::File::create(out) + .map_err(|err| format!("could not write {}: {err}", out.display()))?; + let patch = git(project, &["diff"]) + .args(base) + .arg(from.id()) + .arg(to.id()) + .stdout(Stdio::from(file)) + .stderr(Stdio::piped()) + .output() + .map_err(|err| { + let _ = std::fs::remove_file(out); + format!("git could not run: {err}") + })?; + if !patch.status.success() { + let _ = std::fs::remove_file(out); + return Err(format!( + "git diff failed: {}", + why(&patch.stderr, "no reason given") + )); + } + let numstat = git(project, &["diff", "--numstat", "--no-ext-diff"]) + .arg(from.id()) + .arg(to.id()) + .output() + .map_err(|err| { + let _ = std::fs::remove_file(out); + format!("git could not run: {err}") + })?; + if !numstat.status.success() { + let _ = std::fs::remove_file(out); + return Err(format!( + "git diff failed: {}", + why(&numstat.stderr, "no reason given") + )); + } + let mut stats = DiffStats::default(); + for line in String::from_utf8_lossy(&numstat.stdout).lines() { + let mut parts = line.split('\t'); + let (Some(added), Some(removed)) = (parts.next(), parts.next()) else { + continue; + }; + stats.files += 1; + // A binary file shows `-` for both. + stats.added += added.parse::().unwrap_or(0); + stats.removed += removed.parse::().unwrap_or(0); + } + Ok(stats) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn git_in(repo: &Path, args: &[&str]) -> String { + let out = git(repo, args).output().expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).to_string() + } + + /// A new repository in a unique temp folder with one commit, its config + /// scrubbed of anything global (no autocrlf, no hooks, no signing). + fn scratch(name: &str) -> PathBuf { + let repo = std::env::temp_dir() + .join(format!("plan2code-round-{name}-{}", std::process::id())) + .join("repo"); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + std::fs::create_dir_all(&repo).unwrap(); + git_in(&repo, &["init", "-q"]); + for (key, value) in [ + ("user.name", "Round Test"), + ("user.email", "round@example.com"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git_in(&repo, &["config", key, value]); + } + std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "first"]); + repo + } + + fn cleanup(repo: &Path) { + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn head_is_a_full_commit_id() { + let repo = scratch("head"); + let boundary = head(&repo).unwrap(); + assert!(matches!(&boundary, Boundary::Commit(id) if is_object_id(id))); + assert!(exists(&repo, &boundary)); + cleanup(&repo); + } + + #[test] + fn a_snapshot_leaves_status_and_the_index_unchanged() { + let repo = scratch("untouched"); + std::fs::write(repo.join("a.txt"), "one\ntwo\nthree\n").unwrap(); + std::fs::write(repo.join("new.txt"), "new\n").unwrap(); + // Settle git's own stat refresh before measuring. + git_in(&repo, &["status", "--porcelain"]); + let index = repo.join(".git/index"); + let before = std::fs::read(&index).unwrap(); + let head_before = git_in(&repo, &["rev-parse", "HEAD"]); + let first = snapshot(&repo).unwrap(); + let second = snapshot(&repo).unwrap(); + assert_eq!(first, second, "the same tree twice"); + assert_eq!(std::fs::read(&index).unwrap(), before, "index bytes"); + assert_eq!(git_in(&repo, &["rev-parse", "HEAD"]), head_before); + let status = git_in(&repo, &["status", "--porcelain"]); + assert!(status.contains(" M a.txt"), "{status}"); + assert!(status.contains("?? new.txt"), "still untracked: {status}"); + assert_eq!( + std::fs::read_to_string(repo.join("new.txt")).unwrap(), + "new\n" + ); + cleanup(&repo); + } + + #[test] + fn an_untracked_file_shows_in_the_next_snapshots_diff() { + let repo = scratch("untracked"); + let one = snapshot(&repo).unwrap(); + std::fs::write(repo.join("fresh.txt"), "a\nb\nc\n").unwrap(); + let two = snapshot(&repo).unwrap(); + assert_ne!(one, two); + let out = repo.parent().unwrap().join("round-1.diff"); + let stats = diff(&repo, &one, &two, &out).unwrap(); + let text = std::fs::read_to_string(&out).unwrap(); + assert!(text.contains("+++ b/fresh.txt"), "{text}"); + assert_eq!( + stats, + DiffStats { + files: 1, + added: 3, + removed: 0 + } + ); + cleanup(&repo); + } + + #[test] + fn a_diff_between_two_commits_equals_git_diff() { + let repo = scratch("commits"); + let a = head(&repo).unwrap(); + std::fs::write(repo.join("a.txt"), "one\nTWO\nthree\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "second"]); + let b = head(&repo).unwrap(); + let out = repo.parent().unwrap().join("between.diff"); + let stats = diff(&repo, &a, &b, &out).unwrap(); + let expected = git_in( + &repo, + &[ + "diff", + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + a.id(), + b.id(), + ], + ); + assert_eq!(std::fs::read_to_string(&out).unwrap(), expected); + assert_eq!( + stats, + DiffStats { + files: 1, + added: 2, + removed: 1 + } + ); + cleanup(&repo); + } + + #[test] + fn a_commit_and_a_snapshot_can_be_diffed() { + let repo = scratch("mixed"); + let start = head(&repo).unwrap(); + std::fs::write(repo.join("a.txt"), "one\n").unwrap(); + let now = snapshot(&repo).unwrap(); + let out = repo.parent().unwrap().join("mixed.diff"); + let stats = diff(&repo, &start, &now, &out).unwrap(); + assert_eq!(stats.removed, 1); + cleanup(&repo); + } + + #[test] + fn a_made_up_id_does_not_exist_and_the_diff_refuses_it() { + let repo = scratch("missing"); + let real = head(&repo).unwrap(); + let ghost = Boundary::Tree("0123456789abcdef0123456789abcdef01234567".to_string()); + assert!(!exists(&repo, &ghost)); + assert!(!exists(&repo, &Boundary::Commit("--output=x".to_string()))); + let out = repo.parent().unwrap().join("ghost.diff"); + let err = diff(&repo, &real, &ghost, &out).unwrap_err(); + assert_eq!( + err, + "round boundary missing: 0123456789abcdef0123456789abcdef01234567" + ); + // Either side is checked. + assert!(diff(&repo, &ghost, &real, &out).is_err()); + assert!(!out.exists(), "nothing written for a refused diff"); + cleanup(&repo); + } + + #[test] + fn a_snapshot_outside_a_repository_fails_with_a_reason() { + let dir = std::env::temp_dir().join(format!("plan2code-round-none-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // A `.git` file naming a gitdir that is not there: git stops here + // whatever repository sits above the temp folder. + std::fs::write( + dir.join(".git"), + "gitdir: /plan2code-no-such-gitdir +", + ) + .unwrap(); + let err = snapshot(&dir).unwrap_err(); + assert!(err.starts_with("git could not"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/plan2code-app/src-tauri/src/round_logic.rs b/plan2code-app/src-tauri/src/round_logic.rs new file mode 100644 index 0000000..8b75bba --- /dev/null +++ b/plan2code-app/src-tauri/src/round_logic.rs @@ -0,0 +1,675 @@ +//! The Review Loop's round rules, with no agent, git, file or clock in them: +//! judging a round, picking the next step, and the wording of a round's commit +//! subject and banner detail. The driver passes everything in. + +use serde::Deserialize; + +/// The most rounds a run may ever reach, Continue included. +pub const MAX_ROUNDS: u32 = 6; + +/// The longest commit subject a round writes, in characters. +const SUBJECT_LIMIT: usize = 72; + +/// Which part of a round a session plays. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + Both, + Reviewer, + Fixer, +} + +/// One finding in a round's report. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct Finding { + #[serde(default)] + pub title: String, + #[serde(default)] + pub file: String, + #[serde(default)] + pub line: Option, +} + +/// The counts and lists a round reports. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct RoundReview { + #[serde(default)] + pub critical: u32, + #[serde(default)] + pub warning: u32, + #[serde(default)] + pub suggestion: u32, + #[serde(default)] + pub fixed: Vec, + #[serde(default)] + pub unfixed: Vec, + #[serde(default)] + pub suggestions: Vec, +} + +/// The tests a round ran. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct RoundTests { + #[serde(default)] + pub ran: bool, + #[serde(default)] + pub passed: bool, + #[serde(default)] + pub summary: String, +} + +/// A round session's `roundOutcome`, as the console validated it. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct RoundOutcome { + pub round: u32, + pub role: Role, + /// `passed` or `failed`. + pub result: String, + #[serde(default)] + pub reason: Option, + #[serde(default)] + pub summary: String, + /// Id of the report doc in the session. + #[serde(default)] + pub report: Option, + #[serde(default)] + pub review: RoundReview, + #[serde(default)] + pub tests: Option, + #[serde(default)] + pub subject: Option, +} + +/// What the app checked for itself, so a report cannot vouch for its own work. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RoundProofs { + pub report_doc_present: bool, + pub tests_ran: bool, + pub tests_passed: bool, +} + +/// How a round came out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + Clean, + Findings { critical: u32, warning: u32 }, + Failed(String), +} + +/// Judge a round from its report and the app's own proofs. Suggestions never +/// change the verdict. +pub fn judge_round(outcome: &RoundOutcome, proofs: &RoundProofs) -> Verdict { + if outcome.result == "failed" { + let reason = outcome + .reason + .as_deref() + .filter(|reason| !reason.is_empty()) + .unwrap_or("other"); + return Verdict::Failed(reason.to_string()); + } + if !proofs.report_doc_present { + return Verdict::Failed("no reviewer report in the session".to_string()); + } + if !proofs.tests_ran { + return Verdict::Failed("targeted tests did not run".to_string()); + } + if !proofs.tests_passed { + return Verdict::Failed("targeted tests failed".to_string()); + } + let (critical, warning) = (outcome.review.critical, outcome.review.warning); + if critical == 0 && warning == 0 { + Verdict::Clean + } else { + Verdict::Findings { critical, warning } + } +} + +/// A fixer's counts never vouch for its own fix: in the two-session shape the +/// round is judged on what the separate reviewer found, so a fixer that sends +/// lower counts than its reviewer cannot end the run as clean. +pub fn hold_reviewer_counts(review: &mut RoundReview, critical: u32, warning: u32) { + review.critical = review.critical.max(critical); + review.warning = review.warning.max(warning); +} + +/// Why a run stopped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StopReason { + Clean, + Cap, + Person, + Failed(String), +} + +/// What the run looks like when a round has just been judged. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RunView { + /// The round just judged. + pub round: u32, + pub cap: u32, + pub rounds_run: u32, + pub suggestions_on: bool, + pub suggestions_pending: bool, + /// The Suggestions batch round has run. + pub batch_done: bool, + pub retried_this_round: bool, + pub stop_after_round: bool, + pub stop_now: bool, +} + +/// What the driver does next. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Next { + StartRound(u32), + Retry, + SuggestionsBatch, + FinalCheck, + Stop(StopReason), +} + +/// Pick the next step after a round with `verdict`. +/// +/// Once the batch has run, its verdict leads to one `FinalCheck` (outside the +/// cap); the driver then ends the run with `after_final_check`, carrying the +/// reason the run was going to stop for. +pub fn next_step(run: &RunView, verdict: &Verdict) -> Next { + if run.stop_now { + return Next::Stop(StopReason::Person); + } + let batch_due = run.suggestions_on && run.suggestions_pending && !run.batch_done; + match verdict { + Verdict::Failed(reason) => { + if run.retried_this_round { + Next::Stop(StopReason::Failed(reason.clone())) + } else { + Next::Retry + } + } + _ if run.batch_done => Next::FinalCheck, + Verdict::Clean => { + // A stop after this round means no more work, the batch included. + if batch_due && !run.stop_after_round { + Next::SuggestionsBatch + } else { + Next::Stop(StopReason::Clean) + } + } + Verdict::Findings { .. } => { + if run.stop_after_round { + Next::Stop(StopReason::Person) + } else if run.round >= run.cap.min(MAX_ROUNDS) { + if batch_due { + Next::SuggestionsBatch + } else { + Next::Stop(StopReason::Cap) + } + } else { + Next::StartRound(run.round + 1) + } + } + } +} + +/// The step after the final check, whatever its verdict: the run ends for the +/// reason it was already ending for (FR-19). +pub fn after_final_check(original: StopReason) -> Next { + Next::Stop(original) +} + +/// The cap Continue may use after a run stopped at its cap: one more round, +/// and never above `MAX_ROUNDS`. +pub fn continue_cap(cap: u32, rounds_run: u32) -> Option { + if rounds_run < cap { + return None; + } + let next = rounds_run + 1; + (next <= MAX_ROUNDS).then_some(next) +} + +/// The subject of a round's commit: the fix titles after the round number, +/// trailing titles dropped for "and N more" to stay within 72 characters. +pub fn round_commit_message(round: u32, titles: &[String]) -> String { + let prefix = format!("Review Loop round {round}"); + let titles: Vec<&str> = titles + .iter() + .map(|title| title.trim()) + .filter(|title| !title.is_empty()) + .collect(); + if titles.is_empty() { + return prefix; + } + let total = titles.len(); + for kept in (1..=total).rev() { + let mut body = titles[..kept].join(", "); + if kept < total { + body.push_str(&format!(" and {} more", total - kept)); + } + let subject = format!("{prefix}: {body}"); + if subject.chars().count() <= SUBJECT_LIMIT { + return subject; + } + } + // Even one title is too long: cut it. + let subject = format!("{prefix}: {}", titles[0]); + let mut cut: String = subject.chars().take(SUBJECT_LIMIT - 3).collect(); + cut = cut.trim_end().to_string(); + cut.push_str("..."); + cut +} + +/// The banner's detail line for a round, such as +/// "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)". +pub fn round_detail(round: u32, cap: u32, step: &str, critical: u32, warning: u32) -> String { + let head = format!("Round {round} of {cap}: {step}"); + let total = critical + warning; + if total == 0 { + return head; + } + let mut parts = Vec::new(); + if critical > 0 { + parts.push(format!("{critical} Critical")); + } + if warning > 0 { + parts.push(format!("{warning} Warning")); + } + let noun = if total == 1 { "finding" } else { "findings" }; + format!("{head} {total} {noun} ({})", parts.join(", ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fixer_reporting_zero_is_judged_on_its_reviewers_counts() { + let mut fixer = outcome(0, 0, 0); + fixer.role = Role::Fixer; + hold_reviewer_counts(&mut fixer.review, 1, 2); + let proofs = RoundProofs { + report_doc_present: true, + tests_ran: true, + tests_passed: true, + }; + assert_eq!( + judge_round(&fixer, &proofs), + Verdict::Findings { + critical: 1, + warning: 2 + } + ); + let mut honest = outcome(0, 3, 0); + hold_reviewer_counts(&mut honest.review, 0, 1); + assert_eq!(honest.review.warning, 3, "a higher own count stands"); + } + + fn outcome(critical: u32, warning: u32, suggestion: u32) -> RoundOutcome { + RoundOutcome { + round: 1, + role: Role::Both, + result: "passed".into(), + reason: None, + summary: "done".into(), + report: Some("report".into()), + review: RoundReview { + critical, + warning, + suggestion, + ..RoundReview::default() + }, + tests: Some(RoundTests { + ran: true, + passed: true, + summary: "ok".into(), + }), + subject: None, + } + } + + const ALL: RoundProofs = RoundProofs { + report_doc_present: true, + tests_ran: true, + tests_passed: true, + }; + + #[test] + fn a_round_with_every_proof_and_no_findings_is_clean() { + assert_eq!(judge_round(&outcome(0, 0, 0), &ALL), Verdict::Clean); + } + + #[test] + fn each_missing_proof_fails_with_its_own_message_even_at_zero_counts() { + let no_doc = RoundProofs { + report_doc_present: false, + ..ALL + }; + let no_run = RoundProofs { + tests_ran: false, + tests_passed: false, + ..ALL + }; + let failed = RoundProofs { + tests_passed: false, + ..ALL + }; + let round = outcome(0, 0, 0); + assert_eq!( + judge_round(&round, &no_doc), + Verdict::Failed("no reviewer report in the session".into()) + ); + assert_eq!( + judge_round(&round, &no_run), + Verdict::Failed("targeted tests did not run".into()) + ); + assert_eq!( + judge_round(&round, &failed), + Verdict::Failed("targeted tests failed".into()) + ); + } + + #[test] + fn critical_or_warning_left_is_findings() { + assert_eq!( + judge_round(&outcome(1, 0, 0), &ALL), + Verdict::Findings { + critical: 1, + warning: 0 + } + ); + assert_eq!( + judge_round(&outcome(0, 2, 0), &ALL), + Verdict::Findings { + critical: 0, + warning: 2 + } + ); + } + + #[test] + fn suggestions_alone_are_still_clean() { + assert_eq!(judge_round(&outcome(0, 0, 9), &ALL), Verdict::Clean); + } + + #[test] + fn a_failed_result_passes_its_reason_through() { + let mut round = outcome(0, 0, 0); + round.result = "failed".into(); + round.reason = Some("blocked".into()); + assert_eq!(judge_round(&round, &ALL), Verdict::Failed("blocked".into())); + } + + #[test] + fn an_outcome_reads_from_the_console_json() { + let json = r#"{"round":2,"role":"fixer","result":"passed","reason":null, + "summary":"s","tests":{"ran":true,"passed":true,"summary":"3 pass"}, + "review":{"critical":0,"warning":1,"suggestion":0, + "fixed":[{"title":"t","file":"a.rs","line":4}]}}"#; + let parsed: RoundOutcome = serde_json::from_str(json).unwrap(); + assert_eq!(parsed.role, Role::Fixer); + assert_eq!(parsed.review.fixed[0].line, Some(4)); + assert_eq!(parsed.report, None); + let reviewer: RoundOutcome = + serde_json::from_str(r#"{"round":1,"role":"reviewer","result":"passed"}"#).unwrap(); + assert_eq!(reviewer.role, Role::Reviewer); + } + + fn view() -> RunView { + RunView { + round: 1, + cap: 3, + rounds_run: 1, + suggestions_on: false, + suggestions_pending: false, + batch_done: false, + retried_this_round: false, + stop_after_round: false, + stop_now: false, + } + } + + const FINDINGS: Verdict = Verdict::Findings { + critical: 1, + warning: 0, + }; + + #[test] + fn stop_now_always_stops_for_the_person() { + let run = RunView { + stop_now: true, + suggestions_on: true, + suggestions_pending: true, + ..view() + }; + let done = RunView { + batch_done: true, + ..run + }; + assert_eq!( + next_step(&done, &Verdict::Clean), + Next::Stop(StopReason::Person) + ); + for verdict in [Verdict::Clean, FINDINGS, Verdict::Failed("tests".into())] { + assert_eq!(next_step(&run, &verdict), Next::Stop(StopReason::Person)); + } + } + + #[test] + fn a_failure_retries_once_then_stops_failed() { + let failed = Verdict::Failed("tests".into()); + assert_eq!(next_step(&view(), &failed), Next::Retry); + let retried = RunView { + retried_this_round: true, + ..view() + }; + assert_eq!( + next_step(&retried, &failed), + Next::Stop(StopReason::Failed("tests".into())) + ); + } + + #[test] + fn clean_stops_unless_a_suggestions_batch_is_due() { + assert_eq!( + next_step(&view(), &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + let on_none_pending = RunView { + suggestions_on: true, + ..view() + }; + assert_eq!( + next_step(&on_none_pending, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + let due = RunView { + suggestions_on: true, + suggestions_pending: true, + ..view() + }; + assert_eq!(next_step(&due, &Verdict::Clean), Next::SuggestionsBatch); + let off = RunView { + suggestions_pending: true, + ..view() + }; + assert_eq!( + next_step(&off, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn findings_start_the_next_round_below_the_cap() { + assert_eq!(next_step(&view(), &FINDINGS), Next::StartRound(2)); + let second = RunView { + round: 2, + rounds_run: 2, + ..view() + }; + assert_eq!(next_step(&second, &FINDINGS), Next::StartRound(3)); + } + + #[test] + fn findings_at_the_cap_stop_or_run_the_batch() { + let at_cap = RunView { + round: 3, + rounds_run: 3, + ..view() + }; + assert_eq!(next_step(&at_cap, &FINDINGS), Next::Stop(StopReason::Cap)); + let due = RunView { + suggestions_on: true, + suggestions_pending: true, + ..at_cap + }; + assert_eq!(next_step(&due, &FINDINGS), Next::SuggestionsBatch); + } + + #[test] + fn a_cap_above_the_most_rounds_is_held_to_the_most() { + let run = RunView { + round: MAX_ROUNDS, + rounds_run: MAX_ROUNDS, + cap: 9, + ..view() + }; + assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Cap)); + } + + #[test] + fn a_run_with_cap_one_stops_after_round_one() { + let run = RunView { cap: 1, ..view() }; + assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Cap)); + assert_eq!( + next_step(&run, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn stop_after_this_round_stops_for_the_person_and_skips_the_batch() { + let run = RunView { + stop_after_round: true, + suggestions_on: true, + suggestions_pending: true, + ..view() + }; + assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Person)); + // Clean is clean, but nothing more is started, the batch included. + assert_eq!( + next_step(&run, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn the_batch_never_runs_after_a_failure() { + let run = RunView { + suggestions_on: true, + suggestions_pending: true, + round: 3, + rounds_run: 3, + retried_this_round: true, + ..view() + }; + assert_eq!( + next_step(&run, &Verdict::Failed("tests".into())), + Next::Stop(StopReason::Failed("tests".into())) + ); + } + + #[test] + fn after_the_batch_one_final_check_runs_and_the_original_reason_stands() { + let run = RunView { + suggestions_on: true, + suggestions_pending: true, + batch_done: true, + round: 3, + rounds_run: 4, + ..view() + }; + assert_eq!(next_step(&run, &Verdict::Clean), Next::FinalCheck); + assert_eq!(next_step(&run, &FINDINGS), Next::FinalCheck); + // A batch that fails is retried or stops failed like any round. + assert_eq!( + next_step(&run, &Verdict::Failed("tests".into())), + Next::Retry + ); + // Whatever the final check finds, the run ends as it was ending. + assert_eq!( + after_final_check(StopReason::Cap), + Next::Stop(StopReason::Cap) + ); + assert_eq!( + after_final_check(StopReason::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn continue_adds_one_round_and_never_a_seventh() { + assert_eq!(continue_cap(3, 3), Some(4)); + assert_eq!(continue_cap(1, 1), Some(2)); + assert_eq!(continue_cap(5, 5), Some(6)); + assert_eq!(continue_cap(6, 6), None); + assert_eq!(continue_cap(3, 2), None, "did not stop at the cap"); + } + + fn titles(list: &[&str]) -> Vec { + list.iter().map(|title| title.to_string()).collect() + } + + #[test] + fn the_commit_subject_joins_the_titles() { + assert_eq!( + round_commit_message( + 2, + &titles(&["fix null check in loop_tools", "restore test map row"]) + ), + "Review Loop round 2: fix null check in loop_tools, restore test map row" + ); + assert_eq!( + round_commit_message(1, &titles(&["one fix"])), + "Review Loop round 1: one fix" + ); + assert_eq!(round_commit_message(3, &[]), "Review Loop round 3"); + } + + #[test] + fn a_long_commit_subject_drops_trailing_titles() { + let subject = round_commit_message( + 2, + &titles(&[ + "close the file handle before renaming", + "name the timer", + "restore the test map row", + "tidy the report", + ]), + ); + assert!(subject.chars().count() <= 72, "{subject}"); + assert!(subject.starts_with("Review Loop round 2: close the file handle")); + assert!(subject.contains(" more"), "{subject}"); + // One title that is too long on its own is cut. + let one = round_commit_message(1, &titles(&[&"x".repeat(200)])); + assert_eq!(one.chars().count(), 72); + assert!(one.ends_with("...")); + } + + #[test] + fn the_detail_line_counts_findings() { + assert_eq!( + round_detail(2, 3, "Fixing", 1, 2), + "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)" + ); + assert_eq!( + round_detail(1, 3, "Fixing", 0, 1), + "Round 1 of 3: Fixing 1 finding (1 Warning)" + ); + assert_eq!( + round_detail(1, 3, "Fixing", 1, 0), + "Round 1 of 3: Fixing 1 finding (1 Critical)" + ); + assert_eq!( + round_detail(1, 3, "Reviewing", 0, 0), + "Round 1 of 3: Reviewing" + ); + } +} diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js index 87f3184..bcb3dcd 100644 --- a/plan2code-app/ui/app.js +++ b/plan2code-app/ui/app.js @@ -1038,6 +1038,85 @@ window.addEventListener('message', (event) => { invoke('loop_facts') .then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*')) .catch(() => {}); + } else if (kind === 'review-loop-facts') { + // The Review Loop's setup screen asks what agent a run would use and + // whether it has helpers. Facts only; the page sends no setup value. + const source = event.source; + invoke('review_loop_facts') + .then((facts) => source.postMessage({ plan2code: 'review-loop-facts', facts }, '*')) + .catch(() => {}); + } else if (kind === 'review-loop-start') { + // Start: the setup screen's picks, only the known fields and kinds. The + // notification address is never taken from the page; the app reads it. + const source = event.source; + const picked = event.data.setup && typeof event.data.setup === 'object' ? event.data.setup : {}; + const text = (value) => (typeof value === 'string' ? value : ''); + const flag = (value) => value === true; + const setup = { + scope: text(picked.scope), + spec: text(picked.spec), + cap: Number.isInteger(picked.cap) ? picked.cap : 3, + commit: picked.commit !== false, + preRunCommitAgreed: flag(picked.preRunCommitAgreed), + suggestions: flag(picked.suggestions), + strength: text(picked.strength), + silenceMinutes: Number.isInteger(picked.silenceMinutes) ? picked.silenceMinutes : 20, + notifyRounds: flag(picked.notifyRounds), + }; + invoke('review_loop_start', { setup }) + .then((started) => source.postMessage({ plan2code: 'review-loop-start-result', ok: true, started, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-start-result', ok: false, started: false, error: String(error) }, '*') + ); + } else if (kind === 'review-loop-continue') { + const source = event.source; + invoke('review_loop_continue') + .then(() => source.postMessage({ plan2code: 'review-loop-continue-result', ok: true, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-continue-result', ok: false, error: String(error) }, '*') + ); + } else if (kind === 'review-loop-partial') { + // Keep or Discard what Stop now left: one boolean, nothing else. + const source = event.source; + if (typeof event.data.keep !== 'boolean') { + // Discard cannot be undone: only an explicit true or false is a choice. + source.postMessage({ plan2code: 'review-loop-partial-result', ok: false, error: 'keep must be true or false' }, '*'); + return; + } + invoke('review_loop_partial', { keep: event.data.keep }) + .then(() => source.postMessage({ plan2code: 'review-loop-partial-result', ok: true, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-partial-result', ok: false, error: String(error) }, '*') + ); + } else if (kind === 'review-loop-sign-off') { + // Sign off: the ticked Suggestions by id and the squash switch, nothing else. + const source = event.source; + const { picks, squash } = event.data; + const refuse = (error) => source.postMessage({ plan2code: 'review-loop-sign-off-result', ok: false, error }, '*'); + if (!Array.isArray(picks) || picks.length > 50 || !picks.every((id) => typeof id === 'string' && /^s[0-9]{1,3}$/.test(id))) { + refuse('picks must be a list of up to 50 suggestion ids'); + return; + } + if (typeof squash !== 'boolean') { + refuse('squash must be true or false'); + return; + } + invoke('review_loop_sign_off', { picks, squash }) + .then(() => source.postMessage({ plan2code: 'review-loop-sign-off-result', ok: true, error: null }, '*')) + .catch((error) => refuse(String(error))); + } else if (kind === 'review-loop-next') { + // The finished screen's launch: one of two words, the app builds the brief. + const source = event.source; + const next = event.data.next; + if (next !== 'pr-prep' && next !== 'quick-task') { + source.postMessage({ plan2code: 'review-loop-next-result', ok: false, error: 'next must be pr-prep or quick-task' }, '*'); + return; + } + invoke('review_loop_next', { next }) + .then(() => source.postMessage({ plan2code: 'review-loop-next-result', ok: true, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-next-result', ok: false, error: String(error) }, '*') + ); } else if (kind === 'loop-resume' || kind === 'loop-ask' || kind === 'loop-fix' || kind === 'loop-finalize') { // Fixed requests, no free text: the page answers with ok or the error. const source = event.source; @@ -1628,6 +1707,19 @@ async function syncLoopState() { } } +// Which loop the strip is showing, so the stop buttons press the right commands. +let loopKind = 'phases'; + +// A pip's hover text: "Phase 2", or for a Review Loop round the counts it found +// ("Round 1: 2 Critical, 1 Warning"), "Round 3" for one not finished yet. +function roundPipTitle(state, i) { + if (state.kind !== 'rounds') return `Phase ${i + 1}`; + const counts = Array.isArray(state.roundCounts) ? state.roundCounts[i] : null; + if (!counts) return `Round ${i + 1}`; + const found = [counts.critical > 0 ? `${counts.critical} Critical` : '', counts.warning > 0 ? `${counts.warning} Warning` : ''].filter(Boolean); + return `Round ${i + 1}: ${found.length ? found.join(', ') : 'nothing found'}`; +} + function applyLoopState(state) { if (!state || !state.running) { const wasRunning = loopRunning; @@ -1664,13 +1756,14 @@ function applyLoopState(state) { ...banner.pips.map((kind, i) => { const pip = document.createElement('span'); pip.className = `loop-pip ${kind}`; - pip.title = `Phase ${i + 1}`; + pip.title = roundPipTitle(state, i); return pip; }) ); setLoopTitle(loopWindowTitle(projectPathEl.textContent, state)); const stopLabels = loopStopLabels(state); - loopStopAfterOn = !!state.stopAfterPhase; + loopStopAfterOn = !!(state.kind === 'rounds' ? state.stopAfterRound : state.stopAfterPhase); + loopKind = state.kind === 'rounds' ? 'rounds' : 'phases'; loopStopAfterBtn.disabled = stopLabels.afterDisabled; loopStopAfterBtn.textContent = stopLabels.afterText; loopStopNowBtn.disabled = stopLabels.nowDisabled; @@ -1730,15 +1823,16 @@ function pressLoop(command, args) { loopRetryBtn.onclick = () => { if (loopRetryAction) loopRetryAction(); }; -loopStopAfterBtn.onclick = () => pressLoop('loop_stop_after_phase', { on: !loopStopAfterOn }); +loopStopAfterBtn.onclick = () => pressLoop(loopKind === 'rounds' ? 'review_loop_stop_after' : 'loop_stop_after_phase', { on: !loopStopAfterOn }); loopStopNowBtn.onclick = async () => { + const rounds = loopKind === 'rounds'; const yes = await confirmModal({ title: 'End the agent now?', - lines: [{ kind: 'text', text: "This phase's changes stay uncommitted." }], + lines: [{ kind: 'text', text: rounds ? "This round's changes stay uncommitted until you choose to keep or discard them." : "This phase's changes stay uncommitted." }], primary: 'Stop now', danger: true, }); - if (yes) pressLoop('loop_stop_now'); + if (yes) pressLoop(rounds ? 'review_loop_stop_now' : 'loop_stop_now'); }; // The right end of the bar: whether the console stopped answering and where diff --git a/plan2code-app/ui/meter.js b/plan2code-app/ui/meter.js index 5564f9c..a287d97 100644 --- a/plan2code-app/ui/meter.js +++ b/plan2code-app/ui/meter.js @@ -210,6 +210,11 @@ export function windowTitleFor(dir) { */ export function loopWindowTitle(dir, state) { const name = lastSegment(dir); + if (state.kind === "rounds") { + const where = state.afterRounds || `Round ${state.round}`; + const round = state.step === "Waiting on you" ? `Review Loop needs you: ${where}` : state.afterRounds ? `Review Loop: ${state.afterRounds}` : `Review Loop: Round ${state.round} of ${state.rounds}`; + return name ? `${round} - ${name}` : round; + } 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; } @@ -221,6 +226,7 @@ export function loopWindowTitle(dir, state) { * of the spec up to the last this run builds. */ export function loopBanner(state) { + if (state.kind === "rounds") return roundsBanner(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")); @@ -247,6 +253,40 @@ export function loopBanner(state) { return { ...base, title: "Implementation loop running", detail: ran ? `${where} \u00b7 ${ran}` : where }; } +/** + * The Review Loop's banner (`kind: "rounds"`): the same words as the phase banner + * with "round" for "phase", one pip per round up to the cap, and the detail line + * the app builds from the round, step and counts ("Round 2 of 3: Fixing 3 findings + * (1 Critical, 2 Warning)", carried in `phaseName`). After the rounds, + * `afterRounds` names the Suggestions batch or the final check, and every pip + * shows done. + */ +function roundsBanner(state) { + const { round, rounds, step } = state; + const after = state.afterRounds || ""; + const named = after || `Round ${round} of ${rounds}`; + const detailLine = state.phaseName || (step ? `${named}: ${step}` : named); + const pips = Array.from({ length: Math.max(rounds, 0) }, (_, i) => (after || i + 1 < round ? "done" : i + 1 === round ? "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. You will be asked what to do with the round's changes.", hint: "The stop screen follows in a moment." }; + } + if (step === "Waiting on you") { + return { ...base, tone: "waiting", title: "The Review Loop needs your answer", detail: `${named} is waiting on the question below.`, hint: "Nothing is lost while it waits." }; + } + if (state.stopAfterRound) { + return { ...base, title: "Stopping after this round", detail: `${named} finishes, is judged and committed, then the Review Loop stops.`, hint: "Stop now ends the agent at once." }; + } + if (step === "Starting") { + if (state.phaseRetried) return { ...base, title: after ? `Retrying the ${after.toLowerCase()}` : `Retrying round ${round}`, detail: `The agent crashed or went quiet, so a fresh one is picking up ${after ? `the ${after.toLowerCase()}` : named}.` }; + if (after) return { ...base, title: "Rounds done", detail: `Opening a fresh agent for the ${after.toLowerCase()}.` }; + if (round > 1) return { ...base, title: `Round ${round - 1} done`, detail: `Opening a fresh agent for ${named}.` }; + return { ...base, title: "Starting the Review Loop", detail: `Opening a fresh agent for ${named}.` }; + } + const ran = loopRunText(state); + return { ...base, title: "Review Loop running", detail: ran ? `${detailLine} · ${ran}` : detailLine }; +} + /** * What the running phase runs on, from the app's `loop-state`: "Thrifty (sonnet, * low)" for a phase on a strength, "(opus, high)" for a Match my session phase @@ -267,9 +307,11 @@ export function loopRunText(state) { */ export function loopStopLabels(state) { const stopping = Boolean(state.stopping); - const on = Boolean(state.stopAfterPhase); + const rounds = state.kind === "rounds"; + const on = Boolean(rounds ? state.stopAfterRound : state.stopAfterPhase); + const unit = rounds ? "round" : "phase"; return { - afterText: on ? "Cancel stop after this phase" : "Stop after this phase", + afterText: on ? `Cancel stop after this ${unit}` : `Stop after this ${unit}`, afterDisabled: stopping || (!on && state.canStopAfter === false), nowDisabled: stopping, }; diff --git a/scripts/test-agent-lookup.mjs b/scripts/test-agent-lookup.mjs index a7ecb2c..6e9ae8b 100644 --- a/scripts/test-agent-lookup.mjs +++ b/scripts/test-agent-lookup.mjs @@ -118,6 +118,13 @@ test("loadAgentList: the shipped agents.json loads with 3 built-ins and 5 templa assert.deepEqual(templates.map((a) => a.id), ["copilot", "opencode", "gemini", "pi", "cursor"]); }); +test("loadAgentList: helpers is true for claude, false for every other shipped entry and for one without the key", (t) => { + const { builtins, templates } = loadAgentList({ dir: path.join(ROOT, "src", "launcher") }); + for (const a of [...builtins, ...templates]) assert.equal(a.helpers, a.id === "claude", a.id); + const dir = listDir(t, JSON.stringify({ schema: 1, agents: [{ kind: "template", id: "x", name: "X", command: "x" }, { kind: "template", id: "y", name: "Y", command: "y", helpers: "yes" }] })); + assert.deepEqual(loadAgentList({ dir }).templates.map((a) => a.helpers), [false, false]); +}); + test("every shipped template passes normalizeAgents() with no warnings", () => { const { templates } = loadAgentList({ dir: path.join(ROOT, "src", "launcher") }); const { agents, warnings } = normalizeAgents(JSON.stringify({ schema: 1, agents: templates })); diff --git a/scripts/test-app-meter.mjs b/scripts/test-app-meter.mjs index 4b5dba3..a13c7f6 100644 --- a/scripts/test-app-meter.mjs +++ b/scripts/test-app-meter.mjs @@ -471,8 +471,9 @@ test("the stop buttons: Stop after is a toggle, off on the last phase, and both 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'\)/); + // The press goes to the phase commands for an Implementation Loop and to the Review Loop's own for rounds. + assert.match(app, /'loop_stop_after_phase', \{ on: !loopStopAfterOn \}\)/); + assert.match(app, /: '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/); @@ -570,6 +571,93 @@ test("the banner and stop buttons agree for a state carrying stopping, stopAfter assert.equal(loopStopLabels(last).afterDisabled, true); }); +// The Review Loop's banner: the same states in round words, one pip per round, and the detail the app builds. +const ROUNDS = { running: true, kind: "rounds", round: 2, rounds: 3, phase: 2, phases: 3, phaseName: "Round 2 of 3: Reviewing", step: "Reviewing", stopAfterRound: false, stopAfterPhase: false, stopping: false, canStopAfter: true, phaseRetried: false, roundCounts: [{ critical: 2, warning: 1 }] }; + +test("a rounds state says Review Loop, with one pip per round and the app's detail line", () => { + const banner = loopBanner(ROUNDS); + assert.equal(banner.title, "Review Loop running"); + assert.equal(banner.detail, "Round 2 of 3: Reviewing"); + assert.equal(banner.tone, "running"); + assert.deepEqual(banner.pips, ["done", "current", "todo"]); + assert.deepEqual(loopBanner({ ...ROUNDS, round: 1 }).pips, ["current", "todo", "todo"]); + assert.deepEqual(loopBanner({ ...ROUNDS, round: 3 }).pips, ["done", "done", "current"]); + assert.deepEqual(loopBanner({ ...ROUNDS, rounds: 6, round: 4 }).pips, ["done", "done", "done", "current", "todo", "todo"]); +}); + +test("a rounds state in each step: fixing with counts, starting, retrying, waiting, stopping, stop after this round", () => { + const fixing = loopBanner({ ...ROUNDS, step: "Fixing", phaseName: "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)" }); + assert.equal(fixing.title, "Review Loop running"); + assert.equal(fixing.detail, "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)"); + // Without the app's detail line the banner builds the plain one from the round and step. + assert.equal(loopBanner({ ...ROUNDS, step: "Testing", phaseName: "" }).detail, "Round 2 of 3: Testing"); + assert.equal(loopBanner({ ...ROUNDS, step: "Testing", phaseName: "Round 2 of 3: Testing", model: "sonnet", effort: "low", strength: "thrifty" }).detail, "Round 2 of 3: Testing \u00b7 Thrifty (sonnet, low)"); + + const first = loopBanner({ ...ROUNDS, round: 1, step: "Starting" }); + assert.equal(first.title, "Starting the Review Loop"); + assert.equal(first.detail, "Opening a fresh agent for Round 1 of 3."); + const next = loopBanner({ ...ROUNDS, step: "Starting" }); + assert.equal(next.title, "Round 1 done"); + assert.equal(next.detail, "Opening a fresh agent for Round 2 of 3."); + const retry = loopBanner({ ...ROUNDS, step: "Starting", phaseRetried: true }); + assert.equal(retry.title, "Retrying round 2"); + assert.match(retry.detail, /crashed or went quiet, so a fresh one is picking up Round 2 of 3/); + + const waiting = loopBanner({ ...ROUNDS, step: "Waiting on you" }); + assert.equal(waiting.title, "The Review Loop needs your answer"); + assert.equal(waiting.tone, "waiting"); + assert.equal(waiting.detail, "Round 2 of 3 is waiting on the question below."); + + const stopping = loopBanner({ ...ROUNDS, stopping: true }); + assert.equal(stopping.title, "Stopping"); + assert.deepEqual(stopping.pips, ["done", "current", "todo"]); + + const after = loopBanner({ ...ROUNDS, stopAfterRound: true, stopAfterPhase: true }); + assert.equal(after.title, "Stopping after this round"); + assert.match(after.detail, /Round 2 of 3 finishes, is judged and committed, then the Review Loop stops/); +}); + +test("a rounds state's stop buttons and window title use round words", () => { + assert.deepEqual(loopStopLabels(ROUNDS), { afterText: "Stop after this round", afterDisabled: false, nowDisabled: false }); + assert.deepEqual(loopStopLabels({ ...ROUNDS, stopAfterRound: true }), { afterText: "Cancel stop after this round", afterDisabled: false, nowDisabled: false }); + assert.equal(loopStopLabels({ ...ROUNDS, canStopAfter: false }).afterDisabled, true, "the cap round has nothing to stop after"); + assert.deepEqual(loopStopLabels({ ...ROUNDS, stopping: true }), { afterText: "Stop after this round", afterDisabled: true, nowDisabled: true }); + assert.equal(loopWindowTitle("C:/git/lunch", ROUNDS), "Review Loop: Round 2 of 3 - lunch"); + assert.equal(loopWindowTitle("C:/git/lunch", { ...ROUNDS, step: "Waiting on you" }), "Review Loop needs you: Round 2 - lunch"); +}); + +test("the Suggestions batch and final check are named for what they are, never as a round past the cap", () => { + const batch = { ...ROUNDS, round: 3, phase: 3, afterRounds: "Suggestions batch", phaseName: "Suggestions batch: Fixing", step: "Fixing" }; + const shown = loopBanner(batch); + assert.equal(shown.detail, "Suggestions batch: Fixing"); + assert.deepEqual(shown.pips, ["done", "done", "done"]); + assert.equal(loopBanner({ ...batch, step: "Starting" }).detail, "Opening a fresh agent for the suggestions batch."); + assert.equal(loopWindowTitle("C:/git/lunch", { ...batch, afterRounds: "Final check" }), "Review Loop: Final check - lunch"); + assert.doesNotMatch(JSON.stringify(shown), /Round 4|of 3: Fixing/); +}); + +test("a phases state renders exactly as before, whatever kind it names", () => { + const phases = { running: true, phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: false, canStopAfter: true }; + const plain = loopBanner(phases); + assert.equal(plain.title, "Implementation loop running"); + assert.equal(plain.detail, "Phase 2 of 4: API \u00b7 Build"); + assert.deepEqual(plain.pips, ["done", "current", "todo", "todo"]); + assert.deepEqual(loopBanner({ ...phases, kind: "phases", round: 0, rounds: 0, roundCounts: [], stopAfterRound: false }), plain); + assert.deepEqual(loopStopLabels({ ...phases, kind: "phases" }), loopStopLabels(phases)); + assert.equal(loopWindowTitle("C:/git/lunch", { ...phases, kind: "phases" }), "Loop: Phase 2 of 4 - lunch"); +}); + +test("app.js hangs round counts on the pips and sends the Review Loop's stop buttons to its own commands", () => { + assert.match(APP_JS, /function roundPipTitle\(state, i\)/); + assert.match(APP_JS, /pip\.title = roundPipTitle\(state, i\)/); + const title = APP_JS.slice(APP_JS.indexOf("function roundPipTitle"), APP_JS.indexOf("function applyLoopState")); + assert.match(title, /if \(state\.kind !== 'rounds'\) return `Phase \$\{i \+ 1\}`/, "a phases pip keeps its title"); + assert.match(title, /Round \$\{i \+ 1\}: \$\{found\.length \? found\.join\(', '\) : 'nothing found'\}/); + assert.match(APP_JS, /pressLoop\(loopKind === 'rounds' \? 'review_loop_stop_after' : 'loop_stop_after_phase'/); + assert.match(APP_JS, /pressLoop\(rounds \? 'review_loop_stop_now' : 'loop_stop_now'\)/); + assert.match(APP_JS, /loopStopAfterOn = !!\(state\.kind === 'rounds' \? state\.stopAfterRound : state\.stopAfterPhase\)/); +}); + 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"); diff --git a/scripts/test-console-wire-budgets.mjs b/scripts/test-console-wire-budgets.mjs index d706eb3..4a97eb2 100644 --- a/scripts/test-console-wire-budgets.mjs +++ b/scripts/test-console-wire-budgets.mjs @@ -43,7 +43,8 @@ export const BUDGETS = { "plan.md": 1023, // raised by the UI prototype line's bytes only "pr-prep.md": 4500, "quick-task.md": 5194, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's and the Changes tab lines' bytes only - "review.md": 1140, // raised by the lessons card line's bytes only + "review-loop.md": 4000, // its written size (3,564 bytes) plus 10 percent, rounded up to the next 100 + "review.md": 1190, // raised by the lessons card line's bytes, then the Review Loop pointer line's bytes only "revise-plan.md": 1422, // raised by the UI prototype line's bytes only "test.md": 5540, // raised by the lessons card line's bytes only "ui-prototype.md": 4600, diff --git a/scripts/test-lanes.json b/scripts/test-lanes.json index de6742e..dbe4b71 100644 --- a/scripts/test-lanes.json +++ b/scripts/test-lanes.json @@ -120,6 +120,7 @@ "test-web-console-page-help.mjs", "test-web-console-page-learning.mjs", "test-web-console-page-loop.mjs", + "test-web-console-page-review-loop.mjs", "test-web-console-page-notepad.mjs", "test-web-console-page-prefs.mjs", "test-web-console-page-send.mjs", @@ -128,6 +129,7 @@ "test-web-console-page-workspace.mjs", "test-web-console-pointers.mjs", "test-web-console-qa.mjs", + "test-web-console-review-loop.mjs", "test-web-console-server.mjs", "test-web-console-session.mjs", "test-web-console-source.mjs", diff --git a/scripts/test-web-console-loop.mjs b/scripts/test-web-console-loop.mjs index cedf659..94d3e92 100644 --- a/scripts/test-web-console-loop.mjs +++ b/scripts/test-web-console-loop.mjs @@ -17,7 +17,7 @@ import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; -import { applyPatch, blankState, validate, switchWorkflow } from "../src/web-console/patches.mjs"; +import { applyPatch, blankState, validate, switchWorkflow, ROUND_ROLES } from "../src/web-console/patches.mjs"; import { ROOT, CONSOLE_CLI, ENV, HOME, MODELS_DIR, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs"; const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"]; @@ -82,13 +82,13 @@ test("open --loop under the app locks the session: loop { driving: true } in sta } }); -test("open --loop goes only with Implement or Implement + Review: any other workflow, or none, exits 2", () => { +test("open --loop goes only with Implement, Implement + Review or Review: any other workflow, or none, exits 2", () => { const cwd = tempProject("gate-wf"); const before = sessionCount(); for (const args of [["--workflow", "plan"], ["--workflow", "dashboard"], []]) { const res = run(["open", ...args, "--loop", "--no-open"], { cwd, extra: IN_APP }); assert.equal(res.status, 2, `exit 2 for ${args.join(" ") || "no workflow"}`); - assert.match(res.stderr, /--loop goes only with --workflow implement or --workflow implement-review/); + assert.match(res.stderr, /--loop goes only with --workflow implement or --workflow implement-review or --workflow review/); } assert.equal(sessionCount(), before, "no session folder was made"); }); @@ -546,6 +546,75 @@ test("loopEnd: an unknown evidence id, a push in can, and the other bad fields a } }); +const REPORT_DOC = { id: "report", title: "Review Loop report", blocks: [{ id: "b1", md: "# Clean\n\nNo findings." }] }; +const PARTIAL_DOC = { id: "partial-diff", title: "partial.diff", blocks: [{ id: "d1", diff: "partial.diff", text: "diff --git a/x b/x\n" }] }; +const reviewEnd = (extra = {}) => ({ + kind: "review", + line: "Clean after 2 rounds", + reason: "clean", + report: "report", + canContinue: false, + canSquash: false, + can: [], + ...extra, +}); + +test("loopEnd: a review end with each reason is stored, with no phases or uncommitted", () => { + for (const reason of ["clean", "cap", "person", "failed"]) { + const { problems, next } = tryPatch(loopState(), { docs: [REPORT_DOC], loopEnd: reviewEnd({ reason }) }); + assert.deepEqual(problems, [], reason); + assert.equal(next.loopEnd.reason, reason); + assert.equal(next.loopEnd.kind, "review"); + } + const full = reviewEnd({ + reason: "person", + canContinue: true, + canSquash: true, + partial: { files: 1, added: 2, removed: 0, diff: "partial-diff" }, + suggestions: [{ id: "s1", title: "Rename it", file: "src/a.js", line: 4 }, { id: "s2", title: "Tidy", file: "" }], + open: [{ title: "Unchecked input", file: "src/b.js", line: 9 }, { level: "warning", title: "Slow loop", file: "src/c.js" }], + signedOff: true, + note: "Squashed 3 round commits into one.", + can: ["dashboard"], + }); + const stored = tryPatch(loopState(), { docs: [REPORT_DOC, PARTIAL_DOC], loopEnd: full }); + assert.deepEqual(stored.problems, []); + assert.equal(stored.next.loopEnd.signedOff, true); +}); + +test("loopEnd: bad review fields are refused, each named", () => { + const cases = [ + ["a bad reason", reviewEnd({ reason: "done" }), /loopEnd\.reason must be one of clean, cap, person, failed/], + ["a missing report", reviewEnd({ report: undefined }), /loopEnd\.report must be the id of a doc on the page/], + ["an unknown report", reviewEnd({ report: "nope" }), /loopEnd\.report must be the id of a doc on the page/], + ["a non-boolean canContinue", reviewEnd({ canContinue: "yes" }), /loopEnd\.canContinue must be true or false/], + ["a non-boolean canSquash", reviewEnd({ canSquash: 1 }), /loopEnd\.canSquash must be true or false/], + ["a non-boolean signedOff", reviewEnd({ signedOff: "yes" }), /loopEnd\.signedOff must be true or false/], + ["can that is not an array", reviewEnd({ can: undefined }), /loopEnd\.can must be an array/], + ["a two-line note", reviewEnd({ note: "a\nb" }), /loopEnd\.note must be one line/], + ["a two-line line", reviewEnd({ line: "a\nb" }), /loopEnd\.line must be one line/], + ["a partial with an unknown diff", reviewEnd({ partial: { files: 1, added: 1, removed: 1, diff: "nope" } }), /loopEnd\.partial\.diff must be the id of a doc on the page/], + ["a negative partial count", reviewEnd({ partial: { files: -1, added: 1, removed: 1, diff: "report" } }), /loopEnd\.partial\.files must be a non-negative integer/], + ["a suggestion with a bad id", reviewEnd({ suggestions: [{ id: "x", title: "T", file: "" }] }), /loopEnd\.suggestions\[0\]\.id must look like s1/], + ["duplicate suggestion ids", reviewEnd({ suggestions: [{ id: "s1", title: "A", file: "" }, { id: "s1", title: "B", file: "" }] }), /loopEnd\.suggestions\[1\]\.id must be unique/], + ["a suggestion file that climbs out", reviewEnd({ suggestions: [{ id: "s1", title: "A", file: "../x" }] }), /loopEnd\.suggestions\[0\]\.file must be a relative path/], + ["a suggestion line of zero", reviewEnd({ suggestions: [{ id: "s1", title: "A", file: "a.js", line: 0 }] }), /loopEnd\.suggestions\[0\]\.line must be a positive integer/], + ["an open item with no file", reviewEnd({ open: [{ title: "A" }] }), /loopEnd\.open\[0\]\.file must be a relative path/], + ["an open item with a bad level", reviewEnd({ open: [{ level: "info", title: "A", file: "a.js" }] }), /loopEnd\.open\[0\]\.level must be/], + ["a forbidden marker in line", reviewEnd({ line: "TASK_COMPLETE" }), /loopEnd\.line: contains a loop completion marker/], + ]; + for (const [what, end, expected] of cases) { + const { problems } = tryPatch(loopState(), { docs: [REPORT_DOC], loopEnd: end }); + assert.ok(problems.some((p) => expected.test(p)), `${what}: expected ${expected}, got ${JSON.stringify(problems)}`); + } +}); + +test("loopEnd: an Implementation Loop end still needs its phases and uncommitted, and review ones never need evidence", () => { + assert.deepEqual(tryPatch(loopState(), { loopEnd: goodEnd() }).problems, []); + const { phases, ...noPhases } = goodEnd(); + assert.ok(tryPatch(loopState(), { loopEnd: noPhases }).problems.some((p) => /loopEnd\.phases must be an array/.test(p))); +}); + test("handledBy: \"loop\" is accepted in a loop session and refused outside one or with any other value", () => { const card = (extra = {}) => ({ id: "fixes", @@ -604,6 +673,7 @@ test("loop-setup: a new project reads as the defaults with remembered false, and assert.equal(got.setup.onQuestion, "guess"); assert.deepEqual(got.setup.fix, ["critical", "warning", "suggestion"]); assert.equal(got.setup.silenceMinutes, 20); + assert.equal(got.setup.reviewRounds, 2, "a phase gets two extra review rounds by default"); assert.equal(got.setup.notifyUrl, "", "no web address is called by default"); assert.equal(got.setup.notifyKind, "query"); assert.equal(got.setup.notifyParam, "message"); @@ -658,6 +728,38 @@ test("loop-setup: a save reads back per project, keeps another project's entry, const WORKSPACE_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "workspace.mjs")).href; +test("loop-setup: an entry saved before reviewRounds existed reads the default 2", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const got = inStore( + async (m, { project, workspace }) => { + const fs = await import("node:fs"); + const { foldKey } = await import(workspace); + const { reviewRounds, ...legacy } = { ...m.LOOP_DEFAULTS, fix: ["warning"], saved: "2026-01-01T00:00:00.000Z" }; + fs.writeFileSync(m.LOOP_SETUP_FILE, JSON.stringify({ schema: 1, projects: { [foldKey(project)]: legacy } })); + const stored = JSON.parse(fs.readFileSync(m.LOOP_SETUP_FILE, "utf8")).projects[foldKey(project)]; + const kept = m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: ["warning"], reviewRounds: 0 }); + return { read: m.readLoopSetup(project), onDisk: "reviewRounds" in stored, kept: kept.reviewRounds }; + }, + { project: projectA, workspace: WORKSPACE_URL } + ); + assert.equal(got.onDisk, false, "the stored entry has no reviewRounds"); + assert.equal(got.kept, 0, "0 turns the rounds off and is remembered"); + assert.equal(got.read.reviewRounds, 0); + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const old = inStore( + async (m, { project, workspace }) => { + const fs = await import("node:fs"); + const { foldKey } = await import(workspace); + const { reviewRounds, ...legacy } = { ...m.LOOP_DEFAULTS, fix: ["warning"], saved: "2026-01-01T00:00:00.000Z" }; + fs.writeFileSync(m.LOOP_SETUP_FILE, JSON.stringify({ schema: 1, projects: { [foldKey(project)]: legacy } })); + return m.readLoopSetup(project); + }, + { project: projectA, workspace: WORKSPACE_URL } + ); + assert.equal(old.reviewRounds, 2, "an older entry reads the default"); + assert.equal(old.remembered, true); +}); + test("loop-setup: an entry saved before fixMode existed reads as levels", () => { fs.rmSync(LOOP_SETUP_PATH, { force: true }); const got = inStore( @@ -724,6 +826,7 @@ test("loop-setup: a bad field throws with the problem named and leaves the file const cases = [ ["silenceMinutes: 0", { silenceMinutes: 0 }, /"silenceMinutes" must be a whole number from 1 to 60/], ["silenceMinutes: 61", { silenceMinutes: 61 }, /"silenceMinutes"/], + ...[-1, 7, 1.5, "2", null].map((reviewRounds) => [`reviewRounds: ${reviewRounds}`, { reviewRounds }, /"reviewRounds" must be a whole number from 0 to 6/]), ...["example.com", "ftp://example.com", "javascript:alert(1)", "https:/example.com", "https://", "https://me:secret@example.com/", "https://exa mple.com", "https://example.com/é", "https://example.com/\nx", `https://e.com/${"x".repeat(2000)}`].map((notifyUrl) => [`notifyUrl: ${notifyUrl.slice(0, 30)}`, { notifyUrl }, /"notifyUrl" must be an http or https web address/]), ["notifyUrl as a number", { notifyUrl: 5 }, /"notifyUrl"/], ["notifyKind: carrier-pigeon", { notifyKind: "carrier-pigeon" }, /"notifyKind" must be one of query, discord, slack, teams, google-chat, json/], @@ -854,7 +957,7 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a } // Saving through the route, then reading it back in a new request. - const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", notifyPhases: true, retryOnce: true, silenceMinutes: 30, phaseStrength: false, strengths: {} }); + const save = await send({ review: true, reviewRounds: 3, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", notifyPhases: true, retryOnce: true, silenceMinutes: 30, phaseStrength: false, strengths: {} }); assert.equal(save.status, 200, await save.clone().text()); const after = await get("?spec=specs/demo"); assert.equal(after.body.remembered, true); @@ -1024,7 +1127,7 @@ test("GET /loop-setup?agent= answers the loop agent's resolved strengths and thi // A save with picks reads back for its own spec; a pick for a phase that is not there is pruned. const entry = { review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "guess", afterLast: "offer-finalize", quickCheck: "", - notifyKind: "query", notifyUrl: "", notifyParam: "message", notifyPhases: false, retryOnce: true, silenceMinutes: 20, phaseStrength: true, + notifyKind: "query", notifyUrl: "", notifyParam: "message", notifyPhases: false, retryOnce: true, silenceMinutes: 20, reviewRounds: 2, phaseStrength: true, strengths: { "specs/demo": [{ n: 2, name: "Two", strength: "best" }, { n: 9, name: "Gone", strength: "best" }] }, }; const save = await fetch(`${base}/loop-setup`, { method: "POST", headers: { "content-type": "application/json", cookie, origin: base, connection: "close" }, body: JSON.stringify(entry) }); @@ -1078,3 +1181,226 @@ test("loopSuggest: each bad field is refused with a message naming it", () => { assert.ok(got.problems.some((p) => pattern.test(p)), `${label}: ${got.problems.join(" | ") || "accepted"}`); } }); + +/* -------------------------------------- Review Loop rounds: open and report */ + +const ROUND_FLAGS = (scope) => ["--round", "2", "--role", "both", "--scope-file", scope]; + +function openRound(name = "round", flags = {}) { + const cwd = tempProject(name); + const scope = path.join(cwd, "scope.md"); + fs.writeFileSync(scope, "Scope: the branch diff\n"); + const args = ["open", "--workflow", "review", "--loop", "--no-open", "--round", String(flags.round ?? 2), "--role", flags.role ?? "both", "--scope-file", scope]; + const res = run(args, { cwd, extra: IN_APP }); + assert.equal(res.status, 0, res.stderr); + const stop = () => cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); + return { cwd, sid: res.json.sid, session: res.json.session, scope, json: res.json, stop }; +} + +test("a Review Loop round opens only with --round, --role and --scope-file, each checked, exit 2 naming the flag", () => { + const cwd = tempProject("round-gate"); + const scope = path.join(cwd, "scope.md"); + fs.writeFileSync(scope, "x"); + const before = sessionCount(); + const base = ["open", "--workflow", "review", "--loop", "--no-open"]; + const cases = [ + [["--role", "both", "--scope-file", scope], /--round/], + [["--round", "2", "--scope-file", scope], /--role/], + [["--round", "2", "--role", "both"], /--scope-file/], + [["--round", "0", "--role", "both", "--scope-file", scope], /--round/], + [["--round", "x", "--role", "both", "--scope-file", scope], /--round/], + [["--round", "2", "--role", "boss", "--scope-file", scope], /--role/], + [["--round", "2", "--role", "both", "--scope-file", path.join(cwd, "nope.md")], /--scope-file/], + ]; + for (const [flags, pattern] of cases) { + const res = run([...base, ...flags], { cwd, extra: IN_APP }); + assert.equal(res.status, 2, flags.join(" ")); + assert.match(res.stderr, pattern); + } + assert.equal(sessionCount(), before, "no session folder was made"); +}); + +test("the round flags are refused on an Implement loop open and without --loop, and outside the app a round open exits 3", () => { + const cwd = tempProject("round-other"); + const scope = path.join(cwd, "scope.md"); + fs.writeFileSync(scope, "x"); + const withRound = ROUND_FLAGS(scope); + assert.equal(run(["open", "--workflow", "implement", "--loop", "--no-open", ...withRound], { cwd, extra: IN_APP }).status, 2); + assert.equal(run(["open", "--workflow", "review", "--no-open", ...withRound], { cwd, extra: IN_APP }).status, 2); + const outside = run(["open", "--workflow", "review", "--loop", "--no-open", ...withRound], { cwd }); + assert.equal(outside.status, 3); + assert.match(outside.stderr, /desktop app/); +}); + +test("a round session is stamped with its round, role and scope file, and its open names the round notes", () => { + const s = openRound("round-stamp", { round: 3, role: "reviewer" }); + try { + assert.deepEqual(readState(s.session).loop, { driving: true, round: 3, role: "reviewer", scopeFile: s.scope }); + assert.deepEqual(s.json.read, [path.join(path.dirname(CONSOLE_CLI), "notes", "review-loop.md")]); + const again = run(["open", "--resume", s.sid, "--workflow", "review", "--loop", "--no-open", "--round", "3", "--role", "reviewer", "--scope-file", s.scope], { cwd: s.cwd, extra: IN_APP }); + assert.equal(again.status, 0, again.stderr); + assert.equal(readState(s.session).loop.round, 3); + } finally { + s.stop(); + } + // An Implement loop keeps its stamp exactly as it was. + const impl = openLoop("implement", "round-impl"); + try { + assert.deepEqual(readState(impl.session).loop, { driving: true }); + } finally { + impl.stop(); + } +}); + +// A round session's state as post would see it: the stamp, and the report doc. +const roundState = (role = "both", extra = {}) => ({ + ...blankState({ sid: "s", workflow: "review", project: "p" }), + loop: { driving: true, round: 2, role, scopeFile: "scope.md" }, + docs: [{ id: "report", title: "Report", version: 1, stale: false, blocks: [{ id: "b", md: "Findings" }] }], + ...extra, +}); +const goodRound = (role = "both") => ({ + round: 2, + role, + result: "passed", + reason: null, + summary: "Fixed 2 warnings; 1 suggestion left", + report: "report", + review: { + critical: 0, + warning: 2, + suggestion: 1, + fixed: [{ title: "Close the file handle", file: "src/z.js", line: 12 }], + unfixed: [], + suggestions: [{ title: "Name the timer", file: "src/x.js" }], + }, + tests: { ran: true, passed: true, summary: "14 pass" }, + subject: "Close the file handle in z.js", +}); + +test("a roundOutcome is stored with its report doc in the session, once, for each role", () => { + assert.deepEqual(ROUND_ROLES, ["both", "reviewer", "fixer"]); + for (const role of ROUND_ROLES) { + const o = goodRound(role); + if (role === "reviewer") delete o.tests; + if (role === "fixer") delete o.report; + const got = tryPatch(roundState(role, role === "fixer" ? { docs: [] } : {}), { roundOutcome: o }); + assert.deepEqual(got.problems, [], role); + assert.deepEqual(got.next.roundOutcome, o); + } + const first = tryPatch(roundState(), { roundOutcome: goodRound() }); + const second = tryPatch(first.next, { roundOutcome: goodRound() }); + assert.match(second.problems.join(" "), /roundOutcome: was already posted/); +}); + +test("a roundOutcome with no report doc is refused naming roundOutcome.report", () => { + for (const role of ["both", "reviewer"]) { + const missing = tryPatch(roundState(role, { docs: [] }), { roundOutcome: goodRound(role) }); + assert.match(missing.problems.join(" "), /roundOutcome\.report must name a report doc already posted in this session/, role); + } + const wrong = tryPatch(roundState(), { roundOutcome: { ...goodRound(), report: "other" } }); + assert.match(wrong.problems.join(" "), /roundOutcome\.report/); +}); + +test("each bad roundOutcome field is refused with a message naming it", () => { + const mut = (fn, role = "both") => { + const o = goodRound(role); + fn(o); + return tryPatch(roundState(role), { roundOutcome: o }).problems.join(" | "); + }; + const cases = [ + ["round", (o) => (o.round = 3), /roundOutcome\.round/], + ["round type", (o) => (o.round = "2"), /roundOutcome\.round/], + ["role", (o) => (o.role = "fixer"), /roundOutcome\.role/], + ["result", (o) => (o.result = "maybe"), /roundOutcome\.result/], + ["reason when passed", (o) => (o.reason = "tests"), /roundOutcome\.reason/], + ["reason when failed", (o) => ((o.result = "failed"), (o.reason = "nope")), /roundOutcome\.reason/], + ["summary empty", (o) => (o.summary = ""), /roundOutcome\.summary/], + ["summary long", (o) => (o.summary = "x".repeat(201)), /roundOutcome\.summary/], + ["summary lines", (o) => (o.summary = "a\nb"), /roundOutcome\.summary/], + ["subject long", (o) => (o.subject = "x".repeat(101)), /roundOutcome\.subject/], + ["review missing", (o) => delete o.review, /roundOutcome\.review /], + ["review count", (o) => (o.review.warning = -1), /roundOutcome\.review\.warning/], + ["review list", (o) => (o.review.fixed = "none"), /roundOutcome\.review\.fixed/], + ["review list size", (o) => (o.review.unfixed = Array.from({ length: 51 }, () => ({ title: "t", file: "a.js" }))), /roundOutcome\.review\.unfixed/], + ["finding file", (o) => (o.review.fixed[0].file = "../x"), /roundOutcome\.review\.fixed\[0\]\.file/], + ["finding line", (o) => (o.review.fixed[0].line = 0), /roundOutcome\.review\.fixed\[0\]\.line/], + ["tests missing", (o) => delete o.tests, /roundOutcome\.tests /], + ["tests passed", (o) => (o.tests.passed = "yes"), /roundOutcome\.tests\.passed/], + ["completion marker", (o) => (o.summary = "TASK_COMPLETE"), /roundOutcome\.summary/], + ]; + for (const [label, fn, pattern] of cases) assert.match(mut(fn), pattern, label); +}); + +test("a roundOutcome outside a round session is refused, and a loopOutcome in a round session is refused", () => { + const plain = tryPatch({ ...blankState({ sid: "s", workflow: "review", project: "p" }) }, { roundOutcome: goodRound() }); + assert.match(plain.problems.join(" "), /roundOutcome: is only accepted in a Review Loop round session/); + const impl = tryPatch(loopState(), { roundOutcome: goodRound() }); + assert.match(impl.problems.join(" "), /roundOutcome: is only accepted in a Review Loop round session/); + const viaLoop = tryPatch(roundState(), { loopOutcome: goodOutcome() }); + assert.match(viaLoop.problems.join(" "), /a round reports roundOutcome, not loopOutcome/); +}); + +test("blankState holds no roundOutcome and a hop drops it", () => { + assert.equal("roundOutcome" in blankState({ sid: "s", workflow: "review", project: "p" }), false); + const hopped = switchWorkflow(roundState("both", { roundOutcome: goodRound() }), { workflow: "plan", title: "t", specDir: "" }); + assert.equal("roundOutcome" in hopped, false); + assert.equal("loop" in hopped, false); +}); + +test("a resume drops a stored roundOutcome and report doc when the round or role changes or the lock goes, and keeps them otherwise", () => { + const s = openRound("round-resume", { round: 2, role: "reviewer" }); + const resume = (flags) => run(["open", "--resume", s.sid, "--no-open", ...flags], { cwd: s.cwd, extra: IN_APP }); + const loopFlags = (round, role) => ["--workflow", "review", "--loop", "--round", String(round), "--role", role, "--scope-file", s.scope]; + const seed = () => { + const o = goodRound("reviewer"); + delete o.tests; + const res = post(s, { docs: [{ id: "report", title: "Report", blocks: [{ id: "b1", md: "Findings" }] }], roundOutcome: o }); + assert.equal(res.status, 0, res.stderr); + assert.ok(readState(s.session).roundOutcome, "seeded"); + }; + try { + seed(); + assert.equal(resume(loopFlags(2, "reviewer")).status, 0); + assert.ok(readState(s.session).roundOutcome, "the same round and role keeps its report"); + assert.ok(readState(s.session).docs.some((d) => d.id === "report")); + assert.equal(resume(loopFlags(2, "fixer")).status, 0); + let state = readState(s.session); + assert.equal("roundOutcome" in state, false, "a new role starts without the old report"); + assert.equal(state.docs.some((d) => d.id === "report"), false, "and without the old report doc"); + assert.equal(state.loop.role, "fixer"); + // The fixer's own report is now accepted. + const o = goodRound("fixer"); + delete o.report; + assert.equal(post(s, { roundOutcome: o }).status, 0); + assert.equal(resume(loopFlags(3, "fixer")).status, 0); + assert.equal("roundOutcome" in readState(s.session), false, "a new round starts without the old report"); + seedFixer(s); + assert.equal(resume(["--workflow", "review"]).status, 0); + state = readState(s.session); + assert.equal("roundOutcome" in state, false, "a resume without --loop drops the report"); + assert.equal("loop" in state, false); + } finally { + s.stop(); + } + function seedFixer(sess) { + const o = goodRound("fixer"); + o.round = 3; + delete o.report; + const res = run(["open", "--resume", sess.sid, "--no-open", ...loopFlags(3, "fixer")], { cwd: sess.cwd, extra: IN_APP }); + assert.equal(res.status, 0); + assert.equal(post(sess, { roundOutcome: o }).status, 0); + } +}); + +test("a round session's scope file is stored as an absolute path", () => { + const cwd = tempProject("round-scope"); + fs.writeFileSync(path.join(cwd, "scope.md"), "x"); + const res = run(["open", "--workflow", "review", "--loop", "--no-open", "--round", "1", "--role", "both", "--scope-file", "scope.md"], { cwd, extra: IN_APP }); + try { + assert.equal(res.status, 0, res.stderr); + assert.equal(readState(res.json.session).loop.scopeFile, path.join(cwd, "scope.md")); + } finally { + cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); + } +}); diff --git a/scripts/test-web-console-page-loop.mjs b/scripts/test-web-console-page-loop.mjs index eaaa661..3e8925d 100644 --- a/scripts/test-web-console-page-loop.mjs +++ b/scripts/test-web-console-page-loop.mjs @@ -956,3 +956,37 @@ test("a pick for an unmapped word, or a phase left out, keeps that row as it was assert.deepEqual((await strengthRows(s)).map((r) => r.pick), ["", "thrifty"]); assert.equal(await s.page.locator(".loop-strength-why").count(), 0, "no reason shows for a pick that was not applied"); }); + +test("Review rounds per phase shows under Review, is off with Review off, and goes out with the setup", async (t) => { + const s = await openSetup(t); + const rounds = s.page.locator("#loop-review-rounds"); + const field = s.page.locator(".loop-field", { hasText: "Review each phase with a fresh agent" }); + assert.equal(await field.locator("#loop-review-rounds").count(), 1, "the number sits in the Review field"); + assert.equal(await rounds.inputValue(), "2", "two rounds by default"); + assert.deepEqual(await rounds.evaluate((el) => [el.min, el.max, el.disabled]), ["0", "6", false]); + assert.equal(await field.getByText("Applies only with Review on").count(), 0, "no hint while Review is on"); + + await rounds.fill("4"); + await s.page.locator("#loop-review").uncheck(); + assert.equal(await rounds.isDisabled(), true, "Review off disables the field"); + assert.equal(await field.getByText("Applies only with Review on").count(), 1); + assert.equal(await rounds.inputValue(), "4", "the number is kept while it is off"); + + await s.page.locator("#loop-review").check(); + assert.equal(await rounds.isDisabled(), false); + const body = await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + const { setupBody } = await import(new URL("screens/loop-setup.js", document.baseURI).href); + return setupBody(page.loopSetup.form, page.loopSetup); + }); + assert.equal(body.reviewRounds, 4, "the number is in the posted body"); + const saved = await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + const { setupBody } = await import(new URL("screens/loop-setup.js", document.baseURI).href); + const res = await fetch("/loop-setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(setupBody(page.loopSetup.form, page.loopSetup)) }); + return { status: res.status, body: await res.json() }; + }); + assert.equal(saved.status, 200, JSON.stringify(saved.body)); + const reread = await s.page.evaluate(async () => (await fetch("/loop-setup")).json()); + assert.equal(reread.reviewRounds, 4, "remembered with the rest of the setup"); +}); diff --git a/scripts/test-web-console-page-review-loop.mjs b/scripts/test-web-console-page-review-loop.mjs new file mode 100644 index 0000000..9bbf4cc --- /dev/null +++ b/scripts/test-web-console-page-review-loop.mjs @@ -0,0 +1,421 @@ +// Page tests for the Review Loop's setup screen. The dashboard card that opens +// it only shows inside the desktop app, so these open the screen through its +// own module, then drive the real page, the way test-web-console-page-loop.mjs +// does for the Implementation Loop's. Run with: +// node --test scripts/test-web-console-page-review-loop.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs"; +import { MODELS_DIR } from "./web-console-test-helpers.mjs"; + +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); + +const suite = pageSuite(test); + +const PROJECT = { + "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n", + "specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n", + "specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n", +}; + +const MENU = { menu: { note: "Ready when you are." }, agent: { status: "waiting" } }; + +const FACTS = { agent: "claude", agentLabel: "Claude Code", helpers: true, strengthsMapped: true, running: false, promptSupport: true, notifyKind: "query", notifyUrl: "", notifyParam: "message" }; + +// Stands a real window in for the app that frames the page, listening to what +// the page tells it; the returned function replies the way the app does. +async function frameInFakeApp(s) { + await s.page.evaluate(() => { + const frame = document.createElement("iframe"); + frame.hidden = true; + document.body.appendChild(frame); + const app = frame.contentWindow; + window.__told = []; + app.postMessage = (message) => window.__told.push(message); + Object.defineProperty(window, "parent", { value: app, configurable: true }); + }); + return (data) => + s.page.evaluate((message) => { + window.dispatchEvent(new MessageEvent("message", { source: window.parent, data: message })); + }, data); +} + +// The installed copy of the shipped model menu, with its strengths, as install.js drops it. +function installShippedModels() { + const shipped = path.join(MODELS_DIR, "bin", "models.json"); + fs.mkdirSync(path.dirname(shipped), { recursive: true }); + fs.copyFileSync(path.join(ROOT, "src", "launcher", "models.json"), shipped); +} + +async function openReview(t, { spec = null } = {}) { + installShippedModels(); + const browser = await suite.browser(); + const s = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const skip = s.page.getByRole("button", { name: "Skip the intro" }); + await skip.click(); + await skip.waitFor({ state: "hidden" }); + await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor(); + const welcomeDone = s.page.getByRole("button", { name: "Start building" }); + if (await welcomeDone.isVisible()) { + await welcomeDone.click(); + await welcomeDone.waitFor({ state: "hidden" }); + } + const answer = await frameInFakeApp(s); + await s.page.evaluate(async (pick) => { + const m = await import(new URL("screens/review-loop-setup.js", document.baseURI).href); + await m.openReviewLoopSetup(pick); + }, spec); + await s.page.locator("#review-loop-start").waitFor(); + return { ...s, answer }; +} + +const radios = (s, name) => s.page.locator(`input[name="${name}"]`).evaluateAll((all) => all.map((r) => [r.id, r.checked])); + +test("the screen asks the app for its facts and lists its fields in order, with their defaults", async (t) => { + const s = await openReview(t); + assert.ok(await s.page.evaluate(() => window.__told.some((m) => m.plan2code === "review-loop-facts")), "the facts were asked for"); + + const labels = await s.page.locator(".loop-label").allInnerTexts(); + assert.deepEqual(labels, ["What to review", "Round cap", "Commit", "Suggestions", "Strength", "Reviewers", "If a round goes quiet", "Send a notification"]); + assert.deepEqual(await radios(s, "reviewscope"), [["loop-reviewscope-branch", true], ["loop-reviewscope-uncommitted", false], ["loop-reviewscope-spec", false]]); + assert.equal(await s.page.locator("#review-loop-spec").count(), 0, "no spec picker until the spec scope is chosen"); + assert.equal(await s.page.locator("#review-loop-cap").inputValue(), "3"); + assert.equal(await s.page.locator("#review-loop-commit").isChecked(), true, "commit each round is on"); + assert.equal(await s.page.locator("#review-loop-suggestions").isChecked(), false, "Suggestions on their own are off"); + assert.equal(await s.page.locator("#loop-silence").inputValue(), "20"); + assert.equal(await s.page.locator("#loop-notify-url").inputValue(), ""); + assert.equal(await s.page.locator("#review-loop-notify-rounds").isVisible(), false, "no address, no round messages to choose"); + + await s.page.locator("#loop-notify-url").fill("https://example.com/hook"); + const rounds = s.page.locator("#review-loop-notify-rounds"); + assert.equal(await rounds.isVisible(), true); + assert.equal(await rounds.isChecked(), false, "a message per round is opt-in"); + assert.match(await textOf(s.page.locator("label", { has: rounds })), /Also tell me when each round finishes/); +}); + +test("a spec picked on the dashboard fills the picker and the spec scope", async (t) => { + const s = await openReview(t, { spec: { dir: "specs/ready" } }); + assert.deepEqual(await radios(s, "reviewscope"), [["loop-reviewscope-branch", false], ["loop-reviewscope-uncommitted", false], ["loop-reviewscope-spec", true]]); + assert.equal(await s.page.locator("#review-loop-spec").inputValue(), "specs/ready"); + // The pre-fill is not a save. + const saved = await s.page.evaluate(async () => (await fetch("/review-loop-setup")).json()); + assert.equal(saved.remembered, false); + assert.equal(saved.scope, "branch"); + + await s.page.locator("#review-loop-spec").selectOption(""); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + await s.page.getByText("Pick the spec whose work to review.").waitFor(); + assert.equal(await s.page.locator("#review-loop-start").isDisabled(), true, "the spec scope needs a spec"); +}); + +test("uncommitted changes need a tick before Start, and the tick is what the app is told", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + const start = s.page.locator("#review-loop-start"); + await s.page.waitForFunction(() => !document.getElementById("review-loop-start").disabled); + assert.equal(await s.page.locator("#review-loop-agree").count(), 0, "a clean tree has nothing to agree to"); + + // The tree is dirty: two files changed (what the console's scan counts). + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + page.reviewLoopSetup.facts.pending = 2; + redraw(); + }); + const tick = s.page.locator("#review-loop-agree"); + await tick.waitFor(); + assert.match(await textOf(s.page.locator("label", { has: tick })), /Commit my current changes first as Work before Review Loop/); + assert.equal(await tick.isChecked(), false); + assert.equal(await start.isDisabled(), true, "Start waits on the tick"); + assert.match(await textOf(s.page.locator(".loop-why")), /2 uncommitted changes need your say-so/); + + await tick.check(); + assert.equal(await start.isDisabled(), false); + await start.click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-start")); + const sent = await s.page.evaluate(() => window.__told.find((m) => m.plan2code === "review-loop-start")); + assert.deepEqual(sent.setup, { scope: "branch", spec: "", cap: 3, commit: true, suggestions: false, strength: "", silenceMinutes: 20, notifyRounds: false, preRunCommitAgreed: true }); + const saved = await s.page.evaluate(async () => (await fetch("/review-loop-setup")).json()); + assert.equal(saved.remembered, true, "the picks were saved first"); + assert.equal("preRunCommitAgreed" in saved, false, "the agreement is never remembered"); + + await s.page.getByText("Waiting for the app's confirm...").waitFor(); + await s.answer({ plan2code: "review-loop-start-result", ok: false, started: false, error: "A loop is already running." }); + await s.page.getByText("A loop is already running.").waitFor(); + assert.equal(await start.isDisabled(), false, "a refusal shows inline and gives the button back"); +}); + +test("turning commits off drops the tick, and the app is told the work needs no agreement", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + page.reviewLoopSetup.facts.pending = 1; + redraw(); + }); + await s.page.locator("#review-loop-agree").waitFor(); + await s.page.locator("#review-loop-commit").uncheck(); + assert.equal(await s.page.locator("#review-loop-agree").count(), 0); + await s.page.locator("#review-loop-start").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-start")); + const sent = await s.page.evaluate(() => window.__told.find((m) => m.plan2code === "review-loop-start")); + assert.equal(sent.setup.commit, false); + assert.equal(sent.setup.preRunCommitAgreed, false); +}); + +test("the hands-off line and the reviewer note are on the screen", async (t) => { + const s = await openReview(t); + const main = await textOf(s.page.locator(".review-loop-setup")); + assert.ok(main.includes("Please do not edit this project's files while rounds run: anything changed goes into the round.")); + assert.ok(main.includes("Each round's reviewer runs fresh, whatever the Subagents switch says; the switch still governs other helpers.")); +}); + +test("an agent with no strengths mapped grays the strength choice and links to Agents & models", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: { ...FACTS, agent: "nonesuch", strengthsMapped: false } }); + const note = s.page.locator(".loop-strength-none"); + await note.waitFor(); + assert.match(await textOf(note), /This agent has no strengths mapped yet\./); + assert.equal(await s.page.locator("#review-loop-strength").count(), 0, "no picker to choose from"); + await note.getByRole("button", { name: "Map them in Agents & models" }).click(); + await s.page.locator("#prefs-modal[open], dialog[open]").first().waitFor(); +}); + +test("an agent with strengths shows the choice, and a running loop holds Start", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + await s.page.locator("#review-loop-strength").waitFor(); + const options = await s.page.locator("#review-loop-strength option").allInnerTexts(); + assert.equal(options[0], "Match my session"); + assert.equal(await s.page.locator("#review-loop-strength").inputValue(), ""); + + await s.answer({ plan2code: "review-loop-facts", facts: { ...FACTS, running: true } }); + await s.page.getByText(/A loop is already running in this window/).waitFor(); + assert.equal(await s.page.locator("#review-loop-start").isDisabled(), true); +}); + +/* ---------------------------------------------------------------- the end */ + +const DIFF = [ + "diff --git a/src/app.js b/src/app.js", + "index 1111111..2222222 100644", + "--- a/src/app.js", + "+++ b/src/app.js", + "@@ -1,2 +1,3 @@", + " one", + "-two", + "+TWO", + "+three", + "", +].join("\n"); + +const REPORT_DOC = { id: "report", title: "Review Loop report", blocks: [{ id: "r1", md: "# Report\n\nTwo rounds ran." }] }; +const PARTIAL_DOC = { id: "partial", title: "Partial changes", blocks: [{ id: "p1", diff: "partial.diff" }] }; + +const END = { + kind: "review", + line: "No Critical or Warning findings are left.", + reason: "clean", + report: "report", + canContinue: false, + canSquash: false, + can: [], +}; + +const SUGGESTIONS = [ + { id: "s1", title: "Rename the helper", file: "src/a.js", line: 12 }, + { id: "s2", title: "Drop the unused import", file: "" }, +]; + +// A review session as the app's window shows it, the app faked, with `end` +// posted along with the report and partial diff docs. +async function openEnd(t, end) { + const s = await openSession(await suite.browser(), { + t, + workflow: "implement", + open: ["--loop"], + env: { PLAN2CODE_IN_APP: "1" }, + payload: { title: "demo", agent: { status: "working" } }, + project: tempProject(PROJECT), + }); + const answer = await frameInFakeApp(s); + fs.writeFileSync(path.join(s.session, "partial.diff"), DIFF); + s.post({ docs: [REPORT_DOC, PARTIAL_DOC], loopEnd: end, agent: { status: "waiting" } }); + await s.page.locator(".review-end").waitFor(); + return { ...s, answer }; +} + +const told = (s, kind) => s.page.evaluate((k) => window.__told.filter((m) => m.plan2code === k), kind); +const buttons = (s) => s.page.locator(".review-end button").evaluateAll((all) => all.map((b) => b.id).filter(Boolean)); + +test("the end screen heads each reason in words, with the line under it and the report behind a button", async (t) => { + const s = await openEnd(t, END); + const headings = { clean: "Clean", cap: "Stopped at the round cap", person: "Stopped by you", failed: "Failed" }; + for (const [reason, words] of Object.entries(headings)) { + s.post({ loopEnd: { ...END, reason, line: `Line for ${reason}` } }); + await s.page.getByText(`Line for ${reason}`).waitFor(); + assert.equal(await textOf(s.page.locator(".review-end-heading")), words); + } + await s.page.getByRole("button", { name: "Read the full report" }).click(); + await s.page.getByText("Two rounds ran.").waitFor(); +}); + +test("Continue shows only when allowed, says Run one more round at the cap, and is held while the app answers", async (t) => { + const s = await openEnd(t, END); + assert.equal(await s.page.locator("#review-end-continue").count(), 0, "nothing to continue after a clean run"); + + s.post({ loopEnd: { ...END, reason: "person", line: "You stopped it", canContinue: true } }); + const go = s.page.locator("#review-end-continue"); + await go.waitFor(); + assert.equal(await textOf(go), "Continue"); + + s.post({ loopEnd: { ...END, reason: "cap", line: "The cap was reached", canContinue: true } }); + await s.page.getByRole("button", { name: "Run one more round" }).waitFor(); + + await s.page.locator("#review-end-continue").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-continue")); + assert.equal(await s.page.locator("#review-end-continue").isDisabled(), true, "held while the app answers"); + await s.answer({ plan2code: "review-loop-continue-result", ok: false, error: "A loop is already running." }); + await s.page.getByText("A loop is already running.").waitFor(); + assert.equal(await s.page.locator("#review-end-continue").isDisabled(), false, "an error gives the button back"); +}); + +test("after Stop now the partial diff, its stats, Keep and Discard show and Continue is hidden", async (t) => { + const s = await openEnd(t, { + ...END, + reason: "person", + line: "You stopped it", + canContinue: true, + partial: { files: 1, added: 2, removed: 1, diff: "partial" }, + }); + await s.page.locator(".review-end-diff .diff-view").waitFor(); + assert.match(await textOf(s.page.locator(".review-end-stats")), /1 file changed, \+2 -1/); + assert.match(await textOf(s.page.locator(".review-end-diff")), /app\.js/); + assert.equal(await s.page.locator("#review-end-continue").count(), 0, "Continue waits for Keep or Discard"); + assert.equal(await s.page.locator("#review-end-signoff").isDisabled(), true, "Sign off waits for Keep or Discard too"); + assert.match(await textOf(s.page.locator(".review-end")), /Keep or discard the partial changes first/); + + await s.page.locator("#review-end-keep").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-partial")); + assert.deepEqual(await told(s, "review-loop-partial"), [{ plan2code: "review-loop-partial", keep: true }]); + await s.answer({ plan2code: "review-loop-partial-result", ok: false, error: "Nothing to keep." }); + await s.page.getByText("Nothing to keep.").waitFor(); + await s.page.locator("#review-end-discard").click(); + await s.page.waitForFunction(() => window.__told.filter((m) => m.plan2code === "review-loop-partial").length === 2); + assert.equal((await told(s, "review-loop-partial"))[1].keep, false); + + // The app answers with a new end without the partial: Continue comes back. + s.post({ loopEnd: { ...END, reason: "person", line: "You stopped it", canContinue: true } }); + await s.page.locator("#review-end-continue").waitFor(); + assert.equal(await s.page.locator("#review-end-keep").count(), 0); +}); + +test("a second ending with the same words after Continue starts with live buttons", async (t) => { + const again = { ...END, reason: "cap", line: "Stopped at the cap", canContinue: true }; + const s = await openEnd(t, again); + await s.page.locator("#review-end-continue").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-continue")); + assert.equal(await s.page.locator("#review-end-continue").isDisabled(), true, "the press waits on the app"); + // The app starts another round (a blank session, no end card), then it ends the same way again. + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + window.__keptEnd = page.S.loopEnd; + delete page.S.loopEnd; + redraw(); + }); + await s.page.locator("#review-end-continue").waitFor({ state: "detached" }); + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + page.S.loopEnd = window.__keptEnd; + redraw(); + }); + await s.page.locator("#review-end-continue").waitFor(); + assert.equal(await s.page.locator("#review-end-continue").isEnabled(), true, "Continue is live again"); + assert.equal(await s.page.locator("#review-end-signoff").isEnabled(), true, "Sign off is live again"); +}); + +test("the Suggestions pick starts unticked, shows only with suggestions, and what is ticked is what Sign off sends", async (t) => { + const s = await openEnd(t, END); + assert.equal(await s.page.locator(".review-end-suggestions").count(), 0, "no pick without suggestions"); + assert.equal(await s.page.locator("#review-end-signoff").isEnabled(), true, "Sign off is always there"); + + s.post({ loopEnd: { ...END, line: "With suggestions", suggestions: SUGGESTIONS } }); + await s.page.locator(".review-end-suggestions").waitFor(); + assert.deepEqual( + await s.page.locator(".review-end-pick input").evaluateAll((all) => all.map((i) => [i.id, i.checked])), + [["review-end-pick-s1", false], ["review-end-pick-s2", false]] + ); + assert.match(await textOf(s.page.locator(".review-end-pick").first()), /Rename the helper\s*src\/a\.js:12/); + await s.page.locator("#review-end-pick-s2").check(); + // A redraw keeps the tick. + await s.page.evaluate(async () => (await import(new URL("state.js", document.baseURI).href)).redraw()); + assert.equal(await s.page.locator("#review-end-pick-s2").isChecked(), true); + + await s.page.locator("#review-end-signoff").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-sign-off")); + assert.deepEqual(await told(s, "review-loop-sign-off"), [{ plan2code: "review-loop-sign-off", picks: ["s2"], squash: false }]); + assert.equal(await s.page.locator("#review-end-signoff").isDisabled(), true); + await s.answer({ plan2code: "review-loop-sign-off-result", ok: false, error: "Something went wrong." }); + await s.page.getByText("Something went wrong.").waitFor(); +}); + +test("what was ticked survives Keep or Discard reposting the end without the partial changes", async (t) => { + const withPartial = { ...END, reason: "person", line: "You stopped it", canSquash: true, suggestions: SUGGESTIONS, partial: { files: 1, added: 2, removed: 1, diff: "partial" } }; + const s = await openEnd(t, withPartial); + await s.page.locator("#review-end-pick-s2").check(); + await s.page.locator("#review-end-squash").check(); + const { partial, ...settled } = withPartial; + s.post({ loopEnd: { ...settled, canContinue: true } }); + await s.page.locator("#review-end-continue").waitFor(); + assert.equal(await s.page.locator("#review-end-pick-s2").isChecked(), true, "the pick is kept"); + assert.equal(await s.page.locator("#review-end-squash").isChecked(), true, "the squash switch is kept"); + assert.equal(await s.page.locator("#review-end-signoff").isEnabled(), true, "Sign off is back"); +}); + +test("the squash switch shows only when canSquash, starts off, and is sent with Sign off", async (t) => { + const s = await openEnd(t, END); + assert.equal(await s.page.locator("#review-end-squash").count(), 0); + + s.post({ loopEnd: { ...END, line: "Can squash", canSquash: true } }); + const sw = s.page.locator("#review-end-squash"); + await sw.waitFor(); + assert.equal(await sw.isChecked(), false); + assert.match(await textOf(s.page.locator("label", { has: sw })), /Squash the round commits into one/); + await sw.check(); + await s.page.locator("#review-end-signoff").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-sign-off")); + assert.deepEqual(await told(s, "review-loop-sign-off"), [{ plan2code: "review-loop-sign-off", picks: [], squash: true }]); +}); + +test("the finished screen offers PR Prep, Fix what's left by hand when something is open, and the dashboard", async (t) => { + const done = { ...END, line: "Signed off", signedOff: true, note: "Squashed 3 round commits into one." }; + const s = await openEnd(t, { ...done, open: [{ title: "Unchecked input", file: "src/b.js", line: 9 }] }); + assert.deepEqual(await buttons(s), ["review-end-pr-prep", "review-end-quick-task", "review-end-dashboard"]); + assert.equal(await textOf(s.page.locator(".review-end-heading")), "Signed off"); + assert.match(await textOf(s.page.locator(".review-end-note")), /Squashed 3 round commits into one\./); + assert.equal(await s.page.locator("#review-end-signoff").count(), 0, "no sign-off after sign-off"); + + await s.page.locator("#review-end-quick-task").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-next")); + assert.deepEqual(await told(s, "review-loop-next"), [{ plan2code: "review-loop-next", next: "quick-task" }]); + assert.equal(await s.page.locator("#review-end-pr-prep").isDisabled(), true, "all held while the app answers"); + await s.answer({ plan2code: "review-loop-next-result", ok: false, error: "Could not start it." }); + await s.page.getByText("Could not start it.").waitFor(); + await s.page.locator("#review-end-pr-prep").click(); + await s.page.waitForFunction(() => window.__told.filter((m) => m.plan2code === "review-loop-next").length === 2); + assert.equal((await told(s, "review-loop-next"))[1].next, "pr-prep"); + await s.answer({ plan2code: "review-loop-next-result", ok: false, error: "Nope." }); + await s.page.locator("#review-end-dashboard").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "loop-dashboard")); +}); + +test("Fix what's left by hand is hidden when nothing is open", async (t) => { + const s = await openEnd(t, { ...END, signedOff: true, line: "Signed off" }); + assert.deepEqual(await buttons(s), ["review-end-pr-prep", "review-end-dashboard"]); + s.post({ loopEnd: { ...END, signedOff: true, line: "Signed off", open: [] } }); + await s.page.locator("#review-end-pr-prep").waitFor(); + assert.equal(await s.page.locator("#review-end-quick-task").count(), 0); +}); diff --git a/scripts/test-web-console-review-loop.mjs b/scripts/test-web-console-review-loop.mjs new file mode 100644 index 0000000..4184e1e --- /dev/null +++ b/scripts/test-web-console-review-loop.mjs @@ -0,0 +1,199 @@ +// Web console tests: the Review Loop's setup store and its route. Run with: +// node --test scripts/test-web-console-review-loop.mjs +// +// The store (review-loop-setup.mjs) keeps one entry per project in +// review-loop-setup.json; GET and POST /review-loop-setup serve it. The +// store fixes its file at import time from PLAN2CODE_CONSOLE_HOME, so it runs +// in a child process here, as test-web-console-loop.mjs does for loop-setup.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; +import { ROOT, ENV, HOME, cli, sessionUrl } from "./web-console-test-helpers.mjs"; + +const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID", "PLAN2CODE_LOOP_STRENGTH"]; +const SETUP_PATH = path.join(HOME, "review-loop-setup.json"); +const LOOP_SETUP_PATH = path.join(HOME, "loop-setup.json"); +const STORE_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "review-loop-setup.mjs")).href; + +function cleanEnv() { + const env = { ...ENV }; + for (const key of APP_VARS) delete env[key]; + return env; +} + +// Runs `fn(m, args)` in a child process where m is review-loop-setup.mjs. `fn` +// must be self-contained: it is sent as source text. Returns its JSON result. +function inStore(fn, args = {}) { + const code = + `const m = await import(${JSON.stringify(STORE_URL)});` + + `const out = await (${fn.toString()})(m, ${JSON.stringify(args)});` + + "console.log(JSON.stringify(out));"; + const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env: cleanEnv(), encoding: "utf8", cwd: ROOT }); + assert.equal(res.status, 0, res.stderr); + return JSON.parse(String(res.stdout).trim().split("\n").pop()); +} + +const projectA = path.join(HOME, "review-store-a"); +const projectB = path.join(HOME, "review-store-b"); + +test("review-loop-setup: a new project reads as the defaults with remembered false, and nothing is written", () => { + fs.rmSync(SETUP_PATH, { force: true }); + const got = inStore((m, { project }) => ({ setup: m.readReviewLoopSetup(project), defaults: m.REVIEW_LOOP_DEFAULTS }), { project: projectA }); + assert.deepEqual(got.setup, { ...got.defaults, remembered: false }); + assert.deepEqual(got.defaults, { scope: "branch", spec: "", cap: 3, commit: true, suggestions: false, strength: "", silenceMinutes: 20, notifyRounds: false }); + assert.equal(fs.existsSync(SETUP_PATH), false, "reading never creates the file"); +}); + +test("review-loop-setup: a save reads back per project and keeps another project's entry", () => { + fs.rmSync(SETUP_PATH, { force: true }); + inStore( + (m, { a, b }) => { + m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS, cap: 5, suggestions: true, scope: "spec", spec: "specs/demo", strength: "best" }); + m.saveReviewLoopSetup(b, { ...m.REVIEW_LOOP_DEFAULTS, cap: 2, notifyRounds: true }); + return null; + }, + { a: projectA, b: projectB } + ); + const got = inStore((m, { a, b }) => ({ a: m.readReviewLoopSetup(a), b: m.readReviewLoopSetup(b) }), { a: projectA, b: projectB }); + assert.equal(got.a.cap, 5); + assert.equal(got.a.suggestions, true); + assert.equal(got.a.scope, "spec"); + assert.equal(got.a.spec, "specs/demo"); + assert.equal(got.a.strength, "best"); + assert.equal(got.a.remembered, true); + assert.equal(got.b.cap, 2); + assert.equal(got.b.notifyRounds, true); + const file = JSON.parse(fs.readFileSync(SETUP_PATH, "utf8")); + assert.equal(file.schema, 1); + assert.equal(Object.keys(file.projects).length, 2); + for (const entry of Object.values(file.projects)) assert.match(entry.saved, /^\d{4}-\d\d-\d\dT/); +}); + +test("review-loop-setup: unknown keys and out-of-range values are refused with the problem named", () => { + fs.rmSync(SETUP_PATH, { force: true }); + const problems = (patch) => inStore((m, { patch }) => m.reviewLoopSetupProblems({ ...m.REVIEW_LOOP_DEFAULTS, ...patch }), { patch }); + assert.deepEqual(problems({}), []); + assert.match(problems({ notifyUrl: "https://x.example/" }).join(), /"notifyUrl" is not a setup field/, "the notify address is the loop setup's, never kept here"); + assert.match(problems({ cap: 0 }).join(), /"cap" must be a whole number from 1 to 6/); + assert.match(problems({ cap: 7 }).join(), /"cap"/); + assert.match(problems({ cap: 2.5 }).join(), /"cap"/); + assert.deepEqual(problems({ cap: 1 }), []); + assert.deepEqual(problems({ cap: 6 }), []); + assert.match(problems({ silenceMinutes: 0 }).join(), /"silenceMinutes" must be a whole number from 1 to 60/); + assert.match(problems({ silenceMinutes: 61 }).join(), /"silenceMinutes"/); + assert.match(problems({ scope: "everything" }).join(), /"scope" must be one of branch, uncommitted, spec/); + for (const spec of ["demo", "specs/", "specs/a/b", "specs/.hidden", "../x", 3]) { + assert.match(problems({ spec }).join(), /"spec" must be empty or a folder directly under specs\//, `spec ${spec}`); + } + assert.deepEqual(problems({ spec: "specs/demo" }), []); + assert.match(problems({ commit: "yes" }).join(), /"commit" must be true or false/); + assert.match(problems({ strength: "mighty" }).join(), /"strength"/); + assert.match(inStore((m) => m.reviewLoopSetupProblems(null), {}).join(), /must be an object/); + + const before = inStore((m, { a }) => (m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS }), null), { a: projectA }); + assert.equal(before, null); + const text = fs.readFileSync(SETUP_PATH, "utf8"); + const threw = inStore( + (m, { a }) => { + try { + m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS, cap: 99 }); + return "saved"; + } catch (e) { + return { message: e.message, problems: e.problems }; + } + }, + { a: projectA } + ); + assert.match(threw.message, /the review loop setup is not valid/); + assert.equal(threw.problems.length, 1); + assert.equal(fs.readFileSync(SETUP_PATH, "utf8"), text, "a refused save leaves the file as it was"); +}); + +test("review-loop-setup: the picks live only in review-loop-setup.json, never in the project or the loop's setup", () => { + fs.rmSync(SETUP_PATH, { force: true }); + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const project = fs.mkdtempSync(path.join(HOME, "review-nowrite-")); + inStore((m, { project }) => (m.saveReviewLoopSetup(project, { ...m.REVIEW_LOOP_DEFAULTS, cap: 4 }), null), { project }); + assert.ok(fs.existsSync(SETUP_PATH)); + assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "the Implementation Loop's file is untouched"); + assert.deepEqual(fs.readdirSync(project), [], "nothing appears in the project"); +}); + +test("review-loop-setup: Cleanup never offers the file", () => { + const code = `const m = await import(${JSON.stringify(pathToFileURL(path.join(ROOT, "src", "web-console", "sessions.mjs")).href)}); console.log(JSON.stringify([...m.PROTECTED_CONSOLE_FILES]));`; + const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env: cleanEnv(), encoding: "utf8", cwd: ROOT }); + assert.equal(res.status, 0, res.stderr); + assert.ok(JSON.parse(String(res.stdout).trim().split("\n").pop()).includes("review-loop-setup.json")); +}); + +test("review-loop-setup: GET and POST /review-loop-setup, with ?spec= filling the answer without saving", async () => { + fs.rmSync(SETUP_PATH, { force: true }); + const cwd = fs.mkdtempSync(path.join(HOME, "review-route-")); + const opened = cli(["open", "--workflow", "review", "--no-open"], { cwd }); + const parsed = JSON.parse(String(opened.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop()); + const { base, cookie } = sessionUrl(parsed.url); + const get = async (query = "") => { + const res = await fetch(`${base}/review-loop-setup${query}`, { headers: { cookie, connection: "close" } }); + return { status: res.status, body: await res.json() }; + }; + const send = (body, { origin = base } = {}) => + fetch(`${base}/review-loop-setup`, { + method: "POST", + headers: { "content-type": "application/json", cookie, ...(origin ? { origin } : {}), connection: "close" }, + body: typeof body === "string" ? body : JSON.stringify(body), + }); + try { + const bare = await get(); + assert.equal(bare.status, 200); + assert.equal(bare.body.remembered, false); + assert.equal(bare.body.scope, "branch"); + assert.equal(bare.body.cap, 3); + + const filled = await get("?spec=specs/demo"); + assert.equal(filled.body.spec, "specs/demo"); + assert.equal(filled.body.scope, "spec"); + assert.equal(filled.body.remembered, false); + assert.equal(fs.existsSync(SETUP_PATH), false, "a pre-fill is never saved"); + assert.equal((await get()).body.scope, "branch", "and the next plain read is the defaults again"); + + for (const spec of ["../x", "specs/../x", "specs/a/b", "specs/.hidden", "specs", "specs/"]) { + const refused = await get(`?spec=${spec}`); + assert.equal(refused.status, 400, `spec=${spec} is refused`); + assert.match(refused.body.error, /spec must be a folder directly under specs\//); + } + + const facts = await get("?facts=1"); + assert.equal(typeof facts.body.branch, "string"); + assert.ok("pending" in facts.body); + + const good = { scope: "uncommitted", spec: "", cap: 4, commit: false, suggestions: true, strength: "balanced", silenceMinutes: 15, notifyRounds: true }; + const saved = await send(good); + assert.equal(saved.status, 200, await saved.clone().text()); + const back = await get(); + assert.equal(back.body.remembered, true); + for (const [key, value] of Object.entries(good)) assert.equal(back.body[key], value, key); + + const bad = await send({ ...good, cap: 9, extra: 1 }); + assert.equal(bad.status, 400); + const badBody = await bad.json(); + assert.equal(badBody.ok, false); + assert.ok(badBody.problems.some((p) => /"cap"/.test(p))); + assert.ok(badBody.problems.some((p) => /"extra" is not a setup field/.test(p))); + assert.equal((await get()).body.cap, 4, "a refused save changes nothing"); + assert.equal((await send("[1]")).status, 400); + + // The POST is origin-checked: another page's origin is refused, and nothing is saved by it. + const before = JSON.stringify((await get()).body); + const foreign = await send({ ...good, cap: 2 }, { origin: "http://evil.example" }); + assert.equal(foreign.status, 403, "a foreign origin is refused"); + assert.equal(JSON.stringify((await get()).body), before); + } finally { + cli(["stop", "--session", parsed.sid, "--force"], { cwd, expectFail: true }); + } + assert.deepEqual(fs.readdirSync(cwd), [], "the route never wrote into the project"); + assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "and never touched the Implementation Loop's file"); +}); diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index f2ab885..1706f6a 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -365,6 +365,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe file("looks.json"), file("workspaces.json"), file("loop-setup.json"), + file("review-loop-setup.json"), file("spec-carry.json"), file("loop-reports.json"), file("subagents.json"), @@ -382,7 +383,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort(); assert.deepEqual(stale, ["helper.mjs", "p2.json"]); assert.deepEqual( - (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), + (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "review-loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), ["helper.mjs", "p2.json"] ); for (const p of removable) assert.equal(fs.existsSync(p), false, p); @@ -393,6 +394,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe "loop-reports.json", "loop-setup.json", "pr-hosts.json", + "review-loop-setup.json", "spec-carry.json", "subagents.json", "update-check.json", diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index 4bc3b7a..fb7d7cd 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -193,7 +193,7 @@ const ROUTE_ORDER = [ "/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab", "/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/", "/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/open-prototype", "/chat", "/chat/decision", "/workspace", - "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/spec-carry", "/cancel", "/ping", "/bye", + "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/review-loop-setup", "/review-loop-setup", "/spec-carry", "/cancel", "/ping", "/bye", ]; test("shape: routes.mjs lists every URL the server answers, in order", () => { diff --git a/scripts/test-web-console-skills.mjs b/scripts/test-web-console-skills.mjs index 7063518..c11b04d 100644 --- a/scripts/test-web-console-skills.mjs +++ b/scripts/test-web-console-skills.mjs @@ -19,7 +19,7 @@ import { isWorkflow, isAgentless, } from "../src/web-console/public/skills.js"; -import { CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js"; +import { APP_ONLY_ENTRIES, REVIEW_LOOP_ENTRY, cardAvailability, CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js"; import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js"; import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js"; import { helpTabFor } from "../src/web-console/public/help.js"; @@ -428,19 +428,34 @@ test("helper-strength.md ships in the eighteen skills that start helpers (the da ]); }); -// The Implementation Loop is a card the desktop app offers, not a skill: it -// has no workflow, so no list built from the workflows may hold it. -test("the app-only Implementation Loop entry stays out of every workflow list", () => { - const loop = EVERY_ENTRY.find((s) => s.appOnly); - assert.ok(loop, "skills.js has an appOnly entry"); - assert.equal(loop.skill, "plan2code-loop"); - assert.equal(loop.workflow, null); - assert.deepEqual(EVERY_ENTRY.filter((s) => s.appOnly).length, 1); - assert.ok(!SKILLS.includes(loop), "FLOW_SKILLS leaves it out"); - assert.ok(!WORKFLOWS.includes(null) && !isWorkflow("plan2code-loop") && !isWorkflow(null)); - assert.equal(skillByName("plan2code-loop"), null); - assert.ok(!CONSOLE_WORKFLOWS.includes(loop.command), "no console page is offered for it"); - assert.ok(!SKILL_CATALOG.some((e) => e.skill === loop.skill), "the dashboard does not draw it yet"); +// The Implementation Loop and the Review Loop are cards the desktop app offers, +// not skills: neither has a workflow, so no list built from the workflows may hold them. +test("the app-only Implementation Loop and Review Loop entries stay out of every workflow list", () => { + const apps = EVERY_ENTRY.filter((s) => s.appOnly); + assert.deepEqual(apps.map((s) => s.skill), ["plan2code-loop", "plan2code-review-loop"], "both, the Implementation Loop first"); + for (const entry of apps) { + assert.equal(entry.workflow, null); + assert.ok(!SKILLS.includes(entry), "FLOW_SKILLS leaves it out"); + assert.ok(!isWorkflow(entry.skill)); + assert.equal(skillByName(entry.skill), null); + assert.ok(!CONSOLE_WORKFLOWS.includes(entry.command), "no console page is offered for it"); + assert.ok(!SKILL_CATALOG.some((e) => e.skill === entry.skill), "the dashboard draws it apart from the catalog"); + assert.equal(entry.subagents, null); + assert.equal(entry.card.group, "pipeline", "beside the Implementation Loop"); + } + assert.ok(!WORKFLOWS.includes(null) && !isWorkflow(null)); assert.ok(!("null" in WORKFLOW_LABEL)); - assert.deepEqual([...loop.states], ["documented", "building"]); + assert.deepEqual([...apps[0].states], ["documented", "building"]); + assert.equal(apps[1].states, "any", "a Review Loop needs no spec"); + assert.equal(apps[1].card.title, "Review Loop"); + assert.equal(apps[1].card.blurb, "Review and fix in rounds on its own, each round checked by a fresh reviewer."); +}); + +test("the Review card carries the app-only pointer line, and the app-only cards are the dashboard's extras", () => { + const review = SKILL_CATALOG.find((e) => e.skill === "plan2code-review"); + assert.equal(review.appNote, "In the app, the Review Loop runs review and fix rounds on its own."); + assert.deepEqual(SKILL_CATALOG.filter((e) => e.appNote).map((e) => e.skill), ["plan2code-review"], "no other card has one"); + assert.deepEqual(APP_ONLY_ENTRIES.map((e) => e.skill), ["plan2code-loop", "plan2code-review-loop"]); + assert.equal(REVIEW_LOOP_ENTRY.command, "Desktop app only"); + assert.equal(cardAvailability(REVIEW_LOOP_ENTRY, { hasAgents: true }, null).on, true, "lit for any project state"); }); diff --git a/scripts/test-web-console-state.mjs b/scripts/test-web-console-state.mjs index 9ffc76d..16e9e22 100644 --- a/scripts/test-web-console-state.mjs +++ b/scripts/test-web-console-state.mjs @@ -52,6 +52,10 @@ test("state: the rest of the shared state starts as app.js always started it", ( terminalCollapsed: false, loop: null, loopSetup: null, + reviewLoopSetup: null, + reviewFacts: null, + reviewStart: null, + reviewAction: null, loopFacts: null, loopNotifyTest: null, loopStart: null, diff --git a/src/launcher/agents.json b/src/launcher/agents.json index 760947d..8aa5c0e 100644 --- a/src/launcher/agents.json +++ b/src/launcher/agents.json @@ -6,6 +6,7 @@ "name": "Claude Code", "kind": "builtin", "command": "claude", + "helpers": true, "prompt": "/plan2code", "args": ["{prompt}", "{bypass}", "{model}"], "bypassArgs": ["--permission-mode", "bypassPermissions"], @@ -37,6 +38,7 @@ "name": "Devin", "kind": "builtin", "command": "devin", + "helpers": false, "prompt": "/plan2code", "args": ["{bypass}", "{model}", "--", "{prompt}"], "bypassArgs": ["--permission-mode", "bypass"], @@ -64,6 +66,7 @@ "name": "Codex", "kind": "builtin", "command": "codex", + "helpers": false, "prompt": "$plan2code", "args": ["{bypass}", "{model}", "{prompt}"], "bypassArgs": ["--dangerously-bypass-approvals-and-sandbox"], @@ -94,6 +97,7 @@ "name": "GitHub Copilot CLI", "kind": "template", "command": "copilot", + "helpers": false, "prompt": "Use the /plan2code skill", "args": ["-i", "{prompt}"], "bypassArgs": ["--allow-all-tools"], @@ -104,6 +108,7 @@ "name": "OpenCode", "kind": "template", "command": "opencode", + "helpers": false, "prompt": "@plan2code", "args": ["{model}", "--prompt", "{prompt}"], "bypassArgs": ["--auto"], @@ -114,6 +119,7 @@ "name": "Gemini CLI", "kind": "template", "command": "gemini", + "helpers": false, "prompt": "Use the plan2code skill", "args": ["{model}", "{prompt}"], "bypassArgs": ["--approval-mode=yolo"], @@ -125,6 +131,7 @@ "name": "Pi", "kind": "template", "command": "pi", + "helpers": false, "prompt": "/skill:plan2code", "args": ["{model}", "{prompt}"], "modelArgs": ["--model", "{model}"] @@ -134,6 +141,7 @@ "name": "Cursor CLI", "kind": "template", "command": "agent", + "helpers": false, "prompt": "/plan2code", "args": ["{model}", "{prompt}"], "bypassArgs": ["--force"], diff --git a/src/plan2code-review.md b/src/plan2code-review.md index 11b8032..f597458 100644 --- a/src/plan2code-review.md +++ b/src/plan2code-review.md @@ -8,7 +8,7 @@ Critical review specialist -- experienced senior engineer providing independent ## Interface -The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow review` before reading (: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read /console.md and /notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running. +The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow review` before reading (: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read /console.md and /notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. `--loop` (only inside the desktop app, a Review Loop round): open with `open --loop --workflow review --round --role --scope-file ` from the arguments, read `/notes/review-loop.md` after `console.md`, and follow it; it replaces the scope question, the fix menu, the sign-off, Lessons End and every git step below. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running. ## Scripts diff --git a/src/shared-references/lessons.md b/src/shared-references/lessons.md index 3ffba69..b88e987 100644 --- a/src/shared-references/lessons.md +++ b/src/shared-references/lessons.md @@ -61,7 +61,7 @@ The seven noting skills (and any skill sent here by Start's Review now) run it b **The check** (before step 1, unless the state is `not-set-up`). Skip it when `references/lesson-check.md` is not beside this file (a read-only skill sent here by Review now ships no checker brief): run plain `list`, and the rows show Not checked yet. Otherwise run `node "/lessons.mjs" check-input`. `lessons` empty: skip the check and run step 1 as written. Otherwise: -- **Start the checker** with `references/lesson-check.md` and the JSON. With helpers on and available, it is a fresh helper given reading tools only, never relying on a permission mode (Claude Code: a custom helper already installed whose tool list holds only reading tools, such as `tools: Read, Grep, Glob`, never the built-in `Explore` or a general-purpose one, since both keep the shell; Devin: `run_subagent` with the read-only explore profile; Codex: a fresh helper told it may only read), `how: "helper"`, at `helper-strength.md`'s lesson check row (standard strength, medium effort). With Subagents off for the skill, no helper support, or (Claude Code) no reading-only helper installed, you grade in a separate step after re-reading the brief, `how: "same-agent"`; the card says so. +- **Start the checker** with `references/lesson-check.md` and the JSON. With helpers on and available, it is a fresh helper given reading tools only, never relying on a permission mode (Claude Code: a custom helper already installed whose tool list holds only reading tools, such as one whose `tools:` line lists only the read, search and list-files tools, never the built-in `Explore` or a general-purpose one, since both keep the shell; Devin: `run_subagent` with the read-only explore profile; Codex: a fresh helper told it may only read), `how: "helper"`, at `helper-strength.md`'s lesson check row (standard strength, medium effort). With Subagents off for the skill, no helper support, or (Claude Code) no reading-only helper installed, you grade in a separate step after re-reading the brief, `how: "same-agent"`; the card says so. - Write its reply to a file in the console session folder, or the OS temp folder in a terminal, never in the project. Run `check-record --file `. Exit 4: give the checker its `problems` once and record again; still failing, step 1 runs `list --check-failed ""` and every lesson still shows. - Step 1 then runs `list --check `. On the web console, post an `activity` line while it runs ("Checking 4 lessons"). diff --git a/src/web-console/agent-lookup.mjs b/src/web-console/agent-lookup.mjs index 4afd3fc..143fab0 100644 --- a/src/web-console/agent-lookup.mjs +++ b/src/web-console/agent-lookup.mjs @@ -58,8 +58,11 @@ export function loadAgentList({ dir = MODULE_DIR, optional = false } = {}) { warnings.push(`agents[${index}] skipped: not an object`); return; } - if (entry.kind === "builtin") builtins.push(entry); - else if (entry.kind === "template") templates.push(entry); + // helpers: the agent can start a subagent from inside a session; a missing + // key reads false. + const carried = { ...entry, helpers: entry.helpers === true }; + if (entry.kind === "builtin") builtins.push(carried); + else if (entry.kind === "template") templates.push(carried); else warnings.push(`agents[${index}] skipped: unknown kind ${JSON.stringify(entry.kind)}`); }); return { builtins, templates, warnings }; diff --git a/src/web-console/cmd-open.mjs b/src/web-console/cmd-open.mjs index 8fbdf3b..f0ed227 100644 --- a/src/web-console/cmd-open.mjs +++ b/src/web-console/cmd-open.mjs @@ -42,6 +42,7 @@ import { resolveDocFiles, resolveDocImages, validate, + ROUND_ROLES, } from "./patches.mjs"; import { initialWorkspace, @@ -111,14 +112,40 @@ function leavePointer() { const EMBED_API = 1; // The only workflows a loop drives (open --loop). -const LOOP_WORKFLOWS = ["implement", "implement-review"]; +const LOOP_WORKFLOWS = ["implement", "implement-review", "review"]; // What the loop locks a session with: `driving`, and, when the app started this // phase on a strength, its word (PLAN2CODE_LOOP_STRENGTH), which the server's // Subagents sync reads so the phase's helpers follow it. -function loopLock() { +function loopLock(round) { const strength = process.env.PLAN2CODE_LOOP_STRENGTH; - return STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true }; + const lock = STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true }; + return round ? { ...lock, ...round } : lock; +} + +// A Review Loop round (open --loop --workflow review) carries its round, role +// and scope file; every other open refuses them. Returns the stamp, or null. +function roundFlags(loopMode) { + const given = ["round", "role", "scope-file"].filter((f) => args[f] !== undefined); + const isRound = loopMode && args.workflow === "review"; + if (!isRound) { + if (given.length) die(`--${given[0]} goes only with --loop --workflow review`, 2); + return null; + } + const n = Number(args.round); + if (args.round === undefined || args.round === true || !Number.isInteger(n) || n < 1 || !/^\d+$/.test(String(args.round))) { + die("--round must be a positive integer for a Review Loop round", 2); + } + if (typeof args.role !== "string" || !ROUND_ROLES.includes(args.role)) { + die(`--role must be one of ${ROUND_ROLES.join(", ")} for a Review Loop round`, 2); + } + const scopeFile = args["scope-file"]; + let isFile = false; + try { + isFile = typeof scopeFile === "string" && scopeFile !== "" && fs.statSync(scopeFile).isFile(); + } catch {} + if (!isFile) die("--scope-file must name an existing file for a Review Loop round", 2); + return { round: n, role: args.role, scopeFile: path.resolve(scopeFile) }; } export async function cmdOpen() { @@ -140,6 +167,7 @@ export async function cmdOpen() { die(`--loop goes only with --workflow ${LOOP_WORKFLOWS.join(" or --workflow ")}`, 2); } } + const round = roundFlags(loopMode); leavePointer(); // Under the desktop app the page belongs in the app's window: never the // browser, and (unless a session was named) the app's own session, so one @@ -252,9 +280,10 @@ export async function cmdOpen() { } else if (switching) { s.workflow = args.workflow; // An inline switch (into Review) is not a loop phase. - if (!LOOP_WORKFLOWS.includes(args.workflow)) { + if (!LOOP_WORKFLOWS.includes(args.workflow) || args.workflow === "review") { delete s.loopOutcome; delete s.loopEnd; + delete s.roundOutcome; } } if (args.title) s.title = args.title; @@ -270,9 +299,17 @@ export async function cmdOpen() { // without it (Fix together with an agent, from a stop screen) is an ordinary, // unlocked session. `loopExpect` goes with the lock: the app restamps it // on its next look, so a stale setup never judges a new run. - if (loopMode) s.loop = loopLock(); - else { + if (loopMode) { + // A different round or role never inherits the last one's report: its + // outcome and its `report` doc go, so the report proof is that run's own. + if (round && (s.loop?.round !== round.round || s.loop?.role !== round.role)) { + delete s.roundOutcome; + s.docs = (s.docs || []).filter((d) => d && d.id !== "report"); + } + s.loop = loopLock(round); + } else { delete s.loop; + delete s.roundOutcome; delete s.loopExpect; // The loop's cards mean nothing without it, and validate() refuses // handledBy outside a loop session, which would wedge every post. @@ -302,7 +339,7 @@ export async function cmdOpen() { // Only a freshly opened dashboard plays Planny's wake-up. if (args.workflow === "dashboard") state.wake = true; // Locked from the first frame, before the state is first written. - if (loopMode) state.loop = loopLock(); + if (loopMode) state.loop = loopLock(round); // The setup session's hand-over data (forCli + the token /handover // checks), created with the state so the first write already has it. if (args.workflow === "setup") { @@ -583,6 +620,9 @@ export async function cmdOpen() { ...owed, ...(remote.remote ? { remote: remote.remote } : {}), ...(notes.length ? { note: notes.join(" ") } : {}), + // A Review Loop round reads its own notes once, the way a phase agent is + // pointed at notes/loop.md by its skill: the console names the file. + ...(round ? { read: [path.join(HERE, "notes", "review-loop.md")] } : {}), }); advanceSubagents(dir, subCursor); // After the print, never before it: the page and the link wait for nothing. diff --git a/src/web-console/console.mjs b/src/web-console/console.mjs index b523b45..b96b722 100644 --- a/src/web-console/console.mjs +++ b/src/web-console/console.mjs @@ -115,7 +115,7 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) { // A flag given with no value parses as `true`, and a boolean handed on as a // path or a name crashes somewhere deep (path.basename(true) throws). Every // flag that takes a value is checked once, here, and refused as bad usage. -const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms", "for-cli"]; +const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms", "for-cli", "round", "role", "scope-file"]; for (const flag of VALUE_FLAGS) { if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2); } diff --git a/src/web-console/loop-setup.mjs b/src/web-console/loop-setup.mjs index 14f03e1..d0d75cc 100644 --- a/src/web-console/loop-setup.mjs +++ b/src/web-console/loop-setup.mjs @@ -29,6 +29,7 @@ const SPEC_KEY = /^specs\/[^/\\.][^/\\]*$/; export const LOOP_DEFAULTS = Object.freeze({ review: true, + reviewRounds: 2, fixMode: "smart", fix: Object.freeze([...LEVELS]), commit: true, @@ -68,6 +69,9 @@ export function loopSetupProblems(entry) { if (!Array.isArray(entry.fix) || !entry.fix.every((l) => LEVELS.includes(l)) || new Set(entry.fix).size !== entry.fix.length) { problems.push(`"fix" must list distinct levels from ${LEVELS.join(", ")}`); } + if (!Number.isInteger(entry.reviewRounds) || entry.reviewRounds < 0 || entry.reviewRounds > 6) { + problems.push('"reviewRounds" must be a whole number from 0 to 6'); + } if (!FIX_MODES.includes(entry.fixMode)) problems.push(`"fixMode" must be one of ${FIX_MODES.join(", ")}`); if (!ON_QUESTION.includes(entry.onQuestion)) problems.push(`"onQuestion" must be one of ${ON_QUESTION.join(", ")}`); if (!AFTER_LAST.includes(entry.afterLast)) problems.push(`"afterLast" must be one of ${AFTER_LAST.join(", ")}`); diff --git a/src/web-console/notes/review-loop.md b/src/web-console/notes/review-loop.md new file mode 100644 index 0000000..f5cade8 --- /dev/null +++ b/src/web-console/notes/review-loop.md @@ -0,0 +1,55 @@ +# Review Loop Round + +Read after `console.md`. Run by the desktop app's Review Loop (`--loop` on `review`), part of the `console.md` contract. This note replaces the scope card, the fix menu, the sign-off, Lessons End and every git step. + +## Who you are + +One round of a Review Loop. The app started you with `--round `, `--role ` and `--scope-file `, and opened the session with `open --loop --workflow review --round --role --scope-file `: run that open again if the server went away, with the same flags. Nobody is watching. Never run git in any form, never ask the person, never commit. A real question is a stop: report `failed`, reason `other`. + +## Scope + +Read the scope file first. For round 1 it names the scope the person picked. For a later round it is the previous round's diff. Review nothing outside it. A file the scope names but that is gone is a finding only if the change deleted it. + +## Role both + +1. Start one fresh read-only reviewer subagent with `reviewer-brief.md` filled in for the scope, whatever the Subagents switch says. It never sees this conversation. +2. Verify every finding it returns (`verification-protocol.md`), and drop what does not hold. +3. Post the verified findings as one doc with id `report`, grouped Critical, Warning, Suggestion. +4. Fix Critical and Warning only. List Suggestions without fixing them. +5. Run the targeted tests for the files you changed (`references/test-runs.md`), never the full suite. Changed nothing? Run the targeted tests for the files in scope: a passed round never sends `ran:false`. + +## Role reviewer + +Do the review only: steps 1 to 3 of Role both. Change no file. Post the `report` doc and report; leave `tests` out, and send `fixed` as an empty list. + +## Role fixer + +The scope file names the reviewer's report by file path. Read it, fix Critical and Warning, run the targeted tests for what you changed, and start no new review. Leave `report` out. Still send `review`: its counts and lists come from the reviewer's report, with `fixed` and `unfixed` showing what this round fixed and left. + +## Reporting + +Post in this order, each as its own patch with no `--wait`: + +1. The `report` doc (roles both and reviewer), before the outcome. +2. One top-level `roundOutcome`: + +```json +{ "roundOutcome": { + "round": 2, "role": "both", "result": "passed", "reason": null, + "summary": "Fixed 1 warning; 1 suggestion left", + "report": "report", + "review": { "critical": 0, "warning": 1, "suggestion": 1, + "fixed": [ { "title": "Close the file handle", "file": "src/z.js", "line": 12 } ], + "unfixed": [], + "suggestions": [ { "title": "Name the timer", "file": "src/x.js" } ] }, + "tests": { "ran": true, "passed": true, "summary": "14 pass" }, + "subject": "Close the file handle in z.js" } } +``` + +3. `{"agent":{"status":"waiting"}}`, then keep waiting in bounded `wait` slices until the app ends the session. Never end the turn on text. + +Every field is required except `report` for a fixer and `tests` for a reviewer. `round` and `role` must equal the flags. `critical`, `warning` and `suggestion` count what the review found before fixing; `fixed` and `unfixed` list the Critical and Warning findings by that outcome (at most 50 each, `file` relative to the project). `result` is `passed` when the round ran its steps and its tests; `failed` carries one reason: `tests`, `findings`, `blocked`, `conflict` or `other`. `summary` is one line under 200 characters, `subject` one line under 100. + +## Refusals + +An exit 3 on `roundOutcome` names the field: fix it and post again inside the same round. A `loopOutcome` is refused here: a round reports `roundOutcome` only. diff --git a/src/web-console/notes/review.md b/src/web-console/notes/review.md index d716c2b..1648208 100644 --- a/src/web-console/notes/review.md +++ b/src/web-console/notes/review.md @@ -9,3 +9,5 @@ Closing gate: `review` "Check the fixes", `"doc":"report"`, `"nothingYet":false` Lessons first: with lessons to offer (`references/lessons.md`, End), post its `card` as one `lessons` item with `--wait` before the finish. Completion finish: `command` is the suggested commit when fixes landed (AGENTS.md format, `"where":"When you are happy with it, commit it from your terminal:"`, `"commit":true`), else none; `"dashboard":true`. A stop's `command` is the bare `/plan2code-review`, no dashboard. + +Under `--loop` (a Review Loop round, desktop app only): read `notes/review-loop.md` after `console.md`; it replaces the scope card, the fix menu and the sign-off. diff --git a/src/web-console/patches.mjs b/src/web-console/patches.mjs index 922eb8a..4308c50 100644 --- a/src/web-console/patches.mjs +++ b/src/web-console/patches.mjs @@ -598,7 +598,7 @@ export function applyPatch(state, patch) { if (v === null) { // The loop's report fields are set, never deleted: a null here would // strip the app's criteria or an already-posted report. - if (["loopExpect", "loopOutcome", "loopEnd"].includes(k)) throw new Error(rule("", k, "cannot be deleted by a patch")); + if (["loopExpect", "loopOutcome", "loopEnd", "roundOutcome"].includes(k)) throw new Error(rule("", k, "cannot be deleted by a patch")); delete next[k]; continue; } @@ -664,9 +664,19 @@ export function applyPatch(state, patch) { next.chat = chat; break; } + case "roundOutcome": + // A Review Loop round's one report. validate() checks its shape and + // the report doc; here only who may send it, and how often. + if (state.loop?.driving !== true || !state.loop.round) { + throw new Error(rule("", "roundOutcome", "is only accepted in a Review Loop round session")); + } + if (state.roundOutcome !== undefined) throw new Error(rule("", "roundOutcome", "was already posted for this session")); + next.roundOutcome = v; + break; case "loopOutcome": // The skill's one report of a phase built under the loop. The shape is // checked by validate(); here only who may send it, and how often. + if (state.loop?.round) throw new Error(rule("", "loopOutcome", "is not accepted in a round session: a round reports roundOutcome, not loopOutcome")); if (!state.loop?.driving) { throw new Error(rule("", "loopOutcome", "is only accepted in a loop session; a resume without --loop unlocked it, so run open --resume --workflow --loop, then post this again")); } @@ -1248,6 +1258,7 @@ export function validate(state) { if (state.loopExpect !== undefined) problems.push(...loopExpectProblems(state.loopExpect)); if (state.loopOutcome !== undefined) problems.push(...loopOutcomeProblems(state.loopOutcome, state.loopExpect)); if (state.loopEnd !== undefined) problems.push(...loopEndProblems(state.loopEnd, state)); + if (state.roundOutcome !== undefined) problems.push(...roundOutcomeProblems(state.roundOutcome, state)); // The dashboard agent's answer to Suggest for me on the loop setup screen. if (state.loopSuggest !== undefined) problems.push(...loopSuggestProblems(state.loopSuggest)); @@ -1489,6 +1500,7 @@ export function isOpen(item) { /* ------------------------------------------------------ the loop's reports */ const LOOP_LEVELS = ["critical", "warning", "suggestion"]; +export const ROUND_ROLES = ["both", "reviewer", "fixer"]; const LOOP_REASONS = ["tests", "findings", "blocked", "conflict", "other"]; const LOOP_CAN = ["resume", "ask", "fix", "finalize", "dashboard"]; const TASK_ID = /^\d+\.\d+$/; @@ -1707,9 +1719,153 @@ export function loopSuggestProblems(v) { return p; } +/** + * Problems with a `roundOutcome` (what a Review Loop round reports), as + * sentences naming the field; an empty array when it is good. Rules are the + * overview's Data Model. `state` is the merged session, which holds the + * round's stamp and the report doc the outcome names. + */ +export function roundOutcomeProblems(o, state) { + const p = []; + const bad = (field, rule) => p.push(`roundOutcome.${field} ${rule}`); + if (!isPlainObject(o)) return ["roundOutcome must be an object"]; + const prose = (field, s) => { + if (typeof s === "string") p.push(...proseProblems(s, `roundOutcome.${field}`)); + }; + const stamp = state?.loop || {}; + if (!isPosInt(o.round)) bad("round", "must be a positive integer"); + else if (o.round !== stamp.round) bad("round", `must be ${stamp.round}, this session's round`); + if (!ROUND_ROLES.includes(o.role)) bad("role", `must be one of ${ROUND_ROLES.join(", ")}`); + else if (o.role !== stamp.role) bad("role", `must be "${stamp.role}", this session's role`); + const role = ROUND_ROLES.includes(o.role) ? o.role : stamp.role; + if (o.result !== "passed" && o.result !== "failed") bad("result", 'must be "passed" or "failed"'); + if (o.result === "passed") { + if (o.reason !== null) bad("reason", "must be null when the round passed"); + } else if (o.result === "failed" && !LOOP_REASONS.includes(o.reason)) { + bad("reason", `must be one of ${LOOP_REASONS.join(", ")} when the round failed`); + } + if (!oneLine(o.summary, 200)) bad("summary", "must be one line of 1 to 200 characters"); + else prose("summary", o.summary); + if (!oneLine(o.subject, 100)) bad("subject", "must be one line of 1 to 100 characters"); + else prose("subject", o.subject); + + if (role === "both" || role === "reviewer") { + // A report is a doc the agent already posted: docs carry no kind field, + // so the outcome names the doc by its id. + if (typeof o.report !== "string" || !(state?.docs || []).some((d) => d && d.id === o.report)) { + bad("report", "must name a report doc already posted in this session"); + } + } else if (o.report !== undefined && typeof o.report !== "string") bad("report", "must be a doc id when present"); + + if (!isPlainObject(o.review)) bad("review", "must be an object { critical, warning, suggestion, fixed, unfixed, suggestions }"); + else { + const r = o.review; + for (const level of LOOP_LEVELS) if (!isNonNegInt(r[level])) bad(`review.${level}`, "must be a non-negative integer"); + for (const list of ["fixed", "unfixed", "suggestions"]) { + if (!Array.isArray(r[list])) bad(`review.${list}`, "must be an array"); + else if (r[list].length > 50) bad(`review.${list}`, "has at most 50 entries"); + else { + r[list].forEach((f, i) => { + const at = `review.${list}[${i}]`; + if (!isPlainObject(f)) return bad(at, "must be an object { title, file, line? }"); + if (!oneLine(f.title, 200)) bad(`${at}.title`, "must be one line of 1 to 200 characters"); + else prose(`${at}.title`, f.title); + if (!relativePath(f.file)) bad(`${at}.file`, "must be a relative path inside the project"); + if (f.line !== undefined && !isPosInt(f.line)) bad(`${at}.line`, "must be a positive integer when present"); + }); + } + } + } + + if (role === "both" || role === "fixer") { + if (!isPlainObject(o.tests)) bad("tests", "must be an object { ran, passed, summary }"); + else { + if (typeof o.tests.ran !== "boolean") bad("tests.ran", "must be true or false"); + if (typeof o.tests.passed !== "boolean") bad("tests.passed", "must be true or false"); + if (typeof o.tests.summary !== "string" || /[\r\n]/.test(o.tests.summary)) bad("tests.summary", "must be a one-line string"); + else prose("tests.summary", o.tests.summary); + } + } else if (o.tests !== undefined && !isPlainObject(o.tests)) bad("tests", "must be an object when present"); + return p; +} + +const REVIEW_END_REASONS = ["clean", "cap", "person", "failed"]; + +/** + * The Review Loop's `loopEnd` (`kind: "review"`): why the run ended, the report + * doc, what Continue and the partial diff offer, the Suggestions pick, and + * after sign-off (`signedOff`) the note on what it did. `report` and + * `partial.diff` name docs on the page, as `evidence` does for the other kinds. + */ +function reviewLoopEndProblems(e, state) { + const p = []; + const bad = (field, rule) => p.push(`loopEnd.${field} ${rule}`); + const prose = (field, s) => { + if (typeof s === "string") p.push(...proseProblems(s, `loopEnd.${field}`)); + }; + const onPage = (id) => typeof id === "string" && (state?.docs || []).some((d) => d && d.id === id); + if (!oneLine(e.line, 200)) bad("line", "must be one line of 1 to 200 characters"); + else prose("line", e.line); + if (!REVIEW_END_REASONS.includes(e.reason)) bad("reason", `must be one of ${REVIEW_END_REASONS.join(", ")}`); + if (!onPage(e.report)) bad("report", "must be the id of a doc on the page"); + if (typeof e.canContinue !== "boolean") bad("canContinue", "must be true or false"); + if (typeof e.canSquash !== "boolean") bad("canSquash", "must be true or false"); + if (e.signedOff !== undefined && typeof e.signedOff !== "boolean") bad("signedOff", "must be true or false when present"); + if (e.note !== undefined) { + if (!oneLine(e.note, 200)) bad("note", "must be one line of 1 to 200 characters"); + else prose("note", e.note); + } + if (!Array.isArray(e.can) || !e.can.every((c) => LOOP_CAN.includes(c))) { + bad("can", `must be an array with entries from ${LOOP_CAN.join(", ")}`); + } + if (e.partial !== undefined) { + if (!isPlainObject(e.partial)) bad("partial", "must be an object { files, added, removed, diff }"); + else { + for (const k of ["files", "added", "removed"]) if (!isNonNegInt(e.partial[k])) bad(`partial.${k}`, "must be a non-negative integer"); + if (!onPage(e.partial.diff)) bad("partial.diff", "must be the id of a doc on the page"); + } + } + if (e.suggestions !== undefined) { + if (!Array.isArray(e.suggestions)) bad("suggestions", "must be an array"); + else if (e.suggestions.length > 50) bad("suggestions", "has at most 50 entries"); + else { + const seen = new Set(); + e.suggestions.forEach((s, i) => { + const at = `suggestions[${i}]`; + if (!isPlainObject(s)) return bad(at, "must be an object { id, title, file, line? }"); + if (typeof s.id !== "string" || !/^s[0-9]{1,3}$/.test(s.id)) bad(`${at}.id`, "must look like s1"); + else if (seen.has(s.id)) bad(`${at}.id`, "must be unique"); + else seen.add(s.id); + if (!oneLine(s.title, 200)) bad(`${at}.title`, "must be one line of 1 to 200 characters"); + else prose(`${at}.title`, s.title); + if (s.file !== "" && !relativePath(s.file)) bad(`${at}.file`, "must be a relative path inside the project or empty"); + else prose(`${at}.file`, s.file); + if (s.line !== undefined && !isPosInt(s.line)) bad(`${at}.line`, "must be a positive integer when present"); + }); + } + } + if (e.open !== undefined) { + if (!Array.isArray(e.open)) bad("open", "must be an array"); + else if (e.open.length > 50) bad("open", "has at most 50 entries"); + else { + e.open.forEach((f, i) => { + const at = `open[${i}]`; + if (!isPlainObject(f)) return bad(at, "must be an object { title, file, line? }"); + if (f.level !== undefined && f.level !== "critical" && f.level !== "warning") bad(`${at}.level`, 'must be "critical" or "warning" when present'); + if (!oneLine(f.title, 200)) bad(`${at}.title`, "must be one line of 1 to 200 characters"); + else prose(`${at}.title`, f.title); + if (!relativePath(f.file)) bad(`${at}.file`, "must be a relative path inside the project"); + if (f.line !== undefined && !isPosInt(f.line)) bad(`${at}.line`, "must be a positive integer when present"); + }); + } + } + return p; +} + /** * Problems with a `loopEnd` (the app's word on how the loop ended), given the - * merged state so `evidence` can be checked against the docs on the page. + * merged state so `evidence` (or, for a Review Loop's `kind: "review"`, `report` + * and `partial.diff`) can be checked against the docs on the page. */ export function loopEndProblems(e, state) { const p = []; @@ -1718,7 +1874,8 @@ export function loopEndProblems(e, state) { const prose = (field, s) => { if (typeof s === "string") p.push(...proseProblems(s, `loopEnd.${field}`)); }; - if (e.kind !== "stopped" && e.kind !== "finished") bad("kind", 'must be "stopped" or "finished"'); + if (e.kind === "review") return reviewLoopEndProblems(e, state); + if (e.kind !== "stopped" && e.kind !== "finished") bad("kind", 'must be "stopped" or "finished" (or "review" for a Review Loop)'); if (!oneLine(e.line, 200)) bad("line", "must be one line of 1 to 200 characters"); else prose("line", e.line); if (e.evidence !== undefined) { @@ -1772,7 +1929,8 @@ export function loopEndProblems(e, state) { // Loop mode adds four optional keys that a blank state does not hold (absent, // not null): `loop: { driving: true, strength? }` (set by `open --loop`), `loopExpect` // (the app's judging criteria), `loopOutcome` (the skill's report) and -// `loopEnd` (the app's ending). +// `loopEnd` (the app's ending). A Review Loop round adds `roundOutcome` and +// stamps `loop: { driving, round, role, scopeFile }`. export function blankState({ sid, workflow, title, project, specDir }) { return { schema: SCHEMA, @@ -1809,7 +1967,7 @@ export function switchWorkflow(state, { workflow, title, specDir }) { // A blank state holds no `loop`, `loopExpect`, `loopOutcome` or `loopEnd`, // so a hop never carries them over; `open --loop` stamps `loop` again after // the switch, and the app restamps `loopExpect` on its next look. - for (const key of ["loop", "loopExpect", "loopOutcome", "loopEnd"]) delete next[key]; + for (const key of ["loop", "loopExpect", "loopOutcome", "loopEnd", "roundOutcome"]) delete next[key]; if (state.chat) next.chat = state.chat; return next; } diff --git a/src/web-console/public/answers.js b/src/web-console/public/answers.js index ba1f47a..b254154 100644 --- a/src/web-console/public/answers.js +++ b/src/web-console/public/answers.js @@ -733,6 +733,13 @@ const LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card); export const LOOP_ENTRY = LOOP_SKILL ? { skill: LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...LOOP_SKILL.card } : null; +// The Review Loop's card, the second app-only entry: same shape, own setup screen. +const REVIEW_LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card && s !== LOOP_SKILL); +export const REVIEW_LOOP_ENTRY = REVIEW_LOOP_SKILL + ? { skill: REVIEW_LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...REVIEW_LOOP_SKILL.card } + : null; +// Every app-only card, in the order the dashboard draws them. +export const APP_ONLY_ENTRIES = Object.freeze([LOOP_ENTRY, REVIEW_LOOP_ENTRY].filter(Boolean)); export const OUTSIDE_APP_LINE = "Runs only in the Plan2Code desktop app."; // A workflow by the name its dashboard card gives it ("Implement"), for the @@ -851,7 +858,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) { const hasAgents = Boolean(scan && scan.hasAgents); const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null; const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder"; - const rule = skillByName(entry.skill) || (entry.appOnly ? LOOP_SKILL : null); + const rule = skillByName(entry.skill) || (entry.appOnly ? SKILLS.find((s) => s.appOnly && s.skill === entry.skill) || LOOP_SKILL : null); if (!rule || !rule.states) return ON; // The three cards whose rules read the scan rather than the spec. diff --git a/src/web-console/public/app-bridge.js b/src/web-console/public/app-bridge.js index 851b964..795c102 100644 --- a/src/web-console/public/app-bridge.js +++ b/src/web-console/public/app-bridge.js @@ -40,7 +40,8 @@ export function onAppMessage(kind, handler) { /** * Hear the app's answers to the Implementation Loop's named requests: * `loop-facts` (what agent a loop would use), `loop-start-result`, - * `loop-notify-test-result` and the three stop-screen results. `store` is the page object and `redraw` its + * `loop-notify-test-result` and the three stop-screen results, then the Review Loop's + * `review-loop-facts` and `review-loop-start-result`. `store` is the page object and `redraw` its * render; they are handed in so this file keeps importing nothing. */ export function wireLoopMessages(store, redraw) { @@ -59,6 +60,31 @@ export function wireLoopMessages(store, redraw) { store.loopStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the loop.") }; redraw(); }); + // The Review Loop's own answers: its facts, and the result of its Start. + onAppMessage("review-loop-facts", (data) => { + store.reviewFacts = data.facts && typeof data.facts === "object" ? data.facts : null; + redraw(); + }); + onAppMessage("review-loop-start-result", (data) => { + // Cancel in the app's confirm: nothing started, so the setup is as it was. + if (data.ok === true && data.started === false) { + store.reviewStart = null; + if (store.reviewLoopSetup) store.reviewLoopSetup.starting = false; + redraw(); + return; + } + store.reviewStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the Review Loop.") }; + if (!store.reviewStart.ok && store.reviewLoopSetup) store.reviewLoopSetup.starting = false; + redraw(); + }); + // The end screen's presses (Continue, Keep or Discard, Sign off, the finished + // screen's next step): the answer clears the pressed state and keeps any error. + for (const kind of ["review-loop-continue-result", "review-loop-partial-result", "review-loop-sign-off-result", "review-loop-next-result"]) { + onAppMessage(kind, (data) => { + store.reviewAction = { kind, ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app could not do that.") }; + redraw(); + }); + } onAppMessage("loop-notify-test-result", (data) => { store.loopNotifyTest = { waiting: false, ok: data.ok === true, sent: data.sent === true, error: data.ok === true ? null : String(data.error || "The app could not send the test.") }; redraw(); diff --git a/src/web-console/public/app.js b/src/web-console/public/app.js index c5ca2e7..7c0ce51 100644 --- a/src/web-console/public/app.js +++ b/src/web-console/public/app.js @@ -22,7 +22,7 @@ import { adopt, askSuggestions, banner, clearBanner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter, renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope, wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding, - wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace, + wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, openReviewLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace, openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, renderCard, send, refreshLessonsSend, } from "./screens/core.js"; @@ -37,7 +37,7 @@ import { sound } from "./sound.js"; // and the few calls a screen makes into another are handed to state.js first. onSave(save); useHooks({ - launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, askSuggestions, banner, clearBanner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, + launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, openReviewLoopSetup, askSuggestions, banner, clearBanner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, renderCard, send, refreshLessonsSend, }); diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 3cc72c3..d285b82 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -2511,6 +2511,9 @@ that skips what is not worth fixing and records each skip, or by level (Critical, Warning, Suggestion). +
  • + Review rounds per phase (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers run up to this many more rounds before the phase is committed. +
  • It uses the launch agent and model the app is running, and it needs permission checks off: with them on, an agent would diff --git a/src/web-console/public/loop-parts.js b/src/web-console/public/loop-parts.js new file mode 100644 index 0000000..52a1bd9 --- /dev/null +++ b/src/web-console/public/loop-parts.js @@ -0,0 +1,262 @@ +// Plan2Code Web Console - the parts both loop setup screens draw, so neither screen imports the other; defines only. +// +// The Implementation Loop's screen (screens/loop-setup.js) and the Review Loop's +// (screens/review-loop-setup.js) share these: the field builders, the strength +// words, the notification fields with their checks, and the silence input. The +// page's shape test keeps a screen from importing another screen, so what two +// screens use lives here, beside state.js. + +import { el } from "./render.js"; +import { page } from "./state.js"; + +export const STRENGTH_WORDS = [ + ["thrifty", "Thrifty"], + ["balanced", "Balanced"], + ["best", "Best"], +]; +export const MATCH_SESSION = "Match my session"; + +export const DEFAULT_NOTIFY_PARAM = "message"; +// What the setup can send a notification to. `name` is the label for the field +// the person names, on the kinds that have one. +export const NOTIFY_KINDS = [ + { id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" }, + { id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." }, + { id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." }, + { id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' }, + { id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." }, + { id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" }, +]; + +export const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0; + +/** + * What is wrong with the web address fields as typed, or "". The server checks + * again on save; this is the line that shows while typing. + */ +export function notifyProblem(url, param, kind = "query") { + const address = url.trim(); + if (!address) return ""; + if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://."; + let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address); + if (good) { + try { + good = Boolean(new URL(address).hostname); + } catch { + good = false; + } + } + if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents."; + const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name); + if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~"; + return ""; +} + +/** + * The chat service a pasted address belongs to, or "". A webhook needs a POST: + * a GET to a Discord webhook answers 200 and posts nothing, so staying on the + * query string kind would look like it worked. + */ +export function kindForUrl(url) { + let parsed; + try { + parsed = new URL(url.trim()); + } catch { + return ""; + } + const host = parsed.hostname.toLowerCase(); + const under = (domain) => host === domain || host.endsWith(`.${domain}`); + if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord"; + if (host === "hooks.slack.com") return "slack"; + if (host === "chat.googleapis.com") return "google-chat"; + if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams"; + return ""; +} + +export function field(label, hint) { + const box = el("div", "loop-field"); + box.appendChild(el("p", "loop-label", label)); + if (hint) box.appendChild(el("p", "loop-hint", hint)); + return box; +} + +export function toggle(id, text, checked, onChange) { + const label = el("label", "loop-switch"); + const input = el("input"); + input.type = "checkbox"; + input.id = id; + input.checked = checked; + input.addEventListener("change", () => onChange(input.checked)); + label.append(input, el("span", null, text)); + return label; +} + +export function radios(name, options, current, onChange) { + const group = el("div", "loop-radios"); + group.setAttribute("role", "radiogroup"); + for (const [value, text, detail] of options) { + const label = el("label", "loop-radio"); + const input = el("input"); + input.type = "radio"; + input.name = name; + input.id = `loop-${name}-${value}`; + input.checked = current === value; + input.addEventListener("change", () => input.checked && onChange(value)); + const body = el("span", "loop-radio-body"); + body.appendChild(el("span", "loop-radio-text", text)); + if (detail) body.appendChild(el("span", "loop-radio-detail", detail)); + label.append(input, body); + group.appendChild(label); + } + return group; +} + +/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */ +export function select(id, label, options, value, onChange) { + const box = el("select", "loop-select"); + box.id = id; + box.setAttribute("aria-label", label); + for (const [v, text, disabled] of options) { + const o = el("option", null, text); + o.value = v; + o.disabled = Boolean(disabled); + box.appendChild(o); + } + box.value = value; + box.addEventListener("change", () => onChange(box.value)); + return box; +} + +/** The "stuck after this many minutes" number input, bound to `f.silenceMinutes`. */ +export function silenceField(f, text = "Count the agent as stuck after this many minutes with no activity") { + const silence = el("label", "loop-number"); + silence.appendChild(el("span", null, text)); + const silenceInput = el("input", "is-compact loop-text loop-narrow"); + silenceInput.type = "number"; + silenceInput.id = "loop-silence"; + silenceInput.min = "1"; + silenceInput.max = "60"; + silenceInput.step = "1"; + silenceInput.value = String(f.silenceMinutes); + silenceInput.addEventListener("input", () => { + f.silenceMinutes = Number(silenceInput.value); + }); + silence.appendChild(silenceInput); + return silence; +} + +/** + * The "Send a notification" field: kind, address, the name for the message, the + * per-step toggle and Send a test. `s` is the screen's state (`starting`, + * `notifyKindChosen`), `f` its form (`notifyKind`, `notifyUrl`, `notifyParam`, + * and the toggle's key). `o` says what the toggle is called and keys on, and what + * Send a test does (`onTest`, required); the Implementation Loop's screen takes the + * other defaults. + */ +export function notifyFields(s, f, options = {}) { + const o = { + intro: + "When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which, with the project, the phase, what it built and how long it took. Leave the address empty to send nothing.", + phasesId: "loop-notify-phases", + phasesKey: "notifyPhases", + phasesText: "Also tell me when each phase is complete", + ...options, + }; + const notify = field("Send a notification", o.intro); + const kindLabel = el("label", "loop-number"); + kindLabel.appendChild(el("span", null, "Send to")); + const kindSelect = el("select", "is-compact loop-text"); + kindSelect.id = "loop-notify-kind"; + for (const kind of NOTIFY_KINDS) { + const option = el("option", null, kind.label); + option.value = kind.id; + kindSelect.appendChild(option); + } + kindSelect.value = f.notifyKind; + kindLabel.appendChild(kindSelect); + const kindHint = el("p", "loop-hint"); + const notifyInput = el("input", "is-compact loop-text"); + notifyInput.type = "text"; + notifyInput.inputMode = "url"; + notifyInput.id = "loop-notify-url"; + notifyInput.value = f.notifyUrl; + notifyInput.maxLength = 2000; + notifyInput.setAttribute("aria-label", "Web address to call"); + const paramRow = el("div"); + const paramLabel = el("label", "loop-number"); + const paramText = el("span"); + paramLabel.appendChild(paramText); + const paramInput = el("input", "is-compact loop-text loop-param"); + paramInput.type = "text"; + paramInput.id = "loop-notify-param"; + paramInput.value = f.notifyParam; + paramInput.placeholder = DEFAULT_NOTIFY_PARAM; + paramInput.maxLength = 64; + paramLabel.appendChild(paramInput); + paramRow.appendChild(paramLabel); + const phasesRow = toggle(o.phasesId, o.phasesText, f[o.phasesKey], (v) => { + f[o.phasesKey] = v; + }); + const notifyWarn = el("p", "loop-warn"); + const testRow = el("div", "loop-test"); + const testButton = el("button", "btn", "Send a test"); + testButton.type = "button"; + testButton.id = "loop-notify-test"; + testButton.addEventListener("click", () => o.onTest()); + testRow.appendChild(testButton); + const testLine = notifyTestLine(); + if (testLine) testRow.appendChild(testLine); + const showNotify = () => { + const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind); + kindSelect.value = kind.id; + kindHint.textContent = kind.hint; + notifyInput.placeholder = kind.placeholder; + paramText.textContent = kind.name || ""; + paramRow.hidden = !kind.name || f.notifyUrl.trim() === ""; + phasesRow.hidden = f.notifyUrl.trim() === ""; + const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id); + notifyWarn.textContent = problem; + notifyWarn.hidden = !problem; + testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting; + }; + // What a test said was about the address as it was. + const forgetTest = () => { + if (page.loopNotifyTest && !page.loopNotifyTest.waiting) { + page.loopNotifyTest = null; + testRow.querySelector("p")?.remove(); + } + }; + notifyInput.addEventListener("input", () => { + f.notifyUrl = notifyInput.value; + forgetTest(); + // A pasted webhook picks its own kind, unless the person chose one here. + const service = kindForUrl(f.notifyUrl); + if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service; + showNotify(); + }); + kindSelect.addEventListener("change", () => { + f.notifyKind = kindSelect.value; + forgetTest(); + s.notifyKindChosen = true; + showNotify(); + }); + paramInput.addEventListener("input", () => { + f.notifyParam = paramInput.value; + forgetTest(); + showNotify(); + }); + showNotify(); + notify.append(kindLabel, notifyInput, kindHint, paramRow, phasesRow, notifyWarn, testRow); + return notify; +} + +/** The line beside Send a test, or null with nothing to say. */ +export function notifyTestLine() { + const test = page.loopNotifyTest; + if (!test) return null; + if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm..."); + if (!test.ok) return el("p", "loop-error", test.error); + if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived."); + return null; +} + diff --git a/src/web-console/public/review-loop-end.js b/src/web-console/public/review-loop-end.js new file mode 100644 index 0000000..ae1665a --- /dev/null +++ b/src/web-console/public/review-loop-end.js @@ -0,0 +1,201 @@ +// Plan2Code Web Console - how a Review Loop run ends: the stop screens, the sign-off and the finished screen; defines only. + +import { el } from "./render.js"; +import { field, toggle } from "./loop-parts.js"; +import { blockBody } from "./doc-files.js"; +import { docs } from "./selectors.js"; +import { tellApp } from "./app-bridge.js"; +import { page, redraw } from "./state.js"; + +// The app's `loopEnd` with `kind: "review"` (patches.mjs reviewLoopEndProblems): +// reason why it ended: clean, cap, person or failed +// report a doc on the page holding the Markdown report +// partial after Stop now: the partial diff doc and its stats, until Keep or Discard +// suggestions, canSquash, canContinue, open, signedOff, note +// Before sign-off the card offers Continue (when allowed), the Suggestions pick, +// the squash switch and Sign off; after it, the finished screen's three ways on. + +const HEADINGS = { + clean: "Clean", + cap: "Stopped at the round cap", + person: "Stopped by you", + failed: "Failed", +}; + +// What the card remembers across redraws, keyed by the ending it belongs to: +// the ticked Suggestions, the squash switch, and which press is waiting on the app. +let ticks = { key: null, picks: new Set(), squash: false }; +let pressed = { key: null, what: "" }; +let lastKey = null; + +// The ending a press belongs to. Keep or Discard reposts the same ending without +// its partial changes, so a press waiting on the app ends with that change. +function endKey(end) { + return `review|${end.line}|${end.reason}|${end.signedOff ? "signed" : "open"}|${end.partial ? "partial" : "whole"}`; +} + +// The ending the ticks and the squash switch belong to: the same through Keep +// or Discard, so what the person ticked is not cleared by settling the partial changes. +function tickKey(end) { + return `review|${end.line}|${end.reason}|${end.signedOff ? "signed" : "open"}`; +} + +function button(label, id, cls, disabled, onClick) { + const b = el("button", "btn" + (cls ? " " + cls : ""), label); + b.type = "button"; + b.id = id; + b.disabled = disabled; + b.addEventListener("click", onClick); + return b; +} + +function stats(partial) { + const row = el("p", "diff-totals review-end-stats"); + row.appendChild(el("span", null, `${partial.files} ${partial.files === 1 ? "file" : "files"} changed, `)); + row.appendChild(el("span", "diff-plus", `+${partial.added}`)); + row.appendChild(document.createTextNode(" ")); + row.appendChild(el("span", "diff-minus", `-${partial.removed}`)); + return row; +} + +function where(item) { + if (!item.file) return ""; + return item.line ? `${item.file}:${item.line}` : item.file; +} + +/** How a Review Loop run ended, drawn from the app's `loopEnd`. */ +export function renderReviewLoopEnd(end) { + const key = endKey(end); + if (lastKey !== key) { + lastKey = key; + page.reviewAction = null; + } + const ticked = tickKey(end); + if (ticks.key !== ticked) ticks = { key: ticked, picks: new Set(), squash: false }; + const failed = + page.reviewAction && !page.reviewAction.ok ? page.reviewAction.error : page.loopAction && !page.loopAction.ok ? page.loopAction.error : ""; + const busy = pressed.key === key && !failed; + const press = (what, kind, extra) => { + if (page.gone || busy) return; + pressed = { key, what }; + page.reviewAction = null; + page.loopAction = null; + tellApp(kind, extra); + redraw(); + }; + + const card = el("article", "card handoff loop-end review-end"); + card.appendChild(el("p", "card-kicker", end.signedOff ? "Review Loop finished" : "Review Loop ended")); + const heading = end.signedOff ? "Signed off" : HEADINGS[end.reason] || end.line; + card.appendChild(el("h2", "loop-end-heading review-end-heading", heading)); + if (end.line) card.appendChild(el("p", "loop-line review-end-line", end.line)); + if (end.note) card.appendChild(el("p", "callout is-info review-end-note", end.note)); + + const report = docs().find((d) => d.id === end.report); + if (report) { + const read = el("button", "btn sm review-end-report", "Read the full report"); + read.type = "button"; + read.addEventListener("click", () => { + page.view = "doc:" + report.id; + redraw(); + }); + card.appendChild(read); + } + + if (end.signedOff) { + drawFinished(card, end, busy, press); + } else { + drawStop(card, end, busy, press); + } + if (failed) card.appendChild(el("p", "loop-error review-end-error", failed)); + return card; +} + +function drawPartial(card, end, busy, press) { + const partial = end.partial; + const box = el("section", "review-end-partial"); + box.appendChild(el("h3", null, "What Stop now left")); + box.appendChild(stats(partial)); + const doc = docs().find((d) => d.id === partial.diff); + const block = doc && (doc.blocks || []).find((b) => typeof b.diff === "string" || typeof b.text === "string"); + if (block) { + const view = el("div", "review-end-diff"); + view.appendChild(blockBody(block, doc)); + box.appendChild(view); + } + box.appendChild(el("p", "loop-end-hint", "Keep leaves these changes in your files. Discard takes them out and cannot be undone.")); + const row = el("div", "btn-row"); + row.appendChild(button("Keep these changes", "review-end-keep", "primary", busy, () => press("keep", "review-loop-partial", { keep: true }))); + row.appendChild(button("Discard them", "review-end-discard", "", busy, () => press("discard", "review-loop-partial", { keep: false }))); + box.appendChild(row); + card.appendChild(box); +} + +function drawStop(card, end, busy, press) { + if (end.partial) drawPartial(card, end, busy, press); + // While the partial work is undecided the app refuses Continue, so it is not offered. + if (end.canContinue && !end.partial) { + const choice = el("div", "loop-end-choice"); + const label = end.reason === "cap" ? "Run one more round" : "Continue"; + choice.appendChild(button(label, "review-end-continue", "", busy, () => press("continue", "review-loop-continue"))); + choice.appendChild(el("p", "loop-end-hint", "Pick the review up again with the same setup.")); + card.appendChild(choice); + } + + const suggestions = Array.isArray(end.suggestions) ? end.suggestions : []; + if (suggestions.length) { + const pick = field("Suggestions", "Nothing is ticked. Ticked ones are applied in one last pass, with their own check and commit."); + pick.classList.add("review-end-suggestions"); + for (const s of suggestions) { + const label = toggle(`review-end-pick-${s.id}`, "", ticks.picks.has(s.id), (on) => { + if (on) ticks.picks.add(s.id); + else ticks.picks.delete(s.id); + }); + label.classList.add("review-end-pick"); + const text = label.querySelector("span"); + text.appendChild(el("strong", null, s.title)); + const at = where(s); + if (at) text.appendChild(el("code", "review-end-where", at)); + pick.appendChild(label); + } + card.appendChild(pick); + } + if (end.canSquash) { + const sq = field("Commits"); + sq.appendChild(toggle("review-end-squash", "Squash the round commits into one", ticks.squash, (on) => (ticks.squash = on))); + card.appendChild(sq); + } + const row = el("div", "btn-row"); + row.appendChild( + button("Sign off", "review-end-signoff", "primary", busy || Boolean(end.partial), () => press("sign-off", "review-loop-sign-off", { picks: [...ticks.picks], squash: ticks.squash })) + ); + card.appendChild(row); + card.appendChild( + el("p", "loop-end-hint", end.partial ? "Keep or discard the partial changes first, then sign off." : "Sign off finishes the run, with or without picks.") + ); +} + +function drawFinished(card, end, busy, press) { + const actions = el("div", "loop-end-actions review-end-next"); + const add = (label, id, hint, primary, onClick) => { + const choice = el("div", "loop-end-choice" + (primary ? " is-recommended" : "")); + choice.appendChild(button(label, id, primary ? "primary" : "", busy, onClick)); + choice.appendChild(el("p", "loop-end-hint", hint)); + actions.appendChild(choice); + }; + add("PR Prep", "review-end-pr-prep", "Get the branch ready for a pull request.", true, () => press("pr-prep", "review-loop-next", { next: "pr-prep" })); + if (Array.isArray(end.open) && end.open.length) { + add("Fix what's left by hand", "review-end-quick-task", "Start a Quick task with the Critical and Warning findings still open.", false, () => + press("quick-task", "review-loop-next", { next: "quick-task" }) + ); + } + add("Back to the dashboard", "review-end-dashboard", "Leave this screen and pick another skill. Your work stays as it is.", false, () => press("dashboard", "loop-dashboard")); + card.appendChild(actions); +} + +/** The end card is no longer drawn (Continue started another round): a press and + * the ending it belonged to are over, so the next ending starts with live buttons. */ +export function forgetReviewEnd() { + pressed = { key: null, what: "" }; + lastKey = null; +} diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 433cccd..2944ae6 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -68,6 +68,7 @@ import { import { sound } from "../sound.js"; import { renderConfirm, renderDashboard } from "./dashboard.js"; import { renderLoopSetup } from "./loop-setup.js"; +import { renderReviewLoopSetup } from "./review-loop-setup.js"; import { renderLaunching, renderWaiting } from "./starting.js"; import { attachFiles, findSetAside, heldNotes, noteImages, pendingNotes, purgeImages } from "../uploads.js"; import { closeMentions } from "../mention-box.js"; @@ -82,6 +83,7 @@ import { framed, linkLeavesPage, onAppMessage, shortcutIdFor, startNewSession, t import { openPrefs as openPrefsDialog } from "./prefs-dialog.js"; import { continueButton } from "../continue-button.js"; import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js"; +import { forgetReviewEnd } from "../review-loop-end.js"; import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, renderFooterDashboard, stopInProgress, stopWarning } from "./ending.js"; import { renderNotepadButton } from "./notepad.js"; import { renderActivities } from "./activities.js"; @@ -107,6 +109,7 @@ export { wireEnding } from "./ending.js"; export { wireNotepad } from "./notepad.js"; export { wireActivities } from "./activities.js"; export { openLoopSetup, wireLoopSetup } from "./loop-setup.js"; +export { openReviewLoopSetup } from "./review-loop-setup.js"; const $ = (id) => document.getElementById(id); @@ -450,6 +453,7 @@ export function adopt(body) { if (!isDashboard() || finish()) { page.dashPick = null; page.loopSetup = null; + page.reviewLoopSetup = null; } // A launch (or an ending) mid wake-up: cut it short rather than play on // over a page that is no longer the menu. @@ -1419,6 +1423,9 @@ export function renderStatus() { // still has presses on offer the move is theirs; with none, it is done. if (page.S.loopEnd) { const end = page.S.loopEnd; + if (end.kind === "review") { + return end.signedOff ? say("point", "Signed off. Pick what happens next.") : say("point", "The Review Loop ended. Sign off when you are ready."); + } const moves = Array.isArray(end.can) ? end.can.length : 0; if (!moves) return say("done", "The loop is done."); return say( @@ -1805,6 +1812,7 @@ function paintMain(main) { if (isDashboard() && !finish()) { if (page.local.launching) renderLaunching(main); else if (page.loopSetup) renderLoopSetup(main); + else if (page.reviewLoopSetup) renderReviewLoopSetup(main); else if (page.dashPick) { // A spec-switch under an open confirm can gray the pick out. Rather // than offer START on a card that cannot launch, drop back to the @@ -1816,7 +1824,7 @@ function paintMain(main) { } } else renderDashboard(main); // Review from the Learning banner: the lessons card, over the menu. - renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.dashPick); + renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.reviewLoopSetup && !page.dashPick); return; } renderLessonsDialog(false); @@ -1849,6 +1857,7 @@ function paintMain(main) { // How the Implementation Loop ended, from the app's `loopEnd`: its own // screen, ahead of any card the last phase left behind. + if (!page.S.loopEnd) forgetReviewEnd(); if (page.S.loopEnd && !finish()) { const card = renderLoopEnd(page.S.loopEnd); card.classList.add("is-primary"); @@ -2601,9 +2610,10 @@ export function wireChrome() { // Escape is the confirm pane's Back — but not while a dialog has it. Native // dialogs close themselves on the same key; backing out of the pick at the // same time would be two undos for one press. - if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) { + if (e.key === "Escape" && (page.dashPick || page.loopSetup || page.reviewLoopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) { page.dashPick = null; page.loopSetup = null; + page.reviewLoopSetup = null; redraw(); } }); diff --git a/src/web-console/public/screens/dashboard.js b/src/web-console/public/screens/dashboard.js index 9ba4d49..2345d50 100644 --- a/src/web-console/public/screens/dashboard.js +++ b/src/web-console/public/screens/dashboard.js @@ -30,6 +30,7 @@ import { SKILL_CATALOG, catalogEntry, LOOP_ENTRY, + APP_ONLY_ENTRIES, OUTSIDE_APP_LINE, launchVariant, SPEC_STATE_LABELS, @@ -296,16 +297,17 @@ export function renderDashboard(main) { let shown = 0; for (const g of CATALOG_GROUPS) { const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e))); - // The desktop app's Implementation Loop card closes its group. Outside the - // app it is always drawn, grayed, so the feature can be found. - const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY)); - if (!entries.length && !loopCard) continue; - shown += entries.length + (loopCard ? 1 : 0); + // The desktop app's Implementation Loop and Review Loop cards close their + // group. Outside the app they are always drawn, grayed, so the features can + // be found. + const loopCards = APP_ONLY_ENTRIES.filter((e) => e.group === g.id && (!page.inApp || !hide || available(e))); + if (!entries.length && !loopCards.length) continue; + shown += entries.length + loopCards.length; const section = el("section", "dash-group"); section.appendChild(el("h3", "dash-group-title", g.title)); const grid = el("div", "dash-grid"); for (const e of entries) grid.appendChild(dashCard(e, menu)); - if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu)); + for (const e of loopCards) grid.appendChild(dashCard(e, menu)); section.appendChild(grid); wrap.appendChild(section); } @@ -752,6 +754,8 @@ async function readHandoff(h) { } } +const REVIEW_LOOP_SKILL = "plan2code-review-loop"; + function dashCard(entry, menu) { const presentation = entry.appOnly ? loopPresentation(entry, menu) : cardPresentation(entry, scan(), selSpec(), menu); // The agent's `recommend` and detail describe the initially selected spec. @@ -784,6 +788,8 @@ function dashCard(entry, menu) { title.appendChild(document.createTextNode(entry.title)); b.appendChild(title); b.appendChild(el("span", "dash-card-blurb", entry.blurb)); + // A line only the desktop app shows (the Review card's pointer to the Review Loop). + if (entry.appNote && page.inApp) b.appendChild(el("span", "dash-card-detail", entry.appNote)); if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail)); if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason)); @@ -793,8 +799,8 @@ function dashCard(entry, menu) { b.appendChild(foot); b.addEventListener("click", () => { - // The loop card opens its own setup screen instead of a confirm pane. - if (entry.appOnly) return hooks.openLoopSetup(selSpec()); + // A loop card opens its own setup screen instead of a confirm pane. + if (entry.appOnly) return entry.skill === REVIEW_LOOP_SKILL ? hooks.openReviewLoopSetup(selSpec()) : hooks.openLoopSetup(selSpec()); page.dashPick = entry; redraw(); }); @@ -803,7 +809,7 @@ function dashCard(entry, menu) { if (entry.appOnly) { const wrap = el("div", "dash-card-wrap"); wrap.appendChild(b); - wrap.appendChild(loopHelpLink()); + wrap.appendChild(loopHelpLink(entry)); return wrap; } return b; @@ -814,13 +820,17 @@ function dashCard(entry, menu) { // pre-selected: a person opts into running unattended. function loopPresentation(entry, menu) { if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" }; + if (entry.skill === REVIEW_LOOP_SKILL && loopDriving()) { + return { on: false, reason: "A loop is running. Stop it from the banner at the top of the window first.", recommended: false, detail: "" }; + } return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false }; } // "How the loop works" under the card: a real button styled as a link, a // sibling of the card button inside its wrapper. -function loopHelpLink() { - const a = el("button", "dash-card-link", "How the loop works"); +function loopHelpLink(entry) { + const review = entry && entry.skill === REVIEW_LOOP_SKILL; + const a = el("button", "dash-card-link", review ? "How the Review Loop works" : "How the loop works"); a.type = "button"; a.addEventListener("click", () => hooks.openHelpOn("loop")); return a; diff --git a/src/web-console/public/screens/ending.js b/src/web-console/public/screens/ending.js index 77e09c6..3ba9ebb 100644 --- a/src/web-console/public/screens/ending.js +++ b/src/web-console/public/screens/ending.js @@ -55,6 +55,7 @@ const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the to import { docSavedNote, downloadDoc } from "../doc-files.js"; import { startNewSession, tellApp } from "../app-bridge.js"; import { pendingNotes } from "../uploads.js"; +import { renderReviewLoopEnd } from "../review-loop-end.js"; // The end of the session, and the only screen in this page whose job is to // send someone somewhere else. @@ -239,6 +240,7 @@ function loopEndKey(end) { * its agent made; the report behind the button holds them all). */ export function renderLoopEnd(end) { + if (end.kind === "review") return renderReviewLoopEnd(end); const card = el("article", "card handoff loop-end"); const finished = end.kind === "finished"; card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped")); diff --git a/src/web-console/public/screens/help-dialog.js b/src/web-console/public/screens/help-dialog.js index e94cff0..0ba2b23 100644 --- a/src/web-console/public/screens/help-dialog.js +++ b/src/web-console/public/screens/help-dialog.js @@ -272,6 +272,8 @@ function buildHelp() { } li.appendChild(strong); li.appendChild(document.createTextNode(" " + (e.help || e.blurb))); + // The app-only pointer (Review's line about the Review Loop), shown in the app. + if (e.appNote && page.inApp) li.appendChild(el("span", "help-app-note", " " + e.appNote)); list.appendChild(li); } cards.append(head, list); diff --git a/src/web-console/public/screens/loop-setup.js b/src/web-console/public/screens/loop-setup.js index cbb04f7..b5cd6b8 100644 --- a/src/web-console/public/screens/loop-setup.js +++ b/src/web-console/public/screens/loop-setup.js @@ -11,6 +11,7 @@ import { hooks, page, redraw, saveNow } from "../state.js"; import { SKILL_CATALOG } from "../answers.js"; import { postJson } from "../net.js"; import { tellApp, wireLoopMessages } from "../app-bridge.js"; +import { DEFAULT_NOTIFY_PARAM, MATCH_SESSION, NOTIFY_KINDS, STRENGTH_WORDS, field, hasMapping, notifyFields, notifyProblem, radios, select, silenceField, toggle } from "../loop-parts.js"; let justPicked = ""; // the strength node picked a moment ago, which alone plays its grow // Suggest for me was pressed and has just come back (answer, time-out or failed @@ -34,26 +35,9 @@ const AFTER_LAST = [ ["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."], ]; -const STRENGTH_WORDS = [ - ["thrifty", "Thrifty"], - ["balanced", "Balanced"], - ["best", "Best"], -]; -const MATCH_SESSION = "Match my session"; // How long Suggest for me waits on the dashboard agent before it gives the field back. export const SUGGEST_WAIT_MS = 120000; -const DEFAULT_NOTIFY_PARAM = "message"; -// What the setup can send a notification to. `name` is the label for the field -// the person names, on the kinds that have one. -const NOTIFY_KINDS = [ - { id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" }, - { id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." }, - { id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." }, - { id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' }, - { id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." }, - { id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" }, -]; const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase."; /** Called by the page's start-up: hear the app's answers to the loop's requests. */ @@ -97,6 +81,7 @@ export async function openLoopSetup(spec) { const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, picks, resolved, ...setup } = answer; mine.form = { review: setup.review !== false, + reviewRounds: Number.isInteger(setup.reviewRounds) && setup.reviewRounds >= 0 && setup.reviewRounds <= 6 ? setup.reviewRounds : 2, fixMode: setup.fixMode === "levels" ? "levels" : "smart", fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k), commit: setup.commit !== false, @@ -154,8 +139,6 @@ function ensureResolved(s) { }); } -const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0; - /** This spec's saved word for a phase, or "" for Match my session. */ function pickOf(form, spec, phase) { const list = form.strengths && form.strengths[spec]; @@ -220,87 +203,6 @@ export function startBlock(form, facts, appFacts) { return ""; } -/** - * What is wrong with the web address fields as typed, or "". The server checks - * again on save; this is the line that shows while typing. - */ -export function notifyProblem(url, param, kind = "query") { - const address = url.trim(); - if (!address) return ""; - if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://."; - let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address); - if (good) { - try { - good = Boolean(new URL(address).hostname); - } catch { - good = false; - } - } - if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents."; - const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name); - if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~"; - return ""; -} - -/** - * The chat service a pasted address belongs to, or "". A webhook needs a POST: - * a GET to a Discord webhook answers 200 and posts nothing, so staying on the - * query string kind would look like it worked. - */ -export function kindForUrl(url) { - let parsed; - try { - parsed = new URL(url.trim()); - } catch { - return ""; - } - const host = parsed.hostname.toLowerCase(); - const under = (domain) => host === domain || host.endsWith(`.${domain}`); - if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord"; - if (host === "hooks.slack.com") return "slack"; - if (host === "chat.googleapis.com") return "google-chat"; - if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams"; - return ""; -} - -function field(label, hint) { - const box = el("div", "loop-field"); - box.appendChild(el("p", "loop-label", label)); - if (hint) box.appendChild(el("p", "loop-hint", hint)); - return box; -} - -function toggle(id, text, checked, onChange) { - const label = el("label", "loop-switch"); - const input = el("input"); - input.type = "checkbox"; - input.id = id; - input.checked = checked; - input.addEventListener("change", () => onChange(input.checked)); - label.append(input, el("span", null, text)); - return label; -} - -function radios(name, options, current, onChange) { - const group = el("div", "loop-radios"); - group.setAttribute("role", "radiogroup"); - for (const [value, text, detail] of options) { - const label = el("label", "loop-radio"); - const input = el("input"); - input.type = "radio"; - input.name = name; - input.id = `loop-${name}-${value}`; - input.checked = current === value; - input.addEventListener("change", () => input.checked && onChange(value)); - const body = el("span", "loop-radio-body"); - body.appendChild(el("span", "loop-radio-text", text)); - if (detail) body.appendChild(el("span", "loop-radio-detail", detail)); - label.append(input, body); - group.appendChild(label); - } - return group; -} - function factRow(list, label, value) { const row = el("div", "loop-fact"); row.appendChild(el("dt", null, label)); @@ -348,22 +250,6 @@ export function renderLoopSetup(main) { main.appendChild(pane); } -/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */ -function select(id, label, options, value, onChange) { - const box = el("select", "loop-select"); - box.id = id; - box.setAttribute("aria-label", label); - for (const [v, text, disabled] of options) { - const o = el("option", null, text); - o.value = v; - o.disabled = Boolean(disabled); - box.appendChild(o); - } - box.value = value; - box.addEventListener("change", () => onChange(box.value)); - return box; -} - /** * The rising-bar badge of the Subagents tab for a strength level: bars up to * `level` (1 to 3) are on. Level 0 (Match my session) has no rank, so it draws @@ -521,7 +407,7 @@ function applySuggestion(s, answer, resolved) { } /** The "Strength per phase" field: the toggle, Set all to, and one row per phase left. */ -function strengthField(s, redo) { +export function strengthField(s, redo) { stopWatchingLine(); const f = s.form; const resolved = s.facts.resolved; @@ -697,6 +583,7 @@ function drawBody(pane, s) { const review = field("Review"); review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo()))); + review.appendChild(roundsField(f)); form.appendChild(review); if (f.review) { @@ -735,95 +622,7 @@ function drawBody(pane, s) { after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo()))); form.appendChild(after); - const notify = field( - "Send a notification", - "When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which, with the project, the phase, what it built and how long it took. Leave the address empty to send nothing." - ); - const kindLabel = el("label", "loop-number"); - kindLabel.appendChild(el("span", null, "Send to")); - const kindSelect = el("select", "is-compact loop-text"); - kindSelect.id = "loop-notify-kind"; - for (const kind of NOTIFY_KINDS) { - const option = el("option", null, kind.label); - option.value = kind.id; - kindSelect.appendChild(option); - } - kindSelect.value = f.notifyKind; - kindLabel.appendChild(kindSelect); - const kindHint = el("p", "loop-hint"); - const notifyInput = el("input", "is-compact loop-text"); - notifyInput.type = "text"; - notifyInput.inputMode = "url"; - notifyInput.id = "loop-notify-url"; - notifyInput.value = f.notifyUrl; - notifyInput.maxLength = 2000; - notifyInput.setAttribute("aria-label", "Web address to call"); - const paramRow = el("div"); - const paramLabel = el("label", "loop-number"); - const paramText = el("span"); - paramLabel.appendChild(paramText); - const paramInput = el("input", "is-compact loop-text loop-param"); - paramInput.type = "text"; - paramInput.id = "loop-notify-param"; - paramInput.value = f.notifyParam; - paramInput.placeholder = DEFAULT_NOTIFY_PARAM; - paramInput.maxLength = 64; - paramLabel.appendChild(paramInput); - paramRow.appendChild(paramLabel); - const phasesRow = toggle("loop-notify-phases", "Also tell me when each phase is complete", f.notifyPhases, (v) => { - f.notifyPhases = v; - }); - const notifyWarn = el("p", "loop-warn"); - const testRow = el("div", "loop-test"); - const testButton = el("button", "btn", "Send a test"); - testButton.type = "button"; - testButton.id = "loop-notify-test"; - testButton.addEventListener("click", () => sendTest(s)); - testRow.appendChild(testButton); - const testLine = notifyTestLine(); - if (testLine) testRow.appendChild(testLine); - const showNotify = () => { - const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind); - kindSelect.value = kind.id; - kindHint.textContent = kind.hint; - notifyInput.placeholder = kind.placeholder; - paramText.textContent = kind.name || ""; - paramRow.hidden = !kind.name || f.notifyUrl.trim() === ""; - phasesRow.hidden = f.notifyUrl.trim() === ""; - const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id); - notifyWarn.textContent = problem; - notifyWarn.hidden = !problem; - testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting; - }; - // What a test said was about the address as it was. - const forgetTest = () => { - if (page.loopNotifyTest && !page.loopNotifyTest.waiting) { - page.loopNotifyTest = null; - testRow.querySelector("p")?.remove(); - } - }; - notifyInput.addEventListener("input", () => { - f.notifyUrl = notifyInput.value; - forgetTest(); - // A pasted webhook picks its own kind, unless the person chose one here. - const service = kindForUrl(f.notifyUrl); - if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service; - showNotify(); - }); - kindSelect.addEventListener("change", () => { - f.notifyKind = kindSelect.value; - forgetTest(); - s.notifyKindChosen = true; - showNotify(); - }); - paramInput.addEventListener("input", () => { - f.notifyParam = paramInput.value; - forgetTest(); - showNotify(); - }); - showNotify(); - notify.append(kindLabel, notifyInput, kindHint, paramRow, phasesRow, notifyWarn, testRow); - form.appendChild(notify); + form.appendChild(notifyFields(s, f, { onTest: () => sendTest(s) })); const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it."); const checkInput = el("input", "is-compact loop-text"); @@ -844,20 +643,7 @@ function drawBody(pane, s) { const retry = field("If a phase crashes or goes quiet"); retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo()))); - const silence = el("label", "loop-number"); - silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity")); - const silenceInput = el("input", "is-compact loop-text loop-narrow"); - silenceInput.type = "number"; - silenceInput.id = "loop-silence"; - silenceInput.min = "1"; - silenceInput.max = "60"; - silenceInput.step = "1"; - silenceInput.value = String(f.silenceMinutes); - silenceInput.addEventListener("input", () => { - f.silenceMinutes = Number(silenceInput.value); - }); - silence.appendChild(silenceInput); - retry.appendChild(silence); + retry.appendChild(silenceField(f)); retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count.")); form.appendChild(retry); @@ -895,16 +681,6 @@ function drawBody(pane, s) { pane.appendChild(foot); } -/** The line beside Send a test, or null with nothing to say. */ -function notifyTestLine() { - const test = page.loopNotifyTest; - if (!test) return null; - if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm..."); - if (!test.ok) return el("p", "loop-error", test.error); - if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived."); - return null; -} - function gitButton() { const b = el("button", "btn", "Open the Git board"); b.type = "button"; @@ -915,6 +691,30 @@ function gitButton() { return b; } +/** "Review rounds per phase": fresh reviewer rounds after a phase's own review, off with Review. */ +function roundsField(f) { + const box = el("label", "loop-number"); + box.appendChild(el("span", null, "Review rounds per phase")); + const input = el("input", "is-compact loop-text loop-narrow"); + input.type = "number"; + input.id = "loop-review-rounds"; + input.min = "0"; + input.max = "6"; + input.step = "1"; + input.value = String(f.reviewRounds); + input.disabled = !f.review; + input.addEventListener("input", () => { + f.reviewRounds = Number(input.value); + }); + box.appendChild(input); + const wrap = el("div", null); + wrap.appendChild(box); + wrap.appendChild( + el("p", "loop-hint", f.review ? "When a phase's own review leaves a Critical or a Warning, fresh reviewers run up to this many more rounds before the phase is committed. 0 turns them off." : "Applies only with Review on") + ); + return wrap; +} + /** The form as the console saves it (exported for the page tests). */ export function setupBody(f, s) { const body = { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM }; diff --git a/src/web-console/public/screens/review-loop-setup.js b/src/web-console/public/screens/review-loop-setup.js new file mode 100644 index 0000000..0fbc932 --- /dev/null +++ b/src/web-console/public/screens/review-loop-setup.js @@ -0,0 +1,433 @@ +// Plan2Code Web Console - the Review Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only. +// +// The dashboard's Review Loop card opens this in place of the cards. Nothing +// here runs an agent: Start saves the picks through POST /review-loop-setup, +// then sends them to the desktop app (`review-loop-start { setup }`), which +// confirms in its own window. Its field builders come from ../loop-parts.js, shared with +// the Implementation Loop's screen. The notification address belongs to the +// Implementation Loop's setup: this screen shows it and, when changed, saves it +// there (POST /loop-setup), because the app reads it from that file alone. + +import { el } from "../render.js"; +import { hooks, page, redraw } from "../state.js"; +import { specList } from "../selectors.js"; +import { postJson } from "../net.js"; +import { tellApp } from "../app-bridge.js"; +import { MATCH_SESSION, STRENGTH_WORDS, field, hasMapping, notifyFields, notifyProblem, radios, select, silenceField, toggle } from "../loop-parts.js"; + +const SCOPES = [ + ["branch", "Branch against main, with uncommitted changes", "Everything this branch changed since it left main, plus what is not committed yet."], + ["uncommitted", "Uncommitted changes only", "Only what is changed in your working tree right now."], + ["spec", "A spec's work", "The files the chosen spec's phases built."], +]; + +export const HANDS_OFF_LINE = "Please do not edit this project's files while rounds run: anything changed goes into the round."; +export const REVIEWER_NOTE = "Each round's reviewer runs fresh, whatever the Subagents switch says; the switch still governs other helpers."; +export const COMMIT_FIRST_LINE = "Commit my current changes first as Work before Review Loop"; +const CAP_HINT = "Rounds stop sooner on a clean one. You can always add a round later, one at a time, up to 6 in all."; + +/** + * Open the screen for `spec` (the picker's selected spec object, or null). The + * saved setup and the read-only facts come from the console; the agent and its + * helpers come from the app. A spec pre-fills the picker and the spec scope. + */ +export async function openReviewLoopSetup(spec) { + if (page.gone || page.pendingResult || page.local.launching) return; + const dir = spec && spec.dir ? spec.dir : ""; + page.reviewStart = null; + page.loopNotifyTest = null; + page.reviewLoopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false, resolvedFor: undefined, notifyKindChosen: false }; + tellApp("review-loop-facts"); + redraw(); + const mine = page.reviewLoopSetup; + let res; + try { + res = await fetch("/review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" }); + } catch { + res = null; + } + if (page.reviewLoopSetup !== mine) return; + const answer = res && res.ok ? await res.json().catch(() => null) : null; + if (page.reviewLoopSetup !== mine) return; + if (!answer) { + mine.failed = true; + redraw(); + return; + } + const facts = page.reviewFacts; + mine.form = { + scope: ["branch", "uncommitted", "spec"].includes(answer.scope) ? answer.scope : "branch", + spec: typeof answer.spec === "string" ? answer.spec : "", + cap: Number.isInteger(answer.cap) ? answer.cap : 3, + commit: answer.commit !== false, + agreeCommit: false, + suggestions: answer.suggestions === true, + strength: typeof answer.strength === "string" ? answer.strength : "", + silenceMinutes: Number.isInteger(answer.silenceMinutes) ? answer.silenceMinutes : 20, + notifyRounds: answer.notifyRounds === true, + notifyKind: (facts && facts.notifyKind) || "query", + notifyUrl: (facts && facts.notifyUrl) || "", + notifyParam: (facts && facts.notifyParam) || "message", + }; + // The picker's spec lives in the form; the saved one only matters on the spec scope. + if (dir) mine.form.spec = dir; + mine.facts = { branch: typeof answer.branch === "string" ? answer.branch : "", pending: Number.isInteger(answer.pending) ? answer.pending : null, resolved: undefined }; + mine.loaded = true; + redraw(); +} + +const reviewAgent = () => (page.reviewFacts && typeof page.reviewFacts.agent === "string" ? page.reviewFacts.agent : ""); + +/** The facts' notify values arrive with the app's answer, which can follow the setup: take them while the fields are still as saved. */ +function adoptNotify(s) { + const facts = page.reviewFacts; + if (!facts || s.notifyAdopted || !s.form) return; + s.notifyAdopted = true; + if (!s.form.notifyUrl) s.form.notifyUrl = facts.notifyUrl || ""; + s.form.notifyKind = facts.notifyKind || s.form.notifyKind; + s.form.notifyParam = facts.notifyParam || s.form.notifyParam; +} + +/** Read the agent's strengths once the app has said which agent it is (the two answers come in either order). */ +function ensureResolved(s) { + if (!page.reviewFacts || s.resolvedFor === reviewAgent()) return; + const agent = reviewAgent(); + s.resolvedFor = agent; + if (!agent) { + s.facts.resolved = null; + return; + } + fetch("/review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" }) + .then((res) => (res.ok ? res.json() : null)) + .catch(() => null) + .then((answer) => { + if (page.reviewLoopSetup !== s || s.resolvedFor !== agent) return; + s.facts.resolved = answer && answer.resolved && typeof answer.resolved === "object" ? answer.resolved : null; + redraw(); + }); +} + +function close() { + page.reviewLoopSetup = null; + page.reviewStart = null; + redraw(); +} + +/** + * Why Start is grayed, or "" when it can go, in the spec's order. Exported for + * the page's unit tests. + */ +export function reviewStartBlock(form, facts, appFacts) { + if (!form || !facts) return "Loading the setup..."; + if (!appFacts) return "Asking the app..."; + if (appFacts.running) return "A loop is already running in this window. Stop it from the banner first."; + if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt."; + if (form.scope === "spec" && !form.spec) return "Pick the spec whose work to review."; + if (form.commit && facts.pending !== null && facts.pending > 0 && !form.agreeCommit) { + return `${facts.pending} uncommitted ${facts.pending === 1 ? "change needs" : "changes need"} your say-so: tick the box to commit ${facts.pending === 1 ? "it" : "them"} first, or turn commits off.`; + } + const problem = notifyProblem(form.notifyUrl, form.notifyParam, form.notifyKind); + if (problem) return problem; + return ""; +} + +/** The form as the console saves it (exported for the page tests). */ +export function reviewSetupBody(f) { + return { + scope: f.scope, + spec: f.scope === "spec" ? f.spec : "", + cap: f.cap, + commit: f.commit, + suggestions: f.suggestions, + strength: f.strength, + silenceMinutes: f.silenceMinutes, + notifyRounds: f.notifyRounds, + }; +} + +/** What the app is sent: the saved picks and whether the person agreed to the pre-run commit. */ +export function reviewStartMessage(f, facts) { + const dirty = facts && facts.pending !== null && facts.pending > 0; + return { ...reviewSetupBody(f), preRunCommitAgreed: Boolean(f.commit && dirty && f.agreeCommit) }; +} + +function factRow(list, label, value) { + const row = el("div", "loop-fact"); + row.appendChild(el("dt", null, label)); + row.appendChild(el("dd", null, value)); + list.appendChild(row); +} + +function agentLine(facts) { + if (!facts) return "Asking the app..."; + if (!facts.agent) return "No agent is chosen yet"; + const label = facts.agentLabel || facts.agent; + return facts.helpers ? `${label} (starts its own helpers: one session per round)` : `${label} (no helpers: a reviewer session, then a fixer session, each round)`; +} + +export function renderReviewLoopSetup(main) { + const s = page.reviewLoopSetup; + const pane = el("div", "dash-confirm loop-setup review-loop-setup"); + pane.appendChild(el("p", "card-kicker", "Step 3 · Review Loop")); + pane.appendChild(el("h2", "dash-title", "Set up the Review Loop")); + + if (s.failed) { + pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again.")); + } else if (!s.loaded) { + const wait = el("p", "dash-working"); + wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup...")); + pane.appendChild(wait); + } else { + drawBody(pane, s); + } + + const actions = el("div", "confirm-actions"); + const back = el("button", "btn ghost", "Back"); + back.type = "button"; + back.addEventListener("click", close); + actions.appendChild(back); + const help = el("button", "linky loop-help", "How the loop works"); + help.type = "button"; + help.addEventListener("click", () => hooks.openHelpOn("loop")); + actions.appendChild(help); + pane.appendChild(actions); + main.appendChild(pane); +} + +/** One strength for every round: Match my session, or a mapped word. Grayed when this agent maps none. */ +function strengthPick(s) { + const f = s.form; + const resolved = s.facts.resolved; + const appFacts = page.reviewFacts; + const box = field("Strength"); + const loading = !appFacts || resolved === undefined; + const none = !loading && (appFacts.strengthsMapped === false || !hasMapping(resolved)); + if (none) { + const gray = el("p", "loop-hint loop-strength-none"); + gray.append("This agent has no strengths mapped yet. "); + const link = el("button", "linky", "Map them in Agents & models"); + link.type = "button"; + link.addEventListener("click", () => hooks.openPrefs("agents")); + gray.appendChild(link); + box.appendChild(gray); + return box; + } + if (loading) { + box.appendChild(el("p", "loop-hint", "Asking the app which agent this loop uses...")); + return box; + } + const options = [["", MATCH_SESSION], ...STRENGTH_WORDS.map(([word, label]) => [word, resolved[word] ? label : label + " (not mapped)", !resolved[word]])]; + if (f.strength && !resolved[f.strength]) f.strength = ""; + box.appendChild( + select("review-loop-strength", "Strength for every round", options, f.strength, (v) => { + f.strength = v; + s.problems = []; + redraw(); + }) + ); + const row = f.strength ? resolved[f.strength] : null; + box.appendChild(el("p", "loop-hint", row ? [row.model, row.effort].filter(Boolean).join(", ") : "Rounds use the model and effort this window started with.")); + return box; +} + +function specPicker(s) { + const f = s.form; + const specs = specList(); + const wrap = el("div", "loop-spec-pick"); + const options = [["", "Choose a spec..."]]; + for (const sp of specs) options.push([sp.dir, sp.dir]); + // A spec the list does not hold (one picked on the dashboard that has since moved) stays visible. + if (f.spec && !specs.some((sp) => sp.dir === f.spec)) options.push([f.spec, f.spec]); + wrap.appendChild( + select("review-loop-spec", "Spec to review", options, f.spec, (v) => { + f.spec = v; + s.problems = []; + redraw(); + }) + ); + return wrap; +} + +function drawBody(pane, s) { + const f = s.form; + adoptNotify(s); + ensureResolved(s); + const appFacts = page.reviewFacts; + const redo = () => { + s.problems = []; + redraw(); + }; + + const lines = el("div", "loop-lines"); + for (const text of [ + "The app reviews your change in rounds, each in a fresh agent session. Round 1 looks at everything in scope; each later round looks only at what the round before it changed.", + "It stops on a clean round, at the round cap, or when you press a stop button on the banner at the top of the window. It never pushes.", + ]) { + lines.appendChild(el("p", "loop-line", text)); + } + lines.appendChild(el("p", "loop-line loop-hands-off", HANDS_OFF_LINE)); + pane.appendChild(lines); + + const facts = el("dl", "loop-facts"); + factRow(facts, "Agent", agentLine(appFacts)); + factRow(facts, "Branch", s.facts.branch || "unknown"); + factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending)); + pane.appendChild(facts); + + const form = el("div", "loop-form"); + + const scope = field("What to review"); + scope.appendChild(radios("reviewscope", SCOPES, f.scope, (v) => ((f.scope = v), redo()))); + if (f.scope === "spec") scope.appendChild(specPicker(s)); + form.appendChild(scope); + + const cap = field("Round cap", CAP_HINT); + const capLabel = el("label", "loop-number"); + capLabel.appendChild(el("span", null, "Stop after this many rounds (1 to 6)")); + const capInput = el("input", "is-compact loop-text loop-narrow"); + capInput.type = "number"; + capInput.id = "review-loop-cap"; + capInput.min = "1"; + capInput.max = "6"; + capInput.step = "1"; + capInput.value = String(f.cap); + capInput.addEventListener("input", () => { + f.cap = Number(capInput.value); + }); + capLabel.appendChild(capInput); + cap.appendChild(capLabel); + form.appendChild(cap); + + const commit = field("Commit"); + commit.appendChild(toggle("review-loop-commit", "Commit each round to the current branch", f.commit, (v) => ((f.commit = v), redo()))); + if (f.commit && s.facts.pending !== null && s.facts.pending > 0) { + commit.appendChild(toggle("review-loop-agree", COMMIT_FIRST_LINE, f.agreeCommit, (v) => ((f.agreeCommit = v), redo()))); + } + form.appendChild(commit); + + const sugg = field("Suggestions"); + sugg.appendChild(toggle("review-loop-suggestions", "Apply Suggestions on their own", f.suggestions, (v) => ((f.suggestions = v), redo()))); + sugg.appendChild(el("p", "loop-hint", "Off: Suggestions are listed in the report for you to pick. On: they are applied in one last pass.")); + form.appendChild(sugg); + + form.appendChild(strengthPick(s)); + + const reviewer = field("Reviewers"); + reviewer.appendChild(el("p", "loop-hint loop-reviewer-note", REVIEWER_NOTE)); + form.appendChild(reviewer); + + const retry = field("If a round goes quiet"); + retry.appendChild(silenceField(f, "Count the agent as stuck after this many minutes with no activity")); + retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest test run. A stuck round is retried once.")); + form.appendChild(retry); + + form.appendChild( + notifyFields(s, f, { + intro: "When the Review Loop needs you or ends, except when you stop it yourself, the app sends a short message naming the round. The address is the Implementation Loop's: changing it here changes it there. Leave it empty to send nothing.", + phasesId: "review-loop-notify-rounds", + phasesKey: "notifyRounds", + phasesText: "Also tell me when each round finishes", + onTest: () => sendTest(s), + }) + ); + pane.appendChild(form); + + const block = reviewStartBlock(f, s.facts, appFacts); + const gated = Boolean(block); + const foot = el("div", "loop-start"); + if (gated) { + const why = el("p", "loop-why", block); + why.setAttribute("role", "status"); + foot.appendChild(why); + } + if (s.problems.length) { + const bad = el("ul", "loop-problems"); + for (const p of s.problems) bad.appendChild(el("li", null, p)); + foot.appendChild(bad); + } + const waiting = s.starting && !page.reviewStart; + if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm...")); + if (page.reviewStart && !page.reviewStart.ok) foot.appendChild(el("p", "loop-error", page.reviewStart.error)); + if (page.reviewStart && page.reviewStart.ok) foot.appendChild(el("p", "loop-why", "The Review Loop is starting...")); + const start = el("button", "btn primary", "Start the Review Loop"); + start.type = "button"; + start.id = "review-loop-start"; + start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.reviewStart && page.reviewStart.ok); + start.addEventListener("click", () => startReviewLoop(s)); + foot.appendChild(start); + pane.appendChild(foot); +} + +/** + * Save the notification fields into the Implementation Loop's setup, the only + * place the app reads them from. A project with no loop setup yet gets the + * loop's defaults beside the new address. Resolves to a problem line or "". + */ +async function saveNotify(s) { + const f = s.form; + const facts = page.reviewFacts || {}; + const url = f.notifyUrl.trim(); + const param = f.notifyParam.trim() || "message"; + if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return ""; + let current = null; + try { + const res = await fetch("/loop-setup", { cache: "no-store" }); + current = res.ok ? await res.json() : null; + } catch { + current = null; + } + if (!current) return "The notification address could not be saved. Try again."; + // The loop's own screen drops these two before it saves; the store rejects them as unknown fields. + const { remembered, saved, ...entry } = current; + const { status, body } = await postJson("/loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param }); + if (status !== 200 || !body || body.ok !== true) { + return Array.isArray(body && body.problems) && body.problems.length ? body.problems.join(" ") : "The notification address could not be saved. Try again."; + } + // What the app now reads, so a second Start does not save it again. + if (page.reviewFacts) page.reviewFacts = { ...page.reviewFacts, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param }; + return ""; +} + +async function sendTest(s) { + const f = s.form; + if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return; + s.problems = []; + page.loopNotifyTest = { waiting: true }; + redraw(); + const problem = await saveNotify(s); + if (page.reviewLoopSetup !== s) return; + if (problem) { + page.loopNotifyTest = null; + s.problems = [problem]; + redraw(); + return; + } + tellApp("loop-notify-test"); +} + +async function startReviewLoop(s) { + const f = s.form; + if (reviewStartBlock(f, s.facts, page.reviewFacts) || (s.starting && !page.reviewStart)) return; + s.problems = []; + page.reviewStart = null; + s.starting = true; + redraw(); + const problem = await saveNotify(s); + if (page.reviewLoopSetup !== s) return; + if (problem) { + s.starting = false; + s.problems = [problem]; + redraw(); + return; + } + const { status, body } = await postJson("/review-loop-setup", reviewSetupBody(f)); + if (page.reviewLoopSetup !== s) return; + if (status !== 200 || !body || body.ok !== true) { + s.starting = false; + s.problems = Array.isArray(body && body.problems) && body.problems.length ? body.problems : ["The setup could not be saved. Try again."]; + redraw(); + return; + } + tellApp("review-loop-start", { setup: reviewStartMessage(f, s.facts) }); + redraw(); +} diff --git a/src/web-console/public/skills.js b/src/web-console/public/skills.js index 5c3df1e..35c8884 100644 --- a/src/web-console/public/skills.js +++ b/src/web-console/public/skills.js @@ -42,10 +42,10 @@ // card the dashboard card (group, chip, title, blurb, about, and // `spec: true` when it takes the picked spec), or null; an // optional `help` is Help's line for the card when it differs -// from `blurb`, and `icon` names the `ci-*` symbol in +// from `blurb`, `appNote` is a line only the desktop app shows (card and Help), and `icon` names the `ci-*` symbol in // index.html's card-icons sheet drawn before the title // appOnly the entry is a card the desktop app alone offers (the -// Implementation Loop): no workflow, no installed skill, and no +// Implementation Loop and the Review Loop): no workflow, no installed skill, and no // list derived from the workflows (WORKFLOWS, the meter, the // resume command, Help's card list) holds it. `skill` is an id // only; `workflow` is null. Use FLOW_SKILLS for those lists. @@ -283,6 +283,32 @@ export const SKILLS = Object.freeze([ "Builds every remaining phase of the spec without you at the keyboard. Each phase gets a fresh agent that builds it and reviews it. The app checks the result against the spec, runs your quick check, commits, and moves on. It stops at the first phase that goes wrong and tells you why. Desktop app only.", }, }), + // The desktop app's Review Loop, a second app-only card beside the + // Implementation Loop: it runs review and fix rounds over a finished change, + // each round checked by a fresh reviewer. Any project state lights it; the + // setup screen picks the scope. + skill({ + skill: "plan2code-review-loop", + workflow: null, + appOnly: true, + label: "Review Loop", + name: "Review Loop", + pose: null, + builds: false, phased: false, metered: false, templates: false, + weight: null, started: null, ran: null, resume: null, + subagents: null, + states: "any", + greyed: null, + card: { + group: "pipeline", + chip: "Step 3", + title: "Review Loop", + icon: "loop", + blurb: "Review and fix in rounds on its own, each round checked by a fresh reviewer.", + about: + "Reviews a finished change and fixes what it finds, round after round, without you at the keyboard. The first round reviews everything in scope; each later round reviews only what the last round changed, with a reviewer that never saw the fix being written. It stops on a clean round, at the round cap, or when you say so, then hands back one report and the usual sign-off. Desktop app only.", + }, + }), skill({ skill: "plan2code-4-finalize", workflow: "finalize", @@ -343,6 +369,7 @@ export const SKILLS = Object.freeze([ title: "Review", icon: "review", blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.", + appNote: "In the app, the Review Loop runs review and fix rounds on its own.", about: "A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.", }, diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index a534a4a..5459cfd 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -130,6 +130,14 @@ export const page = { // The setup screen the dashboard's Implementation Loop card opened, or null // (screens/loop-setup.js owns the shape). loopSetup: null, + // The Review Loop's setup screen (screens/review-loop-setup.js owns the shape), what + // the app answered to `review-loop-facts`, and `{ ok, error }` once it answered a + // `review-loop-start`. + reviewLoopSetup: null, + reviewFacts: null, + reviewStart: null, + // `{ kind, ok, error }` once the app answered a press on the Review Loop's end screen. + reviewAction: null, loopFacts: null, loopStart: null, loopNotifyTest: null, diff --git a/src/web-console/public/styles/dashboard.css b/src/web-console/public/styles/dashboard.css index f79a80c..8289bb3 100644 --- a/src/web-console/public/styles/dashboard.css +++ b/src/web-console/public/styles/dashboard.css @@ -666,4 +666,13 @@ .loop-end-details { display: grid; gap: 10px; } .loop-end-details > summary { cursor: pointer; font-size: var(--fs-md); color: var(--ink-2); } .loop-end-details[open] > summary { margin-bottom: 8px; } +/* The Review Loop's end: the partial diff, the Suggestions pick and the finished screen. */ +.review-end-partial { display: grid; gap: 10px; } +.review-end-partial h3 { margin: 0; } +.review-end-stats { margin: 0; } +.review-end-diff { max-height: 420px; overflow: auto; border: 1px solid var(--rule); border-radius: 8px; } +.review-end-suggestions { display: grid; gap: 6px; } +.review-end-pick span { display: grid; gap: 2px; } +.review-end-where { font-family: var(--mono); font-size: var(--fs-xs); color: var(--ink-2); overflow-wrap: anywhere; } +.review-end-note { margin: 0; } .confirm-note > .confirm-note-retry { justify-self: start; } diff --git a/src/web-console/review-loop-setup.mjs b/src/web-console/review-loop-setup.mjs new file mode 100644 index 0000000..f59ce17 --- /dev/null +++ b/src/web-console/review-loop-setup.mjs @@ -0,0 +1,96 @@ +// Plan2Code Web Console - the Review Loop's setup, remembered per project. + +import path from "node:path"; + +import { ensureDir, HOME_DIR, readJson, withStateLock, writeJsonAtomic } from "./files.mjs"; +import { foldKey } from "./workspace.mjs"; + +// One file for the person, beside loop-setup.json, keyed by the folder a +// session runs in (FR-29: its own entry per project): +// +// { "schema": 1, "projects": { "": { ...setup, "saved": "" } } } +// +// Never under specs/: the server never writes into a project. The notify +// address and kind are not kept here: the Review Loop reads them from the +// Implementation Loop's setup (FR-26). +export const REVIEW_LOOP_SETUP_FILE = path.join(HOME_DIR, "review-loop-setup.json"); +export const REVIEW_LOOP_SETUP_LOCK = "review-loop-setup.json.lock"; + +const SCOPES = ["branch", "uncommitted", "spec"]; +const STRENGTH_WORDS = ["", "thrifty", "balanced", "best"]; +// A spec folder directly under specs/, no leading dot (the route's own rule). +const SPEC_KEY = /^specs\/[^/\\.][^/\\]*$/; + +export const REVIEW_LOOP_DEFAULTS = Object.freeze({ + scope: "branch", + spec: "", + cap: 3, + commit: true, + suggestions: false, + strength: "", + silenceMinutes: 20, + notifyRounds: false, +}); + +/** Problems with a setup entry, as sentences naming the field; empty when it is good. */ +export function reviewLoopSetupProblems(entry) { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return ["the setup must be an object"]; + const problems = []; + for (const key of Object.keys(entry)) { + if (!Object.hasOwn(REVIEW_LOOP_DEFAULTS, key)) problems.push(`"${key}" is not a setup field`); + } + if (!SCOPES.includes(entry.scope)) problems.push(`"scope" must be one of ${SCOPES.join(", ")}`); + if (typeof entry.spec !== "string" || (entry.spec !== "" && !SPEC_KEY.test(entry.spec))) { + problems.push('"spec" must be empty or a folder directly under specs/'); + } + if (!Number.isInteger(entry.cap) || entry.cap < 1 || entry.cap > 6) problems.push('"cap" must be a whole number from 1 to 6'); + for (const key of ["commit", "suggestions", "notifyRounds"]) { + if (typeof entry[key] !== "boolean") problems.push(`"${key}" must be true or false`); + } + if (!STRENGTH_WORDS.includes(entry.strength)) problems.push('"strength" must be empty, thrifty, balanced or best'); + if (!Number.isInteger(entry.silenceMinutes) || entry.silenceMinutes < 1 || entry.silenceMinutes > 60) { + problems.push('"silenceMinutes" must be a whole number from 1 to 60'); + } + return problems; +} + +function readStore() { + const saved = readJson(REVIEW_LOOP_SETUP_FILE, null); + const ok = saved && saved.schema === 1 && saved.projects && typeof saved.projects === "object" && !Array.isArray(saved.projects); + return ok ? saved : { schema: 1, projects: {} }; +} + +/** + * The setup for this project: the saved entry over the defaults, or the + * defaults alone. `remembered` says which, so the screen can tell a first + * visit from a returning one. A missing, unreadable or foreign-schema file + * reads as empty. + */ +export function readReviewLoopSetup(project) { + const saved = readStore().projects[foldKey(project)]; + if (saved && typeof saved === "object") return { ...REVIEW_LOOP_DEFAULTS, ...saved, remembered: true }; + return { ...REVIEW_LOOP_DEFAULTS, remembered: false }; +} + +/** Validate and save this project's setup; throws an Error listing the problems. */ +export function saveReviewLoopSetup(project, entry) { + const problems = reviewLoopSetupProblems(entry); + if (problems.length) { + const err = new Error(`the review loop setup is not valid: ${problems.join("; ")}`); + err.problems = problems; + throw err; + } + ensureDir(path.dirname(REVIEW_LOOP_SETUP_FILE)); + return withStateLock( + path.dirname(REVIEW_LOOP_SETUP_FILE), + () => { + const store = readStore(); + // Only the known fields are kept, in the defaults' order. + const known = Object.fromEntries(Object.keys(REVIEW_LOOP_DEFAULTS).map((key) => [key, entry[key]])); + store.projects[foldKey(project)] = { ...known, saved: new Date().toISOString() }; + writeJsonAtomic(REVIEW_LOOP_SETUP_FILE, { schema: 1, projects: store.projects }); + return readReviewLoopSetup(project); + }, + REVIEW_LOOP_SETUP_LOCK, + ); +} diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index edd1de1..51f9b74 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -35,6 +35,7 @@ import { SHOTS_DIR_NAME, SHOT_NAME, shotType, isOpen } from "./patches.mjs"; import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs"; import { specKey } from "./workspace.mjs"; import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs"; +import { readReviewLoopSetup, saveReviewLoopSetup } from "./review-loop-setup.mjs"; import { takeSpecCarry } from "./spec-carry.mjs"; import { resolveStrengths } from "./strengths.mjs"; import { MARKERS, phaseChecklist } from "./spec-files.mjs"; @@ -136,6 +137,8 @@ const ROUTES = [ { path: "/workspace/browse", method: "POST", origin: true, run: workspaceBrowse }, { path: "/loop-setup", method: "GET", run: loopSetupGet }, { path: "/loop-setup", method: "POST", origin: true, run: loopSetupPost }, + { path: "/review-loop-setup", method: "GET", run: reviewLoopSetupGet }, + { path: "/review-loop-setup", method: "POST", origin: true, run: reviewLoopSetupPost }, { path: "/spec-carry", method: "POST", origin: true, run: specCarry }, { path: "/cancel", method: "POST", origin: true, run: cancel }, { path: "/ping", method: "POST", run: ping }, @@ -1878,6 +1881,41 @@ function loopSetupPost(req, res, ctx) { }); } +// The Review Loop's setup for this project (review-loop-setup.mjs). `?spec=` +// puts the spec and the spec scope into the answer without saving anything. +// `?facts=1` adds the read-only facts the screen shows (the branch and the count +// of uncommitted files, as the loop's setup reads them); `?agent=` adds that +// agent's resolved strengths. Neither is saved. +function reviewLoopSetupGet(req, res, ctx, url) { + let answer = readReviewLoopSetup(loopProject(ctx)); + const spec = url && url.searchParams.get("spec"); + if (spec !== null && spec !== undefined) { + if (!/^specs\/[^/\\]+$/.test(spec) || /^specs\/\./.test(spec)) return json(res, 400, { error: "spec must be a folder directly under specs/" }); + answer = { ...answer, spec, scope: "spec" }; + } + if (url && url.searchParams.get("facts") === "1") { + const state = ctx.readState() || {}; + const pending = state.scan && Number.isInteger(state.scan.pending) ? state.scan.pending : null; + answer = { ...answer, branch: state.branch || "", pending }; + } + const agent = url && url.searchParams.get("agent"); + if (agent) answer = { ...answer, resolved: resolvedStrengthsFor(agent) }; + return json(res, 200, answer); +} + +function reviewLoopSetupPost(req, res, ctx) { + return readBody(req, res, (err, body) => { + if (err && err.tooBig) return json(res, 413, { error: "too large" }); + if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] }); + try { + return json(res, 200, { ok: true, setup: saveReviewLoopSetup(loopProject(ctx), body) }); + } catch (e) { + if (Array.isArray(e.problems)) return json(res, 400, { ok: false, problems: e.problems }); + return json(res, 500, { error: String(e.message) }); + } + }); +} + // The spec the app's New Session carried over (spec-carry.mjs), taken once by // the fresh dashboard's page, which keeps it only if its picker lists that spec. function specCarry(req, res, ctx) { diff --git a/src/web-console/sessions.mjs b/src/web-console/sessions.mjs index e201009..f81af4f 100644 --- a/src/web-console/sessions.mjs +++ b/src/web-console/sessions.mjs @@ -306,6 +306,7 @@ export const PROTECTED_CONSOLE_FILES = new Set([ "workspaces.json", "loop-setup.json", "loop-reports.json", + "review-loop-setup.json", "spec-carry.json", "subagents.json", "pr-hosts.json", diff --git a/src/web-console/static.mjs b/src/web-console/static.mjs index ee2867c..a5911cc 100644 --- a/src/web-console/static.mjs +++ b/src/web-console/static.mjs @@ -36,6 +36,8 @@ export const SERVABLE = new Set([ "uploads.js", "sound.js", "looks.js", + "loop-parts.js", + "review-loop-end.js", "selectors.js", "strengths.js", "app.css", @@ -84,6 +86,7 @@ export const SERVABLE = new Set([ "screens/core.js", "screens/ending.js", "screens/loop-setup.js", + "screens/review-loop-setup.js", "screens/docs.js", "screens/cards.js", "screens/starting.js",