Compare commits

..
26 Commits
Author SHA1 Message Date
jparkerweb 8ae55bb76f Merge pull request #18 from jparkerweb/feature/lessons-self-improvement
Feature/lessons self improvement
2026-11-29 10:52:46 -08:00
jparkerweb 78ea888bc7 Note the lessons-card and app-bar changes under v3.2.0
AI Assisted
2026-11-29 10:49:45 -08:00
jparkerweb 97f65edd84 Let the app bar's update line use the room the bar has
AI Assisted
2026-11-29 10:49:44 -08:00
jparkerweb 834b71e82d Fill a lesson's Reword boxes with the words Ask for suggestions sends
AI Assisted
2026-11-29 10:49:42 -08:00
jparkerweb e0f82cc36b Give Help a Review Loop topic and open it from both Review Loop links
AI Assisted
2026-11-28 22:29:52 -08:00
jparkerweb bcb6e43dbd Keep four lessons from the Review Loop build
AI Assisted
2026-11-28 21:09:07 -08:00
jparkerweb 57567d7a0b Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases
AI Assisted
2026-11-28 21:09:02 -08:00
jparkerweb d6a28b5dc8 Release 3.2.0: check every waiting lesson before approval, and tidy up and count saved lessons
AI Assisted
2026-11-28 08:22:31 -08:00
jparkerweb 1345aa0a95 Grade every waiting lesson with a separate check before the lessons card asks for approval
AI Assisted
2026-11-27 23:19:42 -08:00
jparkerweb b06a4cb4ab Release 3.1.5: start the new project's dashboard on Change project, and keep the console page itself from scrolling
AI Assisted
2026-11-24 08:23:00 -08:00
jparkerweb cfc58f5a06 Release 3.1.4: retry an update that stopped partway, and refresh the launcher's model menu and agent install data
AI Assisted
2026-11-20 16:57:47 -08:00
jparkerweb 630a1169c3 Let the lessons reader fill its dialog: lift the 68ch cap and stop balancing long lesson titles
AI Assisted
2026-11-19 19:41:52 -08:00
jparkerweb ab4e3322d6 Record the latest upstream sync in the sync skill
AI Assisted
2026-11-19 13:48:46 -08:00
jparkerweb 1616019705 Free runner disk for the Linux app build, and keep the deps fixture lockfiles under a name dependency scanners skip
AI Assisted
2026-11-19 13:48:39 -08:00
jparkerweb f2e9b8bde8 Record the latest reverse port in the sync skill
AI Assisted
2026-11-19 11:15:49 -08:00
jparkerweb fb81f80ce5 Fix the Subagents dialog test on Chrome 158: count its flow-end reading of justify-content as flex-end
AI Assisted
2026-11-19 08:40:42 -08:00
jparkerweb e5ce951b93 Release 3.1.3: the stranded finish screen's way out, and the CI and test upkeep
AI Assisted
2026-11-18 22:21:15 -08:00
jparkerweb 8658631b5d Steady the status line test: wait for the post's redraw before typing the answer
AI Assisted
2026-11-18 21:40:10 -08:00
jparkerweb 09fb4f4eec Steady the git tab scroll test: note the place after the scroll a click on a tab makes
AI Assisted
2026-11-18 20:18:20 -08:00
jparkerweb c96e1f0f52 Draw a stranded finish screen's way out when the press goes unanswered by time alone
AI Assisted
2026-11-18 19:45:06 -08:00
jparkerweb 3b09d03090 Fix two tests that fail on macOS: the temp folder's real path and the select-all key
AI Assisted
2026-11-18 19:45:04 -08:00
jparkerweb ce073cd07a Fix two page tests the git board path and the Markdown box click fix left failing
AI Assisted
2026-11-18 17:56:28 -08:00
jparkerweb 65fbd1bfe1 Move CI's checkout, setup-node and artifact actions to their Node.js 24 versions
AI Assisted
2026-11-18 17:34:35 -08:00
jparkerweb 52efac51b8 Release 3.1.2: changelog for the git board path and the installer's release redirect
AI Assisted
2026-11-18 16:47:46 -08:00
jparkerwebandClaude Opus 5.5 775b693583 Trim the console card back under its byte budget, say skills/ is gitignored in the internals guide, and record the latest reverse port
AI Assisted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:28:24 -08:00
jparkerwebandClaude Opus 5.5 cc7d89181d Send installers fetched from unreleased main to the newest release, for launchers older than the release channel
AI Assisted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:23:38 -08:00
134 changed files with 15217 additions and 708 deletions

No files matched your search

