mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-29 05:11:19 -08:00
Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases
AI Assisted
This commit is contained in:
1 parent
d6a28b5dc8
commit
57567d7a0b
71 files changed
+11331
-443
No files matched your search
@@ -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-<n>-<word>`, `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-<n>-<word>`, `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 |
|
||||
|
||||
@@ -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`) |
|
||||
|
||||
@@ -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-<date>.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-<date>.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-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-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.
|
||||
|
||||
@@ -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-<game>*.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/<game>/`) | `node prototypes/music/check.cjs <game>` (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-<area>.mjs` (the loop's is `test-web-console-loop.mjs`), and its `test-web-console-page-<area>.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-<area>.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-<area>.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-<skill>.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` |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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/<version>/` (`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<Id>` keys in `looks.json` (and the time each game was last picked in `activityPlayed<Id>`) (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-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (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 woLine truncated
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console/<version>/` (`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<Id>` keys in `looks.json` (and the time each game was last picked in `activityPlayed<Id>`) (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-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (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 wheLine truncated
|
||||
|
||||
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`.
|
||||
|
||||
|
||||
+9
-2
@@ -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-<date>.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)
|
||||
|
||||
@@ -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/<feature>/REVIEW-LOOP-<date>.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.
|
||||
|
||||
+1
-1
@@ -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/teLine truncated
|
||||
"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/tesLine truncated
|
||||
},
|
||||
"devDependencies": {
|
||||
"gpt-tokenizer": "2.9.0",
|
||||
|
||||
@@ -10,6 +10,13 @@
|
||||
//! REPORT <json> write <json> 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 <json> write <json> 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 <path> <text> write <text> to <path> under the working directory (`\n`
|
||||
//! in the text is a line break), for a round's "fixes". Says
|
||||
//! `FILE written <path>` (`FILE refused <path>` for a path that
|
||||
//! leaves the folder)
|
||||
//! ENV <name> print the variable as `ENV <name>=<value>`
|
||||
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
||||
//! <other> echoed back as `echo: <line>`
|
||||
@@ -43,6 +50,10 @@ pub enum Command {
|
||||
Env(String),
|
||||
/// `REPORT <json>`: the phase report the loop waits for, as the JSON text.
|
||||
Report(String),
|
||||
/// `ROUND <json>`: a Review Loop round's report, as the JSON text.
|
||||
Round(String),
|
||||
/// `FILE <path> <text>`: 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::<serde_json::Value>(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::<serde_json::Value>(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 `<home>/sessions/<sid>/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::<serde_json::Value>(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!(
|
||||
|
||||
@@ -78,6 +78,10 @@ pub struct AgentEntry {
|
||||
pub args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub bypass_args: Vec<String>,
|
||||
/// 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<String>,
|
||||
#[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!(
|
||||
(
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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<FixLevel> {
|
||||
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<String>,
|
||||
/// 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<String>,
|
||||
/// The extra round session the phase is waiting on, so `note_page` can hand
|
||||
/// it the page that session announces.
|
||||
pub round_wait: Option<RoundWait>,
|
||||
/// 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<Boundary>,
|
||||
/// The extra review rounds the current phase has run, for its report entry.
|
||||
pub phase_rounds: Vec<loop_report::RoundEntry>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
/// A page announced before it showed the agent's lock, adopted once it does.
|
||||
pub candidate: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
pub effort: Option<String>,
|
||||
/// `"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<RoundCount>,
|
||||
/// 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<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
pub(crate) fn lock<T>(m: &Mutex<T>) -> 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<u32>,
|
||||
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<Stren
|
||||
|
||||
/// What each strength word maps to for `agent`, from the shipped and user
|
||||
/// model files: read once, when the loop begins.
|
||||
fn strength_rows_for(agent: &Agent) -> BTreeMap<String, StrengthRow> {
|
||||
pub fn strength_rows_for(agent: &Agent) -> BTreeMap<String, StrengthRow> {
|
||||
let models: Vec<String> = 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<String> {
|
||||
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<dyn Fn() + Send + Sync>,
|
||||
}
|
||||
|
||||
/// What the watch thread needs, shared by every step of one loop.
|
||||
#[derive(Clone)]
|
||||
struct Ctx {
|
||||
slot: LoopSlot,
|
||||
agent: Arc<AgentManager>,
|
||||
console_dir: PathBuf,
|
||||
home: PathBuf,
|
||||
launch: Launch,
|
||||
run_id: u64,
|
||||
hooks: Arc<Hooks>,
|
||||
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<String> {
|
||||
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::<String>().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<SystemTime> {
|
||||
|
||||
/// 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<SystemTime> {
|
||||
pub(crate) fn newest_work(session_dir: &Path, project: &Path) -> Option<SystemTime> {
|
||||
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<Outcome> {
|
||||
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<AgentManager>, Arc<Mutex<String>>) {
|
||||
pub(crate) fn fake_agent_manager(folder: &Path) -> (Arc<AgentManager>, Arc<Mutex<String>>) {
|
||||
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<Vec<Seen>> {
|
||||
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::<u32>().unwrap(),
|
||||
before.parse::<u32>().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);
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
pub left_open: Vec<String>,
|
||||
pub commit: Option<String>,
|
||||
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<RoundEntry>,
|
||||
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<String> = e.warnings.iter().map(|w| cell(w)).collect();
|
||||
md.push_str(&format!("- Warnings: {}\n", notes.join("; ")));
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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<LoopReport> {
|
||||
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)
|
||||
}
|
||||
@@ -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<String, StrengthRow>,
|
||||
current: &str,
|
||||
) -> Option<String> {
|
||||
models::next_strength(resolved, current)
|
||||
}
|
||||
@@ -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<Result<RoundOutcome, String>> {
|
||||
let raw = state
|
||||
.get("roundOutcome")
|
||||
.filter(|value| value.is_object())?;
|
||||
match serde_json::from_value::<RoundOutcome>(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<String> {
|
||||
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
|
||||
}
|
||||
@@ -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<AgentManager>,
|
||||
pub console_dir: PathBuf,
|
||||
pub home: PathBuf,
|
||||
pub launch: Launch,
|
||||
pub run_id: u64,
|
||||
pub hooks: Arc<Hooks>,
|
||||
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<String>,
|
||||
pub effort: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<SessionStart, String> {
|
||||
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<serde_json::Value> {
|
||||
session_reader::load(&ctx.home, sid)
|
||||
.ok()
|
||||
.map(|session| session.state)
|
||||
}
|
||||
@@ -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<F: FnMut() -> WatchStep>(every: Duration, mut step: F) -> Option<String> {
|
||||
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::<String>().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<u32>,
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -600,11 +600,17 @@ pub fn git_head_short(project: &Path) -> Option<String> {
|
||||
(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<String> {
|
||||
/// The full hash of `HEAD` (40 or 64 hex characters), or why there is none.
|
||||
pub fn git_head_full(project: &Path) -> Result<String, String> {
|
||||
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"}"#;
|
||||
|
||||
@@ -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::<AppState>();
|
||||
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::<AppState>();
|
||||
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<bool, String> {
|
||||
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::LoopStateEvent> {
|
||||
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<AgentManager>, 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<bool, String> {
|
||||
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<String>,
|
||||
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<LastLoop, 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("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!(
|
||||
|
||||
@@ -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<PhaseFinding>,
|
||||
/// 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<RoundEntry> },
|
||||
/// A round failed after its retry.
|
||||
Failed {
|
||||
reason: String,
|
||||
rounds: Vec<RoundEntry>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Done {
|
||||
pub rounds: Vec<RoundEntry>,
|
||||
pub critical: u32,
|
||||
pub warning: u32,
|
||||
pub suggestion: u32,
|
||||
pub unfixed: Vec<Finding>,
|
||||
}
|
||||
|
||||
/// How one session of a round ended.
|
||||
enum SessionEnd {
|
||||
Outcome(Box<RoundOutcome>, 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::<Vec<_>>().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<u64, String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String>> {
|
||||
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<Played, Option<String>> {
|
||||
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<String> {
|
||||
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<Boundary, String> {
|
||||
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<RoundEntry> = 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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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::<Vec<_>>().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<String> = round.fixed.iter().map(finding_text).collect();
|
||||
md.push_str(&format!("- Fixed: {}\n", fixed.join("; ")));
|
||||
}
|
||||
if !round.unfixed.is_empty() {
|
||||
let open: Vec<String> = 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<StopReason>) -> 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<u32>) -> 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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<Boundary, String> {
|
||||
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<Boundary, String> {
|
||||
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<DiffStats, String> {
|
||||
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::<u32>().unwrap_or(0);
|
||||
stats.removed += removed.parse::<u32>().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);
|
||||
}
|
||||
}
|
||||
@@ -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<u32>,
|
||||
}
|
||||
|
||||
/// 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<Finding>,
|
||||
#[serde(default)]
|
||||
pub unfixed: Vec<Finding>,
|
||||
#[serde(default)]
|
||||
pub suggestions: Vec<Finding>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
#[serde(default)]
|
||||
pub summary: String,
|
||||
/// Id of the report doc in the session.
|
||||
#[serde(default)]
|
||||
pub report: Option<String>,
|
||||
#[serde(default)]
|
||||
pub review: RoundReview,
|
||||
#[serde(default)]
|
||||
pub tests: Option<RoundTests>,
|
||||
#[serde(default)]
|
||||
pub subject: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<u32> {
|
||||
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<String> {
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
+99
-5
@@ -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
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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 }));
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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 "<D>/console.mjs" open --workflow review` before reading (<D>: 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 <D>/console.md and <D>/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 "<D>/console.mjs" open --workflow review` before reading (<D>: 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 <D>/console.md and <D>/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 <n> --role <role> --scope-file <path>` from the arguments, read `<D>/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
|
||||
|
||||
|
||||
@@ -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 "<S>/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 <path>`. Exit 4: give the checker its `problems` once and record again; still failing, step 1 runs `list --check-failed "<one line>"` and every lesson still shows.
|
||||
- Step 1 then runs `list --check <checkId>`. On the web console, post an `activity` line while it runs ("Checking 4 lessons").
|
||||
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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(", ")}`);
|
||||
|
||||
@@ -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 <n>`, `--role <role>` and `--scope-file <path>`, and opened the session with `open --loop --workflow review --round <n> --role <role> --scope-file <path>`: 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.
|
||||
@@ -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.
|
||||
+163
-5
@@ -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 <sid> --workflow <yours> --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;
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -2511,6 +2511,9 @@
|
||||
that skips what is not worth fixing and records each skip, or
|
||||
<strong>by level</strong> (Critical, Warning, Suggestion).
|
||||
</li>
|
||||
<li>
|
||||
<strong>Review rounds per phase</strong> (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.
|
||||
</li>
|
||||
<li>
|
||||
It uses the launch agent and model the app is running, and it needs
|
||||
<strong>permission checks off</strong>: with them on, an agent would
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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.",
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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; }
|
||||
@@ -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": { "<folded worktree>": { ...setup, "saved": "<iso>" } } }
|
||||
//
|
||||
// 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,
|
||||
);
|
||||
}
|
||||
@@ -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=<id>` 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) {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user