@@ -60,7 +60,7 @@ Key design points:
- **A loop stop leads with why and what to do next, in two places.** `evidence_markdown` in `loop_driver.rs` opens the report doc with a `> [!CAUTION]` box (the reason, then the stop line) and a `> [!TIP]` box (the advice); `render.js` draws a blockquote that opens with either marker as a colored `md-alert` and hides the marker. The stop card shows the same two as `.loop-why` and `.loop-advice` from `loopEnd.advice`. The advice is the failed phase's own `loopOutcome.nextStep` (one line, 300 characters, optional, only for a `failed` report that refused the phase), else `stop_advice()`'s words for the cause. `failed_words` puts the reason before the agent's summary, since a failed report's summary often reads like success.
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Reset this tab".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 23 panels (in four groups, with a filter box above the tab list) and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 24 panels (in four groups, with a filter box above the tab list) and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
- **Starting ticks are staged by the page, never answered by the server.** A `multi` row with `ticked: true` is seeded into the person's staged answer once (`seedStaged`, marked in `page.local.seeded`); an `answer` on the item would settle the card before anyone saw it, and a staged answer already flows through Send, drafts, the settled record and the reply words.
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
@@ -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 |
@@ -27,12 +28,14 @@ One row per file under `src/web-console/public/` (the games and their sound are
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) |
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
| `public/screens/cards.js` | question cards: every kind (one builder per kind in `BUILDERS`), the pager, settled and in-flight records. The `lessons` kind's builder is `buildLessons()`: the approval card for noted lessons, one row per waiting item (`lessonRow()`) decided on its own with the words its type takes, the choices kept as a draft (`lessons-<id>`) until Send, or the first ask's three answers when the card carries `firstAsk`; a `suggested` map (row id to one of that row's choices, checked in `lessonsProblems()` in `patches.mjs`) draws a dashed `is-suggested` ring on those buttons without picking them; on the dashboard it is drawn in the Lessons to review dialog (`renderLessonsDialog()` in `screens/learning-row.js`). A `multi` option may carry `ticked: true` (the row starts ticked the first time the card shows, never on a `locked` row) and `tag` (1 to 16 characters, drawn as a neutral `.pill.tag` beside the label and read in the checkbox's accessible name after the `k: text`); on a card with a ticked row, unticking the last box (or pressing a lit preset off) stages `ks: []`, an answer that reads `none`, where other cards stage nothing. |
| `public/screens/cards.js` | question cards: every kind (one builder per kind in `BUILDERS`), the pager, settled and in-flight records. The `lessons` kind's builder is `buildLessons()`: the approval card for noted lessons, one row per waiting item (`lessonRow()`) decided on its own with the words its type takes, the choices kept as a draft (`lessons-<id>`) until Send, or the first ask's three answers when the card carries `firstAsk`; a `suggested` map (row id to one of that row's choices, or `{ choice, text?, why? }` where the words go only with Reword, Reword and move or Rename; checked in `lessonsProblems()` in `patches.mjs`, read by `lessonSuggestion()` in `answers.js`) draws a dashed `is-suggested` ring on those buttons without picking them, and its words fill that row's edit boxes once the suggested edit is open (`lessonsFillSuggested()`, once per suggestion, remembered in the draft's `applied`, so later typing stays); on the dashboard it is drawn in the Lessons to review dialog (`renderLessonsDialog()` in `screens/learning-row.js`). A `multi` option may carry `ticked: true` (the row starts ticked the first time the card shows, never on a `locked` row) and `tag` (1 to 16 characters, drawn as a neutral `.pill.tag` beside the label and read in the checkbox's accessible name after the `k: text`); on a card with a ticked row, unticking the last box (or pressing a lit preset off) stages `ks: []`, an answer that reads `none`, where other cards stage nothing. |
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab |
| `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 |
@@ -66,7 +69,7 @@ One row per file under `src/web-console/public/` (the games and their sound are
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (23 tabs: ids, order, labels, diagram flags; `HELP_GROUPS` and `helpGroupStart()` name the four group headings, Start here, Working in a session, Tools and Reference, each a run of neighbors so grouping never moves a tab; every tab uses the chosen highlight color; Implementation Loop sits right after Watching a build, The git board right after it, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Subagents, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping; a re-export of `tabs.js`'s `tabKeyTarget`). No module-scope DOM, so `node --test` covers it |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (24 tabs: ids, order, labels, diagram flags; `HELP_GROUPS` and `helpGroupStart()` name the four group headings, Start here, Working in a session, Tools and Reference, each a run of neighbors so grouping never moves a tab; every tab uses the chosen highlight color; Implementation Loop sits right after Watching a build, Review Loop right after it, The git board right after that, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Subagents, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping; a re-export of `tabs.js`'s `tabKeyTarget`). No module-scope DOM, so `node --test` covers it |
| `public/tabs.js` | the WAI-ARIA tabs shared by Help and User Preferences: `wireTabs()` (buttons and panel links, roving tabindex, automatic activation, `aria-orientation` switching at 720 px, an optional `beforeSelect` guard) and the pure `tabKeyTarget()` |
| `public/prefs.js` | User Preferences' PURE rules: `PREFS_TABS` (Appearance, Agents & models, System, Sounds & activities, with hints and the sections each holds), `prefsOpenTab()` and `prefsResetScope()` (the looks keys Reset this tab resets per tab, or null) |
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, the pull-request link, and the current branch's page on its host (`boardBranchLink()`, null until the branch is pushed under its own name); the next step (ten rules, `nextStep()`), the tab that owns it, where it sits on the Save, Share, Review, Tidy path (`PATH_STOPS`, `boardPath()`), whether the task card carries the commit table (`cardShowsFiles()`), per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
+3 -2
View File
@@ -16,9 +16,10 @@ 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` or `remove`). `__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`) |
| `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`) |
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
| `agents.mjs` | the rules of `~/.plan2code/agents.json` (see "Agents file" in [the install file](./AGENTS-architecture-install.md)), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` |
@@ -40,7 +41,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| loop setup `phaseStrength` / `strengths` | `loop-setup.mjs` keeps the per-project toggle and, per spec folder, a list of `{n, name, strength}` picks, pruned as specs finish and phases move (twin: `LoopSetup` in `loop_driver.rs`). `loop_driver.rs` starts a phase with `AgentManager::start_phase_on(prompt, model, effort, env)` and sets `PLAN2CODE_LOOP_STRENGTH` (thrifty, balanced or best) in its environment, which `cmd-open.mjs` reads to give the phase's helpers the same Helper strength line; a retry goes one step up with `models::next_strength` (Rust twin of `nextStrength`; a Match my session phase stays) |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
| `learning.mjs` | Learning's core, shared with the `lessons.mjs` skill script: the one `learningState()` (not set up, off, on, paused, unknown), the repository key, the tracked `.plan2code/settings.json` read, and the two stores on this machine under `~/.plan2code/learning/<key>/` (`pause.json`, `waiting/<id>.json`; `PLAN2CODE_LEARNING_DIR` moves them for tests); `learningScan()` is the dashboard's `scan.learning`, read without pruning. Never writes into a project |
| `learning.mjs` | Learning's core, shared with the `lessons.mjs` skill script: the one `learningState()` (not set up, off, on, paused, unknown), the repository key, the tracked `.plan2code/settings.json` read, and the stores on this machine under `~/.plan2code/learning/<key>/` (`pause.json`, `waiting/<id>.json`, `checks/`, and the append-only `follows.ndjson` that `followCounts()` sums on read; `PLAN2CODE_LEARNING_DIR` moves them for tests); `learningScan()` is the dashboard's `scan.learning`, read without pruning, with `nearCap` while Learning is On and general lessons reach 22 of 25 or an area file 30. Never writes into a project |
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
+10 -3
View File
@@ -17,7 +17,8 @@ plan2code/
│ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── shared-references/ # Reference files shared across skills
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review, test)
│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose, pr-prep, test)
│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (dashboard, for the lesson check only, init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose, pr-prep, test)
│ │ ├── lesson-check.md # Learning: the lesson checker's brief, four tests, verdicts and reasons, never edits (dashboard, implement, implement-review, review, quick-task, xray, diagnose, test)
│ │ ├── lessons.md # Learning: the fixed words and when a skill runs each `lessons.mjs` command (dashboard, pathfinder, plan, revise-plan, document, implement, implement-review, review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype)
│ │ ├── review-in-build.md # The review a building skill runs on its own work (quick-task, implement, implement-review, review, finalize, dead-code)
│ │ └── test-runs.md # Choosing what tests to run: targeted per task and phase, full suite only where the plan puts it (document, implement, implement-review, quick-task, review, finalize, pr-prep, test, dead-code)
@@ -118,18 +119,24 @@ 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` |
### Release channel
Install and update follow release tags, never `main`. `release-app.yml`'s `publish` job ends by fast-forwarding the `release` branch to the tag it just published (no force: a tag not ahead of the branch fails the job), and the README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`. `plan2code update` installs the newest `vX.Y.Z` tag (`newestReleaseTag()` in `src/launcher/plan2code.js`, using `latestTag()` and `runLsRemote()` from the copy of `update-check.mjs` beside it); `--main` installs the tip of `main`, `--tag <ref>` any ref (how to go back to a release); `--main` and a `--tag` naming a branch always pass `--force`, since unreleased work keeps the last release's version and the installer's `Already on` check would install nothing. `plan2code uninstall` runs the newest release's installer the same way, falling back to `main` only when no release tag can be found. The console's release check (`update-check.mjs`) and the app's notice (`versions.rs` `latest_tag()`) use the same rule: the highest plain `vX.Y.Z` in `git ls-remote --tags`, peeled and pre-release tags skipped. The app's Update skills still pins to the app's own tag.
Install and update follow release tags, never `main`. `release-app.yml`'s `publish` job ends by fast-forwarding the `release` branch to the tag it just published (no force: a tag not ahead of the branch fails the job), and the README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`. `plan2code update` installs the newest `vX.Y.Z` tag (`newestReleaseTag()` in `src/launcher/plan2code.js`, using `latestTag()` and `runLsRemote()` from the copy of `update-check.mjs` beside it); `--main` installs the tip of `main`, `--tag <ref>` any ref (how to go back to a release); `--main` and a `--tag` naming a branch always pass `--force`, since unreleased work keeps the last release's version and the installer's `Already on` check would install nothing. `plan2code uninstall` runs the newest release's installer the same way, falling back to `main` only when no release tag can be found. Launchers older than the channel (and install commands copied without `#release`) still fetch `main`, so `install.js` redirects itself (`redirectToRelease()`): when npx fetched it from a commit no `vX.Y.Z` tag points at (`fetchedCommit()` reads npm's hidden `node_modules/.package-lock.json`; `releaseRedirectRef()` decides), it reruns the same options from `#v<newest>`. The launcher sets `PLAN2CODE_INSTALL_REF` on every installer run (`main` for `--main`) so a deliberate ref is never redirected, a checkout is not under `node_modules` so it never is either, and anything unknown (no lock file, no network) runs in place. The redirect lives on `main` for old launchers to find, so it must stay there. The console's release check (`update-check.mjs`) and the app's notice (`versions.rs` `latest_tag()`) use the same rule: the highest plain `vX.Y.Z` in `git ls-remote --tags`, peeled and pre-release tags skipped. The app's Update skills still pins to the app's own tag.
### Agents file
`~/.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.
@@ -34,7 +34,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
| `ui-prototype.mjs` (shared, with `ui-prototype-round.mjs`, `ui-prototype-page.mjs`, `ui-prototype-drafts.mjs`, `ui-prototype-block.mjs`) | ui-prototype, pathfinder, plan, revise-plan, quick-task (ride-along) | `sweep` (drafts older than 30 days), `new-round`, `assemble` (the page from `round.json`, the variant files and the shell in `references/ui-prototype-shell/`, images and fonts embedded; exit 4 `round-mismatch` when a drafts round's `round.json` names another `name` or `round` than its folder), `check` (the contract's rules, the three image rules `image-type`, `image-size` and `image-missing`, and the size ceiling), `open` (the default browser), `read-block` (a pasted choice block from stdin into fields) and `save` (the pair `specs/<spec>/prototypes/<name>.html` and `.md`, then that prototype's drafts removed). Writes only under `~/.plan2code/prototypes/<project key>/` and, on `save`, the spec's `prototypes/`; never writes project code, never opens a page outside the drafts or `specs/`, never fetches anything over the network. The helper modules are imported only by `ui-prototype.mjs` |
| `lessons.mjs` | dashboard, pathfinder, plan, revise-plan, document, implement(-review), review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype | Learning's one script. Every answer carries `state` (`not-set-up`, `off`, `on`, `paused`, `unknown`) and `active`, decided only by `learningState()` in the bundled `web-console/learning.mjs`, which it loads at run time through `consoleModule("learning.mjs")` (exit 3 `no-console` without it), so the dashboard and the skills never disagree. `state` (the state, since when Paused for you, the waiting count, whether AGENTS.md exists, whether on the default branch) / `switch on\|off` (the team switch) / `pause on\|off` (Paused for you, refused unless On) / `read` (the lessons for the named paths and the branch's changed files, `marked` when their About files changed since, with a `run` handle so a later read hands over only new areas) / `note` (a lesson, an area, a doubt or an AGENTS.md fix, checked, then held as waiting; nothing while Off or Paused for you; a secret exits 5) / `check` (the secret refusal and the email, handle and person-name flags; reads only) / `list` (the approval list of everything waiting, new failure log lines, the first-ask card) / `decide` (applies the person's choices, or `--first-ask yes\|no`; a test map row fix carries `row` on its list item and is reworded with `row` or with `after` as its one table line, read back by `rowFromLine()` in `test-map.mjs`, and every row is validated and secret-checked again at Apply) / `log-lines` (failure log lines added since Learning was first switched on) / `areas --suggest` (first areas from the test map) / `report` (lessons per area, the oldest, marked and gone ones) / `remove --confirm` (deletes every saved lesson). Writes only the project's `.plan2code/settings.json` and `.plan2code/lessons/<area>.md`, the pointer line and upkeep sentence in the project's `AGENTS.md`, its failure log lines (moved into lessons, marked `(kept in the log)`, or added on a first-ask no), accepted fixes to `AGENTS.md` or an `.agents-docs/` file, and, through the core, the pause and the waiting lessons on this machine only, in `~/.plan2code/learning/<repository key>/`. Never stages or commits |
| `lessons.mjs` | dashboard, pathfinder, plan, revise-plan, document, implement(-review), review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype | Learning's one script. Every answer carries `state` (`not-set-up`, `off`, `on`, `paused`, `unknown`) and `active`, decided only by `learningState()` in the bundled `web-console/learning.mjs`, which it loads at run time through `consoleModule("learning.mjs")` (exit 3 `no-console` without it), so the dashboard and the skills never disagree. `state` (the state, since when Paused for you, the waiting count, whether AGENTS.md exists, whether on the default branch) / `switch on\|off` (the team switch) / `pause on\|off` (Paused for you, refused unless On) / `read` (the lessons for the named paths and the branch's changed files, `marked` when their About files changed since, with a `run` handle so a later read hands over only new areas) / `note` (a lesson, an area, a doubt, an AGENTS.md fix or a `tidy` proposal (`--change merge|reword|retire|move --targets <ids>`), checked, then held as waiting; nothing while Off or Paused for you; a secret exits 5; a lesson may carry a literal search, `--shows-in <glob> --match should|never --text-match <text>`, its glob at most 120 characters and three `**`; a correction or convention needs `--why`; an inferred lesson from a read-only skill is refused) / `check-input [--tidy]` (the waiting lessons for the lesson check, oldest first and at most 10, each with its search already run and its named files hashed; a search looks only at the files git tracks or leaves unignored, listed once per command, so ignored build output is never searched; check files over a day old are pruned first) / `check-record --file` (validates the checker's verdicts, four tests of Pass, Doubt or Fail each with a reason, and stores them on the waiting items; exit 4 names the fault) / `follow --lesson <id> --skill <name>` (one line in `follows.ndjson` per "Following a lesson") / `tidy-input` (every saved lesson with its follow count and mark, for the tidy-up coach) / `check` (the secret refusal and the email, handle and person-name flags; reads only) / `list` (the approval list of everything waiting, new failure log lines, the first-ask card; with `--check <checkId>` the rows carry the verdicts, the outline and the how-checked line, `--check-failed` says why the check did not run) / `decide` (applies the person's choices, or `--first-ask yes\|no`; a test map row fix carries `row` on its list item and is reworded with `row` or with `after` as its one table line, read back by `rowFromLine()` in `test-map.mjs`, and every row is validated and secret-checked again at Apply) / `log-lines` (failure log lines added since Learning was first switched on) / `areas --suggest` (first areas from the test map) / `report` (lessons per area, the oldest, marked and gone ones) / `remove --confirm` (deletes every saved lesson). Writes only the project's `.plan2code/settings.json` and `.plan2code/lessons/<area>.md`, the pointer line and upkeep sentence in the project's `AGENTS.md`, its failure log lines (moved into lessons, marked `(kept in the log)`, or added on a first-ask no), accepted fixes to `AGENTS.md` or an `.agents-docs/` file, and, through the core, the pause, the waiting lessons (with their verdicts), `checks/` and `follows.ndjson` on this machine only, in `~/.plan2code/learning/<repository key>/`. `read` also writes there: a marked lesson whose search no longer matches becomes a waiting doubt. Never stages or commits |
| `changes.mjs` | implement, implement-review, quick-task | The sign-off page's Changes tab. `start --session <folder>` snapshots the working tree (tracked, modified and new files, never ignored ones) into a git tree object through a temporary index and `git write-tree`, so the real index, HEAD, branches and working tree stay as they were, and writes the tree id to `<session>/changes-start.json`; a rerun replaces it. `diff --session <folder> [--cap 524288]` snapshots the tree now, compares it with the start tree and writes `<session>/changes.diff` (unified, `git diff --no-color -M` headers; over the cap it is cut at a file boundary with a notice, every file still named; a file that may hold a secret keeps its name and counts, its lines hidden; the counts of hidden and cut files travel as `# counts: <added> <removed> <path>` trailer lines (tab separated fields) that the page applies to files with no lines of their own), printing `{ ok, files, added, removed, truncated, hidden, file }`. Exit 3 for no repository, no snapshot or a snapshot git no longer has, 4 when git cannot snapshot. Work done before `start` never shows, and nothing has to be committed. The notes for Implement and Quick task (`notes/implement.md`, `notes/quick-task.md`) say when to run each; the page draws the result as a `diff` doc block |
**Shared reference for `lessons.mjs`:** `src/shared-references/lessons.md` ships as `references/lessons.md` (through `additionalReferences`) to the same fifteen skills and the dashboard. It is the prose half of Learning: the fixed words (Learning, lesson, waiting; Not set up, Off, On, Paused for you), when a skill runs each command (Start, While working, End, unattended runs, Learning off), and that a failed call means one "Lessons could not be read this run." and carrying on without lessons.
+3 -2
View File
@@ -90,8 +90,9 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md),
| What changed | Run |
|---|---|
| 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` |
@@ -148,7 +149,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|------|--------|
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
| `--update [--force]` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. Compact output: `Updating <old> -> <new>` from the record's version (or `Already on <new>`, which stops unless `--force`), each piece's own output held back (`captureOutput()`) and shown only for a warning or a failure, one summary with human piece names (`PIECE_LABELS`), the release notes link and the restart hint; a failed update also prints `plan2code update --tag v<old>`. A failed update, or one whose desktop app was kept because the release has no app file yet, puts the old version back on `install.json`, so the next update (the app's Update and restart included) runs instead of stopping at Already on. `plan2code update` runs it through npx, pinned to the newest `vX.Y.Z` tag the launcher finds with update-check.mjs's `git ls-remote` pick (`--main` takes the tip of `main`, `--tag <ref>` any ref, `--force` is passed on; `PLAN2CODE_LS_REMOTE_FILE` replaces the git call in tests) |
| `--update [--force]` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. Compact output: `Updating <old> -> <new>` from the record's version (or `Already on <new>`, which stops unless `--force`, and only when the installed command's `bin/version.json` agrees with the record, so an update stopped after its skills step installs again), each piece's own output held back (`captureOutput()`) and shown only for a warning or a failure, one summary with human piece names (`PIECE_LABELS`), the release notes link and the restart hint; a failed update also prints `plan2code update --tag v<old>`. While an update runs, record writes keep the old version (`recordVersionHold`) and the new one is stamped only when every piece is in; a failed update, or one whose desktop app was kept because the release has no app file yet, leaves the old version on `install.json`, so the next update (the app's Update and restart included) runs instead of stopping at Already on. `plan2code update` runs it through npx, pinned to the newest `vX.Y.Z` tag the launcher finds with update-check.mjs's `git ls-remote` pick (`--main` takes the tip of `main`, `--tag <ref>` any ref, `--force` is passed on; `PLAN2CODE_LS_REMOTE_FILE` replaces the git call in tests) |
| `--uninstall [--yes] [--purge]` | No menu: confirm y/N (`--yes` skips it), run `uninstallAll()`, then ask whether to also delete `~/.plan2code` (`purgeData()`; `--purge` says yes without asking, `--yes` alone keeps the data). `uninstallAll()` is driven by the pieces `install.json` records plus a quiet probe for strays (`UNINSTALL_STEPS`, `UNINSTALL_PROBES`), prints one line per piece actually removed, falls back to deleting the `plan2code*` folders under `~/.agents/skills` when the skills CLI is unreachable, and removes the versioned console folders and `console-dir` (`removeConsoleFolders()`, stopping a running console first). What stays in `~/.plan2code` is listed by name with its size (`listKeptData()`), and the run always ends with the Removed / Could not remove / To finish block (`printUninstallReport()`). Deleting the data also removes the app's webview data outside `~/.plan2code` (`appWebviewDirs()`, `purgeAppWebview()`), and a running app is named before anything is removed (`appRunning()`). `plan2code uninstall [--yes] [--purge]` runs it through npx |
## How the Installer Works
+3
View File
@@ -7,15 +7,18 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch
|---|---|---|---|
| Activities games | `src/web-console/public/activities/**`, `src/web-console/public/tones.js`, `src/web-console/public/music.js` | `node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs` | no |
| Launcher | `src/launcher/**` | `node --test scripts/test-launcher.mjs` | no |
| Installer update | `scripts/test-install-update.mjs` | `node --test scripts/test-install-update.mjs` | no |
| Dead Code script | `src/plan2code-dead-code-scripts/**`, `scripts/fixtures/dead-code/**` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-dead-code.mjs` | no |
| Update Dependencies script | `src/plan2code-deps-scripts/**`, `scripts/fixtures/deps/**` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-deps.mjs` | no |
| UI Prototype script and shell | `src/skill-scripts/ui-prototype*.mjs`, `src/plan2code-ui-prototype-references/**`, `scripts/fixtures/ui-prototype/**` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-ui-prototype.mjs scripts/test-ui-prototype-page.mjs` | no |
| 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 |
| Bot | `plan2code-bot/**` | `cd plan2code-bot && npm test` | no |
| Web console page shell and styles | `src/web-console/public/styles/**`, `src/web-console/public/index.html` | `npm run test:page -- scripts/test-web-console-page-layout.mjs` | no |
| Shared code | `install.js`, `src/web-console/public/skills.js`, `src/web-console/console.mjs`, `src/web-console/routes.mjs`, `src/web-console/static.mjs`, `scripts/*-helpers.mjs` | `npm test` | yes |
| Docs only | `**/*.md` | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` | no |
+1 -1
View File
@@ -1 +1 @@
U0VOQwFXeZZ2LQjdLUSSPDZ4vtw/FiDmfXw9fG8bM3nucaLO+T9XQN9U9t3VdtYnGqX/wKp/UefGXZmTT9BatYKzavI8O9yxDFbOkhu2eA8rQ+LfJ3J7H94EeD9GdEoPvoSaW9GJqyBk/zTVcqapukaBllICd/iouX0PzNk0rMOc7yfhsbWuWsYb4q9E/qn5G4SI3n2zOvsaGZqppJPVQMxWAJQvrQhk6VL+8l48ftO9L02hieVdDs8bmLqhTkF19FQkT1DzGuESlMVEcQP546QtAqtXOpTnO7twtXsCpBOguZ/jLArPFh8lAjMsM3/0LQ8WV7i98zKRyCxELlB+BYwz25BRBIUj2uJNRYloXeLuEyVqS+qC/SScOOlY5Oh2oyFcxyZ8K/ESBKai9djOB36/QlrYD69PNOv2Sb39oHcCObPUofzFSGAVydCtQOsc//my+S/aPkNhTtQEsCAwws5AuCPpuQ1UCUHjkNuWfYWOkOGRNHnlbnLjdKTjm/4ggZQYb4jeGAWqPg+da/ZMSn5Bj+ZTiKOk0d4FPQOwZQlkg6vhdNKYRCJRuni2UC3YaY7dLvtKEPcUpjvI6dK40xt3Lt+DY0i+6r6PcUZRVWdq39SyN/nugd++xTRVozLA80/vBgkgWS46qC2n4q3dXZuz2oNOVz5CnZvh7lUkO46/fUjmgJSAJIXlbd8xsuioXd0bAZT7KwYSYQmOQ30QFO7icfxVp9O2HvShP2y7uNVjArC7Ifp2RiHfVT0yaabsai9huP7enYyyIOL8F/klmiN81Zytcp+CT7mBjei6by9Y4mpl9EnVOg5M1THZua5rjxGatG6QDGtjQRFtfg3zGI7LZjpYZ+GpcOdLEQXWUt64RjvFryQnbgioZw0dzqwQLMOmcLTr/0wN6CcNBoKywlDpWD3NdU2J0xfwU+bAA/i8bvWNx0PrJRWXIMHqjOBnIAQWjQ7At1ReQqg+zu8Du2BshrZARUXIzQu9ronANVTaOASe+6KW7rSseqzyX21xsiNppQr5TcPfl07Fg4vhfSvYbNO5KhNuCHzrvvjqiMZGxIAvj5c5PBnoDuVIyp2cwrETGXfCxPHew1ibzC2oRT0dQ3ObR044uOYJ7/prxrccFVrMCDWl8UnWDu5Vj07ktOfS3c7uNZjekvrikA8QPU89Tb1DlWAXpsBb9Kqio5Z+x4BU26FA/bmGPDhWk2QYgPGahpknnVVgBSrOEf7o9JNmw2ARAncIJf300FYJNY2VO8cJ0g4FcRhuMyxFVD/aoVgkVlWDIypJCLacufkCKqbFLlzLUDj9QAeQkMCQwsIDfWOZsF/dlpPTsXUxgp3jxCuXJRr47fkfXxnemBimPtDWf4oqjm3LRE3alFYjT21EeDOrA0Q05JKNWf6wQkZf5beZsk6p14TbkhE91Ip8s8nsFicgK2gAR7LqEoRyNqhVYTrubcQ0b4zeMr+lg/g/NJUAgqYNk4UYDMV4oJJjaCYJ0tABipaafx3eatd83F/zXnpu/F1QlbAgPtuPLf/m+ZR7GWRWRAc89FVjgZec57ST7wSi4LH/15q56B3Oq91DjXWqHzqXYDJROK5iTrxJxGdXb98L1csyc3bSddsxIOKgL0Fw9P6+CMq7PMsw+ZhpMohwM+HQz5UUAvKJaDx9tK9nqZcNF9mYLNAZcz/QCBFkkdxdCLyu0gkcQwaTHmFCcI1ak6WE5Lb0GY8FwuAEMRyqFlzDbVeEYmVw5DvJZ7fkE25HFV/1kvn7/PNlpjeKlSDtdwAA40PUGH4o7N8DWFUACJFuFPJUJynBeCiT0pPX0PEJkvRluj6BB3tHpRTNjy0CTbUUU3O9sSN64Au0ooEHY8wL1VVHZCjHzgGrPV7qppd0KlvSXKZ6mlmFjmI743jzQn+AV+XCwsxIwa3aCLdGDB70mE/m4yrsMobZVL1gOL1gG3WIQu1ShTFxxb8u8/57TvVYKonFLU8Bc74HEYhPtQiE9nI5nGM59Z6KXXURXnmbUNjk/sQu659C2i7jf1F1dSv8ARCmeGvLL7waJ3iAdTn9RYRqxZKPbSOWqh7tAXzkTeaalA54Xw+RNq8QNylJsTYp7/DxyEJZs1MF7ILxZW2Adxud6TnhPXH3r4/ef8LnQHJjVXmcvQcIpnFrkpkeOFsZHYZbsOaPtxO80s77FwiAnFASTxOQz5fv4/SLam/+hoqWDXni42s42Bs1rKg5HloIlsoL28KL4hBeXdwA1IJJH9crmvOhMqPT4dXbHUt5ixs7CcNzHuO9YqcfcktCpi8RJ/0xKgSKh5w51A+GpezVWlwr6GulZADmL6XFNFfiV9QdYDGdcQRcitlpPMAGsvQ+Oed2n7UWuQfrTWFCqBSV+CAkRjgkGk88Oh/MPqBjsYGzpncWrm9bIc/Ub0Puewatjoj7P4c81OZ1eVwMdrXZFWA3qAtW1sTgf144rqkcRf1bZyt0KmCSvLAmrLLyt6BQJAP3JpHyItqkALB51FhYioG2eYlrbI5m5UdNRG7zqTnsko+us+hmb/DZEAwVh0vgwTnsKBVyasItIEznT6hYBOF+63tBOlZWDZJcp7ihhoYSgdz4CZ4pRRSC7fXNqGYGtBd6xbaweFzp6q7VFs7PtvQJuel0WST2GynOoTH+KLanmXnNTD05P9aMip0QJKHUIH8SlQXZn1OsGx31eNyUCmfauyMpc95hxOTu+1Qg5vnZoREX5u57A7DjlMrhKw0wNuj/FuoiLsYw6neLANlTHiJpHaKr2OecR6dRDgzF1uXrJXIhiv9kUM7nOLj4159vBEcgnZNftPXGrcuAwlXcNDFMP44DdXWiD/EkZkI1niksGB9g1J5WMM0ph7Zta4Irn32DkisYydP5oblSmdEB6NNKpOqYeVT+Gsz9Hc32NSPWhiRo4UU+m4rHvccIP35eRCsTFJjeqK578TLC+n9mIdBSahOzHRkJTV0tZydKMsznYuBnb5FTtGW7IzNVfmov5ErJkd3ngeShna19uFG5hkAuwwbx2ueUc9HiMvTlChd5mSrG+NLzXxQxgwWx2RHqMeivBqa0q0a1c/D9fj1LA7L04cnAvMLdLZM/qjNQMIB73udddnATpzmDsVQXW0vbJm/rnQDNUUQmzW4r26mYlPL/xOOIi+17RQKrULGM5ouC80nbXrwn+fH6uJfd9Ub3xkjM6ddqcU7c4r6I/BjRYNc9b31U6Kw395LqtsGyP5m2fjiROM8ddgNhWwVttGLoJ/rl3/eIkRx4Hrx2WISYiUaN4ZleIeBWHTI5uSj4iNEsaBkskZ3HXvpb680bzHAe85a47sN6ncE4X3IawdIvH5ywIpIcku0xj6LlUccgAtZpxO9aXM0d0Dmdb3vKl4QyIB1vmuUkltwBqDNRGtNtMXngP5e/hPNaEE/TCPB69gp177OC/r1GnIrCZSQGou1tCugXqkcfT9uhwCP4eBFpzz/qFM3bi9TArSXYgyuf8fAM0dVsbpmBgp0nBdNrla3/d4SQv5hQ5fLLfv1An6wzkBdM+jj/Bl+W3B0kOWhzvYXR2/5VO3RwuEb8bQgNvNgu7xePdtjwLYFdIsmaue6jTriVeaW3O6rvRWBdeGKhg/a5mVjESfSjI4/YZMIgnbUHrQyO7IR4gV79sKVugDJ/KpAEYDFqKbm0zJf6J1BTqn03Ru+Xy37xgraYOwPByVCM8PbCOxel9RtOeFx33foDEf7+DKOstrS889srVOJpTUY2/kdKt+lDFX1hEm8H6+SAi/ZNU64YMP7qINPBYZIKBDtgpruyGejz8TsxK22knRXL51IAC+eaBzpYo4zL4APio5uEw6jLg3ti7FtOZU76CHzWnfd+30vO0crDbmBK9uwZz6SeR5uBbnr4E9/xU2CuAkV1zKCUBVzJR2dzl95e1bdgHl0s6Qjd/H0RHocvgK623TpFQNHO3lZMAxPw7xR/N+iXvw1UwMChaFLxZMjRtGVKm7aJixsmT9/MoPgWi2OR/ubeYr8nqkVbGmgbQqLrBum+QsZAEW1nFe5g+tsR4NuT0VFDot0gIOVL1Bktk5BoBkPb6yRGXiUJjyWG7ylmwOiqQ5Y7Kvp24j+PbS2XP0ZYSsAiqoSPfl+GtHbTewg59hjVQo5yy8CkZRZCTD1AE+Uf+6H4BG8ZAgC9OcT63qYZqGOi34HOX8B4Y+U19C/ZTRCRf2fUuS2cDhNR4bE9vjxTliZDhsUw7eKFgD0DtTaNZ7X/uSrboyDDudQpRf4vi3Uz9b9PYsMuPt0qDAd3Z2bjkz5GVFnm0Ig2BiRxZ10G6Lm0WeWsqiZiLsfJut6sGajgeayXJlNeP+mvBF36XrVT92j/116WjCzRSsgWRyUZnidgax0A1O4ck3aagka6jJxwA4+MBmEdUkseZLEt8hny/uJJP5wiF+uSx6xer9mkGrvMYrL1zF7JXnPM338xwrS7GCy/H60TRWrnlqV9ZJsWJgZtdecWtp5qFNZQ6pUW/zJlzjDMeMXONAuWdqZKqZj0VC9pW3WkgO/AoObpIPwShi546jr6xOesR0Qzn4oWAwtdBDnuj487E3r/0pIa7H+vnkrcG1cdJPXoifna+O2U4ejWy60zdDtG4NO7Y8Qq8osr3o+BjAra/1ddgOaaLxvV5Sg0wALzkQLTPmO5kwRwNJoRlWyrA5nEte53vfZ3rkU6cg3jw6G/3kGRhdCdWbzfXlOriojszcV8Tdu0Xi1ThpRq1tFJQmnA1nQ8pk3LisntnT8EC+71fpBHHA5z7GOeyStFweJkoFApSerfe3ZOc62sdE4Nr/kgs3b9BPd+Fpd4J7xMeiC3XMeRB6jGAQES89ghu7iSxcGv24emn42h89mstSOT1m+6Jc2WOuhI0djyVaxbMUOKdfoPAD9uKAcdtt/x39Rlad3PA3niLdOwZb6DMWX7+V23N+1OAgUon0bvGhlc3BtlhLQhERg19/0eg5UwJluGhgLH/pROwz+/fRgzf5UOXmoZZ9DLine truncated
U0VOQwEFJpExmufZ7/oN72H5kVdq885u/hNYDc46x6xuOJTrhD8NazvJseXfERYiTRVYpH0nQYkSGppY0m3aK2Ykt+EWExil7v8pHZAr29znkuDrc4T6PBCbcqXoJNoHSMgWUsbaQw5LfZ5LNsJHqhSMeEHzzPNYdKrVrjcTGKWIppp35poHrTj8qc0BFVu+g5sHD2VhcsxGuMiI3OZ2y3hvYhwAyNCi8Ig5gT/W65LDIIY+u+n6vopbpXvpm6wrmIMhSOiMDdZvGtUndGRJfMH4JfugcVdZj9skn3cKqRjy8dVNcFiHnN0Sm2AciPo2CdXboVx+oTjmKioH51VhKwWVoV7AxLR97A8561HDVpnbYAZpKXx9O3VhyFi+foiodSrIBNgdumkkKBXSaekVyw55Y7aMm4pMKCMmGGexmv5RN+sDNpfOF3bx2ZFIMpyei0RvZTXm4j56H8zGDXTGGQwPGSJPOCvDShh2UkbEjA4DUBL46sFRSBJqXFIppDB/A3xh9BnjkBgJssYYMKYDBW6J0BqCkP87LRuEt377HoBwv++l+ZjuLYM+rPXo3w1Mt8Nb3iEVuX0RO4IsRSaf0SBXXtaZpO6PbdINJxcqkKQjXlhEdUHANuH5/xn8kh5xZEqiPmicAivq37uJBwD06dcUVmBxzAy1krcS2QtvedqOOYkw6tEwAxhGJLtl5JAE2ccL22s4TQvDoPWE2XmWORi2KevNZBG4wwBnr2UFCShJdUoFblP1jB60P6ajlkkx44ma53qExhcXNL6meZ8tKistSbG6HuCMfV51WPXlXMtVpQWKJQDfGorLLVjBPQND/T4Zr5BJULP+kFd02txovD1FBZg4n99pKxvn+Yc7Ks77OTxn/ya8liAyyM5JZwJopkifoGNGeqtRpIIPt2xbcCW7mMyfP9bt0a9evYOOZ1VyOdFUjzm3NAEGVW4v4jzQS2wf6MnXpS7YH57Jtc616MOAihkz9gncoXEf0Vc5rJWFATk898QaL0I4dAfKTf/yQ6GToZxtDoAfCd4BGph9rSeDexvQZgbnvRggOooVRBNVchvjKQORTN5hKIqZp5jWY3zFaZSzBPyV/pJC3Z7l6Dz1+GUlxry+S6ziaxINU7yg7DvfzDOVTKpOK/YymQHoimBQuUU2eC+h07qOT/U04PqWuMYdLJPHwgSvdClNjsNdqgAZV6BfNtBNuYJBi+7y+ibthpGd/nyQ9pJHOksEBeTfXJ0cF4qQ2LnNs5g5d1Oep+fDQ5RusJoqYZw0rF9UWI2IM63qCIADaycJM6ihSasHSNExdvJT4QWLGd3WwR5c9j+E6PlutGjMHoYPsA6yfDxBvoeJw683kgwgFc0VXwRBR1Xwl4/xdoKv+W+2azpOeQWNBjqsw8LeQmsdLXIfBloN3C9zhNf4fAgYFsi5JVNlVzYi/P7eTNKovqhfaRoTEWEmUq5NkOqYZsW2H2LyKT3bsWHlDZVIEDREhpUr24wjE34SA6NxtNXJGLriFpPI7JBbs+z7V+Ejg/0R1DBTMff08ludSB2+92EA+LQcAcbg5Ffeyc1/vs/APUljaVF9JehAhFKScBKvK7Ci7lrAvQ8826ujE65q3Fflkr8do675+rrtyq/jYbymYzBzi/qkJt9mi+EFrcJXh3ly1F/zuhCe9dnuQ2bT/tw1t5P+wuwQRPrpiufayfSJKDTU8kOyX5ZgfcnToPKvK0RDbmxpI2QiFOCdj1Bedz/bTyLPj2OxOp9ZBm4hM9f5CuGfTAKTNIkNbl3gqWJNuR5EVY46+x0EBRP9vWsK03FF5gOi08eqmbqHZwxiBqmj94hb/j1L/0sPZSqJVJGfNWPf4n7cNTwzegEIcqMYXglUu+jDwjG5vnEKwH2j9RI064hvjgKxyuTDRIRx41b+gMT0ItgFp9LjW4ZaOHdtb4dJVYK5IlahztiO3wItXpDGHUTBkJm2mBuBv3htxtEIjQanz0Xgod9p+MkVhPOmezksws8yDll6ELlpW7QpAT5/uQFbktZFSDV/VnLv8+WRQdeUejxY71sFq9PJMl1pa0wj4ivM035O+LP2p67U+QYZgmPrpw5g64ylYITtfS9BaPphAntlX0pK4PFU6sj0GyveiCmXMwYNihcCWmhLDA6JEjg/86oaIPkvPZ0W+QcUnGGh87TOANSptzMDhk9ypLe46cOO1IGjclHPsgkqgKl/3zPYCB5FmLLsmPHRx6drgNbIGeMGavn4tbaQCvvZt7oWyPnG71zeQ36anaPg0annlcACxQdP6Jw1bVijPjRzX0k/Xx+hLoydZqiIwRh9ffBBLxP8ddXfLdZd+RhRPhfaY2A2EzDIvFl/BYf1uNi3SeeC4x5CV8JW2gHpwYUjkyWvNDs9YH4nE0uZ9D0WsR9kULGz1MCX1muS1gHOP4TP41kQ8juKPOJbcbZlFEiV1A/ZVfJDCI8DiH52lanGjEVvoelVWtqcrmRHEAivbS9csKmE663EF52OpSUcwvynrJhZbmld0L1QjT9vPKokG8XMzvg0US/IxmbncVh030rsIqTOfTXpiqxfFDuOV+ACNA5flTN0S1V9uXkKM7LSDMoSwGCihAdPi8hO0OuHpAfSxmN2l6DyTue13xvFBe21JZDllOUP8QqcNxFZzLDQXyaP0ZNPkLZpJWPyYAgE4mqF8w+/qMO9WCXOqB2z23xiNT9qim5UvvfK2B5r8sIDELM0XzADAH/PiCWsFoiG1aWqpYFA9QvjSwuv+Biq6UndTKXWaF6GCxm+rNCEhZagrc5kpyal404YX1E5xiiFh5CAvi81b9lKDd9JU/DRLcf+jf2M+oJYS1qyMY+VDWZtDQkg3bqdqyjMu+L5WChGcO687ko/wV+hN4FpQHsVCRQGunkjkJbAzYBOhnF2LXc/dNnZMeNQ311SRGYdrNk8D7/N7vfseGzFfqz59fkkmrm2HnnPyyowZ0oiOlDqsNK5oihzbQyzAv2kHMRHMOgSn7ms5xHoU7hvMAxgG2WBkC8Ef44noz318yy3Mqt8ujeYJODp1xF3bZGoWGALbNfgkBD53k8pcAtAc3dwWe5OJo2P5TLsFVCPDppW5tqZx33uep/GG/9cQsrummpxaJS9r065wa66LMv8SfF0S7ZJWavSfGXZv1L1Jhlt29bOITwCF2cGPJjMdWQ+eeqiA3dhc8sSZJkO7eWpXW42BAEND9P/lptAP0EEnDTb/e8e8YD9x2pbixSrlN0Pwx9mjDRZfPV7JqlQnA3TVw8d5df3WUr6qlTNBQNfK4fzy93ivqodRmUSYtagKVQ+1KCYeSXrPjW/i2DFxZfhLSEFyViOYA6H62Bqsi1FoBl01jdTbP+5mzczZz5JM9QZYkvt8K4bdbxuLcB3wC5N4Otla9SRHcm1/U6r/V0NUFL6JIuKoaxWs+/DDDQzRhDnfiWdiQXaRp9yy2DY9VMvA/fU0zvv4F13Sp+lNjuEVIqvVl5pU1PzahgILkne/PAD0bKDkj8pk9KAHznuMfGjcw3dUbE0Hd9MRJqTxQYLoVpOQF3PY6cqF1RI7nLj31koBGDS0yEzIdlAnhwdTKiZXoCvTaIhciOsZjpft+2d4chWzu7vh5wZawWvFJHxGblbbZ4IGdfXKMgO0ItG/8730RXdOZ88c/s4A6KX5F0ytXIA6eX+YBzl1sSKw9WzibrAhJUpDxyZeNMqKM3e3I2L763fQgRSjreIb6rgzgAo8VSiHiO6L7um0UjH+k2SqeYA+h47iDeHAjczqpR1E+csDpsu0nNCm1cNmtw3UWbP/y4O6rjUnNuqO30ToK9C+F/xWtIbYr7Gcac7Lyho5dKDcTkUNDJc0HlsF2cFYlwRbWTA2e7lI13KJ5sdlBSIoybwTeN/XyxmU9sNnDINaJ8LvQw1VcntkRFE2M9+tmqUot2wryMaSf+b7FHGOow2QQpbPjanXf7ovKEsdMSssBwWAPMLT0XD6NChAzZVq9g806GXTxnR4HTaubepKL1JcOAvZvtSiswyqrjdCf8NFKHp0UzmAN3z82DYdndz8xicACNc4xxdhkCMMgavadAM6Bby9TzJ9UxBSRtMnqIShtewauwx+agmvA9ytFEftC9W+Xh9HQH9420VsX7jyTdH2oZ2vHgTfhyEn/naO8++oiX/GxkTGyE5stbAU8Ok3pUfTlsnKbD1yL5d9e0ozR9HJNf1x2cXoaYiC3+D/jlvEpKddNCy8kL5jnxomnpOfreymVfBe2ImZUlqA6UnhrX4+1LPwvjjKBj6cUuWb0i7Me2KOy8A4DMjKeOARcHJ6qfjNi6DshnHdCi+uhm7nkzgY1OSztLoLnGl9aX+Kurh/JItI0ICZqfBMT6ugnVaTixeU/KbU81SezRBME06uv0iEapb+506XE/ZwKwAXTOCg4W52NtC78VR+TMJTS5ITRLqzEdOA4tiHW7x9Ye8WVDDF1qDiP3FLtW8aP41sY/hy9/DSvLsdZ5hTNgwxeexX9K2B6qQ38SX7eMDCp7KN9NQAOgV6Mffko1VUTqjjDEgFjXVcktL/50CgnSJ7RhndZeZe7H3aHgioij9rL8YGwudETzck9PTV2V/m2+j8tUerf5r1mcUM8LltIpDBYEHRGnrnbSjAIjoA7YK1mikVzRnP9aR74ln0Nrgavuj/cvV29z5Cbv6+fCNlC4Fk6bD0DkMsSY9E2DLNfMg0exhwqMt2GqWSoouBl41Sc0JhQA/5kNvJ/pfpYJOgf9z2LDREkkFdAFqH6H4a2/V6XQiu81dn31/SBmsi89xZUy74L746/QP2iNx6WI2JlMgl1c8ybUwrxq628nrg4Wex6tYsMcZ0pj0HQe6q7yJLK2vTGZMMezG98PPBmABj5pkUkUkUqDF0FFEF19Ls6jSihUw69nqSQ/dbuCgy5DidOuDY0Dp2ifSrA3wOwy7JxKxEhKMonUN3lzxelEy61ee+eObDGP+ditQVhOF5y6zCbheVDH8xRa5lk9E5CwLine truncated
+18 -7
View File
@@ -30,7 +30,7 @@ jobs:
outputs:
code: ${{ steps.diff.outputs.code }}
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
- id: diff
@@ -60,8 +60,8 @@ jobs:
name: prose checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
- uses: actions/checkout@v7.0.1
- uses: actions/setup-node@v7.1.0
with:
node-version: 20
- name: Versions agree
@@ -81,9 +81,20 @@ jobs:
defaults:
run:
working-directory: plan2code-app
env:
# Debug info and incremental state are most of target/'s size; the ubuntu
# runner ran out of disk building both the debug and the release app.
CARGO_INCREMENTAL: 0
CARGO_PROFILE_DEV_DEBUG: 0
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
- name: Free disk space on the Linux runner
if: runner.os == 'Linux'
working-directory: .
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
df -h /
- uses: actions/checkout@v7.0.1
- uses: actions/setup-node@v7.1.0
with:
node-version: 20
cache: npm
@@ -179,8 +190,8 @@ jobs:
matrix:
os: [windows-latest, macos-latest, ubuntu-latest]
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
- uses: actions/checkout@v7.0.1
- uses: actions/setup-node@v7.1.0
with:
node-version: 20
- name: Cache the npm downloads
+4 -4
View File
@@ -27,8 +27,8 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
- uses: actions/checkout@v7.0.1
- uses: actions/setup-node@v7.1.0
with:
node-version: 20
- name: Cache the npm downloads
@@ -60,8 +60,8 @@ jobs:
run:
shell: bash
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
- uses: actions/checkout@v7.0.1
- uses: actions/setup-node@v7.1.0
with:
node-version: 20
- name: Cache the npm downloads
+5 -5
View File
@@ -64,10 +64,10 @@ jobs:
run:
shell: bash
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@v4.4.0
- uses: actions/setup-node@v7.1.0
with:
node-version: 22
cache: npm
@@ -121,7 +121,7 @@ jobs:
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
mkdir -p dist
cp "plan2code-app/target/release/${{ matrix.built }}" "dist/plan2code-app-${VERSION}-${{ matrix.label }}${{ matrix.suffix }}"
- uses: actions/upload-artifact@v4.6.2
- uses: actions/upload-artifact@v7.0.2
with:
name: app-${{ matrix.label }}
path: dist/*
@@ -136,8 +136,8 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/download-artifact@v4.3.0
- uses: actions/checkout@v7.0.1
- uses: actions/download-artifact@v8.0.2
with:
path: dist
pattern: app-*
+45 -3
View File
@@ -14,12 +14,37 @@
### A new file under src/web-console/ needs a row in the AGENTS-architecture console files tables; run scripts/test-web-console-shape.mjs after adding one, since it fails until the row exists.
- Kind: convention
- About: scripts/test-web-console-shape.mjs, .agents-docs/AGENTS-architecture-console-page.md
- Noted: 2026-11-14, implement-review
- Why: test-web-console-shape.mjs fails on any file under src/web-console/ the console files tables do not list
- Noted: 2026-11-14, implement-review, checked 2026-11-28
### A new Help topic needs a HELP_TABS entry, a matching hi-<id> icon and help-panel in index.html in the same order, and the topic count raised in the session test and the docs that state it.
- Kind: convention
- About: src/web-console/public/help.js
- Why: openHelpOn() stays on the default topic for an id Help lacks, so the Review Loop link shipped opening Implementation Loop.
- Noted: 2026-11-28, quick-task
### A new page module under src/web-console/public/ must be added to the file list in src/web-console/static.mjs, or the server answers 404 for it and the whole page never draws.
- Kind: correction
- About: src/web-console/static.mjs
- Why: The Review Loop screen was missing from the list and every page test timed out waiting for the page to draw, with no page error to point at it.
- Noted: 2026-11-28, implement-review
### A new scripts/test-*.mjs file must be named in the test script of the root package.json as well as in scripts/test-lanes.json, or test-skill-scripts.mjs fails.
- Kind: correction
- About: package.json
- Why: Two new test files were listed in test-lanes.json only and the full npm test failed on it.
- Noted: 2026-11-28, implement-review
### A no-hop dashboard request goes as a __<name> send; the agent answers with a top-level patch key checked in validate() (patches.mjs), and pointersForSend() maps it to console-launches.md.
- Kind: convention
- About: src/web-console/patches.mjs, src/web-console/pointers.mjs
- Noted: 2026-11-17, quick-task
- Why: A patch key validate() does not know is refused with exit 3, and a send pointersForSend() does not map leaves the agent without console-launches.md.
- Noted: 2026-11-17, quick-task, checked 2026-11-28
### A page screen never imports another screen (the shape test forbids it): what two screens share, such as the loop setup field builders, goes in a module beside state.js, like public/loop-parts.js.
- Kind: convention
- About: src/web-console/public/loop-parts.js
- Noted: 2026-11-28, implement-review
### A test run of node install.js with a temp HOME still writes the plan2code shims into the real npm global bin, because npm's prefix does not follow HOME; also set npm_config_prefix to a temp folder.
- Kind: correction
@@ -27,6 +52,11 @@
- Why: A piped --update test run repointed the real plan2code shims at a temp folder until they were fixed by hand.
- Noted: 2026-11-17, implement-review
### An extra review round in a loop phase reaches the driver through loop_driver::note_page: a Review page goes to rec.round_wait, because rec.sid still holds the phase's own session.
- Kind: how-it-works
- About: plan2code-app/src-tauri/src/loop_driver.rs
- Noted: 2026-11-28, implement-review
### Before adding a class to the git board, grep styles/git.css for it: short names like git-tools and git-path are already taken (the Branches search row, the file path cell).
- Kind: correction
- About: src/web-console/public/styles/git.css
@@ -38,6 +68,11 @@
- About: install.js
- Noted: 2026-11-17, implement-review
### Every heading and .md-h gets text-wrap: balance from tokens.css, so a long heading such as a lesson title splits into two even halves; set text-wrap: wrap where a heading runs longer than a line.
- Kind: how-it-works
- About: src/web-console/public/styles/tokens.css, src/web-console/public/styles/learning.css
- Noted: 2026-11-19, quick-task
### In a Markdown field (md-field.js), CodeMirror's scroller and content are only as tall as the text, not the bordered host: code that hit-tests the scroller must not assume it fills the box.
- Kind: how-it-works
- About: src/web-console/public/md-field.js
@@ -77,7 +112,14 @@
### To drive launcher prompts in scripts/test-launcher.mjs, use runAtTerminal(): it marks stdin as a terminal with a preload file and answers each prompt only once it shows on stdout.
- Kind: convention
- About: scripts/test-launcher.mjs
- Noted: 2026-11-17, implement-review
- Why: Each launcher prompt opens a new readline, so piping all answers at once loses every answer after the first.
- Noted: 2026-11-17, implement-review, checked 2026-11-28
### To run plan2code-app/ui/app.js in a page test, serve the ui folder over HTTP and stub window.__TAURI__, with platform_info answering { os }; from file:// the module never loads.
- Kind: how-it-works
- About: scripts/test-app-meter.mjs, plan2code-app/ui/app.js
- Why: A test that loaded index.html from file:// never ran fitBar(), and a catch-all stub made mountTerminal's top-level await throw.
- Noted: 2026-11-29, quick-task
### When a card in src/plan2code-deps.md changes (what it lists or asks), change the same card in src/web-console/notes/deps.md in the same edit: the console builds the card from the notes.
- Kind: correction
+5 -5
View File
@@ -169,8 +169,8 @@ origin.
| `POST /open-prototype` | `{ spec, name }`: opens one `.html` from `<spec>/prototypes/` in the person's default browser. 404 for any other name, 500 when no browser could start. |
| `GET /handoff?id=<id>` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. |
| `POST /learning/pause` | Pause for me: `{ paused: boolean }` (origin-checked; anything else is 400 `bad-request`, and 409 `not-on` unless Learning is On or Paused for you). Writes the personal pause on this machine only (`pause.json` under `~/.plan2code/learning/<key>/`), the server's only write for Learning, and repaints the row with no agent. |
| `GET /learning/state` | The Learning row's state worked out now, `{ state, pausedSince, waiting, oldestDays }` (`{}` when the project's settings file is from a format it cannot read), with `cache-control: no-store`. |
| `GET /learning/lessons` | Open the lessons, read only: `{ files: [{ name, title, text }] }` from the project's lessons (`.plan2code/lessons/`, saved with the repository), `general.md` first, then the other `.md` files in name order (plain files only, at most 100 of 512 KB each), with `cache-control: no-store`. |
| `GET /learning/state` | The Learning row's state worked out now, `{ state, pausedSince, waiting, oldestDays, nearCap }` (`{}` when the project's settings file is from a format it cannot read), with `cache-control: no-store`. |
| `GET /learning/lessons` | Open the lessons, read only: `{ files: [{ name, title, text }], follows: { <lesson id>: { count, last } } }` (follows from this machine's `follows.ndjson`, for the reader's "Followed N times" line) from the project's lessons (`.plan2code/lessons/`, saved with the repository), `general.md` first, then the other `.md` files in name order (plain files only, at most 100 of 512 KB each), with `cache-control: no-store`. |
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
@@ -208,9 +208,9 @@ origin.
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and CodeMirror 6 (MIT) for the notebook's editor as one bundled file, `public/vendor/codemirror.esm.js`, made by the dev-only `node scripts/vendor-codemirror.mjs` from a pinned lock (about 500 KB, loaded only when the Notebook is first opened); the page's policy blocks the `<style>` element CodeMirror writes, so the editor lives in a shadow root where it adopts its rules as a constructed stylesheet (steps in the architecture doc's Notebook point) |
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
`npm run build:skills` and commit it with the source change, since `npm test`
(via `--verify-skills`) fails when it drifts from `src/`.
Edit `src/` only. `skills/` is gitignored build output: the installer and
`npm test` (via `--build-skills`) regenerate it, and `npm run build:skills`
rebuilds it by hand.
### Driving it by hand
+11 -2
View File
@@ -89,7 +89,7 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
- **Yours to set up.** Light or dark and a highlight color, a **Card width** of Narrow (720px), Comfortable (880px, the default), Wide (1080px) or Ultra wide (1440px), and a role that puts the most useful starters first (see *Your role*). All remembered on your machine.
- **Files in your notes, and a notebook of your own.** Attach a screenshot or a document to any note or quick question (see *Attachments in notes and questions*), and keep a private notebook per folder (see *Your notebook*).
- **Where you are, at the bottom.** The footer names the folder and its git branch; click it to open the Workspace dialog (see *Your workspace*).
- **Help.** The **?** at the top right opens a Help dialog with 23 topics, one per tab, opening on the one for where you are. It is part of the page, so it reads fully even when the page has lost its program.
- **Help.** The **?** at the top right opens a Help dialog with 24 topics, one per tab, opening on the one for where you are. It is part of the page, so it reads fully even when the page has lost its program.
- Works offline, on your own machine only. No account, no install, no network.
An Implement phase ends on a sign-off card: read the completion report, then review the code first, approve the phase, or ask for changes. Implement + Review has already reviewed the code, so its card has no review button. Finalize always offers one last review of the whole feature after its checks, before the summary is written and the spec is archived.
@@ -113,7 +113,7 @@ The easy way in is the dashboard: type `/plan2code` in your agent, or run `plan2
- **Specs and their states.** The picker at the top chooses the spec. A diagnosed bug reads *Bug diagnosed* (Quick task suggested, Plan lit), then *Bug fixed* once Quick task has fixed it; a held-back upgrade from Update dependencies reads *Upgrade ready*, then *Upgrade done*. A finished one can be archived, or deleted from its chip.
- **Handoffs.** Handoffs this folder has not picked up follow the specs as dashed chips. Select one to preview it, then **Pick it up here**, **Read it all**, **Copy for a new conversation** or **Delete**. They live in `~/.plan2code/handoffs/`, written by *Stop with a handoff* (below) and by the Handoff skill.
- **Git and the utilities.** **Git** opens a board with three tabs (Changes, Branches, Sync) and asks before every push, publish and delete; outside a repository it offers to start one. **Codebase X-ray**, **Diagnose a bug** and **Update dependencies** are always available too.
- **Learning.** A row shows *Not set up*, *Off*, *On* or *Paused for you*; **Pause for me** pauses it for you alone. A banner offers **Review** while lessons are waiting. Kept lessons go to `.plan2code/lessons/` in the project; waiting lessons and your pause stay on this machine, and nothing is committed for you.
- **Learning.** A row shows *Not set up*, *Off*, *On* or *Paused for you*; **Pause for me** pauses it for you alone. A banner offers **Review** while lessons are waiting. Before you see them, each waiting lesson is checked against the code by a separate reader, and the card shows any Doubt or Fail with its reason (and, where it helps, a better wording to use); you still decide. The lessons reader shows how often each lesson was followed. **More, Tidy up lessons** (and a banner nudge once general lessons reach 22 of 25, or an area file 30) has the agent propose merges, rewords, retires and moves, one change each, checked like any lesson and applied only on your **Apply**. Kept lessons go to `.plan2code/lessons/` in the project; waiting lessons and your pause stay on this machine, and nothing is committed for you.
- **Planny wakes up.** A fresh dashboard starts with him asleep; click to wake him (**Skip** or Escape skips it, and reduced motion shows the awake dashboard at once).
Or start any step by its command (the full list is in the README's [Prefer the terminal?](../README.md#prefer-the-terminal) section), and add `--web` to open the console without being asked: `/plan2code-1-plan --web plan a lunch voting app`. Without it, the first question is "In your browser (suggested)" or "Here in the terminal". The page opens straight away at a `127.0.0.1` address, with a starting screen while the skill reads your project. You can switch to the terminal at any point: the files under `specs/` are the same either way.
@@ -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
+2 -2
View File
@@ -36,11 +36,11 @@ 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 24-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`.
**Learning** (lessons about a codebase, kept with it): the dashboard draws a Learning row (Not set up, Off, On or Paused for you, with a Pause for me switch and a More menu) and, while lessons are waiting, a banner with Review, both from the scan's `learning` field (`public/screens/learning-row.js`, `public/styles/learning.css`); skills ask for approval through the `lessons` card kind. The server's only write for it is the personal pause, on this machine only (`POST /learning/pause`, under `~/.plan2code/learning/`); every change to the project's Learning files (`.plan2code/settings.json` and `.plan2code/lessons/`) goes through the `lessons.mjs` skill script, which shares one core with the scan, `src/web-console/learning.mjs`.
**Learning** (lessons about a codebase, kept with it): the dashboard draws a Learning row (Not set up, Off, On or Paused for you, with a Pause for me switch and a More menu) and, while lessons are waiting, a banner with Review (plus a Tidy up nudge from the scan's `nearCap`; More, Tidy up lessons sends the `tidy` action, which writes `tidy` waiting items the same card applies), both from the scan's `learning` field (`public/screens/learning-row.js`, `public/styles/learning.css`); skills ask for approval through the `lessons` card kind. Before that card, every waiting lesson is graded by a separate check, a fresh read-only helper where the agent has one, else a labeled second pass by the same agent (`src/shared-references/lesson-check.md`; `lessons.mjs check-input` prepares, the checker judges, `check-record` stores), and the card shows each Doubt or Fail with its reason; follows ("Following a lesson") are counted on this machine only, in `follows.ndjson`, for the lessons reader. The server's only write for it is the personal pause, on this machine only (`POST /learning/pause`, under `~/.plan2code/learning/`); every change to the project's Learning files (`.plan2code/settings.json` and `.plan2code/lessons/`) goes through the `lessons.mjs` skill script, which shares one core with the scan, `src/web-console/learning.mjs`.
Building or changing an Activities game: follow the game rules in [Activities](./.agents-docs/AGENTS-architecture-activities.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
Details: [Web console server and contract](./.agents-docs/AGENTS-architecture-console.md), [page](./.agents-docs/AGENTS-architecture-console-page.md), [design points](./.agents-docs/AGENTS-architecture-console-design.md), [Activities](./.agents-docs/AGENTS-architecture-activities.md) (and the Ghoul Rush and Bounce Road files it links) [.readme/web-console.md](./.readme/web-console.md) (the user guide), [.readme/activities.md](./.readme/activities.md) and [.readme/web-console-internals.md](./.readme/web-console-internals.md) (routes, security, driving it by hand, refreshing screenshots)
Why the agent-facing console docs are shaped as they are (the card, pointers, refusals): [Web Console Contract](./.agents-docs/AGENTS-web-console-contract.md); it never ships.
+72
View File
@@ -4,6 +4,78 @@ All notable changes to Plan2Code will be documented in this file.
<!-- Format from 3.1.0 on: `## vX.Y.Z (YYYY-MM-DD)` with the date from version.json; a minor release opens with a three-bullet `### Highlights`; sections run Added, Changed, Fixed; game changes sit under one Activities line; tooling and test lines go under "For contributors". Older headings have no date and are not backfilled. -->
## v3.2.0 (2026-11-29)
### Highlights
- 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.
- **Desktop app**: Help has a Review Loop topic (with a diagram of the rounds), opened by How the Review Loop works on the dashboard card and on the setup screen.
- **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).
- **Learning**: a lesson can carry a search (text that should always, or never, appear in some files), so the check and later reads test it against the code and raise a doubt when it stops agreeing.
- **Learning**: Ask for suggestions on the lessons card can now suggest a Reword with its words, and the row's lesson and Why boxes fill with them when its Reword is open.
### 🔧 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.
### 🐛 Fixed
- **Desktop app**: the top bar's update line (and every other next step there) uses the room the bar has instead of stopping at 320px; in a narrow window the model and status text still give way first.
## v3.1.5 (2026-11-23)
### 🐛 Fixed
- **desktop app**: Change project, and picking a recent folder, now starts the new project's agent and dashboard; before, the agent opened inside the old project's stopped session and never showed its page.
- **web console**: the page itself no longer scrolls (its panels do), so the blank space that could show below the footer is gone; the narrow-window layout and printing follow the same rule.
- **For contributors**: `npm run test:page -- <file>` runs page test files with the desktop app's variables unset, and a new layout page test checks that the page shell never scrolls.
## v3.1.4 (2026-11-20)
### 🔧 Changed
- **launcher**: the model menu offers Claude Fable 5.2 in place of 5.1, Gemini 4 Hydrogen and Gemini 4 Neon for Devin, and GPT-6.2 Astra and GPT-6.2 Sol for Codex; Gemini 3.8 Flash, GLM-5.3 Low and SWE-2 Flash Medium leave Devin's list, and Claude's `haiku` and `fable` labels follow the Claude Code docs.
- **launcher**: Claude Code's install options add the Windows CMD installer and install `@latest` through npm, the OpenCode starter template opens with `@plan2code`, and the Gemini CLI note also names Gemini Code Assist for GitHub.
### 🐛 Fixed
- **launcher**: `plan2code update` no longer stops at "Already on" after an earlier update stopped partway and left the `plan2code` command on the old version; the install record keeps the old version until every piece is in.
## v3.1.3 (2026-11-18)
### 🔧 Changed
- **For contributors**: the CI workflows use the Node.js 24 versions of the checkout, setup-node and artifact actions, two tests that always failed on macOS are fixed, and four page tests no longer depend on redraw timing.
### 🐛 Fixed
- **web console**: on a finished screen, a press that nothing ever collects now shows its way out (Start a New Session in the app, or the command to run in a browser) together with the "Plan2Code is not running" line; before, it appeared only if something else happened to redraw the card.
## v3.1.2 (2026-11-18)
### 🔧 Changed
- **web console**: the git board now walks you through four steps, Save, Share, Review and Tidy, with one task card for the step you are on; the Changes, Branches and Sync tabs are folded into **All branches and tools**.
### 🐛 Fixed
- **installer**: an install, update or uninstall started by a launcher older than the release channel, or by an install command copied from an older README, no longer gets unfinished work from `main`: the installer notices, says so and switches to the newest release. `plan2code update --main` still takes `main`.
## v3.1.1 (2026-11-17)
### ✨ Added
+1 -1
View File
@@ -13,7 +13,7 @@
Plan2Code is a spec-driven workflow for AI coding agents. You work through it on a page in your browser: the dashboard lists every step as a card, and each step's questions, progress and sign-offs arrive on that same page while your agent does the work. An approved plan becomes phase documents, and the agent builds to them one phase at a time.
Version 3.1.1 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 3.2.0 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
+52
View File
@@ -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.
+157 -28
View File
@@ -170,7 +170,9 @@ const SOURCE_PROMPTS = [
scripts: ['lessons.mjs', 'glob.mjs', 'test-map.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -240,7 +242,8 @@ const SOURCE_PROMPTS = [
{ source: 'plan2code-review-references' },
{ source: 'plan2code-ui-prototype.md', target: 'ui-prototype.md' },
{ source: 'plan2code-ui-prototype-references' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -310,7 +313,8 @@ const SOURCE_PROMPTS = [
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -329,7 +333,8 @@ const SOURCE_PROMPTS = [
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -347,7 +352,8 @@ const SOURCE_PROMPTS = [
{ source: 'shared-references/review-in-build.md', target: 'review-in-build.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -392,7 +398,8 @@ const SOURCE_PROMPTS = [
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -409,7 +416,8 @@ const SOURCE_PROMPTS = [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -444,7 +452,8 @@ const SOURCE_PROMPTS = [
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
{ source: 'shared-references/lessons.md', target: 'lessons.md' },
{ source: 'shared-references/lesson-check.md', target: 'lesson-check.md' }
]
},
{
@@ -2569,8 +2578,13 @@ function readInstallRecord() {
return null;
}
// While update() runs, every record write keeps the version the update started from (`{ version }`),
// so an update stopped partway (Ctrl+C, a closed window, a killed child) never leaves the record
// claiming the new version over pieces that are still old. update() stamps the new one at the end.
let recordVersionHold = null;
/** Temp file, then rename, so a crash never leaves a half-written record. A failure only skips the record. */
function writeInstallRecord(pieces, skipped = (readInstallRecord() || {}).skipped || [], version = projectVersion.version) {
function writeInstallRecord(pieces, skipped = (readInstallRecord() || {}).skipped || [], version = recordVersionHold ? recordVersionHold.version : projectVersion.version) {
const record = {
version,
scope: 'global',
@@ -2591,15 +2605,25 @@ function writeInstallRecord(pieces, skipped = (readInstallRecord() || {}).skippe
}
/**
* Put `version` back in the record (null when none was known) without touching its pieces: every
* recordInstalled() stamps the version being installed, so an update that failed uses this to
* stay behind, and the next `plan2code update` does not answer "Already on".
* Write `version` on the record without touching its pieces: update() uses it to stamp the new
* version once every piece is in, and to keep the old one (null when none was known) after a
* failure or a kept app, so the next `plan2code update` does not answer "Already on".
*/
function setRecordVersion(version) {
const record = readInstallRecord();
if (record) writeInstallRecord(record.pieces, record.skipped || [], version);
}
/** The version in the installed plan2code command's version.json, or null when it is missing or unreadable. */
function installedLauncherVersion() {
try {
const { version } = JSON.parse(fs.readFileSync(LAUNCHER_VERSION_DEST, 'utf8'));
return typeof version === 'string' ? version : null;
} catch {
return null;
}
}
/** Add a piece after a successful global install. */
function recordInstalled(piece) {
const record = readInstallRecord();
@@ -3725,7 +3749,8 @@ function releaseNotesUrl(version) {
/**
* Reinstall whatever ~/.plan2code/install.json lists, without the menu or any prompt, and print
* one compact summary: `Updating <old> -> <new>` (or `Already on <new>`, which stops early unless
* `force`), one line per piece by its human name, then the release notes link and the restart
* `force`, and only when the installed command's bin/version.json agrees with the record whenever
* the record lists `launcher`), one line per piece by its human name, then the release notes link and the restart
* hint. Each piece's own output is held back and shown only when that piece warns or fails.
* Returns the exit code: 0 when every piece updated, 1 naming the pieces that failed.
*/
@@ -3733,15 +3758,33 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims
const record = readInstallRecord();
const version = projectVersion.version;
const before = record && typeof record.version === 'string' ? record.version : null;
if (before === version && !force) {
const pieces = record ? record.pieces : ['skills', 'launcher'];
// The record alone is not proof: an update stopped before its launcher step (or one run by a
// launcher too old to pass --force on) left the record new and the command old, and every later
// update stopped here. The command's own version.json says what is really in place.
const launcherVersion = pieces.includes('launcher') ? installedLauncherVersion() : version;
if (before === version && launcherVersion === version && !force) {
console.log(`${COLORS.GREEN}${MARKS.DONE}${COLORS.RESET} Already on ${version}`);
console.log(`${COLORS.DIM}Run plan2code update --force to install it again.${COLORS.RESET}`);
return 0;
}
console.log(`${COLORS.BRIGHT}${before ? `Updating ${before} -> ${version}` : `Updating to ${version}`}${COLORS.RESET}`);
const pieces = record ? record.pieces : ['skills', 'launcher'];
if (before === version && launcherVersion !== version && !force) {
console.log(`${COLORS.DIM}The plan2code command is still on ${launcherVersion || 'an unknown version'}, so everything is installed again.${COLORS.RESET}`);
}
if (!record) console.log(`${COLORS.DIM}No install record found; updating the skills and the plan2code command.${COLORS.RESET}`);
recordVersionHold = { version: before };
try {
return await updatePieces({ steps, cleanShims, pieces, before, version });
} finally {
recordVersionHold = null;
}
}
/** update()'s body once it has decided to install: the pieces, the summary, and the version stamp. */
async function updatePieces({ steps, cleanShims, pieces, before, version }) {
await captureOutput(async () => cleanShims());
const results = {};
@@ -3798,7 +3841,7 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims
console.log('');
if (failed.length > 0) {
console.log(`${COLORS.RED}${MARKS.FAIL} Update failed for: ${failed.join(', ')}${COLORS.RESET}`);
// The pieces that did install stamped the new version on the record: take it back, so running
// Keep the old version on the record (writes during the update already held it), so running
// plan2code update again retries instead of stopping at "Already on".
setRecordVersion(before);
console.log(`To try again, run: ${COLORS.CYAN}plan2code update${COLORS.RESET}`);
@@ -3809,7 +3852,9 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims
// The release had no desktop app file yet, so the installed app is still the old one: keep the
// old version on the record, or the next update (the app's Update and restart among them) stops
// at "Already on" and never fetches the app once the file is attached.
if (before && typeof results.app === 'string' && results.app.startsWith('kept')) setRecordVersion(before);
// Otherwise every piece is in: only now does the record name the new version.
const appKept = typeof results.app === 'string' && results.app.startsWith('kept');
setRecordVersion(before && appKept ? before : version);
console.log(`${COLORS.GREEN}${MARKS.DONE} Plan2Code is up to date (v${version})${COLORS.RESET}`);
console.log(`What's new: ${releaseNotesUrl(version)}`);
console.log('Close any open Plan2Code console or app and start `plan2code` again.');
@@ -3817,20 +3862,90 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims
return 0;
}
// ============================================================================
// RELEASE REDIRECT
// ============================================================================
//
// Launchers older than the release channel run `plan2code update` (and uninstall) as
// `npx git+<repo> --update`, which is the tip of main, and so does an install command copied from
// an older README. Without this, those people would get unreleased work. When this copy came from
// an npx fetch of a commit that no `vX.Y.Z` tag points at, it hands the same command to the
// newest release instead. Any run the current launcher starts says which ref it picked on purpose
// (PLAN2CODE_INSTALL_REF, `--main` included), and a checkout (`node install.js`) is never under
// node_modules, so neither is redirected. Anything unknown (no lock file, no network) also means
// no redirect: the run goes on exactly as before.
/** The commit npx fetched this copy from (from npm's hidden lock file beside it), or null. */
function fetchedCommit(dir = __dirname) {
const modules = path.dirname(dir);
if (path.basename(modules) !== 'node_modules') return null;
try {
const lock = JSON.parse(fs.readFileSync(path.join(modules, '.package-lock.json'), 'utf8'));
const entry = lock && lock.packages && lock.packages[`node_modules/${path.basename(dir)}`];
const m = entry && typeof entry.resolved === 'string' ? /#([0-9a-f]{40})$/i.exec(entry.resolved) : null;
return m ? m[1].toLowerCase() : null;
} catch {
return null;
}
}
/**
* The release tag to hand this run to, as `vX.Y.Z`, or null to run here. `lsRemote` is
* `git ls-remote --tags` output and `newest` its newest release (update-check.mjs's pick). A
* commit any release tag points at (peeled or not) stays, so an older launcher's
* `update --tag v3.0.2` and the `#release` branch are left alone.
*/
function releaseRedirectRef({ commit, lsRemote, newest, env = process.env }) {
if (env.PLAN2CODE_INSTALL_REF || !commit || !newest || typeof lsRemote !== 'string') return null;
for (const line of lsRemote.split(/\r?\n/)) {
const m = /^([0-9a-f]{40})\s+refs\/tags\/v\d+\.\d+\.\d+(\^\{\})?$/i.exec(line.trim());
if (m && m[1].toLowerCase() === commit) return null;
}
return `v${newest}`;
}
/**
* Run the newest release's installer with the same options when this copy is unreleased work
* fetched by an older launcher. Resolves the child's exit code, or null to carry on here.
*/
async function redirectToRelease(argv) {
if (!argv.every((a) => /^--[a-z]+$/.test(a))) return null;
const commit = fetchedCommit();
if (!commit || process.env.PLAN2CODE_INSTALL_REF) return null;
let ref = null;
try {
const checker = await import(pathToFileURL(UPDATE_CHECK_SRC).href);
const stub = process.env.PLAN2CODE_LS_REMOTE_FILE;
const lsRemote = stub ? fs.readFileSync(stub, 'utf8') : await checker.runLsRemote();
ref = releaseRedirectRef({ commit, lsRemote, newest: checker.latestTag(lsRemote) });
} catch {
return null;
}
if (!ref) return null;
console.log(`This installer is unreleased work from main, so Plan2Code is switching to the newest release, ${ref}.`);
console.log(`${COLORS.DIM}Fetching it can take a minute or two.${COLORS.RESET}`);
const command = ['npx', '--yes', '--allow-git=all', `git+https://github.com/jparkerweb/plan2code.git#${ref}`, ...argv].join(' ');
return new Promise((resolve) => {
let child;
try {
child = spawn(command, { shell: true, stdio: 'inherit', env: { ...process.env, PLAN2CODE_INSTALL_REF: ref } });
} catch {
resolve(null);
return;
}
// The child owns the terminal now: Ctrl+C reaches it, and this process waits for its code.
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => {});
child.on('error', () => resolve(null));
child.on('exit', (code) => resolve(code ?? 1));
});
}
// ============================================================================
// MAIN
// ============================================================================
// Run only when invoked directly; requiring the file (the update tests do) is load-only.
if (require.main === module) {
// Non-interactive build hooks for the generated skills/ artifact.
const argv = process.argv.slice(2);
if (argv.includes('--build-skills')) {
process.exit(buildSkills() ? 0 : 1);
} else if (argv.includes('--verify-skills')) {
process.exit(verifySkillsSync() ? 0 : 1);
} else if (argv[0] === '--update' && argv.slice(1).every((a) => a === '--force')) {
function runCommand(argv) {
if (argv[0] === '--update' && argv.slice(1).every((a) => a === '--force')) {
update({ force: argv.includes('--force') }).then((code) => process.exit(code));
} else if (argv[0] === '--uninstall' && argv.slice(1).every((a) => a === '--yes' || a === '--purge')) {
uninstall({ yes: argv.includes('--yes'), purge: argv.includes('--purge') }).then((code) => process.exit(code));
@@ -3844,4 +3959,18 @@ if (require.main === module) {
}
}
module.exports = { printKeptData, uninstallSkillsPiece, removeSkillsDirectly, removeConsoleFolders, uninstallStatusLine, listKeptData, newUninstallReport, printUninstallReport, UNINSTALL_STEPS, UNINSTALL_PROBES, PIECE_LABELS, createSpinner, printGettingStarted, pathFixLine, fullCommandPath, desktopAppState, detectAgents, agentInstallLine, writeLauncherShim, isOurLauncherShim, LAUNCHER_MARKER, NO_TERMINAL_MESSAGE, appAllowLine, APP_GUIDE_URL, formatBytes, nodeVersionProblem, appWebviewDirs, purgeAppWebview, appRunning, uninstall, uninstallAll, purgeData, installSharedConsole, sweepOldConsoles, consoleHomeDir, CONSOLE_SHARED_DIR, update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
// Run only when invoked directly; requiring the file (the update tests do) is load-only.
if (require.main === module) {
const argv = process.argv.slice(2);
// Non-interactive build hooks for the generated skills/ artifact.
if (argv.includes('--build-skills')) {
process.exit(buildSkills() ? 0 : 1);
} else if (argv.includes('--verify-skills')) {
process.exit(verifySkillsSync() ? 0 : 1);
} else {
redirectToRelease(argv).then((code) => (code === null ? runCommand(argv) : process.exit(code)));
}
}
module.exports = { fetchedCommit, releaseRedirectRef, printKeptData, uninstallSkillsPiece, removeSkillsDirectly, removeConsoleFolders, uninstallStatusLine, listKeptData, newUninstallReport, printUninstallReport, UNINSTALL_STEPS, UNINSTALL_PROBES, PIECE_LABELS, createSpinner, printGettingStarted, pathFixLine, fullCommandPath, desktopAppState, detectAgents, agentInstallLine, writeLauncherShim, isOurLauncherShim, LAUNCHER_MARKER, NO_TERMINAL_MESSAGE, appAllowLine, APP_GUIDE_URL, formatBytes, nodeVersionProblem, appWebviewDirs, purgeAppWebview, appRunning, uninstall, uninstallAll, purgeData, installSharedConsole, sweepOldConsoles, consoleHomeDir, CONSOLE_SHARED_DIR, update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "3.1.1",
"version": "3.2.0",
"private": true,
"license": "Apache-2.0",
"engines": {
@@ -17,7 +17,8 @@
"play": "node scripts/play.mjs",
"pretest": "node scripts/fix-line-endings.mjs",
"test:fast": "node scripts/test-fast.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-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-Line truncated
"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-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",
+2 -2
View File
@@ -957,7 +957,7 @@ dependencies = [
[[package]]
name = "fake-agent"
version = "3.1.1"
version = "3.2.0"
dependencies = [
"serde_json",
"terminal_size",
@@ -2647,7 +2647,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "plan2code-app"
version = "3.1.1"
version = "3.2.0"
dependencies = [
"chrono",
"libc",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "fake-agent"
version = "3.1.1"
version = "3.2.0"
description = "A stand-in agent program for the Plan2Code app's tests"
edition = "2021"
publish = false
+181 -1
View File
@@ -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!(
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "plan2code-app",
"version": "3.1.1",
"version": "3.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plan2code-app",
"version": "3.1.1",
"version": "3.2.0",
"dependencies": {
"@tauri-apps/api": "2.12.4",
"@xterm/addon-fit": "0.11.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code-app",
"version": "3.1.1",
"version": "3.2.0",
"private": true,
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "plan2code-app"
version = "3.1.1"
version = "3.2.0"
description = "Plan2Code desktop app"
edition = "2021"
publish = false
+25 -4
View File
@@ -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!(
(
+6
View File
@@ -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)]
+533 -123
View File
@@ -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 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"]);
return;
}
}
}
}
@@ -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));
}
}
+39 -3
View File
@@ -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"}"#;
+243 -7
View File
@@ -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();
}
@@ -1139,6 +1145,14 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
let _ = sup.stop();
}
}
// The new project's agent asks the window which session is current and
// joins it; left at the old project's (its console just stopped), its
// `open` joined a dead page and the dashboard never showed.
if let Ok(guard) = state.announce.lock() {
if let Some(server) = guard.as_ref() {
server.forget_current();
}
}
Ok(())
}
@@ -1402,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
@@ -1593,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
@@ -1800,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,
@@ -1840,6 +2054,7 @@ fn main() {
.map(|session| session.state)
.unwrap_or(serde_json::Value::Null);
loop_driver::note_page(&state.loop_run, &notice.workflow, &notice.sid, &page);
review_loop::note_page(&state.review_run, &notice.workflow, &notice.sid, &page);
let _ = handle.emit("console-page", &notice);
} else {
eprintln!(
@@ -2011,8 +2226,22 @@ mod tests {
}
#[test]
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() {
fn changing_project_forgets_the_old_projects_session_so_the_new_agent_starts_its_own() {
// The new agent's `open` asks the window which session is current; left
// at the old project's (its console torn down) it joined a dead page
// and never showed its dashboard.
let state = state_for("project-a");
announce_page(&state, "s1");
teardown_project(&state).unwrap();
assert_eq!(
state.announce.lock().unwrap().as_ref().unwrap().current(),
None,
"the new project's agent must not join the old project's s1"
);
}
/// Starts the announce server on `state` and announces page `sid` to it.
fn announce_page(state: &AppState, sid: &str) {
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
let port: u16 = server
.url()
@@ -2023,7 +2252,8 @@ mod tests {
.parse()
.unwrap();
*state.announce.lock().unwrap() = Some(server);
let body = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
let body =
format!(r#"{{"url":"http://127.0.0.1:5000/s/abc/","sid":"{sid}","workflow":"plan"}}"#);
let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
let token = state
.announce
@@ -2055,8 +2285,14 @@ mod tests {
.unwrap()
.current()
.map(|n| n.sid),
Some("s1".to_string())
Some(sid.to_string())
);
}
#[test]
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() {
let state = state_for("project-a");
announce_page(&state, "s1");
// No console supervised here, so no brief to write: only the forgetting.
assert_eq!(before_fresh_hook(&state)(), None);
+631
View File
@@ -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);
}
}
+675
View File
@@ -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"
);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Plan2Code",
"version": "3.1.1",
"version": "3.2.0",
"identifier": "com.plan2code.desktop",
"build": {
"frontendDist": "../ui",
+103 -6
View File
@@ -427,8 +427,11 @@ function fitBar() {
barRowEl.classList.remove('no-model', 'no-status');
const model = agentModelEl.hidden ? 0 : agentModelEl.offsetWidth;
const status = agentStatusEl.textContent ? agentStatusEl.offsetWidth : 0;
// The step text shrinks rather than overflowing the row, so what it hides
// counts as needed room: the model and status drop before it is cut.
const stepCut = nextStepEl.hidden ? 0 : Math.max(0, nextStepTextEl.scrollWidth - nextStepTextEl.clientWidth);
// Only an agent's menu can hold them, so with none the row keeps everything.
const fit = agentMenuBtn.hidden ? { model: true, status: true } : barFit({ available: barRowEl.clientWidth, needed: barRowEl.scrollWidth, model, status });
const fit = agentMenuBtn.hidden ? { model: true, status: true } : barFit({ available: barRowEl.clientWidth, needed: barRowEl.scrollWidth + stepCut, model, status });
const dropModel = !fit.model && model > 0;
const dropStatus = !fit.status && status > 0;
barRowEl.classList.toggle('no-model', dropModel);
@@ -1038,6 +1041,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 +1710,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 +1759,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 +1826,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
+9 -2
View File
@@ -105,8 +105,15 @@
@media (prefers-reduced-motion: reduce) { #loop-dot, .loop-pip.current { animation: none; } }
#bar-grow { flex: 1; min-width: 0; }
/* The one next step for the console or the skills, at the right end. */
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
#next-step-text { overflow: hidden; text-overflow: ellipsis; max-width: 320px; }
/* It takes the room the row has left and is cut, with an ellipsis, only
once fitBar() has already dropped the model and status text. The text's
column may shrink to nothing, so the box's own floor is its buttons:
it never squeezes them, or runs them under the menu button. */
#bar-row > #next-step {
display: grid; grid-auto-flow: column; grid-template-columns: minmax(0, max-content); grid-auto-columns: max-content;
align-items: center; gap: 8px; flex: 0 1 auto;
}
#next-step > #next-step-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
#next-step-text.is-ok { color: var(--ok); }
#next-step-text.is-warn { color: var(--stage); }
#next-step-text.is-err { color: var(--warn); }
+44 -2
View File
@@ -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,
};
+1 -1
View File
@@ -351,7 +351,7 @@ function makeLearningProject() {
const note = (text, kind, about) =>
spawnSync(
process.execPath,
[path.join(ROOT, "src", "skill-scripts", "lessons.mjs"), "note", "--type", "lesson", "--text", text, "--kind", kind, "--about", about, "--source", "said", "--skill", "implement"],
[path.join(ROOT, "src", "skill-scripts", "lessons.mjs"), "note", "--type", "lesson", "--text", text, "--kind", kind, "--about", about, "--source", "said", "--skill", "implement", ...(kind === "convention" ? ["--why", "An offset skips rows when the list changes between pages."] : [])],
{ cwd: project, env: ENV, encoding: "utf8" }
);
note("Every list endpoint pages with a cursor, never an offset.", "convention", "src/tasks");
+22
View File
@@ -0,0 +1,22 @@
// Runs page test files the way CI does: the PLAN2CODE_* app variables are
// unset first, because inherited from the desktop app (or an agent running
// inside it) they fail about a dozen unrelated tests. Files run through
// node-test.mjs, so its cap of one file per spare core applies. Extra
// arguments (such as --test-name-pattern "<name>") pass straight through.
// Usage: npm run test:page -- scripts/test-web-console-page-layout.mjs
import { spawnSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";
const env = { ...process.env };
for (const name of Object.keys(env)) if (name.startsWith("PLAN2CODE_") && /^PLAN2CODE_(IN_APP|APP_|EMBED_ORIGIN|CONSOLE_SID|LOOP_STRENGTH)/.test(name)) delete env[name];
const args = process.argv.slice(2);
if (!args.length) {
console.error("Usage: npm run test:page -- <scripts/test-web-console-page-*.mjs ...> [--test-name-pattern <name>]");
process.exit(2);
}
const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "node-test.mjs");
const r = spawnSync(process.execPath, [runner, ...args], { env, stdio: "inherit" });
process.exit(r.status ?? 1);
+7
View File
@@ -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 }));
+203 -3
View File
@@ -9,6 +9,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { looksFromMessage, terminalFontStep, TERMINAL_FONT_DEFAULT, TERMINAL_FONT_MIN, TERMINAL_FONT_MAX, splitterFraction, splitterAria, terminalTitle, barFit, terminalAnsi, TERMINAL_ANSI, hexToRgba, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, commandSegments, plainCommandText, menuStep, pageNotShownView, pageDetailsLine, redactSessionUrl, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND, STILL_WAITING_MS, STILL_WAITING_TEXT, waitingView, friendlyError, endedView, confirmButtons, trapTab, SHORTCUTS, shortcutAction, shortcutLabel, tipWithShortcut, shortcutFromMessage, clipboardAction, releaseAfterCheck, releaseNotesUrl, reasonSentence, UPDATE_RECHECK_MS } from "../plan2code-app/ui/meter.js";
@@ -471,8 +472,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 +572,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");
@@ -1047,11 +1136,122 @@ test("barFit drops the model text first, then the status line, and only when the
assert.deepEqual(barFit({ available: 500, needed: 800 }), { model: false, status: false }, "no parts measured, none claimed");
});
// The app's ui/ folder over HTTP on a free local port, for a test that needs app.js to run.
function serveFolder(dir) {
const TYPES = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".woff2": "font/woff2" };
const server = http.createServer((req, res) => {
const file = path.join(dir, decodeURIComponent(new URL(req.url, "http://x").pathname));
if (!file.startsWith(dir) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
res.writeHead(404).end();
return;
}
res.writeHead(200, { "content-type": TYPES[path.extname(file)] || "application/octet-stream" });
fs.createReadStream(file).pipe(res);
});
return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server)));
}
test("the bar's step text uses the room the row has; model and status drop before it is cut, and its buttons never shrink", async (t) => {
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
const browser = await launchBrowser();
try {
const page = await browser.newPage({ viewport: { width: 1800, height: 600 } });
// Later start-up steps trip over the stub's nulls; the bar is wired before them,
// and "the model alone drops" below shows fitBar() ran.
page.on("pageerror", () => {});
// Enough of __TAURI__ for app.js to run, so its real fitBar() lays out the row:
// every command answers null (platform_info a platform), every window call resolves.
await page.addInitScript(() => {
const resolved = () => Promise.resolve();
const win = new Proxy({}, { get: () => resolved });
const known = {
core: { invoke: (cmd) => Promise.resolve(cmd === "platform_info" ? { os: "linux" } : null), Channel: class {} },
window: { getCurrentWindow: () => win },
event: { listen: () => Promise.resolve(() => {}) },
};
window.__TAURI__ = new Proxy(known, { get: (all, key) => all[key] || new Proxy({}, { get: () => resolved }) });
});
// app.js is a module, which Chrome will not load from file://: serve the folder.
const server = await serveFolder(path.dirname(INDEX_HTML_PATH));
t.after(() => server.close());
await page.goto(`http://127.0.0.1:${server.address().port}/index.html`, { waitUntil: "networkidle" });
await page.evaluate(() => {
const show = (id, text) => {
const el = document.getElementById(id);
el.hidden = false;
if (text !== undefined) el.textContent = text;
};
document.getElementById("agent-none").hidden = true;
show("project-menu-button");
document.getElementById("project-name").textContent = "plan2code";
show("agent-restart");
show("agent-menu-button");
document.getElementById("agent-name").textContent = "Claude Code";
show("agent-model", "opus 5.5 xhigh");
document.getElementById("agent-status").textContent = "Working: reading the plan and every phase file";
show("next-step");
const text = document.getElementById("next-step-text");
text.textContent = "npx fetches it quietly first, which can take a minute or two.";
text.className = "is-warn is-busy";
show("next-step-button", "Update and restart");
show("next-step-more", "+1 more");
show("next-step-notes");
});
const settle = () => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
const measure = () =>
page.evaluate(() => {
const row = document.getElementById("bar-row");
const text = document.getElementById("next-step-text");
const box = (id) => document.getElementById(id).getBoundingClientRect();
const menu = box("app-menu-button");
const buttons = ["next-step-button", "next-step-more", "next-step-notes"].map(box);
return {
noModel: row.classList.contains("no-model"),
noStatus: row.classList.contains("no-status"),
cut: text.scrollWidth > text.clientWidth,
textWidth: text.clientWidth,
buttonWidths: buttons.map((b) => Math.round(b.width)),
overlap: buttons.some((b) => b.right > menu.left + 0.5),
menuInside: menu.width > 0 && menu.right <= row.getBoundingClientRect().right + 0.5,
};
});
await settle();
const wide = await measure();
assert.deepEqual([wide.noModel, wide.noStatus, wide.cut], [false, false, false], "a wide window shows everything, the whole line included");
assert.ok(wide.textWidth > 320, `wider than the old 320px cap (${wide.textWidth}px)`);
const seen = new Set();
// Down to the app's minimum width (tauri.conf.json minWidth 960).
for (let width = 1800; width >= 960; width -= 20) {
await page.setViewportSize({ width, height: 600 });
await settle();
const at = await measure();
if (at.cut) assert.ok(at.noModel && at.noStatus, `${width}px: the line is cut only after the model and status dropped`);
if (at.noStatus) assert.ok(at.noModel, `${width}px: the model drops before the status`);
assert.deepEqual(at.buttonWidths, wide.buttonWidths, `${width}px: the step buttons keep their width`);
assert.equal(at.overlap, false, `${width}px: no step button runs under the menu button`);
assert.equal(at.menuInside, true, `${width}px: the menu button stays inside the row`);
seen.add(`${at.noModel}/${at.noStatus}/${at.cut}`);
}
assert.ok(seen.has("true/false/false"), `the model alone drops at some width (${[...seen]})`);
assert.ok(seen.has("true/true/true"), `the line is cut at the narrowest widths (${[...seen]})`);
assert.equal(await page.evaluate(() => getComputedStyle(document.getElementById("next-step-text")).textOverflow), "ellipsis");
// Below the minimum, the row runs out at its end as it always did: the text
// has shrunk to nothing, but its buttons are never squeezed under the menu.
await page.setViewportSize({ width: 400, height: 600 });
await settle();
const tight = await measure();
assert.deepEqual(tight.buttonWidths, wide.buttonWidths, "400px: the step buttons keep their width");
assert.equal(tight.overlap, false, "400px: no step button runs under the menu button");
} finally {
await browser.close();
}
});
test("the top bar collapses instead of scrolling, and +N more is a button that lists the other steps", () => {
assert.doesNotMatch(INDEX_HTML, /#bar-row \{[^}]*overflow-x: auto/, "no sideways scrolling row");
assert.match(INDEX_HTML, /#bar-row\.no-model #agent-model, #bar-row\.no-status #agent-status \{ display: none; \}/);
assert.match(APP_JS, /new ResizeObserver\(scheduleFitBar\)\.observe\(barRowEl\);/);
assert.match(APP_JS, /barFit\(\{ available: barRowEl\.clientWidth, needed: barRowEl\.scrollWidth, model, status \}\)/);
assert.match(APP_JS, /barFit\(\{ available: barRowEl\.clientWidth, needed: barRowEl\.scrollWidth \+ stepCut, model, status \}\)/);
assert.doesNotMatch(APP_JS, /barRowEl\.addEventListener\('scroll'/);
assert.match(INDEX_HTML, /<button id="next-step-more" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="more-menu" hidden><\/button>/);
assert.match(INDEX_HTML, /<div id="more-menu" class="bar-dropdown" role="menu"[^>]*tabindex="-1" hidden><\/div>/);
+2 -1
View File
@@ -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,
+142
View File
@@ -175,9 +175,18 @@ test("update: prints the version change, one line per piece by name, the release
assert.doesNotMatch(out, /Happy coding|PARAMETERS|To go back to a release/);
});
const LAUNCHER_VERSION = path.join(HOME, ".plan2code", "bin", "version.json");
/** The installed plan2code command's version.json, as installLauncher() writes it. */
function writeLauncherVersion(version) {
fs.mkdirSync(path.dirname(LAUNCHER_VERSION), { recursive: true });
fs.writeFileSync(LAUNCHER_VERSION, JSON.stringify({ name: "Plan2Code", version }));
}
test("update: already on the new version it says so and stops, until --force", async () => {
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] }));
writeLauncherVersion(VERSION);
const idle = fakeSteps();
const stopped = await runUpdate(idle.steps);
assert.equal(stopped.code, 0, stopped.out);
@@ -202,6 +211,52 @@ test("update: already on the new version it says so and stops, until --force", a
assert.match(out, new RegExp(`Updating ${VERSION.replace(/\./g, "\\.")} -> ${VERSION.replace(/\./g, "\\.")}`));
});
test("update: a record on the new version over an older plan2code command installs again, without --force", async () => {
// An update stopped after the skills step: the record says new, the command is still old.
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] }));
for (const launcher of ["1.0.0", null]) {
if (launcher) writeLauncherVersion(launcher);
else fs.rmSync(LAUNCHER_VERSION, { force: true });
const fake = fakeSteps();
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 0, out);
assert.doesNotMatch(out, /Already on/);
assert.match(out, new RegExp(`The plan2code command is still on ${launcher ? "1\\.0\\.0" : "an unknown version"}`));
assert.deepEqual(fake.ran(), ["skills"]);
assert.match(out, /plan2code command: updated/);
}
// A record without the command does not look at its version.json.
fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["statusline"] }));
const idle = fakeSteps();
assert.match((await runUpdate(idle.steps)).out, /Already on/);
assert.deepEqual(idle.ran(), []);
});
test("update: the record keeps the old version until every piece is in, so a stopped update retries", async () => {
writeRecord(["skills", "launcher", "app"]);
const seen = [];
const fake = fakeSteps();
// As the real steps: each records its piece as it finishes.
for (const piece of ["skills", "app"]) {
const step = fake.steps[piece];
fake.steps[piece] = async (options) => {
const code = await step(options);
installer.recordInstalled(piece);
seen.push(installer.readInstallRecord().version);
return code;
};
}
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 0, out);
assert.deepEqual(seen, ["1.0.0", "1.0.0"], "mid-update writes keep the old version");
assert.equal(installer.readInstallRecord().version, VERSION, "stamped once the update finished");
assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]);
// Outside an update, a record write stamps the version being installed again.
installer.recordInstalled("statusline");
assert.equal(installer.readInstallRecord().version, VERSION);
});
test("update: a step's own output stays out of the summary, except its warnings and its failures", async () => {
writeRecord(["skills", "statusline", "bot"]);
const fake = fakeSteps();
@@ -312,6 +367,93 @@ test("install.js --update: an option other than --force is refused", () => {
assert.match(refused.stderr, /Unknown option\(s\): --update --nope/);
});
const SHA_RELEASE = "a".repeat(40);
const SHA_OLD_RELEASE = "b".repeat(40);
const SHA_MAIN = "c".repeat(40);
const TAGS = [`${SHA_OLD_RELEASE}\trefs/tags/v3.0.2`, `${SHA_RELEASE}\trefs/tags/v3.1.2`, `${"d".repeat(40)}\trefs/tags/nightly`].join("\n");
test("release redirect: unreleased work goes to the newest release; a release commit, a chosen ref or an unknown stays", () => {
const ref = (commit, extra = {}) => installer.releaseRedirectRef({ commit, lsRemote: TAGS, newest: "3.1.2", env: {}, ...extra });
assert.equal(ref(SHA_MAIN), "v3.1.2");
assert.equal(ref(SHA_RELEASE), null, "the newest release (and the release branch on it) stays");
assert.equal(ref(SHA_OLD_RELEASE), null, "an older launcher's update --tag v3.0.2 stays on v3.0.2");
assert.equal(ref("d".repeat(40)), "v3.1.2", "a tag that is not vX.Y.Z is not a release");
assert.equal(ref(SHA_MAIN, { env: { PLAN2CODE_INSTALL_REF: "main" } }), null, "the current launcher's --main stays on main");
assert.equal(ref(null), null);
assert.equal(ref(SHA_MAIN, { newest: null }), null);
assert.equal(ref(SHA_MAIN, { lsRemote: null }), null);
// An annotated tag's commit is on its peeled line.
assert.equal(ref(SHA_MAIN, { lsRemote: `${"e".repeat(40)}\trefs/tags/v3.1.2\n${SHA_MAIN}\trefs/tags/v3.1.2^{}` }), null);
});
/** install.js laid out as npx leaves a git package: node_modules/plan2code beside npm's hidden lock file. */
function npxCopy(commit) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-npx-copy-"));
const pkg = path.join(dir, "node_modules", "plan2code");
fs.mkdirSync(path.join(pkg, "src", "web-console"), { recursive: true });
fs.copyFileSync(INSTALL, path.join(pkg, "install.js"));
fs.copyFileSync(path.join(ROOT, "version.json"), path.join(pkg, "version.json"));
fs.copyFileSync(path.join(ROOT, "src", "web-console", "update-check.mjs"), path.join(pkg, "src", "web-console", "update-check.mjs"));
if (commit) {
const resolved = `git+ssh://git@github.com/jparkerweb/plan2code.git#${commit}`;
fs.writeFileSync(path.join(dir, "node_modules", ".package-lock.json"), JSON.stringify({ packages: { "node_modules/plan2code": { version: VERSION, resolved } } }));
}
fs.writeFileSync(path.join(dir, "ls-remote.txt"), TAGS + "\n");
// A stand-in npx that records its arguments and the ref the redirect handed it.
const bin = path.join(dir, "bin");
fs.mkdirSync(bin);
const recorder = path.join(bin, "record.js");
fs.writeFileSync(
recorder,
'require("fs").writeFileSync(require("path").join(__dirname, "npx.json"), JSON.stringify({ args: process.argv.slice(2), ref: process.env.PLAN2CODE_INSTALL_REF }));\nprocess.exitCode = 5;\n'
);
if (process.platform === "win32") fs.writeFileSync(path.join(bin, "npx.cmd"), `@"${process.execPath}" "${recorder}" %*\r\n`);
else {
fs.writeFileSync(path.join(bin, "npx"), `#!/bin/sh\nexec "${process.execPath}" "${recorder}" "$@"\n`);
fs.chmodSync(path.join(bin, "npx"), 0o755);
}
const run = (args, env = {}) => {
const runEnv = { ...process.env, HOME, USERPROFILE: HOME, PLAN2CODE_LS_REMOTE_FILE: path.join(dir, "ls-remote.txt"), ...env };
delete runEnv.PLAN2CODE_INSTALL_REF;
for (const key of Object.keys(runEnv)) if (key.toUpperCase() === "PATH") delete runEnv[key];
runEnv.PATH = bin + path.delimiter + (process.env.PATH || process.env.Path || "");
Object.assign(runEnv, env);
return spawnSync(process.execPath, [path.join(pkg, "install.js"), ...args], { encoding: "utf8", env: runEnv, input: "" });
};
const npx = () => (fs.existsSync(path.join(bin, "npx.json")) ? JSON.parse(fs.readFileSync(path.join(bin, "npx.json"), "utf8")) : null);
return { dir, run, npx, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
}
test("release redirect: an old launcher's update from main runs the newest release's installer with the same options", (t) => {
const copy = npxCopy(SHA_MAIN);
t.after(copy.cleanup);
const result = copy.run(["--update", "--force"]);
assert.equal(result.status, 5, "the release installer's exit code is passed through\n" + result.stderr);
assert.match(result.stdout, /switching to the newest release, v3\.1\.2/);
const { args, ref } = copy.npx();
assert.deepEqual(args, ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#v3.1.2", "--update", "--force"]);
assert.equal(ref, "v3.1.2", "the handed-off run is marked, so it never redirects again");
});
test("release redirect: a release copy, a run the launcher chose, or a copy with no lock file is not redirected", (t) => {
for (const [commit, env] of [[SHA_RELEASE, {}], [SHA_MAIN, { PLAN2CODE_INSTALL_REF: "main" }], [null, {}]]) {
const copy = npxCopy(commit);
t.after(copy.cleanup);
// An unknown option shows the run carried on here: the usage error, and no npx.
const result = copy.run(["--update", "--nope"], env);
assert.equal(result.status, 1, result.stdout + result.stderr);
assert.match(result.stderr, /Unknown option\(s\)/);
assert.equal(copy.npx(), null);
}
});
test("release redirect: an interactive install from main is handed to the newest release too", (t) => {
const copy = npxCopy(SHA_MAIN);
t.after(copy.cleanup);
assert.equal(copy.run([]).status, 5);
assert.deepEqual(copy.npx().args.slice(-1), ["git+https://github.com/jparkerweb/plan2code.git#v3.1.2"]);
});
test("update: the real status line step keeps a custom statusLine without asking", async () => {
const claudeDir = path.join(HOME, ".claude");
const settingsFile = path.join(claudeDir, "settings.json");
+3
View File
@@ -115,10 +115,12 @@
"test-web-console-page-cards.mjs",
"test-web-console-page-changes.mjs",
"test-web-console-page-dashboard.mjs",
"test-web-console-page-layout.mjs",
"test-web-console-page-git.mjs",
"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",
@@ -127,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",
+5
View File
@@ -58,6 +58,8 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
fs.writeFileSync(
recorder,
'require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".json"), JSON.stringify(process.argv.slice(3)));\n' +
// The ref the launcher marks its installer runs with, so install.js never redirects them.
'if (process.env.PLAN2CODE_INSTALL_REF) require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".ref"), process.env.PLAN2CODE_INSTALL_REF);\n' +
"process.exitCode = Number(process.env.P2C_TEST_EXIT || 0);\n"
);
for (const cli of clis) {
@@ -503,6 +505,7 @@ test("launcher: update installs the newest release tag, by version and not by na
assert.ok(args.includes("--update"), args.join(" "));
assert.ok(args.includes(`${REPO}#v3.10.0`), args.join(" "));
assert.ok(!args.includes("--force"), args.join(" "));
assert.equal(fs.readFileSync(path.join(box.dir, "bin", "npx.ref"), "utf8"), "v3.10.0", "the run is marked with the ref it picked");
assert.equal(box.argsOf("claude"), null);
});
@@ -518,6 +521,8 @@ test("launcher: update --main installs the tip of main, as it always did", (t) =
// Unreleased work on main carries the last release's version, so the installer's "Already on"
// check would stop it: --main always reinstalls.
assert.ok(args.includes("--force"), args.join(" "));
// Marked as chosen, so install.js's redirect for older launchers leaves it on main.
assert.equal(fs.readFileSync(path.join(box.dir, "bin", "npx.ref"), "utf8"), "main");
});
test("launcher: update --tag reinstalls for a branch, and not for a release tag", (t) => {
+15 -4
View File
@@ -27,6 +27,17 @@ const FIXTURES = path.join(ROOT, "scripts", "fixtures", "deps");
const MANIFESTS = path.join(FIXTURES, "manifests");
const readJson = (...p) => JSON.parse(fs.readFileSync(path.join(FIXTURES, ...p), "utf8"));
// Recorded npm projects keep their lockfile as package-lock.fixture.json, so
// dependency scanners never read the old versions the recordings pin as the
// repository's own. A copy gets the real name back.
const FIXTURE_LOCK = "package-lock.fixture.json";
function copyFixture(src, dir) {
fs.cpSync(src, dir, { recursive: true });
for (const rel of fs.readdirSync(dir, { recursive: true })) {
if (path.basename(rel) === FIXTURE_LOCK) fs.renameSync(path.join(dir, rel), path.join(dir, path.dirname(rel), "package-lock.json"));
}
}
const runDeps = (args, opts) => runScript("plan2code-deps", "deps.mjs", args, opts);
const made = [];
@@ -849,7 +860,7 @@ function runStubbed(args, pathDir) {
/** The recorded project copied into a temp folder (extra files on top), so a run never touches the fixture. */
function project(extra = {}) {
const dir = tmp("deps-project");
fs.cpSync(path.join(NPM, "project"), dir, { recursive: true });
copyFixture(path.join(NPM, "project"), dir);
for (const [rel, content] of Object.entries(extra)) write(dir, rel, typeof content === "string" ? content : JSON.stringify(content, null, 2) + "\n");
return dir;
}
@@ -1206,7 +1217,7 @@ test("apply refuses a batch with no backup (exit 5) and reports a pick that neve
test("backup then restore --verify puts an untracked CRLF lockfile and a tracked one back byte for byte", () => {
const root = project({
"web/package.json": fs.readFileSync(path.join(NPM, "project", "package.json"), "utf8"),
"web/package-lock.json": fs.readFileSync(path.join(NPM, "project", "package-lock.json"), "utf8"),
"web/package-lock.json": fs.readFileSync(path.join(NPM, "project", FIXTURE_LOCK), "utf8"),
});
// The root lockfile is untracked and written with CRLF, as some Windows tools leave one: put back exactly as found.
const lockPath = path.join(root, "package-lock.json");
@@ -1534,7 +1545,7 @@ const UV = fx("uv-0.13.7");
/** A recorded project folder copied into a temp folder, extra files on top. */
function copyFrom(src, extra = {}) {
const dir = tmp("deps-eco");
fs.cpSync(src, dir, { recursive: true });
copyFixture(src, dir);
for (const [rel, content] of Object.entries(extra)) write(dir, rel, content);
return dir;
}
@@ -2564,7 +2575,7 @@ const PINS = fx("pins", "project");
/** The pins fixture project copied into a temp folder, with extra files on top. */
function pinsProject(extra = {}) {
const dir = tmp("deps-pins");
fs.cpSync(PINS, dir, { recursive: true });
copyFixture(PINS, dir);
for (const [rel, content] of Object.entries(extra)) write(dir, rel, content);
return dir;
}
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -374,7 +374,8 @@ test("wait reads --seconds 6s as six seconds, not as nothing", () => {
});
test("only an installed console's open leaves the console-dir pointer; status, help, a bad command and a source checkout's open do not", () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-"));
// macOS hands out a temp folder under the /var link, and the console writes the real path.
const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-")));
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
const pointer = path.join(home, "console-dir");
fs.writeFileSync(path.join(home, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
+78 -8
View File
@@ -14,9 +14,9 @@ import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { ENV, HOME, LEARNING_DIR, ROOT, cli, postPatch, readState, sessionUrl } from "./web-console-test-helpers.mjs";
import { learningScan, storeDir, writePause, writeWaiting } from "../src/web-console/learning.mjs";
import { followCounts, learningScan, lessonsNearCap, recordFollow, storeDir, writePause, writeWaiting } from "../src/web-console/learning.mjs";
import { sessionActions } from "../src/web-console/cmd-post-wait.mjs";
import { indentReply, learningAction, learningBannerText, learningReply, lessonsReply } from "../src/web-console/public/answers.js";
import { indentReply, learningAction, learningBannerText, learningNearCapText, learningReply, lessonDecisionLine, lessonsReply } from "../src/web-console/public/answers.js";
const LESSONS = path.join(ROOT, "src", "skill-scripts", "lessons.mjs");
@@ -67,7 +67,7 @@ function dashboard(t, dir) {
test("scan.learning: not set up, off, on and paused, with the waiting count", (t) => {
const none = project();
const s1 = dashboard(t, none);
assert.deepEqual(readState(s1.session).scan.learning, { state: "not-set-up", pausedSince: null, waiting: 0, oldestDays: 0 });
assert.deepEqual(readState(s1.session).scan.learning, { state: "not-set-up", pausedSince: null, waiting: 0, oldestDays: 0, nearCap: false });
const off = project(SETTINGS("off"));
assert.equal(readState(dashboard(t, off).session).scan.learning.state, "off");
@@ -76,7 +76,7 @@ test("scan.learning: not set up, off, on and paused, with the waiting count", (t
const noted = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000 - 60000).toISOString();
writeWaiting(on, { id: "20261111-120000-abcdef", type: "lesson", text: "A lesson.", noted });
writeWaiting(on, { id: "20261112-120000-abcdef", type: "lesson", text: "Another.", noted: new Date().toISOString() });
assert.deepEqual(readState(dashboard(t, on).session).scan.learning, { state: "on", pausedSince: null, waiting: 2, oldestDays: 2 });
assert.deepEqual(readState(dashboard(t, on).session).scan.learning, { state: "on", pausedSince: null, waiting: 2, oldestDays: 2, nearCap: false });
const paused = project(SETTINGS("on"));
const pause = writePause(paused, true, "2026-11-13T09:00:00.000Z");
@@ -92,6 +92,33 @@ test("scan.learning is absent for a settings format this console does not know",
assert.equal("learning" in scan, false, "no learning field, so the page draws no row");
});
// An area file holding `n` lessons.
const lessonFile = (title, n) =>
`# ${title}\n\n` + Array.from({ length: n }, (_, i) => `### Lesson number ${i}\n- Kind: how-it-works\n- About: src/a.js\n- Noted: 2026-11-01, Implement\n`).join("\n");
test("scan.learning.nearCap: true at 22 general lessons or 30 in an area, false below, and only while Learning is on", (t) => {
const near = (files) => learningScan(project(files)).nearCap;
assert.equal(near({ ...SETTINGS("on") }), false, "no lessons folder");
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 21) }), false);
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 22) }), true);
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 25) }), true);
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/web.md": lessonFile("Web", 29) }), false);
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/web.md": lessonFile("Web", 30) }), true);
// 22 is the general file's line only: an area at 22 is not crowded.
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/web.md": lessonFile("Web", 22) }), false);
// Either file is enough, and CRLF files count the same.
assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 3), ".plan2code/lessons/web.md": lessonFile("Web", 30).replace(/\n/g, "\r\n") }), true);
// Not on: no nudge, however full.
assert.equal(near({ ...SETTINGS("off"), ".plan2code/lessons/general.md": lessonFile("General", 25) }), false);
assert.equal(lessonsNearCap(project({ ".plan2code/lessons/general.md": lessonFile("General", 25) })), true, "the count itself ignores the state");
// It reaches the page through the dashboard's scan.
const full = project({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 23) });
assert.equal(readState(dashboard(t, full).session).scan.learning.nearCap, true);
const before = listing(full);
learningScan(full);
assert.deepEqual(listing(full), before, "the scan writes nothing");
});
test("a failure in Learning's core never fails the scan", () => {
const boom = () => {
throw new Error("the core broke");
@@ -109,7 +136,7 @@ test("an unreadable learning store reads as empty: on, not paused, nothing waiti
fs.writeFileSync(store, "not a folder");
t.after(() => fs.rmSync(store, { force: true }));
const s = dashboard(t, dir);
assert.deepEqual(readState(s.session).scan.learning, { state: "on", pausedSince: null, waiting: 0, oldestDays: 0 });
assert.deepEqual(readState(s.session).scan.learning, { state: "on", pausedSince: null, waiting: 0, oldestDays: 0, nearCap: false });
});
test("the scan reads without pruning: an old waiting item stays on disk", (t) => {
@@ -170,7 +197,7 @@ test("GET /learning/state answers the scan's object, worked out now", async (t)
writeWaiting(dir, { id: "20261113-120000-bbbbbb", type: "lesson", text: "New.", noted: new Date().toISOString() });
const res = await s.get("/learning/state");
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { state: "on", pausedSince: null, waiting: 1, oldestDays: 0 });
assert.deepEqual(await res.json(), { state: "on", pausedSince: null, waiting: 1, oldestDays: 0, nearCap: false });
const unknown = dashboard(t, project({ ".plan2code/settings.json": "{}" }));
assert.deepEqual(await (await unknown.get("/learning/state")).json(), {});
@@ -208,13 +235,37 @@ test("GET /learning/lessons: general first, then the rest by name; no sub-folder
if (linked) assert.equal(files.some((f) => f.name === "linked.md"), false, "the link out was not followed");
const empty = dashboard(t, project(SETTINGS("on")));
assert.deepEqual(await (await empty.get("/learning/lessons")).json(), { files: [] });
assert.deepEqual(await (await empty.get("/learning/lessons")).json(), { files: [], follows: {} });
});
test("followCounts: sums lines per lesson, keeps the latest time and skips an unreadable line", () => {
const dir = project(SETTINGS("on"));
assert.deepEqual(followCounts(dir), {}, "no file yet");
recordFollow(dir, { lesson: "web/a", skill: "implement" }, new Date("2026-11-10T09:00:00Z"));
recordFollow(dir, { lesson: "web/a", skill: "quick-task" }, new Date("2026-11-20T09:00:00Z"));
recordFollow(dir, { lesson: "web/b", skill: "implement" }, new Date("2026-11-12T09:00:00Z"));
fs.appendFileSync(path.join(storeDir(dir), "follows.ndjson"), "{ not json\n\n{\"lesson\":3}\n");
recordFollow(dir, { lesson: "web/a", skill: "implement" }, new Date("2026-11-15T09:00:00Z"));
assert.deepEqual(followCounts(dir), {
"web/a": { count: 3, last: "2026-11-20T09:00:00.000Z" },
"web/b": { count: 1, last: "2026-11-12T09:00:00.000Z" },
});
assert.equal(listing(dir).some((f) => f.includes("follows")), false, "nothing written into the project");
});
test("GET /learning/lessons carries follows from this machine's store", async (t) => {
const dir = project({ ...SETTINGS("on"), ".plan2code/lessons/general.md": "# General\n\n### A lesson\n- Kind: how-it-works\n- About: src/x.js\n- Noted: 2026-11-01, Implement\n" });
recordFollow(dir, { lesson: "general/a-lesson", skill: "implement" }, new Date("2026-11-10T09:00:00Z"));
recordFollow(dir, { lesson: "general/a-lesson", skill: "implement" }, new Date("2026-11-11T09:00:00Z"));
const s = dashboard(t, dir);
const body = await (await s.get("/learning/lessons")).json();
assert.deepEqual(body.follows, { "general/a-lesson": { count: 2, last: "2026-11-11T09:00:00.000Z" } });
});
/* ------------------------------------------------- the action and reply */
test("a Learning action reaches the agent whole, and a launch keeps fromBanner", () => {
for (const what of ["review", "switch-on", "switch-off", "move-log", "remove"]) {
for (const what of ["review", "switch-on", "switch-off", "move-log", "remove", "tidy"]) {
const action = learningAction(what);
assert.deepEqual(action, { i: "__learning", type: "learning", do: what });
assert.deepEqual(sessionActions({ actions: [action] }), [{ i: "__learning", do: what }]);
@@ -235,6 +286,25 @@ test("the waiting banner's line shows only while lessons wait and Learning is on
assert.equal(learningBannerText(undefined), "");
});
test("the tidy-up nudge's line shows only while Learning is on and the lessons are near their limit", () => {
assert.equal(learningNearCapText({ state: "on", waiting: 0, nearCap: true }), "Lessons are nearing their limit. Tidy up?");
assert.equal(learningNearCapText({ state: "on", waiting: 3, nearCap: true }), "Lessons are nearing their limit. Tidy up?", "beside the waiting line");
assert.equal(learningNearCapText({ state: "on", waiting: 0, nearCap: false }), "");
assert.equal(learningNearCapText({ state: "on", waiting: 0 }), "");
assert.equal(learningNearCapText({ state: "paused", nearCap: true }), "");
assert.equal(learningNearCapText({ state: "off", nearCap: true }), "");
assert.equal(learningNearCapText({ state: "not-set-up", nearCap: true }), "");
assert.equal(learningNearCapText(undefined), "");
});
test("a tidy row's decisions read as the change, never as an AGENTS.md file", () => {
const retire = { id: "t1", type: "tidy", change: "retire", text: "Retire: Draw the page from state Reason: Git marks it.", choices: ["Apply", "Leave"] };
const fix = { id: "f1", type: "agents-fix", file: ".agents-docs/AGENTS-code-style.md", text: "x", choices: ["Apply", "Reword", "Drop"] };
assert.equal(lessonDecisionLine(retire, { id: "t1", choice: "Apply" }), "Apply: Retire: Draw the page from state Reason: Git marks it.");
assert.equal(lessonDecisionLine(retire, { id: "t1", choice: "Leave" }), "Leave: Retire: Draw the page from state Reason: Git marks it.");
assert.equal(lessonDecisionLine(fix, { id: "f1", choice: "Apply" }), "Apply: .agents-docs/AGENTS-code-style.md", "a fix still shows its file");
});
/* ---------------------------------------------- the lessons card, end to end */
test("the lessons card from lessons.mjs list goes up on the dashboard, and a Keep comes back as a Keep line and a decisions file decide takes", async (t) => {
+58 -1
View File
@@ -104,6 +104,8 @@ import {
loopLessonsLine,
} from "../src/web-console/public/answers.js";
import { chatView } from "../src/web-console/public/chat.js";
import { LEARNING_BUSY_MS, LEARNING_CHECK_MS, learningBusyLimit, learningBusyNow } from "../src/web-console/public/selectors.js";
import { page } from "../src/web-console/public/state.js";
import { agoWords, whenTitle, whenWords } from "../src/web-console/public/labels.js";
import { ACCENTS, DEFAULT_ACCENT, RETIRED_ACCENTS, accentId } from "../src/web-console/public/palette.js";
import {
@@ -1672,7 +1674,7 @@ test("validate: a lessons item takes rows each with a type and its own choices,
const one = (extra) => validate({ items: [item(extra)] });
assert.deepEqual(one({ opening: "You are on main: kept lessons will be uncommitted changes here.", rows: [row({ why: "A full run hides it.", origin: "You said this.", note: "", flags: [], refused: null, area: "General", areas: ["General"] })] }), []);
assert.deepEqual(
one({ rows: ["lesson", "doubt", "gone", "agents-fix", "log-line", "area"].map((type, i) => row({ id: `w${i}`, type })) }),
one({ rows: ["lesson", "doubt", "gone", "agents-fix", "tidy", "log-line", "area"].map((type, i) => row({ id: `w${i}`, type })) }),
[],
"every row type the list gives"
);
@@ -1698,6 +1700,14 @@ test("validate: a lessons item takes rows each with a type and its own choices,
refused({ rows: [row()], suggested: ["Keep"] }, "suggested: must be");
refused({ rows: [row()], suggested: { w9: "Keep" } }, 'suggested "w9"');
refused({ rows: [row()], suggested: { w1: "Apply" } }, 'suggested "w1"');
// A Reword suggestion may carry the words its boxes start on.
assert.deepEqual(one({ rows: [row()], suggested: { w1: { choice: "Reword", text: "New words.", why: "A reason." } } }), [], "words with a Reword");
assert.deepEqual(one({ rows: [row()], suggested: { w1: { choice: "Keep" } } }), [], "the object form without words");
refused({ rows: [row()], suggested: { w1: { choice: "Keep", why: "A reason." } } }, 'suggested "w1" why');
refused({ rows: [row()], suggested: { w1: { choice: "Reword", why: "" } } }, 'suggested "w1" why');
refused({ rows: [row()], suggested: { w1: { choice: "Reword", text: 3 } } }, 'suggested "w1" text');
refused({ rows: [row()], suggested: { w1: { choice: "Reword", note: "x" } } }, 'suggested "w1" note');
refused({ rows: [row()], suggested: { w1: { text: "New words." } } }, 'suggested "w1"');
const two = validate({ items: [item({ rows: [row()] }), item({ id: "lessons-2", rows: [row()] })] });
assert.ok(two.some((p) => p.includes("2 lessons cards are open at once")), two.join(" | "));
@@ -1705,6 +1715,53 @@ test("validate: a lessons item takes rows each with a type and its own choices,
assert.deepEqual(answered, [], "an answered card does not count");
});
test("validate: a lessons row takes the check's verdicts and a tag, and the card how it was checked", () => {
const check = { fails: [{ test: "Search", reason: "It matches 3 files." }], doubts: [{ test: "Why", reason: "No reason given." }], passed: 2, suggestion: "A shorter wording." };
const row = (extra = {}) => ({ id: "w1", type: "lesson", text: "A lesson.", choices: ["Keep", "Reword", "Drop"], ...extra });
const item = (extra) => ({ id: "lessons", kind: "lessons", title: "Lessons to keep", status: "open", rows: [row()], ...extra });
const one = (extra) => validate({ items: [item(extra)] });
const refused = (extra, field) => {
const problems = one(extra);
assert.ok(problems.some((p) => p.includes(field)), `${field}: ${problems.join(" | ")}`);
};
assert.deepEqual(one({ rows: [row({ check, tag: "Checked in an earlier run" })], checked: { how: "helper", count: 6, seconds: 40 } }), [], "a good check, tag and how");
assert.deepEqual(one({ rows: [row({ check: { fails: [], doubts: [], passed: 4 }, tag: "Not checked yet" })], checked: { how: "same-agent", count: 1, seconds: 0 } }), []);
assert.deepEqual(one({ checked: { failed: "The checker answered with nothing usable." } }), [], "a check that could not run");
refused({ rows: [row({ check: { ...check, extra: 1 } })] }, 'row "w1" check "extra"');
refused({ rows: [row({ check: { ...check, passed: 5 } })] }, 'row "w1" check passed');
refused({ rows: [row({ check: { ...check, fails: [{ test: "Search", reason: 7 }] } })] }, 'row "w1" check fails[0]');
refused({ rows: [row({ check: { ...check, doubts: Array.from({ length: 5 }, () => ({ test: "a", reason: "b" })) } })] }, 'row "w1" check doubts');
refused({ rows: [row({ check: { ...check, suggestion: "x".repeat(201) } })] }, 'row "w1" check suggestion');
refused({ rows: [row({ tag: "Old" })] }, 'row "w1" tag');
refused({ checked: { how: "robot", count: 1, seconds: 1 } }, "checked");
refused({ checked: { how: "helper", count: -1, seconds: 1 } }, "checked");
refused({ checked: { failed: "x".repeat(201) } }, "checked");
});
test("learning busy: a Review or Tidy up the agent is still working on outlasts LEARNING_BUSY_MS, a switch never does", () => {
const saved = { S: page.S, learningBusy: page.learningBusy, pendingResult: page.pendingResult };
try {
page.pendingResult = null;
const at = (what, agoMs, status) => {
page.S = { agent: { status }, items: [] };
page.learningBusy = { what, from: "on", at: Date.now() - agoMs, seen: true };
return learningBusyNow("on");
};
page.S = { agent: { status: "working" }, items: [] };
assert.equal(learningBusyLimit({ what: "review" }), LEARNING_CHECK_MS);
assert.equal(learningBusyLimit({ what: "tidy" }), LEARNING_CHECK_MS);
assert.equal(learningBusyLimit({ what: "switch-on" }), LEARNING_BUSY_MS, "a switch keeps the short limit");
assert.ok(at("review", LEARNING_BUSY_MS + 10000, "working"), "a Review still being checked stays busy past 30 seconds");
assert.ok(at("tidy", LEARNING_BUSY_MS + 10000, "working"), "so does a Tidy up");
assert.equal(at("review", LEARNING_CHECK_MS + 1000, "working"), null, "but not past the check limit");
assert.equal(at("review", LEARNING_BUSY_MS + 10000, "waiting"), null, "an agent back to waiting ends it at the short limit");
page.pendingResult = { id: "x" };
assert.equal(learningBusyLimit({ what: "review" }), LEARNING_CHECK_MS, "a send not yet picked up counts as working");
} finally {
Object.assign(page, saved);
}
});
test("validate: a lesson's own words never get the lessons card refused, but the card's own text still can", () => {
const marker = "TASK_" + "COMPLETE";
const words = ["Requirements 12 and 13 are checked by check-versions.mjs.", "Risk 3 is the slow blame on Windows.", `Never print ${marker} in a spec file.`, "The grill step reads the map first."];
+331 -5
View File
@@ -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 });
}
});
+2 -2
View File
@@ -96,7 +96,7 @@ test("a press in the empty part of the answer box selects like a textarea: Shift
const range = () => host.evaluate((el) => [el.field.selectionStart, el.field.selectionEnd]);
const box = await host.boundingBox();
const low = { x: box.x + box.width / 2, y: box.y + box.height - 12 };
assert.equal(await host.evaluate((el) => getComputedStyle(el).cursor), "text", "the whole box shows the text pointer");
assert.equal(await styleOf(host, "cursor"), "text", "the whole box shows the text pointer");
await s.page.keyboard.press("Home");
// page.mouse takes no modifiers option: hold Shift on the keyboard.
@@ -621,7 +621,7 @@ test("a note box over the git board grows no box, and the card flows at its own
project: dir,
payload: { reread: true, board: { describe: "export-more" }, items: [confirm] },
});
await git.page.getByRole("tablist").waitFor();
await git.page.locator(".git-step").first().waitFor();
const gitCard = itemCard(git.page, "y1");
await gitCard.waitFor();
const note = gitCard.locator(".md-host").first();
+8
View File
@@ -91,6 +91,14 @@ test("each git tab keeps its own scroll place, across a tab switch and an agent
await tab("Changes").click();
await page.getByRole("tabpanel").getByText(/in the Save step above/).waitFor();
await scrollCard(page.locator("#main"), 120);
// The tabs sit below this short window, so a click on one scrolls the column to it first:
// a scroll like the person's own, which the board notes. Make it now and give the page a
// moment to note it, so the place Changes is left at is known before the switch.
// Done in the page in one step: a redraw may swap the tab for a new one at any moment.
await page.evaluate(() => {
document.getElementById("git-tab-branches").scrollIntoView({ block: "center" });
return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
});
const changesAt = await column();
assert.ok(changesAt > 0, "the board's column scrolls");
// Another tab opens at its own place, not where Changes was left.
+53
View File
@@ -0,0 +1,53 @@
// Page tests for the page shell: what keeps the console page itself from
// scrolling (only its panels scroll), checked at wide and narrow window sizes.
// A change to src/web-console/public/styles/ or index.html needs only this
// file, not the whole page suites. Run with:
// npm run test:page -- scripts/test-web-console-page-layout.mjs
//
// Each test drives the real console in a real Chrome or Edge through
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
// session per test.
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession } from "./page-test-helpers.mjs";
const suite = pageSuite(test);
// A plan session on the person's turn: one text question and the agent listening.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
test("the page itself never scrolls: oversized content stays inside its own panel", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.locator("#main [data-item=\"q1\"]").first().waitFor();
const page = await s.page.evaluate(() => {
const big = document.createElement("div");
big.style.cssText = "height: 5000px";
document.querySelector(".main").append(big);
const root = document.documentElement;
const before = { scrollHeight: root.scrollHeight, innerHeight: innerHeight };
scrollTo(0, 400);
return {
...before,
scrolled: scrollY,
rootOverflow: getComputedStyle(root).overflowY,
bodyOverflow: getComputedStyle(document.body).overflowY,
bodyHeight: Math.round(document.body.getBoundingClientRect().height),
};
});
assert.equal(page.rootOverflow, "hidden", "the page root never scrolls");
assert.equal(page.bodyOverflow, "hidden", "the body never scrolls");
assert.equal(page.bodyHeight, page.innerHeight, "the body is exactly the window tall");
assert.ok(page.scrollHeight <= page.innerHeight, "the page is never taller than the window (an absolutely placed bit in a panel stretched it)");
assert.equal(page.scrolled, 0, "the page does not move when asked to scroll");
});
test("the one-column layout (900px and narrower) keeps its page scroll", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.setViewportSize({ width: 600, height: 700 });
const narrow = await s.page.evaluate(() => getComputedStyle(document.documentElement).overflowY);
assert.equal(narrow, "visible", "its content sits under the first screen, so the lock must not apply");
});
+228 -1
View File
@@ -13,7 +13,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, textOf, styleOf, stylesOf, itemCard, sendAndCollect, settled, scrollCard } from "./page-test-helpers.mjs";
import { cli, until } from "./web-console-test-helpers.mjs";
import { writePause, writeWaiting } from "../src/web-console/learning.mjs";
import { recordFollow, writePause, writeWaiting } from "../src/web-console/learning.mjs";
const suite = pageSuite(test);
@@ -126,6 +126,32 @@ test("on: the row is after the last card group, before the tip, with no count of
assert.match(await textOf(dlg), /The project's lessons \(\.plan2code\/lessons\/, saved with the repository\)/);
});
test("the lessons reader draws a quiet follow line under each lesson's heading", async (t) => {
const lesson = (title) => `### ${title}\n- Kind: how-it-works\n- About: src/x.js\n- Noted: 2026-11-01, Implement\n\n`;
const { main } = await dashboard(
t,
{ ...PROJECT("on"), ".plan2code/lessons/general.md": `# General\n\n${lesson("Followed lesson")}${lesson("Untouched lesson")}${lesson("Once lesson")}` },
(project) => {
recordFollow(project, { lesson: "general/followed-lesson", skill: "implement" }, new Date("2026-11-10T12:00:00Z"));
recordFollow(project, { lesson: "general/followed-lesson", skill: "quick-task" }, new Date("2026-11-20T12:00:00Z"));
recordFollow(project, { lesson: "general/once-lesson", skill: "implement" }, new Date("2026-11-12T12:00:00Z"));
}
);
const row = main.locator("section.learn-row");
await row.waitFor();
await row.getByRole("button", { name: "Open the lessons" }).click();
const dlg = main.page().locator("#learn-lessons-modal");
await dlg.locator(".learn-follow").first().waitFor();
const lines = await dlg.locator(".learn-follow").allInnerTexts();
assert.equal(lines.length, 3, "one line per lesson");
assert.match(lines[0], /^Followed 2 times, last on Nov 2[01]$/);
assert.equal(lines[1], "Not followed yet");
assert.match(lines[2], /^Followed once, last on Nov 1[123]$/);
// The line sits right under its heading.
const order = await dlg.locator(".learn-lessons-file").evaluate((n) => [...n.children].map((c) => (c.classList.contains("learn-follow") ? "follow" : c.textContent.includes("Followed lesson") ? "heading" : "other")));
assert.equal(order.indexOf("follow"), order.indexOf("heading") + 1);
});
test("Pause for me repaints the row with no agent listening, both ways", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"));
const bottom = main.locator("section.learn-row.is-bottom");
@@ -153,6 +179,7 @@ test("More opens upward and closes on Escape and on a click outside", async (t)
assert.ok(m.y + m.height <= b.y + 1, `the menu opens above its button: ${JSON.stringify({ m, b })}`);
assert.deepEqual(await menu.getByRole("menuitem").allInnerTexts(), [
"Switch off for this project",
"Tidy up lessons",
"Move the failure log into lessons",
"Remove all lessons…",
]);
@@ -211,6 +238,50 @@ test("the banner shows only with lessons waiting, directly above the title", asy
assert.equal(await paused.main.locator(".learn-banner").count(), 0, "hidden while paused");
});
test("More has Tidy up lessons, which sends the tidy Learning action and shows working at once", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"));
const row = main.locator("section.learn-row.is-bottom");
await row.getByRole("button", { name: /More/ }).click();
await row.getByRole("menuitem", { name: "Tidy up lessons" }).click();
const got = s.wait(10);
assert.equal(got.code, 0, "the send reached the agent");
assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "tidy" }]);
await main.locator(".learn-banner").getByText("Looking over your lessons…").waitFor();
});
// An area file holding `n` lessons.
const lessonFile = (title, n) =>
`# ${title}\n\n` + Array.from({ length: n }, (_, i) => `### Lesson number ${i}\n- Kind: how-it-works\n- About: src/a.js\n- Noted: 2026-11-01, Implement\n`).join("\n");
test("the banner nudges a tidy-up when lessons are near their limit, and only then", async (t) => {
const full = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/general.md": lessonFile("General", 22) });
const banner = full.main.locator(".learn-banner");
await banner.waitFor();
assert.match(await textOf(banner), /Lessons are nearing their limit\. Tidy up\?/);
assert.equal(await banner.getByRole("button", { name: "Review" }).count(), 0, "nothing waits, so no Review");
await banner.getByRole("button", { name: "Tidy up" }).click();
const got = full.s.wait(10);
assert.equal(got.code, 0);
assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "tidy" }]);
// Beside the waiting line when lessons wait too.
const both = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/web.md": lessonFile("Web", 30) }, (p) =>
writeWaiting(p, { id: "20261113-120000-ffffff", type: "lesson", text: "Waits.", noted: new Date().toISOString() })
);
const two = both.main.locator(".learn-banner");
await two.waitFor();
const text = await textOf(two);
assert.match(text, /1 lesson is waiting for your review/);
assert.match(text, /Lessons are nearing their limit\. Tidy up\?/);
assert.equal(await two.getByRole("button", { name: "Review" }).count(), 1);
assert.equal(await two.getByRole("button", { name: "Tidy up" }).count(), 1);
// One short of the line, in general.md and in an area: no nudge.
const below = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/general.md": lessonFile("General", 21), ".plan2code/lessons/web.md": lessonFile("Web", 29) });
await below.main.locator("section.learn-row").waitFor();
assert.equal(await below.main.locator(".learn-banner").count(), 0, "no banner below the line");
});
test("a launch from a dashboard showing lessons waiting carries fromBanner", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"), (p) =>
writeWaiting(p, { id: "20261113-120000-eeeeee", type: "lesson", text: "Waits.", noted: new Date().toISOString() })
@@ -293,6 +364,29 @@ test("lessons card: each row shows its own choice words, and nothing is chosen",
assert.match(await textOf(rowOf(card, "w-area")), /Noted on feature\/x\./);
});
test("lessons card: a tidy row shows the change, the lessons it replaces and its reason, and Reword edits the new wording", async (t) => {
const merge = { id: "w-merge", type: "tidy", change: "merge", text: "Merge 2 lessons into: Keep modules small and kebab-case their files.", why: "They say the same thing twice.", origin: "", note: "", flags: [], refused: null, area: "Source", areas: ["General", "Source"], targets: [{ id: "source/keep-modules-small", text: "Keep modules small", area: "Source" }, { id: "source/name-files-in-kebab-case", text: "Name files in kebab case", area: "Source" }], wording: "Keep modules small and kebab-case their files.", wordingWhy: "Both keep the tree easy to scan.", choices: ["Apply", "Reword", "Leave"] };
const retire = { id: "w-retire", type: "tidy", change: "retire", text: "Retire: Draw the page from state Reason: Git marks it.", why: "", origin: "", note: "", flags: [], refused: null, area: "", areas: ["General", "Source"], targets: [{ id: "web/draw-the-page-from-state", text: "Draw the page from state", area: "Web" }], choices: ["Apply", "Leave"] };
const { s, card } = await lessonsCard(t, CARD([merge, retire]));
assert.deepEqual(await choicesOf(rowOf(card, "w-merge")).allInnerTexts(), ["Apply", "Reword", "Leave"]);
assert.deepEqual(await choicesOf(rowOf(card, "w-retire")).allInnerTexts(), ["Apply", "Leave"], "no Reword where there is no wording");
const text = await textOf(rowOf(card, "w-merge"));
assert.match(text, /Merge 2 lessons into: Keep modules small and kebab-case their files\./);
assert.match(text, /It replaces these lessons:\s+Keep modules small\s+Name files in kebab case/);
assert.match(text, /Why: They say the same thing twice\./);
assert.match(await textOf(rowOf(card, "w-retire")), /Retire: Draw the page from state Reason: Git marks it\./);
// Reword opens on the new wording and its own Why, not on the sentence describing the change.
await rowOf(card, "w-merge").getByRole("button", { name: "Reword" }).click();
const words = rowOf(card, "w-merge").getByLabel("The lesson");
assert.equal(await words.inputValue(), "Keep modules small and kebab-case their files.");
assert.equal(await rowOf(card, "w-merge").getByLabel("Why").inputValue(), "Both keep the tree easy to scan.");
await words.fill("Keep modules small and name their files in kebab case.");
await rowOf(card, "w-retire").getByRole("button", { name: "Apply" }).click();
const got = await sendAndCollect(s);
const decisions = got.actions.find((a) => a.i === "lessons").decisions;
assert.deepEqual(decisions, [{ id: "w-merge", choice: "Reword", text: "Keep modules small and name their files in kebab case.", why: "Both keep the tree easy to scan." }, { id: "w-retire", choice: "Apply" }]);
});
test("lessons card: Keep on one row sends only that row, and the rest are left waiting", async (t) => {
const { s, card } = await lessonsCard(t);
await rowOf(card, "w-lesson").getByRole("button", { name: "Keep" }).click();
@@ -409,6 +503,139 @@ test("lessons card: a refused row's Keep still chooses after its words go back a
]);
});
const CHECKED_ROWS = [
{ ...ROWS[0], id: "c-fail", text: "Never run the full suite.", check: { fails: [{ test: "Search", reason: "It matches 3 files." }], doubts: [], passed: 3 } },
{ ...ROWS[0], id: "c-doubt", text: "The handler is small.", tag: "Checked in an earlier run", check: { fails: [], doubts: [{ test: "Why", reason: "The reason repeats the lesson." }], passed: 3 } },
{ ...ROWS[0], id: "c-pass", text: "Use the helper.", check: { fails: [], doubts: [], passed: 4 } },
{ ...ROWS[0], id: "c-none", text: "Not looked at.", tag: "Not checked yet" },
{ ...ROWS[0], id: "c-all", text: "Every test flagged.", check: { fails: [{ test: "Search", reason: "No match." }, { test: "Worth", reason: "Already in AGENTS.md." }], doubts: [{ test: "Why", reason: "Thin." }, { test: "Clear", reason: "Vague." }], passed: 0 } },
];
test("lessons card: a Fail, a Doubt and a pass show their lines, and the outline follows suggested without choosing", async (t) => {
const { card } = await lessonsCard(t, CARD(CHECKED_ROWS, { suggested: { "c-fail": "Drop", "c-pass": "Keep" }, checked: { how: "helper", count: 4, seconds: 40 } }));
const fail = rowOf(card, "c-fail");
assert.match(await textOf(fail.locator(".lesson-check.fail")), /^Fail Search: It matches 3 files\.$/);
assert.equal(await fail.locator(".lesson-check.doubt").count(), 0);
assert.match(await textOf(fail.locator(".lesson-check-pass")), /^Passed the other 3$/);
const doubt = rowOf(card, "c-doubt");
assert.match(await textOf(doubt.locator(".lesson-check.doubt")), /^Doubt Why: The reason repeats the lesson\.$/);
assert.equal(await doubt.locator(".lesson-check.fail").count(), 0);
assert.match(await textOf(doubt.locator(".lessons-tag")), /^Checked in an earlier run$/);
const pass = rowOf(card, "c-pass");
assert.equal(await pass.locator(".lesson-check.fail, .lesson-check.doubt").count(), 0, "a pass lists no verdicts");
assert.match(await textOf(pass.locator(".lesson-check-pass")), /^Passed the check$/);
const none = rowOf(card, "c-none");
assert.equal(await none.locator(".lesson-checks").count(), 0, "a row never checked draws nothing");
assert.match(await textOf(none.locator(".lessons-tag")), /^Not checked yet$/);
const all = rowOf(card, "c-all");
assert.equal(await all.locator(".lesson-check.fail, .lesson-check.doubt").count(), 4);
assert.equal(await all.locator(".lesson-check-pass").count(), 0, "no pass line when nothing passed");
const outlined = async (row) => row.locator(".lessons-choices button.is-suggested").allInnerTexts();
assert.deepEqual(await outlined(fail), ["Drop"]);
assert.deepEqual(await outlined(doubt), [], "a Doubt outlines nothing");
assert.deepEqual(await outlined(pass), ["Keep"]);
assert.equal(await card.locator('.lessons-choices [aria-pressed="true"]').count(), 0, "nothing is chosen for the person");
assert.notEqual(await styleOf(fail.locator(".lesson-check.fail"), "color"), await styleOf(pass.locator(".lesson-check-pass"), "color"), "a Fail is not drawn like the quiet pass line");
const px = async (loc) => parseFloat(await styleOf(loc, "fontSize"));
assert.ok((await px(pass.locator(".lesson-check-pass"))) < (await px(fail.locator(".lesson-check.fail"))), "the pass line is smaller than a verdict line");
assert.match(await textOf(card.locator(".lessons-checked")), /^Checked 4 lessons in 40 seconds by a fresh helper that could only read$/);
});
test("lessons card: the how-checked line names the same agent, or why the check could not run", async (t) => {
const same = await lessonsCard(t, CARD(CHECKED_ROWS.slice(2, 3), { checked: { how: "same-agent", count: 1, seconds: 1 } }));
assert.match(await textOf(same.card.locator(".lessons-checked")), /^Checked 1 lesson in 1 second by the same agent that noted them$/);
const failed = await lessonsCard(t, CARD(CHECKED_ROWS.slice(3, 4), { checked: { failed: "the checker answered with nothing usable." } }));
assert.match(await textOf(failed.card.locator(".lessons-checked")), /^The check could not run: the checker answered with nothing usable\.$/);
const bare = await lessonsCard(t, CARD(CHECKED_ROWS.slice(3, 4)));
assert.equal(await bare.card.locator(".lessons-checked").count(), 0, "no line without a check");
});
test("lessons card: Use this wording opens Reword filled with the suggestion, and what is sent is a normal Reword", async (t) => {
const row = { ...ROWS[0], id: "c-sug", check: { fails: [], doubts: [{ test: "Search", reason: "Two files match." }], passed: 3, suggestion: "Run one page test file alone first." } };
const { s, card } = await lessonsCard(t, CARD([row]));
const li = rowOf(card, "c-sug");
assert.match(await textOf(li.locator(".lesson-suggestion")), /^Suggested wording: Run one page test file alone first\./);
await li.getByRole("button", { name: "Use this wording" }).click();
const edit = li.locator(".lessons-edit");
await edit.waitFor();
assert.equal(await li.getByRole("button", { name: "Reword" }).getAttribute("aria-pressed"), "true");
const text = edit.getByLabel("The lesson");
assert.equal(await text.inputValue(), "Run one page test file alone first.", "it opens on the suggestion, not the row's own words");
await text.fill("Run one page test file alone first, then the rest.");
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [
{ id: "c-sug", choice: "Reword", text: "Run one page test file alone first, then the rest.", why: "A full run hides the race." },
]);
});
test("lessons card: a Reword suggestion with words fills the lesson and Why boxes, open already or opened after", async (t) => {
const second = { ...ROWS[0], id: "w-later", text: "Another lesson.", why: "An old reason." };
const { s, card } = await lessonsCard(t, CARD([ROWS[0], second]));
const open = rowOf(card, "w-lesson");
// Reword picked before the suggestion lands.
await open.getByRole("button", { name: "Reword" }).click();
await open.locator(".lessons-edit").waitFor();
s.post({
items: [
{
id: "lessons",
suggested: {
"w-lesson": { choice: "Reword", text: "Run one page test file alone first.", why: "A full run hides a race between page tests." },
"w-later": { choice: "Reword", why: "The newer reason." },
},
},
],
agent: { status: "waiting" },
});
await open.locator(".lessons-choices button.is-suggested", { hasText: "Reword" }).waitFor();
await until(async () => (await open.getByLabel("Why").inputValue()) === "A full run hides a race between page tests.", 3000);
assert.equal(await open.getByLabel("The lesson").inputValue(), "Run one page test file alone first.", "the lesson box takes the suggested words");
// Reword opened after the suggestion: a suggestion without text keeps the row's own words.
const later = rowOf(card, "w-later");
await later.getByRole("button", { name: "Reword" }).click();
await later.locator(".lessons-edit").waitFor();
assert.equal(await later.getByLabel("Why").inputValue(), "The newer reason.");
assert.equal(await later.getByLabel("The lesson").inputValue(), "Another lesson.");
// What the person types afterwards stays through a later push.
await open.getByLabel("Why").fill("My own reason.");
s.post({ agent: { status: "waiting", activity: "Still here" } });
await settled(s.page, "#main");
assert.equal(await open.getByLabel("Why").inputValue(), "My own reason.", "the suggestion is applied once, never over typing");
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [
{ id: "w-lesson", choice: "Reword", text: "Run one page test file alone first.", why: "My own reason." },
{ id: "w-later", choice: "Reword", text: "Another lesson.", why: "The newer reason." },
]);
});
test("lessons card: suggested words fill an area's name without a Why, and leave a log line's several lessons whole", async (t) => {
const area = ROWS[4];
const log = { ...ROWS[3], id: "log:two", lessons: ["Run npm run fix:eol for line endings.", "Check .gitattributes first."] };
const { s, card } = await lessonsCard(t, CARD([area, log]));
s.post({
items: [
{
id: "lessons",
suggested: {
"w-area": { choice: "Rename", text: "Games", why: "Ignored: an area has no Why." },
"log:two": { choice: "Reword and move", text: "One sentence.", why: "Line endings break the diff." },
},
},
],
agent: { status: "waiting" },
});
const areaRow = rowOf(card, "w-area");
await areaRow.locator(".lessons-choices button.is-suggested", { hasText: "Rename" }).waitFor();
await areaRow.getByRole("button", { name: "Rename" }).click();
await until(async () => (await areaRow.getByLabel("The area's name").inputValue()) === "Games", 3000);
assert.equal(await areaRow.getByLabel("Why").count(), 0, "an area has no Why box");
const logRow = rowOf(card, "log:two");
await logRow.getByRole("button", { name: "Reword and move" }).click();
await until(async () => (await logRow.getByLabel("Why").inputValue()) === "Line endings break the diff.", 3000);
assert.equal(await logRow.getByLabel("Lesson 1").inputValue(), "Run npm run fix:eol for line endings.", "the several lessons stay");
assert.equal(await logRow.getByLabel("Lesson 2").inputValue(), "Check .gitattributes first.");
});
test("lessons card: a flagged row says what was flagged", async (t) => {
const flagged = { ...ROWS[0], id: "w-flag", flags: [{ pattern: "email", part: "a@b.c" }] };
const { card } = await lessonsCard(t, CARD([flagged]));
+34
View File
@@ -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");
});
+1 -1
View File
@@ -544,7 +544,7 @@ test("each tab keeps its own text and pictures, and switching never saves into t
const notes = idOf(s, "Notes");
const ideas = idOf(s, "Ideas");
// The new tab opens with its heading and the editor focused: clear it to start from empty.
await s.page.keyboard.press("Control+a");
await s.page.keyboard.press("ControlOrMeta+a");
await s.page.keyboard.press("Delete");
await until(() => readNotepad(s.project, notes).text === "notes text" && readNotepad(s.project, ideas).text === "", 4000);
await typeInto(s, "ideas text");
+3
View File
@@ -973,6 +973,9 @@ test("the Subagents dialog looks as it did before Preferences moved to tabs", as
second: await stylesOf(modal.locator("fieldset.modal-ranges").nth(1), ["margin-top"]),
actions: await stylesOf(modal.locator(".modal-actions"), ["display", "justify-content"]),
};
// Chrome 158 reads `justify-content: flex-end` back as "flow-end"; older Chrome and Edge
// say "flex-end". The stylesheet is the same either way, so count them as one.
if (got.actions["justify-content"] === "flow-end") got.actions["justify-content"] = "flex-end";
if (process.env.P2C_PRINT_SUBAGENTS) console.log("SUBAGENTS " + JSON.stringify(got));
assert.deepEqual(got, SUBAGENTS_BEFORE);
});
@@ -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);
});
+8 -1
View File
@@ -11,7 +11,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject , fillBox, boxValue, sendAsk, styleOf } from "./page-test-helpers.mjs";
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject , fillBox, boxValue, sendAsk, styleOf, quiet } from "./page-test-helpers.mjs";
import { cli, until, HOME } from "./web-console-test-helpers.mjs";
import { STOP_HANDOFF_REPLY, HOME_REPLY } from "../src/web-console/public/answers.js";
import { CHAT_OFFLINE_TEXT } from "../src/web-console/public/chat.js";
@@ -818,6 +818,10 @@ test("the quiet, not running and not connected lines offer What to check, openin
// Answered and sent, never collected, and nobody listening: the saved line.
await s.page.clock.setSystemTime(Date.now());
s.post({ agent: { status: "waiting" } });
// The post redraws the question: an answer typed before that redraw lands is lost with the
// old box, and Send then stays off. Wait for the page to show the post and go quiet.
await lineSays(s, /^Your turn: 1 question waiting\./);
await quiet(s.page);
await fillBox(itemCard(s.page, "q1").locator(".md-host, input[type=text]").first(), "audit-export");
await s.page.click("#btn-send");
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
@@ -1156,6 +1160,9 @@ async function strandedFinish(t, opts) {
const main = s.page.locator("#main");
await main.getByRole("button", { name: "Review it now" }).click();
await main.getByRole("button", { name: "Review requested…" }).waitFor();
// Let the page hear the press is saved while it is still fresh, as it does for a person:
// the way out then has to appear by time alone, with no frame to draw it.
await quiet(s.page, { quietMs: 1000 });
await s.page.clock.fastForward(200_000);
await s.page.waitForFunction(() => document.body.innerText.includes("Plan2Code is not running"));
return { s, main };
+199
View File
@@ -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");
});
+3 -1
View 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",
+6 -4
View File
@@ -693,15 +693,17 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
/* ---------------------------------------------------------------- help */
test("help: 23 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 23);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 23);
test("help: 24 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 24);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 24);
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
const ids = HELP_TABS.map((t) => t.id);
assert.equal(ids.indexOf("learning"), ids.indexOf("dashboard") + 1, "Learning comes right after The dashboard");
assert.equal(ids.indexOf("loop"), ids.indexOf("build") + 1, "Implementation Loop comes right after Watching a build");
assert.equal(HELP_TABS[ids.indexOf("loop")].label, "Implementation Loop");
assert.equal(ids.indexOf("git"), ids.indexOf("loop") + 1, "The git board comes right after Implementation Loop");
assert.equal(ids.indexOf("review-loop"), ids.indexOf("loop") + 1, "Review Loop comes right after Implementation Loop");
assert.equal(HELP_TABS[ids.indexOf("review-loop")].label, "Review Loop");
assert.equal(ids.indexOf("git"), ids.indexOf("review-loop") + 1, "The git board comes right after Review Loop");
assert.equal(HELP_TABS[ids.indexOf("git")].label, "The git board");
assert.equal(helpTabFor({ workflow: "git" }), "git");
assert.equal(ids.indexOf("deps"), ids.indexOf("git") + 1, "Update dependencies comes right after The git board");
+1 -1
View File
@@ -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", () => {
+32 -16
View File
@@ -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";
@@ -399,7 +399,7 @@ test("Implement's card launches Implement + Review when Review is ticked", () =>
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
});
test("helper-strength.md ships in the seventeen skills that start helpers, and in no other", () => {
test("helper-strength.md ships in the eighteen skills that start helpers (the dashboard for its lesson check only), and in no other", () => {
// npm test has just built skills/; a direct run builds it so the check never reads a stale tree.
if (process.env.npm_lifecycle_event !== "test") {
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
@@ -407,6 +407,7 @@ test("helper-strength.md ships in the seventeen skills that start helpers, and i
const built = path.join(ROOT, "skills");
const having = fs.readdirSync(built).filter((dir) => fs.existsSync(path.join(built, dir, "references", "helper-strength.md")));
assert.deepEqual(having.sort(), [
"plan2code",
"plan2code-0-pathfinder",
"plan2code-1-plan",
"plan2code-1b-revise-plan",
@@ -427,19 +428,34 @@ test("helper-strength.md ships in the seventeen skills that start helpers, and i
]);
});
// 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");
});
+17
View File
@@ -405,6 +405,23 @@ test("help: the stuck tab is second, and openHelpOn only opens a tab that exists
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
});
// A link that names a topic Help lacks falls back to wherever Help opened, so
// each loop's "How it works" link must open a topic of its own that exists.
test("help: each loop's link opens its own Help topic", () => {
const ids = HELP_TABS.map((t) => t.id);
assert.ok(ids.includes("review-loop"), "Help has a Review Loop topic");
assert.equal(HELP_TABS[ids.indexOf("review-loop")].label, "Review Loop");
const dash = publicSource("screens/dashboard.js");
const link = dash.match(/function loopHelpLink\(entry\) \{([\s\S]*?)\n\}/);
assert.ok(link, "dashboard.js has loopHelpLink");
assert.match(link[1], /openHelpOn\(review \? "review-loop" : "loop"\)/, "the dashboard's Review Loop link opens Review Loop, the other opens Implementation Loop");
const setup = publicSource("screens/review-loop-setup.js");
assert.match(setup, /"How the Review Loop works"/, "the Review Loop setup screen names its own loop");
assert.match(setup, /openHelpOn\("review-loop"\)/, "the Review Loop setup screen opens Review Loop");
assert.doesNotMatch(setup, /openHelpOn\("loop"\)/, "the Review Loop setup screen never opens Implementation Loop");
assert.match(publicSource("screens/loop-setup.js"), /openHelpOn\("loop"\)/, "the Implementation Loop setup still opens Implementation Loop");
});
test("models: the page's built-in rows match the shipped agent list's builtins", () => {
const app = publicSource("screens/agents/agents-data.js");
const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]);
+4
View File
@@ -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,
+14 -5
View File
@@ -6,6 +6,7 @@
"name": "Claude Code",
"kind": "builtin",
"command": "claude",
"helpers": true,
"prompt": "/plan2code",
"args": ["{prompt}", "{bypass}", "{model}"],
"bypassArgs": ["--permission-mode", "bypassPermissions"],
@@ -14,15 +15,16 @@
"install": {
"win": [
{ "label": "PowerShell", "run": "irm https://claude.ai/install.ps1 | iex" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code", "note": "Needs Node.js 22 or later" }
{ "label": "CMD", "run": "curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code@latest", "note": "Needs Node.js 22 or later" }
],
"mac": [
{ "label": "Terminal", "run": "curl -fsSL https://claude.ai/install.sh | bash" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code", "note": "Needs Node.js 22 or later" }
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code@latest", "note": "Needs Node.js 22 or later" }
],
"linux": [
{ "label": "Terminal", "run": "curl -fsSL https://claude.ai/install.sh | bash" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code", "note": "Needs Node.js 22 or later" }
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code@latest", "note": "Needs Node.js 22 or later" }
]
},
"installDirs": {
@@ -36,6 +38,7 @@
"name": "Devin",
"kind": "builtin",
"command": "devin",
"helpers": false,
"prompt": "/plan2code",
"args": ["{bypass}", "{model}", "--", "{prompt}"],
"bypassArgs": ["--permission-mode", "bypass"],
@@ -63,6 +66,7 @@
"name": "Codex",
"kind": "builtin",
"command": "codex",
"helpers": false,
"prompt": "$plan2code",
"args": ["{bypass}", "{model}", "{prompt}"],
"bypassArgs": ["--dangerously-bypass-approvals-and-sandbox"],
@@ -93,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"],
@@ -103,7 +108,8 @@
"name": "OpenCode",
"kind": "template",
"command": "opencode",
"prompt": "Use the plan2code skill",
"helpers": false,
"prompt": "@plan2code",
"args": ["{model}", "--prompt", "{prompt}"],
"bypassArgs": ["--auto"],
"modelArgs": ["--model", "{model}"]
@@ -113,17 +119,19 @@
"name": "Gemini CLI",
"kind": "template",
"command": "gemini",
"helpers": false,
"prompt": "Use the plan2code skill",
"args": ["{model}", "{prompt}"],
"bypassArgs": ["--approval-mode=yolo"],
"modelArgs": ["--model", "{model}"],
"note": "For Google AI Pro and Ultra accounts and free Gemini Code Assist for individuals, Gemini CLI was replaced by Antigravity CLI on June 18, 2026; Standard and Enterprise licenses and paid API keys are unaffected."
"note": "For Google AI Pro and Ultra accounts, free Gemini Code Assist for individuals and Gemini Code Assist for GitHub, Gemini CLI was replaced by Antigravity CLI on June 18, 2026; Standard and Enterprise licenses and paid API keys are unaffected."
},
{
"id": "pi",
"name": "Pi",
"kind": "template",
"command": "pi",
"helpers": false,
"prompt": "/skill:plan2code",
"args": ["{model}", "{prompt}"],
"modelArgs": ["--model", "{model}"]
@@ -133,6 +141,7 @@
"name": "Cursor CLI",
"kind": "template",
"command": "agent",
"helpers": false,
"prompt": "/plan2code",
"args": ["{model}", "{prompt}"],
"bypassArgs": ["--force"],
+46 -34
View File
@@ -15,7 +15,7 @@
},
{
"id": "haiku",
"label": "latest Haiku"
"label": "fast and efficient Haiku"
},
{
"id": "opusplan",
@@ -23,7 +23,7 @@
},
{
"id": "fable",
"label": "latest Fable"
"label": "Fable for your hardest tasks"
},
{
"id": "best",
@@ -79,22 +79,6 @@
"id": "gpt-6-luna-high",
"label": "GPT-6 Luna High Thinking"
},
{
"id": "gemini-3-8-flash-low",
"label": "Gemini 3.8 Flash Low"
},
{
"id": "gemini-3-8-flash-medium",
"label": "Gemini 3.8 Flash Medium"
},
{
"id": "gemini-3-8-flash-high",
"label": "Gemini 3.8 Flash High"
},
{
"id": "glm-5-3-low",
"label": "GLM-5.3 Low"
},
{
"id": "glm-5-3-high",
"label": "GLM-5.3 High"
@@ -115,18 +99,6 @@
"id": "claude-haiku-5-5-high",
"label": "Claude Haiku 5.5 High"
},
{
"id": "claude-fable-5-1-low",
"label": "Claude Fable 5.1 Low"
},
{
"id": "claude-fable-5-1-medium",
"label": "Claude Fable 5.1 Medium"
},
{
"id": "claude-fable-5-1-high",
"label": "Claude Fable 5.1 High"
},
{
"id": "gpt-6-astra-low",
"label": "GPT-6 Astra Low Thinking"
@@ -139,13 +111,45 @@
"id": "gpt-6-astra-high",
"label": "GPT-6 Astra High Thinking"
},
{
"id": "swe-2-flash-medium",
"label": "SWE-2 Flash Medium"
},
{
"id": "swe-2-flash-high",
"label": "SWE-2 Flash High"
},
{
"id": "claude-fable-5-2-low",
"label": "Claude Fable 5.2 Low"
},
{
"id": "claude-fable-5-2-medium",
"label": "Claude Fable 5.2 Medium"
},
{
"id": "claude-fable-5-2-high",
"label": "Claude Fable 5.2 High"
},
{
"id": "gemini-4-hydrogen-low",
"label": "Gemini 4 Hydrogen Low"
},
{
"id": "gemini-4-hydrogen-medium",
"label": "Gemini 4 Hydrogen Medium"
},
{
"id": "gemini-4-hydrogen-high",
"label": "Gemini 4 Hydrogen High"
},
{
"id": "gemini-4-neon-low",
"label": "Gemini 4 Neon Low"
},
{
"id": "gemini-4-neon-medium",
"label": "Gemini 4 Neon Medium"
},
{
"id": "gemini-4-neon-high",
"label": "Gemini 4 Neon High"
}
],
"codex": [
@@ -164,6 +168,14 @@
{
"id": "gpt-6-luna",
"label": "GPT-6 Luna"
},
{
"id": "gpt-6.2-astra",
"label": "GPT-6.2 Astra"
},
{
"id": "gpt-6.2-sol",
"label": "GPT-6.2 Sol"
}
],
"strengths": {
+5 -1
View File
@@ -1700,6 +1700,7 @@ async function runUpdate({ tag, main, force } = {}) {
}
console.log(ref === undefined ? 'Updating Plan2Code to the newest work on main...' : `Updating Plan2Code to ${ref}...`);
console.log(c.dim('One update covers the skills, the plan2code command and the desktop app (when installed).'));
console.log(c.dim('npx fetches it quietly first, which can take a minute or two.'));
const unreleased = main || (tag !== undefined && !/^v\d+\.\d+\.\d+$/.test(tag));
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], ref);
}
@@ -1745,7 +1746,10 @@ function runInstaller(installerArgs, tag) {
return process.exit(127);
}
const spec = tag ? `git+${REPO_URL}#${tag}` : `git+${REPO_URL}`;
const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit' });
// The ref was picked on purpose (main included): install.js's release redirect, there for
// launchers older than the release channel, must leave this run where it is.
const env = { ...process.env, PLAN2CODE_INSTALL_REF: tag || 'main' };
const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit', env });
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
process.on(signal, () => {});
}
+1 -1
View File
@@ -35,7 +35,7 @@ On `local`, the map's bookkeeping is a script; the decisions are yours. `node "<
Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record the outcome as the first line of `## Ground rules`: ``- `AGENTS.md` exists and governs.`` or, when missing, exactly ``- `AGENTS.md` is absent.`` (the handoff reads it).
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`).
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working).
## Rules
+1 -1
View File
@@ -33,7 +33,7 @@ Check if `./AGENTS.md` exists:
Do not proceed until user confirms continuing without `AGENTS.md`.
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); `<S>` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally.
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working); `<S>` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally.
## Rules
+1 -1
View File
@@ -13,7 +13,7 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
## Rules
- Follow `./AGENTS.md` if it exists
- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`).
- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working).
- Never remove completed `[x]` tasks without explicit approval
- Warn if changes invalidate completed work
- Keep task numbers sequential
+1 -1
View File
@@ -22,7 +22,7 @@ The FIRST thing you do, before anything else in this file — before Auto-Discov
## Rules
- Follow `./AGENTS.md` if it exists
- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`).
- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working).
- Require planning document before proceeding
- Tasks must be specific enough for a developer with NO context
- Use checkbox format `- [ ]` for Task items ONLY (not prerequisites, acceptance criteria, or success criteria)
+1 -1
View File
@@ -24,7 +24,7 @@ The FIRST thing you do, before anything else in this file — before the Require
## Rules
- Follow `./AGENTS.md` if it exists
- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`).
- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working).
- Complete steps IN ORDER
- STOP and ask user before proceeding when:
- Incomplete tasks found (Step 1)
+1 -1
View File
@@ -14,7 +14,7 @@ The FIRST thing you do, before anything else in this file, before running a scri
Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites or code reached by name. Dead Code still works without one, but the test map is what tells it which tests and build to run after a removal; without it the scripts read the project's config files, and the person confirms the commands.
**Lessons:** follow `references/lessons.md` → Start and While working.
**Lessons:** follow `references/lessons.md` → Start and While working; note only what the person asks you to remember (references/lessons.md, While working).
## Scripts
+1 -1
View File
@@ -14,7 +14,7 @@ The FIRST thing you do, before anything else in this file, before reading the br
Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites. PR Prep still works without one: the scripts find the project's commands from its config files, and nothing here needs Plan2Code's specs.
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`).
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working).
## Scripts
+1 -1
View File
@@ -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
+1 -1
View File
@@ -24,7 +24,7 @@ When this file is `references/ui-prototype.md` inside Pathfinder, Plan, Revise p
Read `./AGENTS.md` when it exists: its stack, its style files and its conventions help Step 1 find the look. Its absence does not block this skill.
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`).
**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "<S>/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working).
## Scripts
+2 -1
View File
@@ -139,7 +139,8 @@ The Learning row and banner send a `__learning` action with `do`. It is no hop:
- `switch-off`: `switch off`.
- `move-log`: `list --log-all`, then the card below.
- `remove`: `remove --confirm` (the page already asked).
- `review`: `list`, then the card below. While the state is `not-set-up`, `list --first-ask` instead: a `firstAsk` goes up as the reference's The first ask card (never `decide --file` before it), then `decide --first-ask yes` or `decide --first-ask no --skill dashboard`; on Yes, the card below from the list it returns.
- `tidy`: while Learning is On, `tidy-input`, then up to 10 proposals, each `note --type tidy --change merge|reword|retire|move --targets <ids> --reason "<one sentence>" --skill dashboard` (`--text` for a merge or reword, `--area` for a move; one change each, nothing for lessons that are fine). A retire's reason is what you saw: git marks it and the code no longer does this, or `followed` 0 and none in 90 days (a hint only, never alone for a lesson that is not marked). Then the `review` check step with `check-input --tidy`, `list --check <checkId>` and the card below. No proposals: say so in the menu's `note`. In `decide`'s results a tidy-up's `outOfDate` is gone (its lesson changed since), and `applied` and `left` need no follow-up.
- `review`: the check step from `references/lessons.md` End (check-input, the checker, check-record), with an `activity` line ("Checking 4 lessons") posted while it runs, then `list --check <checkId>` (`list` when there was nothing to check), then the card below. While the state is `not-set-up`, `list --first-ask` instead: a `firstAsk` goes up as the reference's The first ask card (never `decide --file` before it), then `decide --first-ask yes` or `decide --first-ask no --skill dashboard`; on Yes, the card below from the list it returns.
The card: post `list`'s `card` as one `lessons` item with `--wait` (the page shows it over the menu; give it a new `id` when an earlier lessons card is in the session). Write the reply's `Decisions:` JSON to a file in the session folder, adding what End step 6 says a choice still needs, run `decide --file <that file>`, and handle its results as End step 7 does. An empty `card` needs no post. The lessons card is the only question the dashboard shows: where End says to ask (a Move's `why` and `about`, or once more for an item), take `about` from the files the line names and post that row again as a new lessons card with the choices `Reword and move` and `Leave` (other rows: their own choices), its `note` saying what is needed.
+2 -1
View File
@@ -1,5 +1,5 @@
# Helper Strength
> Shared by the skills that start helpers (subagents): Init, Init Update, Pathfinder, Plan, Revise Plan, Document, Quick Task, Implement, Implement + Review, Review, Finalize, X-ray, Diagnose, PR Prep, Test, Dead Code and Update Dependencies. Read it when you first start a helper in a session. Never invoked as a skill.
> Shared by the skills that start helpers (subagents): the dashboard (lesson check only), Init, Init Update, Pathfinder, Plan, Revise Plan, Document, Quick Task, Implement, Implement + Review, Review, Finalize, X-ray, Diagnose, PR Prep, Test, Dead Code and Update Dependencies. Read it when you first start a helper in a session. Never invoked as a skill.
## The words
@@ -24,6 +24,7 @@ Never write a model or vendor name in a brief, a report or a file, and never inv
| Build task needing a design decision the spec leaves open | strongest (or keep it yourself) | high |
| Pathfinder research question, sketch | standard | medium |
| Plan's PLAN-DRAFT cross-check against the conversation | standard | medium |
| Lesson check (`lesson-check.md`) | standard | medium |
| Review analysis, focused scope | standard | high |
| Review analysis, branch or full scope, or touching security, auth or data | strongest | high |
+71
View File
@@ -0,0 +1,71 @@
# Lesson check: the checker's brief
> Read by the noting skills (Implement, Implement + Review, Quick Task, Diagnose, X-ray, Review, Test) and the dashboard when they start the checker, and by the checker itself. Never invoked as a skill.
You are the checker. You grade waiting lessons before a person decides on them. You judge only: the person still decides every lesson.
## Hard rules
- Never edit, create or delete any file.
- Never run a command. The search results you need are already in the input.
- Read only the files the input names (each lesson's `files`, plus `AGENTS.md` when `context.agentsMd` is set). Read nothing else.
- Judge only: no fixes, no advice outside a verdict's reason or suggestion.
- Return the JSON below as the whole reply: no prose before or after it, no code fence.
## The input
The JSON that `lessons.mjs check-input` printed:
- `checkId`: copy it into your reply unchanged.
- `lessons`: each with `id`, `text`, `why`, `kind`, `about`, `files` (`path`, `hash`, `read`: `whole` or `sampled`), `budgetHit` (true when files were left unread) and, when the lesson carries a search, `search` and `searchResult` (`matched`, `hits`, `filesSearched`).
- `context`: `agentsMd` (`AGENTS.md` or null), `saved` (the project's saved lessons: `id`, `text`) and `waiting` (the other waiting lessons: `id`, `text`).
## The four tests
Give every lesson all four, each a verdict and one sentence of reason.
- **true**: True against the code. Read the listed files and the search result: does the code still do what the lesson says? A `searchResult` that did not match, or matched where the lesson says it should not, counts against it.
- **worth**: Worth keeping. Not obvious from reading the code, not a one-off, and the `why` earns its place. A teammate's run would act differently because of it.
- **overlap**: Overlap or conflict. Compare with `context.saved`, `context.waiting` and `AGENTS.md`: a near-duplicate, or a statement that contradicts one. Name what it overlaps in the reason.
- **clear**: Clear enough. One sentence a teammate can act on without this conversation: it names the thing and says what to do.
## Tidy-ups
With `check-input --tidy`, a lesson may carry `type: "tidy"`, `change` (merge, reword, retire or move), `reason` and `targets` (the saved lessons it touches: `id`, `text`, `why`, `kind`, `about`, `area`). Give it the same four tests and the same reply shape, judging the change:
- merge, reword: the lesson under test is `text`, the new wording, with the targets' `about`. **true**: it is still true against the files. **worth**: it is worth more than the targets said apart. **overlap**: it overlaps `context.saved` (the targets are left out of it). **clear**: one sentence a teammate can act on. A merge that drops a fact its targets held is a Doubt on **true**.
- retire: grade the proposal, so Pass means the lesson should go. **true**: the reason holds against the files (the lesson no longer matches the code). **worth**: retiring loses nothing a teammate needs. **overlap**: no other saved lesson depends on it. **clear**: the reason is one plain sentence. `reason` is the proposer's view, never proof.
- Suggest a wording only for a merge or reword; a retire or move has none to change, and a suggestion there is dropped.
- move: `area` is where it lands (`targets[0].area` is where it is). **clear**: does the new area's name fit what the lesson is about? The other tests grade the lesson as it stands.
## The three verdicts
- **Pass**: it holds.
- **Doubt**: you cannot tell, or it is weak. Give a Doubt when you could not read enough to decide, when `budgetHit` is true and the unread files could change the answer, or when the search does not test what the lesson says.
- **Fail**: it is plainly wrong, a duplicate, a conflict, or unclear. Say what is wrong.
## A suggested wording
Optional, on a lesson with a Doubt or Fail where a better sentence would fix it. One sentence, at most 200 characters, in the same voice as the lesson, never a secret, a person's name or a customer detail. Leave `suggestion` out when you have none. A bad one is dropped.
## The reply
```json
{
"checkId": "<the input's checkId>",
"how": "helper",
"verdicts": [
{
"id": "<lesson id>",
"tests": {
"true": { "verdict": "Pass", "reason": "One sentence." },
"worth": { "verdict": "Pass", "reason": "One sentence." },
"overlap": { "verdict": "Doubt", "reason": "One sentence." },
"clear": { "verdict": "Pass", "reason": "One sentence." }
},
"suggestion": "Optional one-sentence wording."
}
]
}
```
One verdict per lesson in `lessons`, none for a lesson not listed. `how` is `helper` when you are a fresh helper, `same-agent` when the noting agent grades in a separate step. Every `reason` is one sentence of at most 200 characters, on one line, with no secret in it.
+16 -6
View File
@@ -27,9 +27,12 @@ Once per run: when a reference sends you here inside a run that already did Star
- Before the first edit in a folder outside the areas already read, run `read --paths <that folder> --run <handle>`, keep the new `run`, and print its `line` when not empty, such as "Read 3 more for Web console server."
- When a lesson changes what you do, and you would have done otherwise, print at that moment: "Following a lesson: <the lesson>".
Then run `node "<S>/lessons.mjs" follow --lesson <its id> --skill <this skill>` (the ids come from `read`) so the reader can show how often lessons are followed. It is recorded on this machine only and does nothing while Learning is off; skip it quietly when it fails.
- When your own memory disagrees with a lesson, follow the lesson and say "My own memory says otherwise; following the project's lesson: <the lesson>". If the person says the memory is right, note a doubt about that lesson.
The rest of this section is for the seven skills that note lessons: Implement, Implement + Review, Quick Task, Diagnose, X-ray, Review and Test.
**Remember this (every skill that reads lessons).** When the person asks for something to be remembered ("remember this", "so this doesn't happen again" or the like), note it in that turn with `--source said` (the note commands below) and print the returned "Noted for the end of the run: <the lesson>" line. The script refuses a correction or convention without a `--why`: when the person gave no reason for one, ask one short question first ("Why does this matter?") and note it once with their answer as the Why; with no answer, note it with `--why "You asked for this to be remembered."`: the card's row then asks for the reason, and only a Reword with one saves it. Noting the same words again with a different `--why` replaces the waiting item. A said lesson in a skill with no End waits, and shows in the dashboard banner's Review.
Inferred lessons and fixes to `AGENTS.md` (below) are for the seven skills that note lessons only: Implement, Implement + Review, Quick Task, Diagnose, X-ray, Review and Test. The script refuses `--source inferred` from the other eight, which note only what the person said and the doubts Start step 5 and the memory bullet above ask for.
**What to offer.** Offer only what a teammate's run should follow: a fact about the code, never secrets, customer or personal details, or remarks about people. Facts about this codebase that a teammate would need are offered as lessons; a person's own preferences stay in whatever memory their agent keeps. Never offer what is already in `AGENTS.md` or in a lesson just read.
@@ -44,7 +47,8 @@ The rest of this section is for the seven skills that note lessons: Implement, I
**The note commands** (`--skill` is this skill's name, such as `implement`):
- A lesson: `node "<S>/lessons.mjs" note --type lesson --text "<one sentence>" --kind <kind> --about <one to three files, or one folder> --source said|inferred [--seen <files>] [--why "<one sentence>"] --skill <name>`
- A lesson: `node "<S>/lessons.mjs" note --type lesson --text "<one sentence>" --kind <kind> --about <one to three files, or one folder> --source said|inferred [--seen <files>] [--why "<one sentence>"] [--shows-in <glob> --match should|never --text-match "<literal>"] --skill <name>`
Give it a search (all three flags or none) when the lesson names text that should always, or never, appear in some files, such as "never `localStorage` in `src/web-console/public/**/*.js`": the check and later reads test it against the code, and a search that stops agreeing raises a doubt. The literal is one line, at most 120 characters.
- A doubt about a saved lesson: `note --type doubt --target <lesson id> --found "<one sentence>" --skill <name>`
- A fix to `AGENTS.md`: whatever corrects something `AGENTS.md` states is a fix, not a lesson: `note --type agents-fix --before "<exact text>" --after "<new text>" [--file .agents-docs/<name>.md] --skill <name>`. A test map row is `note --type agents-fix --test-map-row '<{"area","paths":[..],"run","shared"}>' --skill <name>`. Note a lesson only when `AGENTS.md` has no place for it.
- A new area: when a lesson fits no existing area and is not general, run `areas --suggest` and note the fitting suggestion, or, when the test map offers none, a name and paths of your own: `note --type area --name "<Area name>" --paths <glob,glob> --skill <name>`. It shows in the same list as Create, Rename or Drop.
@@ -53,13 +57,19 @@ Print the returned `line`, such as "Noted for the end of the run: <the lesson>".
## End
The seven noting skills only (and any skill sent here by Start's Review now), before the commit instructions and before the console's finish.
The seven noting skills (and any skill sent here by Start's Review now) run it before the commit instructions and before the console's finish. The eight read-only skills have no End: their said lessons wait for the next noting run or the dashboard banner's Review.
1. Run `node "<S>/lessons.mjs" list` (`list --first-ask` when the state is `not-set-up`).
**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 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").
1. Run `node "<S>/lessons.mjs" list` (`list --first-ask` when the state is `not-set-up`; `list --check <checkId>` after a check, or `list --check-failed "<one line>"` when it failed).
2. `items` empty and no `firstAsk`: say nothing and skip this step.
3. `firstAsk` present: see The first ask below, instead of 4 to 7.
4. Show `opening` first when present.
5. **On the web console:** post the returned `card` as one `lessons` item with `--wait` (a new `id` when an earlier lessons card is in the session). Its reply has one line per decision ("Keep: ...", "Reword: ...") and a `Decisions:` line holding them as JSON: that JSON is step 6's file, plus what a choice still needs. A `Suggestions wanted on` line for it: reply in its `thread` and, in the same patch, send `suggested` (row id to one of that row's `choices`, such as `{"w1":"Keep"}`), which outlines those buttons without choosing them. **In a terminal:** ask each group in `rounds` with your question tool, one question per item with exactly its `choices` and nothing pre-selected (`heading`, `text`, `why`, `origin` and `note` are what the person reads; an area shows its `name` and `paths`); with no question tool, a numbered list. A choice that needs more (step 6) asks the person for it.
5. **On the web console:** post the returned `card` as one `lessons` item with `--wait` (a new `id` when an earlier lessons card is in the session). Its reply has one line per decision ("Keep: ...", "Reword: ...") and a `Decisions:` line holding them as JSON: that JSON is step 6's file, plus what a choice still needs. A `Suggestions wanted on` line for it: reply in its `thread` and, in the same patch, send `suggested` (row id to one of that row's `choices`, such as `{"w1":"Keep"}`), which outlines those buttons without choosing them. A Reword you suggest goes with the words you would use, `{"w2":{"choice":"Reword","text":"<the lesson>","why":"<its reason>"}}` (either may be left out): the page puts them in that row's boxes when its Reword is open, so give the same words in the thread. **In a terminal:** ask each group in `rounds` with your question tool, one question per item with exactly its `choices` and nothing pre-selected (`heading`, `text`, `why`, `origin` and `note` are what the person reads; an area shows its `name` and `paths`); with no question tool, a numbered list. Show the card's `checked` line first ("Checked 6 lessons in 40 seconds by a fresh helper that could only read", "... by the same agent that noted them", or "The check could not run: <reason>"). Read each item's `check` and `tag` into its text in this order: every Fail, then every Doubt (each as "Fail <test>: <reason>"), then the pass line ("Passed the other N", "Passed the check" with none, and no pass line when all four found something), then its `tag` when present. A `suggestion` is offered as a Reword carrying exactly those words, which the person may adjust. A choice that needs more (step 6) asks the person for it.
6. Write the decisions, one `{ "id", "choice" }` per answered item plus what its choice needs, to a JSON file in the console session folder, or the OS temp folder in a terminal, never in the project. Run `decide --file <path>` and print its `closing` line, such as "Kept 2 (1 reworded), retired 1. 1 still waiting." What a choice needs:
- Reword of a lesson, a doubt or a lesson whose files are gone: the new `text`, plus `why`, `kind`, `about` or `area` when they change.
- Rename of an area: the new `name`, plus `paths` when they change.
@@ -74,7 +84,7 @@ Never stage or commit: what End writes is part of the run's change.
## Unattended runs
A run with nobody there (an Implementation Loop phase started with `--loop`, or a helper) follows Start without asking the heads-up, follows While working and notes lessons, but never runs End, never approves and never shows the first ask. A helper reports a lesson to the main agent in its result, and the main agent notes it as its own. When `note` exits 5 in an unattended run, the lesson is not written, and the run's report says "1 lesson was not noted: it held secret-shaped text" without the text.
A run with nobody there (an Implementation Loop phase started with `--loop`, or a helper) follows Start without asking the heads-up, follows While working, notes lessons, records each "Following a lesson" moment with `follow` (as above; a helper reports its follows to the main agent, which records them), but never runs End, never approves and never shows the first ask. A helper reports a lesson to the main agent in its result, and the main agent notes it as its own. When `note` exits 5 in an unattended run, the lesson is not written, and the run's report says "1 lesson was not noted: it held secret-shaped text" without the text. A loop phase never runs the check: its lessons are graded at the next lessons card.
## With Learning off
File diff suppressed because it is too large. Load diff
+5 -2
View File
@@ -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 };
+47 -7
View File
@@ -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.
+1 -1
View File
@@ -26,7 +26,7 @@ The ✕ on a chip (after the page's two-step confirm) sends `session:[{"i":"__de
## A Learning action
The Learning row and banner send `session:[{"i":"__learning","do":"switch-on"}]` (`do` is `review`, `switch-on`, `switch-off`, `move-log` or `remove`; Remove was confirmed on the page). No hop: you stay the dashboard. Run `lessons.mjs` as the dashboard skill's "A Learning action arrives" says (a `review` while Learning is not set up is `list --first-ask` and the first ask, before anything is kept; the lessons card is the only question this page shows), then `open --resume <sid> --no-open --workflow dashboard` and post the menu again with `--wait`. Pause for me never reaches you: the page saves it itself. A `__launch` with `fromBanner: true` came from a dashboard showing lessons waiting.
The Learning row and banner send `session:[{"i":"__learning","do":"switch-on"}]` (`do` is `review`, `switch-on`, `switch-off`, `move-log`, `remove` or `tidy`; Remove was confirmed on the page). No hop: you stay the dashboard. Run `lessons.mjs` as the dashboard skill's "A Learning action arrives" says (a `review` while Learning is not set up is `list --first-ask` and the first ask, before anything is kept; the lessons card is the only question this page shows), then `open --resume <sid> --no-open --workflow dashboard` and post the menu again with `--wait`. Pause for me never reaches you: the page saves it itself. A `__launch` with `fromBanner: true` came from a dashboard showing lessons waiting.
## A strength suggestion
+2 -2
View File
@@ -54,7 +54,7 @@ One-line JSON, only what changed; the patch merges (`items`, `topics`, `docs` an
Every item: `id` (new for each question, whole session), `kind`, `title` (2 to 4 plain words), `body` (markdown: the question and why it matters), optional `topic`, `doc`, `required:false` (adds Skip), `token` (`{"A":"approved"}`: the typed word an answer stands for).
- `choice`: `{"id":"q1","kind":"choice","title":"Export format","body":"Which format?","options":[{"text":"CSV","detail":"Opens in Excel","recommended":true},{"text":"JSON","detail":"For scripts"}]}`. Back: `{k}` or `{text}`; `allowOther:false` drops the free-text row.
- `text`: `{"id":"q2","kind":"text","title":"Who uses it","body":"Who, and for what?","placeholder":"For example: reviewers, in Excel every Monday."}`. Back: `{text}`. `pattern` plus `patternHint` checks shape (kebab-case). The placeholder is an offer, so write a whole answer. On the fresh-idea card in Pathfinder, Plan and Quick Task add `"templates":"idea"` (also when the idea came as the argument, with a one-line summary in `placeholder`; a resumed map, PLAN-DRAFT or checkpoint gets no idea card; never mention templates in the terminal); a Notebook tab fills a box marked `"fill":"note"`.
- `text`: `{"id":"q2","kind":"text","title":"Who uses it","body":"Who, and for what?","placeholder":"For example: reviewers, in Excel every Monday."}`. Back: `{text}`. `pattern` plus `patternHint` checks shape (kebab-case). The placeholder is an offer: write a whole answer. On the fresh-idea card in Pathfinder, Plan and Quick Task add `"templates":"idea"` (also when the idea came as the argument, with a one-line summary in `placeholder`; a resumed map, PLAN-DRAFT or checkpoint gets no idea card; never mention templates in the terminal); a Notebook tab fills a box marked `"fill":"note"`.
- `confirm`: `{"id":"q3","kind":"confirm","title":"Keep going","body":"Continue?","yesLabel":"Yes","noLabel":"Not yet"}`. Back: `{yes,text?}`.
- `recap`: `{"id":"q4","kind":"recap","title":"What we heard","body":"Is this right?","summary":"- ..."}`. Back: `{ok,text?}`.
- `menu`: `{"id":"q5","kind":"menu","title":"Next step","body":"What now?","options":[{"text":"Plan it"}],"command":"/plan2code-1-plan"}`. Back: `{k}`.
@@ -65,7 +65,7 @@ Every item: `id` (new for each question, whole session), `kind`, `title` (2 to 4
| `review` | read, then approve | `doc` (required), `summary`, `verdicts:[{id,label,danger?}]`, `nothingYet` (false once the change is on disk) | `{verdict,text?}` |
| `checklist` | steps only they can do | `steps`, `valuesLabel` | `{done?,state?,text?}` |
| `list` | reorder or edit a breakdown | `rows:[{id,title,body}]` | `{rows}` or `{text}` |
| `lessons` | approve noted lessons | `rows`, `opening`, `firstAsk` (from `lessons.mjs list`), `suggested` (row id to a choice: outlined, not picked) | `{decisions}` or `{firstAsk}` |
| `lessons` | approve lessons | `rows`, `opening`, `firstAsk` (`lessons.mjs list`), `suggested` | `{decisions}` or `{firstAsk}` |
| `notice` | read, no answer | none | none |
Items show in the order sent, so send them in answering order.
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more